Re: Can Parallel Python run on a muti-CPU server ?

2007-02-06 Thread [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
> Hi all,
>
> I'm interested in Parallel Python and I learned from the website of 
> Parallel Python
> that it can run on SMP and clusters. But can it run on a our muti-CPU 
> server ?
> We are running an origin3800 server with 128 CPUs.
>
> Thanks.
>   
I have tested that at least it could run sum_primes.py on our server.

But it seems Parallel Python just launch one python process for
each job, and if I let it use 12 CPUs for 8 jobs, Parallel Python
launches 12 python processes, 4 of which just sleep until all 8 jobs
are done.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running long script in the background

2007-02-06 Thread [EMAIL PROTECTED]
On Feb 6, 11:13 pm, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]>
wrote:

> output = os.popen(command, 'r', 1)

OOPS... I imagine the ridiculous buffer size is unnecessary... I was
trying to get it to work with the original for loop iterating on
output, it should work fine without it.

Pete

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


Re: Running long script in the background

2007-02-06 Thread [EMAIL PROTECTED]
On Feb 6, 5:26 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I am trying to write a python cgi that calls a script over ssh, the
> problem is the script takes a very long time to execute so Apache
> makes the CGI time out and I never see any output.  The script is set
> to print a progress report to stdout every 3 seconds but I never see
> any output until the child process is killed.
>

>
> Does anybody know a way to make output show in real time?

Try this:



# test.py
import os
import sys
import time

def command():
for x in range(5):
print x
sys.stdout.flush()
time.sleep(1)

def main():
command = 'python -c "import test; test.command()"'
print 'running: %s' % command
output = os.popen(command, 'r', 1)
while True:
line = output.readline()
if line == '':
break
sys.stdout.write(line)
sys.stdout.flush()

if __name__ == '__main__':
main()



The problem is with using the file-like object returned by popen as an
iterator. It will block until the child process is killed, so just
iterate across it manually.

Pete

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


Re: huge amounts of pure Python code broken by Python 2.5?

2007-02-06 Thread Michele Simionato
On Feb 6, 4:40 pm, Steven Bethard <[EMAIL PROTECTED]> wrote:
> Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>
>  > Huge amounts of my pure Python code was broken by Python 2.5.
>
> Interesting. Could you give a few illustrations of this? (I didn't run
> into the same problem at all, so I'm curious.)
>
> Steve

I have seen breakage in Zope, due to the switch from old-style
exceptions to new-style
exceptions.

 Michele Simionato

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


Re: multithreading concept

2007-02-06 Thread Paddy
On Feb 7, 1:53 am, "S.Mohideen" <[EMAIL PROTECTED]>
wrote:
> Hi Folks,
>
> Python is praised about - me too. But at one instance it fails. It fails to
> behave as a true multi-threaded application. That means utilizing all the
> CPUs parallely in the SMP efficiently stays as a dream for a Python
> Programmer.
>
> Discussion threads say its due to GIL - global interpreter lock. But nobody
> has mentioned any alternative to that apart from suggestions like "Code it
> in C" and POSH (http://poshmodule.sf.net). Is there any other way we can
> make Python programs really multithreaded in real sense.
>
> Moin

Actually their are a *lot* more suggestions & discussions to be found.
I myself move towards the "parallel processing is difficult. If you
think it's easy then your either lucky or theorising. Whilst it would
be nice to have threads==native threads for completeness sake, I'm
quit happy to run concurrent communicating processes, as on my
machines the OS helps me to see what's happening to the processes, and
stops processes trampling over shared data".

-Paddy.



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


Re: Steiner Tree

2007-02-06 Thread [EMAIL PROTECTED]
On Feb 7, 4:11 am, [EMAIL PROTECTED] wrote:
> Suresh:
>
> > I could find GeoSteiner  (http://www.diku.dk/geosteiner/) which is
> > implemented as a C program. Anybody know python wrapper for this?
> > Anybody tried this program in a python program?
>
> Once compiled, you may just need to use it with files calling it
> through the console with pipes from Python. If that isn't enough, you
> can probably write a simple enough wrapper using Pyrex.
> If you succed, I may be interested in the result.
>
> Bye,
> bearophile

bearophile,
 Thanks for the response.
 I could compile the program. I am now doing this with pipes only; but
only thing is that, I had to parse the ps output myself, to generate
the line segements, which looks ugly and fails in some cases. Did you
find any other way to directly get the new line segments and steiner
points.

import popen2,re
def steiner(points):
process = popen2.Popen3('/path/rfst |\
 /path/prunefst \
 | /path/bb')

for pt in points:
process.tochild.write('%f %f\n' % (pt[0], pt[1]))
process.tochild.close()

process.wait()

BeginPlot=False
EndPlot=False
lineSegments = []
for line in process.fromchild:
if not EndPlot:
if BeginPlot:
if line == 'EndPlot\n':
EndPlot = True
else:
if not (re.match('^\s.*%', line) \
or re.match('\s*Plot_Terminals', line) \
or re.match('^\s*\(', line)\
):
#print line
a,b,c,d,j = line.split()
if b == 'T':
p1 = points[int(a)]
else:
p1 = (float(a),float(b))
if d == 'T':
p2 = points[int(c)]
else:
p2 = (float(c), float(d))
if not(p1[0] == p2[0] and p1[1] == p2[1]):
lineSegments.append((p1,p2))
else:
if line == 'BeginPlot\n':
BeginPlot=True
return(lineSegments)

I want to write the code with pyrex, but the c program looks
complicated. Maybe with some help in understanding from you, we can
write the wrapper with pyrex.

-
Suresh


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


Re: need help to kill a process

2007-02-06 Thread Gabriel Genellina
En Tue, 06 Feb 2007 22:59:40 -0300, <[EMAIL PROTECTED]> escribió:

> this is my code snip.
> within my python script I have the following commands..
>
> 
>
> import os
> ...
> os.system ("cd /home; ./TestTool &")
> os.system ("cd /usr/; sh run.sh load.xml &")
>
> 
>
> I need to kill these 2 process after a particular job is done.. is
> there any way to get the pids of these process and if so how do i
> invoke the kill command through os.system..
>
> or else is there anyother way to do this...

If you're using Python>=2.4 you could use the subprocess module.

import subprocess
child1 = subprocess.Popen(["./TestTool"], cwd="/home")
child2 = subprocess.Popen(["sh","run.sh","load.xml"], cwd="/usr")

Popen objects have a pid attribute. You don't have to use os.system to  
kill them; use os.kill instead.
You'll notice that I leave out the final &, because I don't know how to  
start a background process without using the shell. But I think you can  
use: bg [pid], afterwards, to get the same result.

-- 
Gabriel Genellina

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


Re: Dictionary/Hash question

2007-02-06 Thread Gabriel Genellina
En Wed, 07 Feb 2007 00:28:31 -0300, Sick Monkey <[EMAIL PROTECTED]>  
escribió:

> qualm after qualm.  Before you read this, my OS is Linux, up2date, and
> minimal RAM (512).
And Python 2.3 or earlier, I presume, else you would have the builtin set  
type.

> The files that my script needs to read in and interpret can contain  
> anywhere
> from 5 million lines to 65 million lines
>
> I have attached 2 versions of code for you to analyze.
> =
> I am having issues with performance.
>
> Instance 1:  dict_compare.py {which is attached}
> Is awesome, in that I have read a file and stored it into a hash table,  
> but
> if you run it, the program decides to stall after writing all of the  
> date.
>  file has actually finished processing within 1 minute, but the script
> continues to run for additional minutes (10 additional minutes actually).
> 

This version reads both files FULLY into memory; maybe the delay time you  
see, is the deallocation of those two huge lists.

> Instance 2: dictNew.py
> Runs great but it is a little slower than Instance 1 (dict_compare.py).   
> BUT
> WHEN IT FINISHES, IT STOPS THE APPLICATION no  additional  
> minutes.
> 

This version processes both files one line at a time, so the memory  
requirements are a lot lower.
I think it's a bit slower because the Set class is implemented in Python;  
set (Python 2.4) is a builtin type now.
You could combine both versions: use the dict approach from version 1, and  
process one line at a time as in version 2.
You can get the mails in both dictionaries like this:

for key in dict1:
   if key in dict2:
 print key

-- 
Gabriel Genellina

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


Re: Graphs, bar charts, etc

2007-02-06 Thread Joshua J. Kugler
Jan Danielsson wrote:

> Hello all,
> 
>I have some data in a postgresql table which I view through a web
> interface (the web interface is written in python -- using mod_python
> under apache 2.2). Now I would like to represent this data as graphs,
> bar charts, etc.
> 
>I know about matplotlib, and it seemed like exactly what I was
> looking for. I tried importing it in my script, but it gave me some
> error about a home directory not being writable. I'm not sure I like the
> idea of it require to be able to write somewhere. Am I using it wrong?
> 
>Is there something else I can use which can produce graphs easily?

We've had good success with matplotlib.

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
Posted via a free Usenet account from http://www.teranews.com

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

Re: Return images with matplotlib?

2007-02-06 Thread Joshua J. Kugler
Jan Danielsson wrote:

> Hello all,
> 
>I have written a program which takes some data from a postgresql
> database, and via mod_python outputs it as tables on a web site. Now I
> would like to present these tables as graphs, which matplotlib can do.
>   But in order to properly display these graphs on the web page, I need
> to return the image data, like so:
> 
> def barchart(req, params):
>some_format = matplotlib.generate_fancy_graph(params)
>png_buf = make_png_buffer(some_format)
>return png_buf
> 
>Is this possible? If so -- how?

If you are returning the buffer (and nothing else) directly to a browser you
can't print a Content-type header that says it's a png file, and the
browser will accept it as a graphic, as long as you call the script from
within an IMG tag.

j

-- 
Joshua Kugler
Lead System Admin -- Senior Programmer
http://www.eeinternet.com
PGP Key: http://pgp.mit.edu/  ID 0xDB26D7CE

-- 
Posted via a free Usenet account from http://www.teranews.com

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

Re: Dictionary/Hash question

2007-02-06 Thread Sick Monkey

qualm after qualm.  Before you read this, my OS is Linux, up2date, and
minimal RAM (512).
On purpose becuase I want this app to run on anything.

I have 2 very good solutions  to this problem (AND I WANT TO THANK 'Gabriel
Genellina' AND 'Don Morrison' with comparing 2 LARGE files).
(LARGE means anywhere from 2MB to 800MB)

The files that my script needs to read in and interpret can contain anywhere
from 5 million lines to 65 million lines

I have attached 2 versions of code for you to analyze.
=
I am having issues with performance.

Instance 1:  dict_compare.py {which is attached}
Is awesome, in that I have read a file and stored it into a hash table, but
if you run it, the program decides to stall after writing all of the date.


Instance 2: dictNew.py
Runs great but it is a little slower than Instance 1 (dict_compare.py).  BUT
WHEN IT FINISHES, IT STOPS THE APPLICATION no  additional minutes.


Can anyone tell me why Intance1 takes so long to finish?  I love both
methods, but I cannot understand the timeframe differences.

HELP!!!

Output Test1:
[EMAIL PROTECTED] hash]# date
Tue Feb  6 21:23:52 EST 2007
[EMAIL PROTECTED] hash]# python dict_compare.py
date
starting list 2
finished storing information in lists.
storing File1 in dictionary.
finished comparing 2 lists.
Stopped processing
done
[EMAIL PROTECTED] hash]# date
Tue Feb  6 21:36:14 EST 2007
Total:   Over 10 minutes

Output Test2:
Tue Feb  6 21:38:55 EST 2007
[EMAIL PROTECTED] hash]# python dictNew.py
date
finished comparing 2 lists.
Stopped processing
done
[EMAIL PROTECTED] hash]# date
Tue Feb  6 21:40:36 EST 2007
Total: Less than 2 minutes

On 2/6/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:


En Tue, 06 Feb 2007 22:18:07 -0300, Sick Monkey <[EMAIL PROTECTED]>
escribió:

> I have never seen this "with open(fname,'r') as finput:"
>
> It is actually throwing an error .  Do I have to import a special
> library to
> use this?
>
>  File "dictNew.py", line 23
> with open(fname,'r') as finput:
> ^
> SyntaxError: invalid syntax

Oh, sorry. You need two things:
- Python 2.5
- include this line at the very beginning of your script: from __future__
import with_statement

If you're using an earlier version, you can write:

   finput = open(fname,'r')
   try
 ...
   finally
 finput.close()

(Or just omit the try/finally and rely on the garbage collector, but it's
not the recommended practice, specially when external resources are
involved, like files).

--
Gabriel Genellina

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



dictNew.py
Description: application/python


dict_compare.py
Description: application/python
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: IOError: [Errno 4] Interrupted system call

2007-02-06 Thread Gabriel Genellina
En Tue, 06 Feb 2007 22:09:00 -0300, Marco <[EMAIL PROTECTED]> escribió:

> in my old script, I usually use os.popen2() to get info from standard
> unix(LinuX) program like ps,ifconfig...
>
> Now, I write a OO-based programme, I still use os.popen2( check
> whether mplayer still working via ps command ), but some things I got
> the following message:
>
> Traceback (most recent call last):
>   File "./mkt.py", line 351, in loop_timeout
> self.process(self.event.get_next())
>   File "./mkt.py", line 361, in process
> self.player.play(command[1])
>   File "./mkt.py", line 107, in play
> if self.is_playing():
>   File "./mkt.py", line 78, in is_playing
> info = rfd.readlines()
> IOError: [Errno 4] Interrupted system call

I don't know if this is a valid behavior or not, perhaps it's a bug inside  
Python signal handling, but anyway, why don't you just catch the exception?

-- 
Gabriel Genellina

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


Re: Threading in Python

2007-02-06 Thread [EMAIL PROTECTED]
On Feb 7, 11:14 am, "S.Mohideen" <[EMAIL PROTECTED]>
wrote:
> Python is praised about - me too. But at one instance it fails. It fails to
> behave as a true multi-threaded application. That means utilizing all the
> CPUs parallely in the SMP efficiently stays as a dream for a Python
> Programmer.
>
> Discussion threads say its due to GIL - global interpreter lock. But nobody
> has mentioned any alternative to that apart from suggestions like "Code it
> in C" and POSH (http://poshmodule.sf.net). Is there any other way we can
> make Python programs really multithreaded in real sense.
>
> Moin

There are two ways. You can use processes, or you can use IronPython.

Cheers,
-T

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


Re: VIDEO: US OIL NAZIS MAKE FUN OF KIDS

2007-02-06 Thread [EMAIL PROTECTED]
   There is more ... Some American soldiers raped Iraqi girls and The
conservatives living in America still says they are not guilty.Bush
must take responsible of these situation.These are massed most of
Americans.

[EMAIL PROTECTED] wrote:
> Pretzel, please include scientific newsgroups like
> sci.math,comp.lang.python,sci.optics,soc.culture.usa,soc.culture.europe
> in your valuable posts
>
> On Feb 6, 4:24 pm, "Möbius Pretzel" <[EMAIL PROTECTED]>
> wrote:
> > Breaking News: US Soldiers Do It Again- Please Watch!
> > By: Seele
> >
> > 06.02.2007
> >
> > US soldiers insulting and taunting little hungry Iraqi kids, asking
> > them :
> >
> > "You fuck donkeys, right ? Donkey. Hey you fuck donkeys right ? "
> >
> > The Iraqi kids of course don t know what the US soldier says, but seem
> > to believe that the soldier is asking them something good - and answer
> > with "yes".
> >
> > US soldier:
> >
> > "Yeah ! Y'fucked a donkey. Are they good, he ? You're a donkey,
> > right ? Yes, Donkey-fucker. Ah Donkey-fucker, alright ! "
> >
> > http://www.liveleak.com/view?i=52d7e3cd11
> >
> > ---
> >
> > Every last US Oil Nazi DESERVES an IED shoved up his ass.

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


