Re: How do i read just the last line of a text file?

2005-05-29 Thread John Machin
Chris F.A. Johnson wrote:

 
 file = open(argv[1])  ## Open the file given on the command line
 all_lines = file.readlines()  ## Read all the lines

I see your shadowing and raise you one obfuscation:

open = file(argv[1])  ## File the open given on the command line
all_lines = open.readlines()  ## Read all the lines


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


SWIG std::string passing

2005-05-29 Thread Leonard J. Reder
Hello,

I have been trying to get this simple call to work with a SWIG 
interface.  The problem is I do not know how to pass a const char * or a 
std::string  in python to SWIG wrapped code.  I tried several of the 
*.i libraries at http://www.swig.org/Doc1.3/Library.html.  Most notably 
the std_string.i And get the following:

  w.SetDestFilename(test.bmp)
Traceback (most recent call last):
   File stdin, line 1, in ?
   File 
/home/soa/dev/users/reder/Dshell++Pkg-reder01/lib/PYTHON/Dspace/Dnoise_Py.py, 
line 1340, in SetDestFilename
 def SetDestFilename(*args): return 
_Dnoise_Py.WriterBMP_SetDestFilename(*args)
TypeError: argument number 2: a 'std::string *' is expected, 
'str(test.bmp)' is received

The C++ method is:

void WriterBMP::SetDestFilename (const std::string filename)

This should be easy to pass the filename to?  Do you have an example? 
What do I add to the *.i file?

Thanks for any and all replies,

Len

-- 
===
Leonard J. Reder
Home office email : [EMAIL PROTECTED]
Lab email : [EMAIL PROTECTED]
Lab web page  : http://reder.jpl.nasa.gov
===


-- 
===
Leonard J. Reder
Home office email : [EMAIL PROTECTED]
Lab email : [EMAIL PROTECTED]
Lab web page  : http://reder.jpl.nasa.gov
===
-- 
http://mail.python.org/mailman/listinfo/python-list


need help of RE

2005-05-29 Thread cheng
hi all
a string like

(word1  (Word2|woRd3))

how can i use the re to split it to

['word1', 'word2', 'word3']

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


Re: the problem with cgi

2005-05-29 Thread EP
 Has anyone seen that problem with running a python cgi script in a
 server?
 It takes you to myspace.com/redmartian or something. Anyway, does
 anyone know when this problem will be fixed?


Xah Lee is working on it.

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


Re: How do i read just the last line of a text file?

2005-05-29 Thread Chris F.A. Johnson
On Sun, 29 May 2005 at 05:57 GMT, John Machin wrote:
 Chris F.A. Johnson wrote:
 
 file = open(argv[1])  ## Open the file given on the command line
 all_lines = file.readlines()  ## Read all the lines
 
 I see your shadowing and raise you one obfuscation:

   ;)

 open = file(argv[1])  ## File the open given on the command line
 all_lines = open.readlines()  ## Read all the lines

   Such verbosity! (I excuse mine on the grounds that it was my first
   attempt at a Python program.)

all_lines = file(argv[1]).readlines()

   And to answer the question in the subject line:

last_line = file(argv[1]).readlines()[-1]

   Both of which assume from sys import argv.


   Now I have to get serious and forget those bad habits.

-- 
Chris F.A. Johnson http://cfaj.freeshell.org
==
Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
http://www.torfree.net/~chris/books/cfaj/ssr.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need help of RE

2005-05-29 Thread Elliot Temple

On May 29, 2005, at 12:39 AM, cheng wrote:

 hi all
 a string like

 (word1  (Word2|woRd3))

 how can i use the re to split it to

 ['word1', 'word2', 'word3']

Could you be more exact about what the string is like?  Does it  
literally contain the characters '' and '|' ?  If so, just split at  
them.

-- Elliot Temple
http://www.curi.us/


---
[This E-mail scanned for viruses by Declude Virus]

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


Re: need help of RE

2005-05-29 Thread cheng
im sorry, my engilsh is not vell well,

the string not only contain '' and '|' and it can be anyting

i just want to split out the whole word inside the string

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


Re: need help of RE

2005-05-29 Thread cheng
i try

query = query.lower()
print re.split(r'\W+',theString)

the reslut is :
['', 'word1', 'word2', 'word3', '']

how can i fix the statment to get 

['word1', 'word2', 'word3']

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


Re: need help of RE

2005-05-29 Thread cheng
i try

theString= theString.lower()
print re.split(r'\W+',theString)

the reslut is :
['', 'word1', 'word2', 'word3', '']

how can i fix the statment to get 

['word1', 'word2', 'word3']

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


Re: need help of RE

2005-05-29 Thread Elliot Temple

On May 29, 2005, at 12:57 AM, cheng wrote:

 im sorry, my engilsh is not vell well,

 the string not only contain '' and '|' and it can be anyting

 i just want to split out the whole word inside the string

If the string could be anything, how do you know where the words are?

If it's whitespace that separates words, try out str.split()

-- Elliot Temple
http://www.curi.us/


---
[This E-mail scanned for viruses by Declude Virus]

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


Re: need help of RE

2005-05-29 Thread tiissa
cheng wrote:
 im sorry, my engilsh is not vell well,

That's alright, you could have been french. ;)

 the string not only contain '' and '|' and it can be anyting
 
 i just want to split out the whole word inside the string

Look at the example for split function of re module in the doc [1].

In short:

  import re
  s=(word1  (Word2|woRd3))
  re.split(\W+,s)
['', 'word1', 'Word2', 'woRd3', '']
  [w.lower() for w in re.split(\W+,s) if w != '']
['word1', 'word2', 'word3']
 


[1]http://python.org/doc/lib/node114.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need help of RE

2005-05-29 Thread Chris F.A. Johnson
On Sun, 29 May 2005 at 07:39 GMT, cheng wrote:
 hi all
 a string like
 
 (word1  (Word2|woRd3))
 
 how can i use the re to split it to
 
 ['word1', 'word2', 'word3']

This splits the string on one or more occurrences of any character
that is not alphanumeric: 

import re
str = (word1  (Word2|woRd3))
s = re.sub([^a-zA-Z0-9]+, ,str).split()

-- 
Chris F.A. Johnson http://cfaj.freeshell.org
==
Shell Scripting Recipes: A Problem-Solution Approach, 2005, Apress
http://www.torfree.net/~chris/books/cfaj/ssr.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need help of RE

2005-05-29 Thread cheng
thx for help..i got it now :)

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


Re: need help of RE

2005-05-29 Thread vincent wehren

cheng [EMAIL PROTECTED] schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
| hi all
| a string like
|
| (word1  (Word2|woRd3))
|
| how can i use the re to split it to
|
| ['word1', 'word2', 'word3']
|

