Unicode raw string containing \u

2007-10-28 Thread OKB (not okblacke)
I'm trying to write a unicode raw string literal, and I seem to be 
running up against a conflict between the \u unicode character 
escape and the need to have a literal \u (i.e., backslash followed by a 
lowercase letter U) in the string.

If I do ur"\universe" I get a UnicodeDecodeError because (I think) 
it tries to interpret \universe as a Unicode escape.  But if I do 
ur"\\universe" I get a string that contains two backslashes followed by 
the word "universe".

How can I specify a unicode raw string literal that contains a 
single backslash followed by the word "universe"?

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode raw string containing \u

2007-10-28 Thread Steven D'Aprano
On Sun, 28 Oct 2007 06:58:48 +, OKB (not okblacke) wrote:

> I'm trying to write a unicode raw string literal, and I seem to be
> running up against a conflict between the \u unicode character
> escape and the need to have a literal \u (i.e., backslash followed by a
> lowercase letter U) in the string.
> 
>   If I do ur"\universe" I get a UnicodeDecodeError because (I think)
> it tries to interpret \universe as a Unicode escape.  But if I do
> ur"\\universe" I get a string that contains two backslashes followed by
> the word "universe".

That's because in a raw string, \\ means two backslashes.

>   How can I specify a unicode raw string literal that contains a
> single backslash followed by the word "universe"?

The usual way.

>>> word = u'\\universe'
>>> len(word)
9
>>> word[0]
u'\\'
>>> word[1]
u'u'
>>> print word
\universe
>>> word
u'\\universe'


-- 
Steven.

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


insert string problems..

2007-10-28 Thread Abandoned
Hi..
I want to insert some data to postgresql..
My insert code:
yer="019"
cursor.execute("INSERT INTO ids_%s (id) VALUES (%s)", (yer, id))
I don't want to use % when the insert operation.

in this code give me this error:
psycopg2.ProgrammingError: syntax error at or near "'019'"
LINE 1: SELECT link_id from linkkeywords_'019'

if i do int(yer) , 019 change to 19 ..
How can i do int yer string with 0 ?

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


Re: Unicode raw string containing \u

2007-10-28 Thread OKB (not okblacke)
Steven D'Aprano wrote:

>>  How can I specify a unicode raw string literal that
>>  contains a 
>> single backslash followed by the word "universe"? 
> 
> The usual way.
> 
 word = u'\\universe' len(word) 9 word[0] u'\\' word[1] u'u'
 print word \universe word u'\\universe' 

That doesn't answer my question, since I asked for a unicode RAW 
string literal.  Is this not possible?  (I was able to get what I want 
using ur"\u005Cuniverse", although this is not totally ideal.)

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: insert string problems..

2007-10-28 Thread Abandoned
Also..
a="123,245,1235,663"
cursor.execute("SELECT id, name FROM data WHERE id in (%s)", (a,))
In this query must be:
SELECT id, name FROM data WHERE id in (123,245,1235,663)
but it looks:
SELECT id, name FROM data WHERE id in ("123,245,1235,663")
How can i delete " ?

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


Re: Going past the float size limits?

2007-10-28 Thread Hendrik van Rooyen
"Steven D'Aprano"  wrote:

> Calculating numbers like 10**52 or its reciprocal is also a very good 
> exercise in programming. Anyone can write a program to multiply two 
> floating point numbers together and get a moderately accurate answer:
> 
> product = X*Y # yawn
> 
> But multiplying 200,000 floating point numbers together and getting an 
> accurate answer somewhere near 10**-52 requires the programmer to 
> actually think about what they're doing. You can't just say:
> 
> A,T,C,G = (0.35, 0.30, 0.25, 0.10)
> product = map(operator.mul, [A*T*C*G]*20)
> 
> and expect to get anywhere.
> 
> Despite my fear that this is a stupid attempt by the Original Poster's 
> professor to quantify the old saw about evolution being impossible 
> ("...blah blah blah hurricane in a junk yard blah blah Concorde blah blah 
> blah..."), I really like this homework question.

yes it got me going too - and I even learned about the gmpy stuff - so it was
a bit of a Good Thing...

- Hendrik

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


Re: insert string problems..

2007-10-28 Thread Steven D'Aprano
On Sun, 28 Oct 2007 00:24:34 -0700, Abandoned wrote:

> Hi..
> I want to insert some data to postgresql.. My insert code:
> yer="019"
> cursor.execute("INSERT INTO ids_%s (id) VALUES (%s)", (yer, id)) I don't
> want to use % when the insert operation.
> 
> in this code give me this error:
> psycopg2.ProgrammingError: syntax error at or near "'019'" LINE 1:
> SELECT link_id from linkkeywords_'019'
> 
> if i do int(yer) , 019 change to 19 .. How can i do int yer string with
> 0 ?

Integers with a leading 0 are interpreted as base 8 (octal). You can't 
write 019, because there is no digit "9" in octal.

Why do you need a leading zero?


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


Re: Proposal: Decimal literals in Python.

2007-10-28 Thread Hendrik van Rooyen
"Paul Hankin" wrote:


> Even clearer is not to allow octal literals :) Is there *any* use for
> them?

I tend to agree with this point of view - but I fear it will set up a howl
of protest amongst the Brits who cut their teeth on 24 bit ICT/ICL 
equipment...

- Hendrik


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


Re: insert string problems..

2007-10-28 Thread Abandoned
On Oct 28, 9:45 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sun, 28 Oct 2007 00:24:34 -0700, Abandoned wrote:
> > Hi..
> > I want to insert some data to postgresql.. My insert code:
> > yer="019"
> > cursor.execute("INSERT INTO ids_%s (id) VALUES (%s)", (yer, id)) I don't
> > want to use % when the insert operation.
>
> > in this code give me this error:
> > psycopg2.ProgrammingError: syntax error at or near "'019'" LINE 1:
> > SELECT link_id from linkkeywords_'019'
>
> > if i do int(yer) , 019 change to 19 .. How can i do int yer string with
> > 0 ?
>
> Integers with a leading 0 are interpreted as base 8 (octal). You can't
> write 019, because there is no digit "9" in octal.
>
> Why do you need a leading zero?
>
> --
> Steven.
Thank you steven.
I must use 019 beacause my system algoritm in this way..
And what about second question ?

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


Re: insert string problems..

2007-10-28 Thread Marc 'BlackJack' Rintsch
On Sun, 28 Oct 2007 00:24:34 -0700, Abandoned wrote:

> Hi..
> I want to insert some data to postgresql..
> My insert code:
> yer="019"
> cursor.execute("INSERT INTO ids_%s (id) VALUES (%s)", (yer, id))
> I don't want to use % when the insert operation.
> 
> in this code give me this error:
> psycopg2.ProgrammingError: syntax error at or near "'019'"
> LINE 1: SELECT link_id from linkkeywords_'019'

You are executing an INSERT and get an error about a SELECT!?  Hard to
believe!

But in both SQL statements you try to insert table names via placeholders.
This doesn't work as those placeholders are *values* that will be escaped.
The errormessage is quite clear IMHO::

  SELECT link_id from linkkeywords_'019'

That's not a valid table name because of the ' that got added when
inserting the *value* '019'.

Starting to number tables and the need to dynamically create table names is
usually sign of a bad schema design BTW.

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


Re: Unicode raw string containing \u

2007-10-28 Thread Martin v. Löwis
>   That doesn't answer my question, since I asked for a unicode RAW 
> string literal.  Is this not possible?  (I was able to get what I want 
> using ur"\u005Cuniverse", although this is not totally ideal.)

It's a design flaw in Unicode raw string literals that they still
interpret \u escapes. And yes, your notation is one way to get what
you want; another is u"\\"+r"universe", although I'm unsure whether
that meets your requirements.

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


Need some help...

2007-10-28 Thread hyozan . ux3
I want to create a program that I type in a word.

for example...

chaos

each letter equals a number

A=1
B=20

 and so on.

So Chaos would be

C=13 H=4 A=1 O=7 S=5

I want to then have those numbers
13+4+1+7+5 added together to be 30.

How can I do that?

Also, just curious, but, how could I then have the 3 and 0 added
together to be 3?

Please help me out.

Thank you.

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


Re: elementtree w/utf8

2007-10-28 Thread Stefan Behnel
Tim Arnold wrote:
> On a related note, I have another question--where/how can I get the 
> cElementTree.py module? Sorry for something so basic, but I tried installing 
> cElementTree, but while I could compile with setup.py build, I didn't end up 
> with a cElementTree.py file anywhere.

That's because it compiles into a binary extension module, not a plain Python
module (mind the 'c' in its name, which stands for the C language here).

I don't know what the standard library extension is under HP-UX, but look a
little closer at the files that weren't there before, you'll find it.
Depending on what you did to build it, it might also end up in the "build"
directory or as an installable package in the "dist" directory.


> The directory structure on my system 
> (HPux, but no root access) doesn't work well with setup.py install.

That shouldn't be a problem as long as you keep the binary in your PYTHONPATH.

As suggested before, if you have Python 2.5, you don't even need to install it
yourself.

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


How to compile a 32 bit version python on a 64 bit linux platform

2007-10-28 Thread alexdboy
Hi,

  I'm trying to build a 32 bit version Python from the source of Python 2.4.2 
(later version is O.K. too) on a 64 bit platform "SUSE Linux Entrprise Server 
10(x86_64) - Kernel 2.6.16.21-0.8-smp(5)".

  I followed the common routine "1)./configure --enable-shared --with-threads 
2)make clean; make". I succeeded in building Python. 

  The problem is that the resulting .h file and libraries are incompatible with 
my main program which was compiled using the gcc flag "-m32".

  I've tried modifying the pyconfig.h (changing the size of void * from 8 to 4) 
and Makefile (adding -m32 to the CFLAGS) generated by running configure script, 
and then makeing. But this didn't work. Are there any flags I can use when 
running the ./configure to achieve the target. Any advice will be appreciated. 
Thank you.










___


吸铁石邮箱 高速、稳定、大容量空间,强垃圾邮件过滤系统,杀毒专家支持


http://www.citiz.net-- 
http://mail.python.org/mailman/listinfo/python-list

Re: simple question on dictionary usage

2007-10-28 Thread bearophileHUGS
Marc 'BlackJack' Rintsch>``s.startswith('E')`` is a little safer than
``s[0] == 'E'`` as the former returns `False` if `s` is empty while
the latter raises an `IndexError`.<

Thank you.
In this problem if there is an empty key in the record dict then maybe
it's better to raise an IndexError, because probably that's not a
normal condition. Sometimes less safe is more safe :-)

