Re: 450 Pound Library Program

2006-02-08 Thread mwt
A million thanks for in-depth critique. I look forward to figuring out
half of what you're talking about ;)

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


Re: how to remove using replace function?

2006-02-08 Thread Dylan Moreland

[EMAIL PROTECTED] wrote:
> nope didn't work

Could you be more specific about the error? Both my example and yours
work perfectly on my box.

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


Re: how to remove using replace function?

2006-02-08 Thread localpricemaps
nope didn't work

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


Re: how to remove using replace function?

2006-02-08 Thread localpricemaps
tried that, didn't work for me

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


Re: cx_Oracle entry point error

2006-02-08 Thread Albert Leibbrandt
[EMAIL PROTECTED] wrote:

>I downloaded cx_Oracle from
>http://www.cxtools.net/default.aspx?nav=cxorlb and selected the windows
>installer for Oracle 8i, Python 2.4
>
>>From the readme.txt file:
>BINARY INSTALL:
>Place the file cx_Oracle.pyd or cx_Oracle.so anywhere on your Python
>path.
>
>So I tried this and set PYTHONPATH.
>
>I then created a script called ora_conn.py with one line:
>import cx_Oracle
>
>When I run the script (c:\python24\python.exe ora_conn.py) I get this
>error in a pop-up box:
>
>"The procedure entry point OCIEnvCreate could not be located in the
>dynamic link ligrary OCI.dll
>
>The bottom line of what I want to do is to connect to an oracle
>database without having to create an ODBC connection on the individual
>PC.
>
>Any ideas?  Thanks.
>
>  
>
are you running on windows or linux?
On both of these os's I only needed to install the binary. Have a look 
at this page on sourceforge 
http://sourceforge.net/project/showfiles.php?group_id=84168

cheers
albert

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


Re: only a simple xml reader value

2006-02-08 Thread Albert Leibbrandt
[EMAIL PROTECTED] wrote:

>I'm newbie with that xml stuff.
>
>The only thing I must read is the response I get from a EPP server.
>A response like this:
>
>
>http://www.eurid.eu/xml/epp/epp-1.0";
>xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance";
>xmlns:contact="http://www.eurid.eu/xml/epp/contact-1.0";
>xmlns:domain="http://www.eurid.eu/xml/epp/domain-1.0";
>xmlns:eurid="http://www.eurid.eu/xml/epp/eurid-1.0";
>xmlns:nsgroup="http://www.eurid.eu/xml/epp/nsgroup-1.0";
>xsi:schemaLocation="http://www.eurid.eu/xml/epp/epp-1.0 epp-1.0.xsd
>http://www.eurid.eu/xml/epp/contact-1.0 contact-1.0.xsd
>http://www.eurid.eu/xml/epp/domain-1.0 domain-1.0.xsd
>http://www.eurid.eu/xml/epp/eurid-1.0 eurid-1.0.xsd
>http://www.eurid.eu/xml/epp/nsgroup-1.0 nsgroup-1.0.xsd">
>
>
>Command completed successfully; ending session
>
>
>
>c-and-a.eu
> c-and-a_1
>25651602
>2005-11-08T14:51:08.929Z
>
>
>
>
>
>OK
>
>
>
>
>clientref-12310026
>eurid-1589
>
>
>
>
>//
>//Command completed successfully; ending session
>
>what is the official/best way to handle/parse such xml response ?
>
>Thats maybe a better question
>
>  
>
try something like this:

import xml.dom.minidom as dom
doc = dom.parseString("""
The Fascist Menace""")
print doc.getElementsByTagName('title')[0].childNodes[0].data

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


Re: Unable to get PIL to load jpeg images

2006-02-08 Thread Amit Khemka
This is because PIL, is not able to find the jpeg library .