import re
s = (word1  (Word2|woRd3)
parts = re.split('\W+', s)
print [p for p in parts if p]

--

Vincent Wehren 


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


Re: need help of RE

2005-05-29 Thread John Machin
cheng wrote:
 hi all
 a string like
 
 (word1  (Word2|woRd3))
 
 how can i use the re to split it to
 
 ['word1', 'word2', 'word3']
 

OK, so you know about the re module.

Look in the manual: there's a module-level function called
split, with an example similar to yours. Did you try that?
Let's do it now:

  import re
  text = (word1  (Word2|woRd3)).lower()
# you seem to want downshifting ...
  re.split(r\W+, text)
['', 'word1', 'word2', 'word3', '']
 

Hmmm ... near, but not exactly what you want. We need to throw away 
those empty strings, which will appear if you have non-word characters 
at the ends of your text.

Two ways of doing that:

  filter(None, re.split(r\W+, text))
['word1', 'word2', 'word3']

or

  [x for x in re.split(r\W+, text) if x]
['word1', 'word2', 'word3']

Forget about filter. Read about list comprehensions and generator 
expressions -- they are more general and powerful.

Cheers,
John

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


Re: Xml writing in Python and verifying using XSD

2005-05-29 Thread Prashanth Ellina


Diez B. Roggisch wrote:

 Use StringIO to capture the output of your writings, and use a
 xsd-validating parser (not sure which one, but google should help) to
 reread that. Or a temporary file.

Thank you very much. I'll try that.

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


Creating dict from keys and values

2005-05-29 Thread Dirkjan Ochtman
Hi there,

I'm looking for an intuitive way of creating a dict from what the 
dict.keys() and dict.values() will return (two lists).

Currently, I'm using this code:

 d = {}
 for i in range(len(data)):
   d[header[i]] = data[i]

But this feels kind of inelegant. So: is there a better way?

TIA,

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


ControlDesk Automation in dSpace

2005-05-29 Thread Crispen
I am having trouble using the ControlDesk automation libraries in
python. In particluiar running the automation in a thread. My code is
as follows, is keeps coming up with this strange error. Any help would
be great.

Crispen

import cdacon
from time import sleep
from cdautomationlib import *

def Auto():
   sleep(0.5)
   # triggering://dSPACE NumericInput Control_1:WriteData
   Instrumentation().ConnectionController.DisableSystemPoll()
   Instrumentation().Layouts.Item(c:\\users\\matlab
files\\triggering.lay).Instruments.Item(dSPACE NumericInput
Control_1).Value = 1.
   Instrumentation().ConnectionController.ProcessAnimationEvent
(triggering://dSPACE NumericInput Control_1,WriteData)
   Instrumentation().ConnectionController.EnableSystemPoll()
   sleep(0.5)
   # triggering://dSPACE NumericInput Control_1:WriteData
   Instrumentation().ConnectionController.DisableSystemPoll()
   Instrumentation().Layouts.Item(c:\\users\\matlab
files\\triggering.lay).Instruments.Item(dSPACE NumericInput
Control_1).Value = 0.0

Instrumentation().ConnectionController.ProcessAnimationEvent(triggering://dSPACE
NumericInput Control_1,WriteData)
 Instrumentation().ConnectionController.EnableSystemPoll()
   sleep(0.5)
   # triggering://dSPACE NumericInput Control:WriteData
   Instrumentation().ConnectionController.DisableSystemPoll()
   Instrumentation().Layouts.Item(c:\\users\\matlab
files\\triggering.lay).Instruments.Item(dSPACE NumericInput
Control).Value = 1.
   Instrumentation().ConnectionController.ProcessAnimationEvent
(triggering://dSPACE NumericInput Control,WriteData)
   Instrumentation().ConnectionController.EnableSystemPoll()
   sleep(0.5)
   # triggering://dSPACE NumericInput Control:WriteData
   Instrumentation().ConnectionController.DisableSystemPoll()
   sleep(0.5)
   Instrumentation().Layouts.Item(c:\\users\\matlab
files\\triggering.lay).Instruments.Item(dSPACE NumericInput
Control).Value = 0.0

Instrumentation().ConnectionController.ProcessAnimationEvent(triggering://dSPACE
NumericInput Control,WriteData)
   Instrumentation().ConnectionController.EnableSystemPoll()
   sleep(0.5)
   Instrumentation().Layouts.Item(c:\\users\\matlab
files\\triggering.lay).Activate()
   sleep(0.5)
   Instrumentation().Layouts.Item(c:\\users\\matlab
files\\triggering.lay).Activate()


thread.start_new_thread(Auto,())

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


Re: Creating dict from keys and values

2005-05-29 Thread Just
In article [EMAIL PROTECTED],
 Dirkjan Ochtman [EMAIL PROTECTED] wrote:

 Hi there,
 
 I'm looking for an intuitive way of creating a dict from what the 
 dict.keys() and dict.values() will return (two lists).
 
 Currently, I'm using this code:
 
  d = {}
  for i in range(len(data)):
  d[header[i]] = data[i]
 
 But this feels kind of inelegant. So: is there a better way?

   d = dict(zip(header, data))

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


Re: Copy paste in entry widget

2005-05-29 Thread Michael Onfrek
I need it for Linux, so far only TkInter used.

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


Re: Getting value of radiobutton trouble

2005-05-29 Thread VK
Philippe C. Martin wrote:
 PS: Since your starting with TKinter, and although I do not know what your
 goal is, I suggest you take a look at wxPython: it is _wonderfull_ ! (no
 offence to TCL/TK)
 
 Regards,
 
 Philippe
 
 
 
 
 
 
 VK wrote:
 
 
Philippe C. Martin wrote:

Hi,

I think your second call to Tk() does it: this works although the look is
different:


from Tkinter import *
class GetVariant:
 def __init__(self):
 self.root = Tk()
 self.mainframe = Frame(self.root,bg=yellow)
 self.mainframe.pack(fill=BOTH,expand=1)

 self.firstframe = Frame(self.mainframe,bg=red)
 self.firstframe.pack(side=BOTTOM,expand=1)

 global v
 v = StringVar()
 self.radiobutton = Radiobutton(self.firstframe,text= Variant
1, variable=v, value=Variant 1)
 self.radiobutton.pack(side=TOP,anchor=W)
 self.radiobutton.select()
 self.radiobutton = Radiobutton(self.firstframe,text= Variant
2, variable=v, value=Variant 2)
 self.radiobutton.pack(side=TOP,anchor=W)
 self.radiobutton = Radiobutton(self.firstframe,text= Variant
3, variable=v, value=Variant 3)
 self.radiobutton.pack(side=TOP,anchor=W)



 self.secondframe = Frame(self.mainframe,bg=blue)
 self.secondframe.pack()
 self.var = Button(self.secondframe,text=What
Variant,command=self.call)
 self.var.pack(expand=1,side=BOTTOM)



 def call(self):
 self.variant = v.get()
 print 'Input = %s' % self.variant

class OneButton:
 def __init__(self):
 self.root = Tk()
 Button(self.root,text=click me,command=self.getvar).pack()
 def getvar(self):
 a=GetVariant()

d = OneButton()
d.root.mainloop()




VK wrote:



Hi!
What I'm missing in following code? Cannot get the values of
radiobuttons. Starting only one class (GetVariant), it works. When I put
two classes together, it doesn't.
Regards, VK


from Tkinter import *

class GetVariant:
def __init__(self):
self.root = Tk()
self.mainframe = Frame(self.root,bg=yellow)
self.mainframe.pack(fill=BOTH,expand=1)

self.firstframe = Frame(self.mainframe,bg=red)
self.firstframe.pack(side=BOTTOM,expand=1)

global v
v = StringVar()
self.radiobutton = Radiobutton(self.firstframe,text= Variant
1, variable=v, value=Variant 1)
self.radiobutton.pack(side=TOP,anchor=W)
self.radiobutton.select()
self.radiobutton = Radiobutton(self.firstframe,text= Variant
2, variable=v, value=Variant 2)
self.radiobutton.pack(side=TOP,anchor=W)
self.radiobutton = Radiobutton(self.firstframe,text= Variant
3, variable=v, value=Variant 3)
self.radiobutton.pack(side=TOP,anchor=W)



self.secondframe = Frame(self.mainframe,bg=blue)
self.secondframe.pack()
self.var = Button(self.secondframe,text=What
Variant,command=self.call)
self.var.pack(expand=1,side=BOTTOM)



def call(self):
self.variant = v.get()
print 'Input = %s' % self.variant

class OneButton:
def __init__(self):
self.root = Tk()
Button(self.root,text=click me,command=self.getvar).pack()
def getvar(self):
a=GetVariant()

d = OneButton()
d.root.mainloop()


Sorry, but I don't get it. There is no deference between my code and
your answer. I'm beginner...
 
 

Thanks for your help! Toplevel made the job.
Reg. VK
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of doing this?

2005-05-29 Thread Steven D'Aprano
On Sat, 28 May 2005 13:24:19 +, Michael wrote:

 Hi,
 I'm fairly new at Python, and have the following code that works but isn't
 very concise, is there a better way of writing it?? It seems much more
 lengthy than python code i have read. :-)
 (takes a C++ block and extracts the namespaces from it)


Does it work? If Yes, then if it works, don't fix it.

Is it fast enough? If Yes, then don't optimise prematurely.

Does it do everything you need it to do? If Yes, then know when to stop
programming.

Is it written in good Python style? If Yes, then leave it alone.

The last one is the most difficult, because nobody agrees what good
Python style is. A lot of it depends on who is going to be reading your
code. Personally, I worry about folks who try to turn every piece of code
into a one-liner. If you want to write perl, write perl. Just because you
can write something as a nested list comprehension doesn't mean you should.

Having said that, I'll make some stylistic suggestions:
 
 def ExtractNamespaces(data):
  print(Extracting Namespaces)

print is a statement, not a function. The brackets are syntactically
correct, but pointless. Remove them.

  p = re.compile( 'namespace (?Pname[\w]*)[\n\t ]*{')
 
  subNamespaces = []
 
  newNS = p.search(data)
  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.

See http://www.python.org/doc/essays/styleguide.html for Guido's
suggestions.

   print \t + newNS.group(name)
 
   OPCount = 1
   Offset = newNS.end()
   while(OPCount  0):
if( data[Offset] == } ):

See above comment about whitespace inside brackets.

More importantly, you don't need the brackets at all. You can write:

if data[Offset] == }:

which is less visually confusing. The only time I use brackets in an if
statement is to clarify complex Boolean expressions, eg

if myFlag and ((somevalue == 3) or (num_fibberts != 1)):

Otherwise, drop the brackets.

 OPCount = OPCount -1;

You aren't writing Pascal or C now, so you don't need the semi-colon. The
semi-colon isn't wrong, as such, since Python allows you to put multiple
statements on a single line separated with semi-colons, but it isn't
recommended and will give away the fact that you are (1) a newbie and (2)
not really comfortable with Python.

In more recent versions of Python, you can also write that as OPCount -= 1

