Re: List Moderator

2007-05-19 Thread Dotan Cohen
On 18/05/07, Steve Holden <[EMAIL PROTECTED]> wrote:
> Dotan Cohen wrote:
> > Is this list not moderated? I'm really not interested in Britney
> > Spears boobs. All the spam on this list is from the same place, it
> > should be very easy to filter.
> >
> Is it a list, is it a newsgroup? No, it's c.l.py!
>
> In fact you could be reading this in a number of different forms, and
> there are equally many ways to inject content into the stream. It's
> surprisingly difficult to filter everything out, though the list
> managers at python.org seem to do a remarkably effective job.

I don't believe that a python list manager would have a hard time
coming up with a regex that /dev/nulled any post with the words
"britney", "spears", "boobs", "tits", or the like.

> I'm not particularly interested in that subject matter either, but
> believe me there could be a lot more of that kind of thing than actually
> makes it through!

And if it doesn''t start getting filtered now, the spammers will see
this list as an easy target and will attack it. Believe me.

Dotan Cohen

http://lyricslist.com/
http://what-is-what.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Compiling Python code within a module

2007-05-19 Thread Gabriel Genellina
En Fri, 18 May 2007 20:49:33 -0300, Mitko Haralanov <[EMAIL PROTECTED]>  
escribió:

> On 18 May 2007 15:51:40 -0700
> ici <[EMAIL PROTECTED]> wrote:
>
>> exec it :)
>
> Thank you! That works when I compile/exec it in the main body of the
> program. However, when I try to do that in a separate module it
> doesn't. For example:

exec has a long form - see http://docs.python.org/ref/exec.html
And forget the compile pass - let Python handle it automatically. Also  
note that exec is a statement, not a function, so you don't need ()

To "inject" inside a module a function defined in source_code, do:

exec source_code in module.__dict__

To "inject" a function inside a class, it's easier if you use an  
intermediate dictionary:

d = globals().copy()
exec source_code in d
my_class.method = d['method']

>   def register (self, text):
>   exec (compiler.compile (text, "",
>   "exec"))
>
> f.register ("def blah():\n\tprint 'blah'\n")
>
> In this case, the function 'blah' is nowhere to be found. I've tried
> looking in 'f', in the class 'Foo', in the module 'Foo' and it's
> nowhere.

It existed briefly in the local namespace of the register method - after  
register is exited, it's gone.

-- 
Gabriel Genellina

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


Re: pyodbc.Error Crash

2007-05-19 Thread Gabriel Genellina
En Fri, 18 May 2007 20:48:49 -0300, Joe Salmeri <[EMAIL PROTECTED]>  
escribió:

> I believe this bug is also related to the other problem I just reported.

I think you'll get best results reporting them to the author(s) directly:  
http://pyodbc.sourceforge.net/ and click on "Bug tracker"

-- 
Gabriel Genellina

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


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-19 Thread Martin v. Löwis
> Providing a method that would translate an arbitrary string into a
> valid Python identifier would be helpful. It would be even more
> helpful if it could provide a way of converting untranslatable
> characters. However, I suspect that the translate (normalize?) routine
> in the unicode module will do.

Not at all. Unicode normalization only unifies different "spellings"
of the same character.

For transliteration, no simple algorithm exists, as it generally depends
on the language. However, if you just want any kind of ASCII string,
you can use the Unicode error handlers (PEP 293). For example, the
program

import unicodedata, codecs

def namereplace(exc):
if isinstance(exc,
   (UnicodeEncodeError, UnicodeTranslateError)):
s = u""
for c in exc.object[exc.start:exc.end]:
s += "N_"+unicode(unicodedata.name(c).replace(" ","_"))+"_"
return (s, exc.end)
else:
raise TypeError("can't handle %s" % exc.__name__)

codecs.register_error("namereplace", namereplace)

print u"Schl\xfcssel".encode("ascii", "namereplace")

prints SchlN_LATIN_SMALL_LETTER_U_WITH_DIAERESIS_ssel.

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


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-19 Thread Martin v. Löwis
>> But you're making a strawman argument by using extended ASCII
>> characters that would work anyhow. How about debugging this (I wonder
>> will it even make it through?) :
>>
>> class 6자회담관련론조
>>6자회 = 0
>>6자회담관련 고귀 명=10
> 
>That would be invalid syntax since the third line is an assignment
> with target identifiers separated only by spaces.

Plus, the identifier starts with a number (even though 6 is not DIGIT
SIX, but FULLWIDTH DIGIT SIX, it's still of category Nd, and can't
start an identifier).

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

Re: Uninstall speed with Python 2.4 MSI

2007-05-19 Thread Martin v. Löwis
David Bolen wrote:
> I'm in the process of uninstalling 2.4a2 to install 2.4a3 and the
> uninstall is running absolutely dog slow and burning 100% cpu while
> doing it (all going to mshta.exe).  Watching the progress bar it
> almost seems to be doing a whole bunch of operations per file or
> something.

Indeed it does. MSI is transactional, meaning that everything is
reverted if the operation fails (e.g. through user cancel). When
overwriting or deleting files, this means installer needs to move
the old file out of the way. Then, when the action is committed,
the file can be deleted. Therefore, during uninstall, you see two
actions: first, it says that it removes files, then, it says that
it removes backup files.

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


Re: fun with unicode files

2007-05-19 Thread Martin v. Löwis
Thomas Heller wrote:
> I wonder: do I really have to check for the BOM manually, or is there a
> Python function which does that?

If it can also be ASCII (or ansi?), then yes, you need to manually check
for the BOM. This is because you need to make an explicit decision in
the fallback case - Python cannot know whether it is ASCII if it is
not UTF-16. For example, it might also be Latin-1 or UTF-8 if it is not
UTF-16, or, say, iso-2022-jp.

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


Re: Python compared to other language

2007-05-19 Thread Gabriel Genellina
En Sat, 19 May 2007 03:24:15 -0300, walterbyrd <[EMAIL PROTECTED]>  
escribió:

> My guess is that some of the C code used to develop Python is the same
> between the different Python distros, but much of the code is unique
> to the particular platform. If that is the case, then the C code may
> not be very portable.

Well, your guess was wrong. The core CPython code is the same on all  
platforms; of course it uses #define/#ifdef/etc. where appropiate, but  
it's not a mess, and not so much code is conditionally compiled.
The Python developers take special care on portability - the C language  
itself (C89 is currently used) is pretty standard, but you have to be  
careful on how you write your code.

> But, I can often take the same python code, and run it on MacOS,
> Linux, FreeBSD, and Windows. Often I can do this even if the app has a
> gui interface.

Because someone has taken out all the differences, so you don't have to  
struggle with them yourself. GUI toolkits: some libraries "draw" the whole  
thing and manage all the user interaction themselves so they're basically  
portable but never have the native "look&feel" (tcl/tk); other rely on the  
native buttons and controls for each platform, but providing a homogeneous  
view for the programmer (wxWidgets). Anyway, they work across platforms  
because "someone" has already worked on the differences for you - using C.  
Both menctioned libraries are written in C (wx in C++), and Python  
provides a convenient wrapper for them.
Even on the Python side, some libraries do one thing or another depending  
on the platform (cf: subprocess). The good thing is that *you* as a  
developer, don't have to worry about the differences; many are managed by  
Python itself internally, and many are worked on by other people on top of  
this. webbrowser.open('your favourite url') "just works" and does "the  
right thing" because of these efforts.

-- 
Gabriel Genellina

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


Re: RFC - n-puzzle.py

2007-05-19 Thread Raymond Hettinger
On May 18, 4:15 pm, Phoe6 <[EMAIL PROTECTED]> wrote:
> Hi All,
> I would like to request a code and design review of one of my program.
> n-puzzle.pyhttp://sarovar.org/snippet/detail.php?type=snippet&id=83
> Its a N-puzzle problem solver ( Wikipedia page 
> andhttp://norvig.com/ltd/test/n-puzzle.lisp
> )
>
> I have used OO Python for the above program and would like comments on
> my approach as I am just starting with OOP.
>
> Thanks
> Senthil

Nice job, this doesn't look like a beginner program at all.

For feedback, here's a few nits:

Instead of:
if key + x in range(0, self.tsize):
write:
if 0 <=  key + x < self.tsize:


Instead of:
mdist = mdist + jumps + steps
write:
mdist += jumps + steps


Instead of:
least_paths = []
for st in exp_sts:
if self.manhattan_distance(st) == short_path:
least_paths.append(st)
write:
least_paths = [st for st in exp_sts if self.manhattan_distance(st)
== short_path]

Instead of:
short_path = mdists[0]
if mdists.count(short_path) > 1:
write:
short_path = mdists[0]
if short_path in mdists[1:]:

Instead of:
if node != 0:
write:
if node:


Raymond



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


Re: (Modular-)Application Framework / Rich-Client-Platform in Python