1. Install jpeg-libs from sources: (http://www.ijg.org/files/jpegsrc.v6b.tar.gz)
2.0: "clean" the PIL build
2.1 In setup.py that comes with PIL, set the JPEG_ROOT to the jpeg-lib path
3.0 run setup.py

I hope that should help ..

cheers,
amit


On 2/9/06, Andrew Gwozdziewycz <[EMAIL PROTECTED]> wrote:
> On 2/7/06, Steve Holden <[EMAIL PROTECTED]> wrote:
> > [EMAIL PROTECTED] wrote:
> > > Someone out there must surely know - please!
> > >
> > > Peter
> > >
>
> Try building the PIL from scratch. It might give you some insight as
> to which library it exactly is looking for. I can remember when
> compiling the PIL on my mac having to create a symbolic link to
> libjpeg.so.6 or something. It was bizarre but worked fine afterwards.
>
> --
> Andrew Gwozdziewycz <[EMAIL PROTECTED]>
> http://ihadagreatview.org
> http://plasticandroid.org
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--

Amit Khemka -- onyomo.com
Endless the world's turn, endless the sun's Spinning, Endless the quest;
I turn again, back to my own beginning, And here, find rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Uses of The 4th Dimension (New Discovery by The Human Race!)

2006-02-08 Thread TheSmokingGnu
Walter Mitty wrote:
> 
> 
> Jesus. I misread "clock" there for a minute taking into account the
> context. Yeuckkk.
> 

Heh. Don't tell me you've got dirty clocks, too?

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


Re: random playing soundfiles according to rating.

2006-02-08 Thread Michael Spencer
[EMAIL PROTECTED] wrote:
...

> 
> But i am stuck on how to do a random chooser that works according to my
> idea of choosing according to rating system. It seems to me to be a bit
> different that just choosing a weighted choice like so:
> 
...
> 
> And i am not sure i want to have to go through what will be hundreds of
> sound files and scale their ratings by hand so that they all add up to
> 100%. I just want to have a long list that i can add too whenever i
> want, and assign it a grade/rating according to my whims!
> 
Perhaps something like this:

from bisect import bisect_left
from random import randrange

def w_choice(range, weights):
 """Return a choice from range, given *cumulative* relative frequencies"""
 total = weights[-1]
 pick = randrange(1,total)
 ix = bisect_left(weights, pick)
 return range[ix]


def cum_sum(iterable, start = 0):
 cum = []
 for i in iterable:
 start += i
 cum.append(start)
 return cum

Test it:
  >>> files = {"File1": 20, "File2": 10, "File3":70}
  >>> def test(files, N = 1):
  ... names = files.keys()
  ... weights = cum_sum(files.values())
  ...
  ... plays = {}
  ... for i in range(N):
  ... track = w_choice(names, weights)
  ... plays[track] = plays.get(track, 0) + 1
  ... return plays
  ...
  >>> test(files, N=1)
  {'File3': 7039, 'File2': 1049, 'File1': 1912}
  >>> files["File4"] = 50
  >>> test(files, N=15)
  {'File3': 70502, 'File2': 9988, 'File1': 20009, 'File4': 49501}
  >>>


Michael


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


Re: Too Many if Statements?

2006-02-08 Thread [EMAIL PROTECTED]
Juho Schultz wrote:
>
> However, the following gives a SystemError with only 2500 elif's.

SystemErrors should never occur, if you see one it's a bug.

[valid program which demonstrates a python bug]

> Traceback (most recent call last):
>File "iftest.py", line 10, in ?
>  exec prog
> SystemError: com_backpatch: offset too large
>
> I tried this with Python 2.3.3 and 2.3.4 (Linux) and both fail.

Yup, 2.4 fails too.  Unfortunately, this looks like a bugger to fix in
2.4.  So I doubt it will be fixed for old versions of python.  The good
news is that it's fixed for 2.5.

n

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


Re: how to remove using replace function?

2006-02-08 Thread Dylan Moreland
I think you want to use the replace method of the string instance.
Something like this will work:

# See http://docs.python.org/lib/string-methods.html#l2h-196
txt = "an unfortunate  in the middle"
txt = txt.replace("", "")

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


how to remove using replace function?

2006-02-08 Thread localpricemaps
i have some html that looks like this


34 main, Boston, MA

and i am trying to use the replace function to get rid of the  that
i scrape out using this code:

for oText in incident.fetchText( oRE):
strTitle += oText.strip()
strTitle = string.replace(strTitle,'','')

but it doesn't seem to remove the 

any ideas?

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


Re: Replacing curses

2006-02-08 Thread Ian Ward
Ross Ridge wrote:
> Thomas Dickey wrote:
>>...and send UTF-8 text, keeping track of where you really are on the screen.
> You make that sound so easy.

I'll have to deal with that anyway, since I'm doing all my own wrapping,
justification and clipping of text.  (don't talk to me about RtoL text,
I'm getting to it)

I'm going to look at the Mined text editor for some terminal behavior
detection code.  Mined is able to produce good UTF-8 output on a variety
of terminals, and it links agains ncurses, not ncursesw...  Interesting.

Ian Ward


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


Re: random playing soundfiles according to rating.

2006-02-08 Thread Steve Holden
[EMAIL PROTECTED] wrote:
> I am a little bit stuck 
> 
> I want to play a bunch of soundfiles randomly, but i want to give each
> soundfile a rating (say 0-100) and have the likelihood that the file be
> chosen be tied to its rating so that the higher the rating the more
> likely a file is to be chosen.  Then i need some additional flags for
> repetition, and some other business. I am guessing a dictionary would
> be a great way to do this, with the key being the soundfile name and
> the values being my ratings and other flags & associated data.
> 
> #soundfile name : [rating, %chance it will repeat/loop]
> sfiles = { ("sf001") : [85, 15],
>  ("sf002") : [25, 75],
>  ("sf003") : [95, 45],
>  ("sf004") : [35, 95] }
> 
> 
> But i am stuck on how to do a random chooser that works according to my
> idea of choosing according to rating system. It seems to me to be a bit
> different that just choosing a weighted choice like so:
> 
> def windex(lst):
>   '''an attempt to make a random.choose() function that makes weighted
> choices
> 
>   accepts a list of tuples with the item and probability as a pair
>   like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)]
>   >>> y=windex(x)'''
>   n = random.uniform(0, 1)
>   for item, weight in lst:
>   if n < weight:
>   break
>   n = n - weight
>   return item
> 
> 
> And i am not sure i want to have to go through what will be hundreds of
> sound files and scale their ratings by hand so that they all add up to
> 100%. I just want to have a long list that i can add too whenever i
> want, and assign it a grade/rating according to my whims!
> 

A really cheesy scheme: decide you will allocate each file a probability 
between 0 and 10 or 1 and 10 - whatever. 100 may be a bit much - do you 
really need such fine discrimination?

If you have your list [(filename, prob), (filename, prob), ... ] then 
construct a filename list as follows:

flist = []
for filename, prob in lst:
 flist += [filename] * prob

Then choosing a filename becomes quite simple:

file_to_play = random.choice(flist)

The rest is up to you ...

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Replacing curses (Was: Re: Problem with curses and UTF-8)

2006-02-08 Thread Ian Ward
Jean-Paul Calderone wrote:
>> I've looked at newt and snack, but all I really need is:
>> - a way to position the cursor at (0,0)
>> - a way to hide and show the cursor
>> - a way to detect when the terminal is resized
>> - a way to query the terminal size
> 
> You might be interested in Twisted Conch's insults package.  I haven't 
> followed this thread closely, so I'm not sure if it covers all your 
> requirements, but it can do all of the above.

Thanks for the pointer!  twisted.conch.insult definitely has some of 
what I need.  The code for handling window resizing isn't jumping out at 
me but I'll keep looking.

Ian Ward

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


Re: still a valid book?

2006-02-08 Thread John Salerno
Scott David Daniels wrote:
> John Salerno wrote:
>> Jonathan Gardner wrote:
>>> You may want to read
>>> http://python.org/doc/2.4.2/whatsnew/whatsnew24.html to get an idea of
>>> what has changed from 2.3 to 2.4 if you buy the 2.3 book.
>>>
>> Yeah, I was looking at that, but it seems a little over my head right 
>> now. I just didn't want to learn anything and then have to "unlearn" it. 
>> I'm sure I will always be adding new things, so that isn't so much the 
>> problem I guess.
> Python remains _extremely_ compatible from one minor version to the next
> (2.2 to 2.3, 2.3 to 2.4, ...) Python 3000 (which may well be Python 3.0)
> is allowed to break compatibility, _but_ it won't be conceptual
> compatibility; it will just discard "old stuff we no longer like."  I
> would suggest you don't pay much attention to "old-style classes":
>   class WhatEver:
>  ...
> and only use "new-style" classes:
>  class SomeClass(object):
>  ...
> since the "old-style classes" are going away (the "class Name: ..."
> syntax will start defining new-style classes as well).  Starting with
> 2.3 will put you quite near the modern edge, and the changes you will
> have to learn are not that great. People are still running code written
> under 1.5.2, so 2.3 is really quite modern.
> 
> --Scott David Daniels
> [EMAIL PROTECTED]

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


random playing soundfiles according to rating.

2006-02-08 Thread kp87

I am a little bit stuck 

I want to play a bunch of soundfiles randomly, but i want to give each
soundfile a rating (say 0-100) and have the likelihood that the file be
chosen be tied to its rating so that the higher the rating the more
likely a file is to be chosen.  Then i need some additional flags for
repetition, and some other business. I am guessing a dictionary would
be a great way to do this, with the key being the soundfile name and
the values being my ratings and other flags & associated data.

#soundfile name : [rating, %chance it will repeat/loop]
sfiles = { ("sf001") : [85, 15],
 ("sf002") : [25, 75],
 ("sf003") : [95, 45],
 ("sf004") : [35, 95] }


But i am stuck on how to do a random chooser that works according to my
idea of choosing according to rating system. It seems to me to be a bit
different that just choosing a weighted choice like so:

def windex(lst):
'''an attempt to make a random.choose() function that makes weighted
choices

accepts a list of tuples with the item and probability as a pair
like: >>> x = [('one', 0.25), ('two', 0.25), ('three', 0.5)]
>>> y=windex(x)'''
n = random.uniform(0, 1)
for item, weight in lst:
if n < weight:
break
n = n - weight
return item


And i am not sure i want to have to go through what will be hundreds of
sound files and scale their ratings by hand so that they all add up to
100%. I just want to have a long list that i can add too whenever i
want, and assign it a grade/rating according to my whims!

cheers,

-kp---

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


Re: removing characters before writing to file

2006-02-08 Thread Frank Potter
r=re.compile(r"(\(')|( '\))|'")print r.sub('',str(output))On 8 Feb 2006 18:35:01 -0800, [EMAIL PROTECTED]
 <[EMAIL PROTECTED]> wrote:
hii have some output that returns a lines of tuples egtr('sometext1', 1421248118, 1, 'P ')('sometext2', 1421248338, 2, 'S ')and so onI tried thisre.sub(r" '() ",'',str(output)) but it only get rid of the ' and not
the braces. I need to write the output to a file such thatsometext1, 1421248118, 1, Psometext2, 1421248338, 2, SI also tried escaping , re.sub(r" '\(\) ",'',str(output)) but also didnot work
How can i get rid of the braces before writing to file? thanks--http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: removing characters before writing to file

2006-02-08 Thread jawahh
', '.join(map(str,output))

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


Re: Jython inherit from Java class

2006-02-08 Thread Kent Johnson
Mark Fink wrote:
> I wrote a Jython class that inherits from a Java class and (thats the
> plan) overrides one method. Everything should stay the same.
> 
> If I run this nothing happens whereas if I run the Java class it says:
> usage: java fit.FitServer [-v] host port socketTicket
> -v  verbose

It sounds like the Java class has a main() function. When you run it as 
an application, the Java runtime looks for the main() function in the 
class you tell it to run.

Even in Java, this behaviour is not preserved by inheritance, a subclass 
has to have its own main() to be executable.

Jython (and Python) works a little differently, your module is executed 
from start to finish when you run it. Any statements that are not inside 
a class or function definition will be executed. (Actually the class and 
function definitions are executed to, but not in the same way...)

You might get the behaviour you want if you put the line
import sys
fit.FitServer.main(sys.argv)

at the end of your file. This will run the main() function of the Java 
class.

Kent

> 
> I think this is because I do not understand the jython mechanism for
> inheritance (yet).
> 
> JyFitServer.py:
> ===
> import fit.FitServer
> import fitnesse.components.FitProtocol
> from fit.Parse import Parse
> from fit.Fixture import Fixture
> 
> # Inherit from original Java FitServer Implementation by Robert C.
> Martin and Micah D. Martin
> class FitServer(fit.FitServer):
> # call constructor of superclass
> def __init__(self, host, port, verbose):
> FitServer.__init__(self, host, port, verbose)
> 
> # override process method
> def process(self):
> self.fixture.listener = self.fixtureListener
> print "hello, I am JyFitServer!"
> try:
> size = FitProtocol.readSize(self.socketReader)
> if size > 0:
> try:
> document =
> FitProtocol.readDocument(self.socketReader, size)
> tables = Parse(document)
> fixture = Fixture()
> fixture.listener = self.fixtureListener;
> fixture.doTables(tables)
> self.counts.tally(self.fixture.counts)
> except FitParseException, e:
> self.exception(e)
> except Exception, e:
> self.exception(e)
> 
> 
> 
> Please help,
> Mark Fink
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: still a valid book?

2006-02-08 Thread Scott David Daniels
John Salerno wrote:
> Jonathan Gardner wrote:
>> You may want to read
>> http://python.org/doc/2.4.2/whatsnew/whatsnew24.html to get an idea of
>> what has changed from 2.3 to 2.4 if you buy the 2.3 book.
>>
> 
> Yeah, I was looking at that, but it seems a little over my head right 
> now. I just didn't want to learn anything and then have to "unlearn" it. 
> I'm sure I will always be adding new things, so that isn't so much the 
> problem I guess.
Python remains _extremely_ compatible from one minor version to the next
(2.2 to 2.3, 2.3 to 2.4, ...) Python 3000 (which may well be Python 3.0)
is allowed to break compatibility, _but_ it won't be conceptual
compatibility; it will just discard "old stuff we no longer like."  I
would suggest you don't pay much attention to "old-style classes":
  class WhatEver:
 ...
and only use "new-style" classes:
 class SomeClass(object):
 ...
since the "old-style classes" are going away (the "class Name: ..."
syntax will start defining new-style classes as well).  Starting with
2.3 will put you quite near the modern edge, and the changes you will
have to learn are not that great. People are still running code written
under 1.5.2, so 2.3 is really quite modern.

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


removing characters before writing to file

2006-02-08 Thread eight02645999
hi
i have some output that returns a lines of tuples eg

('sometext1', 1421248118, 1, 'P ')
('sometext2', 1421248338, 2, 'S ')
and so on


I tried this
re.sub(r" '() ",'',str(output)) but it only get rid of the ' and not
the braces. I need to write the output to a file such that

sometext1, 1421248118, 1, P
sometext2, 1421248338, 2, S

I also tried escaping , re.sub(r" '\(\) ",'',str(output)) but also did
not work
How can i get rid of the braces before writing to file? thanks

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


Twisted book opinions?

2006-02-08 Thread Jay Parlar
I was hoping to get some c.l.p. opinions on O'Reilly's new Twisted book.

I'm coming at Twisted as someone who's been programming mainly in 
Python for almost 6 years now, but who's never done any Twisted 
development. I've used some of its prepackaged libraries before (and 
did some custom tweaks to TwistedSNMP), but I don't really know much at 
all about Twisted fundamentals.

The few reviews on Amazon seem to imply that it's more of a cookbook. 
Would I be better off, for now, trying to get what I can from the 
twistedmatrix.com docs, and then move to the book when I'm comfortable 
with the basics? Or would the fact that I'm already pretty strong in 
Python be enough that I could start with the book?

I considered posting this to the Twisted list instead, but thought I'd 
try somewhere a little more impartial :)

Thanks in advance,
JayP.

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


Re: Pulling all n-sized combinations from a list

2006-02-08 Thread Swroteb
Yes, certainly.  I hadn't done any profiling up to that point, but it
really seemed like my biggest time sink was inefficiently losing time
in obtaining the combinations.

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


Re: Replacing curses

2006-02-08 Thread Ross Ridge
Thomas Dickey wrote:
> ...and send UTF-8 text, keeping track of where you really are on the screen.

You make that sound so easy.

  Ross Ridge

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


Re: still a valid book?

2006-02-08 Thread John Salerno
Jonathan Gardner wrote:
> You may want to read
> http://python.org/doc/2.4.2/whatsnew/whatsnew24.html to get an idea of
> what has changed from 2.3 to 2.4 if you buy the 2.3 book.
> 

Yeah, I was looking at that, but it seems a little over my head right 
now. I just didn't want to learn anything and then have to "unlearn" it. 
I'm sure I will always be adding new things, so that isn't so much the 
problem I guess.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pulling all n-sized combinations from a list

2006-02-08 Thread Paul Rubin
Michael Spencer <[EMAIL PROTECTED]> writes:
> This is roughly 30 times faster on my box than the general solution above

