Re: iteration over non-sequence ,how can I resolve it?

2006-05-28 Thread BJörn Lindqvist
On 28 May 2006 06:20:20 -0700, python <[EMAIL PROTECTED]> wrote:
> at line "for j in  linkReturned:" , raise an error:
> File "C:\pythonProgram\test.py", line 308, in main
> for j in  linkReturned:
> TypeError: iteration over non-sequence
> how can I get a list from the return of thread.start() ?

You can't. thread.start() always return None.

> class PrintThread(threading.Thread):
>   def __init__(self, urlList):
>   threading.Thread.__init__(self)
>   urllist=[]
>   self.urllist=urlList
>def run(self):
>   urllink=[]
>   ..
>   return urllink
>
>
> for i in range(0,2):
> thread=PrintThread(links)
> threadList.append(thread)
> linkReturned=[]
> for i in threadList:
> linkReturned=i.start()
> for j in  linkReturned:
> links.append(j)

>From the looks of this code it seems like you want a sub-routine not a
thread. You can simulate returning a value from a thread by adding a
"return value" attribute to the PrintThread class that the run()
method writes to. Then you would have to add some form of
synchronizing so that your main program does not try to read the
"return value" of the thread before the thread actually has written
the "return value."

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a package like PyInstaller

2006-05-28 Thread LittlePython
"Im 99.999% confident that this will not happen from the .exe file
generated by pyinstaller (unless you specify--see link above)."

Well I guess that's about as close as any one can get in this business. I
have been trying to introduce py into our environment, and have opened a few
eyes, however I have been given one restriction. I can not install anything,
leave behind anything or alter anything on a systems .. period,  and as
the saying goes "To error is human but to forgive is not company policy!"

thx for your comments!

"James Stroud" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> LittlePython wrote:
> > That is very close to what I have being doing, however I was unable to
> > enclose a bmp or another file for that matter in the exe. I used both
DATA
> > and BINARY key words with no luck. I checked what was in the package and
> > there were there. I guess for some reason it could not locate then when
> > executed. I used snap 274 if I remember correctly.
>
> You can include files with innosetup under the [FILES] section. The docs
> show how. You can then code absolute paths to these resources in your
> code according to the results of 'sys.platform'. If you use the
> "--onedir" option, then you may want to look here:
>
> http://pyinstaller.hpcf.upr.edu/docs/Manual_v1.1.html#accessing-data-files
>
>
> > I am worrying that
> > when the py script is run I am leaving behind files. That the components
of
> > my stand-alone exe is somehow coming out of the exe (PyInstaller) and
being
> > installed.
>
> Im 99.999% confident that this will not happen from the .exe file
> generated by pyinstaller (unless you specify--see link above).
>
> However, innosetup will put files in the 'Program Files' directory or
> wherever you specify. This would be similar to just about every other
> application out there for windows.
>
> James
>
> -- 
> James Stroud
> UCLA-DOE Institute for Genomics and Proteomics
> Box 951570
> Los Angeles, CA 90095
>
> http://www.jamesstroud.com/


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


Re: iteration over non-sequence ,how can I resolve it?

2006-05-28 Thread python
To BJörn Lindqvist :
 thank you . how to write the code specifically ?Could you give a
example?

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


Re: iteration over non-sequence ,how can I resolve it?

2006-05-28 Thread python
To BJörn Lindqvist :
 thank you . how to write the code specifically ?Could you give an
example?

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


Re: unexpected behaviour for python regexp: caret symbol almost useless?

2006-05-28 Thread Paul McGuire
"conan" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> This regexp
> ''
>
> works well with 'grep' for matching lines of the kind
> 
>
> on a XML .glade file
>

As Peter Otten has already mentioned, this is the difference between the re
"match" and "search" methods.

As purely a lateral exercise, here is a pyparsing rendition of your program:


from pyparsing import makeXMLTags, line

# define pyparsing patterns for begin and end XML tags
widgetStart,widgetEnd = makeXMLTags("widget")

# read the file contents
glade_file_name = 'some.glade'
gladeContents = open(glade_file_name).read()

# scan the input string for matching tags
for widget,start,end in widgetStart.scanString(gladeContents):
print "good:", line(start, gladeContents).strip()
print widget["class"], widget["id"]
print "Class: %(class)s; Id: %(id)s" % widget

Not quite an exact match, only the good lines get listed.  But also check
out some of the other capabilities.  To do this with re's, you have to
clutter up the re expression with field names, as in:

(r'".*") id="(?P.*)">')

The parsing patterns generated by makeXMLTags give dict-like and
attribute-like access to any attributes included with the tag.  If not for
the unfortunate attribute name "class" (which is a Python keyword), you
could also reference these values as widget.class and widget.id.

If you are parsing HTML, there is also a makeHTMLTags method, which creates
patterns that are less rigid about upper/lower case and other XML
strictnesses.

-- Paul


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


Re: Array? Please help.

2006-05-28 Thread Dr. Pastor
No it is not home work.
(I have not did any home work for more than 50 years.)
I am a beginner, and just do not see a really proper
way to program the question.
Thanks anyhow.

Scott David Daniels wrote:

> Dr. Pastor wrote:
> 
>> I need a row of 127 bytes that I will use as a
>> circular buffer. Into the bytes (at unspecified times)
>> a mark (0> After some time the "buffer" will contain the last 127 marks.
> 
> 
> Sounds a lot like homework.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dynamic type changing

2006-05-28 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
>>>I'm working on a "TempFile" class that stores the data in memory until
>>>it gets larger than a specified threshold (as per PEP 42).  Whilst
>>>trying to implement it, I've come across some strange behaviour.  Can
>>>anyone explain this?
> 
> 
>>>The test case at the bottom starts a TempFile at size 50 and prints its
>>>type.  It then increases the size to the threshold at which point
>>>"self" is changed to being a TemporaryFile.
>  
>>Changed how ?-)
>  
> Just by being assigned with a TemporaryFile object.
 >
>  I thought that if
> you do
> 
> instance = TempFile()
> 
> that "instance" and "self" defined in the Class

They are not defined "in the class".

> were the same thing so
> that if you changed the class of self, 
> the class of instance would also
> change.

Yes, of course - but you didn't change the class of 'self' !-)

Python's "variable" are really just names "bound to" (referring to) 
objects. Rebinding (ie: assignment) does not impact the object (well, 
not directly), it just associate the name to another object. This is 
totally different from changing the state of the object.

There's nothing magical about the name 'self' - FWIW, you could replace 
it by any other valid python identifier. In Python, a method is just a 
plain function that takes the instance as the first argument. This 
function is wrapped into a method descriptor (google for python's 
descriptor protocol - it's the same thing that is used for properties) 
that takes care of feeding the function with the instance.

FWIW, given:
   class Obj(object):
 def someMethod(self):
   pass

   obj = Obj()

then
   obj.someMethod()

is the same as
   Obj.someMethod(obj)

or also:
   obj.someMethod.im_func(obj)


So, inside someMethod's code, normal scoping rules apply. This means 
that 'self' is a *local* name, and rebinding it only affect the local 
scope. And it doesn't "change the type" of the object (previously) bound 
to 'self', it really re-bind 'self' to another object (IOW: makes 'self' 
a reference to another object). Just like it does in any other Python code.

As I wrote, to dynamicall change the class of an object, you must rebind 
obj.__class__ to another class, ie:

class Other(object):
   def __init__(self, name):
 self.name = name

obj = Obj()
print type(obj)
obj.__class__ = Other
print type(obj)

Now a big warning : this is not garanteed to work seamlessly ! 'obj' 
will keep it's original instance attributes, and the instance attributes 
normally set up by the new class (here, 'Other') won't exist since the 
class initializer won't be called.

So, while this may not be a problem if the original and new classes are 
designed to be used that way (which makes a very straightforward 
implementation of the state pattern), it's usually not a good idea to do 
such a thing. FWIW, it's usually simpler and safer - evn if a bit less 
elegant - to implement the state pattern just like I did in the example: 
by using composition/delegation.

> Thanks very much for your example.

votre humble serviteur, Messire

>  It has solved my problem and helped
> me understand a new pattern at the same time.


FWIW, there's no clear, well defined boudary between State and Strategy 
- the main difference depends mostly on the intention. Your use case 
could also be viewed as a State pattern, with 2 states : buffer < 
capacity, and buffer >= capacity. But the intention is not to know in 
which state is the object - on the contrary, you're trying to hide away 
the chosen implementation (StringIO or TemporayFile) - so it's really a 
Strategy IMHO.

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


Beginner Python OpenGL difficulties

2006-05-28 Thread jg . campbell . ng
I'm beginning learning Python and OpenGL in Python.

Python fine. But difficulties with OpenGL; presumably with the
installation of OpenGL.

OS = Linux FC5.

Python program gl_test.py:

from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *

name = "Hello, World"
height = 400
etc.

[EMAIL PROTECTED]/etc/python>$ python2 gl_test.py

Traceback (most recent call last):
  File "gl_test.py", line 1, in ?
from OpenGL.GLUT import *
ImportError: No module named OpenGL.GLUT

[EMAIL PROTECTED]/etc/python>$ echo $PYTHONPATH
/usr/lib/python2.2/site-packages/OpenGL

[EMAIL PROTECTED]/usr/lib/python2.2/site-packages/OpenGL>$ ll
total 1076
drwxr-xr-x 13 root root   4096 May 28 15:17 Demo/
drwxr-xr-x  3 root root   4096 May 28 15:17 doc/
drwxr-xr-x 25 root root   4096 May 28 15:17 GL/
-rwxr-xr-x  1 root root 624927 Jan  2  2005 GLE.so*
drwxr-xr-x  4 root root   4096 May 28 15:17 GLU/
-rwxr-xr-x  1 root root 312612 Jan  2  2005 GLUT.so*
drwxr-xr-x  6 root root   4096 May 28 15:17 GLX/
-rw-r--r--  1 root root868 Mar 12  2004 __init__.py
-rw-r--r--  1 root root   1466 Jan  2  2005 __init__.pyc
etc ...

Any suggestions.

TIA,

Jon C.

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


propose extension of mimetypes

2006-05-28 Thread GHUM
Hello,


mimetypes lacks the guessing of .svg as image/svg+xml

mimetypes.add_type("image/svg+xml",".svg", True)

maybe this can be added to python 2.5 standard library


Harald

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


Finding a lost PYTHONPATH with find

2006-05-28 Thread John J. Lee
OK, this is really a reminder to myself next time I forget where I set
my PYTHONPATH and forget exactly how to invoke the GNU "find" command
;-)