2007-05-19 Thread Stef Mientki
Jarek Zgoda wrote:
> Stef Mientki napisał(a):
> 
>> I took a look at some of the examples build with eclipse,
>> and I might be wrong, but it's just another IDE,
>> (like Delphi, Lazarus, Visual Basic, Kylix, Pida, Envisage, VisualWX,
>> wxGlade, ...)
>> what am I missing ?
> 
> I think you miss the difference between Eclipse IDE and Eclipse
> Platform. The IDE is and application built using RCP. As Azureus or
> RSSOwl, which aren't IDE-type applications. One of the tutorials
> mentioned int the RCP wiki takes user through creating an email client
> application, which is not an IDE, definitely. Eclipse RCP allows
> building applications as a set of pluggable features over common
> runtime. While not a "mark-and-drop" solution yet, it's a great leap
> forward in Java desktop applications.
> 
> There's more to Eclipse that just IDE. ;)
> 
Sorry, I don't get the difference between an IDE and RPC.
If I look at the demo of the "email client" you mentioned,
(and I don't understand a bit of Java),
I see a very complex story (at least for me).

Is there an easy possibility that I can see the "email client" you mentioned,
working on my computer,
so I can judge how I would create the same functionality in one of the other 
IDE's,
maybe then I get the picture.

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


dislin titlin and string decode

2007-05-19 Thread luis
Hello!

I have an unespectedn result with dislin titlin

dislin.metafl ('WMF')
dislin.disini ()


a="Andrés or Ramón"
dislin.titlin (a.encode("Latin-1"), 1)
# not error raised, is ok


dislin.disfin ()


In the output file all is ok but the title is

Andr s or Ram n

Thanks in advance!

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


Re: Anti-Aliasing in wxPython?

2007-05-19 Thread sturlamolden
On May 18, 8:20 pm, Alexander Dünisch <[EMAIL PROTECTED]> wrote:

> i haven't found anything like this in wxPython yet.
> Thanks

wxPython uses native widgets, so it is OS dependent. You will have to
turn it in Windows, MacOSX (on by default?) or GNOME.


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


Re: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2

2007-05-19 Thread James Stroud
John Machin wrote:
> The approach that I've adopted is to test the values in a column for all 
> types, and choose the non-text type that has the highest success rate 
> (provided the rate is greater than some threshold e.g. 90%, otherwise 
> it's text).
> 
> For large files, taking a 1/N sample can save a lot of time with little 
> chance of misdiagnosis.


Why stop there? You could lower the minimum 1/N by straightforward 
application of Bayesian statistics, using results from previous tables 
as priors.


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


Re: Execute commands from file

2007-05-19 Thread Martin Blume
"Steve Holden" schrieb
> >
> > [ difference between exec open(fname).read() 
> >and for line in open(fname): exec line ] 
> > 
> > So it seems to depend on the way the file is read.
> > 
> It depends on the way the lines of the file are executed, 
> not how they are read. 
>
Could you elaborate a little bit more on the difference?
I assumed that because read() reads the whole file, the 
body of my function sowhat() is present, so that it can
be parsed while the invocation of exec is still running.
If it is read and exec'd line by line, the definition of
the function is still left open at the moment exec() ends,
causing the "EOF" error. Hence my statement, "it depends
on the way the file is read".


> And you may remember the original poster was 
> proposing this:
> 
> inp = open(cmd_file)
> for line in inp:
>   exec line
> 
> As for your first example, why not just use execfile() ?
> 
I assume that 
   execfile(fname)
is equivalent to
   exec open(fname).read() ?


Regards
Martin
   

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


Re: Typed named groups in regular expression

2007-05-19 Thread Paul McGuire
On May 19, 12:32 am, Paddy <[EMAIL PROTECTED]> wrote:
> On May 16, 6:58 pm, "Hugo Ferreira" <[EMAIL PROTECTED]> wrote:
>
> > Hi!
>
> > Is it possible to "automagically" coerce the named groups to python types? 
> > e.g.:
>
> > >>> type(re.match('(?P\d*)', '123').groupdict()['x'])
>
> > 
>
> > But what I'm looking forward is for the type to be 'int'.
>
> > Cheers!
>
> > Hugo Ferreira
>
> If you do a ot of that sort of thing in many programs
> then it might be worth your while to set up a framework
> that does it. Something like adding an underscore
> then the name of a type conversion function to all
> group names, and creating a function to apply the
> type convertion function to all named groups of a
> match object.
> - Paddy.

pyparsing might just be this sort of framework, in that you can attach
parse actions to elements within a grammar.  At parse time, the parse
action is called with the list of tokens currently matched.

>>> from pyparsing import Regex
>>> re = Regex( r"(\d*)" ).setResultsName("x")\
....setParseAction(lambda t:int(t[0]))
>>> results = re.parseString("123")
>>> print results.x
123

-- Paul

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


Re: (Modular-)Application Framework / Rich-Client-Platform in Python

2007-05-19 Thread Wildemar Wildenburger
Ben Finney wrote:
> You already have Python, and can embed it in your program. The only
> missing piece seems to be the primitive operations at the core, which
> surely depend on what exactly it is you have in mind for your program
> and can't really be provided in a generic form by some other party.
>
>   
That's where you're wrong. Such a tool exists. I really can't explain 
any better than I (and Jarek even better so) already did. The keyword is 
Rich-Client-Platform. Wikipedia explains it, so does the already 
presented Eclipse-wiki, as does the Enthought Tools Site (specifically 
Envisage), which also holds the answer to my problem/question. It is 
solved. If you don't understand what I want, go to http://code.enthought.com/ets/> and read what it does.

I really, really appreciate the effort you (all of you) make in helping 
me and getting me on the right track, but I'm a bit confounded by how 
you can be trying to convince me that the tools I'm currently reading 
the docs for don't exist.

I don't mean to be bitching, really. I just don't get your point here.


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


Re: dislin titlin and string decode

2007-05-19 Thread luis
the code is:

#!/usr/bin/env python

def try_dislin():
...import dislin
...dislin.metafl ('WMF')
...dislin.errdev ('FILE')
...dislin.disini ()
...dislin.errmod('PROTOCOL','ON')
...dislin.hwfont ()
...dislin.pagera ()
...dislin.pagfll (255)

...dislin.color('BLACK')
...dislin.axspos (500, 1600)
...dislin.axslen (2200, 1200)
...
...dislin.name...('x','X')
...dislin.name...('y','Y')
...
...dislin.ticks  (10, 'X')
...dislin.ticks  (10, 'Y')

...dislin.labels ('FLOAT','X')
...dislin.labels ('FLOAT','Y')

...dislin.incmrk(1)
...dislin.hsymbl (15)
...dislin.chacod('STANDARD')
...dislin.polcrv('LINEAR')

...x=[1.,2.,3.]
...y=[1.,2.,3.]
.
...a=unicode("Ramón y Andrés",'Latin-1')
...dislin.titlin (a.encode('Latin-1'), 1)
...
...min_x_axis=1.
...max_x_axis=3.
...min_y_axis=1.
...max_y_axis=3
...
...xstep=(max_x_axis - min_x_axis)/10.
...ystep=(max_y_axis - min_y_axis)/10.
...dislin.graf (min_x_axis,max_x_axis,min_x_axis,xstep \
..,min_y_axis,max_y_axis,min_y_axis,ystep)
...
...dislin.title()
...

...dislin.curve(x,y, len(x))

...dislin.color  ('foreground')
...dislin.dash...()
...dislin.xaxgit ()
...dislin.disfin ()


try_dislin()
print 'end'

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


Writelines() a bit confusing

2007-05-19 Thread aiwarrior
If file.WriteLines( seq ) accepts a list and it says it writes lines,
why does it write the whole list in a single line. Be cause of that
the reverse of file.writelines(seq) is not file.readlines().
Are the assumptions i made correct? If yes why is this so?

I find a function called writelines not actualy writing the list in
lines wierd.

[code]
something = ['re','ri','ro']
f.writelines( something )
something_else = f.readlines()
[/code]
In this case the list something_else will be diffrent from something

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


Re: RFC - n-puzzle.py

2007-05-19 Thread Phoe6
On May 19, 2:23 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
> On May 18, 4:15 pm, Phoe6 <[EMAIL PROTECTED]> wrote:
> > I would like to request a code and design review of one of my program.
> > n-puzzle.pyhttp://sarovar.org/snippet/detail.php?type=snippet&id=83
>
> Nice job, this doesn't look like a beginner program at all.

Thanks Raymond. :-)

> For feedback, here's a few nits:

Yes, I made changes in them all. Thanks for the list comprehension
pointer, I missed it.

>
> Instead of:
> short_path = mdists[0]
> if mdists.count(short_path) > 1:
> write:
> short_path = mdists[0]
> if short_path in mdists[1:]:

I would like to understand the difference between the two if
statements.
I had used count method, to signify the meaning that, if the least
distance occurs more then proceed with block.
How is 'in' with list[1:] an advantage? If it is.

> Instead of:
> if node != 0:
> write:
> if node:

Here again, I went by the meaning of non-zero value nodes and made
comparision with node != 0. Just in case, the n-states were
represented by '0', '1', '2', '3', I would have gone for node != '0'
sticking to the meaning. I think, I should aid it with a comment,
otherwise might get confused in the future.

Thanks a lot, Raymond. :-)

--
Senthil

http://uthcode.sarovar.org

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


Re: pyodbc.Error Crash

2007-05-19 Thread Joe Salmeri

Thanks, I reported them there first and then posted here in case they 
monitor the forum more frequently and so others would be aware of the 
problems found.

Joe


"Gabriel Genellina" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> En Fri, 18 May 2007 20:48:49 -0300, Joe Salmeri <[EMAIL PROTECTED]> 
> escribió:
>
>> I believe this bug is also related to the other problem I just reported.
>
> I think you'll get best results reporting them to the author(s) directly: 
> http://pyodbc.sourceforge.net/ and click on "Bug tracker"
>
> -- 
> Gabriel Genellina
> 


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

Re: which is the comprehencive module for postgresql?

2007-05-19 Thread Steve Holden
Gabriel Genellina wrote:
> En Sat, 19 May 2007 02:25:11 -0300, krishnakant Mane  
> <[EMAIL PROTECTED]> escribió:
> 
>> some times having many choices often confuses the users.
>> can some one plese tell me which is the most comprehencive, well
>> documented and widely used and tested module to connect from python to
>> postgresql database?  I looked around PYPgsql but there seams to be
>> very little documentation.
> 
> I've never used Postgresql with Python so I can't recommend any, but see  
> this wiki page:
> http://wiki.python.org/moin/PostgreSQL
> 

I'd recommend psycopg2 - I have used it quite a bit, it seems 
well-written and well-supported.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: docs patch: dicts and sets

2007-05-19 Thread Alan Isaac
I submitted the language based on Bill and Carsten's proposals:

https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&group_id=5470

That language has been rejected.
You many want to read the discussion and see if
acceptible language still seems discoverable.

Alan Isaac


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


Re: List Moderator

2007-05-19 Thread Steve Holden
Dotan Cohen wrote:
> On 18/05/07, Steve Holden <[EMAIL PROTECTED]> wrote:
>> Dotan Cohen wrote:
>>> Is this list not moderated? I'm really not interested in Britney
>>> Spears boobs. All the spam on this list is from the same place, it
>>> should be very easy to filter.
>>>
>> Is it a list, is it a newsgroup? No, it's c.l.py!
>>
>> In fact you could be reading this in a number of different forms, and
>> there are equally many ways to inject content into the stream. It's
>> surprisingly difficult to filter everything out, though the list
>> managers at python.org seem to do a remarkably effective job.
> 
> I don't believe that a python list manager would have a hard time
> coming up with a regex that /dev/nulled any post with the words
> "britney", "spears", "boobs", "tits", or the like.
> 
>> I'm not particularly interested in that subject matter either, but
>> believe me there could be a lot more of that kind of thing than actually
>> makes it through!
> 
> And if it doesn''t start getting filtered now, the spammers will see
> this list as an easy target and will attack it. Believe me.
> 

I'm sorry, but you have no idea what you are talking about. Most of what 
can be done *is* being done, which is why you see the relatively low 
spam volumes you do.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: Python compared to other language

2007-05-19 Thread Steve Holden
walterbyrd wrote:
> On May 18, 8:28 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> 
>> Surely the fact that Python is available on so many platforms implies
>> that C is a fairly portable language.
> 
> Unless it's the same C code, I don't see how that means anything. If I
> write an app on Windows with C, and I rewrite the same app on UNIX
> with C - that doesn't mean the C code has been ported.
> 
> My guess is that some of the C code used to develop Python is the same
> between the different Python distros, but much of the code is unique
> to the particular platform. If that is the case, then the C code may
> not be very portable.
> 
> But, I can often take the same python code, and run it on MacOS,
> Linux, FreeBSD, and Windows. Often I can do this even if the app has a
> gui interface.
> 
Perhaps you could try a more constructive approach in future.

The reason you can do this with Python is precisely because the 
developers have ironed out the wrinkles between platforms by putting the 
requisite conditionals in the C source. Which, by the way, is open in 
case you ever feel like answering your own questions.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: Writelines() a bit confusing

2007-05-19 Thread Stefan Sonnenberg-Carstens
aiwarrior schrieb:
> If file.WriteLines( seq ) accepts a list and it says it writes lines,
> why does it write the whole list in a single line. Be cause of that
> the reverse of file.writelines(seq) is not file.readlines().
> Are the assumptions i made correct? If yes why is this so?
>
> I find a function called writelines not actualy writing the list in
> lines wierd.
>
> [code]
> something = ['re','ri','ro']
> f.writelines( something )
> something_else = f.readlines()
> [/code]
> In this case the list something_else will be diffrent from something
>
>   
Please see this:
 >>> help(f.writelines)
Help on built-in function writelines:

writelines(...)
writelines(sequence_of_strings) -> None.  Write the strings to the file.
   
Note that newlines are not added.  The sequence can be any iterable 
object
producing strings. This is equivalent to calling write() for each 
string.

so you'd want this:

f.writelines([x+os.linesep for x in strings])

or something similar.

Why ? Ask the originator of this function.
One explanation:
If you do this:

f1 = file('file1')
f2 = file('file2','w')
f2.writelines(f1.readlines())
f1.close() ; f2.close()

all is how it should be.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Execute commands from file

2007-05-19 Thread Steve Holden
Martin Blume wrote:
> "Steve Holden" schrieb
>>> [ difference between exec open(fname).read() 
>>>and for line in open(fname): exec line ] 
>>>
>>> So it seems to depend on the way the file is read.
>>>
>> It depends on the way the lines of the file are executed, 
>> not how they are read. 
>>
> Could you elaborate a little bit more on the difference?
> I assumed that because read() reads the whole file, the 
> body of my function sowhat() is present, so that it can
> be parsed while the invocation of exec is still running.
> If it is read and exec'd line by line, the definition of
> the function is still left open at the moment exec() ends,
> causing the "EOF" error. Hence my statement, "it depends
> on the way the file is read".
> 
I simply meant that the whole source has to be presented to the exec 
statement and not chunked into lines.

Clearly I could read all the source in with

lines = open(cmd_file).readlines()

but if you then proceed to try and execute the source line by line as in

for l in lines:
   exec l

you will hit problems because of the disjoint nature of the execution 
which will breal up indented suites and so on.

I was probably just a little over-zealous in pursuing correct English 
usage, in which case please accept my apology.

> 
>> And you may remember the original poster was 
>> proposing this:
>>
>> inp = open(cmd_file)
>> for line in inp:
>>   exec line
>>
>> As for your first example, why not just use execfile() ?
>>
> I assume that 
>execfile(fname)
> is equivalent to
>exec open(fname).read() ?
> 
Pretty much.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: Writelines() a bit confusing