Re: Trouble fixing a broken ASCII string - "replace" mode in codec not working.

2007-02-06 Thread Neil Cerutti
On 2007-02-06, Robert Kern <[EMAIL PROTECTED]> wrote:
> John Nagle wrote:
>>   File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch
>>  sitetext = sitetext.encode('ascii','replace')  # force to clean ASCII
>> 
>> UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in
>> position 29151: ordinal not in range(128)
>> 
>> Why is that exception being raised when the codec was told 'replace'?
>
> The .encode('ascii') takes unicode strings to str strings.
> Since you gave it a str string, it first tried to convert it to
> a unicode string using the default codec ('ascii'), just as if
> you were to have done unicode(sitetext).encode('ascii',
> 'replace').
>
> I think you want something like this:
>
>   sitetext = sitetext.decode('ascii', 'replace').encode('ascii', 'replace')

This is the cue for the translate method, which will be much
faster and simpler for cases like this. You can build the
translation table yourself, or use maketrans.

>>> asciitable = string.maketrans(''.join(chr(a) for a in xrange(127, 256)), 
...'?'*127)


You'd only want to do that once. Then to strip off the non-ascii:

sitetext.translate(asciitable)

I used a similar solution in an application I'm working on that
must uses a Latin-1 byte-encoding internally, but displays on
stdout in ascii.

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


Can Parallel Python run on a muti-CPU server ?

2007-02-06 Thread [EMAIL PROTECTED]
Hi all,

I'm interested in Parallel Python and I learned from the website of 
Parallel Python
that it can run on SMP and clusters. But can it run on a our muti-CPU 
server ?
We are running an origin3800 server with 128 CPUs.

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


need help to kill a process

2007-02-06 Thread elrondrules
Hi

Am new to python and need your help!!

this is my code snip.
within my python script I have the following commands..



import os
...
os.system ("cd /home; ./TestTool &")
os.system ("cd /usr/; sh run.sh load.xml &")



I need to kill these 2 process after a particular job is done.. is
there any way to get the pids of these process and if so how do i
invoke the kill command through os.system..

or else is there anyother way to do this...

thanks

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


multithreading concept

2007-02-06 Thread S.Mohideen
Hi Folks,

Python is praised about - me too. But at one instance it fails. It fails to
behave as a true multi-threaded application. That means utilizing all the
CPUs parallely in the SMP efficiently stays as a dream for a Python
Programmer.

Discussion threads say its due to GIL - global interpreter lock. But nobody
has mentioned any alternative to that apart from suggestions like "Code it
in C" and POSH (http://poshmodule.sf.net). Is there any other way we can
make Python programs really multithreaded in real sense.

Moin

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


Re: Dictionary/Hash question

2007-02-06 Thread Gabriel Genellina
En Tue, 06 Feb 2007 22:18:07 -0300, Sick Monkey <[EMAIL PROTECTED]>  
escribió:

> I have never seen this "with open(fname,'r') as finput:"
>
> It is actually throwing an error .  Do I have to import a special  
> library to
> use this?
>
>  File "dictNew.py", line 23
> with open(fname,'r') as finput:
> ^
> SyntaxError: invalid syntax

Oh, sorry. You need two things:
- Python 2.5
- include this line at the very beginning of your script: from __future__  
import with_statement

If you're using an earlier version, you can write:

   finput = open(fname,'r')
   try
 ...
   finally
 finput.close()

(Or just omit the try/finally and rely on the garbage collector, but it's  
not the recommended practice, specially when external resources are  
involved, like files).

-- 
Gabriel Genellina

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


Re: Dictionary/Hash question

2007-02-06 Thread Sick Monkey

I have never seen this "with open(fname,'r') as finput:"

It is actually throwing an error .  Do I have to import a special library to
use this?

File "dictNew.py", line 23
   with open(fname,'r') as finput:
   ^
SyntaxError: invalid syntax
On 2/6/07, Gabriel Genellina <[EMAIL PROTECTED]> wrote:


En Tue, 06 Feb 2007 20:31:17 -0300, Sick Monkey <[EMAIL PROTECTED]>
escribió:

> Even though I am starting to get the hang of Python, I continue to find
> myself finding problems that I cannot solve.
> I have never used dictionaries before and I feel that they really help
> improve efficiency when trying to analyze huge amounts of data (rather
> than
> having nested loops).

You are right, a list is not the right data structure in your case.
But a dictionary is a mapping from keys to values, and you have no values
to store.
In this case one should use a set: like a list, but without ordering, and
no duplicated elements.
Also, it's not necesary to read all lines at once, you can process both
files line by line. And since reading both files appears to be the same
thing, you can make a function:

def mailsfromfile(fname):
   result = set()
   with open(fname,'r') as finput:
 for line in finput:
   mails = some_regular_expression.findall(line)
   if mails:
 result.update(mails)
   return result

mails1 = mailsfromfile(f1name)
mails2 = mailsfromfile(f2name)

for mail in mails1 & mails2: # & = set intersection, mails present on both
files
   # write mail to output file

--
Gabriel Genellina

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

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

IOError: [Errno 4] Interrupted system call

2007-02-06 Thread Marco
Hello,every one, I meet a question:

in my old script, I usually use os.popen2() to get info from standard
unix(LinuX) program like ps,ifconfig...

Now, I write a OO-based programme, I still use os.popen2( check
whether mplayer still working via ps command ), but some things I got
the following message:

Traceback (most recent call last):
  File "./mkt.py", line 351, in loop_timeout
self.process(self.event.get_next())
  File "./mkt.py", line 361, in process
self.player.play(command[1])
  File "./mkt.py", line 107, in play
if self.is_playing():
  File "./mkt.py", line 78, in is_playing
info = rfd.readlines()
IOError: [Errno 4] Interrupted system call

why? Thank you!


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


Re: Dictionary/Hash question

2007-02-06 Thread Gabriel Genellina
En Tue, 06 Feb 2007 20:31:17 -0300, Sick Monkey <[EMAIL PROTECTED]>  
escribió:

> Even though I am starting to get the hang of Python, I continue to find
> myself finding problems that I cannot solve.
> I have never used dictionaries before and I feel that they really help
> improve efficiency when trying to analyze huge amounts of data (rather  
> than
> having nested loops).

You are right, a list is not the right data structure in your case.
But a dictionary is a mapping from keys to values, and you have no values  
to store.
In this case one should use a set: like a list, but without ordering, and  
no duplicated elements.
Also, it's not necesary to read all lines at once, you can process both  
files line by line. And since reading both files appears to be the same  
thing, you can make a function:

def mailsfromfile(fname):
   result = set()
   with open(fname,'r') as finput:
 for line in finput:
   mails = some_regular_expression.findall(line)
   if mails:
 result.update(mails)
   return result

mails1 = mailsfromfile(f1name)
mails2 = mailsfromfile(f2name)

for mail in mails1 & mails2: # & = set intersection, mails present on both  
files
   # write mail to output file

-- 
Gabriel Genellina

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


Re: British school refuses to withdraw book descibing Jews as monkeys and Xtians as pigs

2007-02-06 Thread thermate2
Habshi, please include scientific newsgroups like
sci.math,comp.lang.python,sci.optics,soc.culture.usa,soc.culture.europe
in your valuable posts

On Feb 6, 3:57 pm, [EMAIL PROTECTED] (habshi) wrote:
> The problem is that the verses are from the Quran. The video
> is remarkably clear . Congrats to the bbc. Meanwhile the Muslim lawyer
> who defended Abu Hamza who got seven years jail for incitiment to
> terror got over $1m from the taxpayer for defending him over just
> seven months. His property should be confiscated to pay for it.
> Jeremy Paxman at his best. The Brits will only have themselves
> to blame if tens of thousands of these school kids grow up believing
> this nonsense and turn into Jihadis.
> excerpt bbc.co.uk
> A former teacher has made shocking allegations that the King
> Fahad Academy in west London has been using racist teaching materials
> which describe Jewish people as monkeys and Christians as pigs. He
> alleges that text books used by the Saudi run school ask pupils to
> "name some repugnant characteristics of Jews". The teacher, who is
> claiming unfair dismissal, has submitted the teaching materials as
> part his evidence for an employment tribunal. Newsnight has obtained
> copies of the text books and is investigating the teacher's claims.
>
> Watch it 
> onhttp://news.bbc.co.uk/player/nol/newsid_467/newsid_4679900/467998...
>
> Lesson 14


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


Re: WATER DEAL EXPOSES SECRET IRAQ CONTRACTS

2007-02-06 Thread thermate2
Pretzel, please include scientific newsgroups like
sci.math,comp.lang.python,sci.optics,soc.culture.usa,soc.culture.europe
in your valuable posts

On Feb 6, 4:12 pm, [EMAIL PROTECTED] or www.mantra.com/jai (Dr.
Jai Maharaj) wrote:
> Water Deal Exposes Secret Iraq Contracts
>
> By Katherine Shrader and Allison Hoffman,
> Associated Press Writers
> The Associated Press
> San Francisco Chronicle
> Tuesday, February 6, 2007
>
> Washington, (AP) -- CIA officers operating in northern Iraq
> bought drinking water from a bottling plant there for years
> prior to the 2003 invasion that ousted Saddam Hussein.
>
> That changed soon afterward. A CIA officer handling
> logistics for the Middle East and other regions recommended
> that an American company provide water and other supplies,
> according to former government officials.
>
> The U.S. contractor that benefited from the multimillion-
> dollar deal wasn't just anyone. The company had personal
> ties to the officer, Kyle "Dusty" Foggo, who would soon
> leave his logistics post in Frankfurt, Germany, and move to
> Washington to become the CIA's third-ranking official.
>
> In at least one written communication, a Baghdad CIA
> officer complained about the no-bid contract. According to
> one official, the officer believed the deal was simply
> unnecessary because safe water was available commercially
> but he was ignored.
>
> The water contract, while small on the scale of the
> billions that flowed into Iraq, raises questions about why
> U.S. taxpayer dollars went to well-connected businessmen
> rather than Iraqis who could have benefited from a share of
> postwar reconstruction business. And the case provides a
> window into the murky world of covert government business
> arrangements.
>
> Foggo retired from the CIA last year. He is now at the
> center of a federal investigation, nearing completion, into
> whether he improperly steered contracts to companies
> controlled by his best friend, San Diego defense contractor
> Brent Wilkes.
>
> Federal prosecutors in San Diego are preparing to seek
> indictments against Foggo and Wilkes on charges of honest
> services fraud and conspiracy, two government officials
> familiar with the investigation told The Associated Press
> last week.
>
> Those officials and others spoke on condition that they not
> be identified because the charges have not been finalized
> and because CIA contracting is classified. Justice
> Department and law enforcement officials in San Diego and
> Washington declined to comment.
>
> Honest services fraud is a charge combining mail and wire
> fraud often used in public corruption cases involving
> officials who have engaged in a pattern of improper
> activities, such as accepting gifts, trips or promises of
> future employment from private individuals.
>
> The probe of Foggo and Wilkes stems from a broader federal
> investigation involving at least five federal agencies into
> how associates of former Rep. Randy "Duke" Cunningham
> directed government business to a favored network of
> national security contractors. Cunningham, a San Diego
> Republican elected to eight terms in Congress, is currently
> serving more than eight years in jail for taking at least
> $2.4 million in bribes. Another defense contractor has
> pleaded guilty to paying some of them.
>
> In June 2002, Wilkes created a government contractor called
> Archer Defense Technologies, which was registered to the
> address of his flagship, Wilkes Corp., in Poway, Calif. The
> company also used the name Liberty Defense Technologies. At
> the beginning of 2004, his nephew and apprentice, Joel
> Combs, formed a new company called Archer Logistics, run
> out of a small Virginia office.
>
> Despite the short history of Wilkes' company, Foggo
> recommended that the CIA buy water from it, current and
> former officials said. He was a supervising officer at the
> CIA supply hub in Germany, and the purchasing officer there
> went along.
>
> Foggo didn't tell the purchasing officer about his personal
> ties to Combs or Wilkes, a government official says. With
> CIA officers literally under fire and other large issues to
> deal with, the CIA station didn't put up a fight, former
> officials say.
>
> The issue in the investigation isn't the price but that the
> contract was awarded without competitive bidding and that
> Foggo had an obligation to disclose his personal
> connections, according to these officials.
>
> Foggo's former attorney publicly acknowledged before he
> died last summer that the investigation includes Archer,
> but he said his client had no idea that the company was
> associated with Wilkes. Foggo's current attorney, Mark
> MacDougall, declined to comment, as did Wilkes' attorney,
> Mark Geragos.
>
> CIA spokesman Mark Mansfield declined to comment citing the
> investigation, which includes the spy agency's inspector
> general. "As a rule, we don't comment publicly about which
> firms may or may not have a contractual relations

Re: division by 7 efficiently ???

2007-02-06 Thread John Machin
On Feb 7, 11:05 am, [EMAIL PROTECTED] wrote:
> On Feb 6, 4:54 pm, "John Machin" <[EMAIL PROTECTED]> wrote:
>
> > Recursive? Bzzzt!
>
> I woudl be happy to hear your alternative, which doesn't depend on
> language specific tricks. Thus far, all you have suggested is using an
> alternative form of the division function,

Huh? Thus far (in this post) all I've said is (in effect) that IMHO
mentioning recursion is just cause for termination of job interview.

>  which I would consider to
> be outside the spirit of the question (though I have been wrong many
> times before).
>
> > Might it not be better to halve the interval at each iteration instead
> > of calling a random number function? mid = (lo + hi) >> 1 looks
> > permitted and cheap to me. Also you don't run the risk of it taking a
> > very high number of iterations to get a result.
>
> I had considered this, but to halve, you need to divide by 2. Using
> random, while potentially increasing the number of iterations, removes
> the dependency of language tricks and division.

"Potentially increases the number of iterations"? Sorry, the interview
for marketing manager is across the hall. For example if your N must
fit in 16 bits, you could end up with O(2**16) iterations. This may
not show up in acceptance testing. And each iteration involves calling
a random number function. A binary search has a guaranteed upper limit
of O(16). Let's get this in contect: the traditional "long division"
approach takes 16 iterations!

Shifting to divide by a power of 2 is not a "language trick". In any
case any compiler that deserves to be used will replace division by a
power of 2 with a shift.

>
> > Did you notice the important word *efficiently* in line 1 of the spec?
> > Even after ripping out recursion and random numbers, your proposed
> > solution is still way off the pace.
>
> Again, I look forward to reading your solution.
>

Respectfully, read my other posts in this thread.
The correct answer IMHO is "Semi-decent compilers like gcc will do a
good-enough job of dividing an integer by a constant. Only in
situations like a very high-use library routine where the N is known
to be much smaller than 2**wordsize might it be worthwhile to see if a
bit-bashing approach could generate faster code".

Cheers,
John

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


Re: VIDEO: US OIL NAZIS MAKE FUN OF KIDS