elif( data[Offset] == { ):
 OPCount = OPCount + 1;
Offset = Offset+1;

Again, drop the brackets from the elif statement and the semi-colons. Not
the colons, they are required!

   #Extract Data:

More comments! Comments are good. There are those who claim that you
should write more comments than code. I don't quite agree with that, but
more detailed comments would not go astray.

   newNSData = data[newNS.end():Offset-1] 
   data = data[0:newNS.start()] + data[Offset:]
   newNamespace = [newNS.group(name), newNSData];
   subNamespaces.append(newNamespace)

By now you should be sick of me telling you not to use semi-colons.

   #Perform NewSearch
   newNS = p.search(data)
  return [subNamespaces,data]

A single space after commas helps make the phrase more readable.

Other than those stylistic comments, and the need for more comments, it
looks good to me.


-- 
Steven


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


Re: Is there a better way of doing this?

2005-05-29 Thread Fredrik Lundh
Steven D'Aprano wrote:

 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, so while(newNS) is bad in more than one way.

/F



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


Re: Help with choice of suitable Architecture

2005-05-29 Thread Cameron Laird
In article [EMAIL PROTECTED],
Paul Rubin  http://[EMAIL PROTECTED] wrote:
.
.
.
good reason exception.  I dunno about suggest.  I do see that
.
.
.
URL: http://labs.google.com//suggestfaq.html , to ensure we're
all talking about the same thing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of doing this?

2005-05-29 Thread Cyril BAZIN
Hi,

I don't know very well what you want to do, but if you want to parse
c++, take a look at GCC-XML python (http://www.gccxml.org) and the
python binding (http://pygccxml.sourceforge.net/). These tools
translate c++ code to XML. Then, you can parse xml with your favorite
tools and find the namespaces for example...

Your code don't seem very pythonic, and it seems there is a bug...
For example what's append if a comment contains a '}' inside a
namesapce? (or a string contains a '{' ? 

I think you should better use most appropriate tools to do this kind of jobs...

Cyril
On 5/28/05, Michael [EMAIL PROTECTED] wrote:
Hi,I'm fairly new at Python, and have the following code that works but isn'tvery concise, is there a better way of writing it?? It seems much morelengthy than python code i have read. :-)(takes a C++ block and extracts the namespaces from it)
def ExtractNamespaces(data): print(Extracting Namespaces) p = re.compile( 'namespace (?Pname[\w]*)[\n\t ]*{') subNamespaces = [] newNS = p.search(data) while( newNS ):
print \t + newNS.group(name)OPCount = 1Offset = newNS.end()while(OPCount  0): if( data[Offset] == } ):OPCount = OPCount -1; elif( data[Offset] == { ):
OPCount = OPCount + 1; Offset = Offset+1;#Extract Data:newNSData = data[newNS.end():Offset-1]data = "" + data[Offset:]newNamespace = [newNS.group(name), newNSData];
subNamespaces.append(newNamespace)#Perform NewSearchnewNS = p.search(data) return [subNamespaces,data]--
http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Trying to understand pickle.loads withou class declaration

2005-05-29 Thread Sbastien Boisgrault
Even

class A:
pass

should do the trick. Only the instance attributes are saved by a
pickle,
not the methods or the class itself. The unpickler tries to merge the
saved data and the class/method info that is not saved to recreate
the fully functional instance... but of course this info should still
be available. The unpickler will even import the class from the
appropriate module if necessary.

If you want your unpickler to manufacture a class for you when
it is not available, you may use the gnosis xml pickler with the
appropriate security (paranoia) level.

http://gnosis.cx/download/gnosis/xml/pickle/

Cheers,

Seb

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


Re: the problem with cgi

2005-05-29 Thread Ivan Van Laningham
Hi All--

EP wrote:
 
  Has anyone seen that problem with running a python cgi script in a
  server?
  It takes you to myspace.com/redmartian or something. Anyway, does
  anyone know when this problem will be fixed?
 
 Xah Lee is working on it.
 

Oh, that's reassuring.  Does he have his tinfoil hat on?

Metta,
Ivan

PS:  Sorry, I meant, Does he have his fucking tinfoil hat on?
--
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a better way of doing this?

2005-05-29 Thread Roman Yakovenko
On 5/29/05, Cyril BAZIN [EMAIL PROTECTED] wrote:
 Hi,
  
  I don't know very well what you want to do, but if you want to parse c++,
 take a look at GCC-XML python (http://www.gccxml.org) and the python
 binding (http://pygccxml.sourceforge.net/). These tools
 translate c++ code to XML. Then, you can parse xml with your favorite tools
 and find the namespaces for example...

Small correction: pygccxml does not translate C++ to xml. The purpose
of pygccxml is to read file generated by GCC-XML and provide simple
framework to navigate C++ declarations using python classes.

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


Re: first release of PyPy

2005-05-29 Thread Anton Vredegoor
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 ;)

Since PyPy is covering new territory it seemed important to provide new
ideas so that they have something to look forward to and will not fall
asleep at the entrance of the new area. Maybe I failed with the new
part but at least I tried :-)

Whether they are supposed to solve the halting problem or if that can
reasonably be expected I don't now either. Is it ethical to send people
on an impossible mission in order to harvest the spinoff? Some evil
genius might have created this universe in order to do just that!

However, people posting code to this list are often reminded of other
algorithms (are you sorting this list? why not use quicksort?) so it
seems possible at least for humans to guess the intentions of another
coder sometimes, and provide better code.

Every time something is described at a higher level (these levels
cannot be found within the original system but must be created by a
leap of the imagination or by divine intervention) there seem to be
ways to remove superfluous things and be more effective even at the
lower level.

Anton

'answering all questions destroys the universe?'

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


nice OOP training problem

2005-05-29 Thread Anton Vredegoor
I found this on the web:

http://www.setgame.com/set/puzzle_frame.htm

and I'm currently trying to develop a script that models this space and
that gives a nice graphic display. Also developing a solver for this or
larger spaces looks interesting. I'm not asking for assistance, it just
looks like some interesting programming experience and why should there
be all work and no play?

So code solving any part of this problem (the grafics) or the solver
(find all solutions) would be interesting.

Anton

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


Re: how to convert string to list or tuple

2005-05-29 Thread Steven D'Aprano
On Thu, 26 May 2005 19:53:38 +0800, flyaflya wrote:

 a = (1,2,3)
 I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',', 
 '2', ',', '3', ')') not (1,2,3)

Others have already given some suggestions. Here are some others.

You didn't say where the input string a came from. Do you control
it? Instead of using:

String_Tuple_To_Real_Tuple((1,2,3))

can you just create the tuple in the first place?

a = (1, 2, 3)

Second suggestion: if you know that the input string will ALWAYS be in the
form (1,2,3) then you can do this:

a = (1,2,3)
a = a[1:-1]  # deletes leading and trailing parentheses
a = a.split(,)  # creates a list [1, 2, 3] (items are strings)
a = [int(x) for x in a]  # creates a list [1, 2, 3] (items are integers)
a = tuple(a)  # coverts to a tuple

or as a one-liner:

a = (1,2,3)
a = tuple([int(x) for x in a[1:-1].split(,)])

Best of all, wrap your logic in a function definition with some
error-checking:

def String_Tuple_To_Real_Tuple(s):
Return a tuple of ints from a string that looks like a tuple.
if not s:
return ()
if (s[0] == () and s[-1] == )):
s = s[1:-1]
else:
raise ValueError(Missing bracket(s) in string.)
return tuple([int(x) for x in s.split(,)])


Hope this helps,


-- 
Steven.


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


2D vector graphics Problem

2005-05-29 Thread Karl Max
Hi all,

I'm new here. Name's Max from tuscany, and I don't speak english very well 
:-) I am not veteran at coding, I am most like an artisan coder since 
commodore 64 times.

Now the problem:
I would like to have a little 2d engine to calculate and trace segments and 
poly's and their collisions, rotations and trasformations. I didn't 
understand too much in tutorials (you're all high school coders, well 
informed in maths and programming theory!!! :-))) so I took my old school 
books on Cartesian space and had a refresh. Proceeding in this not too 
optimized way of coding my needs, I took down some generic classes to 
describe primitive objects in space (vertexes, segments, poly's etc...).

Now I try to make a point rotate around another point.
Here's my piece of code:

def rotate(self, w):
 # This method belongs to the class Vertex
 # w = angle expressed in radiants
 x, y = self.coords
 xRel, yRel = self.relPoint # The rotation should be relative to this
 sin, cos = math.sin(w), math.cos(w)
 x = x * cos - y * sin - xRel * cos + yRel * sin + xRel
 y = x * sin + y * cos - xRel * sin - yRel * cos + yRel
 self.coords = (x,y)

I know the style isn't professional, and if you should have some piece of 
advice, you're welcome... but that's not the question.
When I render it graphically, using pygame 1.6, the point tends to fall 
towards the center of rotation round after round. I mean if I have a loop 
rotating the point by a fixed angle, the point is like attracted by the 
center every round it does, like in a vortex.
I think it depends from float representation inside python, but I have no 
clear idea about how to resolve it. Maybe should I use Decimal module? Or is 
there any trick on this subject (2D vector graphics?) that I can't even 
imagine?
Thanks you all,
 Max 


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


Newbie learning OOP

2005-05-29 Thread LenS
Trying to learn OOP concepts and decided to use Python for this
purpose.  I have coded the following CLASS and it seems to work fine.
Any comments on the code or suggestions would be appreciated.

The class let you take a person's name and split it up into first last
and middle.  The class defaults to the assumption that the name will be
passed in as a string in first last and middle order however you can
set the format attribute to take last first and middle order. You can
then get a string back in and opposite order.

class names:
def __init__(self, format = F):
self.format = format

def namesplit(self, name):
if self.format == F:
self.namelist = name.split()
self.first = self.namelist[0]
self.init = self.namelist[1]
self.last = self.namelist[2]
else:
self.namelist = name.split()
self.first = self.namelist[1]
self.init = self.namelist[2]
self.last = self.namelist[0]

return self.first, self.init, self.last

def fjoin(self):
self.namestring = self.first + ' ' + self.init + ' ' +
self.last

def ljoin(self):
self.namestring = self.last + ' ' + self.first + ' ' +
self.init


Any comments appreciated.

Len Sumnler

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


Re: Is there a better way of doing this?

2005-05-29 Thread Duncan Booth
Michael wrote:

 I'm fairly new at Python, and have the following code that works but
 isn't very concise, is there a better way of writing it?? It seems
 much more lengthy than python code i have read. :-)
 (takes a C++ block and extracts the namespaces from it)

Yes, there is a better way to write the code, but I'm afraid that the 
better way will be much longer rather than shorter. Your code is trying to 
pick up a complete C++ block by counting the opening and closing braces, 
but this will break as soon as you have a brace character inside a string 
or a comment.