2007-05-19 Thread Steve Holden
aiwarrior wrote:
> If file.WriteLines( seq ) accepts a list and it says it writes lines,
> why does it write the whole list in a single line. Be cause of that
> the reverse of file.writelines(seq) is not file.readlines().
> Are the assumptions i made correct? If yes why is this so?
> 
> I find a function called writelines not actualy writing the list in
> lines wierd.
> 
> [code]
> something = ['re','ri','ro']
> f.writelines( something )
> something_else = f.readlines()
> [/code]
> In this case the list something_else will be diffrent from something
> 
Your list is *not* what you would get in from a call to readlines.

Try it.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: RFC - n-puzzle.py

2007-05-19 Thread Steve Holden
Phoe6 wrote:
> On May 19, 2:23 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>> On May 18, 4:15 pm, Phoe6 <[EMAIL PROTECTED]> wrote:
>>> I would like to request a code and design review of one of my program.
>>> n-puzzle.pyhttp://sarovar.org/snippet/detail.php?type=snippet&id=83
>> Nice job, this doesn't look like a beginner program at all.
> 
> Thanks Raymond. :-)
> 
>> For feedback, here's a few nits:
> 
> Yes, I made changes in them all. Thanks for the list comprehension
> pointer, I missed it.
> 
>> Instead of:
>> short_path = mdists[0]
>> if mdists.count(short_path) > 1:
>> write:
>> short_path = mdists[0]
>> if short_path in mdists[1:]:
> 
> I would like to understand the difference between the two if
> statements.
> I had used count method, to signify the meaning that, if the least
> distance occurs more then proceed with block.
> How is 'in' with list[1:] an advantage? If it is.

Because it can stop as soon as short_path is found, whereas the count 
method must examine all elements to determine whether they should 
increment the count beyond one.

> 
>> Instead of:
>> if node != 0:
>> write:
>> if node:
> 
> Here again, I went by the meaning of non-zero value nodes and made
> comparision with node != 0. Just in case, the n-states were
> represented by '0', '1', '2', '3', I would have gone for node != '0'
> sticking to the meaning. I think, I should aid it with a comment,
> otherwise might get confused in the future.
> 
This is a standard Python idiom. If you had used strings then the test 
*would* have had to explicitly compare against '0', but when evaluating 
for a test Python treats zeros, the empty string, the empty list, set or 
dictionary, None (and various other possibilties) as false.

It's not a big deal, but it will be just a tad faster.

> Thanks a lot, Raymond. :-)

Channeling Raymond, he says you're welcome. :-)

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: Writelines() a bit confusing

2007-05-19 Thread Gre7g Luterman
"aiwarrior" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> If file.WriteLines( seq ) accepts a list and it says it writes lines,
> why does it write the whole list in a single line. Be cause of that
> the reverse of file.writelines(seq) is not file.readlines().
> Are the assumptions i made correct? If yes why is this so?

readlines() and writelines() are complimentary.  readlines() leaves the line 
terminators intact. It does not strip them off. writelines() does not add in 
carriage returns for the same reason.  For example:

>>> D=open("temp.txt").readlines()
>>> D
['the quick\n', 'brown fox\n', 'jumps over\n', 'the lazy dog.']
>>> open("temp2.txt","w").writelines(D)

will create temp2.txt to be identical to temp.txt. 


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


Creating a sub folder in the pythons LIB Directory

2007-05-19 Thread [EMAIL PROTECTED]
Hi,

I am creating a library of functions.  I would like to have them saved
in a sub folder of pythons LIB folder, but I cannot get it to work.

I have a script called test.py
I stored it in LIB folder and typed
Import test, work fine.
I store the script in lib/ted
Then type
Import lib\ted
I get a error that says invalid token, how do I do this

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


_PyObject_New / PyObject_Init / PyInstance_New / etc?

2007-05-19 Thread Gre7g Luterman
(My apologies if this appears twice. It did not post the first time.)

I'm so confuzzled! How do I instantiate my new C Python object from C?

After flailing helplessly with my own code, and searching tirelessly with
Google, I stepped back to the classic noddy2.c example in the Python help
files and tried to modify it to not just define a Noddy object, but to
instantiate one as well. I'm not having any luck.

In noddy2.c, I added some printf statements just after the beginning of the
Noddy_dealloc, Noddy_new, and Noddy_init. I compiled noddy2.c and when
called from Python, it does exactly what I would expect:

>>> import noddy2
>>> n=noddy2.Noddy()
Noddy_new
Noddy_init
>>> ^Z
Noddy_dealloc

Perfect!  Now I wanted to create a Noddy() object from C. The simplest way
to do this was to stick it in the Noddy_name function, since that was easily
called. I tried inserting some code with _PyObject_New and PyObject_Init:

static PyObject *
Noddy_name(Noddy* self)
{
static PyObject *format = NULL;
PyObject *args, *result;
printf("Noddy_name\n");
args=_PyObject_New(&NoddyType);
printf("%p\n", args);
PyObject_Init(args, &NoddyType);
printf("init done\n");
Py_DECREF(args);
printf("dec done\n");
... (I left all the original Noddy_name code here) ...

Then I compiled, went into the Python interpreter and tried it.  I would
have expected Noddy_name to create and destroy a Noddy object just like
noddy2.Noddy() does from the interpreter, but it doesn't:

>>> import noddy2
>>> n=noddy2.Noddy()
Noddy_new
Noddy_init
>>> n.name()
Noddy_name
00B1A1B8
init done
Noddy_dealloc

As you can see, calling the name function did my printf of Noddy_name, and
then _PyObject_New returned a pointer to a Python object, but I don't think
it really is a Noddy object (not entirely at least).  After all, Noddy_new
and Noddy_init are never called! The funny thing is that the Py_DECREF
destroys a Noddy object (you can see that Noddy_dealloc got called), but now
something is out of sync. since the construction didn't happen as expected
and Python crashes hard.

I've tried this as above, and with PyInstance_New, with PyObject_New (no
underscore), and PyObject_Call, but none of them work as I would expect. So
what is the *CORRECT* way to do this?  Obviously I'm neglecting something
important.

My modified noddy2.c in case anyone wants to try it: 
http://pastie.textmate.org/62901

Many thanks to anyone who can point me in the correct direction!

Gre7g 


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


ANN: Pyro 3.7 (remote objects)

2007-05-19 Thread Irmen de Jong
I'm happy to announce Pyro 3.7 --
Python's own powerful remote method invocation technology!

You can get it via http://pyro.sourceforge.net, then go to the SF project 
homepage 
download area.

This is a small improvement release since Pyro 3.6.

New stuff:
- bdist_rpm typo fix in setup.cfg
- renamed all batch files with 'pyro-' prefix to avoid name clashes
(debian package already had this)
- NS broadcast retries are a bit faster now
- Pyro.core.SynchronizedObjBase now correctly handles string exceptions
- the NS nt service won't respond to shutdown requests anymore
- wxnsc updated to recent WxPython API, deprecation warning is gone

Have fun, and thanks for your interest, support, and feedback!

--Irmen de Jong


---> What is Pyro?
Pyro is an acronym for PYthon Remote Objects. Pyro is an advanced and powerful 
Distributed Object Technology system written entirely in Python, that is 
designed to be 
very easy to use.

It is extremely easy to implement a distributed system with Pyro, because all 
network 
communication code is abstracted and hidden from your application. You just get 
a remote 
Python object and invoke methods on the object on the other machine.

Pyro offers you a Name Server, an Event Service, mobile objects, remote 
exceptions, 
dynamic proxies, remote attribute access, automatic reconnection, a very good 
and 
detailed manual, and many examples to get you started right away.

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


Re: Creating a sub folder in the pythons LIB Directory

2007-05-19 Thread Gre7g Luterman
<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hi,
>
> I am creating a library of functions.  I would like to have them saved
> in a sub folder of pythons LIB folder, but I cannot get it to work.
>
> I have a script called test.py
> I stored it in LIB folder and typed
> Import test, work fine.
> I store the script in lib/ted
> Then type
> Import lib\ted

Try "import ted.test" or "from ted import test".  I also recommend reading 
http://www.python.org/doc/essays/packages.html as it explains how to use 
__init__.py files. 


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


Re: Execute commands from file

2007-05-19 Thread Martin Blume
"Steve Holden" schrieb 
> 
> I simply meant that the whole source has to be presented 
> to the exec statement and not chunked into lines.
>
That's what I meant: With exec open(f).read() it is not 
broken into several exec invocations.

> 
> I was probably just a little over-zealous in pursuing 
> correct English usage, in which case please accept 
> my apology.
> 
The apology is on my part, I didn't explain my thinking
clearly enough.


Thanks for your explanations. Makes my newbie understanding 
of Python much more robust.

Regards
Martin


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


Re: docs patch: dicts and sets

2007-05-19 Thread Steven Bethard
Alan Isaac wrote:
> I submitted the language based on Bill and Carsten's proposals:
> 
> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&group_id=5470
> 
> That language has been rejected.
> You many want to read the discussion and see if
> acceptible language still seems discoverable.

Seems to me that you're focusing on the wrong part of the docs.  The 
source of this "bug" is not sets or dicts, but the default __hash__ 
method implementation.  Why don't you propose adding something like:

 The default __hash__ method is based on an object's id(), and can
 therefore change between different iterations of the same program.

to the docs for __hash__:

 http://docs.python.org/ref/customization.html

Then if you really feel you need to add something for sets and dicts, 
you can add a cross-reference to the __hash__ docs.

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


Start

2007-05-19 Thread Nautilus
Can anybody halp me start using Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Start

2007-05-19 Thread Paddy
On May 19, 4:18 pm, Nautilus <[EMAIL PROTECTED]> wrote:
> Can anybody halp me start using Python.


http://wiki.python.org/moin/BeginnersGuide

And welcome :-)

- Paddy.

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


Re: Beginner question: module organisation