2007-02-06 Thread thermate
Pretzel, please include scientific newsgroups like
sci.math,comp.lang.python,sci.optics,soc.culture.usa,soc.culture.europe
in your valuable posts

On Feb 6, 4:24 pm, "Möbius Pretzel" <[EMAIL PROTECTED]>
wrote:
> Breaking News: US Soldiers Do It Again- Please Watch!
> By: Seele
>
> 06.02.2007
>
> US soldiers insulting and taunting little hungry Iraqi kids, asking
> them :
>
> "You fuck donkeys, right ? Donkey. Hey you fuck donkeys right ? "
>
> The Iraqi kids of course don t know what the US soldier says, but seem
> to believe that the soldier is asking them something good - and answer
> with "yes".
>
> US soldier:
>
> "Yeah ! Y'fucked a donkey. Are they good, he ? You're a donkey,
> right ? Yes, Donkey-fucker. Ah Donkey-fucker, alright ! "
>
> http://www.liveleak.com/view?i=52d7e3cd11
>
> ---
>
> Every last US Oil Nazi DESERVES an IED shoved up his ass.


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


Re: Coordinate Grid Points

2007-02-06 Thread Matimus
[code]
 #classify "Point"
 class Point(object):
 def _init_(self, x, y):  <--- This is your problem
 self.x = x
 self.y = y
[/code]

That should be '__init__'. Two underscores before and after. But,
IMHO, I don't think a class is really necessary unless you are going
to build in compare facilities. You might as well just use a tuple:

[code]
from random import randint
pt = (randint(1,20),randint(1,20))
...
x,y = pt
x = pt[0]
y = pt[1]
[/code]

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


Re: Coordinate Grid Points

2007-02-06 Thread Eric . Gabrielson
On Feb 6, 4:08 pm, "Gabriel Genellina" <[EMAIL PROTECTED]> wrote:
> En Tue, 06 Feb 2007 20:35:43 -0300, <[EMAIL PROTECTED]> escribió:
>
>
>
> > Anyways heres my error:
> > 
> > ***File "C:/Documents and Settings/Eric/Desktop/Python/2d guessing
> > game.py", line 11, in ***
> > ***randp = Point(random.randint(1, 20), random.randint(1,
> > 20))  ***
> > ***TypeError: default __new__ takes no
> > parameters
> > ***
> > class Point(object):
> >def _init_(self, x, y):
> >self.x = x
> >self.y = y
>
> > #generate random coordinate point
> > randp = Point(random.randint(1, 20), random.randint(1, 20))
>
> _init_ should be __init__ (two leading and trailing underscores)
> That special method is used to initialize your newly constructed Point
> instance.
> See section 9.3.2 on the Python 
> tutorial:http://docs.python.org/tut/node11.html#SECTION001132
>
> --
> Gabriel Genellina

WOW thank you so much I feel like a blind idiot *slaps self on
forehead*

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


Threading in Python

2007-02-06 Thread S.Mohideen
Python is praised about - me too. But at one instance it fails. It fails to 
behave as a true multi-threaded application. That means utilizing all the 
CPUs parallely in the SMP efficiently stays as a dream for a Python 
Programmer.

Discussion threads say its due to GIL - global interpreter lock. But nobody 
has mentioned any alternative to that apart from suggestions like "Code it 
in C" and POSH (http://poshmodule.sf.net). Is there any other way we can 
make Python programs really multithreaded in real sense.

Moin 

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


Re: Yanks gone mad :- for the spoooook bAbe -: Murder in space

2007-02-06 Thread thermate
I know if the events could have been controlled, the bushcons would
have tried to suppress the news .

What goes around comes around .

Thanks Lord, our police system is still functioning without too much
corruption and nepotism .

On Feb 6, 4:01 pm, [EMAIL PROTECTED] wrote:
> diapers, wig, knife ... guys i am dying of laughter, someone help
> me ...
>
> Seems like the Neoconish spirit of Bush/Cheney has permeated the whole
> country thru the cell phones and cause the yanks to go mad ...
> including the internet spok gone mad about bAbe
>
> 
>
> http://www.freep.com/apps/pbcs.dll/article?AID=/20070206/NEWS07/70206...
>
> The Astronaut Babe
> February 6, 2007
>
> BEGIN TRANSCRIPT
> RUSH: So we have this astronaut babe Lisa Nowak. She's 43 years old.
> She flew last July on a shuttle mission to the International Space
> Station. She drove all the way from Houston to the Orlando
> International Airport, and she wore diapers. She drove 900 or a
> thousand miles and wore diapers so she wouldn't have to stop at rest
> areas and use the restroom! This is an obsessed woman. She's part of a
> love triangle. She's married; she's got three kids, and then there's
> this astronaut guy in the middle of this, and there's some other woman
> that Lisa Nowak thought was her rival and I just asked at the
> beginning of the show, "Would you like to be the guy in this
> threesome?" I immediately got a chorus of no's (laughing.)
> Understandably so. All right, here's what happened.
>
> "Nowak believed another woman, Colleen Shipman, was romantically
> involved with [Navy Commander William] Oefelein." He was a pilot
> during the space shuttle Discovery's trip to the space station last
> December. Lisa Nowak told the fuzz that her relationship with the guy
> was "'more than a working relationship, but less than a romantic
> relationship.' A NASA spokesman in Houston said that as of Monday,
> Nowak's status with the astronaut corps remained unchanged. When Lisa
> Nowak found out that Colleen Shipman was flying to Orlando from
> Houston, Nowak decided to confront her, according to the arrest
> affidavit. Nowak raced from Houston to Orlando wearing diapers so she
> wouldn't have to stop to urinate." Now, stop and think about that.
> Colleen Shipman is going to fly there; Lisa Nowak is going to drive
> there. She had to race and get there before the flight did, so she had
> to leave long before the flight did. You know, astronauts do wear
> diapers during launch and reentry, so she has experience with diapers.
> You never know what's going to happen.
>
> "She was dressed in a wig and a trench coat. She boarded an airport
> bus that Colleen Shipman took to her car in an airport parking lot.
> Colleen Shipman told the police that she noticed someone following
> her, hurried inside the car, locked the doors, and then Nowak rapped
> on the window, tried to open the car door and asked for a ride." She's
> wigged up here, so the fellow astronaut babe did not recognize her
> right off the bat. "Shipman refused but rolled down the car window a
> few inches when Nowak started crying. Nowak then sprayed a chemical
> like pepper spray or mace into Shipman's car." This is all according
> to the fuzz affidavit! Shipman then, in the midst of having been maced
> or whatever, "drove to the parking lot booth and the police were
> called. During a check of the parking lot, an officer followed Nowak
> and watched her throw away a bag containing the wig and a BB gun. They
> found a steel mallet, a four-inch folding knife, rubber tubing, $600,
> and garbage bags inside a bag that Nowak was carrying when she was
> arrested.
> "Inside Nowak's vehicle, which was parked at a nearby motel,
> authorities uncovered a pepper spray package, an unused BB gun
> cartridge, Latex gloves, and e-mails between Shipman and," the
> astronaut guy. "They also found a letter that indicated how much Mrs.
> Nowak loved the astronaut, an opened package for a Buck knife,
> Shipman's home address, and handwritten directions to the address.
> Police said that Nowak told them she only wanted to scare Shipman into
> talking to her about her relationship with [the astronaut guy] and
> didn't want to harm her physically." Sergeant Barbara Jones, a
> spokesbabe for the Orlando fuzz said, "'If you were just going to talk
> to someone, I don't know what you would need a wig, a trench coat, an
> air cartridge BB gun and pepper spray for. It's just really a very sad
> case.' Now she ends up finding herself on the other side of the law
> with some v

Re: division by 7 efficiently ???

2007-02-06 Thread garrickp
On Feb 6, 4:54 pm, "John Machin" <[EMAIL PROTECTED]> wrote:
> Recursive? Bzzzt!

I woudl be happy to hear your alternative, which doesn't depend on
language specific tricks. Thus far, all you have suggested is using an
alternative form of the division function, which I would consider to
be outside the spirit of the question (though I have been wrong many
times before).

> Might it not be better to halve the interval at each iteration instead
> of calling a random number function? mid = (lo + hi) >> 1 looks
> permitted and cheap to me. Also you don't run the risk of it taking a
> very high number of iterations to get a result.

I had considered this, but to halve, you need to divide by 2. Using
random, while potentially increasing the number of iterations, removes
the dependency of language tricks and division.

> Did you notice the important word *efficiently* in line 1 of the spec?
> Even after ripping out recursion and random numbers, your proposed
> solution is still way off the pace.

Again, I look forward to reading your solution.

Respectfully, G.

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


Re: Coordinate Grid Points

2007-02-06 Thread Gabriel Genellina
En Tue, 06 Feb 2007 20:35:43 -0300, <[EMAIL PROTECTED]> escribió:

> Anyways heres my error:
> 
> ***File "C:/Documents and Settings/Eric/Desktop/Python/2d guessing
> game.py", line 11, in ***
> ***randp = Point(random.randint(1, 20), random.randint(1,
> 20))  ***
> ***TypeError: default __new__ takes no
> parameters
> ***


> class Point(object):
>   def _init_(self, x, y):
>   self.x = x
>   self.y = y
>
> #generate random coordinate point
> randp = Point(random.randint(1, 20), random.randint(1, 20))


_init_ should be __init__ (two leading and trailing underscores)
That special method is used to initialize your newly constructed Point  
instance.
See section 9.3.2 on the Python tutorial:
http://docs.python.org/tut/node11.html#SECTION001132


-- 
Gabriel Genellina

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


Re: Coordinate Grid Points

2007-02-06 Thread greg
[EMAIL PROTECTED] wrote:

> class Point(object):
>   def _init_(self, x, y):

The name of the __init__ method needs *two* underscores
at each end, i.e.

   def __init__(self, x, y):

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


Yanks gone mad :- for the spoooook bAbe -: Murder in space

2007-02-06 Thread thermate
diapers, wig, knife ... guys i am dying of laughter, someone help
me ...

Seems like the Neoconish spirit of Bush/Cheney has permeated the whole
country thru the cell phones and cause the yanks to go mad ...
including the internet spok gone mad about bAbe



http://www.freep.com/apps/pbcs.dll/article?AID=/20070206/NEWS07/70206009/0/BLOG01

The Astronaut Babe
February 6, 2007

BEGIN TRANSCRIPT
RUSH: So we have this astronaut babe Lisa Nowak. She's 43 years old.
She flew last July on a shuttle mission to the International Space
Station. She drove all the way from Houston to the Orlando
International Airport, and she wore diapers. She drove 900 or a
thousand miles and wore diapers so she wouldn't have to stop at rest
areas and use the restroom! This is an obsessed woman. She's part of a
love triangle. She's married; she's got three kids, and then there's
this astronaut guy in the middle of this, and there's some other woman
that Lisa Nowak thought was her rival and I just asked at the
beginning of the show, "Would you like to be the guy in this
threesome?" I immediately got a chorus of no's (laughing.)
Understandably so. All right, here's what happened.

"Nowak believed another woman, Colleen Shipman, was romantically
involved with [Navy Commander William] Oefelein." He was a pilot
during the space shuttle Discovery's trip to the space station last
December. Lisa Nowak told the fuzz that her relationship with the guy
was "'more than a working relationship, but less than a romantic
relationship.' A NASA spokesman in Houston said that as of Monday,
Nowak's status with the astronaut corps remained unchanged. When Lisa
Nowak found out that Colleen Shipman was flying to Orlando from
Houston, Nowak decided to confront her, according to the arrest
affidavit. Nowak raced from Houston to Orlando wearing diapers so she
wouldn't have to stop to urinate." Now, stop and think about that.
Colleen Shipman is going to fly there; Lisa Nowak is going to drive
there. She had to race and get there before the flight did, so she had
to leave long before the flight did. You know, astronauts do wear
diapers during launch and reentry, so she has experience with diapers.
You never know what's going to happen.

"She was dressed in a wig and a trench coat. She boarded an airport
bus that Colleen Shipman took to her car in an airport parking lot.
Colleen Shipman told the police that she noticed someone following
her, hurried inside the car, locked the doors, and then Nowak rapped
on the window, tried to open the car door and asked for a ride." She's
wigged up here, so the fellow astronaut babe did not recognize her
right off the bat. "Shipman refused but rolled down the car window a
few inches when Nowak started crying. Nowak then sprayed a chemical
like pepper spray or mace into Shipman's car." This is all according
to the fuzz affidavit! Shipman then, in the midst of having been maced
or whatever, "drove to the parking lot booth and the police were
called. During a check of the parking lot, an officer followed Nowak
and watched her throw away a bag containing the wig and a BB gun. They
found a steel mallet, a four-inch folding knife, rubber tubing, $600,
and garbage bags inside a bag that Nowak was carrying when she was
arrested.
"Inside Nowak's vehicle, which was parked at a nearby motel,
authorities uncovered a pepper spray package, an unused BB gun
cartridge, Latex gloves, and e-mails between Shipman and," the
astronaut guy. "They also found a letter that indicated how much Mrs.
Nowak loved the astronaut, an opened package for a Buck knife,
Shipman's home address, and handwritten directions to the address.
Police said that Nowak told them she only wanted to scare Shipman into
talking to her about her relationship with [the astronaut guy] and
didn't want to harm her physically." Sergeant Barbara Jones, a
spokesbabe for the Orlando fuzz said, "'If you were just going to talk
to someone, I don't know what you would need a wig, a trench coat, an
air cartridge BB gun and pepper spray for. It's just really a very sad
case.' Now she ends up finding herself on the other side of the law
with some very serious charges." If she's convicted of the attempted
kidnapping, that alone can get a maximum of life in prison. She got an
attorney. Her attorney went up and testified for her. "An additional
charge of attempted first-degree murder has now been brought."

Wow! What would make somebody do this? Have you ever been that nuts
for somebody? Man, there's a lot of stuff that happens out there in
the human race, and you look at it and you say, "I could never do
that, but I could understand somebody who would." This? I don't know
how many people would do this. Obviously, this kind of thing has
happene

Re: division by 7 efficiently ???