Good point.  You could probably improve the generator version some
(probably not 30x) by doing less list arithmetic and slicing though.
I just wrote it the most straightforward way I could.  You could
probably speed up the nested-loops version somewhat too, by keeping
track of the indices instead of doing all that list slicing.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with curses and UTF-8

2006-02-08 Thread Damjan
I just recompiled my python to link to ncursesw, and tried your example
with a little modification:

import curses, locale
locale.setlocale(locale.LC_ALL, '')
s = curses.initscr()
s.addstr(u'\u00c5 U+00C5 LATIN CAPITAL LETTER A WITH RING
ABOVE\n'.encode('utf-8') )
s.addstr(u'\u00f5 U+00F5 LATIN SMALL LETTER O WITH
TILDE\n'.encode('utf-8'))
s.refresh()
s.getstr()
curses.endwin()

And it works ok for me, Slackware-10.2, python-2.4.2, ncurses-5.4 all
in KDE's konsole.
My locale is mk_MK.UTF-8.

Now it would be great if python's curses module worked with unicode
strings directly.

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


Re: Replacing curses (Was: Re: Problem with curses and UTF-8)

2006-02-08 Thread Jean-Paul Calderone
On Wed, 08 Feb 2006 15:10:26 -0500, Ian Ward <[EMAIL PROTECTED]> wrote:
>Grant Edwards wrote:
>> Depending on what you're tring to do, slang might be an option,
>
>I've looked at newt and snack, but all I really need is:
>- a way to position the cursor at (0,0)
>- a way to hide and show the cursor
>- a way to detect when the terminal is resized
>- a way to query the terminal size

You might be interested in Twisted Conch's insults package.  I haven't followed 
this thread closely, so I'm not sure if it covers all your requirements, but it 
can do all of the above.

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


Re: Pulling all n-sized combinations from a list

2006-02-08 Thread Michael Spencer
Swroteb wrote:
> Paul Rubin wrote:
>> I think the natural approach is to make a generator that yields a
>> 5-tuple for each combination, and then have your application iterate
>> over that generator.  Here's my version:
>>
>> def comb(x,n):
>> """Generate combinations of n items from list x"""
>> if n==0:
>> yield []
>> return
>> for i in xrange(len(x)-n+1):
>> for r in comb(x[i+1:], n-1):
>> yield [x[i]] + r
>>
>> for c in comb([1,2,3,4,5], 3):
>> print c
>>
>> The output is:
>> >>>
>> [1, 2, 3]
>> [1, 2, 4]
>> [1, 2, 5]
>> [1, 3, 4]
>> [1, 3, 5]
>> [1, 4, 5]
>> [2, 3, 4]
>> [2, 3, 5]
>> [2, 4, 5]
>> [3, 4, 5]
>> >>>
> 
> Ah, this definitely seems to work!  It's a lot nicer in appearance than
> my previous code, that's for sure.  It actually runs in approximately
> the same amount of time though.  So, using your comb method, I have the
> following code now:
> 
> myCombinations = comb(myList, 5)
> for a, b, c, d, e in myCombinations:
> # my code
> 
> myList is 48 elements in size, so I'm going to get 1712304
> combinations.  From what I can tell, my speed problems aren't in the
> list generation anymore.
> 
> Thanks for the assistance, Paul!  I appreciate it.  :)
> 
If you're concerned about speed, and don't mind lack of flexibility, spelling 
out the iteration within your function is much faster:

def comb(seq):
 indices = range(len(seq))
 for ia in indices:
 a = seq[ia]
 for ib in indices[ia+1:]:
 b = seq[ib]
 for ic in indices[ib+1:]:
 c = seq[ic]
 for id in indices[ic+1:]:
 d = seq[id]
 for ie in indices[id+1:]:
 e = seq[ie]

This is roughly 30 times faster on my box than the general solution above

Michael



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


Re: Replacing curses

2006-02-08 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Thomas Dickey <[EMAIL PROTECTED]> wrote:

> Ian Ward <[EMAIL PROTECTED]> wrote:
...
> > Also, screen resizing only seems to be reported once by getch() even if
> > the user continues to resize the window.  I have worked around this by
> > calling curses.doupdate() between calls to getch(). Maybe this is by 
> > design?
> 
> Or perhaps it's some interaction with python - I don't know.
> The applications that I use with resizing (and ncurses' test
> programs) work smoothly enough.

I have no idea about the present application, but just as a
general observation, when Python traps a signal, it saves
the signal number, and makes a note to check for trapped signals
as the next Python operation.  That check iterates through the
list of possible signals to see if any have been caught, and
execute their respective handlers if any.

Since an external function call is an operation, no signal
handler will execute until it returns.  At that time, the
signal handler will execute once, at most.

> > Finally, the curses escape sequence detection could be broadened. The
> > top part of the curses_display module in Urwid defines many escape
> > sequences I've run into that curses doesn't detect.
> 
> That's data (terminfo).  ncurses is data-driven, doesn't "detect"
> features of the terminal (though it does of course use environment
> variables for locale, etc.).
> 
> xterm's terminfo lists a lot of function keys, for instance.

This is just my opinion, but any application that depends
on function keys in terminfo is broken, automatically.
Optional support for function keys is a nice touch, but the
data isn't good enough out there to depend on it.

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


Re: still a valid book?

2006-02-08 Thread Jonathan Gardner
You may want to read
http://python.org/doc/2.4.2/whatsnew/whatsnew24.html to get an idea of
what has changed from 2.3 to 2.4 if you buy the 2.3 book.

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


Re: UnboundMethodType and MethodType

2006-02-08 Thread Scott David Daniels
Kirk McDonald wrote:
 > Scott David Daniels wrote: 
 >
 > You know what? That makes perfect sense. Thank you.

Thanks a lot for mentioning this.  I do try to help out, and sometimes
it feels like talking to the wind.  A thanks every now and then is
greatly appreciated.

Just for fun, you can play with:

 import sys
 sys.getrefcount(123**18)
vs.
 sys.getrefcount(12)

You should know that 'small' integers are kept and shared once built.
Similarly, some strings (including all one-character strings and strings
that might be identifiers).
 sys.getrefcount('a')
 sys.getrefcount('probably_not_really_a_variable')

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


Re: Replacing curses

2006-02-08 Thread Thomas Dickey
Ian Ward <[EMAIL PROTECTED]> wrote:
> Thomas Dickey wrote:
>> hmm - I've read Urwid, and most of the comments I've read in that regard
>> reflect problems in Urwid.  Perhaps it's time for you to do a little 
>> analysis.
>> 
>> (looking forward to bug reports, rather than line noise)

> A fair request.  My appologies for the inflammatory subject :-)

> When trying to check for user input without waiting I use code like:
> window_object.nodelay(1)
> curses.cbreak()
> input = window_object.getch()

> Occasionally (hard to reproduce reliably) the cbreak() call will raise
> an exception, but if I call it a second time before calling getch the
> code will work properly.  This problem might be related to a signal
> interrupting the function call, I'm not sure.

perhaps a more complete test-case would let me test it and see.

> Also, screen resizing only seems to be reported once by getch() even if
> the user continues to resize the window.  I have worked around this by
> calling curses.doupdate() between calls to getch(). Maybe this is by design?

Or perhaps it's some interaction with python - I don't know.
The applications that I use with resizing (and ncurses' test
programs) work smoothly enough.

> Finally, the curses escape sequence detection could be broadened. The
> top part of the curses_display module in Urwid defines many escape
> sequences I've run into that curses doesn't detect.

That's data (terminfo).  ncurses is data-driven, doesn't "detect"
features of the terminal (though it does of course use environment
variables for locale, etc.).

xterm's terminfo lists a lot of function keys, for instance.

The limit for predefined function-key names for terminfo is 60,
but ncurses can accept extended terminfo descriptions (but I like to
limit the length and style of names so it's possible to access them
from termcap).  One could define names like shift_f1, but then termcap
applications couldn't see them.  (The last I knew, slang doesn't either,
but that's a different thread).

That's been true for about 6 years.

Current xterm's terminfo includes these names which apply to your
comment:  The ones on the end are extended names that ncurses' tic
deduces from the terminfo file when it compiles it:

comparing xterm-new to xterm-xf86-v44.
comparing booleans.
comparing numbers.
comparing strings.
kf49: '\EO3P', NULL.
kf50: '\EO3Q', NULL.
kf51: '\EO3R', NULL.
kf52: '\EO3S', NULL.
kf53: '\E[15;3~', NULL.
kf54: '\E[17;3~', NULL.
kf55: '\E[18;3~', NULL.
kf56: '\E[19;3~', NULL.
kf57: '\E[20;3~', NULL.
kf58: '\E[21;3~', NULL.
kf59: '\E[23;3~', NULL.
kf60: '\E[24;3~', NULL.
kf61: '\EO4P', NULL.
kf62: '\EO4Q', NULL.
kf63: '\EO4R', NULL.
kind: '\E[1;2B', NULL.
kri: '\E[1;2A', NULL.
kDN: '\E[1;2B', NULL.
kDN5: '\E[1;5B', NULL.
kDN6: '\E[1;6B', NULL.
kLFT5: '\E[1;5D', NULL.
kLFT6: '\E[1;6D', NULL.
kRIT5: '\E[1;5C', NULL.
kRIT6: '\E[1;6C', NULL.
kUP: '\E[1;2A', NULL.
kUP5: '\E[1;5A', NULL.
kUP6: '\E[1;6A', NULL.

-- 
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Circe released to public domain!

2006-02-08 Thread Diez B. Roggisch
Kyle Brooks schrieb:
> Wednesday, February 8th, 2006.
> 
> Dear all,
> 
> I hereby release Circe to the public domain.
> 
> Our repo is at http://kbrooks.ath.cx/repos/circe.


This is the second post I read, followed the link, skimmed through some 
sources and READMEs, and by now I got the impression that Circe is a IRC 
client. It would help tremendously if you could mention that in your 
postings as well as in a simple introductionary HTML-page. Mentioning 
why I should use Circe and what I need to do so (wx) would help too, I 
guess.


Regards,

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


Re: Replacing curses

2006-02-08 Thread Thomas Dickey
Ian Ward <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>> Depending on what you're tring to do, slang might be an option,

> I've looked at newt and snack, but all I really need is:
> - a way to position the cursor at (0,0)
> - a way to hide and show the cursor
> - a way to detect when the terminal is resized
> - a way to query the terminal size

...and send UTF-8 text, keeping track of where you really are on the screen.