2007-05-19 Thread Rainer Grimm
[EMAIL PROTECTED] wrote:
> Hello :)
> 
> I am new to python and I don't have much expirience in object-oriented
> technologies neither.
> 
> The problem is the following: I have to create a simple python
> template script that will always follow the same algorithm, let's say:
> - read a mesh
> - transform the mesh (let's say, refine)
> 
> The last step should be a kind of a black box:
> - the same input data format
> - some algorithme inside
> - the same output data format
> 
> A number of different refine methods should be implemented. The end-
> user must be able to write easily a new method and call it from the
> base script without any major change.
> 
> Something like this would be a solution (no classes created, no OO
> programming):
> - a module defining REFINE1(mesh), REFINE2(mesh), ...
> - in the script:
>   from MODULE import REFINE2 as REFINE
>   REFINE(mesh)
> 
> Is it a proper solution for this kind of problem? How would you
> implement this kind of task?
> 
Hello.

Have a look at the classical GangOfFour design pattern book. You can 
especially with the template methode design the processing of your data. 
The strategy pattern will help you to vary the algroithm in your processing.

To be concret, in your base class you define the processing of the data. 
  There are two distinct methods to do it.
delegate the variation of the algorithmns to other objects => strategy 
pattern
override the steps of the processing in subclasses => template method

Regards,
Rainer
-- 
  _creating IT solutions
Rainer Grimm
scVENUS Schulungsleiter science + computing ag
phone   +49(0)7071 9457-253 Hagellocher Weg 73
fax +49(0)7071 9457-511 D-72070 Tuebingen, Germany
[EMAIL PROTECTED]www.science-computing.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python compared to other language

2007-05-19 Thread Alex Martelli
walterbyrd <[EMAIL PROTECTED]> wrote:

> On May 18, 10:24 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
> 
> >
> > I think that Ruby, which roughly speaking sits somewhere between Python
> > and Perl, is closer to Python than Perl is.
> 
> I don't know much about Ruby, but it does not seem to be commonly used
> for anything other than web-development. It may be that Ruby could be
> used for other purposes, but I don't seem to see it happen much.
> 
> I know that PHP can used at the command line, and could be used for
> the same sort of sys-admin tasks for which, Perl and Python are often
> used, but I don't seem to see that happening either.
> 
> I'm not sure if Ruby, or PHP, are as general purpose as Perl or Python.

PHP was definitely born _for_ webpages; Ruby wasn't, just like Perl or
Python weren't, it just became very popular for webpages when Rails
appeared.

so i tried search queries for [ intitle:X intitle:Y ] where X is each of
various languages and Y one of two words connected with non-web
traditional application programming, and these are the number of hits I
saw:

Y==scientific:
perl 334
python   703
ruby 452
php  423
java2370
c++ 3340
fortran 3200

Y==payroll:
perl  81
python  1
ruby8
php 176  
java382
c++ 101
fortran 1

>From these numbers it would seem that Ruby (and PHP) aren't really more
web-specific than Perl (and Python).

In general, these days, when you're interested in how popular each of a
certain set of technologies / subjects is, search engines can come in
handy (with due precautions, of course: for example, "php" appears in SO
many web pages (2.5 billion, vs e.g. 282 million for java) that you need
to restrict it cleverly (e.g., I used the intitle: attribute -- that
gives 20.1 million for php vs 21.4 million for Java, and biases numbers
towards pages that in some sense are "about" that technology rather than
just happening to mention it as an aside, a part of an URL, etc:-).  "c"
is very hard to search for because many occurrences of that single
letter have nothing to do with the language (here you may try quoted
sentences such as "c programming": without precautions, "c" has 2.86
billion hits, but "c programming" 1.22 million vs 1.09 million for "java
programming", which again puts things in better perspective).  I say
"technology" because this doesn't apply to just programming languages:
e.g., "COM", a classic Microsoft technology for component
interconnection, is swamped by the homonimous occurrence of ".com" in
URLs, so you need the intitle: trick or something like that.

An interesting alternative would be to use search engines which do
semantic annotation, but I'm not very familiar with those, myself; I'd
be interested in details if anybody does try that.

Anyway, if you're interested in popularity issues, I believe these
techniques, for all their defects, will work better than asking a few
people or trying to generalize from unsystematic observations.


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


Re: RFC - n-puzzle.py

2007-05-19 Thread Peter Otten
Steve Holden wrote:

> Phoe6 wrote:
>> On May 19, 2:23 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
>>> Instead of:
>>> short_path = mdists[0]
>>> if mdists.count(short_path) > 1:
>>> write:
>>> short_path = mdists[0]
>>> if short_path in mdists[1:]:
>> 
>> I would like to understand the difference between the two if
>> statements.
>> I had used count method, to signify the meaning that, if the least
>> distance occurs more then proceed with block.
>> How is 'in' with list[1:] an advantage? If it is.
> 
> Because it can stop as soon as short_path is found, whereas the count
> method must examine all elements to determine whether they should
> increment the count beyond one.

It's a trade-off. You check only half (on average) of the items in the
original list, but in exchange copy all but one into a new list.
The idiom Raymond recommended only makes sense because comparison is "slow"
and slicing is "fast" in Python. 

If the original list were large in comparison to the available RAM the
following idiom might be preferrable:

it = iter(mdists)
short_path = it.next()
if short_path in it:
# ...

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


Re: Start

2007-05-19 Thread Glich
I got started here: http://showmedo.com/videos/python

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


Re: Python compared to other language

2007-05-19 Thread walterbyrd
On May 19, 7:23 am, Steve Holden <[EMAIL PROTECTED]> wrote:

> The reason you can do this with Python is precisely because the
> developers have ironed out the wrinkles between platforms by putting the
> requisite conditionals in the C source.

But that is my point. With Python, the language itself takes care of
the platform differences, so the same Python code will run on
different platforms. I realize that, at a lower level, everything is
done is C. But, from the developers point of view: developing code in
C requires more attention to platform specifics, than does developing
code in Python.

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


Re: Writelines() a bit confusing

2007-05-19 Thread aiwarrior
On May 19, 2:46 pm, "Gre7g Luterman" <[EMAIL PROTECTED]> wrote:
> "aiwarrior" <[EMAIL PROTECTED]> wrote in message
>
> news:[EMAIL PROTECTED]
>
> > If file.WriteLines( seq ) accepts a list and it says it writes lines,
> > why does it write the whole list in a single line. Be cause of that
> > the reverse of file.writelines(seq) is not file.readlines().
> > Are the assumptions i made correct? If yes why is this so?
>
> readlines() and writelines() are complimentary.  readlines() leaves the line
> terminators intact. It does not strip them off. writelines() does not add in
> carriage returns for the same reason.  For example:
>
> >>> D=open("temp.txt").readlines()
> >>> D
>
> ['the quick\n', 'brown fox\n', 'jumps over\n', 'the lazy dog.']
>
> >>> open("temp2.txt","w").writelines(D)
>
> will create temp2.txt to be identical to temp.txt.

I Haven't seen that way before thanks, both of you :D

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


Can't embed python in C++(Mingw[3.*] compiler)

2007-05-19 Thread Arjun Narayanan
For thr program,
#include "E:\Python25\include\Python.h"
#include

int main(int argc, char* argv[]){
Py_Initialise();
Py_Finalise();
return 0;
}
I get the errors,
main.cpp:7: `Py_Initialise' undeclared (first use this function)
main.cpp:7: (Each undeclared identifier is reported only once for each
function
   it appears in.)
main.cpp:8: `Py_Finalise' undeclared (first use this function)
Process terminated with status 1 (0 minutes, 1 seconds)
I included "E:\Python25\include\Python.h"

Also I think that when I use C instead of c++ errors did'nt happen
although I can't repeat that now
Also do I need to link only 'libpython25.a'

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


Re: Python compared to other language

2007-05-19 Thread walterbyrd
On May 19, 9:36 am, [EMAIL PROTECTED] (Alex Martelli) wrote:
>
> From these numbers it would seem that Ruby (and PHP) aren't really more
> web-specific than Perl (and Python).
>

Excellent find, nice work. However, if it is found that there are "X"
many PHP programs running payroll applications, does that mean that
those PHP programs are *not* web applications? I don't think that it
does.

I was surprised to see Ruby in the same catagory as Perl and Python,
when it  came to Scientific apps. I always thought of Ruby as being
used for database oriented web-based stuff. Just goes to show what I
don't know.

I can tell you this much for sure: when it comes to UNIX system
scripting, Perl is the leader, with Python as a solid second. Unless,
maybe, you count bash & bourne, which I don't because those are not
multi-purpose languages.

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


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-19 Thread Richard Hanson
On Fri, 18 May 2007 06:28:03 +0200, Martin v. Löwis wrote:

[excellent as always exposition by Martin]

Thanks, Martin. 

> P.S. Anybody who wants to play with generating visualisations
> of the PEP, here are the functions I used:

[code snippets]

Thanks for those functions, too -- I've been exploring with them and
am slowly coming to some understanding.

 -- Richard Hanson

"To many native-English-speaking developers well versed in other
programming environments, Python is *already* a foreign language --
judging by the posts here in c.l.py over the years." ;-)
__

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


Many-to-many pattern possiable?

2007-05-19 Thread Jia Lu
Hi all

 I see dict type can do 1-to-1 pattern, But is there any method to do
1-to-many, many-to-1 and many-to-many pattern ? What about using some
Serialized objects?

Thanks.

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


Re: Beginner question: module organisation

2007-05-19 Thread 7stud
On May 14, 7:09 am, [EMAIL PROTECTED] wrote:
> Hello :)
>
> I am new to python and I don't have much expirience in object-oriented
> technologies neither.
>
> The problem is the following: I have to create a simple python
> template script that will always follow the same algorithm, let's say:
> - read a mesh
> - transform the mesh (let's say, refine)
>
> The last step should be a kind of a black box:
> - the same input data format
> - some algorithme inside
> - the same output data format
>
> A number of different refine methods should be implemented. The end-
> user must be able to write easily a new method and call it from the
> base script without any major change.
>
> Something like this would be a solution (no classes created, no OO
> programming):
> - a module defining REFINE1(mesh), REFINE2(mesh), ...
> - in the script:
>   from MODULE import REFINE2 as REFINE
>   REFINE(mesh)
>
> Is it a proper solution for this kind of problem? How would you
> implement this kind of task?

How about this:

refineModule.py:
---
def refine(userfunc, mesh):
#process mesh
func(mesh)

aprogram.py:

import refineModule

def myRefine(mesh):
print mesh

refineModule.refine(myRefine, "hello world")

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


Re: docs patch: dicts and sets

2007-05-19 Thread 7stud
On May 19, 9:06 am, Steven Bethard <[EMAIL PROTECTED]> wrote:
> Alan Isaac wrote:
> > I submitted the language based on Bill and Carsten's proposals:
>
> >https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&;...
>
> > That language has been rejected.
> > You many want to read the discussion and see if
> > acceptible language still seems discoverable.
>
> Seems to me that you're focusing on the wrong part of the docs.  The
> source of this "bug" is not sets or dicts, but the default __hash__
> method implementation.  Why don't you propose adding something like:
>
>  The default __hash__ method is based on an object's id(), and can
>  therefore change between different iterations of the same program.
>
> to the docs for __hash__:
>
>  http://docs.python.org/ref/customization.html
>
> Then if you really feel you need to add something for sets and dicts,
> you can add a cross-reference to the __hash__ docs.
>
> STeVe


Here's an idea--add All the proposed changes to the docs.  Why not
allow user's to add any explanations to the docs that they want? Then
readers can choose the explanations that make the most sense to them.
It would eliminate endless, petty discussions about what minutiae are
more important, and it would allow people to spend their time on more
productive efforts.  And it would improve the docs exponentially.

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


Re: No Python for Blackberry?

2007-05-19 Thread David Boddie
On Saturday 19 May 2007 03:19, walterbyrd wrote:

> I could not find a version of Python that runs on a Blackberrry.
> 
> I'm just amazed. A fairly popular platform, and no Python
> implementation?

If you can get the hardware into the hands of capable developers, they'll
put Python on it. ;-)

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


Re: zipfile stupidly broken

2007-05-19 Thread Martin Maney
Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> To search 64k for all zip files would slow down the opening of all zip
> files whereas most zipfiles don't have comments.

No, actually it would only slow down for files which do have comments,
assuming I understand the code correctly.  IME most zipfiles don't have
any comments at all, and would be unaffected.  To be honest, if I had
even known that zipfiles could have comments before I ran into this,
I'd long since forgotten it.

> You don't need to do that, you can just "monkey patch" the _EndRecData
> function.

For a quick & dirty test, sure.  If I were certain I'd only ever use
this on one machine for a limited time (viz, no system upgrades that
replace zipfile.py) it might suffice.  But that doesn't generalize
worth a damn.

-- 
Education makes people easy to lead, but difficult to drive;
easy to govern, but impossible to enslave.  -- Henry Peter Brougham
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: zipfile [module and file format, both] stupidly broken

2007-05-19 Thread Martin Maney
Larry Bates <[EMAIL PROTECTED]> bristled:
> Are you serious? A zipfile with a comment > 4Kbytes.  I've never encountered
> such a beast.

If I hadn't run into one I would never have had a clue that Python's
zipfile module had this silly bug.

> As with any open source product it is much better to roll up your sleeves
> and pitch in to fix a problem than to rail about "how it is stupidly
> broken".  You are welcome to submit a patch or at the very least a good
> description of the problem and possible solutions.  If you have gotten a
> lot of value out of Python, you might consider this "giving back".  You
> haven't paid anything for the value it has provided.

Ah yes, the old "well, if you found it you should fix it" meme -
another reason I found it pretty easy to stop reading this group.  It's
as stupid a position as it ever was (and FWIW I don't believe I've ever
seen any of the real Python developers mouth this crap).

Now, I have learned somewhat more than I knew (or ever wanted to know)
about zipfiles since I smacked headfirst into this bug, and I've
changed the subject line to reflect my current understanding.  :-/  Back
then it had already occurred to me that *just* changing the size of the
step back seemed an incomplete fix: after all, that leaves you scanning
through random binary glop looking for the signature.  With the
signature being four bytes, okay, it will *nearly* always work (just as
the exisiting 4K scan does), but... well, from what I've read in the
format specs that's about as good as it gets.  The alternative, some
sort of backwards scan, would avoid the binary glop but has much the
same problem, in principle, with finding the signature embedded in the
archive comment.  Even worse, arguably, since that comment is
apparently entirely up to the archive creator, so if there's a way to
use a fake central directory for nefarious purposes, that would make it
trivial to do.  Which is the point where I decided that the file format
itself is broken...  (oh, and then I came across something from the
info-zip crew that said much the same thing, though they didn't mention
this particular design, uhm, shortcoming.)

So I guess that perhaps the stupidly obvious fix:

- END_BLOCK = min(filesize, 1024 * 4)
+ END_BLOCK = min(filesize, 1024 * 64 + 22)

is after all about the best that can be done.  (the lack of the
size-of-End-Of-Central-Directory-record in the existing code isn't a
separate bug, but if we're going to pretend we accomodate all valid
zipfiles it wouldn't do to overlook it)

So now you may imagine that your rudeness has had the result you
intended after all, and I guess it has, though at a cost - well, you
probably never cared what I thought about you anyway.

BTW, thanks for the pointer someone else gave to the proper place for
posting bugs.  I'd had the silly idea that I would be able to find that
easily at www.python.org, but if I had then I'd not have posted here
and had so much fun.

-- 
The most effective way to get information from usenet is not to ask
a question; it is to post incorrect information.  -- Aahz's Law

Apparently denigrating the bug reporter can sometimes result in a
patch, too, but I don't think that's in the same spirit.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-URL! - weekly Python news and links (May 16)

2007-05-19 Thread Fred Pacquier
[EMAIL PROTECTED] (Cameron Laird) said :

> I'll make a few personal comments.
> 
> I knew the choice of quotes was in questionable taste.  I was
> out to be provocative without being offensive, though.  My
> apologies to Mr. Beliavsky and anyone else I disappointed.  On
> the whole, I still think I constructed the QOTWs appropriately.
> 
> I have very little patience with The Analysts as a category.  I
> have friends and acquaintances in the business, and I respect
> them individually.  I am VERY skeptical about the sausage they
> produce at an institutional level, and can only experience its
> making for a few minutes at a time.

I myself found that QOTW twice hilarious : once for whom it was directed 
at, and once for whom it came from :-)

Thanks for a good laugh !

-- 
YAFAP : http://www.multimania.com/fredp/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Many-to-many pattern possiable?

2007-05-19 Thread Gre7g Luterman
"Jia Lu" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I see dict type can do 1-to-1 pattern, But is there any method to do
> 1-to-many, many-to-1 and many-to-many pattern ?

Dict objects can do many-to-1 relationships.

Dict[Key1] = Obj
Dict[Key2] = Obj
Dict[Key3] = Obj

1-to-many relationships are more tricky and not something built-in to 
dictionaries.  You can make each value in the dictionary a list of 
associated values:

Dict[Key] = [Obj1, Obj2, Obj3]

You can even subclass dict to give it the members you like, for example:

class OneToMany(dict):
def Add(self, Index, Value):
V = self.get(Index, [])
V.append(Value)
self[Index] = V 


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


Structuring the code of a wiki parsing engine

2007-05-19 Thread Michiel Sikma
Hello everybody. I'm kind of new to Python. I'm working on a simple  
text parser that will allow me to transform a certain syntax into a  
certain output. I find wikis interesting, so wiki to HTML parsing is  
one of the things that I want to accomplish (I'm not actually writing  
a whole wiki, that's complex, but I'm only trying to get basic text  
conversion going on).

Presently, I'm thinking of putting the (simple, regexp-driven)  
filters in a module called "parsers", and then make a "handlers"  
module that allows for the actual transformation. So, for example,  
one parser would be a separate class (WikiParser) which would have an  
attribute called "emph" (emphasis) which is a string '\*\*(.+?)\*\*'.  
Then a handler class (HTMLHandler) would have an attribute called  
"emph" which is a string '\\1'. Then the regular expressions  
would be generated via a chosen parser/handler combination. This to  
make it easy to change things around later.

My question to you: is this the right way to go about it? My parser  
doesn't really need to do all that much, but I would like for it to  
be easily changeable by editing a single file.

Thanks for any help!

Greets,
Michiel

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


Re: Many-to-many pattern possiable?

2007-05-19 Thread Raymond Hettinger
On May 19, 9:33 am, Jia Lu <[EMAIL PROTECTED]> wrote:
>  I see dict type can do 1-to-1 pattern, But is there any method to do
> 1-to-many, many-to-1 and many-to-many pattern ?

>>> mm = {'a': ['A', 'B', 'C'], 'c': ['C', 'D', 'E'], 'b': ['A', 'D']}

>>> # Now, invert the relation
>>> mmr = {}
>>> for k, seq in mm.items():
... for elem in seq:
... mmr.setdefault(elem, []).append(k)
>>> mmr
{'A': ['a', 'b'], 'C': ['a', 'c'], 'B': ['a'], 'E': ['c'], 'D': ['c',
'b']}


> What about using some
> Serialized objects?

from pickle import loads, dumps
d = dict(a=dumps(someobj), b=dumps(anotherobj))
obj = loads(d['a'])


Raymond

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


regex matching question

2007-05-19 Thread bullockbefriending bard
first, regex part:

I am new to regexes and have come up with the following expression:
 ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9])