2007-02-06 Thread John Machin
On Feb 7, 2:29 am, [EMAIL PROTECTED] wrote:
> On Feb 1, 8:25 pm, "Krypto" <[EMAIL PROTECTED]> wrote:
>
> > The correct answer as told to me by a person is
> > (N>>3) + ((N-7*(N>>3))>>3)
> > The above term always gives division by 7
>
> Does anybody else notice that this breaks the spirit of the problem
> (regardless of it's accuracy)? 'N-7' uses the subtraction operator,
> and is thus an invalid solution for the original question.
>
> Build a recursive function, which uses two arbitrary numbers, say 1
> and 100.

Recursive? Bzzzt!

> Check each, times 7, and make sure that your target number,
> N, is between them. Increase or decrease your arbitrary numbers as
> appropriate. Now pick a random number between those two numbers, and
> check it. Figure out which two the answer is between, and then check a
> random number in that subset

Might it not be better to halve the interval at each iteration instead
of calling a random number function? mid = (lo + hi) >> 1 looks
permitted and cheap to me. Also you don't run the risk of it taking a
very high number of iterations to get a result.

>. Continue this, and you will drill down
> to the correct answer, by using only *, +, >, and <.
>
> I'll bet money that since this was a programming interview, that it
> wasn't a check of your knowledge of obscure formulas, but rather a
> check of your lateral thinking and knowledge of programming.
>
> ~G

Did you notice the important word *efficiently* in line 1 of the spec?
Even after ripping out recursion and random numbers, your proposed
solution is still way off the pace.

Cheers,
John

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


Re: Python does not play well with others

2007-02-06 Thread Paul Rubin
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> It's possible that we could build it all in a startup module and then
> pickle everything we've built into a file that each child would
> unpickle, but I'm a bit leery about that approach.

Yeah, that's not so great.  You could look at POSH.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Coordinate Grid Points

2007-02-06 Thread Eric . Gabrielson
On Feb 5, 6:33 pm, James Stroud <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Feb 5, 3:29 pm, James Stroud <[EMAIL PROTECTED]> wrote:
>
> >>[EMAIL PROTECTED] wrote:
>
> >>>Hello,
> >>>   I am very knew to python and am attempting to write a program
> >>>in python that a friend of mine is having to write in java. I am doing
> >>>this for fun and would like some help as to how i can generate random
> >>>coordinate points (x,y) and compare them with user inputted coordinate
> >>>points. For example how will I be able to access the separate values,
> >>>the x from the x,y position. I think I understand everything except
> >>>1)the random coordinate points 2) the getting the users inputted x and
> >>>y values in one line ("Please guess a coordinate point from (1,1) to
> >>>(20,20): ") as opposed to  ("Please enter an x value:" and "Please
> >>>enter a y value") and finally 3) acessing the x value from the x,y
> >>>coordinate function. the assignment description is located here http://
> >>>www.cs.washington.edu/education/courses/142/07wi/homework/
> >>>homework.html if you would like to see a more in depth discription of
> >>>the game.
>
> >>>Many Thanks,
> >>>Eric
>
> >>For 1: see the random module (e.g. random.randint)
> >>For 2: see the "eval" function and "raw input"
> >>For 2 (without cheating): see the re module. For example:
> >>*
> >> ***map(int, re.compile("\(?(\d+),(\d+)\)?").search(inpt).groups())
> >>*
> >>(Giving you the latter because eval will do this for you anyway.)
>
> >>Also see "raw_input".
>
> >>James
>
> > Thank you very much for your response i will play around with the code
> > when I have some time ( hopefully later tonight) but could you please
> > breakdown what the part that I surrounded with asterisks, I think I
> > recognize it but don't understand it.
>
> > Eric
>
> "re" is the regular expression module for python. "re.compile()"
> compiles the regular expression into a regular expression object with
> certain attributes, one of which is "search". "search" searches a
> string, here "inpt", and this produces a "match" (actually a
> _sre.SRE_Match) object that has, as one of its attributes, a "groups()"
> method that returns matches to the grouped expressions inside the
> regular expression, i.e. expressions surrounded by un-escaped parentheses.
>
> Inside of the quotes is a regular expression string, (that, in general,
> should be preceded immediately by a lowercase r--but is not here because
> it doesn't matter in this case and I forgot to). map() maps a callable
> (here int) to the list of groups returned by groups(). Each group is a
> string matching r"\d+" which is an expression for one or more digits.
> Each group is converted into an integer and map returns a list of
> integers. I escaped the enclosing parentheses and put question marks
> (match zero or one) so that the enclosing parentheses would be optional.
> This makes all of the following evaluate to [20, 20]:
>
>   "20,20"
>   "(20,20"
>   "20,20)"
>   "(20,20)"
>
> Except for typos, the middle two would be quite uncommon for user input,
> but would match the expression. Note also, that I didn't allow for
> whitespace anywhere, which might be expected. Arbitrary whitespace is
> matched by r"\s*".
>
> James

Thank you for your help so far, it has been useful but i haven't quite
gotten time to figure it out. In the mean time i was posting in a
different forum and got given some help (to define a "point" class) I
took that advice and am now getting an error relating to it that i
have no idea how to fix and was wondering if you might be able to give
me a hand.

Anyways heres my error:

***File "C:/Documents and Settings/Eric/Desktop/Python/2d guessing
game.py", line 11, in ***
***randp = Point(random.randint(1, 20), random.randint(1,
20))  ***
***TypeError: default __new__ takes no
parameters
***

and heres my code:


#Import Random Module
import random

#classify "Point"
class Point(object):
def _init_(self, x, y):
self.x = x
self.y = y

#generate random coordinate point
randp = Point(random.randint(1, 20), random.randint(1, 20))

#print randp

#get user input
x = int(raw_input("Enter guessed x value (1-20): "))
y = int(raw_input("Enter guessed y value (1-20): "))

#compare input to randomly generated point
attempts = 0

while True:
userp = Point(x, y)
attempts += 1

 

Dictionary/Hash question

2007-02-06 Thread Sick Monkey

Even though I am starting to get the hang of Python, I continue to find
myself finding problems that I cannot solve.
I have never used dictionaries before and I feel that they really help
improve efficiency when trying to analyze huge amounts of data (rather than
having nested loops).

Basically what I have is 2 different files containing data.  My program will
take the first line in one file and see if it exists in another file.  If it
does find a match, then it will write the data to a file.
---
Right now, the code will open file1 and store all contents in a list.  Then
it will do the same thing to file2.  THN it will loop over list1 and
insert into a Hash table.   I am trying to find out a way to make this code
more efficient.  SO here is what i would rather have.  when i open file1
send directly to the hash table totally bypassing the insertion of the
script..  Is this possible?

def fcompare(f1name, f2name):
   import re
   mailsrch = re.compile(r'[EMAIL PROTECTED],4}')
   f1 = fopen(f1name)
   f2 = fopen(f2name)
   if not f1 or not f2:
   return 0
   a = f1.readlines(); f1.close()
   b = f2.readlines(); f2.close()
   file1List= []
   print "starting list 1"
   for c in a:
  file1List.extend(mailsrch.findall(c))
   print "storing File1 in dictionary."

   d1 = {}
   for item in file1List :
  d1[item] = None
 print "finished storing information in lists."

  print "starting list 2"
  file2List = []
  for d in b:
 file2List.extend(mailsrch.findall(d))

   utp = open("match.txt","w")
   for item in file2List :
  if d1.has_key( item ) :
 utp.write(item +  '\n')

   utp.close()
   #del file1List
   #del file2List
   print "finished comparing 2 lists."
   #return 1
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python does not play well with others

2007-02-06 Thread [EMAIL PROTECTED]
On Feb 6, 4:27 pm, Paul Rubin  wrote:
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> > In our case, the issue is this: we load a ton of info at server
> > restart, from the database.  Some of it gets processed a bit based on
> > configuration files and so forth.  If this were done in my own C
> > server, I'd do all of that and set up the (read-only) runtime data
> > structures prior to forking.  That would mean that:
> > a) The processing time would be lower since you're just doing the pre-
> > processing once; and
> > b) The memory footprint could be lower if large data structures were
> > created prior to fork; they'd be in shared copy-on-write pages.
>
> If you completely control the server, write an apache module that
> dumps this data into a file on startup, then mmap it into your Python app.

The final data after loading is in the form of a bunch of python
objects in a number of complex data structures, so that's not really a
good solution as far as I can tell.  We read in a bunch of data from
the database and build a data layer describing all the various classes
(and some kinds of global configuration data, etc) used by the various
applications in the system.

It's possible that we could build it all in a startup module and then
pickle everything we've built into a file that each child would
unpickle, but I'm a bit leery about that approach.

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


Re: Steiner Tree