Hope somebody else finds it useful too

find / -maxdepth 3 -size -100k -type f -exec grep -sli pythonpath '{}' \;


The minus in '-100k' (meaning "less than 100k") seems to be
undocumented, at least on my system.  I suppose the -maxdepth is
redundant since I think find searches breadth-first by default.

The file I was looking for turned out to be in /etc/profile.d/, whose
existence I completely forgot about...


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


Re: (mostly-)POSIX regular expressions

2006-05-28 Thread Paddy
maybe this: http://www.pcre.org/pcre.txt and ctypes might work for you?
(I was suprised to find out that PCRE supported POSIX but don't know
what version it supports or how well).

- Pad

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


Re: Array? Please help.

2006-05-28 Thread Scott David Daniels
Dr. Pastor wrote:
> Scott David Daniels wrote:
>> Dr. Pastor wrote:
>>> I need a row of 127 bytes that I will use as a
>>> circular buffer. Into the bytes (at unspecified times)
>>> a mark (0>> After some time the "buffer" will contain the last 127 marks.
>> Sounds a lot like homework.
> No it is not home work.

OK, taking you at your word, here's one way:

 class Circular(object):
 def __init__(self):
 self.data = array.array('b', [0] * 127)
 self.point = len(self.data) - 1

 def mark(self, value):
 self.point += 1
 if self.point >= len(self.data):
 self.point = 0
 self.data[self.point] = value

 def recent(self):
 result = self.data[self.point :] + self.data[: self.point]
 for n, v in enumerate(result):
 if v:
 return result[n :]
 return result[: 0] # an empty array
-- 
--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


itertools.count() as built-in

2006-05-28 Thread [EMAIL PROTECTED]
Is there any chance of itertools.count() ever becoming one of the
built-in functions? It's a wonderful little function and I find myself
importing it in every module I write.

-Janto

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


Re: (mostly-)POSIX regular expressions

2006-05-28 Thread Sébastien Boisgérault
Very good hint ! I wouldn't have found it alone ...

I have to study the doc, but the "THE DFA MATCHING ALGORITHM" may do
what I need Obviously, I didn't expect the Perl-Compatible Regular
Expressions to implement
"an alternative algorithm, provided by the pcre_dfa_exec() function,
that operates in a different way, and is not  Perl-compatible".

Maybe the lib should be renamed in PCREWSO for:
Perl-compatible regular expressions ... well, sort of :)

Cheers,

SB

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


html 2 plain text

2006-05-28 Thread robin
hi,
i remember seeing this simple python function which would take raw html
and output the content (body?) of the page as plain text (no <..> tags
etc)
i have been looking at htmllib and htmlparser but this all seems to
complicated for what i'm looking for. i just need the main text in the
body of some arbitrary webbpage to then do some natural-language
processing with it...
thanks for pointing me to some helpful resources!

robin

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


Fancy GUI with Python

2006-05-28 Thread 63q2o4i02
Hi all.  I just downloaded and installed the new Office suite from MS
with their new 'ribbon' based UI.  I think it's pretty cool and AFT*
for a new UI paradigm.  I hope it sticks.

Anyway, I'm wondering how to implement a gui like this with Python.  I
don't think wx or qt or gtk or tkinter support this sort of fading and
glowing type of effects... or do they?  I played with wx way back in
2000 or so (C++ version), and it certainly didn't have any of that.  I
don't know if this stuff is now built into XP, or if it's specialized
libraries only accessible to MS for their purposes.  Can a python gui
framework be redirected to use the new gui?  Or is this something that
has to be manually emulated from a low-level if python is to make use
of it?  What about under linux?

So I'm not sure if this is a Python question, a xxx-Python question
(where xxx is the widget toolkit of choice), or a windows API type of
question.

How does one make fancy fading guis with python? (cross-platform if
possible)

thanks
ms

*AFT = about freakin' time

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


Re: Array? Please help.

2006-05-28 Thread Scott David Daniels
Scott David Daniels wrote:
> Dr. Pastor wrote:
>> Scott David Daniels wrote:
>>> Dr. Pastor wrote:
 I need a row of 127 bytes that I will use as a
 circular buffer. Into the bytes (at unspecified times)
 a mark (0>>> After some time the "buffer" will contain the last 127 marks.
>>> Sounds a lot like homework.
>> No it is not home work.
> 
> OK, taking you at your word, here's one way:
>  (and some untested code)

As penance for posting untested code, here is a real implementation:

 import array

 class Circular(object):
 '''A circular buffer, holds only non-zero entries'''
 def __init__(self, size=127):
 '''Create as N-long circular buffer

 .data is the circular data store.
 .point is the index of the next value to write
 '''
 self.data = array.array('b', [0] * size)
 self.point = 0

 def mark(self, value):
 '''Add a single value (non-zero) to the buffer'''
 assert value
 self.data[self.point] = value
 self.point += 1
 if self.point >= len(self.data):
 self.point = 0

 def recent(self):
 '''Return the most recent values saved.'''
 result = self.data[self.point :] + self.data[: self.point]
 for n, v in enumerate(result):
 if v:
 return result[n :]
 return result[: 0] # an empty array

Tests:
 c = Circular(3)
 assert list(c.recent()) == []
 c.mark(12)
 assert list(c.recent()) == [12]
 c.mark(11)
 assert list(c.recent()) == [12, 11]
 c.mark(10)
 assert list(c.recent()) == [12, 11, 10]
 c.mark(9)
 assert list(c.recent()) == [11, 10, 9]


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


Re: send an email with picture/rich text format in the body

2006-05-28 Thread Ten
On Sunday 28 May 2006 07:27, anya wrote:
> Acctualy there is a solution:
> see  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810
> (thanks darrin massena for sharing)
>
> and , if you will set all the neccessary parametrs, it won't be
> recognized as a
> spam,
> thanks

Ahah - a slightly different thing to what I thought you were after.

I'd looked at "every one who open the email will see the picture" and
discounted html mail.

Glad you got what you wanted done, done.

Ten.

-- 
There are 10 types of people in this world,
those who understand binary, and those who don't.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: html 2 plain text

2006-05-28 Thread Faber
robin wrote:

> i remember seeing this simple python function which would take raw html
> and output the content (body?) of the page as plain text (no <..> tags
> etc)
> i have been looking at htmllib and htmlparser but this all seems to
> complicated for what i'm looking for. i just need the main text in the
> body of some arbitrary webbpage to then do some natural-language
> processing with it...
> thanks for pointing me to some helpful resources!

Have a look at the Beautiful Soup library:
http://www.crummy.com/software/BeautifulSoup/

Regards

-- 
Faber
http://faberbox.com/
http://smarking.com/

A teacher must always teach to doubt his teaching. -- José Ortega y Gasset
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Fancy GUI with Python

2006-05-28 Thread Ten
On Sunday 28 May 2006 19:25, [EMAIL PROTECTED] wrote:
> Hi all.  I just downloaded and installed the new Office suite from MS
> with their new 'ribbon' based UI.  I think it's pretty cool and AFT*
> for a new UI paradigm.  I hope it sticks.
>
> Anyway, I'm wondering how to implement a gui like this with Python.  I
> don't think wx or qt or gtk or tkinter support this sort of fading and
> glowing type of effects... or do they?  I played with wx way back in
> 2000 or so (C++ version), and it certainly didn't have any of that.  I
> don't know if this stuff is now built into XP, or if it's specialized
> libraries only accessible to MS for their purposes.  Can a python gui
> framework be redirected to use the new gui?  Or is this something that
> has to be manually emulated from a low-level if python is to make use
> of it?  What about under linux?
>
> So I'm not sure if this is a Python question, a xxx-Python question
> (where xxx is the widget toolkit of choice), or a windows API type of
> question.
>
> How does one make fancy fading guis with python? (cross-platform if
> possible)
>
> thanks
> ms
>
> *AFT = about freakin' time

Unless I'm missing something (I haven't examined it exhaustively), everything
therein seems quite easily doable using python and Qt. I'd check it out.