to exactly match strings which look like this:

 1,2/3,4/5,6/7,8/9,10/11,12

i.e. 6 comma-delimited pairs of integer numbers separated by the
backslash character + constraint that numbers must be in range 1-14.

i should add that i am only interested in finding exact matches (doing
some kind of command line validation).

this seems to work fine, although i would welcome any advice about how
to shorten the above. it seems to me that there should exist some
shorthand for (1[0-4]|[1-9]) once i have defined it once?

also (and this is where my total beginner status brings me here
looking for help :)) i would like to add one more constraint to the
above regex. i want to match strings *iff* each pair of numbers are
different. e.g: 1,1/3,4/5,6/7,8/9,10/11,12 or
1,2/3,4/5,6/7,8/9,10/12,12 should fail to be matched  by my final
regex whereas 1,2/3,4/5,6/7,8/9,10/11,12 should match OK.

any tips would be much appreciated - especially regarding preceding
paragraph!

and now for the python part:

results = "1,2/3,4/5,6/7,8/9,10/11,12"
match = re.match("((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),
(1[0-4]|[1-9])", results)
if match == None or match.group(0) != results:
raise FormatError("Error in format of input string: %s" %
(results))
results = [leg.split(',') for leg in results.split('/')]
# => [['1', '2'], ['3', '4'], ['5', '6'], ['7', '8'], ['9', '10'],
['11', '12']]
.
.
.
the idea in the above code being that i want to use the regex match as
a test of whether or not the input string (results) is correctly
formatted. if the string results is not exactly matched by the regex,
i want my program to barf an exception and bail out. apart from
whether or not the regex is good idiom, is my approach suitably
pythonic?

TIA for any help here.

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


Re: Beginner question: module organisation

2007-05-19 Thread 7stud
On May 19, 10:45 am, 7stud <[EMAIL PROTECTED]> wrote:
>
> refineModule.py:
> ---
> def refine(userfunc, mesh):
> #process mesh
> func(mesh)
>

The last line should be:

userfunc(mesh)

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


Re: Python compared to other language

2007-05-19 Thread Steve Holden
walterbyrd wrote:
> On May 19, 7:23 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> 
>> The reason you can do this with Python is precisely because the
>> developers have ironed out the wrinkles between platforms by putting the
>> requisite conditionals in the C source.
> 
> But that is my point. With Python, the language itself takes care of
> the platform differences, so the same Python code will run on
> different platforms. I realize that, at a lower level, everything is
> done is C. But, from the developers point of view: developing code in
> C requires more attention to platform specifics, than does developing
> code in Python.
> 
That I can agree with, but it  isn't the same as "not portable". It 
would have been better to say "more difficult to port".

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: No Python for Blackberry?

2007-05-19 Thread Tommy Nordgren

On 19 maj 2007, at 03.19, walterbyrd wrote:

> I could not find a version of Python that runs on a Blackberrry.
>
> I'm just amazed. A fairly popular platform, and no Python
> implementation?
>
Download the sources and try compiling it yourself.
On most platforms
Expand the archive.
Then either:
Give the command ./configure(in the exanded python directory)
Or
create a directory (For example 'build-python') it the directory  
that CONTAINS the python distribution directory.
And then execute the command  ..//configure
(in the directory 'build' of the previous step)
then give the commands:
make
make check
sudo make install [whereupon the systom will ask for your  
administrator password]


-
This sig is dedicated to the advancement of Nuclear Power
Tommy Nordgren
[EMAIL PROTECTED]



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


Re: RFC - n-puzzle.py

2007-05-19 Thread Steve Holden
Peter Otten wrote:
> Steve Holden wrote:
> 
>> Phoe6 wrote:
>>> On May 19, 2:23 pm, Raymond Hettinger <[EMAIL PROTECTED]> wrote:
 Instead of:
 short_path = mdists[0]
 if mdists.count(short_path) > 1:
 write:
 short_path = mdists[0]
 if short_path in mdists[1:]:
>>> I would like to understand the difference between the two if
>>> statements.
>>> I had used count method, to signify the meaning that, if the least
>>> distance occurs more then proceed with block.
>>> How is 'in' with list[1:] an advantage? If it is.
>> Because it can stop as soon as short_path is found, whereas the count
>> method must examine all elements to determine whether they should
>> increment the count beyond one.
> 
> It's a trade-off. You check only half (on average) of the items in the
> original list, but in exchange copy all but one into a new list.
> The idiom Raymond recommended only makes sense because comparison is "slow"
> and slicing is "fast" in Python. 
> 
That's true.

> If the original list were large in comparison to the available RAM the
> following idiom might be preferrable:
> 
> it = iter(mdists)
> short_path = it.next()
> if short_path in it:
> # ...

Yes, that would nail it. Though of course it loses the obviousness which 
both original solutions have. I suppose that's often the nature of 
optimizations, though.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: docs patch: dicts and sets

2007-05-19 Thread Steve Holden
7stud wrote:
> On May 19, 9:06 am, Steven Bethard <[EMAIL PROTECTED]> wrote:
>> Alan Isaac wrote:
>>> I submitted the language based on Bill and Carsten's proposals:
>>> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&;...
>>> That language has been rejected.
>>> You many want to read the discussion and see if
>>> acceptible language still seems discoverable.
>> Seems to me that you're focusing on the wrong part of the docs.  The
>> source of this "bug" is not sets or dicts, but the default __hash__
>> method implementation.  Why don't you propose adding something like:
>>
>>  The default __hash__ method is based on an object's id(), and can
>>  therefore change between different iterations of the same program.
>>
>> to the docs for __hash__:
>>
>>  http://docs.python.org/ref/customization.html
>>
>> Then if you really feel you need to add something for sets and dicts,
>> you can add a cross-reference to the __hash__ docs.
>>
>> STeVe
> 
> 
> Here's an idea--add All the proposed changes to the docs.  Why not
> allow user's to add any explanations to the docs that they want? Then
> readers can choose the explanations that make the most sense to them.
> It would eliminate endless, petty discussions about what minutiae are
> more important, and it would allow people to spend their time on more
> productive efforts.  And it would improve the docs exponentially.
> 
Except in those instances where users added information that was 
explicitly wrong. Which any reader of this newsgroup knows is all too 
easy to do. So there would need to be some editorial control. Which 
would take effort that may not currently be available.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: Many-to-many pattern possiable?

2007-05-19 Thread 7stud
On May 19, 10:33 am, Jia Lu <[EMAIL PROTECTED]> wrote:
> Hi all
>
>  I see dict type can do 1-to-1 pattern, But is there any method to do
> 1-to-many, many-to-1 and many-to-many pattern ?

How about:

one_to_many = {"a":[10, "red", 2.5]}

many_to_1 = {("red", 2.5, 3):"hello"}

many_to_many = {("red", 2.5, 3):[10, 20, 30]}

In reality, everything is mapped 1-1.  I wonder if there is a computer
language where that isn't the case?

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


getting thread object from SocketServer.ThreadingTCPServer

2007-05-19 Thread Brad Brock
Hi list. I have a little problem when using
SocketServer.ThreadingTCPServer. I want to make a list
of  thread-objects generated by the
ThreadingTCPServer. How can I get the thread object?
Thank you.


   
Looking
 for a deal? Find great prices on flights and hotels with Yahoo! FareChase.
http://farechase.yahoo.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: docs patch: dicts and sets