-- 
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Replacing curses

2006-02-08 Thread Thomas Dickey
Grant Edwards <[EMAIL PROTECTED]> wrote:

> Depending on what you're tring to do, slang might be an option,

perhaps not - he's trying to use UTF-8.  I haven't seen any plausible
comment that indicates John Davis is interested in updating newt to
work with slang2 (though of course he's welcome to show the code ;-)

-- 
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with curses and UTF-8

2006-02-08 Thread Thomas Dickey
Ian Ward <[EMAIL PROTECTED]> wrote:
> Martin v. Löwis wrote:

>> If that was Python's configure: don't do that. Instead, hack setup.py
>> to make it change the compiler/linker settings, or even edit the
>> compiler/linker line manually at first.

> Ok, that compiled.

same here - though it was not immediately not clear which copy of ncurses it's
using (not the shared libraries since I installed those with tracing - a
little odd for it to use the static library, but that's what the access time
tells me).

To check on that (since I wanted to read the ncurses trace),
I ran strace and ltrace to look for clues.

> Now when I run the same test:

> import curses
> s = curses.initscr()
> s.addstr('\xc3\x85 U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE\n')
> s.addstr('\xc3\xa5 U+00F5 LATIN SMALL LETTER O WITH TILDE')
> s.refresh()
> s.getstr()
> curses.endwin()

Testing this, and looking to see what's going on, I notice that python
is doing a

setlocale(LC_ALL, "C");

before the addstr is actually called.  (ncurses never sets the locale;
it calls setlocale in one place to ask what it is).

That makes ncurses think it's not really doing UTF-8, of course.  What I
see on the screen is the U+00C5 comes out with a box and a "~E" (the
latter being ncurses' representation in POSIX for \0x85).

> This is what I see:

>   +00C5 LATIN CAPITAL LETTER A WITH RING ABOVE
>   +00F5 LATIN SMALL LETTER O WITH TILDE


> so, the UTF-8 characters didn't appear and the " U" at the beginning 
> became just " ".

well - running in uxterm I see the second line properly.  But some more
tinkering is needed to make python work properly.

-- 
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net
-- 
http://mail.python.org/mailman/listinfo/python-list


cx_Oracle entry point error

2006-02-08 Thread lblr33
I downloaded cx_Oracle from
http://www.cxtools.net/default.aspx?nav=cxorlb and selected the windows
installer for Oracle 8i, Python 2.4

>From the readme.txt file:
BINARY INSTALL:
Place the file cx_Oracle.pyd or cx_Oracle.so anywhere on your Python
path.

So I tried this and set PYTHONPATH.

I then created a script called ora_conn.py with one line:
import cx_Oracle

When I run the script (c:\python24\python.exe ora_conn.py) I get this
error in a pop-up box:

"The procedure entry point OCIEnvCreate could not be located in the
dynamic link ligrary OCI.dll

The bottom line of what I want to do is to connect to an oracle
database without having to create an ODBC connection on the individual
PC.

Any ideas?  Thanks.

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


Re: Literal Escaped Octets

2006-02-08 Thread Chason Hayes
On Wed, 08 Feb 2006 00:57:45 -0500, Steve Holden wrote:

> Chason Hayes wrote:
>> On Tue, 07 Feb 2006 01:58:00 +, Steve Holden wrote:
>> 
>> 
>>>Chason Hayes wrote:
>>>
On Mon, 06 Feb 2006 13:39:17 +, Steve Holden wrote:
>>>
>>>[...]
>>>
>The URL you reference is discussing how you represent arbitrary values 
>in string literals. If you already have the data in a Python string the 
>best advise is to use a parameterized query - that way your Python DB 
>API module will do the escaping for you!
>
>regards
> Steve


Thanks for the input. I tried that with a format string and a
dictionary, but I still received a database error indicating illegal
string values. This error went away completely when I used a test file
consisting only of text, but reproduced everytime with a true binary file.
If you can let me know where I am wrong or show me a code snippet with a
sql insert that contains a variable with raw binary data that works,
I would greatly appreciate it.

>>>
>>>I tried and my experience was exactly the same, which made me think less 
>>>of PostgreSQL.
>>>
>>>They don't seem to implement the SQL BLOB type properly, so it looks as 
>>>though that rebarbative syntax with all the backslashes is necessary. Sorry.
>>>
>>>regards
>>>  Steve
>> 
>> 
>> with regards to escaping data parameters I have found that I have to
>> specifically add quotes to my strings for them to be understood by
>> pstgresql. For example
>> 
>> ifs=open("binarydatafile","r")
>> binarydata=ifs.read()
>> stringdata=base64.encodestring(binarydata)
>> 
>> #does not work
>> cursor.execute("insert into binarytable values(%s)" % stringdata)
>> 
>> #need to do this first
>> newstringdata = "'" + stringdata + "'"
>> 
>> then the select statment works.
>> Is this expected behavior? Is there a better way of doing this?
>> 
>> thanks for any insight
> 
> Yes, parameterize your queries. I assume you are using psycopg or 
> something similar to create the database connection (i.e. I something 
> that expects the "%s" parameter style - there are other options, but we 
> needn't discuss them here).
> 
> The magic incantation you seek is:
> 
> cursor.execute("insert into binarytable values(%s)", (stringdata, ))
> 
> Note that here there are TWO arguments to the .execute() method. The 
> first is a parameterized SQL statement, and the second is a tuple of 
> data items, one for each parameter mark in the SQL.
> 
> Using this technique all necessary quoting (and even data conversion 
> with a good database module) is performed inside the database driver, 
> meaning  (among other things) that your program is no longer vulnerable 
> to the dreaded SQL injection errors.
> 
> This is the technique I was hoping would work with the bytea datatype, 
> but alas it doesn't. ISTM that PostgreSQL needs a bit of work there, 
> even though it is otherwise a very polished product.
> 
> regards
>   Steve

That was it. Thanks for your great help.

Chason

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


Re: Tkinter, X-windows and ebay

2006-02-08 Thread James Stroud
Bob Greschke wrote:
> When you post something on eBay (and other places) you can use a 'browse' 
> button on a web page to send a picture file from your hard drive to them for 
> inclusion in your listing.  Can the same kind of thing (not the same exact 
> thing, of course) be done with a Python/Tkinter program that is running on a 
> remote machine (that you logged into to start the program), but that's just 
> using your computer's display (with X11 on a Mac, X-whatever on Linux, 
> X-Win32 on Windows, etc.)?  I've got an inventory program that runs this way 
> and it would be nice if users could create a text file on their machine, but 
> then have the program read that file and, for example, update item 
> quantities according to information in that file.  Things like that.
> 
> Thanks!
> 
> Bob
> 
> 

I think xml-rpc was designed to address these kinds of issues:

http://www.pythonware.com/products/xmlrpc/

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


by reference

2006-02-08 Thread dirvine
I would like to create a dictionary based on a variable i.e read a
bunch of filenames and create a dict for each one called the filename
filename={}
to get the filenames I trraverse teh dirs woth os.path.walk or similar

Sorry I'm a bit new to python

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


Re: Problem with curses and UTF-8

2006-02-08 Thread Thomas Dickey
"Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
>> I'll test it if someone would dumb down "link with ncursesw instead of
>> ncurses" a little for me.
>> 
>> I tried:
>> ./configure --with-libs="ncursesw5"
>> 
>> and it failed saying:
>> checking size of wchar_t... configure: error: cannot compute sizeof
>> (wchar_t), 77

> If that was Python's configure: don't do that. Instead, hack setup.py

yes - python's configure script needs a lot of work
(alternatively, it is not the sort of script I would write).

> to make it change the compiler/linker settings, or even edit the
> compiler/linker line manually at first.

that works

-- 
Thomas E. Dickey
http://invisible-island.net
ftp://invisible-island.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ternary Operator Now?

2006-02-08 Thread Roy Smith
Steve Holden  <[EMAIL PROTECTED]> wrote:
>> x = y if C : else z
>> 
>
>Currently scheduled for next (2.5) release, but not yet implemented.

This still makes me barf.  Has Python jumped the shark?

It looks marginally better if you write it as:

x = (y if C else z)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: apostrophe or double quote?

2006-02-08 Thread Terry Hancock
On Wed, 8 Feb 2006 11:57:00 -0600
[EMAIL PROTECTED] wrote:
> Just to present a complete picture, not mentioned in this
> thread are triple-quoted strings:
> 
> 'abc' == '''abc''' == "abc" == """abc"""
> 
> Triple-quoted strings are no different than regular
> strings, though they do allow literal newlines to be
> embedded in the string.  Their presence is most often
> detected in doc strings precisely for this reason.

Also in the mode of beating a dead horse ... ;-)

Some people prefer to use single quotes for 'labels' (i.e. a
name which is meaningful to the program, but not to the
user), and reserve either double-quotes or
triple-double-quotes for text to be shown to the user. This
tends to make things slightly easier when you have to go
back and use gettext to internationalize your code.

But that's a matter of taste.

It is interesting to note, however, that the Python repr()
function prefers to use single quotes, using double quotes
only when a single quote is embedded in the string.

Cheers,
Terry


-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Pulling all n-sized combinations from a list

2006-02-08 Thread my . correo . basura
> Ah, this definitely seems to work!  It's a lot nicer in appearance than
> my previous code, that's for sure.  It actually runs in approximately
> the same amount of time though.

As a side note, this problem will always be "slow". The number of
combinations grows exponentially with n. No matter how fast you
generate a combination, generating them all it's going to take a lot of
time if n is slighty bigger.

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


Re: Ternary Operator Now?

2006-02-08 Thread Steve Holden
Ben Wilson wrote:
> I read somewhere else that Python was getting a ternary operator (e.g.
> x = (true/false) ? y : z). I read the PEP about it and that the PEP had
> been approved this past Fall. Has this been released into the wild yet?
> 
> IIRC, the operator is like:
> 
> x = y if C : else z
> 

Currently scheduled for next (2.5) release, but not yet implemented.

There's no colon in the construct.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Ternary Operator Now?

2006-02-08 Thread Xavier Morel
Ben Wilson wrote:
> I read somewhere else that Python was getting a ternary operator (e.g.
> x = (true/false) ? y : z). I read the PEP about it and that the PEP had
> been approved this past Fall. Has this been released into the wild yet?
> 
> IIRC, the operator is like:
> 
> x = y if C : else z
> 
PEP 308 "Conditional Expressions" has been accepted for Python 2.5, I'm 
pretty sure implementation hasn't even started yet.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: jump into the interpreter in a script

2006-02-08 Thread Rick Ratzel
pdb might help.  Add this to your code:

import pdb
pdb.set_trace()

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


Re: UnboundMethodType and MethodType

2006-02-08 Thread Kirk McDonald
Scott David Daniels wrote:
> To elaborate on this, once 'id' is called, you drop the reference.
> This allows quite surprising things like:
>  >>> id(7**8) == id(8**7)
> True
>  >>> a, b = 7**8, 8**7
>  >>> id(a) == id(b) # this time there are other references to a and b
> False
> 
> If you wanted to test the original code for identity match:
>  >>> B.bar is B().bar
> False
> is the appropriate test (the 'is' test holds the identities through
> the comparison).
> 
> By the by, this is tricky stuff, nobody should expect to understand
> it thoroughly without both study and testing.
> 
> --Scott David Daniels
> [EMAIL PROTECTED]

You know what? That makes perfect sense. Thank you.

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


Re: Python 2.4.2 using msvcrt71.dll on Win and compatibility issues

2006-02-08 Thread Christoph Zwerschke
Martin v. Löwis wrote:
> Christoph Zwerschke wrote:
>> I think this would only shift the problem. Because then I would have to
>> convert the msvcr71 stream I get from Python to a msvcrt stream. Using
>> fileno() (of msvcrt) to get the file descriptor will probably not work.
> 
> It actually would:
> 
> #define _fileno(_stream)  ((_stream)->_file)
> 
> This definition is the same in all CRT version, plus the _file member
> is at the same offset in all CRT versions. Microsoft apparently wants
> to support linkage of object files build with one CRT version against
> a different CRT version.
> 
> It *is* hacky, of course.

I see. So this approach could actually work. Thanks for the hint.

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


Re: Pulling all n-sized combinations from a list

2006-02-08 Thread Swroteb

Paul Rubin wrote:
> I think the natural approach is to make a generator that yields a
> 5-tuple for each combination, and then have your application iterate
> over that generator.  Here's my version:
>
> def comb(x,n):
> """Generate combinations of n items from list x"""
> if n==0:
> yield []
> return
> for i in xrange(len(x)-n+1):
> for r in comb(x[i+1:], n-1):
> yield [x[i]] + r
>
> for c in comb([1,2,3,4,5], 3):
> print c
>
> The output is:
> >>>
> [1, 2, 3]
> [1, 2, 4]
> [1, 2, 5]
> [1, 3, 4]
> [1, 3, 5]
> [1, 4, 5]
> [2, 3, 4]
> [2, 3, 5]
> [2, 4, 5]
> [3, 4, 5]
> >>>

Ah, this definitely seems to work!  It's a lot nicer in appearance than
my previous code, that's for sure.  It actually runs in approximately
the same amount of time though.  So, using your comb method, I have the
following code now:

myCombinations = comb(myList, 5)
for a, b, c, d, e in myCombinations:
# my code

myList is 48 elements in size, so I'm going to get 1712304
combinations.  From what I can tell, my speed problems aren't in the
list generation anymore.

Thanks for the assistance, Paul!  I appreciate it.  :)

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