Ten

-- 
There are 10 types of people in this world,
those who understand binary, and those who don't.
-- 
http://mail.python.org/mailman/listinfo/python-list


why not in python 2.4.3

2006-05-28 Thread Rocco
hi
I made the upgrade to python 2.4.3 from 2.4.2.
I want to take from google news some atom feeds with a funtion like
this
import urllib2
def takefeed(url):
request=urllib2.Request(url)
request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5;
Windows NT')
opener = urllib2.build_opener()
data=opener.open(request).read()
return data
url='http://news.google.it/?output=rss'
d=takefeed(url)
This woks well with python 2.3.5 but does not work with 2.4.3.
Why?
Thanks

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


Re: Serializing / Unserializing datetime

2006-05-28 Thread Brendan
Thanks John.   I've discovered that datetime.strptime will be available
in 2.5, (http://docs.python.org/dev/whatsnew/modules.html) but your
example will work in the meantime.

BJ

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


Re: using FFTW3 with Numeric on Windows

2006-05-28 Thread Robert Kern
sven koenig wrote:
> hi list,
> as the subject says, I'm trying to find a way to use
> FFTW3 with Numeric arrays.
> I'm not very familiar with C(++) - I think ctypes is the
> way to go, but I don't really have a clue how to do it.
> Has somebody already tried this?

scipy can use FFTW3 as its FFT routines.

http://www.scipy.org

-- 
Robert Kern

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

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


Re: why not in python 2.4.3

2006-05-28 Thread Carl Banks

Rocco wrote:
> hi
> I made the upgrade to python 2.4.3 from 2.4.2.
> I want to take from google news some atom feeds with a funtion like
> this
> import urllib2
> def takefeed(url):
>   request=urllib2.Request(url)
>   request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5;
> Windows NT')
>   opener = urllib2.build_opener()
>   data=opener.open(request).read()
>   return data
> url='http://news.google.it/?output=rss'
> d=takefeed(url)
> This woks well with python 2.3.5 but does not work with 2.4.3.
> Why?

Define "woks [sic] well".  It works fine for me on 2.4.3 (and by "works
fine" I mean it ran without an exception and it returned what appeared
to be RSS data).  If you would give us an exception trace it would help
a lot.

Maybe Google's server (or your ISP's) was down.  That happens
sometimes.

Carl

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


Re: html 2 plain text

2006-05-28 Thread robin
lucks yummy. merci beaucoup.

robin

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


q - including manpages in setup.py

2006-05-28 Thread aum

Hi,

What is the best way to incorporate manpages in a distutils setup.py
script?

Is there any distro-independent way to find the most appropriate place to
put the manpages?
For instance, /usr/man/? /usr/share/man? /usr/local/man?
/usr/local/share/man?

Also - I've got .html conversions of the manpages, for the benefit of OSs
such as Windows which don't natively support manpages. What's the best
place to put these?

-- 

Cheers
aum


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


Re: Serializing / Unserializing datetime