2007-05-19 Thread 7stud
On May 19, 11:38 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> Except in those instances where users added information that was
> explicitly wrong.

It's a self correcting mechanism.  Other reader's will spot the error
and post corrections.

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


Re: Python compared to other language

2007-05-19 Thread Michael Torrie
On Fri, 2007-05-18 at 22:28 -0400, Steve Holden wrote:
> Surely the fact that Python is available on so many platforms implies 
> that C is a fairly portable language. I realise that you have to take 
> platform specifics into account much more than you do in Python, but I 
> do feel you are being somewhat unfair to C.

This is now going off-topic.  Cross-platform code is a matter of mindset
and toolset.  It's very possible to write python code that is *not*
cross-platform compatible.  Perhaps it relies a specific behavioral
quirk of the platform.  Or maybe it uses modules that only exist on a
platform.  For example, you can do very low-level COM or even Active X
programming using python.  That certainly wouldn't run on Linux.  The
same can be true of some python code that's only intended to run on
Posix systems.  You may have assumed a certain directory character
separator, for example (of course the os module can give you a portable
way of not making this assumption).

I write cross-platform C code all the time.  I do it by carefully
choosing my libraries (toolset) and then try to code making as few
assumptions as possible.  Platform-specific code is generally less than
6% of the total code.  I even wrote a cross-platform python module in C.
It's no big deal.  Recently I wrote a medium-sized C++ application using
Qt.  The platform-specific code (basically a few minor things Qt doesn't
do for me) is 10 lines total, out of many thousands of lines of code.
The apps compiles and runs on Linux, OS X, and Windows.  I plan to write
the next version in Python, but I'm still not sure what GUI toolkit to
use.  wxWidgets just doesn't sit well with me, Qt's licensing doesn't
fit my client (I can't afford the non-GPL version), and GTK isn't there
on OS X.

Python, like C, can be used easily to make cross-platform programs.
Python makes it even easier than C because the entire standard python
library of modules is available on every platform, so you don't have to
rely on as many third-party abstraction libraries for threads, sockets,
etc.  I think the original poster will find Python, and may wxPython,
satisfies the bulk of his development needs.

> 
> > I'm just learning Python. FWIW: my opinions about Python:
> [ ... ]
> 
> regards
>   Steve
> -- 
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd   http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> -- Asciimercial -
> Get on the web: Blog, lens and tag your way to fame!!
> holdenweb.blogspot.comsquidoo.com/pythonology
> tagged items: del.icio.us/steve.holden/python
> All these services currently offer free registration!
> -- Thank You for Reading 
> 

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


Re: Writelines() a bit confusing

2007-05-19 Thread Gabriel Genellina
En Sat, 19 May 2007 10:31:50 -0300, Stefan Sonnenberg-Carstens  
<[EMAIL PROTECTED]> escribió:

> so you'd want this:
>
> f.writelines([x+os.linesep for x in strings])
>
> or something similar.

You would use os.linesep *only* if the file was opened in binary mode -  
unusual if you want to write lines of text.
For a file opened in text mode (the default) the line terminator is always  
'\n' - let Python handle the platform differences. On Windows you would  
end with malformed or duplicate line terminators if you use explicitely  
os.linesep when writing.
See http://mail.python.org/pipermail/python-list/2000-May/037191.html

-- 
Gabriel Genellina

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


Re: regex matching question

2007-05-19 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>,
bullockbefriending bard wrote:

> first, regex part:
> 
> I am new to regexes and have come up with the following expression:
>  ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9])
> 
> to exactly match strings which look like this:
> 
>  1,2/3,4/5,6/7,8/9,10/11,12
> 
> i.e. 6 comma-delimited pairs of integer numbers separated by the
> backslash character + constraint that numbers must be in range 1-14.
> 
> i should add that i am only interested in finding exact matches (doing
> some kind of command line validation).
>
> […]
>
> the idea in the above code being that i want to use the regex match as
> a test of whether or not the input string (results) is correctly
> formatted. if the string results is not exactly matched by the regex,
> i want my program to barf an exception and bail out. apart from
> whether or not the regex is good idiom, is my approach suitably
> pythonic?

I would use a simple regular expression to extract "candidates" and a
Python function to split the candidate and check for the extra
constraints.  Especially the "all pairs different" constraint is something
I would not even attempt to put in a regex.  For searching candidates this
should be good enough::

  r'(\d+,\d+/){5}\d+,\d+'

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

Re: docs patch: dicts and sets

2007-05-19 Thread Steve Holden
7stud wrote:
> On May 19, 11:38 am, Steve Holden <[EMAIL PROTECTED]> wrote:
>> Except in those instances where users added information that was
>> explicitly wrong.
> 
> It's a self correcting mechanism.  Other reader's will spot the error
> and post corrections.
> 
The last thing I want to read in a language's documentation is an 
ill-informed and sometimes interminable argument about a particular feature.

For documentation I'm all in favor of user contributions, but I believe 
an editorial process is required to ensure readability. I am aware that 
the documentation isn't perfect but it's pretty good, and I don't think 
throwing it open to anyone (including, by the way, web spammers) to add 
to it is necessarily  the best way to improve it.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: docs patch: dicts and sets

2007-05-19 Thread 7stud
On May 19, 12:36 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
> The last thing I want to read in a language's documentation is an
> ill-informed and sometimes interminable argument about a particular feature.
>

Yet some readers will be able to get to the bottom of an issue they
are having by reading those comments.

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


Re: RFC - n-puzzle.py

2007-05-19 Thread Peter Otten
Phoe6 wrote:

> I would like to request a code and design review of one of my program.
> n-puzzle.py

> I have used OO Python for the above program and would like comments on
> my approach as I am just starting with OOP.

[The following has nothing to do with OOP, I just read Raymond's post and
got interested in the context]

> class State:

>def huristic_next_state(self, st):

It's heuristics, not huristics.

  # Choose a random item from exp_sts among those with minimal 
  # manhattan_distance()
> exp_sts = self.expand(st)
> mdists = []
> for st in exp_sts:
> mdists.append(self.manhattan_distance(st))
> mdists.sort()
> short_path = mdists[0]
> if mdists.count(short_path) > 1:
> least_paths = []
> for st in exp_sts:
> if self.manhattan_distance(st) == short_path:
> least_paths.append(st)
> return random.choice(least_paths)
> else:
> for st in exp_sts:
> if self.manhattan_distance(st) == short_path:
> return st

Looks like you do not need the count() method call at all as the branch for
multiple nearest items works with a length-one list, too. As a consequence, 
there's no need to keep a list of distances, just the minimum:

# all untested
exp_sts = self.expand(st)
short_path = min(exp_sts, key=self.manhattan_distance)
least_paths = [s for s in exp_sts 
if self.manhattan_distance(s) == short_path]
return random.choice(least_paths)

Calling random.choice() on a list with only one item is predictable but will
do no harm if the code is not time-critical.

By the way, you could write a helper function that finds all minima
according to some criterion

>>> minima([1, 2, -1, 1.0, 3], key=abs)
[1, -1, 1.0]

With such a function the method body would become

return random.choice(minima(self.expand(st), key=self.manhattan_distance))

Almost self-documenting, I'd say :-)

Here's a quick and dirty implementation:

def minima(values, key=lambda x: x):
d = {}
for v in values:
d.setdefault(key(v), []).append(v)
return d[min(d)]

The advantage of this approach is that you

- iterate over the list just once
- call the key() function once per list item
- can test the function independently from your State class

The memory overhead for the extra lists can be avoided by a better
implementation.

Peter

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


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-19 Thread René Fleschenberg
Martin v. Löwis schrieb:
> I've reported this before, but happily do it again: I have lived many
> years without knowing what a "hub" is, and what "to pass" means if
> it's not the opposite of "to fail". Yet, I have used their technical
> meanings correctly all these years.

I was not speaking of the more general (non-technical) meanings, but of
the technical ones. The claim which I challenged was that people learn
just the "use" (syntax) but not the "meaning" (semantics) of these
terms. I think you are actually supporting my argument ;)

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

Re: Python-URL! - weekly Python news and links (May 16)

2007-05-19 Thread Grant Edwards
On 2007-05-17, Beliavsky <[EMAIL PROTECTED]> wrote:
>
>> QOTW: "Sometimes you just have to take the path of least
>> distaste". - Grant Edwards
>>
>> "I want to choose my words carefully here, so I'm not misunderstood.  
>
>
>
> I think Cameron Laird does a good job with the Python digest
> but blundered here. Why did he highlight a foul comment having
> nothing to do with Python?

Having stumbled across this discussion in mid-thread, I was
relieved to find out after following the thread upstream that
that the "foul comment" in question wasn't mine. :)

That said, I thought the other quote was rather amusing (both
in style and content).

I while I don't think that those "research" firms actually do
anything useful, I wouldn't call them idiots. They seem to have
figured out how to extract sizable amounts of money from
corporate types by providing them with compilations of useless
generalizations and meaningless pseudo-statistics.  The people
paying them are probably the ones more deserving of derision.

-- 
Grant Edwards   grante Yow! Thousands of days of
  at   civilians ... have produced
   visi.coma ... feeling for the
   aesthetic modules --
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-19 Thread René Fleschenberg
Martin v. Löwis schrieb:
>>> Then get tools that match your working environment.
>> Integration with existing tools *is* something that a PEP should
>> consider. This one does not do that sufficiently, IMO.
> 
> What specific tools should be discussed, and what specific problems
> do you expect?

Systems that cannot display code parts correctly. I expect problems with
unreadable tracebacks, for example.

Also: Are existing tools that somehow process Python source code e.g. to
test wether it meets certain criteria (pylint & co) or to aid in
creating documentation (epydoc & co) fully unicode-ready?

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

Re: docs patch: dicts and sets

2007-05-19 Thread Steven Bethard
7stud wrote:
> On May 19, 9:06 am, Steven Bethard <[EMAIL PROTECTED]> wrote:
>> Alan Isaac wrote:
>>> I submitted the language based on Bill and Carsten's proposals:
>>> https://sourceforge.net/tracker/?func=detail&atid=105470&aid=1721372&;...
>>> That language has been rejected.
>>> You many want to read the discussion and see if
>>> acceptible language still seems discoverable.
>> Seems to me that you're focusing on the wrong part of the docs.  The
>> source of this "bug" is not sets or dicts, but the default __hash__
>> method implementation.  Why don't you propose adding something like:
>>
>>  The default __hash__ method is based on an object's id(), and can
>>  therefore change between different iterations of the same program.
>>
>> to the docs for __hash__:
>>
>>  http://docs.python.org/ref/customization.html
>>
>> Then if you really feel you need to add something for sets and dicts,
>> you can add a cross-reference to the __hash__ docs.
> 
> Here's an idea--add All the proposed changes to the docs.  Why not
> allow user's to add any explanations to the docs that they want? Then
> readers can choose the explanations that make the most sense to them.
> It would eliminate endless, petty discussions about what minutiae are
> more important, and it would allow people to spend their time on more
> productive efforts.

Actually, it would just move the "endless, petty discussions about what 
minutiae are more important" into the docs. I don't see how that's an 
improvement.

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


Re: docs patch: dicts and sets

2007-05-19 Thread Robert Kern
7stud wrote:
> On May 19, 12:36 pm, Steve Holden <[EMAIL PROTECTED]> wrote:
>> The last thing I want to read in a language's documentation is an
>> ill-informed and sometimes interminable argument about a particular feature.
> 
> Yet some readers will be able to get to the bottom of an issue they
> are having by reading those comments.

And most will simply be confused.

-- 
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: PEP 3131: Supporting Non-ASCII Identifiers

2007-05-19 Thread Peter Maas
Martin v. Löwis wrote:
> Python code is written by many people in the world who are not familiar
> with the English language, or even well-acquainted with the Latin
> writing system.

I believe that there is a not a single programmer in the world who doesn't
know ASCII. It isn't hard to learn the latin alphabet and you have to know
it anyway to use the keywords and the other ASCII characters to write numbers,
punctuation etc. Most non-western alphabets have ASCII transcription rules
and contain ASCII as a subset. On the other hand non-ascii identifiers
lead to fragmentation and less understanding in the programming world so I
don't like them. I also don't like non-ascii domain names where the same
arguments apply.

Let the data be expressed with Unicode but the logic with ASCII.

-- 
Regards/Gruesse,