2007-02-06 Thread bearophileHUGS
Suresh:
> I could find GeoSteiner  (http://www.diku.dk/geosteiner/) which is
> implemented as a C program. Anybody know python wrapper for this?
> Anybody tried this program in a python program?

Once compiled, you may just need to use it with files calling it
through the console with pipes from Python. If that isn't enough, you
can probably write a simple enough wrapper using Pyrex.
If you succed, I may be interested in the result.

Bye,
bearophile

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


Re: Graphs, bar charts, etc

2007-02-06 Thread dimitri pater

Hi,

check out chartdirector : http://www.advsofteng.com/
it's not free, but very easy to use
right now I am testing it here: http://www.serpia.org/water
a very simple barchart

regards,
Dimitri

On 2/6/07, Jan Danielsson <[EMAIL PROTECTED]> wrote:


Hello all,

   I have some data in a postgresql table which I view through a web
interface (the web interface is written in python -- using mod_python
under apache 2.2). Now I would like to represent this data as graphs,
bar charts, etc.

   I know about matplotlib, and it seemed like exactly what I was
looking for. I tried importing it in my script, but it gave me some
error about a home directory not being writable. I'm not sure I like the
idea of it require to be able to write somewhere. Am I using it wrong?

   Is there something else I can use which can produce graphs easily?

--
Kind regards,
Jan Danielsson
--
http://mail.python.org/mailman/listinfo/python-list





--
---
You can't have everything. Where would you put it? -- Steven Wright
---
please visit www.serpia.org
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Help reading binary data from files

2007-02-06 Thread John Machin
On Feb 7, 9:34 am, "jeff" <[EMAIL PROTECTED]> wrote:
> On Feb 6, 4:01 pm, "jeff" <[EMAIL PROTECTED]> wrote:
>
>
>
> > I am stumped trying to read binary data from simple files.  Here is a
> > code snippet, where I am trying to simply print little-endian encoded
> > data from files in a directory.
>
> > for name in os.listdir(DOWNLOAD_DIR):
> > filename =  s.path.join(DOWNLOAD_DIR, name)
> > if os.path.isfile(filename):
> > f = open(filename, 'rb')
> > while True:
> > ele = unpack(' > print ele
>
> > When the code runs, 0 is always the data printed, but the data files
> > are not all zero.
>
> > Any quick tips?
>
> > thanks
>
> Wow, supreme stupidity on my part.  It turns out that there were a lot
> of zeros at the beginning of the file, and the slowness of the console
> just showed me the zero data during the test time of ~ 10 seconds.

That's a rather severe case of premature emailisation :-)

>  If
> I throw away the zeros, I see my real datasorry for the time waste

Some further suggestions (not mutually exclusive):
1. redirect the console to a file
2. write more per line
3. download a free or shareware gadget that will show you the contents
of a file in hex and char
4. You may want/need to write yourself a better dumper that's tailored
to the type of files that you are loooking at, e.g.

  498: 0031 FONT len = 001e (30)
  502:  b4 00 00 00 08 00 90 01 00 00 00 00 00 a5 07 01  ?~~~?~??
~???
  518:  56 00 65 00 72 00 64 00 61 00 6e 00 61 00
V~e~r~d~a~n~a~
  532: 041e FORMAT len = 001e (30)
  536:  05 00 19 00 00 23 2c 23 23 30 5c 20 22 44 4d 22  ?~?
~~#,##0\ "DM"
  552:  3b 5c 2d 23 2c 23 23 30 5c 20 22 44 4d 22;\-#,##0\
"DM"
  566: 041e FORMAT len = 0023 (35)
  570:  06 00 1e 00 00 23 2c 23 23 30 5c 20 22 44 4d 22  ?~?
~~#,##0\ "DM"
  586:  3b 5b 52 65 64 5d 5c 2d 23 2c 23 23 30 5c 20 22  ;[Red]\-
#,##0\ "
  602:  44 4d 22 DM"

HTH,
John

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


Re: Help reading binary data from files

2007-02-06 Thread John Machin
On Feb 7, 9:01 am, "jeff" <[EMAIL PROTECTED]> wrote:
> I am stumped trying to read binary data from simple files.  Here is a
> code snippet, where I am trying to simply print little-endian encoded
> data from files in a directory.
>
> for name in os.listdir(DOWNLOAD_DIR):
> filename =  s.path.join(DOWNLOAD_DIR, name)
> if os.path.isfile(filename):
> f = open(filename, 'rb')
> while True:
> ele = unpack(' print ele
>
> When the code runs, 0 is always the data printed, but the data files
> are not all zero.
>
> Any quick tips?

Looks to me like it should work -- at least until it hits the end of
the first file. What do you expect to happen at the end of the first
file?? Or did you so snippetise the code so that even if the missing
import statements are added back, it still won't get into the 2nd
file?

I suggest a few more print statements, so that you can see what is
happening.
Try something like this (untested):

 f = open(filename, 'rb')
 print "Opened", filename
 while True:
 buff = f.read(2)
 if not buff: break # EOF
 if len(buff) == 1:
  print repr(buff), ord(buff)
  break
 ele = unpack('http://mail.python.org/mailman/listinfo/python-list


Re: Help reading binary data from files

2007-02-06 Thread jeff
On Feb 6, 4:01 pm, "jeff" <[EMAIL PROTECTED]> wrote:
> I am stumped trying to read binary data from simple files.  Here is a
> code snippet, where I am trying to simply print little-endian encoded
> data from files in a directory.
>
> for name in os.listdir(DOWNLOAD_DIR):
> filename =  s.path.join(DOWNLOAD_DIR, name)
> if os.path.isfile(filename):
> f = open(filename, 'rb')
> while True:
> ele = unpack(' print ele
>
> When the code runs, 0 is always the data printed, but the data files
> are not all zero.
>
> Any quick tips?
>
> thanks

Wow, supreme stupidity on my part.  It turns out that there were a lot
of zeros at the beginning of the file, and the slowness of the console
just showed me the zero data during the test time of ~ 10 seconds.  If
I throw away the zeros, I see my real datasorry for the time waste

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


Re: Help reading binary data from files

2007-02-06 Thread Gabriel Genellina
En Tue, 06 Feb 2007 19:01:20 -0300, jeff <[EMAIL PROTECTED]> escribió:

> I am stumped trying to read binary data from simple files.  Here is a
> code snippet, where I am trying to simply print little-endian encoded
> data from files in a directory.
>
> for name in os.listdir(DOWNLOAD_DIR):
> filename =  s.path.join(DOWNLOAD_DIR, name)
> if os.path.isfile(filename):
> f = open(filename, 'rb')
> while True:
> ele = unpack(' print ele
>
>
> When the code runs, 0 is always the data printed, but the data files
> are not all zero.

Looks fine to me...

-- 
Gabriel Genellina

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


Re: Help reading binary data from files

2007-02-06 Thread Grant Edwards
On 2007-02-06, jeff <[EMAIL PROTECTED]> wrote:
> I am stumped trying to read binary data from simple files.  Here is a
> code snippet, where I am trying to simply print little-endian encoded
> data from files in a directory.
>
> for name in os.listdir(DOWNLOAD_DIR):
> filename =  s.path.join(DOWNLOAD_DIR, name)
> if os.path.isfile(filename):
> f = open(filename, 'rb')
> while True:
> ele = unpack(' print ele
>
>
> When the code runs, 0 is always the data printed, but the data files
> are not all zero.
>
> Any quick tips?

What are the f.read(2) calls returning?

-- 
Grant Edwards   grante Yow!  Hello, GORRY-O!! I'm
  at   a GENIUS from HARVARD!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recursive zipping of Directories in Windows

2007-02-06 Thread Jim
On Feb 6, 2:47 pm, "MRAB" <[EMAIL PROTECTED]> wrote:
> On Feb 6, 1:48 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 4, 12:42 pm, "Jandre" <[EMAIL PROTECTED]> wrote:
>
> > > On Feb 1, 9:39 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
>
> > > > Jandre wrote:
> > > > > Hi
>
> > > > > I am a python novice and I am trying to write a python script (most of
> > > > > the code is borrowed) to Zip a directory containing some other
> > > > > directories and files. The script zips all the files fine but when it
> > > > > tries to zip one of the directories it fails with the following
> > > > > error:
> > > > > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'"
>
> > > > > The script I am using is:
>
> > > > > import zipfile, os
>
> > > > > def toZip( directory, zipFile ):
> > > > > """Sample for storing directory to a ZipFile"""
> > > > > z = zipfile.ZipFile(
> > > > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED
> > > > > )
> > > > > def walker( zip, directory, files, root=directory ):
> > > > > for file in files:
> > > > > file = os.path.join( directory, file )
> > > > > # yes, the +1 is hacky...
> > > > > archiveName = file[len(os.path.commonprefix( (root,
> > > > > file) ))+1:]
> > > > > zip.write( file, archiveName, zipfile.ZIP_DEFLATED )
> > > > > print file
> > > > > os.path.walk( directory, walker, z  )
> > > > > z.close()
> > > > > return zipFile
>
> > > > > if __name__ == "__main__":
> > > > > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' )
>
> > > > > I have tried to set the permissions on the folder, but when I check
> > > > > the directory permissions it is set back to "Read Only"
>
> > > > > Any suggestions?
>
> > > > > Thanks
> > > > > Johan Balt
>
> > > > Couple of quick suggestions that may help:
>
> > > > 1) don't use 'file' as a variable name. It will mask
> > > > the builtin file function.  If it hasn't bitten you before
> > > > it will if you keep doing that.
>
> > > > 2) If you put the target .zip file in the directory you are
> > > > backing what do you expect the program to do when it comes
> > > > to the file you are creating as you walk the directory?  You
> > > > haven't done anything to 'skip' it.
>
> > > > 3) Your commonprefix and +1 appears to result in same
> > > > information that the easier to use os.path.basename()
> > > > would give you.  Double check me on that.
>
> > > > I don't see anything that references C:\\aaa\temp in your
> > > > code.  Does it exist on your hard drive?  If so does it
> > > > maybe contain temp files that are open?  zipfile module
> > > > can't handle open files.  You must use try/except to
> > > > catch these errors.
>
> > > > Hope info helps.
>
> > > > -Larry
>
> > > Thank you Larry.
> > > I've changed the code as epr your advice. The code is now:
>
> > > import zipfile, os
>
> > > def toZip( directory, zipFile ):
> > > """Sample for storing directory to a ZipFile"""
> > > z = zipfile.ZipFile(
> > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED
> > > )
> > > def walker( zip, directory, files, root=directory ):
> > > for f in files:
> > > f = os.path.join( directory, f )
> > > archiveName = os.path.basename(f)
> > > zip.write( f, archiveName, zipfile.ZIP_DEFLATED )
> > > print f
> > > os.path.walk( directory, walker, z  )
> > > z.close()
> > > return zipFile
>
> > > if __name__ == "__main__":
> > > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' )
>
> > > I still get the same 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:\Python24\Scripts\dirZip.py", line 20, in ?
> > > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' )
> > >   File "C:\Python24\Scripts\dirZip.py", line 14, in toZip
> > > os.path.walk( directory, walker, z  )
> > >   File "C:\Python24\lib\ntpath.py", line 329, in walk
> > > func(arg, top, names)
> > >   File "C:\Python24\Scripts\dirZip.py", line 12, in walker
> > > zip.write( f, archiveName, zipfile.ZIP_DEFLATED )
> > >   File "C:\Python24\lib\zipfile.py", line 405, in write
> > > fp = open(filename, "rb")
> > > IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'
>
> > > c:\\aaa\\temp is a directory in the directory I an trying to zip. I
> > > want to use this script to back up my work once a day and would like
> > > to
> > > keep the directory structure as is. I can zip the files in c:\aaa\tem
> > > fine so I guess that there aren't any open files in the directory.
> > > Any more ideas?
>
> > Hi Jandre,
>
> > Your code is treating the directory as a file and trying to open it
> > and read its bytes to zip them. You'll need to differentiate between
> > files and directories.
>
> > You'll need to check out the Zip module to see how it e

Re: Python editor

2007-02-06 Thread Stef Mientki
BBands wrote:
> No, no, no, this is not an invitation to the editor wars.
> 
> I have been using José Cláudio Faria's superb Tinn-R, 
> http://www.sciviews.org/Tinn-R/,
> with the R language, http://www.r-project.org/. This editor allows you
> to send code to the R shell for execution. You can easily send a line,
> the selection, the balance after the cursor or the whole script.
> 
> I have recently decided to move this project to Python instead of R.
> However, I miss the interaction with the shell a la Tinn-R. Do any of
> the Python editors support this feature?
I think PyScripter and SPE both have these features and much more.

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Help reading binary data from files

2007-02-06 Thread jeff
I am stumped trying to read binary data from simple files.  Here is a
code snippet, where I am trying to simply print little-endian encoded
data from files in a directory.

for name in os.listdir(DOWNLOAD_DIR):
filename =  s.path.join(DOWNLOAD_DIR, name)
if os.path.isfile(filename):
f = open(filename, 'rb')
while True:
ele = unpack('http://mail.python.org/mailman/listinfo/python-list


Re: How can I use __setitem__ method of dict object?

2007-02-06 Thread Bruno Desthuilliers
jeremito a écrit :
 > On Feb 6, 2:36 pm, Bruno Desthuilliers
 > <[EMAIL PROTECTED]> wrote:
 >
(snip)

 >>Here's an alternative implementation, so you get the idea.
 >>
 >>class Xs(dict):

oops ! I meant:
  class Xs(object):

of course...

(snip)
> I guess I just
> need more experience.

Possibly - but not only. You may want to have a look at the 
FineManual(tm) for all this kind of "magic", starting with :
http://docs.python.org/ref/specialnames.html
http://docs.python.org/ref/sequence-types.html

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


Re: Running long script in the background

2007-02-06 Thread Gabriel Genellina
En Tue, 06 Feb 2007 16:44:52 -0300, [EMAIL PROTECTED]  
<[EMAIL PROTECTED]> escribió:

> On Feb 6, 2:02 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
>> On 6 Feb 2007 07:37:33 -0800, "[EMAIL PROTECTED]"
>> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>>
>> > Everything works fine until I call the popen function, then it
>> > freezes.  What I want is to print the output in real time, just like
>> > it does when I run it from a shell.
>>
>> And you want /this/ in a web page?
>>
>> I don't think HTTP is designed for that... As I understand it,  
>> it
>> expects to get a complete page back and then the transaction is complete
>> and forgotten (except for the presence of session cookies). To report

If the response does not include a Content-Length header, and has a  
Transfer-Encoding: chunked header, then it is sent in chunks (blocks) and  
the client is able to process it piece by piece.
See the server docs on how to enable and generate a chunked response. On  
Zope 2, by example, it's enough to use response.write().

> Web pages can show output as it's sent.  For testing I created a
> script on the server that untars a 600 meg volume, I can see each file
> name show up in my browser instantly, just like it should.  The other
> script I'm trying to run won't show anything until the entire process
> is complete and it's just a bunch of echo statements in a for loop,
> I'm not sure why they behave differently.

Are you sure the other process is executing? and not buffered? and you're  
reading its output line by line?

-- 
Gabriel Genellina

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


Re: Python does not play well with others

2007-02-06 Thread Paul Rubin
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> In our case, the issue is this: we load a ton of info at server
> restart, from the database.  Some of it gets processed a bit based on
> configuration files and so forth.  If this were done in my own C
> server, I'd do all of that and set up the (read-only) runtime data
> structures prior to forking.  That would mean that:
> a) The processing time would be lower since you're just doing the pre-
> processing once; and
> b) The memory footprint could be lower if large data structures were
> created prior to fork; they'd be in shared copy-on-write pages.

If you completely control the server, write an apache module that
dumps this data into a file on startup, then mmap it into your Python app.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: division by 7 efficiently ???

2007-02-06 Thread MRAB
On Feb 6, 3:29 pm, [EMAIL PROTECTED] wrote:
> On Feb 1, 8:25 pm, "Krypto" <[EMAIL PROTECTED]> wrote:
>
> > The correct answer as told to me by a person is
> > (N>>3) + ((N-7*(N>>3))>>3)
> > The above term always gives division by 7
>
> Does anybody else notice that this breaks the spirit of the problem
> (regardless of it's accuracy)? 'N-7' uses the subtraction operator,
> and is thus an invalid solution for the original question.
>
[snip]
Instead of subtraction you can use complement-and-add: N + ~7 + 1
(that's a tilde '~' not a minus '-').

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


Re: Dlaczego ten destruktor nie dziala [_LONG_]

2007-02-06 Thread Jacol

>> self.__class__.__bases__[0].__del__(self)
>> 

Swoją drogą to nie masz litości pisząc coś takiego ;)
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Dlaczego ten destruktor nie dziala [_LONG_]

2007-02-06 Thread Jacol
Sulsa wrote:

> Mam klase A po ktorej dziedziczy B i jesli w destruktorze klasy B
> wywolam:
> self.__class__.__bases__[0].__del__(self)
> 
> to wszytkos jest ok, i destruktor klasy a jest wywolywany, jesli
> natomiast napisze: A.__del__(self)  to otrzymuje nastepujacy wyjatek:
> Exception exceptions.AttributeError: "'NoneType' object has no
> attribute '__del__'" in  at 0x2b025d04a830>> ignored
> 
> czemu tak sie dzieje?

??

Cześć,
Właściewie to nie rozumiem sensu pytania. :)

Ja zrobiłem tak:

class A:
def __del__(self):
print "Delete A"

class B(A):
def __del__(self):
A.__del__(self)
print "Delete B"

potem sworzyłem instancję: InstanceB=B()

potem uruchomiłem destruktory: del(InstanceB) i moim oczom ukazał się
komunikat:

Delete A
Delete B

1) Czy atrybut A.__del__(self) zosatł zdefiniowany przez Ciebie?? Domyślny
nie jest brany pod uwagę. Sprawdziłem.

class A:
pass
class B(A):
def __del__(self):
A.__del__(self)
print "Cośtam"

potem 

insta=B()
del(insta) daje Exception exceptions.AttributeError: "class A has no
attribute '__del__'" in > ignored

PS.: Python 2.4.4c1
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python does not play well with others

2007-02-06 Thread [EMAIL PROTECTED]
On Feb 5, 5:45 pm, "Graham Dumpleton" <[EMAIL PROTECTED]> wrote:
> On Feb 6, 8:57 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 5, 12:52 pm, John Nagle <[EMAIL PROTECTED]> wrote:
>
> > > [EMAIL PROTECTED] wrote:
> > > > John Nagle wrote:
>
> > > >>Graham Dumpleton wrote:
>
> > > >>>On Feb 4, 1:05 pm, Paul Rubin  wrote:
>
> > > "Paul Boddie" <[EMAIL PROTECTED]> writes:
> > > >> Realistically,mod_pythonis a dead end for large servers,
> > > >>because Python isn't really multi-threaded.  The Global Python
> > > >>Lock means that a multi-core CPU won't help performance.
>
> > > > The GIL doesn't affect seperate processes, and any large server that
> > > > cares about stability is going to be running a pre-forking MPM no
> > > > matter what language they're supporting.
>
> > >Pre-forking doesn't reduce load; it just improves responsiveness.
> > > You still pay for loading all the modules on every request.
>
> > No, you don't.  Each server is persistent and serves many requests--
> > it's not at all like CGI, and it reuses the loaded Python image.
>
> > So if you have, say, an expensive to load Python module, that will
> > only be executed once for each server you start...e.g. if you have
> > Apache configured to accept up to 50 connections, the module will be
> > run at most 50 times; once each of the 50 processes has started up,
> > they stick around until you restart Apache, unless you've configured
> > apache to only serve X requests in one process before restarting it.
> > (The one major feature thatmod_python_is_ missing is the ability to
> > do some setup in the Python module prior to forking.  That would make
> > restarting Apache somewhat nicer).
>
> There would be a few issues with preloading modules before the main
> Apache child process performed the fork.
>
> The first is whether it would be possible for code to be run with
> elevated privileges given that the main Apache process usually is
> started as root. I'm not sure at what point it switches to the special
> user Apache generally runs as and whether in the main process the way
> this switch is done is enough to prevent code getting back root
> privileges in some way, so would need to be looked into.

In our case, the issue is this: we load a ton of info at server
restart, from the database.  Some of it gets processed a bit based on
configuration files and so forth.  If this were done in my own C
server, I'd do all of that and set up the (read-only) runtime data
structures prior to forking.  That would mean that:
a) The processing time would be lower since you're just doing the pre-
processing once; and
b) The memory footprint could be lower if large data structures were
created prior to fork; they'd be in shared copy-on-write pages.

b) isn't really possible in Python as far as I can tell (you're going
to wind up touching the reference counts when you get pointers to
objects in the page, so everything's going to get copied into your
process eventually), but a) would be very nice to have.

> The second issue is that there can be multiple Python interpreters
> ultimately created depending on how URLs are mapped, thus it isn't
> just an issue with loading a module once, you would need to create all
> the interpreters you think might need it and preload it into each. All
> this will blow out the memory size of the main Apache process.

It'll blow out the children, too, though.  Most real-world
implementations I've seen just use one interpreter, so even a solution
that didn't account for this would be very useful in practice.

> There is also much more possibility for code, if it runs up extra
> threads, to interfere with the operation of the Apache parent process.

Yeah, you don't want to run threads in the parent (I'm not sure many
big mission-critical sites use multiple threads anyway, certainly none
of the 3 places I've worked at did).  You don't want to allow
untrusted code.  You have to be careful, and you should treat anything
run there as part of the server configuration.