The better solution would be to use a full blown parser, or at least a 
lexer which recognises comments and strings. There are several parsing 
packages for Python, you might like to look at Ply 
(http://www.dabeaz.com/ply/) since that comes with a sample lexer for Ansi 
C, and if you added some extra keywords (such as namespace) you could then 
just treat your input as a token stream.

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


Re: Copy paste in entry widget

2005-05-29 Thread VK
Michael Onfrek wrote:
 Hi,
 is copy, paste, cut of selection possible in entry widget? Docs say
 selection must be copied by default, in my programm it doesn't work.
 Regards, M.O.
 
Hear it is

 def paste(self):
 self.entry.event_generate('Control-v')
 def cut(self):
 self.entry.event_generate('Control-x')
 def copy(self):
 self.entry.event_generate('Control-c')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to understand pickle.loads withou class declaration

2005-05-29 Thread Philippe C. Martin
Thanks,

Philippe


Sbastien Boisgrault wrote:

 Even
 
 class A:
 pass
 
 should do the trick. Only the instance attributes are saved by a
 pickle,
 not the methods or the class itself. The unpickler tries to merge the
 saved data and the class/method info that is not saved to recreate
 the fully functional instance... but of course this info should still
 be available. The unpickler will even import the class from the
 appropriate module if necessary.
 
 If you want your unpickler to manufacture a class for you when
 it is not available, you may use the gnosis xml pickler with the
 appropriate security (paranoia) level.
 
 http://gnosis.cx/download/gnosis/xml/pickle/
 
 Cheers,
 
 Seb

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

Entry scroll doesn't work

2005-05-29 Thread VK
Hi!
Can entry widget be scrolled?
VK

TypeError: xview() takes exactly 2 arguments (4 given)

Code:



from Tkinter import *
class ScrollEntry:
 def __init__(self):
 self.root = Tk()
 self.scrollbar = Scrollbar(self.root,orient=HORIZONTAL,)
 self.entry = Entry(self.root,xscrollcommand=self.scrollbar.set)
 self.entry.focus()
 self.entry.pack(side=TOP,fill=X)
 self.scrollbar.pack(fill=X)
 self.scrollbar.config(command=self.entry.xview)
 self.entry.config()


a=ScrollEntry()
a.root.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do i read just the last line of a text file?

2005-05-29 Thread Andy Leszczynski
Chris F.A. Johnson wrote:
 On Sun, 29 May 2005 at 05:57 GMT, John Machin wrote:
 
Chris F.A. Johnson wrote:


file = open(argv[1])  ## Open the file given on the command line
all_lines = file.readlines()  ## Read all the lines

I see your shadowing and raise you one obfuscation:
 
 
;)
 
 
open = file(argv[1])  ## File the open given on the command line
all_lines = open.readlines()  ## Read all the lines
 
 
Such verbosity! (I excuse mine on the grounds that it was my first
attempt at a Python program.)
 
 all_lines = file(argv[1]).readlines()
 
And to answer the question in the subject line:
 
 last_line = file(argv[1]).readlines()[-1]
 
Both of which assume from sys import argv.
 
 
Now I have to get serious and forget those bad habits.
 

What if a file is long enough?

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


Re: Entry scroll doesn't work

2005-05-29 Thread VK
VK wrote:
 Hi!
 Can entry widget be scrolled?
 VK
 
 TypeError: xview() takes exactly 2 arguments (4 given)
 
 Code:
 
 
 
 from Tkinter import *
 class ScrollEntry:
 def __init__(self):
 self.root = Tk()
 self.scrollbar = Scrollbar(self.root,orient=HORIZONTAL,)
 self.entry = Entry(self.root,xscrollcommand=self.scrollbar.set)
 self.entry.focus()
 self.entry.pack(side=TOP,fill=X)
 self.scrollbar.pack(fill=X)
 self.scrollbar.config(command=self.entry.xview)
 self.entry.config()
 
 
 a=ScrollEntry()
 a.root.mainloop()

Already found:  :)

http://infohost.nmt.edu/tcc/help/pubs/tkinter/entry-scrolling.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: SWIG std::string passing

2005-05-29 Thread jchiang
Add the line

%include stl.i

to your .i file.  This will make other stl containers available, in
addition to string. Make sure you put this line before any include
directives for classes that use std::string.  SWIG requires classes to
be declared before they are used in order for the interfaces to be
exposed completely.

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


Re: need help of RE

2005-05-29 Thread Steven Bethard
John Machin wrote:
   import re
   text = (word1  (Word2|woRd3)).lower()
 # you seem to want downshifting ...
   re.split(r\W+, text)
 ['', 'word1', 'word2', 'word3', '']
  
 
 Hmmm ... near, but not exactly what you want. We need to throw away 
 those empty strings, which will appear if you have non-word characters 
 at the ends of your text.

You can also avoid the empty strings at the end by using re.findall with 
\w instead of re.split with \W:

py import re
py text = (word1  (Word2|woRd3)).lower()
py re.findall(r\w+, text)
['word1', 'word2', 'word3']

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


Re: How do i read just the last line of a text file?

2005-05-29 Thread Steven Bethard
Andy Leszczynski wrote:
 Chris F.A. Johnson wrote:
And to answer the question in the subject line:

 last_line = file(argv[1]).readlines()[-1]

Both of which assume from sys import argv.
 
 What if a file is long enough?

Huh?  You mean what if it's too big to fit in memory?  Then try this:

for last_line in file(argv[1]):
 pass

At the end of the for loop, last_line should be bound to the last line 
in the file.  (If there's a chance your file might not have any lines, 
you'll want to do some error checking...)

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


Re: How do i read just the last line of a text file?

2005-05-29 Thread nephish
cool. thanks for the help guys !

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


Re: How do i read just the last line of a text file?

2005-05-29 Thread Terry Reedy

Andy Leszczynski
 What if a file is long enough?

I believe you meant What if a file is too long to read all into memory at 
once?

If the file is randomly accessible (with file.seek() backwards from the 
end) then you can read a chunk at the end that you expect to be large 
enough to contain the last line and search backwards for \n (ignoring a 
terminating \n) to find the end of the next-to-last line.  Even if the file 
will fit in memory, this may be faster.

Terry J. Reedy



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


Re: Newbie learning OOP

2005-05-29 Thread Steven Bethard
LenS wrote:
 class names:
 def __init__(self, format = F):
 self.format = format
 
 def namesplit(self, name):
 if self.format == F:
 self.namelist = name.split()
 self.first = self.namelist[0]
 self.init = self.namelist[1]
 self.last = self.namelist[2]
 else:
 self.namelist = name.split()
 self.first = self.namelist[1]
 self.init = self.namelist[2]
 self.last = self.namelist[0]
 
 return self.first, self.init, self.last
 
 def fjoin(self):
 self.namestring = self.first + ' ' + self.init + ' ' +
 self.last
 
 def ljoin(self):
 self.namestring = self.last + ' ' + self.first + ' ' +
 self.init
 
 
 Any comments appreciated.

Seems to me like you really want a Name object, not a Names object. 
Note that fjoin() and ljoin() seem to be methods associated with an 
instance consisting of 'first', 'init' and 'last' attributes.  But your 
constructor does not provide such attributes, so a call to fjoin() or 
ljoin() immediately after creating a new names() object will fail with 
an AttributeError.  I would move the assignment of 'first', 'init' and 
'last' into the constructor, e.g. something like:

py class Name(object):
... def __init__(self, name, format='F'):
... if format == 'F':
... self.first, self.init, self.last = name.split()
... else:
... self.last, self.first, self.init = name.split()
... def first_str(self):
... return ' '.join([self.first, self.init, self.last])
... def last_str(self):
... return ' '.join([self.last, self.first, self.init])
...
py n = Name('Steven John Bethard')
py n.first_str()
'Steven John Bethard'
py n.last_str()
'Bethard Steven John'
py n = Name('Bethard Steven John', 'L')
py n.first_str()
'Steven John Bethard'
py n.last_str()
'Bethard Steven John'

You might consider passing a function instead of a string instead of the 
format parameter:

py def first_splitter(name):
... return name.split()
...
py def last_splitter(name):
... names = name.split()
... return names[1:] + names[:1]
...
py class Name(object):
... def __init__(self, name, splitter=first_splitter):
... self.first, self.init, self.last = splitter(name)
... def first_str(self):
... return ' '.join([self.first, self.init, self.last])
... def last_str(self):
... return ' '.join([self.last, self.first, self.init])
...
py Name('Steven John Bethard').first_str()
'Steven John Bethard'
py Name('Bethard Steven John', last_splitter).first_str()
'Steven John Bethard'

This means you don't have to keep track of a mapping between strings and 
functions; you just pass the function objects themselves.

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


Re: Intellisense and the psychology of typing

2005-05-29 Thread Vincent Foley
I have rapidly skimmed over the few responses here.  Auto completion is
definitly possible in dynamic languages: Common Lisp has it with its
Emacs mode, SLIME.

If you're in a slime buffer, you type (get-un then press C-c Tab and
Emacs will auto-complete with (get-universal-time), if there are many
choices, they will be displayed in a split window, if the function
takes parameters, those will appear in the mini-buffer, like so:

(with-open-file (stream sb-impl::filespec rest sb-impl::options) body
body)

SLIME is also not the only place where a dynamic language has
auto-completion, check out Ecomplete in Squeak or the auto-complete
package in Visual Works Smalltalk.  It can be done, maybe not as easily
as in a statically typed language, but it definitly can be done.

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


Re: how to convert string to list or tuple

2005-05-29 Thread Dan Bishop
Simon Brunning wrote:
 On 5/26/05, flyaflya [EMAIL PROTECTED] wrote:
  a = (1,2,3)
  I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',',
  '2', ',', '3', ')') not (1,2,3)

 Short answer - use eval().

 Long answer - *don't* use eval unless you are in control of the source
 of the string that you are evaluating.