Peter Maas, Aachen
E-mail 'cGV0ZXIubWFhc0B1dGlsb2cuZGU=\n'.decode('base64')
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: List Moderator

2007-05-19 Thread Dotan Cohen
On 19/05/07, Steve Holden <[EMAIL PROTECTED]> wrote:
> I'm sorry, but you have no idea what you are talking about. Most of what
> can be done *is* being done, which is why you see the relatively low
> spam volumes you do.
>

I hope that I don't. I receive no less than 700 spams a day to my
regular address (not gmail, which I use for mailing lists), but then
again I've only twice gone over 2000 spams in a single day. I can only
imagine the efforts used to keep the list clean. Maybe spamassasin, a
few hundred procmail filters, and a last swipe with bogofilter for
good measure?

I don't mean to be pushy, but every day I add another procmail filter
based upon what's been getting through (and they still do, I try to
err on 'false negative'). Four filters "britney", "spears", "boobs"
and "tits" would show the spammers that the moderators are serious
about keeping this list clean.

I'll go back to reading and not writing now, at least until I get to
the point where either I feel that I can contribute, or until I get
myself real stuck.

Dotan Cohen

http://lyricslist.com/lyrics/artist_albums/252/heaven_17.html
http://what-is-what.com/what_is/operating_system.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: _PyObject_New / PyObject_Init / PyInstance_New / etc?

2007-05-19 Thread Gabriel Genellina
En Sat, 19 May 2007 10:54:32 -0300, Gre7g Luterman <[EMAIL PROTECTED]>  
escribió:

> I'm so confuzzled! How do I instantiate my new C Python object from C?
> I tried inserting some code with _PyObject_New and PyObject_Init:
>
> Then I compiled, went into the Python interpreter and tried it.  I would
> have expected Noddy_name to create and destroy a Noddy object just like
> noddy2.Noddy() does from the interpreter, but it doesn't:

 From Python, you create a Noddy object by *calling* its type. Do the same  
in C:

return PyObject_CallObject((PyObject *) &NoddyType, NULL);

Or any other suitable variant of PyObject_CallXXX. (I've answered this  
same question yesterday, when I was not sure about this; then I've tried  
it and it appears to be working. But I've not read any docs telling this  
is *the* right way to create an object).

> I've tried this as above, and with PyInstance_New, with PyObject_New (no
> underscore), and PyObject_Call, but none of them work as I would expect.  
> So
> what is the *CORRECT* way to do this?  Obviously I'm neglecting something
> important.

PyInstance_New is for old style classes. PyObject_New only initializes the  
object structure, and this is enough for most builtin types that usually  
don't define __init__ (or tp_init). You were right with PyObject_Call, but  
maybe you didn't invoke it correctly.

-- 
Gabriel Genellina

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


Re: Can't embed python in C++(Mingw[3.*] compiler)

2007-05-19 Thread Gabriel Genellina
En Sat, 19 May 2007 13:14:40 -0300, Arjun Narayanan  
<[EMAIL PROTECTED]> escribió:

> For thr program,
> #include "E:\Python25\include\Python.h"
> #include

Configure your environment so using:

#include 

works (you may need to add E:\Python25\include to some list of searched  
directories, maybe an INCLUDE environment variable).

-- 
Gabriel Genellina

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


Re: List Moderator

2007-05-19 Thread Steve Holden
Dotan Cohen wrote:
> On 19/05/07, Steve Holden <[EMAIL PROTECTED]> wrote:
>> I'm sorry, but you have no idea what you are talking about. Most of what
>> can be done *is* being done, which is why you see the relatively low
>> spam volumes you do.
> 
> I hope that I don't. I receive no less than 700 spams a day to my
> regular address (not gmail, which I use for mailing lists), but then
> again I've only twice gone over 2000 spams in a single day. I can only
> imagine the efforts used to keep the list clean. Maybe spamassasin, a
> few hundred procmail filters, and a last swipe with bogofilter for
> good measure?
> 
> I don't mean to be pushy, but every day I add another procmail filter
> based upon what's been getting through (and they still do, I try to
> err on 'false negative'). Four filters "britney", "spears", "boobs"
> and "tits" would show the spammers that the moderators are serious
> about keeping this list clean.
> 
> I'll go back to reading and not writing now, at least until I get to
> the point where either I feel that I can contribute, or until I get
> myself real stuck.
> 
All I am saying is that it's difficult to catch *everything* when so 
much of the content comes in via Usenet. These posts never touch any 
python.org infrastructure before being incorporated into the newsgroup 
content on servers all over the world. Whose procmail filters will 
protect you from that?

You are right about some of the technologies being used, and Spambayes 
also enters the picture. I'm not sure we are using bogofilter.

Looking at the headers in one of the messages you were writing about it 
appears they are being posted from Google groups, so maybe you could 
complain to them. Good luck with that ;-).

The Python list managers know what they are doing, and they *do* keep a 
huge amount of spam off the list. The occasional piece gets through, but 
this is Usenet. It will, from time to time.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
-- Asciimercial -
Get on the web: Blog, lens and tag your way to fame!!
holdenweb.blogspot.comsquidoo.com/pythonology
tagged items: del.icio.us/steve.holden/python
All these services currently offer free registration!
-- Thank You for Reading 

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


Re: getting thread object from SocketServer.ThreadingTCPServer

2007-05-19 Thread Gabriel Genellina
En Sat, 19 May 2007 14:40:55 -0300, Brad Brock <[EMAIL PROTECTED]>  
escribió:

> Hi list. I have a little problem when using
> SocketServer.ThreadingTCPServer. I want to make a list
> of  thread-objects generated by the
> ThreadingTCPServer. How can I get the thread object?

If getting the list of ALL threads (using threading.enumerate()) is not  
enough, you would need to override the process_request method to save the  
thread object in your own list.

-- 
Gabriel Genellina

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


Re: zipfile [module and file format, both] stupidly broken

2007-05-19 Thread Gabriel Genellina
En Sat, 19 May 2007 14:00:01 -0300, Martin Maney <[EMAIL PROTECTED]>  
escribió:

> BTW, thanks for the pointer someone else gave to the proper place for
> posting bugs.  I'd had the silly idea that I would be able to find that
> easily at www.python.org, but if I had then I'd not have posted here
> and had so much fun.

My microwave oven doesn't work very well, it's rather new and I want it  
fixed. I take the manual, go to the last pages, and find how to contact  
the factory.
A module in the Python Standard Library has a bug. I take the Python  
Library Reference manual, go to the last pages (Appendix B), and find how  
to properly report a bug.

-- 
Gabriel Genellina

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


Re: [Bulk] Re: Python compared to other language

2007-05-19 Thread scott
Michael Torrie wrote:

> I think the original poster will find Python, and may wxPython,
> satisfies the bulk of his development needs.
True, I like how Python is a general language that can be used for many 
different purposes and hope to learn wxPython as well.  I have read 
through the archives and found some good suggestions for books/tutorials.

-- 
Your friend,
Scott

Sent to you from a 100% Linux computer using Kubuntu Version 7.04 
(Feisty Fawn)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: dislin titlin and string decode

2007-05-19 Thread luis
On 19 mayo, 12:56, luis <[EMAIL PROTECTED]> wrote:
> Hello!
>
> I have an unespectedn result with dislin titlin
>
> dislin.metafl ('WMF')
> dislin.disini ()
>
> 
> a="Andrés or Ramón"
> dislin.titlin (a.encode("Latin-1"), 1)
> # not error raised, is ok
> 
>
> dislin.disfin ()
>
> In the output file all is ok but the title is
>
> Andr s or Ram n
>
> Thanks in advance!

The problem was the value of dislin.chacod. This must be 'ISO1' not
the default ('STANDAR')

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


Re: dislin titlin and string decode

2007-05-19 Thread Gabriel Genellina
En Sat, 19 May 2007 18:28:51 -0300, luis <[EMAIL PROTECTED]> escribió:

> The problem was the value of dislin.chacod. This must be 'ISO1' not
> the default ('STANDAR')

I used to use DISLIN some time ago, but now I use PyChart most of the  
time. Its convoluted interfase (mostly due to Fortran support, I guess)  
makes it rather "ugly" to use from Python. (And has a very strange  
licence, btw.)

-- 
Gabriel Genellina

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


Re: docs patch: dicts and sets

2007-05-19 Thread 7stud
>Actually, it would just move the "endless, petty discussions about what
>minutiae are more important" into the docs. I don't see how that's an
>improvement.

Because it highlights the issues you will be faced with when using the
described functions.  People will post about an issue they had with a
function, and then they will post their solution.  Instead of having
to search all over google for an answer, the most relevant discussions
will be right in the docs.   As you read the user comments, you would
be able to quickly tell whether a comment pertains to the issue you
are having trouble with, and if the comment isn't relevant, you can
skip the comment and look at the next comment.  If you wanted, you
could limit yourself to reading just the official python description
of the function and be no worse off.

>And most will simply be confused.

Then it's likely someone will post something to clear up the confusion.

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


Re: regex matching question

2007-05-19 Thread bullockbefriending bard
thanks for your suggestion. i had already implemented the all pairs
different constraint in python code. even though i don't really need
to give very explicit error messages about what might be wrong with my
data (obviously easier to do if do all constraint validation in code
rather than one regex), there is something to be said for your
suggestion to simplify my regex further - it might be sensible from a
maintainability/readability perspective to use regex for  *format*
validation and then validate all *values* in code.

from my cursory skimming of friedl, i get the feeling that the all
pairs different constraint would give rise to some kind of fairly
baroque expression, perhaps likely to bring to mind the following
quotation from samuel johnson:

 "Sir, a woman's preaching is like a dog's walking on his hind legs.
It is not done well; but you are surprised to find it done at all."

however, being human, sometimes some things should be done, just
because they can :)... so if anyone knows hows to do it, i'm still
interested, even if just out of idle curiosity!

On May 20, 12:57 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> In <[EMAIL PROTECTED]>,
>
>
>
> bullockbefriending bard wrote:
> > first, regex part:
>
> > I am new to regexes and have come up with the following expression:
> >  ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9])
>
> > to exactly match strings which look like this:
>
> >  1,2/3,4/5,6/7,8/9,10/11,12
>
> > i.e. 6 comma-delimited pairs of integer numbers separated by the
> > backslash character + constraint that numbers must be in range 1-14.
>
> > i should add that i am only interested in finding exact matches (doing
> > some kind of command line validation).
>
> > [...]
>
> > the idea in the above code being that i want to use the regex match as
> > a test of whether or not the input string (results) is correctly
> > formatted. if the string results is not exactly matched by the regex,
> > i want my program to barf an exception and bail out. apart from
> > whether or not the regex is good idiom, is my approach suitably
> > pythonic?
>
> I would use a simple regular expression to extract "candidates" and a
> Python function to split the candidate and check for the extra
> constraints.  Especially the "all pairs different" constraint is something
> I would not even attempt to put in a regex.  For searching candidates this
> should be good enough::
>
>   r'(\d+,\d+/){5}\d+,\d+'
>
> Ciao,
> Marc 'BlackJack' Rintsch


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


Re: regex matching question

2007-05-19 Thread Gabriel Genellina
En Sat, 19 May 2007 19:40:39 -0300, bullockbefriending bard  
<[EMAIL PROTECTED]> escribió:

> from my cursory skimming of friedl, i get the feeling that the all
> pairs different constraint would give rise to some kind of fairly
> baroque expression, perhaps likely to bring to mind the following
> quotation from samuel johnson:
>
>  "Sir, a woman's preaching is like a dog's walking on his hind legs.
> It is not done well; but you are surprised to find it done at all."

Try this, it's not as hard, just using match and split (with the regular  
expression propossed by MR):

import re
regex = re.compile(r'(\d+,\d+/){5}\d+,\d+')

def checkline(line):
 if not regex.match(line):
 raise ValueError("Invalid format: "+line)
 for pair in line.split("/"):
 a, b = pair.split(",")
 if a==b:
 raise ValueError("Duplicate number: "+line)

Here "all pairs different" means "for each pair, both numbers must be  
different", but they may appear in another pair. That is, won't flag  
"1,2/3,4/3,5/2,6/8,3/1,2" as invalid, but this wasn't clear from your  
original post.

-- 
Gabriel Genellina

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


mod_python performs several magnitudes slower than PHP?

