write html-headers (utf-8)

2005-05-30 Thread db
Hello all,

I hope this is the correct newsgroup for this question.

Does anybody know how I can write a html-header with python(cgi)? 
The problem is, I have a few html templates in which I have a header e.g:

http://www.w3.org/TR/html4/strict.dtd";>




In this template I write a few Mysql variables. 
Those variable often have german characters. This characters (Gösing in
stead of Gösing). The german characters in the html template are shown
correctly.

If I change the character encoding with the browser to utf-8, all the 
characters are shown correctly. 
As you can see, I put in the header of the html template that the encoding
is UTF-8, the browser still shows windows ISO-8859-15. Can I write the
header with python so the browser uses the utf-8 encoding?

My hosting providor uses fedora core 2, Python 2.2.3, MySQLdb. Mysql 3.23.58

I googled for hours, but I can't find the answer. I hope ypu can help me.

Thanks in advance.

Arjen

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


Re: prime number

2005-05-30 Thread Brian van den Broek
lostinpython said unto the world upon 2005-05-30 02:50:
> It is a homework assignment from a book but not for a class.  I'm
> trying to teach my self some basic programming before I have to take it
> in college.  If I show enough understanding of the subject, my advisor
> will let me forgo Intro. to Programming and go into Intro. to C++.
> What civil engineers need with all this programming is beyond me.  We
> have to learn another language to program our CADD software, which I
> find much easier than this.  But needless to say, I'm stumped on this
> problem.  I keep ending up in a never ending loop.
> 
> Shanna

Hi Shanna,

Since you are just beginning, I'd like to recommend the tutor list 
. It is not that 
newcomers are not welcome here. But the folks who populate the tutor 
list are particularly good at answering neophytes' questions at the 
level.

Since you've got some code together, even though it isn't doing what 
you want, you've already got a decent start for getting help. Post the 
question and the code to the tutor list and I'd not be surprised if 
you will soon be well on your way to solving your problem.

Best,

Brian vdB
Who owes much of what he knows about Python to the tutor list.

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


where can i find pylibpcap module for win32?

2005-05-30 Thread jerky
thanks for your any imformation.


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


Re: write html-headers (utf-8)

2005-05-30 Thread "Martin v. Löwis"
db wrote:
> In this template I write a few Mysql variables. 
> Those variable often have german characters. This characters (Gösing in
> stead of Gösing). The german characters in the html template are shown
> correctly.

The problem is then with these variables: apparently, the Mysql
variables are encoded in iso-8859-15, and you need to recode them
to UTF-8 first before putting them into the template.

var = var.decode("iso-8859-15").encode("utf-8")

> As you can see, I put in the header of the html template that the encoding
> is UTF-8, the browser still shows windows ISO-8859-15. Can I write the
> header with python so the browser uses the utf-8 encoding?

The problem is not the header, but the body. The browser sees your claim
that the page is UTF-8, but doesn't believe it. This is because it tries
to interpret the page as UTF-8, and then finds invalid byte sequences
(your latin-9 characters), and then knows that the page *can't* be
UTF-8. It then guesses that the page must be latin-something. That guess
is wrong, of course, also, because some characters in the page are
utf-8, and others latin-9. This is invalid HTML.

Regards,
Martin

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


Re: Tkinter slowes down

2005-05-30 Thread Eric Brunel
On Sat, 28 May 2005 18:21:46 +0200, pavel.kosina <[EMAIL PROTECTED]> wrote:

> Fredrik Lundh napsal(a):
>> when you add an item to the canvas, it's part of the canvas
>> until you remove it.  if performance drops, it's usually because
>> you keep adding new items without removing the old ones.
>>
>> try adding a w.delete(ALL) call before you "repaint".

I noticed once that if this actually deletes all canvas items, it does not 
delete the bindings on them: every binding put on a canvas item registers a 
Python callable at tcl level, but does not associate it with the item. So 
deleting the item keeps the binding even if it cannot be called anymore. If you 
have many items with several bindings, this can cause the memory usage to grow 
up and slow down the canvas.

> In the meantime I found that widget.destroy() works well, too (before
> "repainting").

This was the only solution I found using "regular" Tkinter widgets when there 
are bindings on canvas items. I tried to find another solution by modifying 
Tkinter.py, but the problem is much harder than it seems, since many things 
happen at tcl level. However, I didn't investigate the WCK.

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in 
'U(17zX(%,5.zmz5(17;8(%,5.Z65\\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattribute__ and __getattr__

2005-05-30 Thread Gigi
Terry Reedy wrote:
> "Gigi" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>Hi,
>>In the Python documentation regarding __getattribute__ (more attribute
>>access for new style classes) it is mentioned that if __getattribute__
>>is defined __getattr__ will never be called (unless called explicitely).
>>Here is the exact citation:
> 
> 
> Discrepancy reported in
> 
> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1204734&group_id=5470
> 
> Guido declared behavior right and doc wrong and in need of correction.
> 
> Terry J. Reedy
> 
> 
> 

Thanks for your reply. It definitely clears the issue. I'm writing an 
article to Dr. Dobbs about the Python object model and I wouldn't want 
to be inaccurate. I fill a little like Leibnitz :-) . It's a curious 
coincidence that two separate people notice the same documentation issue 
that lingere for such a long time in such a short time span.

Thanks, Gigi


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


Re: write to the same file from multiple processes at the same time?

2005-05-30 Thread gabor
Jp Calderone wrote:
> To briefly re-summarize, when you 
> want to acquire a lock, attempt to create a directory with a well-known 
> name.  When you are done with it, delete the directory.  This works 
> across all platforms and filesystems likely to be encountered by a 
> Python program.

thanks...

but the problem now is that the cgi will have to wait for that directory 
  to be gone, when he is invoked.. and i do not want to code that :)
i'm too lazy..

so basically i want the code to TRY to write to the file, and WAIT if it 
  is opened for write right now...

something like a mutex-synchronized block of the code...

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


Re: write to the same file from multiple processes at the same time?

2005-05-30 Thread gabor
jean-marc wrote:
> Sorry, why is the temp file solution 'stupid'?, (not
> aesthetic-pythonistic???) -  it looks OK: simple and direct, and
> certainly less 'heavy' than any db stuff (even embedded)
> 
> And  collating in a 'official log file' can be done periodically by
> another process, on a time-scale that is 'useful' if not
> instantaneous...
> 
> Just trying to understand here...
> 

actually this is what i implemented after asking the question, and works 
fine :)

i just thought that maybe there is a solution where i don't have to deal 
  with 4000 files in the temp folder :)

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


Design problem, call function from HTML?

2005-05-30 Thread bart
This is the python way i have.

imgref = 'image.py'
out.write(''
  % (imgref)


in ASP.NET u can do something like this



//allready loaded data
data

image(){
  return data.img
}

Is there any remote possibility u can pulloff the same in python? Now
i have to process my data to display page and do it again to generate
my image (execute same code twice).

One solution would be to save the image to harddisk and then load it.
But rather keep it clean as return value.
-- 
http://mail.python.org/mailman/listinfo/python-list


[OT] SQL-records and OOP

2005-05-30 Thread egbert
Each row of an sql table may be the data_part_in_spe  
of some class_instance.
I try to think about, and am looking for, the do's and don'ts 
and caveat's and the right way of thinking about this transformation.
For me it is new territory.

For instance, my sql-query produces much more rows than I am 
interested in eventually. So I have to narrow this collection.

I can inspect the data while it is still a list of rows,
and make instances of only the rows I really need.
Or I may create an aggregate of full-blown instances derived
from all the selected rows.

I suppose Google has lots to offer, but I must be looking 
in the wrong direction.

egbert
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Re: Design problem, call function from HTML?

2005-05-30 Thread deelan
bart wrote:
(...)
> Is there any remote possibility u can pulloff the same in python? Now
> i have to process my data to display page and do it again to generate
> my image (execute same code twice).
> 
> One solution would be to save the image to harddisk and then load it.
> But rather keep it clean as return value.

something like Cheetah might help here:

 >>> from Cheetah.Template import Template
 >>> t = ''

 >>> data = {}
 >>> data['img'] = 'foo.jpg'
 >>> def image(): return data['img']
...
 >>> T = Template(source=t, searchList=[{'image':image}])
 >>> T


...or you can access "img" directly in the template:

 >>> t = ''
 >>> data = {}
 >>> data['img'] = 'foo.jpg'
 >>> T = Template(source=t, searchList=[{'image':data}])
 >>> T


say that "data" changes, you don't have to compile the template
again, just issue a render command again:

 >>> data['img'] = 'BAZ.jpg'
 >>> T



see:




-- 
@prefix foaf:  .
<#me> a foaf:Person ; foaf:nick "deelan" ;
foaf:weblog  .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter slowes down

2005-05-30 Thread Fredrik Lundh
Eric Brunel wrote:

>> In the meantime I found that widget.destroy() works well, too (before
>> "repainting").
>
> This was the only solution I found using "regular" Tkinter widgets when
> there are bindings on canvas items. I tried to find another solution by
> modifying Tkinter.py, but the problem is much harder than it seems,
> since many things happen at tcl level.

for pure Tkinter, I recommend using bind classes to implement "controllers"
on the canvas level, using appropriate find functions to locate the individual
items, and dispatching via "trackers".  see

http://online.effbot.org/2004_09_01_archive.htm#wck-track

for some background (I guess it's time to write that "later article" I mention
in that article.  if you cannot wait, feel free to steal the controller code 
from
the WCK).

 



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


Re: regexp for sequence of quoted strings

2005-05-30 Thread Magnus Lycka
gry@ll.mit.edu wrote:
> I have a string like:
>  {'the','dog\'s','bite'}
> or maybe:
>  {'the'}
> or sometimes:
>  {}
...
> I want to end up with a python array of strings like:
> 
> ['the', "dog's", 'bite']

Assuming that you trust the input, you could always use eval,
but since it seems fairly easy to solve anyway, that might
not be the best (at least not safest) solution.

 >>> strings = [r'''{'the','dog\'s','bite'}''', '''{'the'}''', '''{}''']
 >>> for s in strings:
... print eval('['+s[1:-1]+']')
...
['the', "dog's", 'bite']
['the']
[]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: where can i find pylibpcap module for win32?

2005-05-30 Thread ionel
i've compiled a pcapy
http://lenoi.3x.ro/
works fine ( using it :) )

On 5/30/05, jerky <[EMAIL PROTECTED]> wrote:
> thanks for your any imformation.
> 
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 


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


plotting with Python

2005-05-30 Thread Rolf Wester
Hi,