Or if you do use eval, don't give it access to any names.

 import os
 eval(raw_input(), {})
os.system(rm -rf *)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File string, line 0, in ?
NameError: name 'os' is not defined

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


Re: Help with choice of suitable Architecture

2005-05-29 Thread Rob Cowie
Thanks for the comments.

I kind of get the impression that CGI is the way to go for this
application, and that I should forget about adding client-side
scripting based functionality for the sake of accessibility - which I
understand and kind of agree with.

I'll look into the problem of concurrent access to an XML file. I may
get back to the group about this!

Cheers

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


Re: 2D vector graphics Problem

2005-05-29 Thread Scott David Daniels
Karl Max wrote:
 def rotate(self, w):
  # This method belongs to the class Vertex
  # w = angle expressed in radiants
  x, y = self.coords
  xRel, yRel = self.relPoint # The rotation should be relative to this
  sin, cos = math.sin(w), math.cos(w)
  x = x * cos - y * sin - xRel * cos + yRel * sin + xRel
  y = x * sin + y * cos - xRel * sin - yRel * cos + yRel
  self.coords = (x,y)

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

If you define a testcase or two, you can catch things like this early.


test = Point(1, 1)
test.rotate(math.pi / 2)
x, y = test.coords
assert (x - -1) ** 2 + (y - 1) ** 2  .1


--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert string to list or tuple

2005-05-29 Thread Duncan Booth
Dan Bishop wrote:

 Simon Brunning wrote:
 [...]
 
 Or if you do use eval, don't give it access to any names.
 
 [...]
 os.system(rm -rf *)
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File string, line 0, in ?
 NameError: name 'os' is not defined
 
Have you tried giving it the string '__import__(os).system(rm -rf *)'?
[Don't try that at home children!]

Even if you take steps to avoid that working by hiding the builtins, there 
are still too many ways to do nasty things with eval for it ever to be 
safe.

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


tracing crash

2005-05-29 Thread Nir Aides
Hi,

I am facing a strange problem.
I will appreciate an explanation and a work around for the problem.

Look in the following code paste. It seems that taking a reference to 
the frame object crashes python in some scripts:

#
# trace_hell.py
#
# crashes with spe (stani's python editor) v0.7.3.a
#
# to see the crash add import trace_hell; trace_hell.unleash_hell() as
# the first line in spe.py
#
# 1. The statement that triggers the crash is g_frame = frame
#

import sys

g_frame = None

def tracer(frame, event, arg):
 global g_frame
 g_frame = frame
 return None

def unleash_hell():
 sys.settrace(tracer)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert string to list or tuple

2005-05-29 Thread John Roth

Duncan Booth [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
 Dan Bishop wrote:

 Simon Brunning wrote:
 [...]

 Or if you do use eval, don't give it access to any names.

 [...]
 os.system(rm -rf *)
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File string, line 0, in ?
 NameError: name 'os' is not defined

 Have you tried giving it the string '__import__(os).system(rm -rf *)'?
 [Don't try that at home children!]

 Even if you take steps to avoid that working by hiding the builtins, there
 are still too many ways to do nasty things with eval for it ever to be
 safe.

There was a posting here Nov 5, 2003 by Huaiyu Zhu at IBM Almaden
that shows how to do eval type stuff safely. The basic notion is to use the
compiler and then check the ast to see if the result fits the straitjacket 
you
want to put it into. Pass / Fail; trying to fix it up if it's close is 
usually a
real bad idea.

He gives an example, and there's a much more extensive set of working
code in the taBase.py module of PyFit that handles lists, tuples and
dicts which contain arbitrary literals including complex and arbitrarily 
nested
lists, tuples and dicts.

--- code snippet starts here 

def _safeEval(self, s):

Evaluate strings that only contain the following structures:
const,  tuple,  list,   dict
Taken from c.l.py newsgroup posting Nov 5, 2003 by Huaiyu Zhu at IBM 
Almaden

#print in _safeEval. input: '%s' % s
node1 = compiler.parse(s)

# !!! special case of attempting to compile a lone string
if node1.doc is not None and len(node1.node.nodes) == 0:
#print in _safeEval. string: '%s' found as docstring % 
node1.doc
return node1.doc

#print in _safeEval. nodes: '%s' % (node1,)
stmts = node1.node.nodes
assert len(stmts) == 1
node = compiler.parse(s).node.nodes[0]
assert node.__class__ == compiler.ast.Discard
nodes = node.getChildNodes()
assert len(nodes) == 1
result = self._safeAssemble(nodes[0])
#print in _safeEval result: '%s' % (result,)
return result

seq_types = {
compiler.ast.Tuple: tuple,
compiler.ast.List: list,
}
map_types = {
compiler.ast.Dict: dict,
}

oper_types = {
compiler.ast.Add: operator.add,
compiler.ast.Sub: operator.sub,
}

builtin_consts = {
True: True,
False: False,
None: None,
}

def _safeAssemble(self, node):
 Recursively assemble parsed ast node 
cls = node.__class__
if cls == compiler.ast.Const:
return node.value
elif cls in self.seq_types:
nodes = node.nodes
args = map(self._safeAssemble, nodes)
return self.seq_types[cls](args)
elif cls in self.map_types:
keys, values = zip(*node.items)
keys = map(self._safeAssemble, keys)
values = map(self._safeAssemble, values)
return self.map_types[cls](zip(keys, values))
elif cls in self.oper_types:
left = self._safeAssemble(node.left)
right = self._safeAssemble(node.right)
if type(left) == type(1.0j) or type(right) == type(1.0j):
return self.oper_types[cls](left, right)
else:
raise FitException, (Parse001,)
elif cls == compiler.ast.Name:
result = self.builtin_consts.get(node.name, ?)
if result != ?:
return result
else:
raise FitException, (Parse002, node.name)
else:
raise FitException, (Parse003, cls)

--- end of code snippet ---

John Roth


 

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


Re: 2D vector graphics Problem

2005-05-29 Thread Karl Max

Scott David Daniels [EMAIL PROTECTED] ha scritto nel messaggio 
news:[EMAIL PROTECTED]
  x = x * cos - y * sin - xRel * cos + yRel * sin + xRel
  y = x * sin + y * cos - xRel * sin - yRel * cos + yRel
  self.coords = (x,y)

 Your equation for y uses the new x, not the old x.

De hi hi ho. I must sleep some more hours at night... ;-)
Be more free with names.

Well, I often report book formulas, and forget renaming variables to more 
comprehensive language. Thank you for your help.

Max 


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


Re: 2D vector graphics Problem

2005-05-29 Thread Scott David Daniels
Karl Max wrote:
 Scott David Daniels [EMAIL PROTECTED] ha scritto nel messaggio 
... Your equation for y uses the new x, not the old x
 De hi hi ho. I must sleep some more hours at night... ;-)
Be more free with names.
 
 Well, I often report book formulas, and forget renaming variables to more 
 comprehensive language. Thank you for your help.

I was trying to give you a couple of ways to avoid similar problems in
the future.  The way to get better at programming is to:
Figure out why you made the mistake.
See if you can change the way you work to prevent such problems.
If you can't prevent the problems:
Try to make the problem rare.
Try to catch the problems early.

It's not so much that I want you to do it my way; I was just suggesting
a couple of ways to improve your own process.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Case Sensitive, Multiline Comments

2005-05-29 Thread Arthur
On 26 May 2005 17:33:33 -0700, Elliot Temple [EMAIL PROTECTED]
wrote:

Thanks for the link on case sensitivity.  I'm curious about the person
who found case sensitivity useful though: what is it useful for?

I am curious about why you find case sensitivity annoying.  But just
mildly curious.

Martelli can tell you why Guido keeping case sensitivity in Python was
him bowing to the stupidity of the masses.

I have been neutral on the subject except to the extent the impetous
for going case insensitive would be to statisfy the needs - as Guido
uses the word -  non-programmers.

a) its probably better to design a programming language around the
needs of programmers than around those of non-porgrammers.  that much
always seemed quite obvious to me. 

b) it would only help non-programmers who were more comfortable with
case insensitivity but hurt non-progammers more comfortable with case
sensitivity.

That Martelli so strongly favors case insensitivity for his own use,
is one of many indications that this is not an issue that cuts along
the lines of quantity of programming experience..

That much also seemed pretty obvious, but it didn't seem to stop the
folks who wanted case insensitivity from making the non-programmer
accessibility issue paramount. and on the flimiest of evidence.  Those
who prefer sensitivity were anti-accessbility elitists. Damn near
Republicans.  

Classic politics.

Thankfully Guido seemed to have lost patience for the whole thing.  I
think the position is pretty much that Python will be case sensitive
becasue it has been case sensitive.

Art


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


Re: Software licenses and releasing Python programs for review

2005-05-29 Thread poisondart
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--in all the cases you've described, the answer should
be no.

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

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. If she hasn't
debugged my code...what is she doing selling my property?

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

Business partner Billy is using a scheme similar to the magazine
publisher example.

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.

Thanks,

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


double w pythonie?

2005-05-29 Thread turbos10
Witam!
Z jaka precyzja python dokonuje obliczen zmiennoprzecinkowych. Czy jest 
w pythonie typ podwojnej precyzji (double z c).
Pozdrawiam
-- 
Uwagi o bdach ortograficznych czy interpunkcyjnych, oraz wszelkie 
sowne utarczki zaatwiaj listami prywatnymi.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: double w pythonie?