With few tests I have seen that (using Psyco) this is probably the
faster solution (and it's quite readable by a newbe too):

record2 = {}
for k in record:
  if k[0] == 'E':
record2[k] = record[k]

Misteriously with Psyco it becomes faster than even the equivalent D
language solution (keys starting with "E" are about 5% of the total)
that is statically typed and generally very fast:

string[string] record2;
foreach(k, v; record)
  if (k[0] == 'E')
record2[k] = v;

Bye,
bearophile

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


Re: Need some help...

2007-10-28 Thread bearophileHUGS
> I want to create a program that I type in a word.

You can see that Python has a command to input strings from the
command line.

> chaos
> each letter equals a number
> A=1
> B=20
>  and so on.
> So Chaos would be
> C=13 H=4 A=1 O=7 S=5
> I want to then have those numbers
> 13+4+1+7+5 added together to be 30.
> How can I do that?

Python has a dictionary data structure called dict(), or {}, that you
can use to map your letters to those numbers. With it you can created
the letter-number association.

Then you can scan the characters of the input string one after the
other, and sum their values into a single total value. Try writing
that code, and then show it to us, we can give more suggestions if you
need them...

Bye,
bearophile

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


Re: Need some help...

2007-10-28 Thread martyw
[EMAIL PROTECTED] wrote:
>> I want to create a program that I type in a word.
> 
> You can see that Python has a command to input strings from the
> command line.
> 
>> chaos
>> each letter equals a number
>> A=1
>> B=20
>>  and so on.
>> So Chaos would be
>> C=13 H=4 A=1 O=7 S=5
>> I want to then have those numbers
>> 13+4+1+7+5 added together to be 30.
>> How can I do that?
> 
> Python has a dictionary data structure called dict(), or {}, that you
> can use to map your letters to those numbers. With it you can created
> the letter-number association.
> 
> Then you can scan the characters of the input string one after the
> other, and sum their values into a single total value. Try writing
> that code, and then show it to us, we can give more suggestions if you
> need them...
> 
> Bye,
> bearophile
> 
as an alternative for the suggest dictionary approach you could study 
the built in functions ord() and chr(), see the documentation 
(http://docs.python.org/lib/built-in-funcs.html)
-- 
http://mail.python.org/mailman/listinfo/python-list


Using matplotlib/wxpython on XP embedded

2007-10-28 Thread Jürgen Kareta
Hello List,

my customer is looking for an application to show some simple 2d graphs 
based on messured data.

I'm consider to use wxpython, matplotlib and py2exe to build and compile 
this application. Mayby I also like to use WxMPL and inosetup. The 
target platform is XP embedded. As I don't have XP embedded available, I 
can't try it out.

So my question is, if somebody has experiances with the above mentioned 
libraries on XP embedded ? Should it work out of the box similar to a
usual windows environment or do I have to do some special builds for XPe 
or is it even impossible to use those libraries on it?

Thanks for your help.

Jürgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: iterating over the other and finding the greatest

2007-10-28 Thread Tim Chase
> have carry out a process a>b then i should print the line and if b>c then i
> should print the line and c>d then i should print... like this i have to
> continue.say for eg: 43<387 so the first row is omitted, 387 is greater then
> 98 so i can print the line second row...
> my code:
>  fh = open('364010_spacing','r')
> for lines in fh.readlines():
> data = lines.strip().split('\t')
> start =data[0].strip()
> end = data[1].strip()
> values = data[2].strip()
> id = data[3].strip()
> if a > b :#hanged up here
> print lines

though you don't really define a/b/c anywhere, other than
obliquely referencing values in your 3rd column, I presume they
map to the lines in the file a=1st-line, b=2nd-line, etc.

You also don't disclose when you want the printing to happen,
whether you want to print the highest at each line as you iterate
over them (in your example, printing a,b,b,b,e,e,e,e or if you
want to find the maximum and then print it at the end (just
printing line e once).

I don't know if you want to do if more than one row has the
maximum value.  Do you want to print all of the matching lines?
or just the first or last one encountered?

The code below iterates over the file, finding the maximum of the
3rd column, and then printing the first line that matched that.

  for i,line enumerate(open(filename, 'r')):
c  = int(line.rstrip('\n').split('\t')[2])
if i == 0:
  highest_id = c
  best_match = line
else:
  if c > highest_id:
highest_id = c
best_match = line
  print line

In your code, you parsed start/end, but didn't use them for
anything...vestigial code?

-tkc






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


Which index can i use ?

2007-10-28 Thread Abandoned
Hi..
I want to do index in postgresql & python.
My table:
id(int) | id2(int) | w(int) | d(int)

My query:
select id, w where id=x and id2=y (sometimes and d=z)

I have too many insert and select operation on this table.
And which index type can i use ? Btree, Rtree, Gist or Hash ?
Also I want to unique (id, id2)..
Now this is my index. is it give me good performance ?
CREATE UNIQUE INDEX ind1 ON test USING btree (id, id2)
CREATE INDEX ind2 ON test USING btree (id)
CREATE INDEX ind3 ON test USING btree (id2)
CREATE INDEX ind4 ON test USING btree (w)
CREATE INDEX ind5 ON test USING btree (d)

I'm too sorry my bad english.
King regards..

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


Re: fclient project seeking co-coders

2007-10-28 Thread kirby urner
Another Urner, that's interesting.  Not many of us.

Kirby Urner
Portland, Oregon
USA


On 10/28/07, Jürgen Urner <[EMAIL PROTECTED]> wrote:
>
> Hello all,
>
> I Just recently registered a project fclient to sourceforge.net
> [http://sourceforge.net/projects/fclient]. fclient is intended to
> become desktop client for the freenet [freenetproject.org]
> network written in python and Qt4.
>
> fclient is very alpha, in fact only parts of the freenet client
> protocol
> are curently implementated and loads of work ahead. But I would
> appreciate very much finding interested co-coders to take part in the
> project.
>
> Me, I am no professional coder, but an enthusiast with one or the
> other year
> of python (and Qt) experience. If interested in the project (and
> freenet), feel free
> to drop a mail to the users mailing list at the project page.
>
>
> Have fun, Juergen
>
> --
> http://mail.python.org/mailman/listinfo/python-announce-list
>
> Support the Python Software Foundation:
> http://www.python.org/psf/donations.html
>
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Which index can i use ?

2007-10-28 Thread Marc 'BlackJack' Rintsch
On Sun, 28 Oct 2007 06:00:19 -0700, Abandoned wrote:

> Hi..
> I want to do index in postgresql & python.
> My table:
> id(int) | id2(int) | w(int) | d(int)
> 
> My query:
> select id, w where id=x and id2=y (sometimes and d=z)
> 
> I have too many insert and select operation on this table.
> And which index type can i use ? Btree, Rtree, Gist or Hash ?
> Also I want to unique (id, id2)..
> Now this is my index. is it give me good performance ?
> CREATE UNIQUE INDEX ind1 ON test USING btree (id, id2)
> CREATE INDEX ind2 ON test USING btree (id)
> CREATE INDEX ind3 ON test USING btree (id2)
> CREATE INDEX ind4 ON test USING btree (w)
> CREATE INDEX ind5 ON test USING btree (d)

This isn't a Python question.  You'll get more and probably better
feedback in a group, mailing list or forum dealing with PostgreSQL.

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


Re: Need some help...

2007-10-28 Thread Peter Decker
On 10/28/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> I want to then have those numbers
> 13+4+1+7+5 added together to be 30.
>
> How can I do that?
>
> Also, just curious, but, how could I then have the 3 and 0 added
> together to be 3?
>
> Please help me out.

Will you put our names on your homework when you hand it in?

-- 

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


caluclating median distance

2007-10-28 Thread Beema shafreen
hi everybody,
I have a file
1175123443A_16_P03652190
12771336387A_16_P41582022
1723178298A_16_P03652191
18801932270A_16_P41582024
1000120210001261539A_16_P41582025
100018001000185916A_16_P41582026
100018751000192343A_16_P21378376
1000196610002011361A_16_P03652193
100023721000242249A_16_P21378377
1000247110002527118A_16_P03652194
1000264510002704187A_16_P41582029
1000289110002941130A_16_P21378379
1000307110003121415A_16_P03652195
1000353610003595-38A_16_P03652196

how to calculate the median spacing of an data in the file basically
focusing on the third column of an file. say for example the median spacing
is to be 635. how do we programtically calculate the median spacing and sort
the file according to the third column's median spacing.
hope median we calculate  using (N+1)/2

can somebody help me in this point of view

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

Return value from os.system() call

2007-10-28 Thread Calder Coalson
I was searching for ways to get the return value from os.system()  
calls, when I came across this from 6 years ago.  I tried what was  
suggested in this thread, but
output = os.popen("/tmp/other").read()
returns
sh: line 1: /tmp/other: Permission denied

I'm relatively new to Python, hardly ever use the shell and am  
currently running Python 2.5.5 on Mac OS 10.4.10

Cameron Laird  wrote:
 > In article <98795o$kq8$0 at 216.39.151.169>, Donn Cave   wrote:
 >>Quoth Damian Menscher :
 >>| I'm new to Python (as in, my experience is essentially the  
tutorial),
 >>| but I've already come up with an interesting question:
 >>|
 >>| How do I get the return code from an os.system call?  I would have
 >>| expected I could do something like
 >>|
 >>| ---returncode---
 >>| #/bin/csh
 >>| echo do stuff
 >>| exit 3
 >>|
 >>| and then in my python program I could do
 >>|
 >>| print os.system('./returncode')
 >>|
 >>| But it prints out 768.  Not particularly useful, even after I  
recognize
 >>| the trick of dividing by 256 (byte-swapping going on?  No,  
because a
 >>| return code of 768 reports as 0).  Given that my real return codes
 >>| will be (possibly large) integers, this limitation will likely  
cause
 >>| some serious problems down the line.
 >>|
 >>| Even better would be a way of returning a string (the script I run
 >>| can be something other than csh, but it has to be a separate  
script).
 >>|
 >>| Ideas?  I'm trying to avoid writing the string out to a file and  
then
 >>| read the file back in to the python program

 > Guys, guys; you are making it too hard on Mr. Menscher.  My guess
 > is that he'd appreciate being told that, if he creates /tmp/other
 > with contents
 >   #!/bin/sh
 >   echo "This is a string from an external process."
 > he can then have fun with
 >   import os
 >   print os.popen("/tmp/other").read()

Thank you much -- this solves my problem.  I'm sure I'll have more
questions in the near future, though

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


Re: Return value from os.system() call

2007-10-28 Thread Wildemar Wildenburger
Calder Coalson wrote:
> I was searching for ways to get the return value from os.system() calls, 
> when I came across this from 6 years ago.  I tried what was suggested in 
> this thread, but
> output = os.popen("/tmp/other").read()
> returns
> sh: line 1: /tmp/other: Permission denied
> 

I would assume that this is an OS problem more than a python problem. Do 
you have write access to /tmp/other?
I'm fairly sure its a permission thing.

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


how to convert tuple to a "list of single values" ?

2007-10-28 Thread stef mientki
hello,

The next piece of code bothers me:

  ptx, pty, rectWidth, rectHeight = self._point2ClientCoord (p1, p2 )
  dc.SetClippingRegion ( ptx, pty, rectWidth, rectHeight )

Because I want to write it in 1 line,
and without the use of intermediate variables (for which I have to 
invent names ;-)
like this:

dc.SetClippingRegion ( self._point2ClientCoord (p1, p2 ) )

Now that doesn't work, because
- dc.SetClippingRegion() requires 4 integer parameters
- _point2ClientCoord()  returns a tupple of 4 integers

I can't think of a solution,
is there any ?

thanks,
Stef Mientki


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


Re: how to convert tuple to a "list of single values" ?

2007-10-28 Thread Duncan Booth
stef mientki <[EMAIL PROTECTED]> wrote:

> hello,
> 
> The next piece of code bothers me:
> 
>   ptx, pty, rectWidth, rectHeight = self._point2ClientCoord (p1, p2 )
>   dc.SetClippingRegion ( ptx, pty, rectWidth, rectHeight )
> 
> Because I want to write it in 1 line,
> and without the use of intermediate variables (for which I have to 
> invent names ;-)
> like this:
> 
> dc.SetClippingRegion ( self._point2ClientCoord (p1, p2 ) )
Try:
   dc.SetClippingRegion ( *self._point2ClientCoord (p1, p2 ) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert tuple to a "list of single values" ?

2007-10-28 Thread Matthieu Brucher
Use :

  something = self._point2ClientCoord (p1, p2 )
  dc.SetClippingRegion (*something)

Matthieu

2007/10/28, stef mientki <[EMAIL PROTECTED]>:
>
> hello,
>
> The next piece of code bothers me:
>
>   ptx, pty, rectWidth, rectHeight = self._point2ClientCoord (p1, p2 )
>   dc.SetClippingRegion ( ptx, pty, rectWidth, rectHeight )
>
> Because I want to write it in 1 line,
> and without the use of intermediate variables (for which I have to
> invent names ;-)
> like this:
>
> dc.SetClippingRegion ( self._point2ClientCoord (p1, p2 ) )
>
> Now that doesn't work, because
> - dc.SetClippingRegion() requires 4 integer parameters
> - _point2ClientCoord()  returns a tupple of 4 integers
>
> I can't think of a solution,
> is there any ?
>
> thanks,
> Stef Mientki
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
French PhD student
Website : http://miles.developpez.com/
Blogs : http://matt.eifelle.com and http://blog.developpez.com/?blog=92
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: os.walk and recursive deletion

2007-10-28 Thread Martin Marcher
27 Oct 2007 17:38:10 GMT, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]>:
> On Sat, 27 Oct 2007 18:07:44 +0200, Martin Marcher wrote:
> > I'm playing around with os.walk and I made up del_tree(path) which I
> > think is correct (in terms of the algorithm, but not as python wants
> > it :)).
>
> It's not correct in terms of the algorithm if you take the algorithm of
> `os.walk()` into the equation.
>
> `os.walk()` is itself diving recursivly into the subdirectories…

True but isn't the problem that I need either backtracking to remember
which directories are empty and thus can be deleted or that I need to
do another recursion (like in my function) which returns as soon as
the "new root" is deleted or at least empty?

I mean having a directory structure with 3 subdiretories, each of them
has files in it

> >   else:
> >  for subdir in subdirs:
> > subdir = os.path.join(cwd, subdir)
> > print "We need to recurse into: %s" % (subdir, )
> > del_tree(subdir)
>
> …and here you are calling the your function recursively which then calls
> again `os.walk()` on that subdirectory.  That's a little bit too much.

I call it recursively here because I

* either need to backtrack to remember which directories are empty (and leafs)
* or I just recurse my function which yields an OSError because a
directory the original os.walk will visit doesn't exist anymore
because some recursion already deleted it.

(correct me if I'm wrong - but I'd like to stick with os.walk for this
as an exercise)

> Or `shutil.rmtree()`.  :-)

Nice function but not part of my exercise :) - No it isn't homework
just doing it to play around.

thanks
martin

PS: as I'm writing this i just discovered that I missed the
topdown=False argument for os.walk. Playing a bit with it the docs
seem to say that is more what I want than topdown=True

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to convert tuple to a "list of single values" ?

2007-10-28 Thread stef mientki
thanks Duncan, Matthieu and Ed (offlist),
this is exactly what I was looking for.

cheers,
Stef

Duncan Booth wrote:
> stef mientki <[EMAIL PROTECTED]> wrote:
>
>   
>> hello,
>>
>> The next piece of code bothers me:
>>
>>   ptx, pty, rectWidth, rectHeight = self._point2ClientCoord (p1, p2 )
>>   dc.SetClippingRegion ( ptx, pty, rectWidth, rectHeight )
>>
>> Because I want to write it in 1 line,
>> and without the use of intermediate variables (for which I have to 
>> invent names ;-)
>> like this:
>>
>> dc.SetClippingRegion ( self._point2ClientCoord (p1, p2 ) )
>> 
> Try:
>dc.SetClippingRegion ( *self._point2ClientCoord (p1, p2 ) )
>   

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