But it would still be mighty nice.  We're considering migrating to
another platform (still Python-based) because of this issue, but
that's only because we've gotten big enough (in terms of "many big fat
servers sucking up CPU on one machine", not "tons of traffic") that
it's finally an issue.  mod_python is still very nice and frankly if
our startup coding was a little less piggish it might not be an issue
even now--on the other hand, we've gotten a lot of flexibility out of
our approach, and the code base is up to 325,000 lines of python or
so.  We might be able to refactor things to cut down on startup costs,
but in general a way to call startup code only once seems like the
Right Thing(TM).

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


Re: Python editor

2007-02-06 Thread Bruno Desthuilliers
BBands a écrit :
> No, no, no, this is not an invitation to the editor wars.
> 
> I have been using José Cláudio Faria's superb Tinn-R, 
> http://www.sciviews.org/Tinn-R/,
> with the R language, http://www.r-project.org/. This editor allows you
> to send code to the R shell for execution. You can easily send a line,
> the selection, the balance after the cursor or the whole script.
> 
> I have recently decided to move this project to Python instead of R.
> However, I miss the interaction with the shell a la Tinn-R. Do any of
> the Python editors support this feature? I would be especially
> interested in using IPython as the shell.

emacs

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


Re: Calling J from Python

2007-02-06 Thread bearophileHUGS
Gosi:
> There are a number of graphics examples, utilities and demos you can
> use in J and combine it with Python.

Some of those graphic examples are very nice, I have seen a big site
filled with complex fractals, chaotic attractors, etc.
Python Zen seems somewhat opposed to part of the J spirit, that's why
it's not easy to advertise J in this newsgroup. Python is open source,
and it values readability, it belives that it's better to write more
and be more readable/debuggable, than to be able to express many
things with few symbols. APL was an interesting language, powerful
too, and J looks more keyboard-friendly and it's probably better for
other things too. K seems even less readable than J to me. Probably J
has to be compared more to scipy than to Python itself, because they
share some purposes, the vector/matrix processing. If you need to do
lot of array processing the syntax of scipy (with the help of
MatPlotLib too, that's partially copied from MatLab) isn't (may be
not) high-level enough, the system isn't able to simplify things by
itself, etc. So in that situation a more functional language may be
fitter (maybe even F#, but probably there are better languages around
for that purpose, some modern ones coming from ML family).

Bye,
bearophile

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


Re: How can I use __setitem__ method of dict object?

2007-02-06 Thread jeremito
On Feb 6, 2:36 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> jeremito a écrit :
>
>
>
> > On Feb 6, 10:59 am, "[EMAIL PROTECTED]"
> > <[EMAIL PROTECTED]> wrote:
>
> >>On 6 fév, 16:23, "jeremito" <[EMAIL PROTECTED]> wrote:
>
> (snip)
> >>>But I can't even get __setitem__ to run.
>
> >>of course, since your __new__ method returns a dict instance, not a xs
> >>instance...
> >>There are very few cases where you really need to override the __new__
> >>method.
>
> > The reason I create my object with __new__ instead of __init__ is
> > because when I use __init__ when a value is set it calls __setitem__.
> > This is what I want to happen, but not inside of __init__.   Does this
> > make sense?
>
> It would make sens - if you couldn't call dict.__setitem__ directly.
>
>
>
>
>
> > I'm sure there is a better/more pythonic way to do this,
> > but I'm unsure of what it is.  Can someone show me an example of how
> > this should work?
>
> (snip)
> >>>Is this what the __setitem__ method is for?
>
> >>Yes. But note that you you need to manually call the superclass's
> >>overriden method  - unless you
> >>really want to replace it with your own, which is obviously not the
> >>case here...
>
> >>Note that if someone manually changes the values of xG, xF, or xS, the
> >>computed values of xA and/or xT
> >>won't reflect this change. Is that what you want ?
>
> > Eventually (when I figure out how to use __setitem__) I will change
> > what happens when xG, xF, or xS are changed so that it also changes xA
> > and xT.
>
> Which is not the best way to go IMHO. Unless the computation is very
> intensive (which doesn't seem to be the case here) or it's heavily used
> in big loops *and* the perfs are not good enough, it's better to
> recompute on the fly at read time. And if one of the above cases arises,
> then it will be time to use memoization (ie: cache the result of
> computation, invalidating the cache when needed).
>
>
>
> >>Finally, and if I may ask, what is your use-case for subclassing
> >>dict ? You don't need this to implement a dict-like object,
> >>and it might be simpler in your case to write an ordinary class, then
> >>add support for the required subset of the dict interface.
>
> > Eventually I am going to add other features to my class (as I have
> > mentioned) so I can't simply use a dict object.
>
> I already understood this. My question is : why do you want to
> *subclass* dict. In Python, inheritence is only about implementation,
> it's *not* needed for polymorphism to work. So you don't have to
> subclass dict to have an object behaving (more or less, that's up to
> you) like a dict.
>
> Here's an alternative implementation, so you get the idea. Note that it
> behaves mostly like a dict (well, not totally, but since we don't know
> which subset of the dict interface you need...), but also like a
> 'standard' object, so you can use either cs.['xT'] or cs.xT with the
> same result.
>
> class Xs(dict):
>  """
>  Xs is a container object to hold information about cross sections.
>  """
>  _computedkeys = 'xA', 'xT'
>
>  def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
>  self.xS = xS
>  self.xF = xF
>  self.xG = xG
>  self.nu = nu
>
>  # xA and xT as properties (AKA computed attributes)
>  def _get_xA(self):
>  return self.xG + self.xF
>  def _set_xA(self, dummy):
>  raise AttributeError(
>  "%s.xA is read-only" % self.__class__.__name__
>  )
>  xA = property(fset=_set_xA, fget=_get_xA)
>
>  def _get_xT(self):
>  return self.xA + self.xS
>  def _set_xT(self, dummy):
>  raise AttributeError(
>  "%s.xT is read-only" % self.__class__.__name__
>  )
>  xT = property(fset=_set_xT, fget=_get_xT)
>
>  # dict interface support, to be extended if needed
>  def __setitem__(self, key, value):
>  setattr(self, key, value)
>
>  def __getitem__(self, key):
>  return getattr(self, key)
>
>  def keys(self):
>  return self.__dict__.keys() + list(self._computedkeys)
>
>  def values(self):
>  return self.__dict__.values() \
> + [getattr(self, key) for key in self._computedkeys]
>
>  def items(self):
>  return zip(self.keys(), self.values())
>
>  def __iter__(self):
>  for k in self.keys():
>  yield k
>  raise StopIteration
>
>  def __contains__(self, key):
>  return key in self.keys()
>
>  def __repr__(self):
>  return repr(dict(self.items()))

Thanks a lot for your help.  I think what you have written is much
better than what I could have come up with on my own.  I guess I just
need more experience.
Thanks,
Jeremy

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


Re: Python editor

2007-02-06 Thread Jean-Paul Calderone
On 6 Feb 2007 12:51:13 -0800, BBands <[EMAIL PROTECTED]> wrote:
>No, no, no, this is not an invitation to the editor wars.
>
>I have been using José Cláudio Faria's superb Tinn-R, 
>http://www.sciviews.org/Tinn-R/,
>with the R language, http://www.r-project.org/. This editor allows you
>to send code to the R shell for execution. You can easily send a line,
>the selection, the balance after the cursor or the whole script.
>
>I have recently decided to move this project to Python instead of R.
>However, I miss the interaction with the shell a la Tinn-R. Do any of
>the Python editors support this feature? I would be especially
>interested in using IPython as the shell.

Python mode for emacs defines these functions which may be interesting to
you:

python-send-buffer
  Command: Send the current buffer to the inferior Python process.
python-send-command
  Function: Like `python-send-string' but resets `compilation-minor-mode'.
python-send-defun
  Command: Send the current defun (class or method) to the inferior Python 
process.
python-send-receive
  Function: Send STRING to inferior Python (if any) and return result.
python-send-region
  Command: Send the region to the inferior Python process.
python-send-region-and-go
  Command: Send the region to the inferior Python process.
python-send-string
  Command: Evaluate STRING in inferior Python process.

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

Re: Missing member

2007-02-06 Thread Bruno Desthuilliers
Mizipzor a écrit :
> I have some troubles with a member variable that seems to be missing
> in a class. In short, heres what I do; class A is the parent class, B
> inherits from A and C inherits from B (hope I used the right words
> there). Now, I create an instance of C, which calls A's __init__ which
> in turn creates all the member variables. Then I call C.move() (a
> function defined in A), but then, one of the variables seems to have
> become 'NoneType'.
> 
> The code can be found here (Ive taken away unnecessery stuff):
> http://pastebin.com/875394
> 
> The exact error is (which occur on line 15 in the pasted code):
> TypeError: unsupported operand type(s) for *: 'NoneType' and 'float'

Alas, there's a dependency on an unknown class or function vector (which 
I presume lives in the eponym module), so we just can guess that the 
call to vector() at line 8 returned None. IOW, the problem is elsewhere...

> Any comments are welcome. :)

You ask for it, you get it:

import pygame, math
from pygame.locals import *
=> bad style
import tilemap, dataManager
from vector import *
=> idem

class _BaseEntity:

=> class _BaseEntity(object):

 def __init__(self, type, x, y):
 self._direction = vector()
 self.pos = vector(x,y)
 self.stats = dataManager.getEntityStats(type)
 self.hp = self.stats.maxHp  # todo: make all atttributes local

 def move(self):
 """ moves the entity in its direction according to its speed """
 self.pos += (self._direction * self.stats.speed)

 def setDirection(self, point, y = None):
 """ sets the direction to point, and normalises it
 if y is specifed, "point" is expected to be x,
 otherwise, "point" is expected to be a vector class """
 # make a vector
 if not y == None:
=>  if y is not None:
 point = vector(point, y)
 self._direction = point.normalise()


 #def lookAt(self, point, y = None):
 #""" changes the angle so the entity "looks" at the specified 
coords
 #if y is specifed, "point" is expected to be x,
 #otherwise, "point" is expected to be a vector class """
 ## make a vector
 #if not y == None:
 #point = vector(point, y)

=> code duplication, should be factored out

 #vec = vector(point.x - self.posx, point.y - self.posy)
 #vec.normalise()
 #
 #angle = math.degrees(math.asin(vec.y))
 #print angle

 def draw(self, targetSurface):
 """ blits the entire stats.image onto the targetSurface at the 
ent's coords """
 targetSurface.blit(self.stats.image, (self.pos.x,self.pos.y))

class Entity(_BaseEntity):
 def __init__(self, type, x = 0, y = 0):
 _BaseEntity.__init__(self, type, x, y)

=> You don't need to override the __init__ method if it's just to call 
the superclass's __init__ with the same args...

(snip)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Two mappings inverse to each other: f, g = biject()

2007-02-06 Thread bearophileHUGS
Jonathan Fine:
> A google search for biject.py and bijection.py
> produced no hits, so I suspect that this may not
> have been done before.

There are few (good too) implementations around, but they are called
bidict or bidirectional dicts. Sometimes I use this implementation,
with few changes:
http://www.radlogic.com.au/releases/two_way_dict.py

Bye,
bearophile

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


Re: electronics and python

2007-02-06 Thread Stef Mientki
lee wrote:
> Hi guys.Is there any software written using python for
> electronics.i mean any simulation software or something??
> 
There are a few starts,
(I can't find my notes right now, so from my head)
- there's a 68c11 simulator
- there's a spice implementation or at least a good coupling
- the most promising combination is Python+Modelica, some seem to have it workin
- and there's another one, can't remember

as an exercise I tried to build a PIC simulator, works, but it is slow.

cheers,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: electronics and python

2007-02-06 Thread Richard Charts
On Feb 6, 1:38 pm, "lee" <[EMAIL PROTECTED]> wrote:
> Hi guys.Is there any software written using python for
> electronics.i mean any simulation software or something??

There's MyHDL.
http://myhdl.jandecaluwe.com/doku.php

I found it originally in a Linux Journal article some years ago.
http://www.linuxjournal.com/article/7542

Haven't tried it in a while so you'll have to test it yourself.

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


Python editor

2007-02-06 Thread BBands
No, no, no, this is not an invitation to the editor wars.

I have been using José Cláudio Faria's superb Tinn-R, 
http://www.sciviews.org/Tinn-R/,
with the R language, http://www.r-project.org/. This editor allows you
to send code to the R shell for execution. You can easily send a line,
the selection, the balance after the cursor or the whole script.

I have recently decided to move this project to Python instead of R.
However, I miss the interaction with the shell a la Tinn-R. Do any of
the Python editors support this feature? I would be especially
interested in using IPython as the shell.

jab

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


Re: Recursive zipping of Directories in Windows

2007-02-06 Thread MRAB
On Feb 6, 1:48 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> On Feb 4, 12:42 pm, "Jandre" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Feb 1, 9:39 pm, Larry Bates <[EMAIL PROTECTED]> wrote:
>
> > > Jandre wrote:
> > > > Hi
>
> > > > I am a python novice and I am trying to write a python script (most of
> > > > the code is borrowed) to Zip a directory containing some other
> > > > directories and files. The script zips all the files fine but when it
> > > > tries to zip one of the directories it fails with the following
> > > > error:
> > > > "IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'"
>
> > > > The script I am using is:
>
> > > > import zipfile, os
>
> > > > def toZip( directory, zipFile ):
> > > > """Sample for storing directory to a ZipFile"""
> > > > z = zipfile.ZipFile(
> > > > zipFile, 'w', compression=zipfile.ZIP_DEFLATED
> > > > )
> > > > def walker( zip, directory, files, root=directory ):
> > > > for file in files:
> > > > file = os.path.join( directory, file )
> > > > # yes, the +1 is hacky...
> > > > archiveName = file[len(os.path.commonprefix( (root,
> > > > file) ))+1:]
> > > > zip.write( file, archiveName, zipfile.ZIP_DEFLATED )
> > > > print file
> > > > os.path.walk( directory, walker, z  )
> > > > z.close()
> > > > return zipFile
>
> > > > if __name__ == "__main__":
> > > > toZip( 'c:\\aaa', 'c:\\aaa\\test.zip' )
>
> > > > I have tried to set the permissions on the folder, but when I check
> > > > the directory permissions it is set back to "Read Only"
>
> > > > Any suggestions?
>
> > > > Thanks
> > > > Johan Balt
>
> > > Couple of quick suggestions that may help:
>
> > > 1) don't use 'file' as a variable name. It will mask
> > > the builtin file function.  If it hasn't bitten you before
> > > it will if you keep doing that.
>
> > > 2) If you put the target .zip file in the directory you are
> > > backing what do you expect the program to do when it comes
> > > to the file you are creating as you walk the directory?  You
> > > haven't done anything to 'skip' it.
>
> > > 3) Your commonprefix and +1 appears to result in same
> > > information that the easier to use os.path.basename()
> > > would give you.  Double check me on that.
>
> > > I don't see anything that references C:\\aaa\temp in your
> > > code.  Does it exist on your hard drive?  If so does it
> > > maybe contain temp files that are open?  zipfile module
> > > can't handle open files.  You must use try/except to
> > > catch these errors.
>
> > > Hope info helps.
>
> > > -Larry
>
> > Thank you Larry.
> > I've changed the code as epr your advice. The code is now:
>
> > import zipfile, os
>
> > def toZip( directory, zipFile ):
> > """Sample for storing directory to a ZipFile"""
> > z = zipfile.ZipFile(
> > zipFile, 'w', compression=zipfile.ZIP_DEFLATED
> > )
> > def walker( zip, directory, files, root=directory ):
> > for f in files:
> > f = os.path.join( directory, f )
> > archiveName = os.path.basename(f)
> > zip.write( f, archiveName, zipfile.ZIP_DEFLATED )
> > print f
> > os.path.walk( directory, walker, z  )
> > z.close()
> > return zipFile
>
> > if __name__ == "__main__":
> > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' )
>
> > I still get the same 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:\Python24\Scripts\dirZip.py", line 20, in ?
> > toZip( 'c:\\aaa\\', 'c:\\bbb\\test.zip' )
> >   File "C:\Python24\Scripts\dirZip.py", line 14, in toZip
> > os.path.walk( directory, walker, z  )
> >   File "C:\Python24\lib\ntpath.py", line 329, in walk
> > func(arg, top, names)
> >   File "C:\Python24\Scripts\dirZip.py", line 12, in walker
> > zip.write( f, archiveName, zipfile.ZIP_DEFLATED )
> >   File "C:\Python24\lib\zipfile.py", line 405, in write
> > fp = open(filename, "rb")
> > IOError: [Errno 13] Permission denied: 'c:\\aaa\\temp'
>
> > c:\\aaa\\temp is a directory in the directory I an trying to zip. I
> > want to use this script to back up my work once a day and would like
> > to
> > keep the directory structure as is. I can zip the files in c:\aaa\tem
> > fine so I guess that there aren't any open files in the directory.
> > Any more ideas?
>
> Hi Jandre,
>
> Your code is treating the directory as a file and trying to open it
> and read its bytes to zip them. You'll need to differentiate between
> files and directories.
>
> You'll need to check out the Zip module to see how it expects files
> that should be nested within folders. I believe you'll need to set the
> archive name for the nested files to something like \\temp\\file.ext
> etc.
>
In my experience, zip files don't contain nested folders, instead they
contain a 'flat' l