2005-05-29 Thread turbos10
w news:[EMAIL PROTECTED]
turbos10 napisa(a):

 Witam!
 Z jaka precyzja python dokonuje obliczen zmiennoprzecinkowych. Czy
 jest w pythonie typ podwojnej precyzji (double z c).

sorry!

-- 
Uwagi o bdach ortograficznych czy interpunkcyjnych, oraz wszelkie 
sowne utarczki zaatwiaj listami prywatnymi.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Case Sensitive, Multiline Comments

2005-05-29 Thread Elliot Temple

On May 29, 2005, at 11:44 AM, Arthur wrote:

 On 26 May 2005 17:33:33 -0700, Elliot Temple [EMAIL PROTECTED]
 wrote:


 Thanks for the link on case sensitivity.  I'm curious about the  
 person
 who found case sensitivity useful though: what is it useful for?


 I am curious about why you find case sensitivity annoying.  But just
 mildly curious.

I'm glad you asked ;-)

Case insensitivity gives you more choice about how to type keywords  
that you have no control over.  if or If.  for or For.  i don't think  
being inconsistent within a single program is a good idea, but having  
your choice of which to do is nice.  I personally think all lowercase  
is good, but some languages have capitalised keywords, so apparently  
other people prefer that.

I don't think the case sensitivity hurts beginners argument is  
persuasive.  Anyone who seriously wants to program can look up the  
correct capitalisation of everything.  *If* having to look up or keep  
track of capitalisation is annoying, *then* that argument applies to  
experienced programmers (who are devoting memory to the issue) just  
as much as beginners.

-- Elliot Temple
http://www.curi.us/


---
[This E-mail scanned for viruses by Declude Virus]

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


Re: Tkinter weirdness item count

2005-05-29 Thread pavel.kosina
I think the answer you should find under Subject: Tkinter slowes down


---
geon
Exception is rule.

phil napsal(a):
 Using Tkinter Canvas to teach High School Geometry
 with A LOT of success.
 
 My drawing gets very slow after a lot of actions.
 
 For instance I have created code to rotate a set of objects
 about a rotation point.
 rotate 360 degrees starts to get slow
 after 720 degrees its crawling.
 
 I checked the item list with with find_all: IT GROWS!
 
 OK, I create 3 lines using a line Class I created.
 When I rotate these 3 lines thru 360 degrees it creates
 360 lines times 3. But each new instance of line REPLACES
 the old instance.  The line class has a destructor to delete
 the drawn object.
 
 class line:
 count = 0
 def __init__(s,glob,argl,color=''):
 line.count = line.count + 1
 ##
 ## buncha code here
 ##
 s.obj = glob.can.create_line(x0,y0,x1,y1,
 width=glob.width,fill=s.color)
 def __del__(s):
 line.count = line.count - 1
 
 ## delete the line object if the
 ## class instance is deleted
 s.glob.can.delete(s.obj)
 
 
 After the rotation I check line.count and it is 3
 But find_all returns a tuple ofover 1000 items.
 The drawn objects are not being deleted.
 Which is kinda weird because the rotation works.
 That is they appear to be deleted.
 
 Is find_all() fooling me?
 Is this the reason drawing slows down? Is it refreshing
 invisible objects?
 
 This slowing down also occurs when I draw a lot of objects.
 Lets say I draw a sine wave, say 1000 individual points.
 If I draw 4 or 5 sine waves it gets really slow.
 
 I should mention I call update() after each drawing action.
 This is necessary for the students to watch the progress.
 I might be drawing objects in a lengthy loop and without
 update() they only appear at the end of the loop.
 
 Thanks for any help.
 
 -- Confused
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to learn OO of python?

2005-05-29 Thread Harlin Seritt
?

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


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

2005-05-29 Thread Michael Onfrek
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

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


Re: how to convert string to list or tuple

2005-05-29 Thread Steven Bethard
Duncan Booth wrote:
 Dan Bishop wrote:
 Or if you do use eval, don't give it access to any names.
[snip]
 os.system(rm -rf *)
 Traceback (most recent call last):
   File stdin, line 1, in ?
   File string, line 0, in ?
 NameError: name 'os' is not defined
 
 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 interactive input, line 1, in ?
   File string, 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.)

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


Re: Newbie learning OOP

2005-05-29 Thread John Machin
LenS wrote:
 Trying to learn OOP concepts and decided to use Python for this
 purpose.  I have coded the following CLASS and it seems to work fine.
 Any comments on the code or suggestions would be appreciated.
 
 The class let you take a person's name and split it up into first last
 and middle.  The class defaults to the assumption that the name will be
 passed in as a string in first last and middle order however you can
 set the format attribute to take last first and middle order. You can
 then get a string back in and opposite order.
 
 class names:
 def __init__(self, format = F):
 self.format = format
 
 def namesplit(self, name):
 if self.format == F:
 self.namelist = name.split()
 self.first = self.namelist[0]
 self.init = self.namelist[1]
 self.last = self.namelist[2]
 else:
 self.namelist = name.split()
 self.first = self.namelist[1]
 self.init = self.namelist[2]
 self.last = self.namelist[0]
 
 return self.first, self.init, self.last
 
 def fjoin(self):
 self.namestring = self.first + ' ' + self.init + ' ' +
 self.last
 
 def ljoin(self):
 self.namestring = self.last + ' ' + self.first + ' ' +
 self.init
 

You are missing 'return' in the fjoin and ljoin methods.

A practical problem: not everbody's name can be shoe-horned into the 
first/initial/last model. You face catastrophic loss of information.

Some examples, with last name in capitals:

J. Edgar HOOVER - J E HOOVER
Rip J. VAN WINKLE - Rip J VAN
Jean Paul DE LA SALLE - Jean P DE
DE LA SALLE, Jean Paul - LA S DE
MAO Tse Tung - Tse T MAO # or MAO T Tung
MAO Tse-tung - Tse-tung M empty # or an IndexError
MAO Zedong - Zedong M empty # or an IndexError
Vigdis ERIKSDOTTIR - Vigdis E empty # and lost the gender, too
Gunnlaug ILLUGASON Ormstunga - Gunnlaug I Ormstunga # nickname 
Snakestongue
Ivan Denisovich SHUKHOV - Ivan D SHUKHOV # and lost father's first 
name, too
Friedrich Heinrich Karl VON UND ZU HOHENLOHE - Friedrich H Karl
NGUYEN Thi Thanh Van - Thi T NGUYEN
# Thi means female and Nguyen is the last name of about 50% of 
the Vietnamese population ...