Weird AttributeError With Imports

2007-10-28 Thread Juha S.
I'm getting a "AttributeError: 'module' object has no attribute 'clock'" 
when importing a module from within two packages related to the line: 
"self.lastTime = time.clock()" in the __init__() of the class Time in 
the target module.

The module (mytime.py) sits in a package hierarchy such as the following 
"packageA.packageB.mytime", and imports the Python module "time" like 
this: "import time"

In another module outside of both packages (in a folder that holds the 
other package folders) I do this:


from packageA.packageB import mytime

timer = mytime.Time() #Throws the above AttributeError


Strangely it seems that if I create a Time object in mytime.py 
everything works perfectly. I have no idea why I'm getting this error, 
so any help is welcome!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: modifying __class__

2007-10-28 Thread Gabriel Genellina
En Fri, 26 Oct 2007 04:49:37 -0300, Evan Klitzke <[EMAIL PROTECTED]> escribi�:

> On 10/26/07, Piyush Jain <[EMAIL PROTECTED]> wrote:
>> Hi,
>> Itis possible to change the class of an object by assigning new value to
>> __class__
>> Is it possible to call my module when it is done.
>> For example,
>> object = ClassA()
>>
>> object.__class__ = classB # I want to call my method when this  
>> statement is
>> executed.
>
> Here's an example of how to do this:
>
> class A(object):
> def __init__(self):
> self._class = A
>
> def getclass(self):
> return self._class
>
> def setclass(self, x):
> print 'setting __class__ to %s' % x
> self._class = x
>
> __class__ = property(getclass, setclass)
>
> class B(object):
> pass
>
> if __name__ == '__main__':
> a = A()
> print 'Running a.__class__ = B'
> a.__class__ = B
>
> print 'a.__class__ = %s' % a.__class__

Sorry but this is unnecesarily complicated and almost useless. Ok, using a  
property you change the __class__ attribute, but this has no effect on the  
object behavior. type(a) is still A, and B is not overriding any of A  
methods.

>> I want to do it in a general way. For ex. , whenever __class__ is  
>> changed
>> for any object instance (of different classes), my own function is  
>> called.
>> How should I do it ?
> I think you can do this using a metaclass, and then have all of your
> classes inherit from the metaclass rather than object, but I don't
> really have any experience doing this.

Perhaps, but using a metaclass is still too much complicated for this task.
I assume the OP doesn't have a lot of __class__ assignments all along the  
code, so keeping the syntax x.__class__ = another_class is not a  
requirement.
So, just define a function change_class wich assigns the new class to  
__class__ and additionally does whatever is needed:

py> class A(object):
... def foo(self):
... print "Inside A.foo"
...
py> class B(object):
... def foo(self):
... print "Inside B.foo"
...
py> def change_class(inst, newclass):
... print "Look ma! Changing class from %s to %s" % (
...  inst.__class__, newclass)
... inst.__class__ = newclass
...
py> x = A()
py> x.foo()
Inside A.foo
py> type(x)

py> change_class(x, B)
Look ma! Changing class from  to 
py> x.foo()
Inside B.foo
py> type(x)


change_class might be a method of A instead, but I don't see any gain on  
it.

-- 
Gabriel Genellina

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

Re: Weird AttributeError With Imports

2007-10-28 Thread Peter Otten
Juha S. wrote:

> I'm getting a "AttributeError: 'module' object has no attribute 'clock'" 
> when importing a module from within two packages related to the line: 
> "self.lastTime = time.clock()" in the __init__() of the class Time in 
> the target module.

You probably have a time module that you wrote yourself and which is now
hiding the one in python's standard library. Was your mytime.py formerly
named time.py, and if so, did you remove the corresponding time.pyc?

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


Pari Python

2007-10-28 Thread Anton Mellit
Hi,