Re: Python cheatsheets

2007-02-06 Thread cyberco
> If you have a good color printer, try 
> PQRChttp://www.limsi.fr/Individu/pointal/python/pqrc/

That is a very usefull document to use besides Richard Gruets quick
ref. The only disadvantage is that it's a PDF document, pity there's
no HTML version.

2B

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


Re: Trouble fixing a broken ASCII string - "replace" mode in codec not working.

2007-02-06 Thread Robert Kern
John Nagle wrote:
> I'm trying to clean up a bad ASCII string, one read from a
> web page that is supposedly in the ASCII character set but has some
> characters above 127.  And I get this:
> 
>   File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch
>  sitetext = sitetext.encode('ascii','replace')  # force to clean ASCII
> 
> UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 29151: 
> ordinal not in range(128)
> 
> Why is that exception being raised when the codec was told 'replace'?

The .encode('ascii') takes unicode strings to str strings. Since you gave it a
str string, it first tried to convert it to a unicode string using the default
codec ('ascii'), just as if you were to have done
unicode(sitetext).encode('ascii', 'replace').

I think you want something like this:

  sitetext = sitetext.decode('ascii', 'replace').encode('ascii', 'replace')

-- 
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: XMLRPC Server

2007-02-06 Thread Brian Quinlan
Fredrik Lundh wrote:
> well, if you're talking pure CGI, you need to start the interpreter, 
> import the required modules, connect to the database, unmarshal the 
> xml-rpc request, talk to the database, marshal the response, and shut 
> down, in less than 30 milliseconds.
> 
> just importing the CGI module (or the database module) can take longer 
> than that...

The original performance specification was "...receive up to 2000 calls 
per minute". I don't believe that means that a call has to be serviced 
in under 30ms (wall-clock time) but total CPU time would have to be 
<30ms in order to not fall behind under a constant 2000 requests/second 
load. So we can probably remove database connection and communication 
time (i.e. IO-bound components). Still, it's a lot tighter than I though 
it would be:

% time python -c "import SimpleXMLRPCServer; import MySQLdb"

real 0m0.144s
user 0m0.046s
sys  0m0.064s

So it's already almost 4x too slow. But I'm running this on Ubuntu, 
running on VMWare on my 1.6GHz Pentium-M laptop. I would assume that a 
beefy server would do a lot better.

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


Re: electronics and python

2007-02-06 Thread Bill Scherer
lee wrote:

>Hi guys.Is there any software written using python for
>electronics.i mean any simulation software or something??
>  
>
Here's 'something': http://home.tiscali.be/be052320/Unum.html