:-)
You don't work for the Department of Homeland Security, do you?
(-:
-- 
http://mail.python.org/mailman/listinfo/python-list


finding indices in a sequence of parentheses

2005-05-29 Thread Steven Bethard
I have a list of strings that looks something like:

lst = ['0', '0', '(*)', 'O', '(*', '*', '(*', '*))', '((*', '*)', '*)']

The parentheses in the labels indicate where an annotation starts and 
ends.  So for example, the label '(*)' at index 2 of the list means that 
I have an annotation at (2, 2), and the labels '(*', '*', '(*', '*))' at 
indices 4 through 7 mean that I have an annotation at (4, 7) and an 
annotation at (6, 7).

I'd like to determine all indices at which I have an annotation.  So for 
the data above, I want the indices:

 (2, 2), (4, 7), (6, 7), (8, 9) and (8, 10)

Here's what I'm doing now:

py def indices(lst):
... stack = []
... for i, s in enumerate(lst):
... if s == 'O':
... continue
... stack.extend([i]*s.count('('))
... if '*' in s and not stack:
... raise Exception('No start for %r at %i' % (s, i))
... for _ in range(s.count(')')):
... try:
... yield stack.pop(), i
... except IndexError:
... raise Exception('No start for %r at %i' % (s, i))
... if stack:
... raise Exception('No ends for starts at %r' % stack)
...
py list(indices(['0', '0', '(*)', 'O', '(*', '*', '(*', '*))', '((*', 
'*)', '*)', '0']))
[(2, 2), (6, 7), (4, 7), (8, 9), (8, 10)]

I think that works right, but I'm not certain.  So two questions:

(1) Can anyone see anything wrong with the code above? and
(2) Does anyone see an easier/clearer/simpler[1] way of doing this?

Thanks,

STeVe

[1] Yes, I know easier/clearer/simpler are subjective terms.  It's okay, 
I'm only looking for opinions here anyway. =)
-- 
http://mail.python.org/mailman/listinfo/python-list


cgi.py?

2005-05-29 Thread david . tolpin
Hi,

I've looked into cgi.py from 2.4's distribution, and its contents
puzzle me. In parse_header, the first line splits on ';':

plist = map(lambda x: x.strip(), line.split(';'))

but header parameters may contain semicolon in quoted strings:

   Content-Type: image/jpeg; filename=home:lib;images;face.jpg

and headers like this one will be parsed incorrectly. A few subsequent
lines unquote a quoted value, but the only place where quoted-string
production is defined is RFC 3875, and there is no quote escaping in
the production (nor in any other draft or related RFC). So, even if the
former is fixed, the latter will still prevent headers like

  Content-Type: text/plain; filename=c:\files\; title=My Files

from being parsed correctly. What am I missing?

David

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


Re: Process monitoring

2005-05-29 Thread gsteff
Thanks- subprocess was exactly what I needed.  For anyone else that
reads this, I just launched a new subprocess via subprocess.Popen, did
what I needed to do in a while look, while calling the poll method of
the Popen object to check whether it was finished, and if so, what its
error code was.  Pretty simple.

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


2005 ICFP Programming Contest

2005-05-29 Thread Robby Findler
Think your favorite programming language is the best one out
there? Put it to the test in this year's International Conference
on Functional Programming's annual Programming Contest. The
contest is coming up in a little under 4 weeks and we have just
released more information (including a live cd, mailing list, and
prize details) to the web page, at:

http://icfpc.plt-scheme.org/

This year's competition rewards programmers who can plan ahead. As
before, we'll announce a problem and give you three days to solve it.
Two weeks later, we'll announce a change to the problem specification
and give you one day to adapt your program to the new spec. And you
guessed it: the second half will be worth considerably more than the
first.

Important dates:

  Problem announced: Friday, June 24th, 9:00am CDT (UTC-6)
  Initial entries due: Monday, June 27th, 9:00am CDT (UTC-6)
  Revision announced: Saturday, July 9th, 9:00am CDT (UTC-6)
  Final entries due: Sunday, July 10th, 9:00am CDT (UTC-6)

ICFP Contest Organizers
[EMAIL PROTECTED]

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


Re: finding indices in a sequence of parentheses

2005-05-29 Thread tiissa
Steven Bethard wrote:
 (2) Does anyone see an easier/clearer/simpler[1] way of doing this?

I'd personnally extract the parenthesis then zip the lists of indices.
In short:

   def indices(mylist):
  ... lopen=reduce(list.__add__, [[i]*s.count('(') for i,s in 
enumerate(mylist)],[])
  ... lclose=reduce(list.__add__, [[i]*s.count(')') for i,s in 
enumerate(mylist)],[])
  ... return zip(lopen,lclose)
  ...
   indices(lst)
  [(2, 2), (4, 7), (6, 7), (8, 9), (8, 10)]
  

Before returning, you can check if the lists have same size and if the 
'(' has lower or equal index than ')' in each of these couples. If not 
you can raise the appropriate exception.

Disclaimer: not tested further than example above (but confident).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help with choice of suitable Architecture

2005-05-29 Thread John J. Lee
Rob Cowie [EMAIL PROTECTED] writes:

 Thanks for the comments.
 
 I kind of get the impression that CGI is the way to go for this
 application, and that I should forget about adding client-side
 scripting based functionality for the sake of accessibility - which I
 understand and kind of agree with.

I don't see any intrinsic reason for client-side scripting, or
JavaScript in particular, messing up accessibility.  One can fall back
to vanilla HTML+CSS for people who don't have JS turned on.  I don't
say it's easy, though.  I don't know what you intend the content of
your Masters to be, but this seems like an interesting and useful
thing to work on, and a fashionable topic to boot: write your app as
one piece of code that can run happily with JavaScript (and taking
advantage of AJAX) or without (without resort to if statements in your
application code, obviously ;-).

Personally, I'm anticipating the day I can change an import statement
in my Qt GUI applications and run them on the web (== JavaScript +
HTML + CSS + HTTP) 0.5 wink.

In the mean time, I recommend Quixote (yes, you can run it on CGI).
Lots of people seem to like Twisted, too (nevow has some AJAX
support), though perhaps Twisted and CGI don't sensibly go together
(and I certainly understand the desire to avoid long-running server
processes).

If you're interested in new stuff, certainly take a look at Kamaelia
(after you've oriented yourself a bit by writing a tiny web app or
two!).


 I'll look into the problem of concurrent access to an XML file. I may
 get back to the group about this!

From my own unpleasant experience, CGI + locking = pain.  At least if
you don't have full control of the server (even then, do yourself a
favour, use a DBMS, and let somebody else worry about some of the hard
parts of locking, transactions c.).  Why not keep the XML in a
database blob, if somebody insists on an XML-based implementation?
Or, more sane, store your data in the DB, then just write out XML,
which presumably solves the *real* problem for which XML is the
solution (interoperability)?

have-the-appropriate-amount-of-fun-ly y'rs,


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


Re: Software licenses and releasing Python programs for review

2005-05-29 Thread John J. Lee
poisondart [EMAIL PROTECTED] writes:
[...]
 Ultimately I desire two things from the license (but not limited to):
 - being able to distribute it freely, anybody can modify it
 - nobody is allowed to make profit from my code (other than myself)
[...]

If you believe it's feasible to get contributors to (literally) sign
over their copyright to you, consider dual GPL+commercial licensing.
Trolltech do this very successfully with their Qt GUI framework (they
also have educational licenses too, I believe, though the release of
Qt 4/Win under the GPL will presumably make those licenses redundant).

In general, people tend to find it very hard to get unpaid code
contributions if there are annoying restrictions such as prohibition
against commercial distribution of the code, which is one reason why
people pick BSD or GPL licenses.  Whatever you do, pick a standard,
well known license, simply because nobody has the time or inclination
to read somebody else's pet license.

(Of course, if the contributions you're most interested in aren't
copyrightable (comment on algorithms or scientific ideas, or
high-level feedback about the implementation of your code, for
example), all this may not be a big issue.)

Though they sometimes mix, the academic world is driven by different
motivations than the open source world, of course.  As someone from
the linguistics field, you're probably far better placed than we are
to know about the social environment in which your code will find
itself.  Unless there's another Linguistic Pythonista here ;-)


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


__getattribute__ and __getattr__

2005-05-29 Thread Gigi
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:


The following methods only apply to new-style classes.

__getattribute__(   self, name)
 Called unconditionally to implement attribute accesses for 
instances of the class. If the class also defines __getattr__, it will 
never be called (unless called explicitly). This method should return 
the (computed) attribute value or raise an AttributeError exception. In 
order to avoid infinite recursion in this method, its implementation 
should always call the base class method with the same name to access 
any attributes it needs, for example, object.__getattribute__(self, 
name).


I discovered that it is not so for Python 2.3.4 on Windows at least. The 
actual behavior is that if both __getattribute__ and __getattr__ methods 
exist then __getattribute__ is called first, but if it raises 
AttributeError then the exception will be swallowed silently and 
__getattr__ will be invoked. Note that if I forward to the default 
object.__getattribute__ or if I raise the AttributeError myself the 
result is the same. My understanding of the documentation is it that the 
program should just exit with the AttributeError exception.

Here is the code:

class A(object):
 def __getattribute__(self, name):
 return object.__getattribute__(self, name)
# raise AttributeError()

 def __getattr__(self, name):
 return 42

if __name__ == '__main__':
 a = A()
 print a.x

Here is the Output:

42


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


network ping

2005-05-29 Thread Sam the Cat
Besides calling the external ping utility -- is there a way native to python
to execute a similar utility ?


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


Re: cgi.py?

2005-05-29 Thread Skip Montanaro

david I've looked into cgi.py from 2.4's distribution, and its contents
david puzzle me. In parse_header, the first line splits on ';':

david plist = map(lambda x: x.strip(), line.split(';'))

david but header parameters may contain semicolon in quoted strings:

davidContent-Type: image/jpeg; filename=home:lib;images;face.jpg

...

david What am I missing?

Probably nothing.  Can you maybe submit a patch?

Thx,

-- 
Skip Montanaro
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


stdout and stderr showing output only after script is done

2005-05-29 Thread MKoool
I just installed python 2.4 for windows.  I was using the cygwin
version previously, but wanted to use the official python 2.4 release
to install a module that reads off some registry entries.

After installing, I did what I normally do, ssh to my local windows
machine, and run the python script I wrote.  The script takes about 30
seconds to complete and gives me incremental output.  I ran it, and it
seems to be buffering standard input and  output.  It ran my whole
script and showed me all the output of stderr and stdout only after the
whole script was done.  For example, my script can sometimes take like
10 minutes to finish, so I print out 1% complete, 2% complete and
so on.  Now it shows me nothing, and at the end, it just tells me 1%
complete, 2% complete... 100% complete all in one shot.

Can I change this behavior somehow?

thanks,
mohan

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


Re: stdout and stderr showing output only after script is done

2005-05-29 Thread MKoool
sorry, i'm an idoit who just found that i should use the -u option, my
bad

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


Re: stdout and stderr showing output only after script is done

2005-05-29 Thread MKoool
sorry i meant i installed python version 2.4.1, thanks

MKoool wrote:
 I just installed python 2.4 for windows.  I was using the cygwin
 version previously, but wanted to use the official python 2.4 release
 to install a module that reads off some registry entries.

 After installing, I did what I normally do, ssh to my local windows
 machine, and run the python script I wrote.  The script takes about 30
 seconds to complete and gives me incremental output.  I ran it, and it
 seems to be buffering standard input and  output.  It ran my whole
 script and showed me all the output of stderr and stdout only after the
 whole script was done.  For example, my script can sometimes take like
 10 minutes to finish, so I print out 1% complete, 2% complete and
 so on.  Now it shows me nothing, and at the end, it just tells me 1%
 complete, 2% complete... 100% complete all in one shot.
 
 Can I change this behavior somehow?
 
 thanks,
 mohan

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


Re: __getattribute__ and __getattr__

2005-05-29 Thread Terry Reedy

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=detailatid=105470aid=1204734group_id=5470

Guido declared behavior right and doc wrong and in need of correction.

Terry J. Reedy



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


Re: finding indices in a sequence of parentheses

2005-05-29 Thread Steven Bethard
tiissa wrote:
 I'd personnally extract the parenthesis then zip the lists of indices.
 In short:
 
   def indices(mylist):
  ... lopen=reduce(list.__add__, [[i]*s.count('(') for i,s in 
 enumerate(mylist)],[])
  ... lclose=reduce(list.__add__, [[i]*s.count(')') for i,s in 
 enumerate(mylist)],[])
  ... return zip(lopen,lclose)
  ...
   indices(lst)
  [(2, 2), (4, 7), (6, 7), (8, 9), (8, 10)]
  