jump into the interpreter in a script

2006-02-08 Thread Brian Blais
Hello,

I was wondering if there is a way to, within a script, jump into the 
interpreter.
What I mean is something like the "keyboard" command in Matlab, where the script
pauses and you get an interpreter prompt, where you can look at variables, 
change
their values, etc.  then when you exit the interpreter, the script continues 
from
where it left off.  Is this possible in python?


thanks,

Brian Blais


-- 
-

 [EMAIL PROTECTED]
 http://web.bryant.edu/~bblais

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


Re: breadth first search

2006-02-08 Thread Charles Krug
On 2006-02-08, News <[EMAIL PROTECTED]> wrote:
> I am new in using Python
>
> Anyone know how to implement breadth first search using Python?  Can Python
> create list dynamically, I want to implement a program which will read data
> from a file and store each line into a list, is this possible?
>
> Please send mail to me at [EMAIL PROTECTED] or reply this mail
>
> Thanks a lot!
>

Yes.  List has methods that support a stack, in case you find it useful
in this context.

Yes.  List has methods that allow dynamic creation, such as might be
useful when implementing a stack, in case you find it useful in this
context.

And Yes.  File has methods that will populate a list from a file.
Examples are in the tutorials.

You're welcome.

You can find numerous examples of the breadth-first algorithm on the
web.  You can then take the individual steps and translate them into
Python.  You'll likely find one or two sticking points, but the
implementation is straightforward from pseudocode or from a GOOD
statement of the algorithm.

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


RE: module with __call__ defined is not callable?

2006-02-08 Thread Delaney, Timothy (Tim)
Steven D'Aprano wrote:

> That's not a _reason_, it is just a (re-)statement of fact. We know
> that defining a __call__ method on a module doesn't make it callable.
> Why not? The answer isn't "because defining a __call__ method on a
> module or an instance doesn't make it callable", that's just avoiding
> the question. 

My reading of the OP sounded like he wanted to know the *technical*
reason for why it doesn't work - which is what I provided.

If you can come up with a convincing argument, after re-reading the OP
(as I've just done), that that is *not* what he meant, I'm all ears.

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


Re: Pulling all n-sized combinations from a list

2006-02-08 Thread Paul Rubin
"Swroteb" <[EMAIL PROTECTED]> writes:
> I'm a little bit confused about your generator suggestion.  My list is
> a set of references to instantiated objects.  I'm just unsure about how
> to iterate through every unique combination of those references.  Are
> you suggesting that I set up methods to provide the indices I'm looking
> for in the list to iterate over?

I think the natural approach is to make a generator that yields a
5-tuple for each combination, and then have your application iterate
over that generator.  Here's my version:

def comb(x,n):
"""Generate combinations of n items from list x"""
if n==0:
yield []
return
for i in xrange(len(x)-n+1):
for r in comb(x[i+1:], n-1):
yield [x[i]] + r

for c in comb([1,2,3,4,5], 3):
print c

The output is:
>>>
[1, 2, 3]
[1, 2, 4]
[1, 2, 5]
[1, 3, 4]
[1, 3, 5]
[1, 4, 5]
[2, 3, 4]
[2, 3, 5]
[2, 4, 5]
[3, 4, 5]
>>> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Ternary Operator Now?

2006-02-08 Thread Ben Wilson
I read somewhere else that Python was getting a ternary operator (e.g.
x = (true/false) ? y : z). I read the PEP about it and that the PEP had
been approved this past Fall. Has this been released into the wild yet?

IIRC, the operator is like:

x = y if C : else z

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


Re: Another try at Python's selfishness

2006-02-08 Thread Charles Krug
On 2006-02-08, Ben Wilson <[EMAIL PROTECTED]> wrote:
> "But the point is, the current situation is not newbie-friendly (I can
> tell, I am a newbie)"
>
> I will agree to that, as I consider myself still new. _But_, it's a
> stumbling stone only briefly. Get enough nagging error messages, and
> you learn and move on. I agree with the grandparent poster that it is a
> perfect self-documenting thing, as the use of 'self' is pretty obvious.
> For a language that one can learn in a short time, this is a tempest in
> a teacup.
>

This old C hound finds it much more sensible than C++ or Java, where the
"self" parameter (called "this") is implicit rather than explicit and
you just sorta kinda hafta "know" it's there and the correct syntax to
use to reference it.

Then there's all the places where you need a Secret Decoder Ring--in
Java you have to define the equivalents of stdout and stdin as they
aren't provided.  In c++ you can't overload the << operator in your
class, you have to use a "friend" function and you have to return an
ostream--the "Rule of Three" for constructors, and just generally lots
of small knotty issues to bite beginners.

9 times out of 10, Python "Just Works" the first time and things do what
your mind says they "should" without having to learn a seventeen special
cases to everything.

IMO, YMMV, Not Valid in Vermont, Happy Fun Ball may accellerate to
dangerous speeds.  Do NOT taunt Happy Fun Ball.


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


Re: Problem with curses and UTF-8

2006-02-08 Thread Ian Ward
Martin v. Löwis wrote:

> If that was Python's configure: don't do that. Instead, hack setup.py
> to make it change the compiler/linker settings, or even edit the
> compiler/linker line manually at first.

Ok, that compiled.

Now when I run the same test:

import curses
s = curses.initscr()
s.addstr('\xc3\x85 U+00C5 LATIN CAPITAL LETTER A WITH RING ABOVE\n')
s.addstr('\xc3\xa5 U+00F5 LATIN SMALL LETTER O WITH TILDE')
s.refresh()
s.getstr()
curses.endwin()


This is what I see:

  +00C5 LATIN CAPITAL LETTER A WITH RING ABOVE
  +00F5 LATIN SMALL LETTER O WITH TILDE


so, the UTF-8 characters didn't appear and the " U" at the beginning 
became just " ".

Ian Ward

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


Re: Xah's Edu Corner: Unix damage: color names

2006-02-08 Thread William James

[EMAIL PROTECTED] wrote:

> On AIX and Linux (SuSE 9.3) each color name which contains "gray" is
> also aliased as "grey" for the benefit of both Yanks and Brits.  Thus,

Yankee, n.  In Europe, an American. In the Northern States of
our Union, a New Englander. In the Southern States the word is
unknown. (See  DAMYANK.)

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


Re: What editor shall I use?

2006-02-08 Thread Benji York
Dylan Moreland wrote:
> I myself have just begun using vim. Does anyone have any
> tips/convenient tweaks for python programming with it?

EnhancedCommentify, ShowFunc, spacehi, svncommand, and pythonhelper are 
nice Vim plugins to use with Python.  They can all be found on vim.org.

Not Python-specific, but I highly recommend Steve Oualline's Vim book 
(http://www.amazon.com/gp/product/0735710015).
--
Benji York
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What editor shall I use?

2006-02-08 Thread Tim Chase
> I myself have just begun using vim. Does anyone have any
> tips/convenient tweaks for python programming with it?

For python programming several settings can make life far less 
painful (assuming you like 4-spaces-per-tab) :

set ai ts=4 sw=4 et

or

set ai ts=4 sw=4 noet

(depending on whether you prefer tabs or spaces...just be consistent)

Setting 'ai' puts vim in "autoindent" mode.

Setting 'ts' sets how many spaces are considered an a tab

Setting 'sw' sets how many spaces-worth a shift does

Setting 'et' sets the 'expandtab' property.  When set, it expands 
typed tabs as spaces.  When unset ('noexpandtab'), tabs aren't 
touched.

You might also search the "scripts" or "tips" section of 
www.vim.org for "python" and see what sorts of scripts, tips, and 
plugins are available to supercharge your python-coding in vim.

http://www.vim.org/search.php

Additionally, the vim mailing list is one of the best I've been 
on--regularly on-topic, with friendly folk, accurate answers, 
fairly fast replies, and some great minds to tap.

http://www.vim.org/community.php

-tkc






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


Re: What editor shall I use?

2006-02-08 Thread Dylan Moreland

Radek Kubicek wrote:
> > What editor shall I use if my Python script must contain utf-8
> > characters?
> > I use XP
>
> vim :-)
>
> > Thank you for reply
> > l.b.
>
> not for all :-)