2006-05-28 Thread Gerard Flanagan
Brendan wrote:
> Thanks John.   I've discovered that datetime.strptime will be available
> in 2.5, (http://docs.python.org/dev/whatsnew/modules.html) but your
> example will work in the meantime.
>
> BJ

I don't think it's what you want but I had the following on file - it
uses time.strptime() which I didn't know there was a problem with.  Not
tested beyond what you see.


import time
import datetime

DDMMYY = ['%d %m %Y', '%d %m %y', '%d/%m/%Y', '%d/%m/%y', '%d-%m-%Y',
'%d-%m-%y' ]

def yearmonthday(datestring, fmts=DDMMYY):
ymd = None
for f in fmts:
try:
ymd = time.strptime( datestring, f )
break
except ValueError:
continue
if ymd is None:
raise ValueError
return ymd[0], ymd[1], ymd[2]

def is_valid_date(datestring, fmts=DDMMYY):
try:
yearmonthday(datestring, fmts)
return True
except ValueError:
return False

def string_to_date(datestring, fmts=DDMMYY):
return datetime.date( *yearmonthday(datestring, fmts) )

assert string_to_date( '1/2/01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '1 2 01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '01/02/01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '1/02/2001', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '29/02/2008', DDMMYY) ==
datetime.date(2008,2,29)
assert string_to_date( '01/2/99', DDMMYY) == datetime.date(1999,2,1)

for d in [ '', '32/1/01', '01/13/01', '29/2/07', '1/2', 'abcdef' ]:
assert not is_valid_date(d, DDMMYY)


Gerard

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


Re: Fancy GUI with Python

2006-05-28 Thread Ravi Teja
> Hi all.  I just downloaded and installed the new Office suite from MS
> with their new 'ribbon' based UI.  I think it's pretty cool and AFT*
> for a new UI paradigm.  I hope it sticks.

> Anyway, I'm wondering how to implement a gui like this with Python.

I haven't seen their new Office suit (apart form a few screenshots).
Judging from the past, the code is probably statically linked to MS
Office. Many of the previous iterations of MS Office did introduce
their own look and feels, effects and widgets. Third party Windows
developers soon followed suit reimplementing the widgets. Delphi
community for example focuses a lot on UI and UI effects (Python
community does not). VCL libraries can be compiled to ActiveX
components and you should then be able to use them from Python, at
least on Windows. Or maybe someone will make a .NET assembly and you
will be able to drive it from IronPython or Python for .NET. If you are
lucky, it may even be cross-platform via Mono.

> So I'm not sure if this is a Python question, a xxx-Python question
> (where xxx is the widget toolkit of choice), or a windows API type of
> question.

This is NOT a Python specific issue. It is a widget library and FFI
(Foreign Function Interface) issue. If another language can get at the
functionality, so can Python.

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


Re: html 2 plain text

2006-05-28 Thread Ravi Teja
> i remember seeing this simple python function which would take raw html
> and output the content (body?) of the page as plain text (no <..> tags
> etc)

http://www.aaronsw.com/2002/html2text/

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


Re: Array? Please help.

2006-05-28 Thread Dr. Pastor
Many thanks to you all. (Extra thanks to Mr. Daniels.)

Dr. Pastor wrote:
> I need a row of 127 bytes that I will use as a
> circular buffer. Into the bytes (at unspecified times)
> a mark (0 After some time the "buffer" will contain the last 127 marks.
> (A pointer will point to the next byte to write to.)
> What would be the Pythonic way to do the above?
> Thanks for any guidance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Array? Please help.

2006-05-28 Thread Diez B. Roggisch
George Sakkis schrieb:
> Diez B. Roggisch wrote:
>> Dr. Pastor schrieb:
>>> I need a row of 127 bytes that I will use as a
>>> circular buffer. Into the bytes (at unspecified times)
>>> a mark (0>> After some time the "buffer" will contain the last 127 marks.
>>> (A pointer will point to the next byte to write to.)
>>> What would be the Pythonic way to do the above?
>>> Thanks for any guidance.
>> Use a list, use append and slicing on it:
>>
>>
>> max_size = 10
>> buffer = []
>>
>> for i in xrange(100):
>>  buffer.append(i)
>>  buffer[:] = buffer[-max_size:]
>>  print buffer
>>
>>
>> Diez
> 
> You're not serious about this, are you ?

Tell me why I shouldn't. I presumed he's after a ringbuffer. Ok, the 
above lacks a way to determine the amount of bytes added since the last 
read. Add a counter if you want. And proper synchronization in case of a 
multithreaded environment. But as the OP was sketchy about what he 
actually needs, I thought that would at least give him a start.

Maybe I grossly misunderstood his request. But I didn't see your better 
implementation so far. So - enlighten me.


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


HTMLParser chokes on bad end tag in comment

2006-05-28 Thread Rene Pijlman
The code below results in an exception (Python 2.4.2):

HTMLParser.HTMLParseError: bad end tag: "", at line 4,
column 6

Should it? The end tag it chokes on is in comment, isn't it?

import HTMLParser
HTMLParser.HTMLParser().feed("""



""")

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why not in python 2.4.3

2006-05-28 Thread Rene Pijlman
Rocco:
>but does not work with 2.4.3.

Define "does not work".

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: why not in python 2.4.3

2006-05-28 Thread Rocco
This is the problem when I run the function
this is the result from 2.3.5
>>> print rss
http://purl.org/atom/ns#";>NFE/1.0Google
News Italiahttp://news.google.it/"/>Google News
ItaliaGoogle
Inc.[EMAIL PROTECTED]©2006
Google2006-05-28T19:09:13+00:00
Benedetto XVI: Wojtyla santo subito - LibertÃ
http://www.liberta.it/default.asp?IDG=605282024"/>tag:news.google.com,2005:cluster=41b535fbPrima
pagina2006-05-28T11:05:00+00:002006-05-28T11:05:00+00:00
>> import sys >>> sys.getdefaultencoding() 'ascii' >>> this is the result with 2.4.3 >>> print rss ヒ >>> rss '\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff\xe5}Ks\xe3F\xb6\xe6\xfeF\xdc\xff\x90\xd77\xba\xc3\x9e\x10D\xbc\x01\xcaU\xee\xa1\x9eM[\xa2\xd4$\xabl\xf7\x86\x93\x04\x93Tv\x81H\x1a\x0fV\xa9V\xfe\x0f3\x9b\x8e\x98\x89\xb8\xcb\x1b\xd1\xb3\x9a\xddD\xef\xec\x7f\xe2_2\xe7$\x00\x8a/\x11|\x93\xd6\xb4\xa3U"\x04\x02\x99\xe7d\x9e<\xdfy\xbe\xf9\xd3\xa7\xbeO\x86,\x8c\xb8\x08\xde~\xa1\x9d\xaa_\x10\x16x\xa2\xc3\x83\xde\xdb/\xde5\xaf\x15\xf7\x8b?}\xf3&\x8c\xa2\xe7\x9bt\xb8\xe9\x9b7\xde#\r\x02\xe6\x7f\xf3\xa6\xc7\x02\x16\xd2X\x84\xdf\xd4\xae\xafJ\xf0\x847\xa5\xe7Kob\x1e\xfb\xec\x9b\x1b!z>#5\xf61"\xd5\x98\xfa\x9c\xbe)\xa5\x7fy\xe3\xf3\xe0\xc37\x8fq<8+\x95\x02\xf8\xfbiO\xde{\xca\xe3\xd2\x9b\x92\xfc\xe3\x9b\x0e\x8b\xbc\x90\x0fbx\xfb\xdc\'\x8d\xff\xfd\x8dO\x83^B{\xec\x1b\x1e\xc3\xf7\xf3\x0fo>\xb2\xf6\x1d\x8db\x16~\x83/Q\xba\x8cu\xda\xd4\xfb\xf0_\xb3\xb7y\xa2\xff\xa6\xf4|\xcf\x1bO\x0c\x9eB\xde{\x8c\xbf\xf9#\xed\x0f\xbe\xc6\x8f_\xeb\xaaj\x93\xf4\xfdoJ\xcf7\xbc\x19$\xedK\x1a\xb3o\x1aIpBt\x97\xdc\xd1\'"\xef\xd5\xb53\xcd<3\x1crs\xd7|S\xcao\x83\x11F\xf1y\xc2\xfd\xce2\xdf\x9a\xbc\xf9_\xff\xe5\xcd\xbf)\n\xa9\x10O$\x03 C b\x16\x9d\xfd\xeb\xbf\x10\xfc\xdf\x7f!\xb4\xd3!4 [EMAIL PROTECTED]'\xb1 =\x16\x93z\xa31\xba9b\x1eR\x0cn\xe8\xb1\x88<\xd2!#\x94|\x11\x8b\x01\xf7\xde\xfe)\xfb\xde\xd7\xd9\xdd\x84$\x11\xcb\xff\xf8\xf8\x05\xe9\x8a\x10nn\x8a\x01i\x00\x979|?{\xda\xe9\xbf\xfe\x8b\xa2|\xf3\x86\xf7%\xd1\x0b\x99\x9f\x84\xfe<\xde\x037J<\x88\xfd\x12\x8f[\xb0\x0e\xe4\xd3"yG+dp\x17\xef\xbe)\xe1W\x97Y<\xa5l,~\xfcx\xca\xfd\x18_\x82\x0f\xa1\x83A(\xba"\xe8\xf0>\x0bb\x0e\x04\xea\xb0O\xa74\x >>> import sys >>> sys.getdefaultencoding() 'latin_1' >>> No exception trace Thanks again -- http://mail.python.org/mailman/listinfo/python-list

Re: Using a package like PyInstaller

LittlePython wrote:
> "Im 99.999% confident that this will not happen from the .exe file
> generated by pyinstaller (unless you specify--see link above)."
> 
> Well I guess that's about as close as any one can get in this business. I
> have been trying to introduce py into our environment, and have opened a few
> eyes, however I have been given one restriction. I can not install anything,
> leave behind anything or alter anything on a systems .. period,


You can always hard-code external resources. For example, first write a 
script that makes a module out of one or several jpegs (assuming jpeg 
extension is consitently 'jpg':

import binascii

def append_to_jpeg_module(modulename, jpegs):
   myjpegs = open('%s.py' % modulename, 'wa')
   for jpegname in jpegs:
 afile = open('%s.jpg' % jpegname, 'rb')
 ajpeg = afile.read()
 afile.close()
 jpegascii = binascii.b2a_base64(ajpeg)
 print jpegascii
 myjpegs.write('%s = """%s"""\n\n' % (jpegname, jpegascii))
   myjpegs.close()

append_to_jpeg_module('myjpegs', ['logo_sm'])

#heres how you use it
append_to_jpeg_module('myjpegs', ['coolpik1', 'coolpik2', 'anotherpik'])

Now, in your file that needs the jpegs, you can pretend these strings 
are files with the cStringIO module, e.g. (pretending 'modulename' above 
is 'myjpegs'):

import binascii
import myjpegs
import cStringIO

def get_jpeg_as_opened_file(jpegname, module):
   jpegascii = module.__dict__[jpegname]
   jpegbin = binascii.a2b_base64(jpegascii)
   return cStringIO.StringIO(jpegbin)

# getting that pik
get_jpeg_as_opened_file('coolpik1', myjpegs)


And your company can go on making widgets feeling secure in the fact 
that you have not required any extra entries in their file allocation 
tables.

James

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

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


Re: (mostly-)POSIX regular expressions


Paddy a écrit :

> maybe this: http://www.pcre.org/pcre.txt and ctypes might work for you?

Well finally, it doesn't fit. What I need is a "longest match" policy
in
patterns like "(a)|(b)|(c)" and NOT a "left-to-right" policy.
Additionaly,
I need to be able to obtain the matched ("captured") substring and
the PCRE does not allow this in DFA mode.

Too bad ...

SB

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


Re: Serializing / Unserializing datetime

On 29/05/2006 5:23 AM, Brendan wrote:
> Thanks John.   I've discovered that datetime.strptime will be available
> in 2.5, (http://docs.python.org/dev/whatsnew/modules.html) but your
> example will work in the meantime.
> 

Only in the meantime? I would thought there was a good chance it would 
continue to work in 2.5 -- especially as I tested it with 2.5a2 :-)

Hmmm ... now you've got me thinking, maybe there's an anti-DIY 
enforced-use-of-official-functionality gadget in 2.5. Just because I'm 
paranoid doesn't mean the PSU isn't out to ~;{[]=]|\ 

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


pygame and wxpython

I'm somewhat new to Python but not to programming.

I just want to know if it's possible to have a SINGLE wxPython frame
containing two sections where one will contain widgets and the other
will host an animation done using PyGame.

More specifically, I want to have a list of names of animations on the
left and depending on what is selected, run the PyGame animation in the
main area.

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


Re: Serializing / Unserializing datetime

On 29/05/2006 6:27 AM, Gerard Flanagan wrote:

> I don't think it's what you want but I had the following on file - it
> uses time.strptime() which I didn't know there was a problem with. 

In 2.3, time.strptime became a pure-Python routine, thus losing its 
dependency on the existence and correctness of the strptime in the C 
library.

However, the whole time module has a problem: the range of years it 
handles -- 1970 to 2038 (maybe). This is documented on the first page of 
The Fine Manual. Not very useful for customer's date of birth, and (as 
Brendan indicated), likely to cause Y2.038K problems.

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


Re: (mostly-)POSIX regular expressions

On 29/05/2006 7:46 AM, Sébastien Boisgérault wrote:
> Paddy a écrit :
> 
>> maybe this: http://www.pcre.org/pcre.txt and ctypes might work for you?
> 
> Well finally, it doesn't fit. What I need is a "longest match" policy
> in
> patterns like "(a)|(b)|(c)" and NOT a "left-to-right" policy.
> Additionaly,
> I need to be able to obtain the matched ("captured") substring and
> the PCRE does not allow this in DFA mode.
> 

Perhaps you might like to be somewhat more precise with your 
requirements. "POSIX-compliant" made me think of yuckies like [:fubar:] 
in character classes :-)

The operands of | are such that the length is not fixed and so you can't 
write them in descending length order? Care to tell us some more detail 
about those operands?

If those operands are simple strings (LOGICAL|LOGIC|LOG) and you've got 
more than a handful of them, try Danny Yoo's ahocorasick module.

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


Re: Using a package like PyInstaller

Thx for the tip ... I'll give it a go


"James Stroud" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> LittlePython wrote:
> > "Im 99.999% confident that this will not happen from the .exe file
> > generated by pyinstaller (unless you specify--see link above)."
> >
> > Well I guess that's about as close as any one can get in this business.
I
> > have been trying to introduce py into our environment, and have opened a
few
> > eyes, however I have been given one restriction. I can not install
anything,
> > leave behind anything or alter anything on a systems .. period,
>
>
> You can always hard-code external resources. For example, first write a
> script that makes a module out of one or several jpegs (assuming jpeg
> extension is consitently 'jpg':
>
> import binascii
>
> def append_to_jpeg_module(modulename, jpegs):
>myjpegs = open('%s.py' % modulename, 'wa')
>for jpegname in jpegs:
>  afile = open('%s.jpg' % jpegname, 'rb')
>  ajpeg = afile.read()
>  afile.close()
>  jpegascii = binascii.b2a_base64(ajpeg)
>  print jpegascii
>  myjpegs.write('%s = """%s"""\n\n' % (jpegname, jpegascii))
>myjpegs.close()
>
> append_to_jpeg_module('myjpegs', ['logo_sm'])
>
> #heres how you use it
> append_to_jpeg_module('myjpegs', ['coolpik1', 'coolpik2', 'anotherpik'])
>
> Now, in your file that needs the jpegs, you can pretend these strings
> are files with the cStringIO module, e.g. (pretending 'modulename' above
> is 'myjpegs'):
>
> import binascii
> import myjpegs
> import cStringIO
>
> def get_jpeg_as_opened_file(jpegname, module):
>jpegascii = module.__dict__[jpegname]
>jpegbin = binascii.a2b_base64(jpegascii)
>return cStringIO.StringIO(jpegbin)
>
> # getting that pik
> get_jpeg_as_opened_file('coolpik1', myjpegs)
>
>
> And your company can go on making widgets feeling secure in the fact
> that you have not required any extra entries in their file allocation
> tables.
>
> James
>
> -- 
> James Stroud
> UCLA-DOE Institute for Genomics and Proteomics
> Box 951570
> Los Angeles, CA 90095
>
> http://www.jamesstroud.com/


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


Re: itertools.count() as built-in

On 29/05/2006 4:14 AM, [EMAIL PROTECTED] wrote:
> Is there any chance of itertools.count() ever becoming one of the
> built-in functions? It's a wonderful little function and I find myself
> importing it in every module I write.
> 

Every module?? Do you use any/many other itertools functions? Care to 
give us a sample of your typical usage of itertools.count?

Cheers,
John

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


Re: pygame and wxpython


DK wrote:
> I'm somewhat new to Python but not to programming.
>
> I just want to know if it's possible to have a SINGLE wxPython frame
> containing two sections where one will contain widgets and the other
> will host an animation done using PyGame.
>
> More specifically, I want to have a list of names of animations on the
> left and depending on what is selected, run the PyGame animation in the
> main area.

I have not seen this done but you should note that both wxPython and
Pygame run their own event loops - which can cause some serious
problems.

However, here's a link that may help you get started on trying to do
what you're looking for.
http://wiki.wxpython.org/index.cgi/IntegratingPyGame?highlight=%28pygame%29

André

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


Re: send an email with picture/rich text format in the body

"anya" <[EMAIL PROTECTED]> writes:

> Acctualy there is a solution:
> see  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810

Again, sending anything but plain text as the message body ensures
that your message is unreadable to a large number of people using a
variety of software. It's your choice whether to restrict your
audience in this way, but know that that's what you're doing.

If your message is going to be accompanied by a plain text body anyway
(as advised by the recipe you refer to), that plain text body is either
sufficient to give the necessary information, or not.

If the plain text is sufficient, please don't bloat the message with
the same information in an inefficient, non-standard message body. If
the plain text is not sufficient to say what you want to say, please
use a means of distributing it other than email.

> and , if you will set all the neccessary parametrs, it won't be
> recognized as a spam,

For many people, who have trained their spam classifier with the
majority of spam they receive, the simple fact that it contains HTML
and images *at all* is enough to classify it as spam.

-- 
 \   "Prediction is very difficult, especially of the future."  -- |
  `\Niels Bohr |
_o__)  |
Ben Finney

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


Re: pygame and wxpython


"DK" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> I'm somewhat new to Python but not to programming.
>
> I just want to know if it's possible to have a SINGLE wxPython frame
> containing two sections where one will contain widgets and the other
> will host an animation done using PyGame.
>
> More specifically, I want to have a list of names of animations on the
> left and depending on what is selected, run the PyGame animation in the
> main area.

I am sure that some PyGamers have used pygame with wxpython.  If you don't 
get an answer here, I suggest asking on the pygame list, gatewayed to 
gmane.comp.python.pygame. (news.gmane.org) 



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


Re: itertools.count() as built-in

I have a project of around 6000 lines where I used count() 20 times. It
has 14 modules, 10 of which I needed an explicit import.

Many of the usages are of the form:

for item, n in zip(items, count(N)):
 dostuff

Around half of these are due to using pylab.subplot(x,y.n), which
requires values for n>=1. So I want N=1. The enumerate builtin starts
from 0.
I also write out textual reports that start with n=1.

I also have things like
  for n, component, rotations in zip(count(),
sorted(tools.component_files().keys()), all_symbol_rotations)
where the enumerate version just looks even more confusing and easy to
mess up
  for n, component, rotations in
enumerate(sorted(tools.component_files().keys()), all_symbol_rotations)

Some more examples follow. Note that I find it more natural to specify
the count last as it's usually less important than the other values.
This is different from the order given by enumerate, so I'm more
inclined to use count().

mutated_symbols_and_names = zip(mutated_symbols, (("<%s mutation %s>" %
(component, m)) for m in count()))
edge_weight=dict(zip(Intersection.types, count(1)))
for (component, filename), n in zip(components, count()):
for (component, filename), component_count in
zip(tools.component_files().items(), count()):

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


Re: itertools.count() as built-in

Oh and I use repeat, chain and cycle quite a bit. But I don't mind
importing them as they are usually limited to one module.

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


Re: itertools.count() as built-in

[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> I have a project of around 6000 lines where I used count() 20 times. It
> has 14 modules, 10 of which I needed an explicit import.
> 
> Many of the usages are of the form:
> 
> for item, n in zip(items, count(N)):
>  dostuff
> 
> Around half of these are due to using pylab.subplot(x,y.n), which
> requires values for n>=1. So I want N=1. The enumerate builtin starts
> from 0.

Hmmm, makes me wonder if enumerate should grow optional arguments for
starting and stepping... I've found myself in similar situations, using
"x*i+y" on the i returned by enumerate, or zipping an xrange instead...


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


pyswt SWT.NULL

hi-

i am trying to make a pyswt gui and when it gets to this line:
 colType = Combo(self.shell, SWT.NULL)

i get:
colType = Combo(self.shell, SWT.NULL)
AttributeError: NULL

when using swt with java i had to have lots of imports at the beginning of a 
swt file.
are they not needed when using pyswt?

thanks for any help,
jim 


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


Re: pyswt SWT.NULL

I got it.  it is SWT.None

thanks,
jim

"3rdshiftcoder" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> hi-
>
> i am trying to make a pyswt gui and when it gets to this line:
> colType = Combo(self.shell, SWT.NULL)
>
> i get:
> colType = Combo(self.shell, SWT.NULL)
> AttributeError: NULL
>
> when using swt with java i had to have lots of imports at the beginning of 
> a swt file.
> are they not needed when using pyswt?
>
> thanks for any help,
> jim
> 


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


Re: itertools.count() as built-in

On 29/05/2006 9:50 AM, [EMAIL PROTECTED] wrote:
> I have a project of around 6000 lines where I used count() 20 times. It
> has 14 modules, 10 of which I needed an explicit import.
> 
> Many of the usages are of the form:
> 
> for item, n in zip(items, count(N)):
>  dostuff
> 
> Around half of these are due to using pylab.subplot(x,y.n), which
> requires values for n>=1. So I want N=1. The enumerate builtin starts
> from 0.

Call me a Luddite if you will, but I'd suggest that instead of
for item, n in zip(items, count(N)):
 dostuff(item, n)
you try
(1)
for n, item in enumerate(items):
 dostuff(item, n+N)
or (2)
n = N-1
for item in items:
 n += 1
 dostuff(item, n)

> I also write out textual reports that start with n=1.
> 
> I also have things like
>   for n, component, rotations in zip(count(),
> sorted(tools.component_files().keys()), all_symbol_rotations)
> where the enumerate version just looks even more confusing and easy to
> mess up
>   for n, component, rotations in
> enumerate(sorted(tools.component_files().keys()), all_symbol_rotations)

As enumerate takes only 1 argument, I presume that is the messed-up version.

Yes, the correct version is a pain:
for n, (component, rotations) in enumerate(zip(yadda1, yadda2)):

Perhaps you could use something like this:

 >>> def zipwithcount(N, *args):
... for x, guff in enumerate(zip(*args)):
... yield guff + (x + N,)
...
 >>> list(zipwithcount(666, 'abc', 'xyz'))
[('a', 'x', 666), ('b', 'y', 667), ('c', 'z', 668)]
 >>>

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


Re: Best way to check that a process is running on a Unix system?

Arthur Pemberton wrote:

> What is the best way to check that a process is running (or better yet
> number of instances) based on the name of the process? Would have to
> work on a unix/linux system.

Did you try pidof?

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


Re: why not in python 2.4.3

Rocco wrote:

> >>> import sys
> >>> sys.getdefaultencoding()
> 'latin_1'

Don't change default encoding. It should be always ascii.

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


Re: Array? Please help.

Diez B. Roggisch wrote:

> George Sakkis schrieb:
> > Diez B. Roggisch wrote:
> >> Dr. Pastor schrieb:
> >>> I need a row of 127 bytes that I will use as a
> >>> circular buffer. Into the bytes (at unspecified times)
> >>> a mark (0 >>> After some time the "buffer" will contain the last 127 marks.
> >>> (A pointer will point to the next byte to write to.)
> >>> What would be the Pythonic way to do the above?
> >>> Thanks for any guidance.
> >> Use a list, use append and slicing on it:
> >>
> >>
> >> max_size = 10
> >> buffer = []
> >>
> >> for i in xrange(100):
> >>  buffer.append(i)
> >>  buffer[:] = buffer[-max_size:]
> >>  print buffer
> >>
> >>
> >> Diez
> >
> > You're not serious about this, are you ?
>
> Tell me why I shouldn't. I presumed he's after a ringbuffer. Ok, the
> above lacks a way to determine the amount of bytes added since the last
> read. Add a counter if you want. And proper synchronization in case of a
> multithreaded environment. But as the OP was sketchy about what he
> actually needs, I thought that would at least give him a start.
>
> Maybe I grossly misunderstood his request. But I didn't see your better
> implementation so far. So - enlighten me.

Strange; there are two threads on this and my reply was sent to the
first one: http://tinyurl.com/lm2ho. In short, adding a new mark should
be a simple O(1) operation, not an O(buf_size). This is textbook
material, that's why I wasn't sure if you meant it.

George

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


Re: generating random passwords ... for a csv file with user details

Hi ALL,

I am sorry for not mentioning that I am new to python and scripting.
How can I add the above script to handle csv file. I want the script to
generate passwords in the passwords column/row in a csv file.

userid,realname,dateofB,passwd

The script should read the userid and genrate the password for each
user id (there are thousands of userids)

Kanthi

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


Re: Method Delegation To Subinstances

I could then fill the getattr function with different conditional statements as needed, cool. Thanks Steve!On 5/27/06, Steve Holden <
[EMAIL PROTECTED]> wrote:Cloudthunder wrote:> In the example:>
> class Boo:> def __init__(self, parent):> self.parent = parent> print self.parent.testme> def run():> print "Yaho!">> class Foo:
> testme = "I love you!"> def __init__(self):> test = Boo(self)>> A = Foo()>>> How can I set up method delegation so that I can do the following:
>> A.run()>> and have this call refer to the run() method within the boo instance?> Also, what if I have tons of functions like run() within the boo> instance and I want all them to be directly accessible as if they were
> part of their parent (the Foo instance)?>The usual way is to provide a __getattr__ method, since this is invokedafter the usual mechanisms have failed to produce a sought attribute.class Boo:
 def run(self): print "Yaho!" def identify(self):print repr(self)class Foo: testme = "I love you!" def __init__(self): self.test
 = Boo() def __getattr__(self, attname): return getattr(self.test, attname)A = Foo()B = Boo()B.run()B.identify()A.run()A.identify()[EMAIL PROTECTED] ~/Projects/Python
$ python test49.pyYaho!<__main__.Boo instance at 0x186c002c>Yaho!<__main__.Boo instance at 0x186b9d4c>regards  Steve--Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.comLove me, love my blog  http://holdenweb.blogspot.comRecent Ramblings 
http://del.icio.us/steve.holden--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: q - including manpages in setup.py

aum wrote:
> Hi,
>
> What is the best way to incorporate manpages in a distutils setup.py
> script?
>
> Is there any distro-independent way to find the most appropriate place to
> put the manpages?
> For instance, /usr/man/? /usr/share/man? /usr/local/man?
> /usr/local/share/man?

What do you mean distro? Linux? That should be /usr/local/man but AFAIK
some distros are misconfigured and their man doesn't search /usr/local
by default, YMMV.

> Also - I've got .html conversions of the manpages, for the benefit of OSs
> such as Windows which don't natively support manpages. What's the best
> place to put these?

your_tool --html-manual that uses os.start or webbrowser module to
invoke html viewer. Or your_tool --man that dumps plain text on the
screen.

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


Re: iteration over non-sequence ,how can I resolve it?

python wrote:
> To BJörn Lindqvist :
>  thank you . how to write the code specifically ?Could you give a
> example?

Use Queue module:

import threading
from Queue import Queue

class PrintThread(threading.Thread):
  def __init__(self, urlList, results_queue):
threading.Thread.__init__(self)
urllist=[]
self.urllist=urlList
self.results_queue = results_queue
  def run(self):
urllink=[self.urllist] * 2
self.results_queue.put(urllink)

results = Queue()
threadList = []
for i in range(0,2):
thread=PrintThread("Thread"+str(i), results)
threadList.append(thread)
thread.start()

for i in threadList:
linkReturned = results.get()
for j in linkReturned:
print j

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


dynamically loaded libraries

I have a question about how dynamically loaded C++ modules work, which
I will phrase as a hypothetical scenario involving the Numeric module.
 Please understand that I don't really care about Numeric per se, it's
just a useful example of a module that defines a generally useful data
type.

Let's say I want to create a C++ Python extension module that has
methods accepting the Numeric array type as input, and also create
these arrays as output. 

In order to make this work, do I have to statically link against the
Numeric source, or do I only have to include the headers, under the
assumption (??) that the Numeric functionality will be available
because the Python executable has dynamically loaded it?

Thanks!

Mike



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


Re: dynamically loaded libraries

mhearne808 wrote:
> I have a question about how dynamically loaded C++ modules work, which
> I will phrase as a hypothetical scenario involving the Numeric module.
>  Please understand that I don't really care about Numeric per se, it's
> just a useful example of a module that defines a generally useful data
> type.
> 
> Let's say I want to create a C++ Python extension module that has
> methods accepting the Numeric array type as input, and also create
> these arrays as output. 
> 
> In order to make this work, do I have to statically link against the
> Numeric source, or do I only have to include the headers, under the
> assumption (??) that the Numeric functionality will be available
> because the Python executable has dynamically loaded it?

Here's how Numeric/numarray/numpy do it (I'll discuss numpy since it is the
currently developed one):

Pointers to each of the API items that we want to export, types and functions
mostly, are packed into a void** array, PyArray_API. A common header file is
used by the numpy extension module that provides the API (multiarraymodule.so)
and each of the modules that use the API. We use #ifdefs to determine whether to
use real prototypes (for multiarray) or #defines that index into PyArray_API and
cast the function pointer there to the appopriate prototype (for everybody 
else).

In initmultiarray(), we actually pack PyArray_API with the appropriate pointers
and create a PyCObject that points to the beginning of the array. The CObject is
assigned to multiarray._ARRAY_API . We define a function import_array() for the
API-users that will import multiarray, get the object _ARRAY_API and assign
pointer to the beginning of the array to void **PyArray_API. import_array() is
supposed to be called in the initialization function of the other extension
modules. That will make sure that multiarray is imported and the function
pointers are available for dereferencing.

-- 
Robert Kern

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

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


Re: generating random passwords ... for a csv file with user details

Something like:

import csv
in_csv=csv.reader( file('your INPUT filenamehere.csv') )
out_csv=csv.writer( file('your OUPUT filenamehere.csv','wb') )
## If you have a header record on your input file, then
out_csv.writerow( in_csv.next() )
## Iterate over your input file
for row in in_csv:
# Row will be a list where row[0]=userid and row[3]=passwd
password=some_function_as_advised_by_rest_of_group()
# Assuming you want to write password as new field then
out_csv.writerow( row + [password] )
# Assuming you want to over-write password field then
row[3] = password
out_csv.writerow(row)

All the best,

Jon.

k.i.n.g. wrote:
> Hi ALL,
>
> I am sorry for not mentioning that I am new to python and scripting.
> How can I add the above script to handle csv file. I want the script to
> generate passwords in the passwords column/row in a csv file.
>
> userid,realname,dateofB,passwd
>
> The script should read the userid and genrate the password for each
> user id (there are thousands of userids)
> 
> Kanthi

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


Re: Python for my mum

Many thanks for the helpful links.

I don't think she's going to start programming, but at least she can
run her French grammar program.

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


Re: Large Dictionaries

Klaas schrieb:

> 4. Insert your keys in sorted order.
This advice is questionable -
it depends on the at least on the db vendor and probably
sometimes on the sort method, if inserting pre-sorted
values is better.

My gut feeling on this matter is:
IF the insert times of pre-sorted values is far better
than the times of unsorted values, there is a chance
that the resulting tree is unbalanced: only 1 compare
operation after insert and no re-balancing of the tree.

re-indexing will probably give you far better access times
in this case. Another option is to drop non RI indexes used only
for query optimization and recreate them after batch insert.

my 0.02 EUR

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


deleting item from ListCtrl by pop-up menu

hi all,
i need more information on the EVT_LIST_DELETE_ITEM()
for a list ctrl! iam not able to delete the selected
list item from the popup menu...below i have given the
part of the code ... im using popup menu... wher am i
wrong any suggestions wud b of great help...


list.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, 
self.OnRightClick)
def OnRightClick(self, event):
# Pop Up Menu Initialisation
self._menu_popup = wx.Menu()
[
self._ID_MENU_POPUP_DELETE,
] = [wx.NewId() for i in range(2)]

'Pop Up Menu'
self.Bind(wx.EVT_MENU, self.OnPopupDelete, id
= self._ID_MENU_POPUP_DELETE)  
  
self._menu_popup.Append(self._ID_MENU_POPUP_DELETE,
'Delete')

self.PopupMenu(self._menu_popup)
self._menu_popup.Destroy()

def OnPopupDelete(self, event):
self.Bind(wx.EVT_LIST_DELETE_ITEM,
self.OnDelete)

def OnDelete(self):
print "Del"
self.remove()


thanx in advance,
SendhilKumar B.Tech

__
Do You Yahoo!?
Tired of spam?  Yahoo! Mail has the best spam protection around 
http://mail.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Need C# Coding for MD5 Algorithm...

Hi all,

I need C# code for Implementing MD5 Algorithm.. Hope all would have
heard of MD5 Algorith... Does any one have the C# coding for that
Algorithm.. please Send... ITs URgent.

Thanks In Advance to all...

With Regards,

Sanjay.C

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


Re: HTMLParser chokes on bad end tag in comment

Rene Pijlman wrote:

> The code below results in an exception (Python 2.4.2):
> 
> HTMLParser.HTMLParseError: bad end tag: "", at line 4,
> column 6
> 
> Should it? The end tag it chokes on is in comment, isn't it?

no.  STYLE and SCRIPT elements contain character data, not parsed 
character data, so comments are treated as characters, and the first 
"

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


Re: Need C# Coding for MD5 Algorithm...

> I need C# code for Implementing MD5 Algorithm.

So ask in a C# group.
Python's is here
http://docs.python.org/lib/module-md5.html

> please Send... ITs URgent

http://www.catb.org/~esr/faqs/smart-questions.html#urgent

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


generating random passwords ... for a csv file with user details

Hi,

I have a csv file which in taken as the input file for adding users in
my linux mail server with the format

userid,fullname,passwword,dateofbith

Now I have to write a script to generate random password in the
password field for each user. A simple algorithm is sufficient for
passwords

I being new to scripting would seek all your help in doing so

Thanks In advance

kanthi

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


Re: Pyrex speed

The stuff you do are not representative of 100% of programming
conducted in the world. Not even 90% and probably not even 50% of
programming work is similar to what you do.
The fact you never use sophisticated math doesn't mean this guy doesn't
either.
Personally, I've used pyrex a lot. And it was never for wrapping -
always for speeding up.

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


Re: dynamic type changing

>> I'm working on a "TempFile" class that stores the data in memory until
>> it gets larger than a specified threshold (as per PEP 42).  Whilst
>> trying to implement it, I've come across some strange behaviour.  Can
>> anyone explain this?

>> The test case at the bottom starts a TempFile at size 50 and prints its
>> type.  It then increases the size to the threshold at which point
>> "self" is changed to being a TemporaryFile.

> Changed how ?-)

Just by being assigned with a TemporaryFile object.  I thought that if
you do

instance = TempFile()

that "instance" and "self" defined in the Class were the same thing so
that if you changed the class of self, the class of instance would also
change.

Thanks very much for your example.  It has solved my problem and helped
me understand a new pattern at the same time.

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


Re: generating random passwords ... for a csv file with user details

import random

def rand_str(len):
chars = ''.join(['abcdefghijklmnopqrstuvwxyz',
 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
 '1234567890',
 '_+']) # plus whatever additional characters you
want
return ''.join([random.choice(chars) for i in range(len)])

print rand_str(10)

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


Re: Generating random passwords ... for a csv file with user details

Kanthi skrev:

> I have a csv file which in taken as the input file for adding 
> users in my linux mail server with the format
>
> userid,fullname,passwword,dateofbith
>
> Now I have to write a script to generate random password in the
> password field for each user. A simple algorithm is sufficient
> for passwords

#v+

>>> import sha
>>> sha.sha('userid,fullname,passwword,dateofbith').digest().encode('base64')[:10]
'q0nCDQ1YdL'
>>> 

#v-

Mvh, 

-- 
Klaus Alexander Seistrup
SubZeroNet, Copenhagen, Denmark
http://magnetic-ink.dk/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: access serial port in python


google for win32serialport.py
may be this is what you want



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


Re: starting some Python script from C#

Hello. I tried to implement ypour suggestion, but an error apears:
"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreateProcess()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop 
Projects\CS_script\CS_script\Main.cs:32,5  "

The C# code is the following:

/*
 * Created by SharpDevelop.
 * User: Zlatko
 * Date: 28.5.2006
 * Time: 9:38
 *
 * To change this template use Tools | Options | Coding | Edit Standard 
Headers.
 */
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Windows.Forms;

namespace CS_script
{
 class MainClass
 {
  public static void Main(string[] args)
  {

System.Diagnostics.ProcessStartInfo psi =new 
System.Diagnostics.ProcessStartInfo();
psi.FileName="my_script.py";
psi.WorkingDirectory=Environment.CurrentDirectory;
psi.RedirectStandardOutput = true;
psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
psi.UseShellExecute = false;
psi.CreateNoWindow = true;

System.Diagnostics.Process script;
script = System.Diagnostics.Process.Start(psi);

System.IO.StreamReader myOutput = script.StandardOutput;
script.WaitForExit(2000);
if (script.HasExited)
 {
 string output = myOutput.ReadToEnd();
 //this.processResults.Text = output;
}
MessageBox.Show("finished!");
  }
 }
}

When running the program, I have the following error:

"Exception System.ComponentModel.Win32Exception was thrown in debugee:
The specified executable is not a valid Win32 application.

StartWithCreateProcess()
Start()
Start()
Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop 
Projects\CS_script\CS_script\Main.cs:32,5  "

"Gerard Flanagan" <[EMAIL PROTECTED]> je napisao u poruci interesnoj 
grupi:[EMAIL PROTECTED]
> tatamata wrote:
>> Hello.
>>
>> How can I run some Python script within C# program?
>>
>
> -
>ProcessStartInfo startInfo;
>Process process;
>string directory;
>string pyArgs;
>string script;
>
>startInfo = new ProcessStartInfo("python");
>startInfo.WorkingDirectory = directory;
>startInfo.Arguments = script + " " + pyArgs;
>startInfo.UseShellExecute = false;
>startInfo.CreateNoWindow = true;
>startInfo.RedirectStandardOutput = true;
>startInfo.RedirectStandardError = true;
>
>process = new Process();
>process.StartInfo = startInfo;
>process.Start();
>
>string s;
>while ((s = process.StandardOutput.ReadLine()) != null)
>{
>//do something with s
>}
> -
>
> HTH
>
> Gerard
> 


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


any advanced table module for wxpython?

Just like excel or vb does. A grid always looks like a normal grid, and can acts as a normal gird, where we can input some text. but when we click the right-most part, this grid becomes a choice widget, so we can choose some pre-defined gizmo; or it becomes a file-selector, and there is a button with "..." on it, the selected file name is filled; or it pops up a coluor/font choose dialog.

 
It seems that wxpython supports the choice only.
thank you
 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Running External Commands + Seeing when they are Finished

Hello Tommy,

Use the subprocess module
(http://docs.python.org/lib/module-subprocess.html).

for app in MY_APPLICATION_LIST:
pipe = Popen(app)
pipe.wait()

HTH,
http://pythonwise.blogspot.com/

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


Re: generating random passwords ... for a csv file with user details

k.i.n.g. enlightened us with:
> Now I have to write a script to generate random password in the
> password field for each user. A simple algorithm is sufficient for
> passwords

Check out the source of pwsafe, it has a great password generator. It
can generate with different lengths, based on amount of entropy, and
can also generate different types (alpha/digit, hex, easy to read
alpha/digit, etc.)

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Linking onClick event to other controls on the Frame

Hello Harles,

Please define "link" - is it bind event, get information from control,
...?
If I'm guessing the you want to the the value of each control then you
need to store a reference to this control and call the method that gets
the value of each control.
(GetValue() for most, GetStringSelection() for others ...)

Also I suggest you use sizers instead of hard coding the widgets
location.

My best suggestion however is that you download the wxPython demo and
view the examples over there.

See revised code below:

import wx
class Form1(wx.Panel):
def __init__(self, parent, id):
wx.Panel.__init__(self, parent, id)
sizer = wx.GridSizer(wx.VERTICAL)
gsizer = wx.FlexGridSizer(2, 2)

# First Name: ___
gsizer.Add(wx.StaticText(self, -1, "First Name:"))
self._first_name = wx.TextCtrl(self, -1, size=(100, -1))
gsizer.Add(self._first_name, 0, wx.EXPAND)

# Last Name: ___
gsizer.Add(wx.StaticText(self, -1, "Last Name:"))
self._last_name = wx.TextCtrl(self, -1, size=(100, -1))
gsizer.Add(self._last_name, 0, wx.EXPAND)
gsizer.AddGrowableCol(1)

sizer.Add(gsizer, 1, wx.EXPAND)

self._work_status = wx.RadioBox(self, -1, "Work Status",
choices=["Employed", "Unemployed"])
sizer.Add(self._work_status, 0, wx.EXPAND)

self._martial_status = wx.RadioBox(self, -1, "Martial Status",
choices=["Married", "Single"])
sizer.Add(self._martial_status, 0, wx.EXPAND)

b = wx.Button(self, -1, "GO!")
self.Bind(wx.EVT_BUTTON, self.OnClick, b)
sizer.Add(b)

self.SetSizer(sizer)
self.SetAutoLayout(1)
sizer.Fit(self)

# Button event
def OnClick(self,event):
fo = open("job.cfg", "w")
print >> fo, "First Name:", self._first_name.GetValue()
print >> fo, "Last Name:", self._last_name.GetValue()
print >> fo, "Work Status:",
self._work_status.GetStringSelection()
print >> fo, "Martial Status:",
self._martial_status.GetStringSelection()
fo.close()

HTH,
Miki
http://pythonwise.blogspot.com/

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


Re: Speed up this code?

Hello Martin,

You can use gmpy (http://gmpy.sourceforge.net/)

def primes():
n = 2
while 1:
yield long(n)
n = gmpy.next_prime(n)

HTH,
Miki
http://pythonwise.blogspot.com/

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


Re: starting some Python script from C#

> "Gerard Flanagan" <[EMAIL PROTECTED]> je napisao u poruci interesnoj
> grupi:[EMAIL PROTECTED]
> > tatamata wrote:
> >> Hello.
> >>
> >> How can I run some Python script within C# program?
> >>
> >
> > -
> >ProcessStartInfo startInfo;
> >Process process;
> >string directory;
> >string pyArgs;
> >string script;
> >
> >startInfo = new ProcessStartInfo("python");
> >startInfo.WorkingDirectory = directory;
> >startInfo.Arguments = script + " " + pyArgs;
> >startInfo.UseShellExecute = false;
> >startInfo.CreateNoWindow = true;
> >startInfo.RedirectStandardOutput = true;
> >startInfo.RedirectStandardError = true;
> >
> >process = new Process();
> >process.StartInfo = startInfo;
> >process.Start();
> >
> >string s;
> >while ((s = process.StandardOutput.ReadLine()) != null)
> >{
> >//do something with s
> >}
> > -
> >

tatamata wrote:
> Hello. I tried to implement ypour suggestion, but an error apears:
> "Exception System.ComponentModel.Win32Exception was thrown in debugee:
> The specified executable is not a valid Win32 application.
>
> namespace CS_script
> {
>  class MainClass
>  {
>   public static void Main(string[] args)
>   {
>
> System.Diagnostics.ProcessStartInfo psi =new
> System.Diagnostics.ProcessStartInfo();
> psi.FileName="my_script.py";
> psi.WorkingDirectory=Environment.CurrentDirectory;
> psi.RedirectStandardOutput = true;
> psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
> psi.UseShellExecute = false;
> psi.CreateNoWindow = true;
>
> System.Diagnostics.Process script;
> script = System.Diagnostics.Process.Start(psi);
>
> System.IO.StreamReader myOutput = script.StandardOutput;
> script.WaitForExit(2000);
> if (script.HasExited)
>  {
>  string output = myOutput.ReadToEnd();
>  //this.processResults.Text = output;
> }
> MessageBox.Show("finished!");
>   }
>  }
> }
>
> When running the program, I have the following error:
>
> "Exception System.ComponentModel.Win32Exception was thrown in debugee:
> The specified executable is not a valid Win32 application.
>
> StartWithCreateProcess()
> Start()
> Start()
> Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop
> Projects\CS_script\CS_script\Main.cs:32,5  "
>


I have no means of running C# programs at present and can't claim much
expertise in any case.  A guess is that a "valid Win32 application"
means an '.exe' file, not a '.py' file.

You are assuming that a Process object is as smart as the command
interpreter ('cmd.exe') and will know to use 'python.exe' for a file
with a 'py' extension?

What happens if you use 'python.exe' (or 'cmd.exe') as your file and
the script name as argument as in the code I posted?

Gerard


(PS. This group prefers that one doesn't top-post)

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


unexpected behaviour for python regexp: caret symbol almost useless?

This regexp
''

works well with 'grep' for matching lines of the kind


on a XML .glade file

However that's not true for the re module in python, since this one
takes the regexp as if were specified this way: '^'

For some reason regexp on python decide to match from the start of the
line, no matter if you used or not the caret symbol '^'.

I have a hard time to note why this regexp wasn't working:
regexp = re.compile(r'')

The solution was to consider spaces:
regexp = re.compile(r'\s*\s*')

To reproduce behaviour just take a .glade file and this python script:

import re

glade_file_name = 'some.glade'

bad_regexp = re.compile(r'')
good_regexp = re.compile(r'\s*\s*')

for line in open(glade_file_name):
if bad_regexp.match(line):
print 'bad:', line.strip()
if good_regexp.match(line):
print 'good:', line.strip()


The thing is i should expected to have to put caret explicitly to tell
the regexp to match at the start of the line, something like:
r'^'
however python regexp is taking care of that for me. This is not a
desired behaviour for what i know about regexp, but maybe i'm missing
something.

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


Re: unexpected behaviour for python regexp: caret symbol almost useless?

conan wrote:

> The thing is i should expected to have to put caret explicitly to tell
> the regexp to match at the start of the line, something like:
> r'^'
> however python regexp is taking care of that for me. This is not a
> desired behaviour for what i know about regexp, but maybe i'm missing
> something.

You want search(), not match().

http://docs.python.org/lib/matching-searching.html

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


Re: dynamic type changing

On 28 May 2006 01:07:16 -0700, [EMAIL PROTECTED] wrote:

>>> I'm working on a "TempFile" class that stores the data in memory until
>>> it gets larger than a specified threshold (as per PEP 42).  Whilst
>>> trying to implement it, I've come across some strange behaviour.  Can
>>> anyone explain this?
>
>>> The test case at the bottom starts a TempFile at size 50 and prints its
>>> type.  It then increases the size to the threshold at which point
>>> "self" is changed to being a TemporaryFile.
>
>> Changed how ?-)
>
>Just by being assigned with a TemporaryFile object.  I thought that if
>you do
>
>instance = TempFile()
>
>that "instance" and "self" defined in the Class were the same thing so
>that if you changed the class of self, the class of instance would also
>change.
>
>Thanks very much for your example.  It has solved my problem and helped
>me understand a new pattern at the same time.

Bruno says you _can_ assign to __class__ but calls that "risky".
If you ever do feel the urge to assign a new value to some
object's __class__ it might be a good idea to first make certain
you can predict the behavior of the following:

class A:
  msg = 'A'
  def hmm(self):
print self.msg

class B:
  msg = 'B'
  def hmm(self):
print self.msg

x = A()
x.hmm()
x.__class__ = B
x.hmm()

class C:
  def __init__(self):
self.msg = 'C'
  def hmm(self):
print self.msg

class D:
  def __init__(self):
self.msg = 'D'
  def hmm(self):
print self.msg

x = C()
x.hmm()
x.__class__ = D
x.hmm()



David C. Ullrich
-- 
http://mail.python.org/mailman/listinfo/python-list


iteration over non-sequence ,how can I resolve it?

at line "for j in  linkReturned:" , raise an error:
File "C:\pythonProgram\test.py", line 308, in main
for j in  linkReturned:
TypeError: iteration over non-sequence
how can I get a list from the return of thread.start() ?
below is the codes:

class PrintThread(threading.Thread):
  def __init__(self, urlList):
  threading.Thread.__init__(self)
  urllist=[]
  self.urllist=urlList
   def run(self):
  urllink=[]
  ..
  return urllink


for i in range(0,2):
thread=PrintThread(links)
threadList.append(thread)
linkReturned=[]
for i in threadList:
linkReturned=i.start()
for j in  linkReturned:
links.append(j)

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



using FFTW3 with Numeric on Windows

hi list,
as the subject says, I'm trying to find a way to use
FFTW3 with Numeric arrays.
I'm not very familiar with C(++) - I think ctypes is the
way to go, but I don't really have a clue how to do it.
Has somebody already tried this?

thx,
sven.

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