Thanks, that's a good idea.  In case anyone else is reading this thread, 
and had to mentally unwrap the reduce expressions, I believe they could 
be written as:

lopen  = [x for i, s in enumerate(lst) for x in [i]*s.count('(')]
lclose = [x for i, s in enumerate(lst) for x in [i]*s.count(')')]

or maybe:

lopen  = [i for i, s in enumerate(lst) for _ in xrange(s.count('('))]
lclose = [i for i, s in enumerate(lst) for _ in xrange(s.count(')'))]

Sorry, I have an irrational fear of reduce. ;)

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


Re: Case Sensitive, Multiline Comments

2005-05-29 Thread D H
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.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Case Sensitive, Multiline Comments

2005-05-29 Thread Roy Smith
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.

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.
-- 
http://mail.python.org/mailman/listinfo/python-list


Monitoring Outgoing Connections?

2005-05-29 Thread Joseph Chase
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?

TIA. 


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


prime number

2005-05-29 Thread lostinpython
I'm having trouble writing a program that figures out a prime number.
Does anyone have an idea on how to write it?  All I know is that n  2
is prim if no number between 2 and sqrt of n (inclusivly) evenly
divides n.

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


Re: prime number

2005-05-29 Thread Tim Leslie
On 29 May 2005 19:55:32 -0700, lostinpython
[EMAIL PROTECTED] wrote:
 I'm having trouble writing a program that figures out a prime number.
 Does anyone have an idea on how to write it?  All I know is that n  2
 is prim if no number between 2 and sqrt of n (inclusivly) evenly
 divides n.

This sounds remarkably like a homework problem, so I'm not going to
give you a full answer. Perhaps if you could be more specific about
which part's giving you trouble we could help you out with that.

If it finding square roots? is it checking for divisibility? is it
getting the loop to run through correctly? Is it some other problem?

Tim

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

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


Re: finding indices in a sequence of parentheses

2005-05-29 Thread Raymond Hettinger
[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


To see something like this in production code, look at
Tools/scripts/texcheck.py



Raymond Hettinger

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


Re: prime number

2005-05-29 Thread Mike Meyer
lostinpython [EMAIL PROTECTED] writes:
 I'm having trouble writing a program that figures out a prime number.
 Does anyone have an idea on how to write it?  All I know is that n  2
 is prim if no number between 2 and sqrt of n (inclusivly) evenly
 divides n.

How about this (untested):

import sys
import subprocess

primes = subprocess.Popen([primes, sys.argv[1], sys.argv[1]],
stdout=subprocess.PIPE).stdout.readlines()
if primes:
   print sys.argv[1], prime
else:
   print sys.argv[1], not prime

Seriously, this sounds like a homework assignment. Google for sieve
of eratosthenes. The BSD primes program I used in the above is an
implementation of that in C.

If it isn't a homework assignment, and you're honestly in such, then
you should know there's been a lot of research in this area, because
primes are important in cryptographic applications. Once again, google
is a good place to start on looking for recent research on the subject.

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


use of AttributesNSImpl in writing ?

2005-05-29 Thread spinach
I just can't find a good example for the use of AttributesNSImpl in the
context of writing XML through XMLGenerator. I need to generate XML
that uses several namespaces. The documentation is brief (understands
attribute names as two-tuples of namespaceURI and localname), it
appears you have to send it lots of dictionaries full of tuples.
Any clarification on this would be most appreciated.

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


test sorrry

2005-05-29 Thread ´º½º66
aaa


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


test from hanaro sorry

2005-05-29 Thread Çϳª·Î


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


[ python-Feature Requests-1210975 ] break and continue-ing out of nested 'for' loops

2005-05-29 Thread SourceForge.net
Feature Requests item #1210975, was opened at 2005-05-29 22:59
Message generated for change (Tracker Item Submitted) made by Item Submitter
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1210975group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Interpreter Core
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: Geraint Luff (geraintluff)
Assigned to: Nobody/Anonymous (nobody)
Summary: break and continue-ing out of nested 'for' loops

Initial Comment:
I wasn't entirely sure whether this should go under
Interpreter Core or Parser/Compiler, but whatever.

At the moment, break and continue can only break
out of the innermost for loop. I would appreciate a
way of breaking out of multiple 'for' or 'while' loops.

This would be extremely useful for instance when you
have some 'for' loops cycling through several
combinations, and you are using another 'for' loop to
check their validity (in my example, checking that my
two values are co-prime). In this situation, the only
solution I have found is to create a boolean variable
that is assigned a value when the check fails, just
before 'break'-ing out of a 'for' loop, and immediately
after that 'for' loop, having a statement that checks
the status of the boolean variable, and then
'continue's or 'breaks' again accordingly. I'm not an
experienced programmer, but this strikes me as
inefficient :p

Sorry if the above explanation is muddled. I can send a
short (15 lines) bit of code which might explain it better.

BTW, PHP seems to do this with break 2; or continue
2; which is very useful.

--G

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1210975group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Feature Requests-1209664 ] calling it revert is fine with me

2005-05-29 Thread SourceForge.net
Feature Requests item #1209664, was opened at 2005-05-27 02:36
Message generated for change (Comment added) made by rhettinger
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1209664group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: None
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: paul rubin (phr)
Assigned to: Nobody/Anonymous (nobody)
Summary: calling it revert is fine with me

Initial Comment:
Calling it revert is fine with me.  I don't want to get
into an editor war thing, let's just say emacs is what
I've always used; it's not a matter of any single
killer feature, it's a highly integrated system and I
do everything in it (shell, news reader, email, syntax
driven editing for N different languages, etc).  I do
use IDLE sometimes but comparing IDLE to Emacs is
almost like comparing it to Eclipse.  They're just
light years apart.

Btw re editor wars, I'm reminded of the T-shirt with a
kid asking Why are we running from the police,
daddy?.  The dad answers Because we use emacs, son. 
They use vi.

--

Comment By: Raymond Hettinger (rhettinger)
Date: 2005-05-29 20:49

Message:
Logged In: YES 
user_id=80475

Please clarify what you're requesting.  Is there some IDLE
feature you want added or renamed.  If this was just an
editor rant, please close the RFE.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1209664group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Feature Requests-1210975 ] break and continue-ing out of nested 'for' loops

2005-05-29 Thread SourceForge.net
Feature Requests item #1210975, was opened at 2005-05-29 17:59
Message generated for change (Comment added) made by rhettinger
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1210975group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Python Interpreter Core
Group: None
Status: Closed
Resolution: Rejected
Priority: 5
Submitted By: Geraint Luff (geraintluff)
Assigned to: Nobody/Anonymous (nobody)
Summary: break and continue-ing out of nested 'for' loops

Initial Comment:
I wasn't entirely sure whether this should go under
Interpreter Core or Parser/Compiler, but whatever.

At the moment, break and continue can only break
out of the innermost for loop. I would appreciate a
way of breaking out of multiple 'for' or 'while' loops.

This would be extremely useful for instance when you
have some 'for' loops cycling through several
combinations, and you are using another 'for' loop to
check their validity (in my example, checking that my
two values are co-prime). In this situation, the only
solution I have found is to create a boolean variable
that is assigned a value when the check fails, just
before 'break'-ing out of a 'for' loop, and immediately
after that 'for' loop, having a statement that checks
the status of the boolean variable, and then
'continue's or 'breaks' again accordingly. I'm not an
experienced programmer, but this strikes me as
inefficient :p

Sorry if the above explanation is muddled. I can send a
short (15 lines) bit of code which might explain it better.

BTW, PHP seems to do this with break 2; or continue
2; which is very useful.

--G

--

Comment By: Raymond Hettinger (rhettinger)
Date: 2005-05-29 20:43

Message:
Logged In: YES 
user_id=80475

Sorry, this was considered and rejected long ago.  Most
other languages have made a similar choice.  In Python, the
best alternatives include:

* try/except which can penetrate multiple layers of looping
and/or function calls.

* boolean flags

* enclosing the innermost loops in a function so that a
return statement exits all pending loops within the function.

*and try/finally statements which are not a general purpose
replacement but do cover a whole class of use cases.

For more reading on the subject, take a look at Knuth's
Structured Programming with go to Statements.  That is a
rather thorough analysis of various structured constructs
and their strengths and weaknesses.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1210975group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com



[ python-Feature Requests-1209562 ] add single html files

2005-05-29 Thread SourceForge.net
Feature Requests item #1209562, was opened at 2005-05-26 19:37
Message generated for change (Settings changed) made by rhettinger
You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1209562group_id=5470

Please note that this message will contain a full copy of the comment thread,
including the initial issue submission, for this request,
not just the latest update.
Category: Documentation
Group: None
Status: Open
Resolution: None
Priority: 5
Submitted By: paul rubin (phr)
Assigned to: Fred L. Drake, Jr. (fdrake)
Summary: add single html files

Initial Comment:
It would be good if the docs directory on python.org
included a view entire document as one big html page
for each document.  If I want to read through a
document from beginning to end, it's a  big pain to
have to keep clicking around at the end of each page,
especially if I'm looking at most pages for just a
second or so.  For the biggest documents (Python
library) maybe there could be several sections.  Right
now the only way to see everything at once is with the
PDF, which is much more hassle than browsing html.

--

You can respond by visiting: 
https://sourceforge.net/tracker/?func=detailatid=355470aid=1209562group_id=5470
___
Python-bugs-list mailing list 
Unsubscribe: 
http://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com