I myself have just begun using vim. Does anyone have any
tips/convenient tweaks for python programming with it?

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


Re: What editor shall I use?

2006-02-08 Thread [EMAIL PROTECTED]
I use JEdit and I like it very much.

http://www.jedit.org/

Uros

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


Re: Pulling all n-sized combinations from a list

2006-02-08 Thread Swroteb

Paul Rubin wrote:
> "Swroteb" <[EMAIL PROTECTED]> writes:
> > Atrocious and slow, I'm sure, but is there a better way?  I can't
> > simply create a list with the combinations I want, since it won't fit
> > into memory.  And I'm sure I can do it using a standard paradigm using
> > five indexed for loops (ie, for i = 1, for j = i+1, for k = j+1, etc.).
> >  But is there a really nice way to handle this in Python?
>
> Is this a homework problem?  Hint: 1) use recursion; 2) use generators.

I appreciate the response; no, this is not a homework problem.

I'm a little bit confused about your generator suggestion.  My list is
a set of references to instantiated objects.  I'm just unsure about how
to iterate through every unique combination of those references.  Are
you suggesting that I set up methods to provide the indices I'm looking
for in the list to iterate over?

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


Avoiding FTP server timeout for files based on sockets (long posting)

2006-02-08 Thread Stefan Schwarzer
Hi all!

For my FTP library module ftputil [1], some users have asked
for a way to avoid server timeouts (FTP status code 421). But I
haven't found out yet how I can do this in all cases.

I try to explain the problem in more detail. The following is
rather special and probably not so easy to understand, but I'll
do my best. Please ask if you need more information.

ftputil has an FTPHost class (defined in [2]), which can be
instantiated like

# very similar to ftplib.FTP
host = ftputil.FTPHost(ftphost, user, password)

You can use an FTPHost instance to get file(-like) objects from it:

read_from_this_file = host.file("remote_file", "r")
write_to_this_file = host.file("another_remote_file", "wb")

In the background, each call of the FTPHost.file method opens
another connection to the FTP server by using the login data from
the FTPHost instantiation. The return value of each call is a
_FTPFile object (defined in [3]) which wraps a file object
returned by socket.makefile.

My current FTPHost.keep_alive is roughly defined as

# in FTPHost
def keep_alive(self):
# just prevent loss of the connection, so discard the result
self.getcwd()
# refresh also connections of associated file-like objects
for host in self._children:
# host._file is an _FTPFile object (see [3])
host._file.keep_alive()

whereas in _FTPFile it's

# in _FTPFile
def keep_alive(self):
if self._readmode:
# read delegates to the file made from the data transfer
# socket, made with socket.makefile (see [4])
self.read(0)
else:
# write delegates to the file made from the data transfer
# socket, made with socket.makefile (see [4])
self.write("")
self.flush()

In fact, the read method call above on the data transfer channel
keeps the connection open but the call to the write method can't
avoid a timeout from the FTP server (however, I notice this only
when I call _FTPFile.close(), so it seems that no data is sent
until the _FTPFile.close call).

An approach which seems feasible at first is to call pwd() on the
FTP session (an ftplib.FTP class) on which the _FTPFile builds
(similar to the FTPHost.getcwd() call above). Unfortunately, this
doesn't work because as soon as the file is opened, a STOR
command has been sent to the FTP server and it seems I can't send
another FTP command until the data transfer is finished (by calling
_FTPFile.close; see _FTPFile._open in [3] for details of making
the connection).

So to re-phrase my question: How can I keep the connection - for
writing of remote files - from being closed by the FTP server
without requiring the user of the ftputil library to explicitly
send data with _FTPFile.write?

Stefan

[1] http://ftputil.sschwarzer.net/
[2] http://ftputil.sschwarzer.net/trac/browser/trunk/ftputil.py
[3] http://ftputil.sschwarzer.net/trac/browser/trunk/ftp_file.py
[4] http://docs.python.org/lib/socket-objects.html#l2h-2660
-- 
http://mail.python.org/mailman/listinfo/python-list


Circe released to public domain!

2006-02-08 Thread Kyle Brooks
Wednesday, February 8th, 2006.

Dear all,

I hereby release Circe to the public domain.

Our repo is at http://kbrooks.ath.cx/repos/circe.

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


Re: Number Format function

2006-02-08 Thread Rick Zantow
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> wrote in 
news:[EMAIL PROTECTED]:

> def number_format(num, places=0):
> """Format a number according to locality and given places"""
> locale.setlocale(locale.LC_ALL, "")
> return locale.format("%.*f", (places, num), True)
> 

There are some edge cases in the format conversion that could present 
some issues. For example:

>>> print number_format( 2312753.4450, 2 )
2,312,753.44
>>> print number_format( 2312753.4451, 2 )
2,312,753.45

I would expect the first to produce the same results as the second, but, 
I suppose because of one of floating point's features, it doesn't work 
that way.

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


spell check code

2006-02-08 Thread rtilley
What is the most common way to spell check comments in code? Are there 
any idle plugins or modules that do this?

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


Re: os.walk() dirs and files

2006-02-08 Thread rtilley
George Sakkis wrote:

> Or a bit more efficiently (no need to allocate a new list for storing
> files+dirs):
> 
> from itertools import chain
> for root, dirs, files in os.walk(path):
>   for fs_object in chain(files,dirs):
>   ADD fs_object to dictionary

I like that! itertools is cool... a bit abstract and computer sciencey, 
but it sure does work in a practical manner :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pulling all n-sized combinations from a list

2006-02-08 Thread Paul Rubin
"Swroteb" <[EMAIL PROTECTED]> writes:
> Atrocious and slow, I'm sure, but is there a better way?  I can't
> simply create a list with the combinations I want, since it won't fit
> into memory.  And I'm sure I can do it using a standard paradigm using
> five indexed for loops (ie, for i = 1, for j = i+1, for k = j+1, etc.).
>  But is there a really nice way to handle this in Python?

Is this a homework problem?  Hint: 1) use recursion; 2) use generators.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.path and unicode folder names

2006-02-08 Thread Martin v. Löwis
Nir Aides wrote:
> Actually, I already managed to make a Patch for this problem.
> I will post it soon on my website and in this group.
> 
> But I find it strange that this problem even exists, and that I could
> not find any workarounds on the Internet.

Very few people use file names not in their respective CP_ACP (why
do you need such filenames?), and virtually nobody wants to put such
a file name on Python's sys.path (why do you want to? - just rename
the directory and be done).

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


Re: Problem with curses and UTF-8

2006-02-08 Thread Martin v. Löwis
> I'll test it if someone would dumb down "link with ncursesw instead of
> ncurses" a little for me.
> 
> I tried:
> ./configure --with-libs="ncursesw5"
> 
> and it failed saying:
> checking size of wchar_t... configure: error: cannot compute sizeof
> (wchar_t), 77

If that was Python's configure: don't do that. Instead, hack setup.py
to make it change the compiler/linker settings, or even edit the
compiler/linker line manually at first.

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


Re: Number Format function

2006-02-08 Thread [EMAIL PROTECTED]
This is a little faster:

def number_format(num, places=0):
"""Format a number according to locality and given places"""
locale.setlocale(locale.LC_ALL, "")
return locale.format("%.*f", (places, num), True)

I tested this ok with my test

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


Re: Question about idioms for clearing a list

2006-02-08 Thread Bryan Olson
Magnus Lycka wrote:
> Ed Singleton wrote:
> 
>> The point is that having to use del to clear a list appears to the
>> inexperienced as being an odd shaped brick when they've already used
>> the .clear() brick in other places.
> 
> 
> Agreed. The smart way to go from this stage of surprise is
> not to assume that Python is broken, but to try to understand
> how lists are different from e.g. dicts, and why the so-much-
> smarter-than-me Python designers made it like this.

That two of Python's three built-in mutable collections support
clear() is clearly a historical artifact.

> Not that Python is perfect, but when you don't get a
> "sorry, this change would break existing code, won't happen
> until Python 3.0"-resonse, but a "study this more"-response,
> the smart thing is to open your mind and try to fully grok
> this.

The original question was about idioms and understanding, but
there's more to the case for list.clear. Python is "duck typed".
Consistency is the key to polymorphism: type X will work as an
actual parameter if and only if X has the required methods and
they do the expected things.

Emptying out a collection is logically the same thing whether
that collection is a list, set, dictionary, or user-defined
SortedBag. When different types can support the same operation,
they should also support the same interface. That's what
enables polymorphism.


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


Re: What editor shall I use?

2006-02-08 Thread Steve Holden
Petr Jakes wrote:
> http://www.pspad.com/en/
> 
> Petr Jakes
> 
Windows provides the perfectly usable Notepad which, while not perfect 
for Python, is quite good enough to get started.

The Save dialog box allows the user to select an encoding, including UTF-8.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: module with __call__ defined is not callable?

2006-02-08 Thread Steve Holden
Antoon Pardon wrote:
> Op 2006-02-08, Steve Holden schreef <[EMAIL PROTECTED]>:
> 
>>Why should a module be callable? What's the advantage? Should we be able 
>>to add two modules together, yielding a module that contains all the 
>>code of both modules? What happens if I multiply a module by two - 
>>presumably the result should be the same as adding a module to itself? 
>>Perhaps we should be able to divide a module by a function?
>>
>>The pursuit of orthogonality, while admirable, can lead to insanity if 
>>pushed too far.
> 
> 
> This is not an argument. This doesn't give a clue about where to stop
> this pursuit en when to go on.
> 
Well, let's say we should stop short of unsane behavior. That's a phrase 
you should understand.

> Whether it is usefull to call modules add them or multiply them by two
> is up to the person producing the code. That is no different than when
> he decides it is usefull to call certain objects, add them or multiply
> them by two.
> 
> I can understand there are implemenation details that make it not
> worth while to implement this. But otherwise I would think it
> a bad reason to give up orthogonality just because one can't imagine
> what it could be usefull for.
> 
Fine. Off you go, then.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