I find it useful for basic electronics math (Ohm's law, filters, etc). 
It keeps track of the units for you and does the right thing when you 
divide and multiply.

You might find this recipie useful in combination with Unum: 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499350

I'm not aware of anything else in the Python world that fits your query. 
Wish I was...

HTH,

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


Trouble fixing a broken ASCII string - "replace" mode in codec not working.

2007-02-06 Thread John Nagle
I'm trying to clean up a bad ASCII string, one read from a
web page that is supposedly in the ASCII character set but has some
characters above 127.  And I get this:

  File "D:\projects\sitetruth\InfoSitePage.py", line 285, in httpfetch
 sitetext = sitetext.encode('ascii','replace')  # force to clean ASCII

UnicodeDecodeError: 'ascii' codec can't decode byte 0x92 in position 29151: 
ordinal not in range(128)

Why is that exception being raised when the codec was told 'replace'?

(And no, just converting it to Unicode with "sitetext = unicode(sitetext)"
won't work either; that correctly raises a Unicode conversion exception.)

[Python 2.4, Win32]

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


Re: Running long script in the background

2007-02-06 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:

> Web pages can show output as it's sent.  For testing I created a
> script on the server that untars a 600 meg volume, I can see each file
> name show up in my browser instantly, just like it should.  The other
> script I'm trying to run won't show anything until the entire process
> is complete and it's just a bunch of echo statements in a for loop,
> I'm not sure why they behave differently.

In a word:  buffering.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   You could have another fate / You could be in another place
-- Anggun
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running long script in the background

2007-02-06 Thread [EMAIL PROTECTED]
On Feb 6, 2:02 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On 6 Feb 2007 07:37:33 -0800, "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>
>
> > Everything works fine until I call the popen function, then it
> > freezes.  What I want is to print the output in real time, just like
> > it does when I run it from a shell.
>
> And you want /this/ in a web page?
>
> I don't think HTTP is designed for that... As I understand it, it
> expects to get a complete page back and then the transaction is complete
> and forgotten (except for the presence of session cookies). To report
> dynamically on a web page tends to either be something like a
> timed-redirect (reload) of the same URL with the cookie, and that is a
> completely separate transaction starting a new CGI (or equivalent)
> process. AJAX techniques may clean up some of this -- by not really
> reloading the whole page, instead updating the DOM based upon data
> transferred.


Web pages can show output as it's sent.  For testing I created a
script on the server that untars a 600 meg volume, I can see each file
name show up in my browser instantly, just like it should.  The other
script I'm trying to run won't show anything until the entire process
is complete and it's just a bunch of echo statements in a for loop,
I'm not sure why they behave differently.



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


Re: Running long script in the background

2007-02-06 Thread Erik Max Francis
[EMAIL PROTECTED] wrote:

> I tried flushing stdout and the same thing happens.  As soon as the
> os.popen(command) line runs it stops there, the next print statement
> never even runs.
> 
> I've also tried using os.spawnv to make the process run in the
> background but then the ssh command never runs.

Based on what you describe, this isn't a good application for a 
single-transaction CGI exchange.  The timeouts are not happening at the 
level of your CGI script, but rather either at the HTTP server itself or 
at the remote client.  In either case, fixing it as a one-transaction, 
one-script solution is not going to be very feasible.

A more sensible way to do it is to have one logical page (which could be 
the same physical page if you want) which accepts job requests, spawns 
them off in the background, and offers a link to a second logical page 
which sees if the job has completed -- showing the results if it has -- 
or refreshes periodically if it hasn't yet.

-- 
Erik Max Francis && [EMAIL PROTECTED] && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 20 N 121 53 W && AIM, Y!M erikmaxfrancis
   You could have another fate / You could be in another place
-- Anggun
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How can I use __setitem__ method of dict object?

2007-02-06 Thread Bruno Desthuilliers
jeremito a écrit :
> On Feb 6, 10:59 am, "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> wrote:
> 
>>On 6 fév, 16:23, "jeremito" <[EMAIL PROTECTED]> wrote:
>>
(snip)
>>>But I can't even get __setitem__ to run.
>>
>>of course, since your __new__ method returns a dict instance, not a xs
>>instance...
>>There are very few cases where you really need to override the __new__
>>method.
> 
> 
> The reason I create my object with __new__ instead of __init__ is
> because when I use __init__ when a value is set it calls __setitem__.
> This is what I want to happen, but not inside of __init__.   Does this
> make sense? 

It would make sens - if you couldn't call dict.__setitem__ directly.

> I'm sure there is a better/more pythonic way to do this,
> but I'm unsure of what it is.  Can someone show me an example of how
> this should work?
> 
> 
(snip)
>>>Is this what the __setitem__ method is for?
>>
>>Yes. But note that you you need to manually call the superclass's
>>overriden method  - unless you
>>really want to replace it with your own, which is obviously not the
>>case here...
>>
>>Note that if someone manually changes the values of xG, xF, or xS, the
>>computed values of xA and/or xT
>>won't reflect this change. Is that what you want ?
>>
> 
> 
> Eventually (when I figure out how to use __setitem__) I will change
> what happens when xG, xF, or xS are changed so that it also changes xA
> and xT.

Which is not the best way to go IMHO. Unless the computation is very 
intensive (which doesn't seem to be the case here) or it's heavily used 
in big loops *and* the perfs are not good enough, it's better to 
recompute on the fly at read time. And if one of the above cases arises, 
then it will be time to use memoization (ie: cache the result of 
computation, invalidating the cache when needed).

> 
>>Finally, and if I may ask, what is your use-case for subclassing
>>dict ? You don't need this to implement a dict-like object,
>>and it might be simpler in your case to write an ordinary class, then
>>add support for the required subset of the dict interface.
> 
> 
> Eventually I am going to add other features to my class (as I have
> mentioned) so I can't simply use a dict object.

I already understood this. My question is : why do you want to 
*subclass* dict. In Python, inheritence is only about implementation, 
it's *not* needed for polymorphism to work. So you don't have to 
subclass dict to have an object behaving (more or less, that's up to 
you) like a dict.

Here's an alternative implementation, so you get the idea. Note that it 
behaves mostly like a dict (well, not totally, but since we don't know 
which subset of the dict interface you need...), but also like a 
'standard' object, so you can use either cs.['xT'] or cs.xT with the 
same result.

class Xs(dict):
 """
 Xs is a container object to hold information about cross sections.
 """
 _computedkeys = 'xA', 'xT'

 def __init__(self, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
 self.xS = xS
 self.xF = xF
 self.xG = xG
 self.nu = nu

 # xA and xT as properties (AKA computed attributes)
 def _get_xA(self):
 return self.xG + self.xF
 def _set_xA(self, dummy):
 raise AttributeError(
 "%s.xA is read-only" % self.__class__.__name__
 )
 xA = property(fset=_set_xA, fget=_get_xA)

 def _get_xT(self):
 return self.xA + self.xS
 def _set_xT(self, dummy):
 raise AttributeError(
 "%s.xT is read-only" % self.__class__.__name__
 )
 xT = property(fset=_set_xT, fget=_get_xT)

 # dict interface support, to be extended if needed
 def __setitem__(self, key, value):
 setattr(self, key, value)

 def __getitem__(self, key):
 return getattr(self, key)

 def keys(self):
 return self.__dict__.keys() + list(self._computedkeys)

 def values(self):
 return self.__dict__.values() \
+ [getattr(self, key) for key in self._computedkeys]

 def items(self):
 return zip(self.keys(), self.values())

 def __iter__(self):
 for k in self.keys():
 yield k
 raise StopIteration

 def __contains__(self, key):
 return key in self.keys()

 def __repr__(self):
 return repr(dict(self.items()))



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


Re: huge amounts of pure Python code broken by Python 2.5?

2007-02-06 Thread Jean-Paul Calderone
On Tue, 06 Feb 2007 08:40:40 -0700, Steven Bethard <[EMAIL PROTECTED]> wrote:
>Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> > Huge amounts of my pure Python code was broken by Python 2.5.
>
>Interesting. Could you give a few illustrations of this? (I didn't run
>into the same problem at all, so I'm curious.)
>

There are about half a dozen examples linked from here: 

  http://twistedmatrix.com/trac/ticket/1867

Check out the closed ticket linked from there or the changesets for more
detail.

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


Re: XMLRPC Server

2007-02-06 Thread Fredrik Lundh
Brian Quinlan wrote:

> Actually, you might not have to. 2000 calls/minute isn't that big, 
> assuming you have a decent server.

well, if you're talking pure CGI, you need to start the interpreter, 
import the required modules, connect to the database, unmarshal the 
xml-rpc request, talk to the database, marshal the response, and shut 
down, in less than 30 milliseconds.

just importing the CGI module (or the database module) can take longer 
than that...



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


Re: How can I access data from MS Access?

2007-02-06 Thread BartlebyScrivener
On Feb 5, 4:52 am, "Andy Dingley" <[EMAIL PROTECTED]> wrote:
> On 3 Feb, 15:43, [EMAIL PROTECTED] wrote:
>
> > How to access data from MS Access?
>
> First of all check that the DSN is working and connects to the
> back end MDB. This might not be Python's problem.
>
> Secondly check whatever errors you're being returned.

Yes, and then move onto something like this:

http://www.freelance-developer.com/howto_odbcpy

rd

 "Give a man a fire and keep him warm for a day. Light a man on fire
  and he will be warm for rest of his life."

  --Terry Pratchett


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


Re: Repr or Str ?

2007-02-06 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 "Johny" <[EMAIL PROTECTED]> wrote:

> Where and when is good/nescessary to use `repr`  instead of `str` ?
> Can you please explain the differences

You expect repr to include information that you might call
`meta-data' or `type' -- object class and so forth.  To the
extent that this is of any interest, it's more or less equally
of interest with all objects.

If you go to the trouble to support str separately, it's a data
conversion and of course should render only the data.  An application
should be able to use str() to force data to string type (that's
what I mean by conversion.)  If the object can't sensibly be
converted to string type, then normally __str__ is omitted, and
defaults to __repr__.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with multiple key sort

2007-02-06 Thread ian . brady1
Paul already answered it.  Tnx Paul. My data is in a file and now I
have to take care to strip \t and \n from it.

Thanks

> I'm not a guru. Maybe that's why I don't understand which "sql-like
> sort-by on multiple keys" would produce output that lacks some of the
> input but has additional items. ;)
>
> In other words: why don't you show your concrete program and the input
> and output data to use. Is the data a list of tuples or lists or what?
>
> Cheers,
> Jussi


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


Re: Help with multiple key sort

2007-02-06 Thread Jussi Salmela
[EMAIL PROTECTED] kirjoitti:
> gurus:
> 
> I want to implement a sql-like sort-by on multiple keys.  I've seen
> many examples of just two keys.
> 
> I have a list like this
> 
> 1 one 2
> 1 one 1
> 1 two 1
> 1 one 0
> 1 xx   0
> 
> result should be like this
> 
> 1 four 2
> 1 one 0
> 1 one 1
> 1 one 2
> 1 xx   0
> 
> It moves right while keeping sorted order to the left.  This is the
> new stable sort in 2.5.
> 
> I'm not sure what I'm doing wrong.  please help.
> 
> Thanks
> 

I'm not a guru. Maybe that's why I don't understand which "sql-like 
sort-by on multiple keys" would produce output that lacks some of the 
input but has additional items. ;)

In other words: why don't you show your concrete program and the input 
and output data to use. Is the data a list of tuples or lists or what?

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


Re: How can I access data from MS Access?

2007-02-06 Thread Andy Dingley
On 5 Feb, 19:40, "Sells, Fred" <[EMAIL PROTECTED]> wrote:

> Years ago we used to get our FORTRAN card decks back from the DP center
> with a piece of scrap paper saysing "She No Work".  top that.

I used to use a cross-compiler (targetting some obscure single-chip
hardware) that had just a single error message

"Diddley-squat somewhere near here"

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


Re: How to prevent from race conditions to share data between many process and thread in python

2007-02-06 Thread Gabriel Genellina
En Tue, 06 Feb 2007 08:49:51 -0300, Diez B. Roggisch <[EMAIL PROTECTED]>  
escribió:

> mars wrote:
>
>> On 2月6日, 下午6时14分, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
>>> mars wrote:
>>> > I use TurboGears to do some web service. TurboGears use cherrypy.  
>>> When
>>> > web browser access this site, the cherrypy will call my python
>>> > program. So my program looks like a lib. When web browser access the
>>> > site, the http server will fock a process or gerenate a thread. I  
>>> need
>>> > share some data or operate some files. How can I prevent from race
>>> > conditions. Is there any way can I lock this.
>>> > Thank you in advance!
>>>
>>> There are the Lock and RLock objects available in the module threading.
>>
>> Can this also lock mutil-process?
>
> No.

You have to use the syncronization tools provided by your OS in that case;  
maybe using a locked file (fcntl).

-- 
Gabriel Genellina

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

Re: Help with multiple key sort

2007-02-06 Thread Paul Rubin
[EMAIL PROTECTED] writes:
> It moves right while keeping sorted order to the left.  This is the
> new stable sort in 2.5.

>>> b
['1 one 2', '1 one 1', '1 two 1', '1 one 0', '1 xx   0']
>>> sorted(b,key=lambda x: x.split())
['1 one 0', '1 one 1', '1 one 2', '1 two 1', '1 xx   0']
-- 
http://mail.python.org/mailman/listinfo/python-list


electronics and python

2007-02-06 Thread lee
Hi guys.Is there any software written using python for
electronics.i mean any simulation software or something??

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


Help with multiple key sort

2007-02-06 Thread ian . brady1
gurus:

I want to implement a sql-like sort-by on multiple keys.  I've seen
many examples of just two keys.

I have a list like this

1 one 2
1 one 1
1 two 1
1 one 0
1 xx   0

result should be like this

1 four 2
1 one 0
1 one 1
1 one 2
1 xx   0

It moves right while keeping sorted order to the left.  This is the
new stable sort in 2.5.

I'm not sure what I'm doing wrong.  please help.

Thanks

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


Re: huge amounts of pure Python code broken by Python 2.5?

2007-02-06 Thread skip

John> MySQLdb isn't fully supported for Python 2.5 yet, and there's no
John> tested Windows executable available, although there's an untested
John> version from a World of Warcraft guild available.

As Andy Dustman has pointed out a number of times, he doesn't do Windows.
Someone in the MySQLdb community who does use Windows is going to have to
fill that void.

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


Re: Module problem

2007-02-06 Thread Boris Ozegovic
Matimus wrote:

> Do you have more than one version of Python installed? Is
> win32clipboard installed for both versions? It could be that the

Yup, that was the problem.  Thanx!

-- 
"A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa
silovana"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling J from Python

2007-02-06 Thread Bruno Desthuilliers
Gosi a écrit :
> On Feb 6, 3:04 am, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote:
> 
>>On Feb 5, 8:48 am, "Gosi" <[EMAIL PROTECTED]> wrote:
>>
>>
>>>It is quite easy to call J from Python
>>
>>>http://groups.google.com/group/J-Programming/browse_thread/thread/5e8...
>>
>>There are a couple of issue that should be adressed.  Am I going to
>>jail if I write a program and then redistribute all the files required
>>to run the program I write??
> 
> 
> J is free for anyone to download and use.

But not to inspect or modify. This is "free" as in "free beer", not as 
in "free speech".

> 
>>The second is how do I use the j stuff
>>without learning all that much about j.
> 
> 
> Just like Python then how much time you spend is uo to you.
 >
> If you want to be good at it you may have to spend some time.
> 
> You may also be just a casual user and dip into it now and again.

This is easy with Python, which emphasis readability. I doubt one can 
say the same about j.
-- 
http://mail.python.org/mailman/listinfo/python-list


Testing a website with HTTPS login and cookies

2007-02-06 Thread Dwyer, Mike # ATLANTA
Did you ever get a response to your posting on "Testing a website with
HTTPS login and cookies"? The reason I ask is that I need to do a
similar thing, and am not being very successful getting pointers or
sample code.

Any response appreciated.

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

Re: huge amounts of pure Python code broken by Python 2.5?

2007-02-06 Thread John Nagle
Steven Bethard wrote:
> Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>  > Huge amounts of my pure Python code was broken by Python 2.5.
> 
> Interesting. Could you give a few illustrations of this? (I didn't run 
> into the same problem at all, so I'm curious.)
> 
> Steve

   I'd like to know, too.  I have the same code running in 2.4 and 2.5,
and I've had the following problems:

1.  Bug [ 1651995 ] sgmllib _convert_ref UnicodeDecodeError exception,
new in 2.5
(a patch to sgmllib._convert_ref appears to have broken something)
(This might be the switch from Latin-1 to ascii as default, now that
I think about it.)

2.  MySQLdb isn't fully supported for Python 2.5 yet, and there's no tested
Windows executable available, although there's an untested version from
a World of Warcraft guild available.

3.  M2Crypto has versioning issues between Python, SWIG, gcc, and OpenSSL,
and getting everything to play together can be difficult.  This is
a packaging issue; major Linux distros aren't shipping a compatible set of
components.

But my own pure Python code is working fine in both version of Python,
and on both Windows and Linux.

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


Re: Module problem

2007-02-06 Thread Matimus
On Feb 6, 9:29 am, Boris Ozegovic <[EMAIL PROTECTED]>
wrote:
> Hi
>
> I am writing some simple script, and when I start my script from command
> line (python Imenik.py), everything works perfectly.  If I double clik the
> same script in my desktop I get the following error:
>
> "No module name import win32clipboard"
>
> --
> "A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa
> silovana"

Do you have more than one version of Python installed? Is
win32clipboard installed for both versions? It could be that the
python in your PATH variable, used when calling from the command line,
is different from the association in the registry. To see the
association in the registry use: "reg query HKEY_CLASSES_ROOT
\Python.File\shell\open\command" on the command line.

Matt

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


Re: when will python 2.5 take in mainstream?

2007-02-06 Thread Chris Mellon
On 6 Feb 2007 08:46:29 -0800, Ben Sizer <[EMAIL PROTECTED]> wrote:
> On Feb 6, 3:35 pm, [EMAIL PROTECTED] (Aahz) wrote:
> > Ben Sizer <[EMAIL PROTECTED]> wrote:
> >
> > >It would be great if someone could invest some time in trying to fix
> > >this problem. I don't think I know of any other languages that require
> > >recompilation of libraries for every minor version increase.
> >
> > How do you define "minor version increase"?  If you look at the
> > progression from 2.0 through 2.5, it's pretty clear that each version
> > doesn't particularly fit "minor version increase" even though each one
> > only increments by 0.1.
>
> I can't say I agree with that. In terms of naming, it's a minor
> release because the 'major' release number has stayed at 2. In terms
> of time, it's a minor release because it's only happening about once
> every 18 months or so - a short period in computer language terms. In
> terms of semantics, I'd argue they are minor releases because
> generally the changes are just minor additions rather than large
> revisions; I don't see much in the way of significant language
> alterations for 2.5 apart from arguably 'unified try/except/finally',
> nor in 2.4. I don't count addition of new types or modules as 'major'.
> The language itself is fairly stable; it's just the way that it links
> to extensions which is pretty fragile.
>
> --
> Ben Sizer
>

You're claiming that it's a minor increase because you didn't see
anything that "justifies" a major release. Well, the ABI changed, so
there you go.

It doesn't really matter what you call it - the Python releases are
numbered according to their own rules, and if you disagree you can
call 2.5 a major release all you want. Or you can call it a minor
release and accept that the ABI changes between minor releases. But
making up your own release rules and arguing from those is pretty much
a non-starter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python cheatsheets

2007-02-06 Thread Laurent Pointal
Bart Ogryczak wrote:

> On Jan 7, 10:03 pm, gonzlobo <[EMAIL PROTECTED]> wrote:
>> Curious if anyone has a python cheatsheet* published? I'm looking for
>> something  that summarizes all commands/functions/attributes. Having
>> these printed on a 8" x 11" double-sided laminated paper is pretty
>> cool.
>>
>> * cheatsheet probably isn't the right word, but you get the idea. :)
> 
> http://www.onlamp.com/python/excerpt/PythonPocketRef/


If you have a good color printer, try PQRC
http://www.limsi.fr/Individu/pointal/python/pqrc/


But... it use more than a double-sided 8" x 11"...


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


Module problem

2007-02-06 Thread Boris Ozegovic
Hi

I am writing some simple script, and when I start my script from command
line (python Imenik.py), everything works perfectly.  If I double clik the
same script in my desktop I get the following error:

"No module name import win32clipboard"

-- 
"A mi smo stranci u vlastitoj zemlji zbog ljudskog sljama, lipa nasa
silovana"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: huge amounts of pure Python code broken by Python 2.5?

2007-02-06 Thread Gabriel Genellina
"John Roth" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]
> On Feb 6, 8:40 am, Steven Bethard <[EMAIL PROTECTED]> wrote:
>> Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>>
>>  > Huge amounts of my pure Python code was broken by Python 2.5.
>>
>> Interesting. Could you give a few illustrations of this? (I didn't run
>> into the same problem at all, so I'm curious.)
>>
>
> At a guess, the most likely thing to break code in job lots in 2.5 was
> the change in default coding from latin-1 (or whatever the
> installation has the default set to) to ascii.

And that has given a warning since 2.3...

-- 
Gabriel Genellina 


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


Re: How can I use __setitem__ method of dict object?

2007-02-06 Thread Gabriel Genellina
"jeremito" <[EMAIL PROTECTED]> escribió en el mensaje 
news:[EMAIL PROTECTED]

> Please excuse me if this is obvious to others, but I can't figure it
> out.  I am subclassing dict, but want to prevent direct changing of
> some key/value pairs.  For this I thought I should override the
> __setitem__ method as such:
>if key == 'xT':
>raise AttributeError("""Can't change xT.  Please change,
> xF, xS, or xG""")

Why using a dictionary? I'd use a simple class with properties:

py> class Xs(object): # class names should be Uppercase
... def __init__(self,  xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
... self.xS = xS
... self.xF = xF
... self.nu = nu
... self.xG = xG
... xA = property(fget=lambda self: self.xG + self.xF)
... xT = property(fget=lambda self: self.xA + self.xS)
...
py> xs = Xs(1.0, 0.95, 0.80, 0.70)
py> print xs.xG
0.8
py> print xs.xA
1.75
py> print xs.xT
2.75
py> xs.xG = 0.5
py> print xs.xA
1.45
py> print xs.xT
2.45
py> xs.xA = 1.5
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: can't set attribute
py> xs.xT = 1.2
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: can't set attribute
py>

-- 
Gabriel Genellina 


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


Re: huge amounts of pure Python code broken by Python 2.5?

2007-02-06 Thread John Roth
On Feb 6, 8:40 am, Steven Bethard <[EMAIL PROTECTED]> wrote:
> Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>
>  > Huge amounts of my pure Python code was broken by Python 2.5.
>
> Interesting. Could you give a few illustrations of this? (I didn't run
> into the same problem at all, so I'm curious.)
>
> Steve


At a guess, the most likely thing to break code in job lots in 2.5 was
the change in default coding from latin-1 (or whatever the
installation has the default set to) to ascii.

This would have a tendency to break most modules that depended on the
default source coding. Fortunately, the fix is (not quite trivially)
easy - just scan the library and put the right coding comment in the
front.

John Roth

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


Re: when will python 2.5 take in mainstream?

2007-02-06 Thread Ben Sizer
On Feb 6, 3:35 pm, [EMAIL PROTECTED] (Aahz) wrote:
> Ben Sizer <[EMAIL PROTECTED]> wrote:
>
> >It would be great if someone could invest some time in trying to fix
> >this problem. I don't think I know of any other languages that require
> >recompilation of libraries for every minor version increase.
>
> How do you define "minor version increase"?  If you look at the
> progression from 2.0 through 2.5, it's pretty clear that each version
> doesn't particularly fit "minor version increase" even though each one
> only increments by 0.1.

I can't say I agree with that. In terms of naming, it's a minor
release because the 'major' release number has stayed at 2. In terms
of time, it's a minor release because it's only happening about once
every 18 months or so - a short period in computer language terms. In
terms of semantics, I'd argue they are minor releases because
generally the changes are just minor additions rather than large
revisions; I don't see much in the way of significant language
alterations for 2.5 apart from arguably 'unified try/except/finally',
nor in 2.4. I don't count addition of new types or modules as 'major'.
The language itself is fairly stable; it's just the way that it links
to extensions which is pretty fragile.

--
Ben Sizer

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


Re: How can I use __setitem__ method of dict object?

2007-02-06 Thread jeremito
On Feb 6, 10:59 am, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On 6 fév, 16:23, "jeremito" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Please excuse me if this is obvious to others, but I can't figure it
> > out.  I am subclassing dict, but want to prevent direct changing of
> > some key/value pairs.  For this I thought I should override the
> > __setitem__ method as such:
>
> > class xs(dict):
> > """
> > XS is a container object to hold information about cross sections.
> > """
>
> > def __new__(cls, xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
> > """
> > """
> > x = {}
> > x['xS'] = xS
> > x['xF'] = xF
> > x['nu'] = nu
> > x['xG'] = xG
> > x['xA'] = x['xG'] + x['xF']
> > x['xT'] = x['xA'] + x['xS']
>
> > return x
>
> replace this with:
> def __init__(self,  xS=1.0, xF=1.0, xG=1.0, nu=1.0, debug=0):
>dict.__init__(
>self,
>xS=xS,
>xF=xF,
>xG=xG,
>   nu=nu,
>   xA=xG + xF,
>   xT=xG + xF + xS
>  )
>
> > def __setitem__(self, key, value):
> > """
> > I have overridden this method to prevent setting xT or xA
> > outside the
> > class.
> > """
> > print "I am in __setitem__"
> > if key == 'xT':
> > raise AttributeError(
>
>   "Can't change xT.  Please change, xF, xS, or xG"
>)
>dict.__setitem__(self, key, value)
>
> > But I can't even get __setitem__ to run.
>
> of course, since your __new__ method returns a dict instance, not a xs
> instance...
> There are very few cases where you really need to override the __new__
> method.

The reason I create my object with __new__ instead of __init__ is
because when I use __init__ when a value is set it calls __setitem__.
This is what I want to happen, but not inside of __init__.  Does this
make sense?  I'm sure there is a better/more pythonic way to do this,
but I'm unsure of what it is.  Can someone show me an example of how
this should work?


>
> > Example:
> > Python 2.5 (r25:51918, Sep 19 2006, 08:49:13)
> > [GCC 4.0.1 (Apple Computer, Inc. build 5341)] on darwin
> > Type "help", "copyright", "credits" or "license" for more information.>>> 
> > import xs
> > >>> cs = xs.xs()
> > >>> cs
>
> > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT': 3.0}>>> 
> > cs['xT'] = 3.1415
> > >>> cs
>
> > {'xA': 2.0, 'xF': 1.0, 'xG': 1.0, 'xS': 1.0, 'nu': 1.0, 'xT':
> > 3.14150002}
>
> > Is this what the __setitem__ method is for?
>
> Yes. But note that you you need to manually call the superclass's
> overriden method  - unless you
> really want to replace it with your own, which is obviously not the
> case here...
>
> Note that if someone manually changes the values of xG, xF, or xS, the
> computed values of xA and/or xT
> won't reflect this change. Is that what you want ?
>

Eventually (when I figure out how to use __setitem__) I will change
what happens when xG, xF, or xS are changed so that it also changes xA
and xT.

> Finally, and if I may ask, what is your use-case for subclassing
> dict ? You don't need this to implement a dict-like object,
> and it might be simpler in your case to write an ordinary class, then
> add support for the required subset of the dict interface.

Eventually I am going to add other features to my class (as I have
mentioned) so I can't simply use a dict object.

>
> My 2 cents...

Thanks again,
Jeremy

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


  1   2   >