I have a Python console application that is intended to be used 
interactively and I have to add plotting capabilities (multiple XY plots 
and if possible 2D-surface plots). I'm loocking for a reasonably fast 
plotting library (not GPL'ed, needs not be for free) that can be used 
under Windows. An alternative would also be a standalone application 
that can be controlled via TCP/IP from my Python application. I tried 
matplotlib but this is not fast enough (especially under Windows). I 
considered PyQwt but this is GPL'ed. So I would be very appreciative for 
any help.

With kind regards

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


Re: 2D vector graphics Problem

2005-05-30 Thread Fredrik Lundh
Scott David Daniels wrote:

> Your equation for y uses the new x, not the old x.  Be more free with
> names.  Here's one way to write it:
>
> class ...
> def rotate(self, angle):
> '''Rotate point angle radians around relPoint'''
> x, y = self.coords
> xRel, yRel = self.relPoint
> sin, cos = math.sin(angle), math.cos(angle)
> newx = x * cos - y * sin - xRel * cos + yRel * sin + xRel
> newy = x * sin + y * cos - xRel * sin - yRel * cos + yRel
> self.coords = newx, newy

and here's another one:

http://online.effbot.org/2004_09_01_archive.htm#tkinter-complex

 



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


Re: Get number of lines in file

2005-05-30 Thread Magnus Lycka
[EMAIL PROTECTED] wrote:
> Thanks!  I was trying len(cpn_version) and that didn't work.

What's your problem? You get a value that's one more than
you expected? You should use splitlines() instead of split('\n'),
or easier, use readlines() instead of read(). Of course, with
a modern python you can just iterate over the file, but note
the difference between split and splitlines when the last line
is complete and ends with a newline character:

 >>> a = """dgdgsdfg
... sdfgsdfgsdfg
... sdfgsdfgsdfg
... sdfgsdfgsdfg
... """
 >>> a
'dgdgsdfg\nsdfgsdfgsdfg\nsdfgsdfgsdfg\nsdfgsdfgsdfg\n'
 >>> a.split('\n')
['dgdgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg', '']
 >>> a.splitlines()
['dgdgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg']
 >>>

If you're allergic to splitlines ;) you could do...

 >>> a.rstrip().split('\n')
['dgdgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg', 'sdfgsdfgsdfg']

...but it depends how you want to view files that end with
several linefeeds in a row (or other whitespace for that
matter).

 >>> a = dfgdfg
... dfgdfg
...
... dgfdfg
...
...
...
... """
 >>> a.split('\n')
['"dfgdfg', 'dfgdfg', '', 'dgfdfg', '', '', '', '']
 >>> a.splitlines()
['"dfgdfg', 'dfgdfg', '', 'dgfdfg', '', '', '']
 >>> a.rstrip().split('\n')
['"dfgdfg', 'dfgdfg', '', 'dgfdfg']

In other words, the right solution depends on what behaviour
you want for such cases (if they might exist with your files).

Experimenting like this with the interpreter is a very
convenient way to get a grip on things in Python, and one of
the reasons that Python debugging is usually quicker than
debugging in other languages.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Determine if windows drive letter is hard drive or optical from python?

2005-05-30 Thread Magnus Lycka
Wolfgang Strobl wrote:
> ... for drive in string.letters[len(string.letters)/2:]:

Or better...
..for drive in string.ascii_uppercase:

string.letters differ with locale, but Windows drives are always
only A-Z (right?) and just iterating over upper case (or lower)
seems more clear than to iterate over half of the sum of both...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write html-headers (utf-8)

2005-05-30 Thread Benjamin Niemann
db wrote:

> Hello all,
> 
> I hope this is the correct newsgroup for this question.
> 
> Does anybody know how I can write a html-header with python(cgi)?
> The problem is, I have a few html templates in which I have a header e.g:
> 
>  "http://www.w3.org/TR/html4/strict.dtd";> 
> 
> 
> 
> In this template I write a few Mysql variables.
> Those variable often have german characters. This characters (Gösing in
> stead of Gösing). The german characters in the html template are shown
> correctly.
> 
> If I change the character encoding with the browser to utf-8, all the
> characters are shown correctly. As you can see, I put in the header of the
> html template that the encoding is UTF-8, the browser still shows windows
> ISO-8859-15. Can I write the header with python so the browser uses the
> utf-8 encoding?
> 
> My hosting providor uses fedora core 2, Python 2.2.3, MySQLdb. Mysql
> 3.23.58
> 
> I googled for hours, but I can't find the answer. I hope ypu can help me.
Does your browser send a Content-Type HTTP header (don't confuse this with
the HTML  part)? If it does and it specifies a charset, this will
override your . Often iso-8859-1 is the default charset
for the Content-Type header.

-- 
Benjamin Niemann
Email: pink at odahoda dot de
WWW: http://www.odahoda.de/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie learning OOP

2005-05-30 Thread LenS
Thanks for the reply.  I will be looking over you code.  I'm trying to
learn OOP.  It just hasn't sunk in yet;-\

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


Re: Newbie learning OOP

2005-05-30 Thread LenS
You are correct, the code so far is just a simple problem to learn OOP.
 Oh by the way I don't work for Dept. of Homeland Security just
remember "drop those fingernail clipers and step away from those
shoes:-)

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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Arthur
On Thu, 26 May 2005 16:24:39 -0500, Mike Meyer <[EMAIL PROTECTED]> wrote:

>"Elliot Temple" <[EMAIL PROTECTED]> writes:
>
>> Hi I have two questions.  Could someone explain to me why Python is
>> case sensitive? I find that annoying.
>
>Because it comes from a language background of case sensitive
>languages (C, shell, etc.). But read what the BDFL has to say about
>it: http://mail.python.org/pipermail/python-list/2001-July/054788.html >

As Guido's statement on his position on case sensitivity/insensitivity
cited above was in response to a post/provocation of mine, its gives
me, and I shall indulge myself in, an opportunity to partake of a
favorite pasttime - venting,

I will make it short:

It gauls the hell out of me that that the Python community mass "head"
was in such a strange place at that moment that I had to take the pose
of maniacal extremist to have a sensible converstaion.

Or that's the history I am writing, in any case.

Art 

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


Re: write html-headers (utf-8)

2005-05-30 Thread Kent Johnson
db wrote:
> Hello all,
> 
> I hope this is the correct newsgroup for this question.
> 
> Does anybody know how I can write a html-header with python(cgi)? 
> The problem is, I have a few html templates in which I have a header e.g:
> 
>  "http://www.w3.org/TR/html4/strict.dtd";>
> 
> 
> 

If you are using CGI you can set the Content-Type header directly. Before you 
output your HTML do
print "Content-Type: text/html; charset=UTF-8"
print  # blank line, end of headers

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


Re: how to convert string to list or tuple

2005-05-30 Thread Duncan Booth
Steven Bethard wrote:

>> Have you tried giving it the string '__import__("os").system("rm -rf
>> *")'? [Don't try that at home children!]
> 
> But you can try it at home if you set __builtins__ to something other 
> than the default:
> 
> py> eval("""__import__("os").system('echo "hello"')""", 
> dict(__builtins__=None))
> Traceback (most recent call last):
>File "", line 1, in ?
>File "", line 0, in ?
> NameError: name '__import__' is not defined
> 
> If you're just doing work with constants, the lack of access to any 
> builtins is ok:
> 
> py> eval("(1,2,3)", dict(__builtins__=None))
> (1, 2, 3)
> 
> I know there have been security holes in this technique before, but I 
> looked at the archives, and all the old ones I found have been
> patched. 
>   (Or at least I wasn't able to reproduce them.)
> 
I guess you are referring to things like this not working when you use eval 
with an empty __builtins__:

eval('''[ cls for cls in {}.__class__.__bases__[0].__subclasses__()
   if '_Printer' in `cls` 
][0]._Printer__setup.func_globals['__builtins__']['__import__']''',
  dict(__builtins__=None))

That gets blocked because func_globals is a 'restricted attribute', so I 
can't get directly at __import__ that way, but what I can do is to access 
any new style class you have defined and call any of its methods with 
whatever arguments I wish.

Even with the big holes patched you are going to find it pretty hard to 
write a safe program that uses eval on untrusted strings. The only way to 
go is to filter the AST (or possibly the bytecode).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: write to the same file from multiple processes at the same time?

2005-05-30 Thread gabor
gabor wrote:
> Jp Calderone wrote:
> 
>> To briefly re-summarize, when you want to acquire a lock, attempt to 
>> create a directory with a well-known name.  When you are done with it, 
>> delete the directory.  This works across all platforms and filesystems 
>> likely to be encountered by a Python program.
> 
> 
> thanks...
> 
> but the problem now is that the cgi will have to wait for that directory 
>  to be gone, when he is invoked.. and i do not want to code that :)
> i'm too lazy..
> 
> so basically i want the code to TRY to write to the file, and WAIT if it 
>  is opened for write right now...
> 
> something like a mutex-synchronized block of the code...
> 
ok, i ended up with the following code:

def syncLog(filename,text):
 f = os.open(filename,os.O_WRONLY | os.O_APPEND)
 fcntl.flock(f,fcntl.LOCK_EX)
 os.write(f,text)
 #FIXME: what about releasing the lock?
 os.close(f)

it seems to do what i need ( the flock() call waits until he can get 
access).. i just don't know if i have to unlock() the file before i 
close it..


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


Newbie learning OOP 2nd ?

2005-05-30 Thread LenS
I have coded this little program which is a small little tip calculator
program.  I am in the process of trying to convert this program to use
OOP.  Would appreciate others more experienced in OOP code in how they
might do it.

Would be happy to forward all profits from the sale of the program;-))

#Program name:  tipcalc05.py
#This program calculates the dollar amount of a tip on a resturant bill
import datetime
import string

def calc_full_bill():
'''This function is used to get information regarding the bill and
   calculate the tax, tip, and total amount of the bill'''
global billamt
global tippct
global taxpct
global totalbill

billamt = raw_input("Please enter the bill amount: ")
tippct = raw_input("Please enter the percent tip: ")
location = getanswers("Are you in Chicago, ")

if location == True:
taxpct = 7.25
else:
taxpct = 6.75

tipamt = calcpct(billamt, tippct)

taxamt = calcpct(billamt, taxpct)

totalbill = float(billamt) + taxamt + tipamt

print "Tip = %.2f Tax = %.2f Total = %.2f" % (tipamt, taxamt,
totalbill)

def group_bill_process():
grpbill = open("grpbill.txt", 'a+')
group = raw_input("Please give the name of the group? ")

for line in grpbill:
print string.split(line, sep=',')

who_paid = raw_input("Who paid the bill? ")
grpdate = datetime.datetime.now()
group_detail = group + ',' + who_paid + ',' + str(totalbill) + ','
+ str(grpdate) + '\n'
grpbill.write(group_detail)

def calc_bill_by_guest():
'''This function allows you to get multiple amounts for any number
   of individuals and calculate each individuals share of the tip
   tax and bill amount'''

guest = []
netbill = float(billamt)
while True:
gf_name = raw_input("Enter girlfriends name: ")
gf_amt = raw_input("Enter girlfriends amount: ")
guest.append((gf_name, gf_amt))
netbill = netbill - float(gf_amt)
print "Amount remaining %.2f" % netbill
anymore = getanswers("Anymore girlfriends, ")
if anymore == False:
break

#these print lines are here just to show the tuples within a list

print guest
print

for (g, a) in (guest):
gf_tax = calcpct(a, taxpct)
gf_tip = calcpct(a, tippct)
gf_total = float(a) + gf_tax + gf_tip
print "%s Tip = %.2f Tax = %.2f Total = %.2f" % (g, gf_tip,
gf_tax, gf_total)
print

def getanswers(question):
'''This function allows you to print some question looking for
   and answer of the form Yes or No'''
answer = raw_input(question + "'Yes' or 'No': ")
print
if answer in ["Yes", "yes", "Y", "y", "OK", "ok", "Ok", "yeh",
"Yeh"]:
return(True)
else:
return(False)

def calcpct(bill, pct):
'''This function calculates the amount base off of some
   given percentage'''
amt = float(bill) * float(pct) / 100
return(amt)

while True:
calc_full_bill()

group_bill = getanswers("Is this a group bill? ")
if group_bill == True:
group_bill_process()
else:
split_the_bill = getanswers("Do you want to equally spilt the
Bill, ")
if split_the_bill == True:
no_of_dinners = raw_input("Split between how many people?
")
print "Each person owes %.2f" % (float(totalbill) /
float(no_of_dinners))
else:
calc_bill_by_guest()

runagain = getanswers("Do you want to run again, ")

if runagain == False:
break


PS If there is somewhere else I should be posting this kind of thing
let me know otherwise thanks everyone for your help.

Len Sumnler

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


Re: prime number

2005-05-30 Thread phil

> What civil engineers need with all this programming is beyond me. 


One of my best friends and expartner and top civil-structural
engineers in the country (he built Dallas Reunion Arena and many
other complex structures) was an ace programmer in many languages.

He was not willing to just accept the results of canned packages,
he wanted to know where the answers came from and make software
that made sense to his engineers.

I presume you are young and if you wish to be an engineer and not
a salesman you must be eaten up with the desire to know
"How Stuff Works".  Computers are ubiquitous in engineering
and if you want to be the best, learn how they work.

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


Re: Monitoring Outgoing Connections?

2005-05-30 Thread Peter Hansen
Joseph Chase wrote:
> Is it possible to write a client within Python that would trigger some sort 
> of callback interface when the user is attempting to make an outgoing TCP/IP 
> connection?  I'd like to accomplish this on a Windows XP box.
> 
> Is this something that could be accomplished with the Twisted framework, or 
> am I going to have to dive in the platform specific API?

AFAIK, there is no cross-platform way of doing anything resembling that, 
so you will have to do the dive...

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


Re: How to restrict lenght of entry widget to certain number of character

2005-05-30 Thread flupke
Michael Onfrek wrote:
> Hi!
> I'm playing with entry again and trying to restrict length of entry
> widget to certain number of character, so users cannot enter more
> character into it. Any ideas?
> Reg. Michael Onfrek
> 

What widget set are you talking about, wxPython pygtk, tkinter?

In wxPython:
.SetMaxLength(length)

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


Re: Is there a better way of doing this?

2005-05-30 Thread Magnus Lycka
Steven D'Aprano wrote:
 > print is a statement, not a function. The brackets are syntactically
 > correct, but pointless. Remove them.
...
> On Sat, 28 May 2005 13:24:19 +, Michael wrote:
>> while( newNS ):
> 
> Guido (our Benevolent Dictator For Life and creator of Python) hates
> seeing whitespace next to parentheses. I agree with him. while(newNS)
> good, while( newNS ) bad.

while is a statement, not a function. The brackets are syntactically
correct, but pointless. Remove them. ;^)

 while newNS:

Not only are they pointless (in both print and while), but they are
blurring the distinction between statements and callables, and they
add noise. Only wrap the expression following a statement such as
while, if, print etc in () if the following expression spans several
lines.

Using () instead of \ as line continuator is considered good style.
(See http://www.python.org/doc/essays/ppt/regrets/PythonRegrets.pdf
slide 3.) In that case, make sure you have a space between the
statement and the (. Never have space between a callable and
the (. That way, we emphasize the difference between a statemens
and a call. E.g:

while (aVeryVeryVeryLongVariableName == anotherVeryVeryLongName
or aThirdLongVariableName == aFourthLongVariableName):
 something = function(parameterOne, parameterTwo, parameterThree,
  parameterFour, parameterFive, etc)


N.B. Use "while (" but "function(".

(I'm not suggesting that such long variable names are generally
good, but there are certainly cases where both logical expressions
and parameter lists will be too long for one line, for instance when
working with stuff such as the win32 APIs.)

Please note the big conceptual difference in using a statement which
controls local program flow, and calling a function/method/class etc
which means that we transfer control to a different part of the
program. Some of the current statements in Python, e.g. print,
actually behaves more like a function than like the normal statements,
and this might be considered a wart. It's also mentioned in Guido's
"regrets" slides mentioned above. Print and exec *are* still not
callables though. They *are* statements, whether we like it or not.

If writing "print(something)" feels better than "print something",
I suggest you define a function called writeln etc and use that
instead of print, e.g.

 >>> import sys
 >>> def writeln(*args):
... sys.stdout.write(" ".join(map(str, args)) + '\n')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading questions

2005-05-30 Thread Magnus Lycka
Antal Rutz wrote:
> Hi, All!
> 
> I'm new to threading. I have some design questions:
> Task: I collect data and store them in an RDBMS (mysql or pgsql)
> 
> The question is how to do that with threading?
> The data-collecting piece of the code runs in a thread.
> 
> 1. Open the db, and each thread writes the result immediately.
>(Sub-question: which is better: cursor object passed to the thread
>or stored in a global var.)
> 2. Threads return data, which is written to DB after that.
> 3. Threads write to global variable, after 'join()' data is written.
>(Can be used global (write-only) variables with threads at all?)
> 4. ?...

I'm not sure why you need threading at all here, but I would avoid
both globals and passing cursors between threads. I don't think all
DB-API implementations can handle threading properly.

I suspect it might be useful to do data collection in one thread,
DB communication in another, and to use a Queue.Queue object to
pass data from data collection to DB insertion thread.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie learning OOP 2nd ?

2005-05-30 Thread [EMAIL PROTECTED]
I would split your code such that the Q&A is seperated from the
calculations, and I would model the bill something like :

class allbills(object):
def __init__(self, bill, tip):
self._bill = bill
self._tip = tip

def gettip(self):
return self._tip / 100.0
tip = property(gettip)

def gettotal(self):
return self._bill * (1 + self.tax + self.tip)
total = property(gettotal)

def __repr__(self):
return 'tip = %.2f, tax = %.2f, total = %.2f ' % \
   (self.tip, self.tax, self.total)

class usbill(allbills):
def __init__(self, bill, tip):
super(usbill, self).__init__(bill, tip)

def gettax(self):
return 0.0675
tax = property(gettax)

class chicago_bill(allbills):
def __init__(self, bill, tip):
super(chicago_bill, self).__init__(bill, tip)

def gettax(self):
return 0.0725
tax = property(gettax)

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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Leif K-Brooks
Roy Smith wrote:
> Just wait until the day you're trying to figure out why some C++ function 
> is behaving the way it is and you don't notice that a 50-line stretch of 
> code is commented out with /* at the top and */ at the bottom.

The same thing's happened to me in Python when I accidentally included a
function's code in its docstring (don't ask me how I managed to do that
-- I don't know). But my editor's syntax highlighting helped me to find
the error very quickly.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie learning OOP 2nd ?

2005-05-30 Thread LenS
Thank you for your suggestion and especially your time.   I will study
your code:-)

Len Sumnler

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


Re: Software licenses and releasing Python programs for review

2005-05-30 Thread John J. Lee
"poisondart" <[EMAIL PROTECTED]> writes:
[...]
> I plan to release my programs for academic and pedagogical purposes.
> The knowledge contained in these programs is the same knowledge that
> people use to speak a language--did you buy a copy of the English
> language when you decided to learn it?
> 
> This is why I feel that it would not make sense for me to sell my
> programs for profit.

I'm a little curious about your position.

Though code encodes knowledge (hence the word, of course :-), the
system of concepts embodied in your code is not the same thing as the
code itself.  Right?

So, firstly, I don't follow your argument there: how does it follow
from the fact that scientific and mathematical knowledge should not be
treated by the law as - in some sense - property (a moot point of
course, though I lean towards your view) that it doesn't 'make sense'
(scare quotes because I'm not sure of your precise meaning) to sell
your software for profit?

Secondly, do you think it's a bad thing for anybody to sell software
that makes use of the *concepts* in your code (provided that the use
of those concepts is not restricted by financial or other legal
means)?  If so, why?


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


Is pyunit still usable?

2005-05-30 Thread could ildg
I want to know something about unittest these days,
and since I'm learning python, I want to touch it through
python. But when I found the newest pyunit is even so
old, I wonder if it is still usable for current python version
2.4. Will you please tell me? Thank you.

What are the advantages and disadvantages of unittest?
Can somebody give me a detailed listing?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Threading questions

2005-05-30 Thread Antal Rutz
Magnus Lycka wrote:
> Antal Rutz wrote:
> 
>>Hi, All!
>>
>>I'm new to threading. I have some design questions:
>>Task: I collect data and store them in an RDBMS (mysql or pgsql)
>>
>>The question is how to do that with threading?
>>The data-collecting piece of the code runs in a thread.
>>
>>1. Open the db, and each thread writes the result immediately.
>>   (Sub-question: which is better: cursor object passed to the thread
>>   or stored in a global var.)
>>2. Threads return data, which is written to DB after that.
>>3. Threads write to global variable, after 'join()' data is written.
>>   (Can be used global (write-only) variables with threads at all?)
>>4. ?...
> 
> 
> I'm not sure why you need threading at all here, but I would avoid
> both globals and passing cursors between threads. I don't think all
> DB-API implementations can handle threading properly.

I 'snmpwalk' routers and some are very slow, so it's better to spread
the routers among data-collecting threads.

> I suspect it might be useful to do data collection in one thread,
> DB communication in another, and to use a Queue.Queue object to
> pass data from data collection to DB insertion thread.

Yes, I just figure out how the many-collecting-one-dbwriting-thread
design could be made. It doesn't seem to be too difficult.

Thanks for the hints!

-- 


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


Re: Is pyunit still usable?

2005-05-30 Thread Kent Johnson
could ildg wrote:
> I want to know something about unittest these days,
> and since I'm learning python, I want to touch it through
> python. But when I found the newest pyunit is even so
> old, I wonder if it is still usable for current python version
> 2.4. Will you please tell me? Thank you.

unittest is a standard Python module since Python 2.1. It is a version of 
PyUnit.

> What are the advantages and disadvantages of unittest?
> Can somebody give me a detailed listing?

Of unittest the module or unit testing the practice?

If you mean the module, you might be interested in these articles comparing 
unittest, py.test and 
doctest:
http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-1-unittest.html
http://agiletesting.blogspot.com/2005/01/python-unit-testing-part-2-doctest.html
http://agiletesting.blogspot.com/2005_01_01_agiletesting_archive.html

If you mean the practice, Google is your friend. Countless books and articles 
have been written 
about unit testing.

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


Re: How to restrict lenght of entry widget to certain number of character

2005-05-30 Thread Michael Onfrek
I'm using tkinter

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


Re: Is pyunit still usable?

2005-05-30 Thread John Roth
PyUnit came with a GUI, which is not part of the
unittest version in the standard library.

I don't know whether the GUI from PyUnit still
works with the version of unittest in the standard
library, but other than that, there is no reason to
maintain the PyUnit branch.

John Roth



"could ildg" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
I want to know something about unittest these days,
and since I'm learning python, I want to touch it through
python. But when I found the newest pyunit is even so
old, I wonder if it is still usable for current python version
2.4. Will you please tell me? Thank you.

What are the advantages and disadvantages of unittest?
Can somebody give me a detailed listing?


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


Python crash

2005-05-30 Thread Stormbringer
I am using latest python 2.4 under Windows.

I have a file where I have a bunch of functions, but none with a
special name and nothing outside the functions, no import etc

In the main module all works fine if I don't import that file.
The moment I import it nothing happens but I get a crash later on when
I call a pyopengl function. If I comment just the 'import ...' line
then all works ok.

The crash occurs in pythonw.exe and can't follow further as pythonw
doesn't seem to contain any debug information.

Obviously something must be wrong with my pyopengl but I don't
understand why including a module generates the crash later on. Anyone
got something similar ? Any hints/tips/tricks on finding the cause of
the problem ?

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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread D H
Roy Smith wrote:
> In article <[EMAIL PROTECTED]>, D H <[EMAIL PROTECTED]> wrote:
> 
> 
>>Elliot Temple wrote:
>>
>>>Hi I have two questions.  Could someone explain to me why Python is
>>>case sensitive?  I find that annoying.  
>>
>>I do too.  As you've found, the only reason is because it is, and it is 
>>too late to change (it was even too late back in 1999 when it was 
>>considered by Guido).  I guess the most popular case-insensitive 
>>language nowadays is visual basic (and VB.NET).
>>
>> > Also, why aren't there
>>
>>>multiline comments?  Would adding them cause a problem of some sort?
>>
>>Again, just because there aren't and never were.  There is no technical 
>>reason (like for example a parsing conflict) why they wouldn't work in 
>>python.  That's why most python editors have added a comment section 
>>command that prepends # to consecutive lines for you.
> 
> 
> If it really bothers you that there's no multi-line comments, you could 
> always use triple-quoted strings.

Where did I say that?

> I actually don't like multi-line comments.  They're really just syntactic 
> sugar, and when abused, they can make code very difficult to understand.  
> Just wait until the day you're trying to figure out why some C++ function 
> is behaving the way it is and you don't notice that a 50-line stretch of 
> code is commented out with /* at the top and */ at the bottom.

Same with triple quotes, btw.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re:

2005-05-30 Thread Paul English
Thanks for sending me email, but please click the following link
or else my mail server will not deliver your message to me:

  http://blade.f7.net/cr.cgi/pme/[EMAIL PROTECTED]

I use this system to prevent spam. Once you click the above
link, you will be added to the whitelist and not be challenged again.

Thanks,
Paul

--
ps, see http://blade.f7.net for more information about this system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Software licenses and releasing Python programs for review

2005-05-30 Thread Rocco Moretti
poisondart wrote:

> With the exception of the example with neighbour Bobby (which directly
> utilizes my code for profit, in which case is a definite no), I don't
> see why your other examples should make me reconsider releasing my
> software for free.

I don't think he's trying to make you reconsider releasing the code for 
free, he just wants you to think about what you want to happen in 
certain scenarios - There are no right or wrong answers, but your 
answers will help you decide what license you want to release your code as.

> You publish a magazine and include a CD with my code--you are using my
> code to attract readers (this, I did not agree to).

Well, depending on what license you use, the agreement may be implicit 
in the license. (e.g. the GPL allows Steven to do this, a Microsoft type 
EULA doesn't)

> The example with colleague Betty does not say whether she has debugged
> my code and sold it for profit. If she does, then she will have done
> something very selfish in my view--also undesirable. 

What's selfish? The fact that she debugged it? The fact that she sold 
it? The fact that she debugged it and didn't give you the corrections? 
Your answer will help you decide what you want in a license.

> If she hasn't debugged my code...what is she doing selling my property?

It depends on how you look at things. She might not be selling your 
software - she's selling a list of bug-free and stable programs, which 
happens to have a copy of your program on the same CD. If you allow free 
redistribution, this is implicit. She's distributing your program for 
free (allowed by your license), but is selling her value added service 
of certifying that the program is bug free.

> I plan to release my programs for academic and pedagogical purposes.
> The knowledge contained in these programs is the same knowledge that
> people use to speak a language--did you buy a copy of the English
> language when you decided to learn it?
> 
> This is why I feel that it would not make sense for me to sell my
> programs for profit.

You have several things going on here:

Although it might not make sense for *you* to sell your program for 
profit, someone else might think it worthwhile. Do you want to disallow 
this, why or why not?

Secondly, you should distinguish between being *required* to purchase 
the program and being *able* to purchase the program. Just because 
Barney is selling a copy of the program doesn't mean other people can't 
download it for free off of your website. They *could* pay for it, but 
they can also get it for free. Using your English language example, no 
one sold me a copy of the English language, but there are a number of 
companies which have sold the "knowledge that people use to speak a 
language" to me in the form of dictionaries, thesauruses, and grammar 
guides over the years. I'm no less free in using the English language, 
but Merriam Webster still can make money by selling it back to me.

 > The competitor Barney--This is exactly what I _don't_ want. What's he
 > doing selling my code?

Last point to consider. Say you make a restrictive license. No 
commercial use. No redistribution. etc. Barney comes along and ignores 
the license - distributes the program, sells it for loads of cash.

What are you willing to do? Send a nasty letter? Barney isn't a nice 
guy. He doesn't care that you've sent him an angry letter. He'll still 
sell your program - he's making loads of money. Are you willing to sue 
him? A license doesn't mean much unless you're willing to back it up in 
court. Are you prepared to spend years and  to make Barney stop?

If you aren't making money off of it yourself, having a restrictive 
license isn't going to help most hobbyists/academics, for the sole 
reason that they don't want to go the the effort required to enforce it.

If all you want is to make sure that your program is always available 
for free to academics/the general public, just use a lax license (like 
MIT) and provide it for free. So what if someone else charges for it? 
They can always go to you to get it for free.

If you're offended at the thought that someone else might be able to 
make money off of your program, then a certified "Open Source" license 
isn't really going to help - one of the requirements is no bias against 
fields of endeavor - they specifically mention the "no commercial use" 
clause as forbidden. http://www.opensource.org/docs/definition.php

That doesn't stop you from choosing a non-"open source" license if you 
want - just be aware that that license choice may substantially affect 
what the community is willing to give back to you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: prime number

2005-05-30 Thread Rocco Moretti
lostinpython wrote:
> But needless to say, I'm stumped on this
> problem.  I keep ending up in a never ending loop.

I've been told that the trick with recursion/iteration is to always 
determine what your ending condition is first, and then construct the 
body of the recursion/loop to reach that ending condition eventually. If 
you post the specific code which is giving you problems, people here can 
point out why you're missing the exit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: first release of PyPy

2005-05-30 Thread Rocco Moretti
Kay Schluehr wrote:
> Anton Vredegoor wrote:
> 
> 
>>I'm not involved in PyPy myself but this would seem a logical
>>possibility. To go a step further, if the compiler somehow would know
>>about the shortest machine code sequence which would produce the
>>desired effect then there would be no reason to limit onself to only
>>those relatively inefficent standard code sequences that are inside
>>system dll's.
> 
> 
> Are You shure that this problem is effectively solvable in any
> language? Since You did not precise Your idea I'm not shure whether You
> want to solve the halting-problem in PyPy or not ;)

I'm always amazed at how many people take the intractableness of the 
halting problem as a reason to not even try. Sure, you can't tell if an 
*arbitrary* program halts or not, but there are many where you can. 
(Assuming a perfect Python Interpreter):

c = 5 + 6

halts.

c = 5
while 1:
 c = c + 6

doesn't.

A trip through the Zope internals may be a little harder to decide. But 
one might argue that code that does not give a clear "yes, it halts" is 
poorly written, and should be rewritten to be better behaved.

At any rate, Anton isn't talking about solving the halting problem, but 
is hinting more along the lines of introspecting the code and, for 
example, substituting a bubble sort for a quick sort when the specific 
circumstances determine that it would be quicker. Granted, giving the 
"best" code sequence would be tough to impossible to determine, but a 
"better" code sequence would still make people happy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: plotting with Python

2005-05-30 Thread Philippe C. Martin
Look at wxPython

Regards,

Philippe



Rolf Wester wrote:

> Hi,
> 
> I have a Python console application that is intended to be used
> interactively and I have to add plotting capabilities (multiple XY plots
> and if possible 2D-surface plots). I'm loocking for a reasonably fast
> plotting library (not GPL'ed, needs not be for free) that can be used
> under Windows. An alternative would also be a standalone application
> that can be controlled via TCP/IP from my Python application. I tried
> matplotlib but this is not fast enough (especially under Windows). I
> considered PyQwt but this is GPL'ed. So I would be very appreciative for
> any help.
> 
> With kind regards
> 
> Rolf Wester

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


avl tree

2005-05-30 Thread Zunbeltz Izaola
Hi,

I'm trying to install avl module from
http://www.nightmare.com/squirl/python-ext/avl

and i had the following instruction to install

Building:

Unix:
First, cd $(AVL_LIB), then 'make libavl.a'

Then copy AVLmodule.c into your Modules directory.
add a few lines like this to your Python/Modules/Setup file.
---
# avl module
AVL_LIB=/usr/src/other-homes/rushing/python/avl
avl AVLmodule.o -DDEBUG_AVL -I$(AVL_LIB) -L$(AVL_LIB) -lavl
-

I have build livavl.a, but i don't understan where is Python/Modules/Setup
and where goes the AVLModule.c file goes.


Could anyone help me,

Thanks,

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


How to run functions in the background?

2005-05-30 Thread Ognjen Bezanov
Hello


I need to find a way to 'fork' a function into the background yet still
be able to send commands to it.

I am writing a media player, and I have a function which plays the
media. I want to be able to run this function but to (at the same time)
be able to send commands from it (e.g. pause, play etc...)

How could I do this?

any help appreciated.

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


Re: __getattribute__ and __getattr__

2005-05-30 Thread Gigi
Terry Reedy wrote:
> "Gigi" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> 
>>Hi,
>>In the Python documentation regarding __getattribute__ (more attribute
>>access for new style classes) it is mentioned that if __getattribute__
>>is defined __getattr__ will never be called (unless called explicitely).
>>Here is the exact citation:
> 
> 
> Discrepancy reported in
> 
> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1204734&group_id=5470
> 
> Guido declared behavior right and doc wrong and in need of correction.
> 
> Terry J. Reedy
> 
> 
> 

Thanks for your reply. It definitely clears the issue. I'm writing an
article to Dr. Dobbs about the Python object model and I wouldn't want
to be inaccurate. I fill a little like Leibnitz :-) . It's a curious
coincidence that two separate people notice the same documentation issue
that lingere for such a long time in such a short time span.

Thanks, Gigi



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


Re: How to run functions in the background?

2005-05-30 Thread Grant Edwards
On 2005-05-30, Ognjen Bezanov <[EMAIL PROTECTED]> wrote:

> I need to find a way to 'fork' a function into the background
> yet still be able to send commands to it.

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

-- 
Grant Edwards   grante Yow!  I'm a fuschia bowling
  at   ball somewhere in Brittany
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert string to list or tuple

2005-05-30 Thread Steven Bethard
Duncan Booth wrote:
> Steven Bethard wrote:
> 
>>But you can try it at home if you set __builtins__ to something other 
>>than the default:
>>
>>py> eval("""__import__("os").system('echo "hello"')""", 
>>dict(__builtins__=None))
>>Traceback (most recent call last):
>>   File "", line 1, in ?
>>   File "", line 0, in ?
>>NameError: name '__import__' is not defined
>>
[snip]
>>
>>I know there have been security holes in this technique before, but I 
>>looked at the archives, and all the old ones I found have been
>>patched. 
>>  (Or at least I wasn't able to reproduce them.)
> 
> I guess you are referring to things like this not working when you use eval 
> with an empty __builtins__:
> 
> eval('''[ cls for cls in {}.__class__.__bases__[0].__subclasses__()
>if '_Printer' in `cls` 
> ][0]._Printer__setup.func_globals['__builtins__']['__import__']''',
>   dict(__builtins__=None))
> 
> That gets blocked because func_globals is a 'restricted attribute', so I 
> can't get directly at __import__ that way

Among other things, yes, that's one of the big ones.  func_globals is 
inaccessible.  Also, IIRC the file constructor is inaccessible.

> but what I can do is to access 
> any new style class you have defined and call any of its methods with 
> whatever arguments I wish.

Any new style class that I've defined?  Or just any one I pass in as 
part of dict(__builtins__=None, ...)?  If the former, could you 
elaborate?  If the latter, then yes, I can see the problem.  However for 
the case where all you pass in is dict(__builtins__=None), is there 
still a risk?  Note that in the OP's case, all that is necessary is 
constant parsing, so no names need to be available.

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


Re: How to run functions in the background?

2005-05-30 Thread Will McGugan
Ognjen Bezanov wrote:
> Hello
> 
> 
> I need to find a way to 'fork' a function into the background yet still
> be able to send commands to it.
> 
> I am writing a media player, and I have a function which plays the
> media. I want to be able to run this function but to (at the same time)
> be able to send commands from it (e.g. pause, play etc...)
> 
> How could I do this?

Put your function in a thread, and add a queue to send your commands. 
Look up 'thread' and 'queue' in the help.


Will McGugan
-- 
http://www.willmcgugan.com
"".join({'*':'@','^':'.'}.get(c,0) or chr(97+(ord(c)-84)%26) for c in 
"jvyy*jvyyzpthtna^pbz")
-- 
http://mail.python.org/mailman/listinfo/python-list


Python Exercises for Newbee

2005-05-30 Thread Kanthi Kiran Narisetti
Hi ALL,

I am Windows Administrator, moving little ahead from batch files and
scripts I started learning Python. I found that Python is very easy and
is very well documented. Still I am looking more than examples. As a
beginner i want to do lot of excersice from simple addition to complex
...which help me to understand the concepets more clearly.

I appreciate if any one can give me such exersices or any link for the
same.


Thank You ,
Kanthi Kiran

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


Uk Shoppers - Discount Vouchers and Promotional Codes - NOREPLY

2005-05-30 Thread savemoney
Do you shop online? Do you want to save money?  Discount vouchers and
promotional codes exist for a wide range of on-line retailers. A
comprehensive list of these retailers are to be found here:

http://www.ukshops.h15.ru/vouchers.html

The site includes codes and vouchers for top UK shops such as Marks &
Spencer, Currys, Boots and John Lewis. Plus many, many more.

Click here for full details:
http://www.ukshops.h15.ru/vouchers.html

Note: J=£
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: write to the same file from multiple processes at the same time?

2005-05-30 Thread Mike Meyer
gabor <[EMAIL PROTECTED]> writes:

> ok, i ended up with the following code:
>
> def syncLog(filename,text):
>  f = os.open(filename,os.O_WRONLY | os.O_APPEND)
>  fcntl.flock(f,fcntl.LOCK_EX)
>  os.write(f,text)
>  #FIXME: what about releasing the lock?
>  os.close(f)
>
> it seems to do what i need ( the flock() call waits until he can get
> access).. i just don't know if i have to unlock() the file before i
> close it..

The lock should free when you close the file descriptor. Personally,
I'm a great believer in doing things explicitly rather than
implicitly, and would add the extra fcntl.flock(f, fcntl.LOCK_UN) call
before closing the file.

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


standard doc style for method signatures

2005-05-30 Thread David S.
Is there a generally accepted way to denote method signatures---that is,
expected type or required interface for each argument.  

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


Unicode Congruence

2005-05-30 Thread phil
I can't find, anyone know the unicode symbol
CONGRUENT.
either tilde over equal or triple
tidde would do.
Thanks.

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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Terry Reedy

"D H" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> Elliot Temple wrote:
>> Hi I have two questions.  Could someone explain to me why Python is
>> case sensitive?  I find that annoying.
>
> I do too.

I don't.

>  As you've found, the only reason is because it is,

False.  As someone else already pointed out in this thread, and as some 
said years ago when Guido brought up the subject, standard math notation 
*is* case sensitive and some people like Python because they can directly 
translate math expressions into Python expressions.

I am annoyed by the disinformation and slander ('anti-newbie') repeated 
indefinitely by some case-folding advocates.  Difference annoyances for 
different folks, I guess.

Terry J. Reedy





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


How do you drive-by-wire a car using Python ?

2005-05-30 Thread [EMAIL PROTECTED]
Hello everybody,

Our entry in the DARPA Grand Challenge race uses Python as a
programming language. For those of you who are interested, we are
beginning to put some of our code on our blog.

Before being autonomous, our vehicle (a four wheel drive Jeep) has to
first be driven by wire, i.e. use controls through a computer in order
to command the different steering, acceleration/braking actions.

This entry shows you the lighter version of the code we use to do this
drive-by-wire

http://pegasusbridge.blogspot.com/2005/05/how-do-you-drive-by-wire-car-using.html

(please note the disclaimer)

Cheers,

Igor.

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


decimal numarray

2005-05-30 Thread km
Hi all,
 is there any support for decimal type in numarray module ? 
regards,
KM
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding indices in a sequence of parentheses

2005-05-30 Thread tiissa
Peter Otten wrote:
> tiissa wrote:
>>Disclaimer: not tested further than example above (but confident).
> 
> Not tested but confident should be an oxymoron for a programmer.

Not tested but confident is an oxymoron for mathemtaticians.
Programmers know better than that, they leave bugs in their code to have 
more work to do. ;)

OTOH, you're right. Matching parentheses cannot be done without a stack, 
that should have rung a bell.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decimal numarray

2005-05-30 Thread Robert Kern
km wrote:
> Hi all,
>  is there any support for decimal type in numarray module ? 

Not specifically, no. However, there is the concept of an "object 
array," which are arrays of arbitrary Python objects. See numarray.objects .

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


Re: How to run functions in the background?

2005-05-30 Thread Terry Reedy

"Ognjen Bezanov" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I need to find a way to 'fork' a function into the background yet still
> be able to send commands to it.

Others gave you the answer to this..

> I am writing a media player, and I have a function which plays the
> media. I want to be able to run this function but to (at the same time)
> be able to send commands from it (e.g. pause, play etc...)

But for this, you might look into PyGame, which, I believe, has functions 
like this.

Terry J. Reedy



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


Exiting SocketServer: socket.error: (98, 'Address already in use')

2005-05-30 Thread Magnus Lycka
I have a socket server like below which I want to exit when
it's out of data. If I interrupt the client, I'll get a
broken pipe on the server side, and after a Ctrl-C, I can
restart the server again, but if I let it run out of data,
and exit via handle_error as can be seen below, I will get
a socket.error: (98, 'Address already in use') when I try
to restart the server. (Unless I wait a minute or so, or
use another port.) I feel like I'm waving a dead chicken
here. I can't seem to find any proper description on how to
handle this in the docs for SocketServer or socket, and my
futile experiments seem to lead nowhere... Neither Nutshell
nor the Essential Reference helped me solve this.

I'm using Python 2.2.3 on Linux. Why doesn't my socket
get released by the OS when I exit via my handle_error?

class MyRequestHandler(SocketServer.BaseRequestHandler):
 def handle(self):
 while True:
 [snip]
 try:
 [snip]
 except [snip]:
 # Done!
 # Uncommenting the next line makes no difference
 # self.request.close()
 sys.exit()

class ExitableSocketServer(SocketServer.TCPServer):
 def handle_error(self, request, client_address):
 exc_info = sys.exc_info()
 if exc_info and isinstance(exc_info[1], SystemExit):
 request.shutdown(2)
 request.close()
 del request
 self.socket.shutdown(2)
 self.socket.close()
 del self.socket
 sys.exit()
 SocketServer.TCPServer.handle_error(self, request, client_address)

...

server = ExitableSocketServer(('', port), MyRequestHandler)
server.serve_forever()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode Congruence

2005-05-30 Thread John Machin
phil wrote:
> I can't find,

Having looked where?

> anyone know the unicode symbol
> CONGRUENT.
> either tilde over equal or triple
> tidde would do.
> Thanks.
> 

Go to

http://www.unicode.org

click on:
  Where is my Character?

follow your nose till you get to:

http://www.unicode.org/charts/symbols.html

What you need is:

http://www.unicode.org/charts/PDF/U2200.pdf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: avl tree

2005-05-30 Thread Berthold Höllmann
Zunbeltz Izaola <[EMAIL PROTECTED]> writes:

> Hi,
>
> I'm trying to install avl module from
> http://www.nightmare.com/squirl/python-ext/avl
>
> and i had the following instruction to install
>
> Building:
>
> Unix:
> First, cd $(AVL_LIB), then 'make libavl.a'
>
> Then copy AVLmodule.c into your Modules directory.
> add a few lines like this to your Python/Modules/Setup file.
> ---
> # avl module
> AVL_LIB=/usr/src/other-homes/rushing/python/avl
> avl AVLmodule.o -DDEBUG_AVL -I$(AVL_LIB) -L$(AVL_LIB) -lavl
> -
>
> I have build livavl.a, but i don't understan where is Python/Modules/Setup
> and where goes the AVLModule.c file goes.

I'm afraid you won't be happy with the code. It's very old and likely
won't compile. We have an inhouse version of this module which
compiles and run on Sparc solaris (32 Bit) and linux x86 with Python
up to 2.4. I fixed some warnigs just today for compilation on Linux
x86_64, it also seems to work on this platform now. Installation is
setup.py based. I'm quite sure we once sent patches to Sam Rushing,
but they never made it into his release. I'll try to publish our
version the next days. 

Regards
Berthold
-- 
[EMAIL PROTECTED] / 
[EMAIL PROTECTED] / 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Python Exercises for Newbee

2005-05-30 Thread vincent wehren
"Kanthi Kiran Narisetti" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
| Hi ALL,

Hi to you too!

|
| I am Windows Administrator, moving little ahead from batch files and
| scripts I started learning Python. I found that Python is very easy and
| is very well documented. Still I am looking more than examples. As a
| beginner i want to do lot of excersice from simple addition to complex
| ...which help me to understand the concepets more clearly.

have you already perused the Python Cookbook?

http://aspn.activestate.com/ASPN/Python/Cookbook/



As a Windows admin, you may also be interested in looking at
Tim Golden's Python Stuff:

http://tgolden.sc.sabren.com/python/index.html


Enjoy!

--
Vincent Wehren


|
| I appreciate if any one can give me such exersices or any link for the
| same.
|
|
| Thank You ,
| Kanthi Kiran
| 


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


Re: finding indices in a sequence of parentheses

2005-05-30 Thread Peter Otten
tiissa wrote:

> Not tested but confident is an oxymoron for mathemtaticians.

I think no amount of testing will give these strange people confidence.
"Proof" is the magic word here.

Peter

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


Re: finding indices in a sequence of parentheses

2005-05-30 Thread tiissa
Peter Otten wrote:
> I think no amount of testing will give these strange people confidence.
> "Proof" is the magic word here.

Some would maybe be satisfied if your tests cover the whole set of input.

When that's possible, that may be useless. But that's not a matter to 
bother them with. ;)

(And of course, you just don't tell them how you generated their output 
with the same program.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Exercises for Newbee

2005-05-30 Thread Bruno Desthuilliers
Kanthi Kiran Narisetti a écrit :
> Hi ALL,
> 
> I am Windows Administrator, moving little ahead from batch files and
> scripts I started learning Python. I found that Python is very easy and
> is very well documented. Still I am looking more than examples. As a
> beginner i want to do lot of excersice from simple addition to complex
> ...which help me to understand the concepets more clearly.
> 
> I appreciate if any one can give me such exersices or any link for the
> same.
> 

You may want to try Dive into Python
http://diveintopython.org/

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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Magnus Lycka
Terry Reedy wrote:
> Difference annoyances for different folks, I guess.

IN MY EXPERIENCE, MANY PEOPLE ON THE INTERNET ARE
ANNOYED BY PEOPLE WHO DON'T USE CASE THE WAY THEY
ARE EXPECTED. IT ALSO SEEMS TO ME THAT LOWER CASE
TEXT IS OFTEN MORE EASY TO READ, AND ALSO THAT IT
IS EASIER TO SCAN TEXTS IF CASE IS CONSISTENT. WE
DO AFTER ALL SEE IMAGES ON THE SCREEN. EVEN IF WE
RELATE "IF" WITH "if",  THEY DON'T LOOK THE SAME.
MY SON POINTED AT THE WORD "TOYOTA" IN A MAGAZINE
AND EXCLAIMED "TOTOTA" WHEN HE WAS ONLY THREE. HE
WAS CLEARLY TOO YOUNG TO READ,  BUT HE RECOGNIZED
THE IMAGE OF THE LOGO HE HAD SEEN ON OLD TOYOTAS.
IN GENERAL,  PYTHON "TRIES" TO FORCE A PARTICULAR
STYLE OF CODING ON PROGRAMMERS. WE HAVE TO INDENT
IN A PARTICULAR WAY. THE STYLE OF PROGRAMMING HAS
BEEN CODIFIED IN PEP 008,  AND COWBOY PROGRAMMING
ISN'T REALLY APPRECIATED.  YOU ARE NOT "SUPPOSED"
TO PROGRAM PYTHON "YOUR WAY". YOU ARE SUPPOSED TO
PROGRAM THE RIGHT WAY. IF YOU DON'T LIKE THAT, IT
IS PROBABLY BETTER TO USE ANOTHER LANGUAGE.  PERL
IS MORE OF A COWBOY LANUGAGE.  THE FUNNY THING IS
THAT EVEN PERL IS CASE SENSITIVE! EXPLAIN THAT!!!
IMO IT'S A STRENGTH OF PYTHON THAT PYTHON CODE IS
ALWAYS CONSISTENT IN CASE. IT IS PROBABLY A MINOR
FEATURE COMPARED TO THE BLOCK STRUCTURES ETC, BUT
I THINK IT ADDS TO THE EASE OF READING CODE WHICH
HAS BEEN WRITTEN BY OTHERS. I DO ALSO DISLIKE THE
ALTERNATIVES.  NEITHER CODE WITH INCONSISTENT USE
OF CASE NOR THE STUPID "CASE CORRECTING" FEATURES
IN E.G. THE VISUAL BASIC IDE SEEMS TO BE ANYTHING
TO STRIVE FOR.  IF YOU THOUGHT IT WAS ANNOYING TO
READ THIS,  THEN YOU CAN AT LEAST APPRECIATE THAT
PYTHON CODE NEVER LOOKS LIKE SUCH A COMPACT BLOB!

Who am I kidding with this? Everybody knows that
case doesn't matter, right? The text below isn't
a bit easier to read than the text above, right?

In my experience, many people on the internet are
annoyed by people who don't use case the way they
are expected. It also seems to me that lower case
text is often more easy to read, and also that it
is easier to scan texts if case is consistent. We
do after all see images on the screen. Even if we
relate "IF" with "if",  they don't look the same.
My son pointed at the word "TOYOTA" in a magazine
and exclaimed "Totota" when he was only three. He
was clearly too young to read,  but he recognized
the image of the logo he had seen on old toyotas.
In general,  Python "tries" to force a particular
style of coding on programmers. We have to indent
in a particular way. The style of programming has
been codified in PEP 008,  and cowboy programming
isn't really appreciated.  You are not "supposed"
to program Python "your way". You are supposed to
program the right way. If you don't like that, it
is probably better to use another language.  Perl
is more of a cowboy lanugage.  The funny thing is
that even Perl is case sensitive! Explain that!!!
IMO it's a strength of Python that Python code is
always consistent in case. It is probably a minor
feature compared to the block structures etc, but
I think it adds to the ease of reading code which
has been written by others. I do also dislike the
alternatives.  Neither code with inconsistent use
of case nor the stupid "case correcting" features
in e.g. the Visual Basic IDE seems to be anything
to strive for.  If you thought it was annoying to
read this,  then you can at least appreciate that
Python code never looks like such a compact blob!

oF cOuRsE, wE sHoUlDn'T aSsUmE tHaT pEoPlE wIlL
aBuSe ThE fReEdOm ThEy GeT, bUt I'm RaThEr SaFe
ThAn SoRrY! ;^) I'm ReAlLy hApPy ThAt I'lL nEvEr
HaVe To SeE aLl-CaPs PyThOn PrOgRaMs!

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


(", ) Print This! Press [Ctrl][P] Keys To Print... >> http://www.phpbbserver.com/phpbb/viewtopic.php?t=2&mforum=anysubjectchat < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < <

2005-05-30 Thread compaq71127
(",) Print This! Press [Ctrl][P] Keys To Print... >>
http://www.phpbbserver.com/phpbb/viewtopic.php?t=2&mforum=anysubjectchat
< < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < <
< < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < <
< < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < <
< < < < < < < < < < < < < < < < < < < < < <

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


Re: Unicode Congruence

2005-05-30 Thread phil
Thanks.
I did search that site but, wow, huge.
That page had no reference to congruence
and the pdf did not contain the pattern
congru.
But I'll have some better ideas how to search next
time.
thanx
I used \u2245 btw

John Machin wrote:

> phil wrote:
> 
>>I can't find,
>>
> 
> Having looked where?
> 
> 
>>anyone know the unicode symbol
>>CONGRUENT.
>>either tilde over equal or triple
>>tidde would do.
>>Thanks.
>>
>>
> 
> Go to
> 
> http://www.unicode.org
> 
> click on:
> Where is my Character?
> 
> follow your nose till you get to:
> 
> http://www.unicode.org/charts/symbols.html
> 
> What you need is:
> 
> http://www.unicode.org/charts/PDF/U2200.pdf
> 



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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Benji York
What I want to know is how Mangus wrote an entire message fully
justified.  I looked for extra spaces and other cheats but only
found a couple of superfluous exclamation marks.  Well done! He
must be a justification wizard.  I wish I could do that too. :)
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do you drive-by-wire a car using Python ?

2005-05-30 Thread Tim Churches
[EMAIL PROTECTED] wrote:
> Hello everybody,
> 
> Our entry in the DARPA Grand Challenge race uses Python as a
> programming language. For those of you who are interested, we are
> beginning to put some of our code on our blog.

Here is a shot of a Pythonic DARPA Grand Challenge autonomous vehicle
pausing to do garbage collection:
http://www.shoalhaven.nsw.gov.au/council/sections/waste/images/garbage_truck_lifting_bin_1.jpg

Tim C


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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Roel Schroeven

Benji York wrote:

> What I want to know is how Mangus wrote an entire message fully
> justified.  I looked for extra spaces and other cheats but only
> found a couple of superfluous exclamation marks.  Well done! He
> must be a justification wizard.  I wish I could do that too. :)

I hadn't even seen it at first, since I use a proportional font for 
reading my mail.

You haven't looked very well though: there are actually quite a lot of 
extra spaces. Still, it's nicely done indeed.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: Unicode Congruence

2005-05-30 Thread John Machin
phil top-posted
> Thanks.
> I did search that site but, wow, huge.

Searched how

1. If you use their own search box, the first hit is U+2A6D CONGRUENT 
WITH DOT ABOVE

The U2A00.pdf entry for U+2A6D does refer back to U+2245


2. The "where is my character" page also says: "You can also do a text 
search in the online Unicode  NamesList."

which gives you:

2A6DCONGRUENT WITH DOT ABOVE
x (approximately equal to - 2245)


> That page had no reference to congruence
> and the pdf did not contain the pattern
> congru.

So do your bit towards making the world a better place by e-mailing 
unicode.org and suggesting (1) that the description for 2245 be 
augmented (2) that in general where they have a character named 
" WITH " it would be a good idea to check that the 
basic  character is actually so described.


> But I'll have some better ideas how to search next
> time.
> thanx
> I used \u2245 btw

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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Fraca7
On Mon, 30 May 2005 20:56:22 +, Roel Schroeven wrote:

> You haven't looked very well though: there are actually quite a lot of 
> extra spaces. Still, it's nicely done indeed.

C-u M-q ?

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


Re: plotting with Python

2005-05-30 Thread [EMAIL PROTECTED]
We use dislin in my lab. I don't think it's GPL...

http://www.linmpi.mpg.de/dislin

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


Re: Exiting SocketServer: socket.error: (98, 'Address already in use')

2005-05-30 Thread Andrew Dalke
Magnus Lyckå wrote:
> Why doesn't my socket
> get released by the OS when I exit via my handle_error?

Hi Magnus,

  I wrote about this at
http://www.dalkescientific.com/writings/diary/archive/2005/04/21/using_xmlrpc.html

The reason for it is described at
  http://hea-www.harvard.edu/~fine/Tech/addrinuse.html

You can set the class variable "allow_reuse_address = True" in
your derived ExitableSocketServer to get the behaviour you
expect, at the expense of some problems mentioned in the
above URL.

Andrew
[EMAIL PROTECTED]

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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Arthur
On Mon, 30 May 2005 14:24:54 -0400, "Terry Reedy" <[EMAIL PROTECTED]>
wrote:

>
>"D H" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
>> Elliot Temple wrote:
>>> Hi I have two questions.  Could someone explain to me why Python is
>>> case sensitive?  I find that annoying.
>>
>> I do too.
>
>I don't.
>
>>  As you've found, the only reason is because it is,
>
>False.  As someone else already pointed out in this thread, and as some 
>said years ago when Guido brought up the subject, standard math notation 
>*is* case sensitive and some people like Python because they can directly 
>translate math expressions into Python expressions.

False.

In the sense that it is the way it is only because Guido kept it the
way it is, but he did so without acknowledging that your argument or
anyone else's argument was in the least bit pursuasive to him.

>I am annoyed by the disinformation and slander ('anti-newbie') repeated 
>indefinitely by some case-folding advocates.  Difference annoyances for 
>different folks, I guess.

I am annoyed that Guido skated while those of us vocally annoyed that
Guido could be influenced into this substanceless "newbie" issue, and
influence so many others to contemplate it with such solemnity - did
not skate as well.

Art 

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


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Benji York
Roel Schroeven wrote:
 > You haven't looked very well though: there are actually quite a lot
 > of extra spaces. Still, it's nicely done indeed.

Hmm.  I only saw doubled spaces after commas and periods.  That's
fairly standard practice, for the periods at least.  I don't know
if people regularly put two spaces after commas though.  I know I
don't.  I did spot a couple of extra quotation marks, but I guess
I can give him those. :)
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Checking for a full house

2005-05-30 Thread mwdsmith
Wow...  This is amazing, I didn't know there were so many way's of
doing this!  Thank you every one for all your suggestions.   I
particularly like the sorting counting ones.

And no, Roy, this isn't a home work assignment, at the moment all of
those contain php and java RMI.  :)

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


how to prepend string to a string?

2005-05-30 Thread flamesrock
so I know you can append a string. But how do you *prepend* a string,
as shown in the following code

#dirList = ['depth1','depth2','depth3']
#string = """position"""
#for x in len(dirList):
#   string += '>> %s'%dirList.pop()#()
#

to return
position>> depth1 >> depth2 >> depth3

rather than
position>> depth3 >> depth2 >> depth1


I really hope this feature exists =)

-thanks

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


eric3 question

2005-05-30 Thread Alexander Zatvornitskiy
Hello All!

I'am using eric3 IDE under win32 (snapshot 2005-04-10), and have a trouble. I
use this code:
print "enter q to quit, or smthing else to continue"
while not sys.stdin.readline()=="q":
smthing(else)

I can't run this code to debug in eric3. The questions are - how to fix it and
how to ask user for press a key without troubles with eric?

msvcrt.kbhit don't work also.

Thank you in advance

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


Re: how to prepend string to a string?

2005-05-30 Thread Benji York
flamesrock wrote:
> so I know you can append a string. But how do you *prepend* a string,
> as shown in the following code
> 
> #dirList = ['depth1','depth2','depth3']
> #string = """position"""
> #for x in len(dirList):
> #   string += '>> %s'%dirList.pop()#()
> #

How about string = whatever + string?

Note that recommended form is to build a list of strings and then use 
''.join(all_my_strings) to form the final result.

After saying all that, here's a better way:

dirList = ['depth1','depth2','depth3', 'position']
print ' >> '.join(dirList)
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to run functions in the background?

2005-05-30 Thread Ognjen Bezanov
Terry Reedy wrote:

>"Ognjen Bezanov" <[EMAIL PROTECTED]> wrote in message 
>news:[EMAIL PROTECTED]
>  
>
>>I need to find a way to 'fork' a function into the background yet still
>>be able to send commands to it.
>>
>>
>
>Others gave you the answer to this..
>
>  
>
>>I am writing a media player, and I have a function which plays the
>>media. I want to be able to run this function but to (at the same time)
>>be able to send commands from it (e.g. pause, play etc...)
>>
>>
>
>But for this, you might look into PyGame, which, I believe, has functions 
>like this.
>
>Terry J. Reedy
>
>
>
>  
>
I had a look into this, but have decided on pymedia, which was more
focused on well... media.

Either way thanks all of you, I have written my first threaded program,
and it does what I need it to perfectly.

The only thing i have a problem with now is how to communicate with the
thread, I need to send commands such as "play","pause" and the like to
it. someone here mentioned queues, but searching the python
documentation only have me a description of the queue object.

Is there anywhere where I can find out about queues, for people who know
python but have not had a lot of experience with threaded programs? Cheers

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


Re: How to run functions in the background?

2005-05-30 Thread Benji York
Ognjen Bezanov wrote:
> Is there anywhere where I can find out about queues, for people who know
> python but have not had a lot of experience with threaded programs? Cheers

FOLDOC to the rescue:
http://foldoc.doc.ic.ac.uk/foldoc/foldoc.cgi?queue
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Case Sensitive, Multiline Comments

2005-05-30 Thread Peter Hansen
Benji York wrote:
> Roel Schroeven wrote:
>  > You haven't looked very well though: there are actually quite a lot
>  > of extra spaces. Still, it's nicely done indeed.
> 
> Hmm.  I only saw doubled spaces after commas and periods.  That's
> fairly standard practice, for the periods at least.  I don't know
> if people regularly put two spaces after commas though.  I know I
> don't.  I did spot a couple of extra quotation marks, but I guess
> I can give him those. :)

Doubled spaces after commas are definitely not standard usage.

Doubled spaces after periods are fairly common (a holdover from 
fixed-pitch typewriters, as I recall, where the period itself takes up a 
full character width and so needs doubled space after it to make the 
sentence breaks more noticeable).

Inconsistent use of doubled spaces after periods, however, is a sign of 
a smart justification algorithm.  

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


Re: how to prepend string to a string?

2005-05-30 Thread Peter Hansen
flamesrock wrote:
> so I know you can append a string. But how do you *prepend* a string,
> as shown in the following code
> 
> #dirList = ['depth1','depth2','depth3']
> #string = """position"""
> #for x in len(dirList):
> #   string += '>> %s'%dirList.pop()#()

There's not _really_ anything wrong with this code, provided the length 
of dirList is "short" (since otherwise the performance issues of growing 
strings with += may cause trouble).  It might also be preferable to 
change from the for statement to a "while dirList:" since that doesn't 
require the unused "x" and the confusion of apparently testing the 
length of a list that is getting shorter with each iteration.

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


ANN: wxPython 2.6.0.1

2005-05-30 Thread Robin Dunn
Announcing
--

I'm pleased to announce the 2.6.0.1 release of wxPython, now available
for download at http://wxpython.org/download.php.  This release
consists mostly of bug fixes made since the 2.6.0.0 release a month
ago.


What is wxPython?
-

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

wxPython is a cross-platform toolkit. This means that the same program
will usually run on multiple platforms without modifications.
Currently supported platforms are 32-bit Microsoft Windows, most Linux
or other Unix-like systems using GTK or GTK2, and Mac OS X.


Changes in 2.6.0.1
--

Added wx.BrushFromBitmap to create a stippled brush in a single step.
Also added missing brysh style flags: wx.STIPPLE_MASK
wx.STIPPLE_MASK_OPAQUE.

wxMSW: Fix for default control colours when the system text fg colour
is not black.

wxGTK: Patch #1171754, It is now possible to have a menu item that
both has an icon and is a submenu.

wxMSW: Patch #1197009, better refreshes when windows are moved and
resized.

wxMSW: Patch #1197468.  Keeps track of pending size/position changes
in case there is more than one adjustment for a window in a single
DeferWindowPos set, then the pending values can be used for defaults
instead of current values.

Fixed the typemap that converts a Python list of strings to a
wxArrayString so it uses the wxPython default encoding.

Several docstrings added and updated.  Lots more to go.

wxMac: Strings added to the clipboard or used in DnD no longer have an
extra null character at the end.

Added wx.GetXDisplay that returns a raw swigified pointer for the X11
Display, or None for the non-X11 platforms.

wxMenu: Don't send an event when selecting an already selected radio
item.

Added wx.LaunchDefaultBrowser.

wxMSW: Fixed erroneous selection of content in wx.ComboBox when within
a wx.StaticBox.

wxMSW: Fixed alpha blitting to take into account source position.

Ensure that Python is still in an initialized state before doing any
locking or unlocking in wxPyBeginBlockThreads and wxPyEndBlockThreads
as these can be triggered after Python has been finalized in embedding
situations.

Added alternate constructors for wx.Font: wx.FontFromPixelSize,
wx.FFont, wx.FFontFromPixelSize.  See the docstrings or new api docs
for details.

Added wx.lib.hyperlink from Andrea Gavana.  It is a control like
static text that acts like a hyper-link, launching the system's
default browser in response to the clicks.

Added an optional parameter to wxversion.select that allows you to
specify that the extra components specified in the version string are
required.  For example, if you ask for "2.6-unicode" but only the ansi
version is installed then by default the ansi version will be selected
as it considered close enough since the version numbers match.  If you
want to force the options to be required then you can just add a True
parameter, like this::

 import wxversion
 wxversion.select("2.6-unicode", True)
 import wx

Tweaked wx.lib.buttons such that flat buttons (e.g. have no bevel and
a wx.BORDER_NONE style flag) paint themed backgrounds if there are
transparent areas and the parent is displaying a theme.

wxMSW:  Fix for wrong sash colour of wx.SplitterWindow in the silver
theme on XP.

Added a wx.xrc.XmlResourceHandler for the Ticker class.  See
wx/lib/ticker_xrc.py

wxSTC: Fixed CmdKeyAssign key bindings for Ctrl-Backspace.

wxMSW: Fixed a bug in wx.TextCtrl where all the lines were being used
to calculate the best size, instead of using a reasonable limit.

XRCed: Use wx.GetDefaultPyEncoding/wx.SetDefaultPyEncoding for
changing active encoding.  Fixed pasting siblings (Ctrl key pressed
while pasting).

wx.lib.filebrowsebutton: Bug fix from Chad Netzer for when
self.history is None.

wx.ogl: Patch from Davide Salomoni that adds an optional point
parameter to LineShape.InsertLineControlPoint allowing one to
optionally specify where the new control point has to be drawn.

wxMSW: setting foreground colour for wx.CheckBox now works when using
XP themes.

More updates to the docview library modules and sample apps from the
ActiveGrid folks.  Their sample IDE is now able to integrate with
Subversion.

wx.grid.Grid:  Ensure that the grid gets the focus when it is
left-clicked.  Note that if you have custom widgets that handle the
EVT_LEFT_DOWN event but do not call event.Skip() then you will
probably want to add a call to self.SetFocus in the event handler.

wxGTK:  Add wxSTAY_ON_TOP support [Patch 1206023]

wx.TreeCtrl:  wx.EVT_TREE_ITEM_MENU event made consistent on all
platforms.  The location of the click or the item is included in the
event as well.

wxGTK: Setting background col

Re: how to prepend string to a string?

2005-05-30 Thread Kent Johnson
flamesrock wrote:
> so I know you can append a string. But how do you *prepend* a string,
> as shown in the following code
> 
> #dirList = ['depth1','depth2','depth3']
> #string = """position"""
> #for x in len(dirList):
> #   string += '>> %s'%dirList.pop()#()
> #
> 
> to return
> position>> depth1 >> depth2 >> depth3

ISTM the problem is not prepending, but getting the elements of dirList in the 
order you want. If 
you iterate over the list normally you get the desired result:
dirList = ['depth1','depth2','depth3']
string = """position"""
for x in dirList:
string += '>> %s'% x

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


Finite Element Solver for Python?

2005-05-30 Thread Hsuan-Yeh Chang
Dear All,

Anyone knows a good Finite Element Solver for python programer?

Thanks!

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


Re: Finite Element Solver for Python?

2005-05-30 Thread Robert Kern
Hsuan-Yeh Chang wrote:
> Dear All,
> 
> Anyone knows a good Finite Element Solver for python programer?

google("finite element python")

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
  Are the graves of dreams allowed to die."
   -- Richard Harter

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


wxTextCtrl problem

2005-05-30 Thread austin
I produced 5 wxTextCtrl.
My program is to let the user enter the serial number.
Each wxTextCtrl has 4 maxlength.
My ideal is
if the user enter 4 digits on first wxTextCtrl, and the program will move
the cursor to the second wxTextCtrl.
I checked the wxTextCtrl::SetInsertingPoint.
But this function is only move on itself.
For exammple,

xxx




self.tctrl_1 = wxTextCtrl(..)
self.tctrl_2 = wxTextCtrl(..)

self.Bind(EVT_TEXT,self.OnTextProcessing_1,self.tctrl_1)
self.Bind(EVT_TEXT,self.OnTextProcessing_2,self.tctrl_2)




def OnTextProcessing_1(self,evt):
 if len(evt.GetString())==4:
  self.tctrl_2.SetInsertionPoint(0)

xxx


The code "self.tctrl_2.SetInsertingPoint(0)" doesn't work.
But if i change to "self.tctrl_1..." works fine.

So what's problem?



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


a newbie question about debug

2005-05-30 Thread flyaflya
I use pdb.set_trace() to debug code.the Debugger Commands "enable" and 
"disable" need argumet -- "breakpoint number",but I can't  find any 
information about it,so how to can i get the breakpoint number? I think 
"disable","enable" are very useful commands...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: finding indices in a sequence of parentheses

2005-05-30 Thread Steven Bethard
Raymond Hettinger wrote:
> [Steven Bethard]
> 
>>>I have a list of strings that looks something like:
>>>lst = ['0', '0', '(*)', 'O', '(*', '*', '(*', '*))', '((*', '*)', '*)']
> 
>  . . .
> 
>>>I want the indices:
>>>(2, 2), (4, 7), (6, 7), (8, 9) and (8, 10)
> 
> opener_stack = []
> for i, elem in enumerate(lst):
> for c in elem:
> if c == '(':
> opener_stack.append(i)
> elif c == ')':
> print opener_stack.pop(), i
> 

Thanks Raymond, this is definitely an elegant solution. It was also easy 
to add all the error checking I needed into this one.  For the curious, 
my final solution looks something like:

def indices(lst):
 stack = []
 for i, elem in enumerate(lst):
 for c in elem:
 if c == '(':
 stack.append(i)
 elif c == ')' and not stack:
 raise Exception('")" at %i without "("' % i)
 elif c == ')':
 yield stack.pop(), i
 elif c == 'O' and stack:
 raise Exception('"O" at %i after "(" at %i' %
 (i, stack[-1]))
 elif c == '*' and not stack:
 raise Exception('"*" at %i without "("' % i)
 if stack:
 raise Exception('"(" at %r without ")"' % stack)

Thanks again!

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


Re: prime number

2005-05-30 Thread Dale Hagglund
lostinpython> I'm having trouble writing a program that figures
lostinpython> out a prime number.  Does anyone have an idea on how
lostinpython> to write it?  

[I can't quite tell from your posts what your level of programming
knowledge is, so I've aimed low.  If this was wrong, please accept my
apologies. --rdh]

It's not quite clear precisely what the problem is. Do you want to
find all primes less than some number N, or find the prime
factorization of some input number, or something else altogether?  Are
there any other constraints?  Ie, does the program have to be
recursive?

I'm going to assume that you want to find all primes less than N, and
that are no constraints on the form of the program.  

First, pretend you have a function called "is_prime".  It will look
something like this:

def is_prime(n):
# return True if n is prime, False otherwise
# magic goes here

If we had this function, the our main program would look something
like this:

N = 20
for n in range(1, N+1):
if is_prime(n):
   print n

NOTE: range(1,N+1) returns a list of numbers from 1 to N inclusive.

The question now is how to fill in the missing part of is_prime.  In
your original post, you noted that n>2 is prime if no number between 2
and sqrt(n) inclusive divides into n evenly.

This tells us that we have to test a list of possible factors for
divisibility into n.  Ignoring, for a little while, how we figure out
the possible factors, we can now expand is_prime as follows:

def is_prime(n):
# return 1 if n is prime, 0 otherwise
from math import sqrt
for i in possible_factors:
# if i divides n, n isn't prime
# if no i divided into n, ie, we fell out of the loop, 
# n is prime

The possible factor i divides into n if n % i == 0.  Once we've
decided that n is or isn't prime, we can just return True or False
respectively.  Adding these details:

def is_prime(n):
# return 1 if n is prime, 0 otherwise
from math import sqrt
for i in possible_factors:
if n % i == 0:
return True
return False   

The final step is to figure out the list of possible factors.  By the
definition, this is the list of integers from 2 to the integer value
of sqrt(n), inclusive.  To get this list, we can use the range
function again, assuming that sqrt(n) to compute the square root for
us.  The list of possible factors is given by

range(2, int(sqrt(n)) + 1)

The final trick to is to get the definition of sqrt.  It turns out
that this function is defined in the math module.  Adding the bit of
syntax needed to access the sqrt function, we have:

def is_prime(n):
# return 1 if n is prime, 0 otherwise
from math import sqrt
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True

Put together with the main program above, this will print out a list
as follows:

1
2
3
5
7
11
13
17
19

However, there's a slight problem here.  By definition, 1 is not a
prime.  We could fix this a couple of ways.  Either we could change
the main program not to start its range with 1, or we can fix
is_prime.  The latter is simple:

def is_prime(n):
# return 1 if n is prime, 0 otherwise
from math import sqrt
if n == 1:
return False
for i in range(2, int(sqrt(n)) + 1):
if n % i == 0:
return False
return True

Another algorithm mentioned in the followups to your posting is the
Sieve of Eratosthenes, named for its ancient Greek discoverer.  You
can find a description of the Sieve in many places on the web.  Trying
to implement it might be a good next step.

Dale.

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


Re: prime number

2005-05-30 Thread Dale Hagglund
Sigh ... one of my intermediate versions of is_prime() returns True if
the n is *not* prime, and false otherwise.  The final version is
correct, though.

Dale.

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


  1   2   >