2007-05-19 Thread chris . monsanto
Recently I've had to move my site to a new dedicated server running
FreeBSD 6.1. After installing apache 2.0.59, python 2.4.4 and
mod_python 3.3.1, I decided to bench a script in PHP vs one in Python.
I found out that for some reason, my mod_python was performing
extremely slow - magnitudes slower than it should. I scowered the
internet for hours and asked a few friends and still haven't been able
to find a solution to the problem.

from mod_python import apache

def handler(req):
  for i in xrange(1000):
print >> req, "Yeah"
  return apache.OK

and...



when I ran ab on both using 1000 requests and a concurrency of 10, i
got these results:

python- Requests per second:21.37 [#/sec] (mean)
php- Requests per second:1008.37 [#/sec] (mean)

Any ideas would really be appreciated... I'm on my last leg.

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


Re: regex matching question

2007-05-19 Thread John Machin
On 20/05/2007 3:21 AM, bullockbefriending bard wrote:
> first, regex part:
> 
> I am new to regexes and have come up with the following expression:
>  ((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),(1[0-4]|[1-9])
> 
> to exactly match strings which look like this:
> 
>  1,2/3,4/5,6/7,8/9,10/11,12
> 
> i.e. 6 comma-delimited pairs of integer numbers separated by the
> backslash character + constraint that numbers must be in range 1-14.

Backslash? Your example uses a [forward] slash.

Are you sure you don't want to allow for some spaces in the data, for 
the benefit of the humans, e.g.
1,2 / 3,4 / 5,6 / 7,8 / 9,10 / 11,12
?

> 
> i should add that i am only interested in finding exact matches (doing
> some kind of command line validation).
> 
> this seems to work fine, although i would welcome any advice about how
> to shorten the above. it seems to me that there should exist some
> shorthand for (1[0-4]|[1-9]) once i have defined it once?
> 
> also (and this is where my total beginner status brings me here
> looking for help :)) i would like to add one more constraint to the
> above regex. i want to match strings *iff* each pair of numbers are
> different. e.g: 1,1/3,4/5,6/7,8/9,10/11,12 or
> 1,2/3,4/5,6/7,8/9,10/12,12 should fail to be matched  by my final
> regex whereas 1,2/3,4/5,6/7,8/9,10/11,12 should match OK.
> 
> any tips would be much appreciated - especially regarding preceding
> paragraph!
> 
> and now for the python part:
> 
> results = "1,2/3,4/5,6/7,8/9,10/11,12"
> match = re.match("((1[0-4]|[1-9]),(1[0-4]|[1-9])/){5}(1[0-4]|[1-9]),
> (1[0-4]|[1-9])", results)

Always use "raw" strings for patterns, even if you don't have 
backslashes in them -- and this one needs a backslash; see below.

For clarity, consider using "mobj" or even "m" instead of "match" to 
name the result of re.match.


> if match == None or match.group(0) != results:

Instead of
if mobj == None 
use
if mobj is None ...
or
if not mobj ...

Instead of the "or match.group(0) != results" caper, put \Z (*not* $) at 
the end of your pattern:
mobj = re.match(r"pattern\Z", results)
if not mobj:


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


Inverse of id()?

2007-05-19 Thread Paul McGuire
Is there an inverse function to the builtin 'id'?  The poster who
asked about 1-to-1, 1-to-n, etc. relationships (presumably in CS terms
- I hope I didn't misread some porn spam by mistake), got me thinking
about containers and ids, and what kind of a container would implement
a many-to-many.

I happened to still have my Python interpreter open from noodling
about another poster's question, using named arguments and parse-time
functions in a regex, so I looked at the 'results' variable that
experiment generated (this was a quick way to work with a non-trivial
object, so if I reconstructed it from an id, I could test whether I
really got back the object):
>>> re = Regex("(\d*)").setResultsName("x").setParseAction(lambda t:int(t[0]))
>>> results = re.parseString("123")

pyparsing results have some special lookup behavior, that if the
results name is a Python-friendly identifier, can use the name as if
it were an object attribute:
>>> results.x
123

So I extracted the id of results, and then started looking for the
function that does the inverse of id.  Unfortunately, skimming through
the docs, I didn't find it, so I brute-force searched the globals()
dict:
>>> z = id(results)
>>> for x in globals().values():
...   if id(x)==z: break
...

This gives me a variable x that is indeed another ref to the results
variable:
>>> x is results
True
>>> x.x
123

Now is there anything better than this search technique to get back a
variable, given its id?

-- Paul

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


Re: regex matching question

2007-05-19 Thread bullockbefriending bard

> Backslash? Your example uses a [forward] slash.

correct.. my mistake. i use forward slashes.

> Are you sure you don't want to allow for some spaces in the data, for
> the benefit of the humans, e.g.
> 1,2 / 3,4 / 5,6 / 7,8 / 9,10 / 11,12

you are correct. however, i am using string as a command line option
and can get away without quoting it if there are no optional spaces.

> Always use "raw" strings for patterns, even if you don't have
> backslashes in them -- and this one needs a backslash; see below.

knew this, but had not done so in my code because wanted to use '\' as
a line continuation character to keep everything within 80 columns.
have adopted your advice regarding \Z below and now am using raw
string.

> For clarity, consider using "mobj" or even "m" instead of "match" to
> name the result of re.match.

good point.

> > if match == None or match.group(0) != results:
>
> Instead of
> if mobj == None 
> use
> if mobj is None ...
> or
> if not mobj ...
>
> Instead of the "or match.group(0) != results" caper, put \Z (*not* $) at
> the end of your pattern:
> mobj = re.match(r"pattern\Z", results)
> if not mobj:
>
> HTH,
> John

very helpful advice. thanks!

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


Re: mod_python performs several magnitudes slower than PHP?

2007-05-19 Thread John Nagle
That's puzzling, because with mod_python, you're only invoking
the compiler once per Apache restart.  With CGI programs, you pay
the loading penalty on every request.

John Nagle

[EMAIL PROTECTED] wrote:
> Recently I've had to move my site to a new dedicated server running
> FreeBSD 6.1. After installing apache 2.0.59, python 2.4.4 and
> mod_python 3.3.1, I decided to bench a script in PHP vs one in Python.
> I found out that for some reason, my mod_python was performing
> extremely slow - magnitudes slower than it should. I scowered the
> internet for hours and asked a few friends and still haven't been able
> to find a solution to the problem.
> 
> from mod_python import apache
> 
> def handler(req):
>   for i in xrange(1000):
> print >> req, "Yeah"
>   return apache.OK
> 
> and...
> 
>for ($i = 0; $i < 1000; $i++)
> echo "Yeah\n" ;
> ?>
> 
> when I ran ab on both using 1000 requests and a concurrency of 10, i
> got these results:
> 
> python- Requests per second:21.37 [#/sec] (mean)
> php- Requests per second:1008.37 [#/sec] (mean)
> 
> Any ideas would really be appreciated... I'm on my last leg.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2

2007-05-19 Thread John Machin
On 19/05/2007 9:17 PM, James Stroud wrote:
> John Machin wrote:
>> The approach that I've adopted is to test the values in a column for 
>> all types, and choose the non-text type that has the highest success 
>> rate (provided the rate is greater than some threshold e.g. 90%, 
>> otherwise it's text).
>>
>> For large files, taking a 1/N sample can save a lot of time with 
>> little chance of misdiagnosis.
> 
> 
> Why stop there? You could lower the minimum 1/N by straightforward 
> application of Bayesian statistics, using results from previous tables 
> as priors.
> 

The example I gave related to one file out of several files prepared at 
the same time by the same organisation from the same application by the 
same personnel using the same query tool for a yearly process which has 
been going on for several years. All files for a year should be in the 
same format, and the format should not change year by year, and the 
format should match the agreed specifications ... but this doesn't 
happen. Against that background, please explain to me how I can use 
"results from previous tables as priors".

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


Re: regex matching question

2007-05-19 Thread bullockbefriending bard
> Instead of the "or match.group(0) != results" caper, put \Z (*not* $) at
> the end of your pattern:
> mobj = re.match(r"pattern\Z", results)
> if not mobj:

as the string i am matching against is coming from a command line
argument to a script, is there any reason why i cannot get away with
just $ given that this means that there is no way a newline could find
its way into my string? certainly passes all my unit tests as well as
\Z. or am i missing the point of \Z ?

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


Re: regex matching question

2007-05-19 Thread bullockbefriending bard
> Here "all pairs different" means "for each pair, both numbers must be  
> different", but they may appear in another pair. That is, won't flag  
> "1,2/3,4/3,5/2,6/8,3/1,2" as invalid, but this wasn't clear from your  
> original post.
>
> --
> Gabriel Genellina

thanks! you are correct that the 'all pairs different' nomenclature is
ambiguous. i require that each pair have different values, but is OK
for different pairs to be identical... so exactly as per your code
snippet.

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


Re: python shell

2007-05-19 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Paddy  <[EMAIL PROTECTED]> wrote:
>On May 16, 6:38 pm, Krypto <[EMAIL PROTECTED]> wrote:
>> I have been using python shell to test small parts of the big program.
>> What other ways can I use the shell effectively. My mentor told me
>> that you can virtually do anything from testing your program to
>> anything in the shell. Any incite would be useful.
>
>Doctest!
>http://en.wikipedia.org/wiki/Doctest
.
.
.
http://en.wikipedia.org/wiki/DocTest > will probably prove more fruitful.

While I don't like follow-ups which consist of trivial corrections, I *very*
much want to encourage readers to explore Doctest more deeply; it deserves the 
attention, even at the cost of appearing pedantic.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to convert a number to binary?

2007-05-19 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Lyosha  <[EMAIL PROTECTED]> wrote:
.
.
.
>While I agree with this general statement, I think remembering a
>particular one-liner to convert a number to a binary is more valuable
>to my brain than remembering where I placed the module that contains
>this function.
>
>I needed the one-liner not to save disk space or screen lines.  It's
>to save time, should I need to convert to binary when doing silly
>little experiments.  I would spend more time getting the module
>wherever it is I stored it (and rewriting it if it got lost).
>
>It's fun, too.

I know the feeling.

In fact, there's a point here that's deep enough to deserve a follow-up.
Various people, including, I think, the timbot, have said that the 
distinction of a good high-level language is code NON-re-use; that is,
in the positive aspect, a language like Python is so expressive and 
productive that it makes it generally easier to re-use *ideas* than code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: converting strings to most their efficient types '1' --> 1, 'A' ---> 'A', '1.2'---> 1.2

2007-05-19 Thread John Machin
On 19/05/2007 3:14 PM, Paddy wrote:
> On May 19, 12:07 am, py_genetic <[EMAIL PROTECTED]> wrote:
>> Hello,
>>
>> I'm importing large text files of data using csv.  I would like to add
>> some more auto sensing abilities.  I'm considing sampling the data
>> file and doing some fuzzy logic scoring on the attributes (colls in a
>> data base/ csv file, eg. height weight income etc.) to determine the
>> most efficient 'type' to convert the attribute coll into for further
>> processing and efficient storage...
>>
>> Example row from sampled file data: [ ['8','2.33', 'A', 'BB', 'hello
>> there' '100,000,000,000'], [next row...] ]
>>
>> Aside from a missing attribute designator, we can assume that the same
>> type of data continues through a coll.  For example, a string, int8,
>> int16, float etc.
>>
>> 1. What is the most efficient way in python to test weather a string
>> can be converted into a given numeric type, or left alone if its
>> really a string like 'A' or 'hello'?  Speed is key?  Any thoughts?
>>
>> 2. Is there anything out there already which deals with this issue?
>>
>> Thanks,
>> Conor
> 
> You might try investigating what can generate your data. With luck,
> it could turn out that the data generator is methodical and column
> data-types are consistent and easily determined by testing the
> first or second row. At worst, you will get to know how much you
> must check for human errors.
> 

Here you go, Paddy, the following has been generated very methodically; 
what data type is the first column? What is the value in the first 
column of the 6th row likely to be?

"$39,082.00","$123,456.78"
"$39,113.00","$124,218.10"
"$39,141.00","$124,973.76"
"$39,172.00","$125,806.92"
"$39,202.00","$126,593.21"

N.B. I've kindly given you five lines instead of one or two :-)

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


  1   2   >