still a valid book?

2006-02-08 Thread John Salerno
Hi everyone. I have Learning Python 2nd edition (O'Reilly) and I noticed 
that Wrox has a newer book out (Beginning Python) that covers version 
2.4. Do you think that Learning Python is still a good enough book to be 
an intro to the language? Is there anything so different about 2.4 from 
2.3 that it will mess me up to start with LP?

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


Pulling all n-sized combinations from a list

2006-02-08 Thread Swroteb
Hi there,

I've got a reasonably sized list of objects that I'd like to pull out
all combinations of five elements from.  Right now I have a way to do
this that's quite slow, but manageable.  I know there must be a better
way to do this, but I'm not sure what it is.  Here's what I've got so
far:

for a in myList:
for b in myList:
if a == b:
break
for c in myList:
if b == c:
break
for d in myList:
if c == d:
break
for e in myList:
if d == e:
break
# my code here.

Atrocious and slow, I'm sure, but is there a better way?  I can't
simply create a list with the combinations I want, since it won't fit
into memory.  And I'm sure I can do it using a standard paradigm using
five indexed for loops (ie, for i = 1, for j = i+1, for k = j+1, etc.).
 But is there a really nice way to handle this in Python?

Thanks for your time!
Scott

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


Re: Unable to get PIL to load jpeg images

2006-02-08 Thread Andrew Gwozdziewycz
On 2/7/06, Steve Holden <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > Someone out there must surely know - please!
> >
> > Peter
> >

Try building the PIL from scratch. It might give you some insight as
to which library it exactly is looking for. I can remember when
compiling the PIL on my mac having to create a symbolic link to
libjpeg.so.6 or something. It was bizarre but worked fine afterwards.

--
Andrew Gwozdziewycz <[EMAIL PROTECTED]>
http://ihadagreatview.org
http://plasticandroid.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.path and unicode folder names

2006-02-08 Thread Nir Aides
Actually, I already managed to make a Patch for this problem.
I will post it soon on my website and in this group.

But I find it strange that this problem even exists, and that I could 
not find any workarounds on the Internet.

Nir


Martin v. Löwis wrote:
> Nir Aides wrote:
>> I can not restrict the name to CP_ACP.
>> I am interested in the general case of Unicode.
> 
> So you should implement a patch, and contribute this
> to sf.net/projects/python.
> 
> Regards,
> Martin
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Number Format function

2006-02-08 Thread Edward Hartfield
Thanks.  I noticed the bugs later.  But after talking with my boss, he 
suggested something more elegant (again *untested*, yet):


import locale

def number_format(num, places=0)
   """Format a number according to locality and given places"""
   locale.setlocale(locale.LC_ALL, locale.getdefaultlocale()[0])
   return locale.format("%.*f", (places, num), 1)

[EMAIL PROTECTED] wrote:

Your code has a little bug, I highly recommend to add a test to your
code, for an idea see below - I fixed your code as well.

#!/usr/bin/env python
import math

def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal
places"""
#is_negative = (num < 0)
#if is_negative:
#num = -num

places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[:point]
decimal = (point != -1) and tmp[point:] or ""

count = commas = 0
formatted = []
for i in range(len(integer) - 1, 0, -1):
count += 1
formatted.append(integer[i])
if count % 3 == 0:
formatted.append(",")
formatted.append(integer[0]) # this misses in your part
integer = "".join(formatted[::-1])
return integer+decimal


#
# add something like this: it helps to prevent you break your code
#
import unittest

class test_number_format(unittest.TestCase):
def test(self):
self.assertEqual(number_format(100, 2), '1,000,000.00')
self.assertEqual(number_format(10, 2), '100,000.00')
self.assertEqual(number_format(100, 2), '100.00')
self.assertEqual(number_format(100.33, 2), '1,000,000.33')
self.assertEqual(number_format(100.333, 2), '1,000,000.33')
self.assertEqual(number_format(100.3, 2), '1,000,000.30')
self.assertEqual(number_format(123456, 2), '123,456.00')
self.assertEqual(number_format(12345, 2), '12,345.00')
self.assertEqual(number_format(123, 2), '123.00')
self.assertEqual(number_format(123456.33, 2), '123,456.33')
self.assertEqual(number_format(12345.333, 2), '12,345.33')
self.assertEqual(number_format(123.3, 2), '123.30')

suite = unittest.makeSuite(test_number_format)
unittest.TextTestRunner(verbosity=2).run(suite)

  
begin:vcard
fn:Edward Hartfield
n:Hartfield;Edward
org:BungeeCraft Technologies
adr;dom:;;4824 W Medford Avenue;Milwaukee;Wisconsin;53216
email;internet:[EMAIL PROTECTED]
title:President
tel;work:414 839-2387
tel;fax:414 449-9105
note:Milwaukee-based BungeeCraft Technologies provides cost-effective technology solutions for small and mid-sized businesses. From aligning our clients' business and IT strategies to improving business processes and deploying and supporting solutions that accelerate business results, we are able and ready to provide YOU with comprehensive information technology solutions and services.
x-mozilla-html:FALSE
url:http://www.bungeecraft.com
version:2.1
end:vcard

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

Re: breadth first search

2006-02-08 Thread Tim Chase
> Thanks for your reply and the structure of the file structure going to be
> read is
> 
> 
> 
> ...
> 
> 
> The aims is to find out the shortest path(s) for the leaf node(s)
> 
> Example:
> 9
> 0 1 1
> 0 4 2
> 1 2 3
> 1 3 4
> 4 3 2
> 4 5 1
> 4 8 2
> 5 6 2
> 5 7 2
> -1
> 
> Output:
> Possible solutions:
> Path=0,1,2 length=4
> Path=0,4,3 length=4

Well, I notice several items here:

1)  the number of records is obvious, as you have newlines
2)  the end-of-file is obvious to Python
3)  you don't explicitly spell out which nodes are availble 
leaf-nodes

To build a tree like your data provides, you might have some code 
like

data = open("data.txt","r")
lines = [line[:-1] for line in data.readlines()[1:-1]]
data.close()
graph = {}
for line in lines:
 a,b,weight = line.split(" ",2)
 weight = int(weight)
 if a in graph:
 graph[a][b] =(weight)
 else:
 graph[a] = {b:weight}

print repr(graph)

You can then navigate this graph/tree.  Starting at the root node:

root = graph("0")

root now contains a dictionary.  The keys in this dictionary 
specify which nodes can be reached from the current location, and 
the values of the dictionary represent the weight/cost associated 
with traversing to this node.

You can then do a breadth-first search of this data structure 
just as you would in any other language.  It doesn't look like it 
would be a straight-forward breadth-first search, as it looks 
like you want to take the weight into account as well as the 
number of steps from the root.

-tkc

PS:  you should CC the list when you reply, as I certainly don't 
have all the answers, and there are others on the mailing list 
that can point out better ways to do things, have other ideas, or 
be there more predictable than I am (otherwise, you may mail 
something and I might not get it for a week)







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


Re: Number Format function

2006-02-08 Thread [EMAIL PROTECTED]
Your code has a little bug, I highly recommend to add a test to your
code, for an idea see below - I fixed your code as well.

#!/usr/bin/env python
import math

def number_format(num, places=0):
"""Format a number with grouped thousands and given decimal
places"""
#is_negative = (num < 0)
#if is_negative:
#num = -num

places = max(0,places)
tmp = "%.*f" % (places, num)
point = tmp.find(".")
integer = (point == -1) and tmp or tmp[:point]
decimal = (point != -1) and tmp[point:] or ""

count = commas = 0
formatted = []
for i in range(len(integer) - 1, 0, -1):
count += 1
formatted.append(integer[i])
if count % 3 == 0:
formatted.append(",")
formatted.append(integer[0]) # this misses in your part
integer = "".join(formatted[::-1])
return integer+decimal


#
# add something like this: it helps to prevent you break your code
#
import unittest

class test_number_format(unittest.TestCase):
def test(self):
self.assertEqual(number_format(100, 2), '1,000,000.00')
self.assertEqual(number_format(10, 2), '100,000.00')
self.assertEqual(number_format(100, 2), '100.00')
self.assertEqual(number_format(100.33, 2), '1,000,000.33')
self.assertEqual(number_format(100.333, 2), '1,000,000.33')
self.assertEqual(number_format(100.3, 2), '1,000,000.30')
self.assertEqual(number_format(123456, 2), '123,456.00')
self.assertEqual(number_format(12345, 2), '12,345.00')
self.assertEqual(number_format(123, 2), '123.00')
self.assertEqual(number_format(123456.33, 2), '123,456.33')
self.assertEqual(number_format(12345.333, 2), '12,345.33')
self.assertEqual(number_format(123.3, 2), '123.30')

suite = unittest.makeSuite(test_number_format)
unittest.TextTestRunner(verbosity=2).run(suite)

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


Re: Too Many if Statements?

2006-02-08 Thread Paul Rubin
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> SystemError: com_backpatch: offset too large

Yeah, that sounds like there's some 16-bit fields in the bytecode format.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python and the health of the public

2006-02-08 Thread Tim Churches
The use of Python in a public health surveillance system is described
here (see references 15 and 26):
http://www.biomedcentral.com/1471-2458/5/141

Some more papers describing Python's starring role in some other public
health projects should appear in the next several months.

Tim C



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


Re: Replacing curses (Was: Re: Problem with curses and UTF-8)

2006-02-08 Thread Ian Ward
Grant Edwards wrote:
> Depending on what you're tring to do, slang might be an option,

I've looked at newt and snack, but all I really need is:
- a way to position the cursor at (0,0)
- a way to hide and show the cursor
- a way to detect when the terminal is resized
- a way to query the terminal size

Ian Ward


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


Re: Too Many if Statements?

2006-02-08 Thread [EMAIL PROTECTED]

> > I made a script with 100,000 if's, (code below) and it appears
> > to work on a couple systems, including Python 2.4.2 on Win32-XP.
> > So at first cut, it doesn't seem to be just the if-count that
> > triggers the bug.
>
> I tried that code. It runs fine.
>
> However, the following gives a SystemError with only 2500 elif's.
>
>...
>
> I tried this with Python 2.3.3 and 2.3.4 (Linux) and both fail.

Just tried it with 2.4.2 On FreeBSD 6.0 and I get the same result:

Traceback (most recent call last):
  File "buggyif.py", line 10, in ?
exec prog 
SystemError: com_backpatch: offset too large

Curtis

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


Re: A __getattr__ for class methods?

2006-02-08 Thread Xavier Morel
Oh, and I wondered too: is your goal to build an ORM, or do you just 
need an ORM?

Cause if it's the latter then Python does already have some fairly good 
ORMs such as SQLAlchemy or PyDO2, you don't *need* to create yours.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with curses and UTF-8

2006-02-08 Thread Martin v. Löwis
Thomas Dickey wrote:
> no need for debugging - it's a well-known problem.  UTF-8 uses more than
> one byte per cell, normal curses uses one byte per cell.  To handle UTF-8,
> you need ncursesw.

I tried that, but it didn't improve anything.

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


Re: email questions

2006-02-08 Thread Scott Frankel

Yes, I was doing something wrong:  I was connecting to the localhost  
after instantiation.  All better now.

Thanks for the tips!
Scott



On Feb 8, 2006, at 11:04 AM, Carsten Haese wrote:

>
> Then you're doing something wrong. The line
>
> s = smtplib.SMTP("mail.ispname.net") instantiates an SMTP instance and
> connects it. Are you doing s.connect() afterwards? If yes, don't do
> that, it'll try to connect to the local host, which is not an smtp
> server.
>
> If you want to separate instantiation and connection, do this:
>
> s = smtplib.SMTP()
> s.connect("mail.ispname.net")
>
> -Carsten
>
>

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


Re: Python 2.4.2 using msvcrt71.dll on Win and compatibility issues

2006-02-08 Thread Ross Ridge

Martin v. Löwis wrote:
> In general, the only Microsoft-supported strategy is that you
> must use only a single msvcrt in the entire application. So
> either recompile PostGres, or recompile Python.

If you want a compiled version of Python that already uses
MSVCRT then you try using pyMingGW:

http://jove.prohosting.com/iwave/ipython/pyMinGW.html

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


Re: Dual Core outlook

2006-02-08 Thread malv
Hi All,
Thank you for your commentaries.
In the meantime, I read up in Python-Dev and came across a post by
Johnatan LaCour which kind of nicely sums up the state of affairs:
"Its really a shame.  There seems to be some consensus about
multi-processing, but not a whole lot of interest in making it easier
out of the box.  When it comes to multi-processing, batteries really
_aren't_ included.  Sure, you have lead dioxide and some sulphuric
acid, but you have to put them together to make your battery.  This
isn't the end of the world, but I find it tedious, and I am sure it
confuses and frustrates people new to Python."
Possibly things are not much brighter for other languages.

I'll keep on trying
malv

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


Re: Python 2.4.2 using msvcrt71.dll on Win and compatibility issues

2006-02-08 Thread Martin v. Löwis
Christoph Zwerschke wrote:
> I think this would only shift the problem. Because then I would have to
> convert the msvcr71 stream I get from Python to a msvcrt stream. Using
> fileno() (of msvcrt) to get the file descriptor will probably not work.

It actually would:

#define _fileno(_stream)  ((_stream)->_file)

This definition is the same in all CRT version, plus the _file member
is at the same offset in all CRT versions. Microsoft apparently wants
to support linkage of object files build with one CRT version against
a different CRT version.

It *is* hacky, of course.

> But thanks a lot for your help. Sometimes you don't know whether you're
> doing something terribly wrong or missing a very easy solution if you
> don't discuss with others.

Right. I come more and more to the conclusion that you shouldn't really
be using the CRT on Win32.

Anyway, I just proposed to have Python 2.5 link against msvcrt.dll
on python-dev, and got mixed responses.

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


Re: Question about idioms for clearing a list

2006-02-08 Thread Terry Reedy

"Magnus Lycka" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Statements and operators are really fundamental in Python. We
> don't support n = 1.add(2), since we have the '+' operator.

Actually, since the 2.2 union of type and new-style classes, which gave 
attributes to all types 

>>> 1 .__add__(2)  # note space after 1
3
>>> 1.__add__(2)  # ambiguous, interpreter won't guess
SyntaxError: invalid syntax
>>> 1..__add__(2.)
3.0

I only see this as useful for making bound methods:

>>> inc = 1 .__add__
>>> inc(2)
3
>>> dub = 2 .__mul__
>>> dub(2)
4

which is certainly nicer than the older method of writing a 'makeoper' 
function that returned a nested function with either a default param or a 
closure.

Terry Jan Reedy



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


Re: A __getattr__ for class methods?

2006-02-08 Thread Xavier Morel
Dylan Moreland wrote:
> I'm trying to implement a bunch of class methods in an ORM object in
> order to provide functionality similar to Rails' ActiveRecord. This
> means that if I have an SQL table mapped to the class "Person" with
> columns name, city, and email, I can have class methods such as:
> 
> Person.find_by_name
> Person.find_by_city_and_name
> Person.find_by_name_and_city_and_email
> 
> I have a metaclass generating basic properties such as .name and .city,
> but I don't want to generate a class method for every permutation of
> the attributes. I'd like to have something much like __getattr__ for
> instance attributes, so that if a method like
> Person.find_by_city_and_email cannot be found, I can construct a call
> to the basic find method that hides the SQL. Is there any way of doing
> this, or am I trying to mirror a functionality that Python simply does
> not have?
> 
I'm not sure that the way you tackled this is the good approach: while 
it's quite flexible as far as the search criteria go, it'll require less 
than obvious code to match keywords (field names) and values, will lead 
to somewhat verbose syntax (especially with many criteria), and the 
syntax itself is unforgiving (every new search field requires at least 5 
additional characters on top of the field name itself), brittle (you'll 
have to do an extensive validation of your method name and fields unless 
you want everything to break, and Python doesn't support your syntax) 
and not really pythonic.

Since you seem to know ActiveRecord, you're probably familiar with the 
way AR does this task: with a hash of column_name, value pairs. The 
syntax is quite straightforward especially due to the fact that any "key 
=> value" comma-separated pairs sequence generates a hash, without 
requiring explicit hash boundaries ( { and } ). The syntax is extremely 
straightforward since it relies on the language's syntax itself, and the 
correctness of the grammar is checked by the compiler/interpreter itself 
since no custom syntax is built. This construct is therefore quite 
solid, on top of being obvious to a Rubyist.

Now, you're in luck, because Python has even better than that: **kwargs, 
the optional keyword arguments.

As you probably know, Python has a good support for keyword args, 
allowing you to fill your arguments out of order (and leave the 3th 
argument at it's default value while specifying the value of the 5th 
argument). But **kwargs goes beyond the regular explicit keyword 
arguments: when specified, **kwargs is a dict populated with the 
implicit keyword arguments (keyword:value pairs), the ones you haven't 
specified in the argument tuple of your method.

This means that if I define a function as

def foo(bar=0, **kwargs):
 print kwargs

Then calling foo() will print an empty dict
As will calling foo(3) or foo(bar=3), because the explicit "bar" keyword 
argument is used.

Now if I call foo(something=5, somethingelse="woohoo"), kwargs will 
evaluate to

{"somethingelse":"woohoo","something":5}

This means that all you have to do is replace your method definition with

 >>> def find_by(cls, **kwargs): pass

and in the method itself iterate over the key:value pairs of kwargs to 
automagically get both the field names and the values upon which your 
search shall be performed.

Calling the method would then look something like:

 >>> Person.find_by( name="thenameyoulookfor", city="somecity")
the syntax is fairly obvious and pythonic, has a low verbosity, and 
Python itself will do the parsing and the grammatical validation of your 
method calls for you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with curses and UTF-8

2006-02-08 Thread Ian Ward
Thomas Dickey wrote:
> "Martin v. Löwis" <[EMAIL PROTECTED]> wrote:
>>The ncurses documentation suggests that you should link with
>>ncurses_w instead of linking with ncurses - you might try
>>that as well. If it helps, please do report back.
> 
> 
> ncursesw

I'll test it if someone would dumb down "link with ncursesw instead of 
ncurses" a little for me.

I tried:
./configure --with-libs="ncursesw5"

and it failed saying:
checking size of wchar_t... configure: error: cannot compute sizeof 
(wchar_t), 77

Ian Ward

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


Re: A __getattr__ for class methods?

2006-02-08 Thread Dylan Moreland
Michael Spencer wrote:
> Dylan Moreland wrote:
> > I'm trying to implement a bunch of class methods in an ORM object in
> > order to provide functionality similar to Rails' ActiveRecord. This
> > means that if I have an SQL table mapped to the class "Person" with
> > columns name, city, and email, I can have class methods such as:
> >
> > Person.find_by_name
> > Person.find_by_city_and_name
> > Person.find_by_name_and_city_and_email
> >
> > I have a metaclass generating basic properties such as .name and .city,
> > but I don't want to generate a class method for every permutation of
> > the attributes. I'd like to have something much like __getattr__ for
> > instance attributes, so that if a method like
> > Person.find_by_city_and_email cannot be found, I can construct a call
> > to the basic find method that hides the SQL. Is there any way of doing
> > this, ...
>
> Sure, define __getattr__ on the type of the class i.e., the metaclass, just as
> you define it on a class to provide default-attribute-lookup to its instances:
>
>   >>> class A(object):
>   ... class __metaclass__(type):
>   ... def __getattr__(cls, attr):
>   ... return "%s.%s" % (cls.__name__, attr)
>   ...
>   >>> A.somefunc
>   'A.somefunc'
>   >>> A.someotherfunc
>   'A.someotherfunc'
>   >>>
>
> HTH
>
> Michael

Thanks! I only recently realized that I would have to learn metaclasses
in order to make this work, and I'm still a bit unclear on their
properties.

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


Re: Is Python good for web crawlers?

2006-02-08 Thread Magnus Lycka
Simon Brunning wrote:
> On 2/8/06, Alex Martelli <[EMAIL PROTECTED]> wrote:
> 
>>Bot? me? did I fail a Turing test again without even noticing?!
> 
> 
> If you'd noticed the test, you'd have passed.

No no, it's just a regular expression that notices the
word 'bot' close to 'Martelli'. Wouldn't surprise me
if more or less the same message appears again as a
response to this post. ;)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Too Many if Statements?

2006-02-08 Thread Alan Morgan
In article <[EMAIL PROTECTED]>,
Pierre Quentel <[EMAIL PROTECTED]> wrote:
>This is because Python has a hidden mechanism to detect programs
>generated by Perl scripts, and make them crash with no explanation

In my case it turned out to be python having a hidden method to detect when
you are using an ancient version of python.  Retesting with a newer version
didn't find any problems. 

Alan
-- 
Defendit numerus
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   3   >