I am working on a Pari-Python module (see about GP/PARI at
http://pari.math.u-bordeaux.fr/). Similar project was started by
Stefane Fermigier 12 years ago (you can find a post about it on this
newsgroup). You can see some screenshots on my blog (http://
mellit.wordpress.com/2007/10/28/pari-python/). I reproduce the text on
my blog here.

I finished some working version of the pari-python module. I tried to
make it is close as possible to the standard PARI shell, at the same
time using the standard python syntax. Here I put some screenshots. I
didn’t make a proper package distribution for python (the code still
looks ugly and I still don't know how to make proper distributions),
but if someone is interested to test it send me an email. This is in
early alpha stage. A lot of things are not working. I imported almost
all functions of gp by an automated perl script but I don’t know which
of them actually work and which not.

There are two special difficulties you may notice about python. The
first one is the power operation. In python it is ‘**’, whereas ‘^’ is
reserved for the bitwise xor. I made some little changes to the python
source so that ‘^’ and ‘^=’ now work as power, and ‘^^’ and ‘^^=’ work
as xor if you still want to use it. This is done by modifying about 30
lines of source code in several files: Include/token.h, Modules/
parsermodule.c, Parser/tokenizer.c, Python/ast.c, Grammar/Grammar.

The second difficulty is that expressions like ‘1/2′ produce 0 in
python. For this my module installs my own handler for the operation
‘divide’ for integers and longs. That’s it. In other respects it is a
normal python module.

I will greatly appreciate any feedback.

Anton

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

Re: Weird AttributeError With Imports

2007-10-28 Thread Juha S.
Peter Otten wrote:
> Juha S. wrote:
>
>   
>> I'm getting a "AttributeError: 'module' object has no attribute 'clock'" 
>> when importing a module from within two packages related to the line: 
>> "self.lastTime = time.clock()" in the __init__() of the class Time in 
>> the target module.
>> 
>
> You probably have a time module that you wrote yourself and which is now
> hiding the one in python's standard library. Was your mytime.py formerly
> named time.py, and if so, did you remove the corresponding time.pyc?
>
> Peter
>   

Yes, I did have mytime.py named as time.py previously. Now that I 
deleted the .pyc it seems to work fine. Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Getting callfunc from ast code.

2007-10-28 Thread Glich
"""Hi, how can I extend the code shown below so that I can identify
any "CallFunc" in "func.code" and identify the value of "node" in
"CallFunc"? Thanks.

This is my code so far:
"""

""" Given a python file, this program prints out each function's name
in that file, the line number and the ast code of that function.

"""

import compiler
import compiler.ast

parse_file = compiler.parseFile("/home/glich/file.py")

count = 0

while count < (len(parse_file.node.nodes) - 1):

func = parse_file.node.nodes[count]

print "\nFunc name: " + str(func.name)
print "Func line number: " + str(func.lineno) + "\n"

print str(func.code) + "\n"

count += 1


"""file.py:


def fun1():

print "Hi"
hi = "1"

fun2()
fun4()

def fun2():

fun3()

def fun3():

fun4()

def fun4():
print "Hi"

fun1()

"""

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


Re: while within while

2007-10-28 Thread Tony
 Shawn Minisall wrote:


also, surely it should be paper covers rock?

Tony


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


Re: fclient project seeking co-coders

2007-10-28 Thread David Boddie
On Sun Oct 28 11:49:17 CET 2007, Jürgen Urner wrote:

> I Just recently registered a project fclient to sourceforge.net
> [http://sourceforge.net/projects/fclient]. fclient is intended to
> become desktop client for the freenet [freenetproject.org]
> network written in python and Qt4.

It sounds like an interesting project.

> fclient is very alpha, in fact only parts of the freenet client
> protocol are curently implementated and loads of work ahead. But I
> would appreciate very much finding interested co-coders to take part
> in the project.
>
> Me, I am no professional coder, but an enthusiast with one or the
> other year of python (and Qt) experience. If interested in the project
> (and freenet), feel free to drop a mail to the users mailing list at
> the project page.

If you need advice on parts of the implementation, there are plenty of
Python and Qt experts on the PyQt mailing list:

  http://www.riverbankcomputing.com/mailman/listinfo/pyqt

If you're trying to avoid subscribing to additional mailing lists, don't
worry: quite a few of us read python-list/comp.lang.python as well.

Incidentally, you might find it useful to add your project to the list
of application on the PyQt Wiki:

  http://www.diotavelli.net/PyQtWiki/SomeExistingApplications

David

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


Re: simple question on dictionary usage

2007-10-28 Thread Martin v. Löwis
>> egt = {}
>> for key in record:
>>if key.startswith('E'):
>>egt[key] = record[key]
> 
> I actually had come up with something like this, but thought it wasn't
> quite as pythonish as it should be.  It is certainly much more readable
> to a neophyte to python.

My recommendation: forget about the comprehension-based ones. It *is*
Pythonic to have the code readable to a neophyte; there is no price to
win for shortness or cuteness.

>> egt = dict((k, v) for k, v in record.iteritems() if k.startswith('E'))
> 
> This is what I was looking for.  I thought I had seen something simular
> to this in one of the tutorials I had read, but couldn't seem to find it.

And you consider this readable? I find it way too complex.

> Ah!  Now this is one solution I can get my teeth into.  If its not obvious,
> I'm a recovering perl programmer.

Ok, I now see why you can appreciate the comprehension-based one :-)

Again, much of Python's strength comes from it being readable. Simple
is better than complex, and sparse is better than dense, and readability
counts (import this).

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


Capturing output with input

2007-10-28 Thread gopala
Hi, I am pretty new to python but i do have experience with c++. As a
part of learning exercise i wrote a python script to insert
beautifying comments(with name, problem...) to our lab program source
files (c language).

The script is working for most of the cases. The problem is i also
need to append the test output of the lab programs to the
corresponding source files(again the output should be added as a
beautified comment). The lab programs are interactive and very
different from each other. Currently in the script, i am prompting the
user(me!) to manually enter the output of the program which it to be
inserted. I want to eliminate this tedious step.

for eg i want "python commenter.py lab1.c" to initially prepend
comments with my name... and then spawn lab1.exe , capture its output
and append it with comments to lab1_com.c

My initial attempts of using spawn.. , exec.. pipe.. failed since they
can't capture the std input and std output continuously.
The lab1.exe will be something like

Enter 2 nos
2 3
The sum is 5

Now i should be able to capture all these.
Is this possible ? If so please do give me some hints on how to
achieve this.

Cheers,
Gopala Krishna

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


Re: Is the subprocess module thread-safe?

2007-10-28 Thread Martin v. Löwis
>Can the subprocess module be used to launch subprocesses from threads?

The answer to this question ("can") is a clear yes. Notice that this
question is different from the question in the subject.

> Or does the subprocess module affect the entire process context, like
> "fork"?

On POSIX systems, it uses fork(2) - what else could it do? I'm not sure
what effects to the entire process context you are referring to. In
a POSIX system, you can also fork from a thread just fine.

> Or is this OS dependent?

The precise semantics are OS dependent, yes. However, you can use it
in the presence of threads on most systems that support threads (for
a reasonable definition of "supports threads", which may exclude
HP-UX and FreeBSD :-)

It's technically not thread-safe if other threads manipulate file
descriptors; there is always a chance of race conditions when some
thread opens a file handle and then tries to set the CLOEXEC flag
on it - if some other thread creates a subprocess in-between, there
is a chance that the child process "sees" the file handle even though
it "should" have the CLOEXEC flag set (but didn't at the point when
the process forked).

>Also, if you launch processes from the subprocess module module and
> don't wait them to complete, do zombies accumulate under UNIX/Linux?

No. It depends on the precise code, but if you drop the reference to the
Popen object, or call one of the functions that don't return one in the
first place, the module itself will wait for the child processes
"regularly".

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


Re: Getting callfunc from ast code.

2007-10-28 Thread Paul Boddie
On 28 Okt, 19:09, Glich <[EMAIL PROTECTED]> wrote:
> """Hi, how can I extend the code shown below so that I can identify
> any "CallFunc" in "func.code" and identify the value of "node" in
> "CallFunc"? Thanks.
>
> This is my code so far:
> """

I tend to use isinstance to work out what kind of AST node I'm looking
at, although I often use the visitor infrastructure to avoid doing
even that.

> """ Given a python file, this program prints out each function's name
> in that file, the line number and the ast code of that function.
>
> """
>
> import compiler
> import compiler.ast
>
> parse_file = compiler.parseFile("/home/glich/file.py")
>
> count = 0
>
> while count < (len(parse_file.node.nodes) - 1):
>
> func = parse_file.node.nodes[count]

A quick style tip here: it's easier to iterate over the nodes, and if
you want a counter, use the enumerate built-in function. Together with
the above advice...

for count, func in enumerate(parse_file.node.nodes):
if isinstance(func, compiler.ast.CallFunc):
...

> print "\nFunc name: " + str(func.name)
> print "Func line number: " + str(func.lineno) + "\n"
>
> print str(func.code) + "\n"

Take a look at the help text for enumerate to see how I arrived at the
above:

help(enumerate)

Paul

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


Re: Pari Python

2007-10-28 Thread [EMAIL PROTECTED]
On Oct 28, 12:45 pm, Anton Mellit <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am working on a Pari-Python module (see about GP/PARI 
> athttp://pari.math.u-bordeaux.fr/). Similar project was started by
> Stefane Fermigier 12 years ago (you can find a post about it on this
> newsgroup). You can see some screenshots on my blog (http://
> mellit.wordpress.com/2007/10/28/pari-python/). I reproduce the text on
> my blog here.

Cool.

>
> I finished some working version of the pari-python module. I tried to
> make it is close as possible to the standard PARI shell, at the same
> time using the standard python syntax.

Does your version use the GMP library (optional in PARI).
Does it support Windows? I couldn't tell if the PARI
Windows distribution has GMP, but I suspect not since GMP
doesn't support Windows.

> Here I put some screenshots. I
> didn't make a proper package distribution for python (the code still
> looks ugly and I still don't know how to make proper distributions),
> but if someone is interested to test it send me an email. This is in
> early alpha stage. A lot of things are not working. I imported almost
> all functions of gp by an automated perl script but I don't know which
> of them actually work and which not.
>
> There are two special difficulties you may notice about python. The
> first one is the power operation. In python it is '**', whereas '^' is
> reserved for the bitwise xor. I made some little changes to the python
> source so that '^' and '^=' now work as power, and '^^' and '^^=' work
> as xor if you still want to use it.

Oh, dear.

> This is done by modifying about 30
> lines of source code in several files: Include/token.h, Modules/
> parsermodule.c, Parser/tokenizer.c, Python/ast.c, Grammar/Grammar.

Am I gonna have to re-compile Python?

That's imposible for ordinary Windows users.

Are you going to make a binary Windows distribution?

If not, it may as well be on the far side of the moon for
all the good it would be to me.

>
> The second difficulty is that expressions like '1/2 produce 0 in
> python. For this my module installs my own handler for the operation
> 'divide' for integers and longs. That's it. In other respects it is a
> normal python module.
>
> I will greatly appreciate any feedback.
>
> Anton


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


Re: Going past the float size limits?

2007-10-28 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> You can't just say:
> product = map(operator.mul, [A*T*C*G]*20)
> and expect to get anywhere.

from math import log
A,T,C,G = (0.35, 0.30, 0.25, 0.10)
c,m = divmod(20*log(A*T*C*G,10), 1)
print "%.3fe%d"%(m, int(c))
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Going past the float size limits?

2007-10-28 Thread Paul Rubin
Paul Rubin  writes:
> c,m = divmod(20*log(A*T*C*G,10), 1)
> print "%.3fe%d"%(m, int(c))

Barf.  Left as exercise: fix the error.


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


Re: Pari Python

2007-10-28 Thread Robert Kern
Anton Mellit wrote:
> Hi,
> 
> I am working on a Pari-Python module (see about GP/PARI at
> http://pari.math.u-bordeaux.fr/). Similar project was started by
> Stefane Fermigier 12 years ago (you can find a post about it on this
> newsgroup). You can see some screenshots on my blog (http://
> mellit.wordpress.com/2007/10/28/pari-python/). I reproduce the text on
> my blog here.
> 
> I finished some working version of the pari-python module. I tried to
> make it is close as possible to the standard PARI shell, at the same
> time using the standard python syntax. Here I put some screenshots. I
> didn’t make a proper package distribution for python (the code still
> looks ugly and I still don't know how to make proper distributions),
> but if someone is interested to test it send me an email. This is in
> early alpha stage. A lot of things are not working. I imported almost
> all functions of gp by an automated perl script but I don’t know which
> of them actually work and which not.
> 
> There are two special difficulties you may notice about python. The
> first one is the power operation. In python it is ‘**’, whereas ‘^’ is
> reserved for the bitwise xor. I made some little changes to the python
> source so that ‘^’ and ‘^=’ now work as power, and ‘^^’ and ‘^^=’ work
> as xor if you still want to use it. This is done by modifying about 30
> lines of source code in several files: Include/token.h, Modules/
> parsermodule.c, Parser/tokenizer.c, Python/ast.c, Grammar/Grammar.
> 
> The second difficulty is that expressions like ‘1/2′ produce 0 in
> python. For this my module installs my own handler for the operation
> ‘divide’ for integers and longs. That’s it. In other respects it is a
> normal python module.
> 
> I will greatly appreciate any feedback.

Have you looked at SAGE at all? They already have wrappers for Pari.

  http://www.sagemath.org/

I don't recommend continuing to modify core parts of Python just for your
module. It means that you will break other Python modules. If you can't use
other Python modules with your module, what's the point of using Python at all?

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

Readline on OS X for trunk build

2007-10-28 Thread James Thiele
Just got the trunk out of svn to build 2.6 alpha on OS X 10.4(Tiger).
No readline. I can't remember what I did to get it when I built 2.5
but it works there. Google searches are bringing up what to do for the
Python 2.3 that comes with OS X 10.4. Could someone point me in the
right direction?

Thanks,
James

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


Re: finding out the call (and not only the caller)

2007-10-28 Thread Carl Friedrich Bolz
Hi Neal,

[EMAIL PROTECTED] wrote:
> The code doesn't handle all the cases (e.g., nested functions), but
> gives you an idea of what can be done and where to look for the info
> (ie, in the stack frame and how to parse the byte codes to some
> extent).  For nested functions, look in co_consts.
> 
> Bytecodes are specific to CPython.  This code won't work on
> IronPython, Jython, or PyPy.  This code really shouldn't be used for
> production.  However, it demonstrates some of the info available.

Actually that's not true for PyPy. PyPy uses CPython's bytecode, so the 
example works just fine.

Cheers,

Carl Friedrich Bolz
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem--IOError: [Errno 13] Permission denied

2007-10-28 Thread patrick . waldo
Hi all,

After sludging my way through many obstacles with this interesting
puzzle of a text parsing program, I found myself with one final error:

Traceback (most recent call last):
  File "C:\Python24\Lib\site-packages\pythonwin\pywin\framework
\scriptutils.py", line 310, in RunScript
exec codeObject in __main__.__dict__
  File "C:\Documents and Settings\Patrick Waldo\My Documents\Python
\WORD\try5-2-file-1-all patterns.py", line 77, in ?
input = codecs.open(input_text, 'r','utf8')
  File "C:\Python24\lib\codecs.py", line 666, in open
file = __builtin__.open(filename, mode, buffering)
IOError: [Errno 13] Permission denied: 'C:\\text_samples\\test\
\output'

The error doesn't stop the program from functioning as it should,
except the last line of every document gets split with | in between
the words, which is just strange.  I have no idea why either is
happening, but perhaps they are related.

Any ideas?

#For text files in a directory...
#Analyzes a randomly organized UTF8 document with EINECS, CAS,
Chemical, and Chemical Formula
#into a document structured as EINECS|CAS|Chemical|Chemical Formula.

import os
import codecs
import re

path = "C:\\text_samples\\test\\"
path2 = "C:\\text_samples\\test\\output\\"

EINECS = re.compile(r'^\d\d\d-\d\d\d-\d$')
FORMULA = re.compile(r'([A-Z][a-zA-Z0-9]*\.?[A-Za-z0-9]*/?[A-Za-
z0-9]*)')
FALSE_POS = re.compile(r'^[A-Z][a-z]{4,40}\)?\.?')
FALSE_POS1 = re.compile(r'C\.I\..*')
FALSE_POS2 = re.compile(r'vit.*')
FALSE_NEG = re.compile(r'C\d+\.')

def iter_elements(tokens):
product = []
for tok in tokens:
if EINECS.match(tok) and len(product) >= 3:
match = re.match(FORMULA,product[-1])
match_false_pos = re.match(FALSE_POS,product[-1])
match_false_pos1 = re.match(FALSE_POS1,product[-1])
match_false_pos2 = re.match(FALSE_POS2,product[2])
match_false_neg = re.match(FALSE_NEG,product[-1])
if match_false_neg:
product[2:-1] = [' '.join(product[2:])]
del product[-1]
yield product
product = []
elif match_false_pos:
product[2:-1] = [' '.join(product[2:])]
del product[-1]
yield product
product = []
elif match:
product[2:-1] = [' '.join(product[2:-1])]
yield product
product = []
elif match_false_pos1 or match_false_pos2:
product[2:-1] = [' '.join(product[2:])]
del product[-1]
yield product
product = []
else:
product[2:-1] = [' '.join(product[2:])]
del product[-1]
yield product
product = []
product.append(tok)
yield product

for text in os.listdir(path):
input_text = os.path.join(path,text)
output_text = os.path.join(path2,text)
input = codecs.open(input_text, 'r','utf8')
output = codecs.open(output_text, 'w', 'utf8')
tokens = input.read().split()
for element in iter_elements(tokens):
output.write('|'.join(element))
output.write("\r\n")
input.close()
output.close()

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


Going past the float size limits?

2007-10-28 Thread Fredrik Johansson
jimmy.musselwhite at gmail.com wrote:
> Hello all
> It would be great if I could make a number that can go beyond current
> size limitations. Is there any sort of external library that can have
> infinitely huge numbers? Way way way way beyond say 5x10^350 or
> whatever it is?

> I'm hitting that "inf" boundary rather fast and I can't seem to work
> around it.

> Thanks!

mpmath (http://code.google.com/p/mpmath/) supports nearly unlimited
exponents (as large as fit in your computer's memory); much larger
than gmpy. It is also essentially compatible with regular floats with
respect to rounding, function support, etc, if you need that.

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


Re: Questions for the Python Devs Out There

2007-10-28 Thread Terry Reedy

"Ann Thompson" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| If you know of places that I might be able to post queries for python
| developers, I'm certainly open to suggestions.

Many people involved with Python and gaming subscribe to the pygame mailing 
list, also accessible as gmane.comp.python.pygame 



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


Re: Pari Python

2007-10-28 Thread Anton Mellit
> Does your version use the GMP library (optional in PARI).
> Does it support Windows? I couldn't tell if the PARI
> Windows distribution has GMP, but I suspect not since GMP
> doesn't support Windows.

No, I didn't try to use gmp. But this may be not a bad idea. I am
trying to compile gmp right now. I am also using Windows. Here there
are two ways to work. The first is cygwin. Actually the standard PARI
distribution uses cygwin. Problem is that in this case you must also
use cygwin version of Python. It is very easy in my case - I have a
full Cygwin system installed together with python, bash, gcc etc. It
is not bad actually - bash is much more powerful than cmd. And you can
start windows programs from bash, start cygwin problems from windows,
I mean it is having linux and windows simultaneously.

But if you are using windows python then you must compile everything
for windows because somehow cygwin1.dll (yes, just one dll is enough)
does not work with windows python. So there are no problems with
compiling my module on windows provided you managed to compile PARI
which does not use cygwin. It is possible (you have to use mingw32 +
msys to compile and remove '#define UNIX' from paricfg.h), I tried
this and it seem to work. Personally I don't like it so much because
on windows python does not support colors, everything is black and
white. There is a thing called ipython (google it) which has some
colors. So this may be an option. So there should be no problems to
make the whole thing purely windows. I haven't tried to compile GMP
under mingw. But I think there should be no problems as well. This is
just mathematical library, it shouldn't use too much from the system.

> >
> > There are two special difficulties you may notice about python. The
> > first one is the power operation. In python it is '**', whereas '^' is
> > reserved for the bitwise xor. I made some little changes to the python
> > source so that '^' and '^=' now work as power, and '^^' and '^^=' work
> > as xor if you still want to use it.
>
> Oh, dear.
>
> > This is done by modifying about 30
> > lines of source code in several files: Include/token.h, Modules/
> > parsermodule.c, Parser/tokenizer.c, Python/ast.c, Grammar/Grammar.
>
> Am I gonna have to re-compile Python?

Yes, unfortunately this hack with '^' needs python to be recompiled.
You see, the problem is not just with symbol. The problem is that
normally ^ has precedence less than +. For example even if you
redefine '^' to be the power operation the following expression 2*2^2
will be 16, not 8 as you expect.

>
> That's imposible for ordinary Windows users.
>

Well, this should not be impossible. I haven't tried, but I've heard
that the free version of Microsoft Visual C++ is enough
(http://msdn2.microsoft.com/en-us/express/aa975050.aspx).

> Are you going to make a binary Windows distribution?

Definitely I can make a binary distribution as well. Just need some time :)

>
> If not, it may as well be on the far side of the moon for
> all the good it would be to me.
>

So when I make a binary distribution for Windows I can upload it
somewhere and post a link.
-- 
http://mail.python.org/mailman/listinfo/python-list


coverage.py: "Statement coverage is the weakest measure of code coverage"

2007-10-28 Thread Ben Finney
Howdy all,

Ned Batchelder has been maintaining the nice simple tool 'coverage.py'
http://nedbatchelder.com/code/modules/coverage.html> for
measuring unit test coverage.

On the same site, Ned includes documentation
http://nedbatchelder.com/code/modules/rees-coverage.html> by the
previous author, Gareth Rees, who says in the "Limitations" section:

Statement coverage is the weakest measure of code coverage. It
can't tell you when an if statement is missing an else clause
("branch coverage"); when a condition is only tested in one
direction ("condition coverage"); when a loop is always taken and
never skipped ("loop coverage"); and so on. See [Kaner 2000-10-17]
http://www.kaner.com/pnsqc.html> for a summary of test
coverage measures.

So, measuring "coverage of executed statements" reports complete
coverage incorrectly for an inline branch like 'foo if bar else baz',
or a 'while' statement, or a 'lambda' statement. The coverage is
reported complete if these statements are executed at all, but no
check is done for the 'else' clause, or the "no iterations" case, or
the actual code inside the lambda expression.

What approach could we take to improve 'coverage.py' such that it
*can* instrument and report on all branches within the written code
module, including those hidden inside multi-part statements?

-- 
 \"Technology is neither good nor bad; nor is it neutral." |
  `\   —Melvin Kranzberg's First Law of Technology |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Pari Python

2007-10-28 Thread Anton Mellit
> Have you looked at SAGE at all? They already have wrappers for Pari.

Well :) I expected that question. I tried. But the distribution for
windows is so big :( (2GB) and I could not build it on cygwin, where
it is also pretty big. And I so much like pari - it is so light and
simple and still can do almost everything. So my idea is to make
simple module for python so that you don't need to install 2GB program
with 2000 functions where it is difficult to find the one you need,
but just type 'import pari', and then help(pari), and then find a
function like 'ellinit' and create an elliptic curve, or type some
polynomial and factor, or expand some function into power series, or
integrate numerically...

I heard from some people that SAGE is good but i somehow don't
appreciate the approach.

> I don't recommend continuing to modify core parts of Python just for your
> module. It means that you will break other Python modules. If you can't use
> other Python modules with your module, what's the point of using Python at 
> all?

Of course you don't have to replace ** with ^ or making that hack with
division. The module would work with or without these changes. But I
think every mathematician agrees that x**2 is really ugly. It is so
often I have to type something like
(1+x)*(1+x^2)*(1+x^3), compare with (1+x)*(1+x**2)*(1+x**3)
or some polynomial (compare 1+x+x^2+x^3 and 1+x+x**2+x**3)
The same thing about the division. Having to write R*1/2 (where R
equals to one, but the type of R is the new number type) is also ugly.
If you write a program you don't have to do it too often, but if you
work 'interactively' then you have to type it more often, then read
the result from screen, or copy-paste a formula from somewhere.

And I think (correct me if I am wrong) that the ^ operator (xor) is
used very very infrequently. And it is not difficult to replace all ^
with say ^^. The division is probably used more often, but python has
this trend anyway - to replace division with 'true' division, so
people should use // when they divide integers and expect an integer.

Other than these two things (the second one does not require
recompilation, so it is not so bad probably) I don't need any changes
to python core. I agree that a standard must be standard.

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


Re: Proposal: Decimal literals in Python.

2007-10-28 Thread Tim Roberts
MRAB <[EMAIL PROTECTED]> wrote:

>On Oct 27, 12:12 am, Ben Finney <[EMAIL PROTECTED]>
>wrote:
>> Matimus <[EMAIL PROTECTED]> writes:
>> > The trailing L [for 'long' literals] is going away in Python 3.0.
>>
>> Yes. On the other hand, we are gaining '0b' for binary literals,
>> to go along with '0o' for octal and '0x' for hexadecimal.
>>
>> So, the original poster might get further by proposing an '0dNNN.NNN'
>> syntax for 'decimal.Decimal' literals. At least the syntax would be
>> consistent and wouldn't add a new punctuation character to the
>> language...
>>
>[snip]
>Some languages have or permit 0q or 0Q for octal to reduce the
>chance of confusion of 'O' (oh) with '0' (zero) in uppercase, eg.
>0Q123 is clearer than 0O123 (0 oh 123), although lowercase is better,
>eg. 0q123 or 0o123.

My favorite notation for this comes from Ada, which allows arbitrary bases
from 2 to 16, and allows for underscores within numeric literals:

  x23_bin : constant :=  2#0001_0111#;
  x23_oct : constant :=  8#27#;
  x23_dec : constant := 10#23#;
  x23_hex : constant := 16#17#;

The opportunities for obfuscated coding by writing all constants in base 7
boggle the mind.

I'm not convinced you need delimiters on both ends; I think 16'fffe_3777
would be just as good.

Although, now that I think about the original thread, this doesn't have a
neat solution for the decimal problem...
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal: Decimal literals in Python.

2007-10-28 Thread Tim Roberts
"Hendrik van Rooyen" <[EMAIL PROTECTED]> wrote:

>"Paul Hankin" wrote:
>
>> Even clearer is not to allow octal literals :) Is there *any* use for
>> them?
>
>I tend to agree with this point of view - but I fear it will set up a howl
>of protest amongst the Brits who cut their teeth on 24 bit ICT/ICL 
>equipment...

As a long-time Control Data employee, I know that 60-bit words and 18-bit
addresses meant that I could do octal arithmetic nearly as fast as decimal.
On the other hand, Python doesn't run on the 6000s...
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pari Python

2007-10-28 Thread Michael L Torrie
Anton Mellit wrote:
> And I think (correct me if I am wrong) that the ^ operator (xor) is
> used very very infrequently. And it is not difficult to replace all ^
> with say ^^. The division is probably used more often, but python has
> this trend anyway - to replace division with 'true' division, so
> people should use // when they divide integers and expect an integer.

That's besides the point.  It *breaks* python, which is a problem.  How
can someone use your code with other third-party modules which may use
this operator?

> 
> Other than these two things (the second one does not require
> recompilation, so it is not so bad probably) I don't need any changes
> to python core. I agree that a standard must be standard.

With that in mind, why not implement your shell layer using pypy (python
on python). That way you can have a full python parser that you can
modify to your hearts content, running on an unmodified cpython core.
Or implement your own parser using pyparsing.

Or how about this:  Implement a shell in python that uses regex to
replace and translate PariPython syntax into python syntax, and then
evaluate it on the unmodified core.

There's got to be some solution that doesn't break python.   Of course
really you would be (and are) creating a new language.  Call it
PariPython or something.  Make a new file extension so people don't
confuse it with python.  like ".ppy" or something.


> 
> Anton

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


Re: Pari Python

2007-10-28 Thread Robert Kern
Anton Mellit wrote:
>> Have you looked at SAGE at all? They already have wrappers for Pari.
> 
> Well :) I expected that question. I tried. But the distribution for
> windows is so big :( (2GB) and I could not build it on cygwin, where
> it is also pretty big. And I so much like pari - it is so light and
> simple and still can do almost everything. So my idea is to make
> simple module for python so that you don't need to install 2GB program
> with 2000 functions where it is difficult to find the one you need,
> but just type 'import pari', and then help(pari), and then find a
> function like 'ellinit' and create an elliptic curve, or type some
> polynomial and factor, or expand some function into power series, or
> integrate numerically...
> 
> I heard from some people that SAGE is good but i somehow don't
> appreciate the approach.
> 
>> I don't recommend continuing to modify core parts of Python just for your
>> module. It means that you will break other Python modules. If you can't use
>> other Python modules with your module, what's the point of using Python at 
>> all?
> 
> Of course you don't have to replace ** with ^ or making that hack with
> division. The module would work with or without these changes. But I
> think every mathematician agrees that x**2 is really ugly.

So? There is no reason to make alterations to the core to achieve what you want.
You just need to parse your almost-Python code yourself before executing it.
That's what SAGE does. You really should take a closer look at it. It is
possible to take just part of SAGE and not install the whole thing.

-- 
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: Getting callfunc from ast code.

2007-10-28 Thread Glich
Your help is very useful. I would not be able to progress without you!
Thanks.

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


Re: coverage.py: "Statement coverage is the weakest measure of code coverage"

2007-10-28 Thread John Roth
On Oct 28, 4:56 pm, Ben Finney <[EMAIL PROTECTED]> wrote:
> Howdy all,
>
> Ned Batchelder has been maintaining the nice simple tool 'coverage.py'
> http://nedbatchelder.com/code/modules/coverage.html> for
> measuring unit test coverage.
>
> On the same site, Ned includes documentation
> http://nedbatchelder.com/code/modules/rees-coverage.html> by the
> previous author, Gareth Rees, who says in the "Limitations" section:
>
> Statement coverage is the weakest measure of code coverage. It
> can't tell you when an if statement is missing an else clause
> ("branch coverage"); when a condition is only tested in one
> direction ("condition coverage"); when a loop is always taken and
> never skipped ("loop coverage"); and so on. See [Kaner 2000-10-17]
> http://www.kaner.com/pnsqc.html> for a summary of test
> coverage measures.
>
> So, measuring "coverage of executed statements" reports complete
> coverage incorrectly for an inline branch like 'foo if bar else baz',
> or a 'while' statement, or a 'lambda' statement. The coverage is
> reported complete if these statements are executed at all, but no
> check is done for the 'else' clause, or the "no iterations" case, or
> the actual code inside the lambda expression.
>
> What approach could we take to improve 'coverage.py' such that it
> *can* instrument and report on all branches within the written code
> module, including those hidden inside multi-part statements?
>
> --
>  \"Technology is neither good nor bad; nor is it neutral." |
>   `\   -Melvin Kranzberg's First Law of Technology |
> _o__)  |
> Ben Finney

Well, having used it for Python FIT, I've looked at some if its
deficiencies. Not enough to do anything about it (although I did
submit a patch to a different coverage tool), but enough to come to a
few conclusions.

There are two primary limitations: first, it runs off of the debug or
trace hooks in the Python kernel, and second, it's got lots of little
problems due to inconsistencies in the way the compiler tools generate
parse trees.

It's not like there are a huge number of ways to do coverage. At the
low end you just count the number of times you hit a specific point,
and then analyze that.

At the high end, you write a trace to disk, and analyze that.

Likewise, on the low end you take advantage of existing hooks, like
Python's debug and trace hooks, on the high end you instrument the
program yourself, either by rewriting it to put trace or count
statements everywhere, or by modifying the bytecode to do the same
thing.

If I was going to do it, I'd start by recognizing that Python doesn't
have hooks where I need them, and it doesn't have a byte code
dedicated to a debugging hook (I think). In other words, the current
coverage.py tool is getting the most out of the available hooks: the
ones we really need just aren't there.

I'd probably opt to rewrite the programs (automatically, of course) to
add instrumentation statements. Then I could wallow in data to my
heart's content.

One last little snark: how many of us keep our statement coverage
above 95%? Statement coverage may be the weakest form of coverage, but
it's also the simplest to handle.

John Roth

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


Re: while within while

2007-10-28 Thread Shawn Minisall
Thanks a lot for your suggestions.  Unfortunately, a lot of the issues 
brought up were simply the way I was taught by my professor and the way 
she wants things done,having to use a numbered menu as opposed to 
entering r, p or s, being taught just to use one main function for the 
entire program, having to init all variables in the program b4 the 
actual program starts or else points off for each program, while 
statements surrounding every input statement for input validation 
purposes...

Going beyond those things, would look like someone else wrote my program 
since we didn't talk about or ever cover them in class.  I think we get 
to true statements in the next chapter next week.

It turns out that my problem was with indentation, as soon as I fixed 
it, it's working perfectly now. 

thx

Dennis Lee Bieber wrote:
> On Sat, 27 Oct 2007 15:11:37 -0400, Shawn Minisall
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>   Smells like homework -- so this week I won't be supplying a working
> program (even one with no documentation -- requiring the student to
> study the reference manuals to figure out what is being done) I'm going
> to more focus on some stylistic features.
>   
>> import random
>>
>>
>> def main():
>>
>> #define and initialize variables
>> #choice as int
>> choice = 0
>> 
>   
>   Please note that one cannot define /type/ for a variable NAME. the
> name is just a name that is attached to an object, and can be attached
> to some other object later... It is the object on the RHS of the
> assignment that has a type.
>
>   The above binds the name "choice" to an object of type integer -- a
> 0... The type is part of the 0, not of the name.
>
>   
>> #play again loop
>> again = "no"
>> 
>
>   
>   
>>
>> #Menu loop
>> while choice != 4:
>> #display menu
>> print "Please choose from the following menu: "
>> print "1. See the rules"
>> print "2. Play against the computer"
>> print "3. Play a two player game"
>> print "4. Exit"
>>
>> #prompt user for their menu choice
>> choice = input("Please enter your choice here: ")
>> print
>>
>> 
>   Rather than having to pre-initialize your loop conditional (and
> notice that you can use ANY value EXCEPT 4 to initialize it) just for
> the pleasure of using a while loop (I'm guessing being taught from the
> "go to is forbidden" crowd, and not knowing of structured loop exits..)
> that you go out of your way to avoid duplicating code (Pardon my
> phrasing -- I'm not quite sure what my point was trying to be...) Let me
> just mention that in Ada, what you are trying would be formulated as:
>
> loop
>   --display menu
>   -- prompt for choice
>   exit when choice = 4
>   -- process other choices
> end loop
>
>   No need to preload the condition variable, since the first time it
> is used is when it receives a value from the user.
>
>   Python can produce the same formulation... (hint: the naked "loop"
> in Ada is "while True" in Python).
>
>   
>>
>>
>> #if statements to determine which choice
>> if choice == 1:
>> print
>> print "The rules of the game are as follows: "
>> print
>> print "Rock Covers Rock"
>> print
>> print "Rock Smashes Scissors"
>> print
>> print "Scissors Cuts Paper"
>> print
>> print
>>
>> 
>   Python triple quoted strings can be split over multiple lines:
>
>   print """
> The rules of the game are as follows:
>
>   Paper Covers Rock
>
>   Scissors Cut Paper
>
>   Rock Breaks Scissors
>
> """
> even better -- This should be an initialized item at the start of the
> program:
>
> rules = """
> The rules... etc.
> """
> and then you just use one
>
>   print rules
>
> 
>   
>>
>> elif choice == 2:
>> while again[0] == "y":
>> 
>
>   I'd suggest same concern as prior while loop... don't preload
> choices when the real determination can only be made after first
> entering the loop.
>
>   Secondly... If you are taking user input, you should probably expect
> things like case changes
>
>   while again.lower().startswith("y")
>
>   
>> #display menu
>> print "Please choose a weapon from the following menu: "
>> print "1. Rock"
>> print "2. Paper"
>> print "3. Scissors"
>>
>> while weaponchoice != 1 and weaponchoice != 2 and 
>> weaponchoice != 3:
>> 
>
>   A third preloaded nested while loop... And why require numeric
> input? Why not allow the user to enter, say "r" for rock?
>
>   
>> weaponchoice = input("Please choose a weapon: ")
>> 
>
>   Don't use input()... input() will evaluate whatever th

Re: Pari Python

2007-10-28 Thread J. Cliff Dyer
Anton Mellit wrote:
> And I think (correct me if I am wrong) that the ^ operator (xor) is
> used very very infrequently. And it is not difficult to replace all ^
> with say ^^. 
Oh God!  *Please* don't start that conversation again.  We had a thread
about bitwise operators a few weeks back.  Half the people will pipe up
and say, "Nope, I never use them," and the other half will say, "I can't
live without them."  And the ones who can't live without them tend to be
the ones doing more math-heavy work.

It's not worth messing with the bitwise operators. 
> The division is probably used more often, but python has
> this trend anyway - to replace division with 'true' division, so
> people should use // when they divide integers and expect an integer

If you want to use true division, delay your release until python 3 or
import it from __future__ yourself.  Don't break all current code by
recompiling python to do it.  You'll alienate most of your potential
user base, and develop a reputation for not playing well with others.

Cheers,
Cliff


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


Re: coverage.py: "Statement coverage is the weakest measure of code coverage"

2007-10-28 Thread Ben Finney
John Roth <[EMAIL PROTECTED]> writes:

> On Oct 28, 4:56 pm, Ben Finney <[EMAIL PROTECTED]> wrote:
> > What approach could we take to improve 'coverage.py' such that it
> > *can* instrument and report on all branches within the written
> > code module, including those hidden inside multi-part statements?
> 
> If I was going to do it, I'd start by recognizing that Python
> doesn't have hooks where I need them, and it doesn't have a byte
> code dedicated to a debugging hook (I think).

Is this something that Python could be improved by adding? Perhaps
there's a PEP in this.

> One last little snark: how many of us keep our statement coverage
> above 95%? Statement coverage may be the weakest form of coverage,
> but it's also the simplest to handle.

Yes, I have several projects where statement coverage of unit tests is
98% or above. The initial shock of running 'coverage.py' is in seeing
just how low one's coverage actually is; but it helpfully points out
the exact line numbers of the statements that were not tested.

Once you're actually measuring coverage as part of the development
process (e.g. set up a rule so 'make coverage' does it automatically),
it's pretty easy to see the holes in coverage and either write the
missing unit tests or (even better) refactor the code so the redundant
statements aren't there at all.

-- 
 \ "I'd like to see a nude opera, because when they hit those high |
  `\   notes, I bet you can really see it in those genitals."  -- Jack |
_o__)   Handey |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


PEP 299 and unit testing

2007-10-28 Thread Ben Finney
Howdy all,

PEP 299 http://www.python.org/dev/peps/pep-0299> details an
enhancement for entry points to Python programs: a module attribute
(named '__main__') that will be automatically called if the module is
run as a program.

The PEP has status "Rejected", citing backward-compatibility issues,
and Guido's pronouncement that "It's not worth the change (in docs,
user habits, etc.) and there's nothing particularly broken."

I don't deny the backward-compatibility issues in the cited
discussion, but I'd like to point out one thing that is broken by
this: unit testing of program modules.


Unit tests need to import a module and introspectively test small
units from the module to verify their behaviour in isolation. The
boundary of a unit test is the code that's actually in the module
under test: any functional code in that module needs to be tested by
the module's unit test, any code not in that module is outside the
scope of that unit test module.

The logical extension of this is to put *all* functional code into
discrete units, including the "main line" code that gets executed when
the module is run as a program. This leads to code of the type
discussed in PEP 299:

def main(argv):
""" Do the main stuff of this program """
parse_commandline(argv)
try:
do_interesting_things()
except SystemExit, e:
exitcode = e.code
return exitcode

if __name__ == "__main__":
import sys
exitcode = main(sys.argv)
sys.exit(exitcode)

This allows the module's 'main' function to be called as a discrete
unit from the unit test module; the unit test passes in 'argv' as
desired, and fakes out other units that aren't being tested.

What it doesn't allow is for the testing of the 'if __name__ ==
"__main__":' clause itself. No matter how simple we make that, it's
still functional code that can contain errors, be they obvious or
subtle; yet it's code that *can't* be touched by the unit test (by
design, it doesn't execute when the module is imported), leading to
errors that won't be caught as early or easily as they might.

So, I'd argue that "nothing particularly broken" isn't true: unit
testing is flawed in this scenario. It means that even the simple
metric of statement-level test coverage can't ever get to 100%, which
is a problem since it defeats a simple goal of "get all functional
code covered by unit tests".


On the other hand, if PEP 299 *were* implemented (and the
backward-compatibility issues solved), the above could be written as:

def __main__(argv):
""" Do the main stuff of this program """
parse_commandline(argv)
try:
do_interesting_things()
except SystemExit, e:
exitcode = e.code
return exitcode

with no module-level 'if __name__' test at all, and therefore no
functional code unreachable by the unit test module. The effect of the
program is the same, but the invocation of the '__main__' function
isn't left to be implemented in every single program, separately and
subject to error in every case. Instead, it becomes part of the
*external* environment of the module, and is trivially outside the
scope of a unit test module for that program.

-- 
 \  "What I have to do is see, at any rate, that I do not lend |
  `\   myself to the wrong which I condemn."  -- Henry Thoreau, _Civil |
_o__)Disobedience_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: simple question on dictionary usage

2007-10-28 Thread George Sakkis
On Oct 27, 8:58 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sat, 27 Oct 2007 05:23:30 -0700, bearophileHUGS wrote:
> > My take too :-)
>
> > dict(item for item in record.iteritems() if item[0][0] == 'E')
>
> ``s.startswith('E')`` is a little safer than ``s[0] == 'E'`` as the former
> returns `False` if `s` is empty while the latter raises an `IndexError`.

A string slice is safe and faster though: if s[:1] == 'E'.

George

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


7000+ beautiful Russian girls waiting for men

2007-10-28 Thread my glass
7000+ beautiful Russian girls waiting for men
http://groups.google.com/group/all-good-things/web/beautiful-girls-and-ladies

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


New

2007-10-28 Thread jkbiwott2002
Hi!
Am new to Python and am looking for a sample project that demonstrates
how to connect to MySQL, save data in MySQL database using a form on a
web page.

Regards,
Joseph

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


Re: coverage.py: "Statement coverage is the weakest measure of code coverage"

2007-10-28 Thread Kay Schluehr
On Oct 28, 11:56 pm, Ben Finney <[EMAIL PROTECTED]> wrote:
> Howdy all,
>
> Ned Batchelder has been maintaining the nice simple tool 'coverage.py'
> http://nedbatchelder.com/code/modules/coverage.html> for
> measuring unit test coverage.
>
> On the same site, Ned includes documentation
> http://nedbatchelder.com/code/modules/rees-coverage.html> by the
> previous author, Gareth Rees, who says in the "Limitations" section:
>
> Statement coverage is the weakest measure of code coverage. It
> can't tell you when an if statement is missing an else clause
> ("branch coverage"); when a condition is only tested in one
> direction ("condition coverage"); when a loop is always taken and
> never skipped ("loop coverage"); and so on. See [Kaner 2000-10-17]
> http://www.kaner.com/pnsqc.html> for a summary of test
> coverage measures.
>
> So, measuring "coverage of executed statements" reports complete
> coverage incorrectly for an inline branch like 'foo if bar else baz',
> or a 'while' statement, or a 'lambda' statement. The coverage is
> reported complete if these statements are executed at all, but no
> check is done for the 'else' clause, or the "no iterations" case, or
> the actual code inside the lambda expression.
>
> What approach could we take to improve 'coverage.py' such that it
> *can* instrument and report on all branches within the written code
> module, including those hidden inside multi-part statements?

I used to write once a coverage tool ( maybe I can factor this out of
my tool suite some time ) which is possibly transformative. Currently
it generates measurement code for statement coverage and i'm not sure
it has more capabilities than coverage.py because I was primary
interested in the code generation and monitoring process, so I didn't
compare.

Given it's nature it might act transformative. So a statement:

if a and b:
BLOCK

can be transformed into

if a:
if b:
BLOCK

Also

if a or b:
BLOCK

might be transformed into

if a:
   BLOCK
elif b:
   BLOCK

So boolean predicates are turned into statements and statement
coverage keeps up. This is also close to the way bytecode works
expressing "and" | "or" predicates using jumps. I'm not sure about
expressions yet, since I did not care about expression execution but
traces.

The underlying monitoring technology needs to be advanced. I used a
similar approach for an even more interesting purpose of feeding
runtime type information back into a cloned parse tree of the initial
tree which might be unparsed to type annotated source code after
program execution. But that's another issue.

The basic idea of all those monitorings is as follows: implement an
identity function with a side effect. I'm not sure how this monitoring
code conflicts with rather deep reflection ( stacktrace inspection
etc. )

Kay

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


ANNOUNCE: wxPython 2.8.6.1

2007-10-28 Thread Robin Dunn

Announcing
--

The 2.8.6.1 release of wxPython is now available for download at
http://wxpython.org/download.php.  This release has a number of
important bug fixes and is a general improvement of the 2.8.6.0
release.

Source code is available, as well as binaries for Python 2.3, 2.4 and
2.5, for Windows and Mac, as well some pacakges for various Linux
distributions.  A summary of changes is listed below and also at
http://wxpython.org/recentchanges.php.


What is wxPython?
-

wxPython is a GUI toolkit for the Python programming language. It
allows Python programmers to create programs with a robust, highly
functional graphical user interface, simply and easily. It is
implemented as a Python extension module that wraps the GUI components
of the popular wxWidgets cross platform library, which is written in
C++.

wxPython is a cross-platform toolkit. This means that the same program
will usually run on multiple platforms without modifications.
Currently supported platforms are 32-bit Microsoft Windows, most Linux
or other Unix-like systems using GTK2, and Mac OS X 10.3+, in most
cases the native widgets are used on each platform to provide a 100%
native look and feel for the application.


Changes in 2.8.6.1
--

wxMac: Fixed paste bug when the clipboard contains unicode text.

AUI: Added missing event binders for the notebok tab events.

wxMac: Fixed bug that resulted in portions of virtual listctrl's to
not be repainted when scrolling with PgUp/PgDown/Home/End.

wxMac: Fixed bug that broke tab traversal when tabbing runs into a
wx.StaticBox.

wxGTK:  Add wx.Window.GetGtkWidget.

All: Undprecated wx.ListCtrl.[G|S]etItemSpacing

All: Fixed wx.Palette constructor wrapper.  It takes three seqences of
integers to specify the R, G, and B values for each color in the
palette, which must all be the same length and which must contain
integer values in the range of 0..255 inclusive.

Thanks to some grunt work from Edouard TISSERANT, wxPython now has the
needed tweaks in config.py to be able to be built with mingw32.  See
BUILD.txt for details.

Changes in wx.GraphicsContext to make things like the half-pixel
offsets more consistent across platforms.

wxMSW: If freezing a top-level window wxWidgets will actually freeze
the TLW's children instead.  This works around a feature of MS Windows
that allowed windows beneath the frozen one in Z-order to paint
through, and also mouse events clicking through to the lower window.


-- 
Robin Dunn
Software Craftsman
http://wxPython.org  Java give you jitters?  Relax with wxPython!

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


clear shell screen

2007-10-28 Thread Shawn Minisall
Does anyone know how to clear the shell screen completely ?  I tried 
import os and then os.system("clear") was said to have worked in Windows 
XP, but it's just bringing up another window, then it turns black and 
then it closes in within about a second moving the prompt at the 
os.system("clear") line .  I've also tried os.system("cls") with the 
same results.

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


Re: Anagrams

2007-10-28 Thread Gabriel Genellina
En Thu, 25 Oct 2007 00:40:12 -0300, sandipm <[EMAIL PROTECTED]>  
escribi�:

> thanks..I  am using python 2.4.4. so i couldnt find "all" either as
> inbuilt module
> or by doing "from itertools import *",  "all" is not available.
> I think I need to move to 2.5 then

It's easy to write in pure Python:

def all(iterable):
 for item in iterable:
 if not item: return False
 return True

And its cousin, any:

def any(iterable):
 for item in iterable:
 if item: return True
 return False

> but what are the pros/cons of moving to 2.5? as we are using 2.4.4 on
> production server which is quite stable.
> any good pointers?

Pros: See the "What's new" document  
http://www.python.org/doc/2.5/whatsnew/whatsnew25.html

Cons: As always with any "dot" release, extension modules are incompatible  
and have to be recompiled. Even a year after the 2.5 release, you may have  
some problems finding precompiled binaries. Ensure that all your required  
libraries are available for 2.5

-- 
Gabriel Genellina

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

Re: coverage.py: "Statement coverage is the weakest measure of code coverage"

2007-10-28 Thread Ben Finney
Kay Schluehr <[EMAIL PROTECTED]> writes:

> I used to write once a coverage tool ( maybe I can factor this out
> of my tool suite some time )

That'd be wonderful. I'd like to see comparisons between different
test-coverage tools, just as we have the different but comparable
'pyflakes' and 'pylint' code inspection tools.

> Given it's nature it might act transformative. So a statement:
> 
> if a and b:
> BLOCK
> 
> can be transformed into
> 
> if a:
> if b:
> BLOCK

I don't see that this actually helps in the cases described in the
original post. The lack of coverage checking isn't "are both sides of
an 'and' or 'or' expression evaluated", since that's the job of the
language runtime, and is outside the scope of our unit test.

what needs to be tested is "do the tests execute both the 'true' and
'false' branches of this 'if' statement", or "do the tests exercise
the 'no iterations' case for this loop", et cetera. That is, whether
all the functional branches are exercised by tests, not whether the
language is parsed correctly.

-- 
 \"Know what I hate most? Rhetorical questions."  -- Henry N. Camp |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 299 and unit testing

2007-10-28 Thread Steven Bethard
Ben Finney wrote:
> What it doesn't allow is for the testing of the 'if __name__ ==
> "__main__":' clause itself. No matter how simple we make that, it's
> still functional code that can contain errors, be they obvious or
> subtle; yet it's code that *can't* be touched by the unit test (by
> design, it doesn't execute when the module is imported), leading to
> errors that won't be caught as early or easily as they might.

You could always use runpy.run_module.

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


Re: caluclating median distance

2007-10-28 Thread Gabriel Genellina
En Sun, 28 Oct 2007 11:13:39 -0300, Beema shafreen  
<[EMAIL PROTECTED]> escribi�:

> 1175123443A_16_P03652190
> 12771336387A_16_P41582022
> 1723178298A_16_P03652191
>
> how to calculate the median spacing of an data in the file basically
> focusing on the third column of an file. say for example the median  
> spacing
> is to be 635. how do we programtically calculate the median spacing and  
> sort
> the file according to the third column's median spacing.
> hope median we calculate  using (N+1)/2

I don't understand exactly what you want. To compute the median, the  
easiest and obvious way is to sort the data first and choose the middle  
element. For large sets, there are more efficient ways; see this recipe in  
the Python Cookbook:  


-- 
Gabriel Genellina

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

Re: Capturing output with input

2007-10-28 Thread Gabriel Genellina
En Sun, 28 Oct 2007 15:39:07 -0300, gopala <[EMAIL PROTECTED]>  
escribi�:

> My initial attempts of using spawn.. , exec.. pipe.. failed since they
> can't capture the std input and std output continuously.
> The lab1.exe will be something like
>
> Enter 2 nos
> 2 3
> The sum is 5
>
> Now i should be able to capture all these.
> Is this possible ? If so please do give me some hints on how to
> achieve this.

On Linux, use the "script" command.
On Windows, select the region to copy using the mouse and paste it onto a  
notepad file.
I don't think Python would help here.

-- 
Gabriel Genellina

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

Re: Easiest way to get exit code from os.popen()?

2007-10-28 Thread Gabriel Genellina
En Wed, 24 Oct 2007 16:07:44 -0300, mrstephengross  
<[EMAIL PROTECTED]> escribi�:

> Hi folks. I'm using os.popen() to run a command; according to the
> documentation, the filehandle.close() oepration is suppsoed to return
> the exit code. However, when I execute something like "exit 5",
> close() returns 1280. Here's the code:
>
>   pipe = os.popen("exit 5")
>   print pipe.close() # prints 1280
>
> Am I doing something wrong? Is there an easier way to get the exit
> code?

Read the docs again...

-- 
Gabriel Genellina

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

Re: PEP 299 and unit testing

2007-10-28 Thread Ben Finney
Steven Bethard <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> > What it doesn't allow is for the testing of the 'if __name__ ==
> > "__main__":' clause itself. No matter how simple we make that,
> > it's still functional code that can contain errors, be they
> > obvious or subtle; yet it's code that *can't* be touched by the
> > unit test (by design, it doesn't execute when the module is
> > imported), leading to errors that won't be caught as early or
> > easily as they might.
> 
> You could always use runpy.run_module.

For values of "always" that include Python 2.5, of course. (I'm still
coding to Python 2.4, until 2.5 is more widespread.)

Thanks! I was unaware of that module. It does seem to nicely address
the issue I discussed.

-- 
 \ "Pinky, are you pondering what I'm pondering?" "I think so, |
  `\Brain, but Zero Mostel times anything will still give you Zero |
_o__)   Mostel."  -- _Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


iPod Library

2007-10-28 Thread D
Is there a Python library available that will allow you to read/write
from the database of an iPod 3G and 5G?  Basically, I'm sick of iTunes
and would much rather write a simple program myself.  Thanks.

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


Re: PEP 299 and unit testing

2007-10-28 Thread Steven Bethard
Ben Finney wrote:
> Steven Bethard <[EMAIL PROTECTED]> writes:
> 
>> Ben Finney wrote:
>>> What it doesn't allow is for the testing of the 'if __name__ ==
>>> "__main__":' clause itself. No matter how simple we make that,
>>> it's still functional code that can contain errors, be they
>>> obvious or subtle; yet it's code that *can't* be touched by the
>>> unit test (by design, it doesn't execute when the module is
>>> imported), leading to errors that won't be caught as early or
>>> easily as they might.
>> You could always use runpy.run_module.
> 
> For values of "always" that include Python 2.5, of course. (I'm still
> coding to Python 2.4, until 2.5 is more widespread.)
> 
> Thanks! I was unaware of that module. It does seem to nicely address
> the issue I discussed.

You might try the runpy module as-is with Python 2.4.  I don't know if 
it works, but it's pure Python so it's worth a try.

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


Re: coverage.py: "Statement coverage is the weakest measure of code coverage"

2007-10-28 Thread Kay Schluehr
On Oct 29, 4:15 am, Ben Finney <[EMAIL PROTECTED]>
wrote:
> Kay Schluehr <[EMAIL PROTECTED]> writes:
> > I used to write once a coverage tool ( maybe I can factor this out
> > of my tool suite some time )
>
> That'd be wonderful. I'd like to see comparisons between different
> test-coverage tools, just as we have the different but comparable
> 'pyflakes' and 'pylint' code inspection tools.
>
> > Given it's nature it might act transformative. So a statement:
>
> > if a and b:
> > BLOCK
>
> > can be transformed into
>
> > if a:
> > if b:
> > BLOCK
>
> I don't see that this actually helps in the cases described in the
> original post. The lack of coverage checking isn't "are both sides of
> an 'and' or 'or' expression evaluated", since that's the job of the
> language runtime, and is outside the scope of our unit test.
>
> what needs to be tested is "do the tests execute both the 'true' and
> 'false' branches of this 'if' statement", or "do the tests exercise
> the 'no iterations' case for this loop", et cetera. That is, whether
> all the functional branches are exercised by tests, not whether the
> language is parsed correctly.

You are right. I re-read my coverage tool documentation and found also
the correct expansion for the statement

if a and b:
   BLOCK

which is:

if a:
if b:
BLOCK
else:
BLOCK
else:
BLOCK

This will cover all relevant traces. The general idea still holds.

Note I would like to see some kind of requirement specification ( a
PEP style document ) of different coverage purposes and also a test
harness. I'm all for advancing Python and improve the code base not
just accidentally. Something in the way of an MVC framework was nice
in addition which implements UI functions independently s.t. the basic
coverage functionality can be factored out into components and
improved separately. I do not think it's a good idea to have 10
coverage tools that handle presentation differently.





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


Any library parsing wikipedia API

2007-10-28 Thread est
I got some text via wikipedia API

http://en.wikipedia.org/w/api.php?action=query&prop=revisions&titles=Chengdu&rvprop=content&redirects&format=xml&callback=wikiCallback

but it's not HTML formated. So how can I parse these texts to standard
HTML? Are there any library in python could do this?

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


Re: PEP 299 and unit testing

2007-10-28 Thread Ben Finney
Steven Bethard <[EMAIL PROTECTED]> writes:

> Ben Finney wrote:
> > Thanks! I was unaware of that module. It does seem to nicely
> > address the issue I discussed.
> 
> You might try the runpy module as-is with Python 2.4.  I don't know
> if it works, but it's pure Python so it's worth a try.

Drat. It uses (by explicit design) "the standard import mechanism" to
load the module, which means it doesn't work for exactly the thing I'm
trying to do: load a program file *not* named with a '.py' suffix.

I've long been able to load my program modules from no-suffix
filenames (or indeed any non-standard filenames) with this function::

def make_module_from_file(module_name, file_name):
""" Make a new module object from the code in specified file """

from types import ModuleType
module = ModuleType(module_name)

module_file = open(file_name, 'r')
exec module_file in module.__dict__
sys.modules[module_name] = module

return module

Unfortunately, it seems that "module is already present with name
'foo' in 'sys.modules'" is insufficient for the Python import
mechanism. The module loader used by 'runpy' still complains that it
can't find the module, which is no surprise because its filename is
not that of a library module.

Perhaps I need to delve into the details of the import mechanism
myself :-(

-- 
 \"With Lisp or Forth, a master programmer has unlimited power |
  `\ and expressiveness. With Python, even a regular guy can reach |
_o__)for the stars."  -- Raymond Hettinger |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 299 and unit testing

2007-10-28 Thread Ben Finney
Ben Finney <[EMAIL PROTECTED]> writes:

> Steven Bethard <[EMAIL PROTECTED]> writes:
> 
> > Ben Finney wrote:
> > > What it doesn't allow is for the testing of the 'if __name__ ==
> > > "__main__":' clause itself. No matter how simple we make that,
> > > it's still functional code that can contain errors, be they
> > > obvious or subtle; yet it's code that *can't* be touched by the
> > > unit test (by design, it doesn't execute when the module is
> > > imported), leading to errors that won't be caught as early or
> > > easily as they might.
> > 
> > You could always use runpy.run_module.
> 
> Thanks! I was unaware of that module. It does seem to nicely address
> the issue I discussed.

Thinking about it further: I don't think it does address the issue.

Running the *entire* module code again in a single step (as
'run_module' seems to do) would happily overwrite any instrumented
faked attributes of the module that were inserted for the purpose of
unit testing, rendering it useless for unit test purposes.

The issue here is that there is an irreducible amount of functional
code inside the module that cannot be unit tested without running the
entire program with all its side effects.

PEP 299 promises to make that specific small-but-significant code
become an implementation detail in the language runtime, which would
mean it would no longer be prone to errors in the modules themselves,
and thus no longer the topic of a unit test on those modules. I think
100% statement coverage is not possible in Python programs without
this, or something that achieves the same thing.

-- 
 \   "We spend the first twelve months of our children's lives |
  `\  teaching them to walk and talk and the next twelve years |
_o__)telling them to sit down and shut up."  -- Phyllis Diller |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


[OT] Re: Proposal: Decimal literals in Python.

2007-10-28 Thread Gabriel Genellina
En Fri, 26 Oct 2007 23:28:31 -0300, Carl Banks <[EMAIL PROTECTED]>  
escribi�:

> FYI: The $ sign is used to denote currency in many countries; as a
> rule of thumb countties that call their currency "dollars" or "pesos"
> use the $.  So Mexico, Canada, Australia, much of Latin America, much
> of the Pacific, not to mention countries in Africa (Zimbabwe) and Asia
> (Singapore).

[OT] Furthermore, the $ sign was used originally to denote "pesos", or  
Spanish reals (pieces of eight each). It was later that the US adopted the  
sign to denote "dollars" too.

-- 
Gabriel Genellina

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

IEC - cannot find button

2007-10-28 Thread daniel_nolan
I'm brand new to Python--and programming in general. I'm trying to use
IEC to control Internet Explorer. I've navigated to a page, and now
I'm trying to click a button. The button appears to be called 'PDF
Preview' but I honestly do not know whether that's the name or the
caption. Here is my code:

 from win32com.client import Dispatch
 import IEC

 .
 .
 .


 ie = IEC.IEController(window_num = 1)
 ie.Navigate(URL_part_1 + x + URL_part_2)
 ie.ClickButton(name='PDF Preview')

(I've also tried replacing name w/ caption but I get a similar error
message.) I get this error message:

Traceback (most recent call last):
  File "C:\Program Files\Python25\experiment", line 14, in 
ie.ClickButton(name='PDF Preview')
  File "C:\Program Files\Python25\lib\IEC.py", line 126, in
ClickButton
elem = elemcoll.item(i)
  File ">", line 3, in item
com_error: (-2147024891, 'Access is denied.', None, None)

I really have no idea how to interpret this. I'm pasting the button
tag below:


 


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


Solaris 10 + Sun Studio 12 Pyrhon 2.4.4 64-bit build problem

2007-10-28 Thread plumb and tree
I've been trying for days to build 64 bit python with Solaris 10 + Sun
Studio 12.

Can anyone helpl please.

This is how I tried to do build:

# ./configure --prefix=/opt/python2.4 --without-gcc --enable-shared
checking MACHDEP... sunos5
checking EXTRAPLATDIR...
checking for --without-gcc... yes
checking for --with-cxx=... no
checking for c++... /opt/SUNWspro/bin/CC
checking for C++ compiler default output file name... a.out
checking whether the C++ compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for gcc... cc
checking for C compiler default output file name... a.out
checking whether the C compiler works... yes
checking whether we are cross compiling... no
checking for suffix of executables...
checking for suffix of object files... o
checking whether we are using the GNU C compiler... no
checking whether cc accepts -g... yes
checking for cc option to accept ANSI C... none needed
checking how to run the C preprocessor... /opt/SUNWspro/bin/CC
configure: error: C preprocessor "/opt/SUNWspro/bin/CC" fails sanity
check
See `config.log' for more details.

(sorry for the long log file but I'm not sure which part are
important)
config.log:
This file contains any messages produced by compilers while
running configure, to aid debugging if configure makes a mistake.

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

  $ ./configure --prefix=/opt/python2.4 --without-gcc --enable-shared

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

hostname = zone2
uname -m = sun4u
uname -r = 5.10
uname -s = SunOS
uname -v = Generic_118833-36

/usr/bin/uname -p = sparc
/bin/uname -X = System = SunOS
Node = zone2
Release = 5.10
KernelID = Generic_118833-36
Machine = sun4u
BusType = 
Serial = 
Users = 
OEM# = 0
Origin# = 1
NumCPU = 1

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

PATH: /usr/local/bin
PATH: /usr/xpg4/bin
PATH: /usr/sfw/bin
PATH: /opt/SUNWspro/bin
PATH: /usr/local/mysql/bin
PATH: /usr/ccs/bin
PATH: /usr/local/bin
PATH: /usr/xpg4/bin
PATH: /usr/sfw/bin
PATH: /opt/SUNWspro/bin
PATH: /usr/local/mysql/bin
PATH: /usr/ccs/bin
PATH: /usr/local/bin
PATH: /usr/xpg4/bin
PATH: /usr/sfw/bin
PATH: /opt/SUNWspro/bin
PATH: /usr/local/mysql/bin
PATH: /usr/ccs/bin
PATH: /usr/sbin
PATH: /usr/bin
PATH: /usr/openwin/bin
PATH: /usr/sfw/bin
PATH: /usr/openwin/bin
PATH: /usr/sfw/bin
PATH: /usr/openwin/bin
PATH: /usr/sfw/bin


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

configure:1510: checking MACHDEP
configure:1655: result: sunos5
configure:1661: checking EXTRAPLATDIR
configure:1676: result:
configure:1697: checking for --without-gcc
configure:1746: result: yes
configure:1752: checking for --with-cxx=
configure:1773: result: no
configure:1792: checking for c++
configure:1818: result: /opt/SUNWspro/bin/CC
configure:1858: checking for C++ compiler default output file name
configure:1861: /opt/SUNWspro/bin/CC   -L/opt/SUNWmlib/lib -lrt -lm
conftest.cc  >&5
configure:1864: $? = 0
configure:1910: result: a.out
configure:1915: checking whether the C++ compiler works
configure:1921: ./a.out
configure:1924: $? = 0
configure:1941: result: yes
configure:1948: checking whether we are cross compiling
configure:1950: result: no
configure:1953: checking for suffix of executables
configure:1955: /opt/SUNWspro/bin/CC -o conftest   -L/opt/SUNWmlib/lib
-lrt -lm conftest.cc  >&5
configure:1958: $? = 0
configure:1983: result:
configure:2057: checking for gcc
configure:2083: result: cc
configure:2327: checking for C compiler version
configure:2330: cc -V &5
cc: Sun C 5.9 SunOS_sparc Patch 124867-01 2007/07/12
usage: cc [ options] files.  Use 'cc -flags' for details
configure:2333: $? = 1
configure:2356: checking for C compiler default output file name
configure:2359: cc -O2  -L/opt/SUNWmlib/lib -lrt -lm conftest.c  >&5
configure:2362: $? = 0
configure:2408: result: a.out
configure:2413: checking whether the C compiler works
configure:2419: ./a.out
configure:2422: $? = 0
configure:2439: result: yes
configure:2446: checking whether we are cross compiling
configure:2448: result: no
configure:2451: checking for suffix of executables
configure:2453: cc -o conftest -O2  -L/opt/SUNWmlib/lib -lrt -lm
conftest.c  >&5
configure:2456: $? = 0
configure:2481: result:
configure:2487: checking for suffix of object files
configure:2508: cc -c -O2  conftest.c >&5
configure:2511: $? = 0
configure:2533: result: o
configure:2537: checking whether we are using the GNU C compiler
configure:2561: cc -c -O2  conftest.c >&5
"conftest.c", line 15: undefined symbol: choke
"conftest.c", line 15: syntax error before or at: me
cc: acomp failed for conftest.c
configure:2567: $? = 2
configure: failed program was:
| /* confdefs.h.  */
|
| #define _GNU_SOURCE 1
| #define _NET

Help with pyparsing and dealing with null values

2007-10-28 Thread avidfan
Help with pyparsing and dealing with null values

I am trying to parse a log file (web.out) similar to this:

---

MBeanName: "mtg-model:Name=mtg-model_managed2,Type=Server"
AcceptBacklog: 50
AdministrationPort: 0
AutoKillIfFailed: false
AutoRestart: true
COM: mtg-model_managed2
COMEnabled: false
CachingDisabled: true
ClasspathServletDisabled: false
ClientCertProxyEnabled: false
Cluster: mtg-model-cluster
ClusterRuntime: mtg-model-cluster
ClusterWeight: 100
CompleteCOMMessageTimeout: -1
CompleteHTTPMessageTimeout: -1
CompleteIIOPMessageTimeout: -1
CompleteMessageTimeout: 60
CompleteT3MessageTimeout: -1
CustomIdentityKeyStoreFileName:
CustomIdentityKeyStorePassPhrase:
CustomIdentityKeyStorePassPhraseEncrypted:
CustomIdentityKeyStoreType:
CustomTrustKeyStoreFileName:
CustomTrustKeyStorePassPhrase:
CustomTrustKeyStorePassPhraseEncrypted:
CustomTrustKeyStoreType:
DefaultIIOPPassword:
DefaultIIOPPasswordEncrypted:
DefaultIIOPUser:
DefaultInternalServletsDisabled: false
DefaultProtocol: t3
DefaultSecureProtocol: t3s
DefaultTGIOPPassword:
DefaultTGIOPPasswordEncrypted: **
DefaultTGIOPUser: guest
DomainLogFilter:
EnabledForDomainLog: true
ExecuteQueues: weblogic.kernel.Default,foglight
ExpectedToRun: false
ExternalDNSName:
ExtraEjbcOptions:
ExtraRmicOptions:
GracefulShutdownTimeout: 0

---

and I need the indented values (eventually) in a dictionary.  As you
can see, some of the fields have a value, and some do not.  It appears
that the code I have so far is not dealing with the null values and
colons as I had planned.  Here is the code:

---

from pyparsing import *

input = open("web.out", 'r')
data = input.read()

end = Literal("\n").suppress()
all = SkipTo(end)
colon = Literal(":").suppress()
MBeanName = Literal("MBeanName:")
ServerName = dblQuotedString
identity = Word(alphas, alphanums+"._*/,-")
pairs = Group(identity + colon + Optional(identity) +all)

logEntry = MBeanName + ServerName.setResultsName("servername") +
OneOrMore(pairs)

for tokens in logEntry.searchString(data):
print
print "ServerName =\t "+ tokens.servername
for t in tokens:
   print t
print
print 50*"-"

-

which is giving me this:

-

ServerName = "mtg-model:Name=mtg-modelserver_map501,Type=Server"
MBeanName:
"mtg-model:Name=mtg-modelserver_map501,Type=Server"
['AcceptBacklog', '50']
['AdministrationPort', '0']
['AutoKillIfFailed', 'false', 'AutoRestart: true']
['COM', 'mtg-modelserver_map501', 'COMEnabled: false']
['CachingDisabled', 'true', 'ClasspathServletDisabled: false']
['ClientCertProxyEnabled', 'false', 'Cluster:']
['ClusterRuntime', 'ClusterWeight', ': 100']
['CompleteCOMMessageTimeout', '-1']
['CompleteHTTPMessageTimeout', '-1']
['CompleteIIOPMessageTimeout', '-1']
['CompleteMessageTimeout', '60']
['CompleteT3MessageTimeout', '-1']
['CustomIdentityKeyStoreFileName', 'CustomIdentityKeyStorePassPhrase',
':']
['CustomIdentityKeyStorePassPhraseEncrypted',
'CustomIdentityKeyStoreType', ':']
['CustomTrustKeyStoreFileName', 'CustomTrustKeyStorePassPhrase', ':']
['CustomTrustKeyStorePassPhraseEncrypted', 'CustomTrustKeyStoreType',
':']
['DefaultIIOPPassword', 'DefaultIIOPPasswordEncrypted', ':']
['DefaultIIOPUser', 'DefaultInternalServletsDisabled', ': false']
['DefaultProtocol', 't3', 'DefaultSecureProtocol: t3s']
['DefaultTGIOPPassword', 'DefaultTGIOPPasswordEncrypted', ': **']
['DefaultTGIOPUser', 'guest', 'DomainLogFilter:']
['EnabledForDomainLog', 'true', 'ExecuteQueues:
weblogic.kernel.Default,foglight']
['ExpectedToRun', 'false', 'ExternalDNSName:']
['ExtraEjbcOptions', 'ExtraRmicOptions', ':']
['GracefulShutdownTimeout', '0']



instead of this (one to one):



ServerName = "mtg-model:Name=mtg-modelserver_map501,Type=Server"
MBeanName:
"mtg-model:Name=mtg-modelserver_map501,Type=Server"
['AcceptBacklog', '50']
['AdministrationPort', '0']
['AutoKillIfFailed', 'false']
['AutoRestart', 'true']
['COM', 'mtg-modelserver_map501']
['COMEnabled', 'false']
['CachingDisabled', 'true']
['ClasspathServletDisabled', false']
['ClientCertProxyEnabled', 'false']
['Cluster', 'mtg-model-cluster']
['ClusterRuntime', 'mtg-model-cluster']
['ClusterWeight', '100']
['CompleteCOMMessageTimeout', '-1']
['CompleteHTTPMessageTimeout', '-1']
['CompleteIIOPMessageT

Kudzu Version of SonomaSunshine

2007-10-28 Thread SamFeltus
Funkiest SonomaSunshine page ever... A slim, trim 30ish MB page,
leaves time for fetching a beer or some coffee.  Takes about 10
minutes to watch.  Yet another example of using Django to generate
frilly, colorful Flash pages instead of more of that hypertext
stuff...

:)

http://samfeltus.com/kudzu/KudzuMan.html

###

http://samfeltus.com/site_index.html

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


Re: Weird AttributeError With Imports

2007-10-28 Thread Gabriel Genellina
En Sun, 28 Oct 2007 14:50:24 -0300, Juha S. <[EMAIL PROTECTED]> escribi�:

> Peter Otten wrote:
>> You probably have a time module that you wrote yourself and which is now
>> hiding the one in python's standard library. Was your mytime.py formerly
>> named time.py, and if so, did you remove the corresponding time.pyc?
>
> Yes, I did have mytime.py named as time.py previously. Now that I
> deleted the .pyc it seems to work fine. Thanks!

Wow! Most standard crystall balls would tell just about the time.py  
problem. Yours is certainly a very sophisticated one! It was even capable  
of detecting a rename and a forgotten .pyc file - that's far beyond the  
usual range! Congratulations!

-- 
Gabriel Genellina

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

Re: clear shell screen

2007-10-28 Thread Gabriel Genellina
En Mon, 29 Oct 2007 00:08:14 -0300, Shawn Minisall  
<[EMAIL PROTECTED]> escribi�:

> Does anyone know how to clear the shell screen completely ?  I tried
> import os and then os.system("clear") was said to have worked in Windows
> XP, but it's just bringing up another window, then it turns black and
> then it closes in within about a second moving the prompt at the
> os.system("clear") line .  I've also tried os.system("cls") with the
> same results.

Try running cls from a command prompt. If it works, it should work from  
inside Python, using os.system("cls")


-- 
Gabriel Genellina

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

Function to resize global numpy array interactively in ipython

2007-10-28 Thread David Sanders
Hi,

I have a script with function definitions which I load into ipython
for interactive use.
These functions modify a global numpy array, whose size I need to be
able to change interactively.  I thus have a script which looks like
this:

from numpy import *

def do_resize(N):
global a
a = resize(a, N)

a = array([])

N=10; do_resize(N)
print "Length of a is: ", len(a)
N=20; do_resize(N)
print "Length of a is: ", len(a)


If I run this in ipython, using "run resize.py", it correctly outputs
10 and then 20.
If I now type *interactively*  N=30; do_resize(N),  then the length of
a is still 20, rather than 30 as I was hoping -- somehow I seem to be
now dealing with a different copy of a?

Doing the same thing in idle works as I expect, i.e. interactively the
size is changed to 30.

Could somebody please explain what's going on, and how I solve the
problem?

Thanks and best wishes,
David.

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