Re: "no variable or argument declarations are necessary."

2005-10-08 Thread Alex Martelli
Paul Rubin  wrote:

> [EMAIL PROTECTED] (Alex Martelli) writes:
> > ap.py:4: No global (test) found
> > ap.py:5: Local variable (ego1d) not used
> > Helen:/tmp alex$ 
> > 
> > If you're so typo-prone and averse to unittests that you consider this
> > kind of issue to be a serious problem, just use pychecker and get
> > informed about any such typo, just as above.
> 
> That's very helpful, but why isn't it built into Python?

Because some users will prefer to use a different approach to checking,
for example, such as pylint (much more thorough in enforcing coding
rules and checking for all sort of things) or nothing (much faster than
pychecker, which in turn is faster than pylint).  Just as for other
programming tools, such as, say, an editor, I think it's wise to avoid
excessive and premature standardization on one specific tool to the
detriment of others.  (IDLE is "bundled with" Python, but not _built
into_ it -- indeed some would claim that the bundling was too much).

Not all tools need evolve at the same speed as the core language, which
currently follows a wise policy of "major" releases (2.3, 2.4, etc)
about 18 to 24 months apart, and NO feature changes for "point" release
(2.4.2 has exactly the same features as 2.4.1 -- it just fixes more
bugs).  Any tool which gets built into python (or, less strictly but
still problematically, is separate but bundled with it) must get on
exactly the same schedule and policy as Python itself, and that is
definitely not something that's necessarily appropriate.

If you're worried about the end-users which can't be bothered to
download tools (and, for that matter, libraries) separately from the
main language, the solution is "sumo releases" -- Enthought Python (from
Enthought) being an extreme example, but Active Python (from
ActiveState) comes with quite a few bundled add-ons, too.  I believe
that Linux has proven the validity of this general model: having the
"core" (mostly the kernel, in Linux's case; the language and standard
library, in Python's) evolve and get released as its own speed, and
having _distributions_ bundling the core with different set of tools and
add-ons get released on THEIR preferred schedules, independently.


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


Re: Will python never intend to support private, protected and public?

2005-10-08 Thread Alex Martelli
Simon Brunning <[EMAIL PROTECTED]> wrote:

> On 9/28/05, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> > > If *real* private and protected are *enforced*, Python will be the
> > > poorer for it. See
> > > .
> >
> > That's a wonderful, if long, essay.
> 
> That's the Martellibot for you. Never use a word where a paragraph
> with explanatory footnotes will do.
> 
> Sigh. I miss him on c.l.py.

Why, thanks -- it's sweet to be missed!-)  I also had fun rereading that
little piece of mine...

Unfortunately my current presence is probably a somewhat short-lived
phenomenon (I just need a breather right now, but I'll have to plunge
back into Google work AND writing the 2nd edition of the Nutshell
soon...), but, for a short while, I'm back!


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


Re: Will python never intend to support private, protected and public?

2005-10-08 Thread Alex Martelli
Kay Schluehr <[EMAIL PROTECTED]> wrote:

> Honestly I like to use private/protect/public modifiers in C++ for the
> sake of code documentation. I like to know which attributes are
> dedicated to be known by other objects, which ones are for internal use
> only and which ones should be at least publicly accessible within a
> class hierarchy. This helps structuring code in the large and spotting
> attention. Code becomes easier accessible. But if we have Sunday or I

This advisory role is played in Python by naming conventions.  Start
attribute names with a single underscore to suggest "private but may be
easily overridden by subclasses" (roughly the equivalent of "protected";
Stroustrup is on record, in his book "The Design and Evolution of the
C++ Programming Language", as regretting the exact details whereby
"protected" became entrenched in C++, and wishing they could be
changed... I believe Python's single-underscore is somewhat better), two
underscores if you ever want to make names hard to override (I used to
like that, but as time goes by have come to like it less and less; right
now, unless I have to respect existing coding standards, I entirely
avoid the double-underscore usage, while single-underscores are OKish).


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


Re: Extending Python

2005-10-08 Thread Alex Martelli
Micah Elliott <[EMAIL PROTECTED]> wrote:

> On Oct 05, Tuvas wrote:
> > I am looking for a good tutorial on how to extend python with C
> > code. I have an application built in C that I need to be able to use
> > in Python. I have searched through various sources, starting of
> > course with the Python site itself, and others, but I felt a bit
> > lacking from the Python site, it seems it was only made for those
> > who installed the source distribution, as for the other people...
> > Anyways, thanks for the help!
> 
> I have no experience with this, but I see that Alex Martelli's "Python
> In A Nutshell" has quite a few pages on the subject.

I also covered the same subject in a more tutorial (but less deep and
extended) way in articles for "Py" magazine, but I don't know if those
old issues of it are still in print.


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


Re: Simulating low bandwidth network on localhost

2005-10-08 Thread qvx
I forgot to tell you that I'm using Windows.

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


Re: Python's Performance

2005-10-08 Thread Laszlo Zsolt Nagy
Dave wrote:

> Hello All,
>  
> I would like to gather some information on Python's runtime 
> performance. As far as I understand, it deals with a lot of string 
> objects. Does it require a lot string processing during program 
> execution? How does it handle such time-consuming operations? Is there 
> a way to find out how many string operations (perhaps in the 
> underlying system) ) it does during program execution?

Do you want to know how many internal string operations are done inside 
the Python interpreter? I believe it is not a useful information. There 
are benchmarks testing the *real performance* of Python.

For example: http://www.osnews.com/story.php?news_id=5602


   Les

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


Re: os.access with wildcards

2005-10-08 Thread Fredrik Lundh
> > if glob.glob(...): ...
>
> As for your possible solutions, if you consider any
> of yours to be "readable", then i have no interest in
> coding with you.

> > if glob.glob(...): ...
>
> I guess, for readability, nothing has come up that
> seems _great_.

> > if glob.glob(...): ...
>
> It works, it's elegant, and it uses python strengths.

cute. I guess this thread shows that python can grow on you.





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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread Alex Martelli
George Sakkis <[EMAIL PROTECTED]> wrote:

> "Lasse Vågsæther Karlsen" <[EMAIL PROTECTED]> wrote:
> 
> > Thanks, that looks like Mike's solution except that it uses the
> > built-in heapq module.
> 
> This make a big difference for the algorithmic complexity; replacing an
> item in a heap is much more efficient than sorting the whole list.

In the most general case, yes.  However, Python's sort ("timsort") is
preternaturally fast when sorting sequences that are mostly sorted
except for maybe one element being in the wrong place... try it (and
read the Timbot's article included in Python's sources, and the sources
themselves)...  I suspect that heapq will still be faster, but by
nowhere as much as one might think.


> Yes, it's a little inconvenient that the builtin heap doesn't take a
> comparison operation but you can easily roll your own heap by transforming
> each item to a (key,item) tuple. Now that I'm thinking about it, it might
> be a good addition to the cookbook.

I believe Python 2.5 adds a key= argument to heapq's functions...


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


Re: Google Not Universal Panacea [was: Re: Where to find python c-sources]

2005-10-08 Thread Alex Martelli
Steve Holden <[EMAIL PROTECTED]> wrote:
   ...
>  >> Are people really too lazy to do elementary research on Google?
> 
> goes a bit too far in imputing motives to the enquirer and overlooking
> the fact that there are some very good reasons for *not* using Google.

It's a good thing you don't actually name any of those reasons, tho:-).

> we're talking male hormones here, since by and large women don't appear
> to have embraced the Python community (except perhaps individually, but
> that's no business of mine).

Anna seems to be doing fine, though.  She's currently taking a C class
at college and claims "the more I know C, the more I love Python" - and
I gather she's evangelizing (and the class is about 50/50 genderwise;-).

> Also, many regular readers didn't grow up speaking English (I was 

Yep -- I'm one example of that.  Didn't stop Google from hiring me,
though;-).


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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread Kay Schluehr
Alex Martelli wrote:

> try it (and read the Timbot's article included in Python's sources, and the
> sources themselves)...

Just a reading advise. The translated PyPy source
pypy/objectspace/listsort.py might be more accessible than the
corresponding C code. 

Kay

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


Re: Contest snub?

2005-10-08 Thread Will McGugan
[EMAIL PROTECTED] wrote:
> Notice anything strange here? The Python entry seems to have edged the PHP
> entries, but is not declared the victor. Source is missing as well (the 
> archive
> is empty.) 
> 
> http://www.apress.com/promo/fractal/seesource.html
> 
> H... an irrational fear of snakes perhaps?

Its not irrational if you are a gator!

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


Re: PIL Image can't open png file with "I"?

2005-10-08 Thread Fredrik Lundh
"James Hu" wrote:

> I have png file with mode "I", 16 bit,
> And I tried to open it with im=Image.open("output.png"), im.show()
> I got all white image.
> Don't why?

because all of the PNG file are larger than 255 ?

show doesn't support 16-bit images, so it clamps the values down to
an 8-bit range.  adding a

print im.getextrema()

will tell you what values you have in the image (it returns min and max).

to scale things down before you display it, you can use something like:

im = im.point(lambda x: x*(1.0/256))

or

lo, hi = im.getextrema()
if lo == hi:
im = im.point(lambda x: 128) # or something
else:
scale = 255.0 / (hi - lo)
offset = -lo * scale + 0.5
im = im.point(lambda x: x*scale + offset)





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


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-08 Thread Steve Holden
Terry Hancock wrote:
> On Friday 07 October 2005 03:44 pm, Steve Holden wrote:
> 
>>Precisely because there *is* such a thing as a saving. If I buy a $100 
>>gumball for $80 I have achieved a saving of 20%.
> 
> 
> Nope, that's incorrect American. ;-)
> 
> You can say "I bought a $100 gumball for $80, saving 20%," or
> "If I buy a $100 gumball for $80, I have achieved a savings of 20%."
> 
> (Although, you lose points for style with "achieved", and those
> are awfully expensive gumballs). ;-)
> 
I must have been working at NASA at the time; they are well known for 
embiggening prices.

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: When someone from Britain speaks, Americans hear a "Britishaccent"...

2005-10-08 Thread Steve Holden
Duncan Smith wrote:
> Rocco Moretti wrote:
[...]
> 
> So English is spoken only in the South East of England, except London?
> I think you should also disbar the queen (unless she's already
> classified as a Londoner), due to her apparent confusion between the 1st
> person singular and 1st person plural :-).
> 
There are special rules for the monarchs, who are expected to refer to 
themselves in the first person plural.

Oscar Wilde understood this. When he boasted that he could speak 
extempore for a minute on any subject of a challenger's choosing someone 
shouted "The Queen", to which he replied "The Queen, sir, is not a subject".

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


is there any Python code for spatial tessellation?

2005-10-08 Thread Shi Mu
is there any Python code for spatial tessellation?
thanks a lot!
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: noob question Letters in words?

2005-10-08 Thread Fredrik Lundh
(re that earlier thread, I think that everyone that thinks that it's a
good thing that certain Python constructs makes grammatical sense
in english should read the previous post carefully...)

Rob Cowie wrote:

> A string can be thought of as a tuple of characters.

footnote: the correct python term is "sequence of characters".

> Tuples support membership testing thus...
>
> choice1 = raw_input("> ")
>
> if '1' or 's' or 'S' in choice1:
>   #do something
> elif '2' or 'e' or E' in choice1:
>   #do something
>
> It doesn't seem to me to be a good idea; If the input is 'Start',
> option1 is executed, likewise if the input is 'Stop', or any other
> string with 's' in it.

in fact, the first choice is always executed, because

if '1' or 's' or 'S' in choice1:
...

might look as if it meant

if ('1' in choice1) or ('s' in choice1) or ('S' in choice1):
...

but it really means

if ('1') or ('s') or ('S' in choice1):
...

since non-empty strings are true, the '1' will make sure that the entire
expression is always true, no matter what choice1 contains.

> Perhaps a better idea is to present the user with a choice that cannot
> be deviated from, along the lines of...
>
> def main():
>   print "1.\tStart"
>   print "2.\tSomething Else"
>   print "3.\tStop"
>
>   x = raw_input()
>   if x is '1': print 'Start'
>   elif x is '2': print 'Something else'
>   elif x is '3': print 'End'
>   else: main()

The "is" operator tests for object identity, not equivalence.  Nothing
stops a Python implementation from creating *different* string objects
with the same contents, so the above isn't guaranteed to work.  (it
does work on current CPython versions, but that's an implementation
optimization, and not something you can rely on).

You should always use "==" to test for equivalence (and you should never
use "is" unless you know exactly what you're doing).





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


Re: Continuous system simulation in Python

2005-10-08 Thread niels . ellegaard
I don't know much about numerical aerodynamics, but assume that you are
interested in a finite element solver. I googled a bit and found the
following projects. The first is a 2d finite element solver for python.
The second is a 2d finite element solver without python.

http://ellipt2d.sourceforge.net/
http://www-rocq1.inria.fr/gamma/cdrom/www/freefem/eng.htm

You can probably find more libraries by looking at http://netlib.org.

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


Re: Feature Proposal: Sequence .join method

2005-10-08 Thread Alex Martelli
Michele Simionato <[EMAIL PROTECTED]> wrote:
   ...
> I have noticed a while ago that inside generators StopIteration is
> automatically trapped, i.e.
> 
> def g():
> yield 1
> raise StopIteration
> yield "Never reached"
> 
> only yields 1. Not sure if this is documented behavior, however, of if
> it is an implementation
> accident. Anybody who knows?

It yields 1 and on the next call to .next() raises StopIteration, which
is the way an iterator says it's done -- so, it yields 1 and then it's
done.  I'm not sure what you mean by "inside generators ...
automatically trapped", or what's undocumented about that.


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


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-08 Thread Michael
Steve Holden wrote:
...
> Or is "the green tomato" also unacceptable?
> 

Of course it is. We all know* it should be "the green fried tomato", or "the
killer tomato". 

:-)

(is it me, or is the subject line for this thread silly? After all, what
accent would you expect from someone in the UK? However, that said, the
concept of a *single* British accent is a silly as the idea. Sillier even
than the suggestion that the two lines below are British vs American:

> American: Minnesota is behind 7-0.  The Vikings are behind 7-0.
> British: Minnesota are behind 7-0. The Vikings are behind 7-0.

Or even these lines:

> American: The war department has decided to cancel the program.
> British: The war department have decided to cancel the program.

A better one might be:
> British: "They installed tunnelling for the petrol pipes made of grey
> coloured aluminium." 
> American: "They installed tunneling for the gas pipes made of gray
> colored aluminum."

(I think :-) I do my best with grammar, but can fail spectactularly, more
often than I'd like :)

Bad grammar flies at the same speed as the pedants who decide that the way
that other people talk is wrong. If the majority of people use a language
one way, and a small number of people say "you're wrong", who's right? 

Is it the people who speak the language in a shared way that they all
understand, or the people who are setting rules based on how people *used*
to speak and *used* to define words? (NB, I *did* say majority above ;-)
Does /human/ language _require_ backwards compatibility?

;-)


Michael.

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


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-08 Thread Michael
Terry Hancock wrote:

> 
> Well, yeah, although the correct pronunciation is apparently
> "te-tra-HEE-dra-GON".
> 
As opposed to a "te-tra-SHE-dra-GON" ?

;-)


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


Re: CSV like file format featured recently in Daily Python URL?

2005-10-08 Thread Alex Willmer
On Fri, 2005-10-07 at 18:56 +0200, Fredrik Lundh wrote:
> Alex Willmer wrote:
> 
> > I'm trying to track down the name of a file format and python module,
> > that was featured in the Daily Python URL some time in the last month or
> > two.
> 
> http://www.netpromi.com/kirbybase.html ?

No I don't think that was it. Although KirbyBase looks like a nice
project, particularly the alternative to SQL it uses to specify queries.

I remember the webpage presenting the format as fairly established and
in active use as an export/import medium, the python module was a
binding to an existing library. It's very possible I've combined the
memories of KirbyBase (for instance) and HDF. My recollection is to say
the least, foggy.

Thankyou for replying and thankyou for Daily Python-URL. I'll put this
on a backburner for now. I may remember it or come across it again by
fortune.

Alex

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


Re: Extending Python

2005-10-08 Thread gene tani
Yup, still there, issues 1 and 2
http://pyzine.com/Issue002/index.html

Also recommend Dave Kuhlman's brief intro (open in your tabbed browser)
http://www.rexx.com/~dkuhlman/python_201/python_201.html#SECTION00600


Alex Martelli wrote:
> Micah Elliott <[EMAIL PROTECTED]> wrote:
>
> > On Oct 05, Tuvas wrote:
> > > I am looking for a good tutorial on how to extend python with C
> > > code. I have an application built in C that I need to be able to use
> > > in Python. I have searched through various sources, starting of

>
> I also covered the same subject in a more tutorial (but less deep and
> extended) way in articles for "Py" magazine, but I don't know if those
> old issues of it are still in print.
> 
> 
> Alex

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


Re: Python 2nd favorite language in Linux Journal poll

2005-10-08 Thread beliavsky
beza1e1 wrote:
> Hm, you didn't include a link and my google did not find the final
> results.

I could not find a link, but the results appear on page 88 of the
November 2005 issue of Linux Journal.

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


Re: socketServer questions

2005-10-08 Thread rbt
On Fri, 2005-10-07 at 15:07 -0700, Paul Rubinhttp: wrote:
> rbt <[EMAIL PROTECTED]> writes:
> > The server just logs data, nothing else. It's not private or important
> > data... just sys admin type stuff (ip, mac addy, etc.). I just don't
> > want some script kiddie discovering it and trying to 'hack' it. By doing
> > so, they'd fill the log up with crap. So, If the data doesn't contain x,
> > y, and z and if the data is too big or too small, I record it to a
> > 'tamper' log and tell the leet hacker to 'go away'. 
> 
> Well, rather than this x,y,z stuff, it's best to do it properly and
> authenticate the records with the hmac module.


Off-topic here, but you've caused me to have a thought... Can hmac be
used on untrusted clients? Clients that may fall into the wrong hands?
How would one handle message verification when one cannot trust the
client? What is there besides hmac? Thanks, rbt

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


how do you pronounce wxpython

2005-10-08 Thread Alex
My native language is not English so I just wonder how you pronounce
wxPython.

vi-ex python
double-you-ex python
wax-python

or something else

Thanks

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


Re: how do you pronounce wxpython

2005-10-08 Thread John J. Lee
"Alex" <[EMAIL PROTECTED]> writes:

> My native language is not English so I just wonder how you pronounce
> wxPython.
> 
> vi-ex python
> double-you-ex python
> wax-python
> 
> or something else

I'm sure you'll get five different answers.

Personally, I say the 'wx' bit as 'wooks' (like 'books' in Southern
England pronunciation, ie. short 'oo').

Qt --> 'cute'

Tk --> 'tick'

Gtk --> I can't write this one down...


John

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


Re: how do you pronounce wxpython

2005-10-08 Thread Sam Pointon
I'd always assumed it was doubleyew-ecks python, but it could be wicks
python, or similar.

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


Re: Continuous system simulation in Python

2005-10-08 Thread Michael
Nicolas Pernetty wrote:

> I'm looking for any work/paper/ressource about continuous system
> simulation using Python or any similar object oriented languages (or
> even UML theory !).
> 
> I'm aware of SimPy for discrete event simulation, but I haven't found
> any work about continuous system.
> I would like to develop a generic continous system simulator, and so
> would be eager to join any open source effort on the subject.

There was going to be a talk on continuous system simulation (*) at
EuroPython this year, but for some reason it didn't appear to happen (It
was one of the talks I was hoping to see). I've no real idea of the content
of the talk or the work involved though for obvious reasons. Maybe that can
provide a lead?
   (*) http://www.python-in-business.org/ep2005/alisttrack.chtml?track=646
   "Implementing Continuous Time Simulation Systems in Python, Paul J
   Nolan"

Another lead //might// actually be to ask on the pygame list (MAYBE). It's
not directly the same thing, but essentially lots of games are in many
respects a form of continuous systems simulation, and someone on that
list might be able to point you in a good direction.

One book I bought a while back (looked interesting) which might be relevant
for you is O'Reilly's "physics for game developers", and and another is "AI
for games programmer"(*) since they both touch on these areas. If you have
a Safari account already that could be an easy way of checking to see
whether the book covers the sorts of answers you're after. (They don't use
python as their example language, but that's a minor problem really IMO)

(*) This is less obviously relevant, but deals with things deciding to move
themselves around continuous spaces and visualised at indeterminate
frame or display rates.

Best Regards,


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


Function decorator that caches function results

2005-10-08 Thread Lasse Vågsæther Karlsen
After working through a fair number of the challenges at 
www.mathschallenge.net, I noticed that some long-running functions can 
be helped *a lot* by caching their function results and retrieving from 
cache instead of calculating again. This means that often I can use a 
natural recursive implementation instead of unwinding the recursive 
calls to avoid big exponential running-times.

Ok, so I thought, how about creating a decorator that caches the 
function results and retrieves them from cache if possible, otherwise it 
calls the function and store the value in the cache for the next invokation.

This is what I came up with so far:

def cache_function(fn):
 cache = {}
 def cached_result(*args, **kwargs):
 if args in cache:
 return cache[args]
 result = fn(*args, **kwargs)
 cache[args] = result
 return result
 return cached_result

Example of usage:

@cache_function
def fibonacci(idx):
 if idx in (1, 2):
 return 1
 else:
 return fibonacci(idx-1) + fibonacci(idx-2)

for index in range(1, 101):
 print index, fibonacci(index)

this example goes from taking exponential time to run to being near 
instantaneous.

However, this:

for index in range(1, 101):
 print index, fibonacci(idx = index)

this one uses the kwargs list of arguments, and I'm not sure how to 
change my function to take that into account.

Does anyone have any clues as to how to do that?

The solution would have to consider fibonacci(50) and fibonacci(idx = 
50) as the same call and thus retrieve the second one from the cache.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-08 Thread Steve Horsley
Steve Holden wrote:
> Then again, there's room for infinite disagreement about these topics. I 
> mentioned a while ago that I disliked the English on a bumper sticker I 
> liked, which read
> 
> "Some village in Texas is missing their idiot".
> 
> Several people defended this, saying that a village could use the plural 
> possessive "their". I personally found it odd (and essentially 
> non-grammatical) not because either the singular or plural forms should 
> be mandated but because this one manages to mix them up. So
> 
> "Some village in Texas are missing their idiot"
> 
> would be better (though it sounds like the kind of thing only the idiot 
> alluded to would say), while my preferred choice would be
> 
> "Some village in Texas is missing its idiot".
> 

Strangely, the one that scans most naturally to me is the first 
one. Maybe its because the sentence starts by talking of a 
village in Texas singular point on a map, but the idiot in the 
second half is one of many inhabitants who have noticed his 
absence. Yes, it is mixing singular and plural from a syntactic 
point of view, but not so badly after interepretation into mental 
images.

The one that always makes me grit my teeth is "You have got to, 
don't you?". Well no, I do NOT got to, actually. Shudder!

Steve, Brung up in norf London.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socketServer questions

2005-10-08 Thread Tim Williams (gmail)
On 07/10/05, rbt <[EMAIL PROTECTED]> wrote:
> I have written a python socketServer program and I have a few questions

This is a multithreaded non-blocking version of your server (not
tested), with a basic attempt to hande errors.

from socket import *
from SocketServer import *
import  time, threading, sys

class tr_server(ThreadingMixIn, TCPServer):
def some_function(self):
pass

class tr_handler(StreamRequestHandler):
global write_to_file, file_path

def handle(self):
print "Current Connection count:", threading.activeCount() -1
public_ip = self.client_address[0]
serv_date = time.strftime('%Y-%m-%d', time.localtime())
serv_time = time.strftime('%H:%M:%S', time.localtime())

try:
data = self.rfile.readline(300)
data = str.strip(data)
bytes = str(len(data))
# Note that 'data; comes from the client.
fp = file('/home/rbt/Desktop/tr_report.txt', 'a')

fp.write(data+"\t"+serv_date+"\t"+serv_time+"\t"+public_ip+"\t"+bytes+"\n")
fp.close()
except:
print "unknown error", sys.exc_info()[0]

def StartServer():
setdefaulttimeout( 30  )  # timeout incoming connections
server = tr_server(('', 55503 ), tr_handler)
server.serve_forever()

if __name__ == '__main__':
StartServer()

Consider putting the writing to file function in its own class or
thread.  Then opening the file once and appending the data to it from
each connection. Yoou would need to use fp.flush() after each
fp.write()  so that the data survives a program fail.

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


Re: Function decorator that caches function results

2005-10-08 Thread Duncan Booth
Lasse Vågsæther Karlsen wrote:
> However, this:
> 
> for index in range(1, 101):
>  print index, fibonacci(idx = index)
> 
> this one uses the kwargs list of arguments, and I'm not sure how to 
> change my function to take that into account.
> 
> Does anyone have any clues as to how to do that?
> 
> The solution would have to consider fibonacci(50) and fibonacci(idx = 
> 50) as the same call and thus retrieve the second one from the cache.
> 

Most of your gain comes from caching the recursive calls, not from caching 
the original call.

If the solution doesn't consider keyword arguments equivalent to positional 
arguments, it will make *one* call to the real function, and then the 
recursive call will still come out of the cache, so the net result will 
still be to give you almost all the speedup you wanted. 

Unless the results stored in the cache are very large data structures, I 
would suggest that you simply store (args,kwargs) as the cache key and 
accept the hit that sometime you'll cache the same call multiple times.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help creating extension for C function

2005-10-08 Thread Fredrik Lundh
"Java and Swing" wrote:

>I need to write an extension for a C function so that I can call it
> from python.
>
> C code (myapp.c)
> ==
> typedef unsigned long MY_LONG;
>
> char *DoStuff(char *input, MY_LONG *x) { ... }
>
> so you pass in a string and an array of MY_LONGS...such as
>
> MY_LONGS vals[10] = {};
> char *input = "this is my input";
> char *result;
>
> result = DoStuff(input, vals);
>
> ...I need to create an extension so that I can call this from Python
> such as...
>
>>> import myapp
>>> vals = [1,2,3,4,5,6,7,8,9,10]
>>> input = "this is my input"
>>> result = myapp.DoStuff(input, vals)
>>> print result
>
> ideally the result would be a String, vals would be a list and input
> would be a string.

$ more module.c

/* $Id$ */
/* a module */

#include "Python.h"

static long*
get_long_array(PyObject* data, int* data_size)
{
int i, size;
long* out;
PyObject* seq;

seq = PySequence_Fast(data, "expected a sequence");
if (!seq)
return NULL;

size = PySequence_Size(seq);
if (size < 0)
return NULL;

if (data_size)
*data_size = size;

out = (long*) PyMem_Malloc(size * sizeof(long));
if (!out) {
Py_DECREF(seq);
PyErr_NoMemory();
return NULL;
}

for (i = 0; i < size; i++)
out[i] = PyInt_AsLong(PySequence_Fast_GET_ITEM(seq, i));

Py_DECREF(seq);

if (PyErr_Occurred()) {
PyMem_Free(out);
out = NULL;
}

return out;
}

static PyObject*
do_stuff(PyObject* self, PyObject* args)
{
int i;
long* vals;
int vals_size;

char* my_result;

char* input;
PyObject* vals_in;
if (!PyArg_ParseTuple(args, "sO:do_stuff", &input, &vals_in))
return NULL;

vals = get_long_array(vals_in, &vals_size);
if (!vals)
return NULL;

if (vals_size != 10) {
PyErr_SetString(PyExc_ValueError, "expected 10 values");
PyMem_Free(vals);
return NULL;
}

/* do stuff */
printf("input = %s\n", input);
for (i = 0; i < 10; i++)
printf("vals[%d] = %ld\n", i, vals[i]);
my_result = "result";
/* done */

PyMem_Free(vals);

return PyString_FromString(my_result);
}

static PyMethodDef functions[] = {
{"do_stuff", do_stuff, METH_VARARGS},
{NULL, NULL}
};

PyMODINIT_FUNC initmodule(void)
{
Py_InitModule4(
"module", functions, "my module", NULL, PYTHON_API_VERSION
);
}

$ more setup.py

# $Id$
# a setup file

from distutils.core import setup, Extension

setup(
name="module",
ext_modules = [Extension("module", ["module.c"])]
)

$ python setup.py build_ext -i
...

$ python
>>> import module
>>> vals = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> input = "this is some input"
>>> result = module.do_stuff(input, vals)
input = this is some input
vals[0] = 1
vals[1] = 2
vals[2] = 3
vals[3] = 4
vals[4] = 5
vals[5] = 6
vals[6] = 7
vals[7] = 8
vals[8] = 9
vals[9] = 10
>>> result
'result'

 



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


Re: When someone from Britain speaks, Americans hear a "Britishaccent"...

2005-10-08 Thread Duncan Smith
Steve Holden wrote:
> Duncan Smith wrote:
> 
>> Rocco Moretti wrote:
> 
> [...]
> 
>>
>> So English is spoken only in the South East of England, except London?
>> I think you should also disbar the queen (unless she's already
>> classified as a Londoner), due to her apparent confusion between the 1st
>> person singular and 1st person plural :-).
>>
> There are special rules for the monarchs, who are expected to refer to
> themselves in the first person plural.
> 
> Oscar Wilde understood this. When he boasted that he could speak
> extempore for a minute on any subject of a challenger's choosing someone
> shouted "The Queen", to which he replied "The Queen, sir, is not a
> subject".
> 

Yes, although I'm not actually sure where the 'royal we' comes from; and
we (Brits) are technically subjects rather than citizens.  But if
northerners are not English speakers because we use words like 'aye'
(although we say far less understandable things than that) I think the
queen should be similarly classified for using the 'royal we'  :-).

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


Re: CSV like file format featured recently in Daily Python URL?

2005-10-08 Thread EP
> From: Alex Willmer <[EMAIL PROTECTED]> inquired

> I'm trying to track down the name of a file format and python module,
> that was featured in the Daily Python URL some time in the last month 
> or
> two.
> 
> The format was ASCII with a multiline header defining types for the
> comma seperated column data below. It may have had the capability to
> store multiple tables in one file. There was news on the homepage that
> an alternate 'no data here' syntax was also supported.
> 
> An example file had vaguely this structure:
> 
> columnname as datatype
> columnname as datatype
> columnname as datatype
> columnname as datatype
> 
> data,data,data,data
> data,"other data",data,data
> data,data,"",data


Was it something like ARFF?  http://www.cs.waikato.ac.nz/~ml/weka/arff.html

Google "ARFF Python":  http://www.google.com/search?q=arff+python

-

   % 1. Title: Iris Plants Database
   % 
   % 2. Sources:
   %  (a) Creator: R.A. Fisher
   %  (b) Donor: Michael Marshall ([EMAIL PROTECTED])
   %  (c) Date: July, 1988
   % 
   @RELATION iris

   @ATTRIBUTE sepallength  NUMERIC
   @ATTRIBUTE sepalwidth   NUMERIC
   @ATTRIBUTE petallength  NUMERIC
   @ATTRIBUTE petalwidth   NUMERIC
   @ATTRIBUTE class{Iris-setosa,Iris-versicolor,Iris-virginica}
  

The Data of the ARFF file looks like the following:

   @DATA
   5.1,3.5,1.4,0.2,Iris-setosa
   4.9,3.0,1.4,0.2,Iris-setosa
   4.7,3.2,1.3,0.2,Iris-setosa
   4.6,3.1,1.5,0.2,Iris-setosa
   5.0,3.6,1.4,0.2,Iris-setosa
   5.4,3.9,1.7,0.4,Iris-setosa
   4.6,3.4,1.4,0.3,Iris-setosa
   5.0,3.4,1.5,0.2,Iris-setosa
   4.4,2.9,1.4,0.2,Iris-setosa
   4.9,3.1,1.5,0.1,Iris-setosa
  

Lines that begin with a % are comments. The @RELATION, @ATTRIBUTE and @DATA 
declarations are case insensitive. 

-

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


Re: Function decorator that caches function results

2005-10-08 Thread jepler
On Sat, Oct 08, 2005 at 01:53:28PM +, Duncan Booth wrote:
> Unless the results stored in the cache are very large data structures, I 
> would suggest that you simply store (args,kwargs) as the cache key and 
> accept the hit that sometime you'll cache the same call multiple times.

... except that dicts cannot be dict keys

Another 'memoize' decorator uses this to get the key:
kw = kwargs.items()
kw.sort()
key = (args, tuple(kw))
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325905

Jeff


pgp4a5R0heoxU.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread cfbolz
Kay Schluehr wrote:
> Alex Martelli wrote:
>
> > try it (and read the Timbot's article included in Python's sources, and the
> > sources themselves)...
>
> Just a reading advise. The translated PyPy source
> pypy/objectspace/listsort.py might be more accessible than the
> corresponding C code.

indeed. it is at

http://codespeak.net/svn/pypy/dist/pypy/objspace/std/listsort.py

Cheers,

Carl Friedrich Bolz

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


Re: Function decorator that caches function results

2005-10-08 Thread Sam Pointon
What about not storing args at all? Something like this:

def cache_function(func, args_list):
cache = {}
def cached_result(*args, **kwargs):
kwargs.update(dict(zip(args_list, args)))
if kwargs in cache:
return cache[kwargs]
result = func(**kwargs)
cache[kwargs] = result
return result
return cached_result

args_list is a list of all the argument names, so that they can be
converted into keyword arguments.

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


Re: Function decorator that caches function results

2005-10-08 Thread Lasse Vågsæther Karlsen
[EMAIL PROTECTED] wrote:
> On Sat, Oct 08, 2005 at 01:53:28PM +, Duncan Booth wrote:
> 
>>Unless the results stored in the cache are very large data structures, I 
>>would suggest that you simply store (args,kwargs) as the cache key and 
>>accept the hit that sometime you'll cache the same call multiple times.
> 
> 
> ... except that dicts cannot be dict keys
> 
> Another 'memoize' decorator uses this to get the key:
> kw = kwargs.items()
> kw.sort()
> key = (args, tuple(kw))
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/325905
> 
> Jeff

Yeah, but as far as I can see it, this one too fails to recognize 
situations where the function is called twice with essentially the same 
values, except that in one call it uses named arguments:

k1 = fibonacci(100)
k2 = fibonacci(idx = 100)

this is essentially the same call, except the second one uses a named 
argument, which means the function will be invoked and a second cache 
entry will be stored.

Granted, not a big problem in most such cases, but here's my augmented 
function. Bare in mind that I'm 2 weeks into Python so there's bound to 
be room for improvement :)

def cache(fn):
 cache = {}
 arg_names = inspect.getargspec(fn)[0]
 def cached_result(*args, **kwargs):
 # If function is called without parameters, call it without 
using the cache
 if len(args) == 0 and len(kwargs) == 0:
 return fn()

 # Work out all parameter names and values
 values = {}
 for i in range(len(args)):
 values[arg_names[i]] = args[i]
 for key in kwargs:
 values[key] = kwargs[key]
 key = tuple([(key, value) for (key, value) in 
sorted(values.iteritems())])

 # Check cache and return cached value if possible
 if key in cache:
 return cache[key]

 # Work out new value, cache it and return it
 result = fn(*args, **kwargs)
 cache[key] = result
 return result

 # Return wrapper function
 return cached_result


-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function decorator that caches function results

2005-10-08 Thread Lasse Vågsæther Karlsen
Sam Pointon wrote:
> What about not storing args at all? Something like this:
> 
> def cache_function(func, args_list):
> cache = {}
> def cached_result(*args, **kwargs):
> kwargs.update(dict(zip(args_list, args)))
> if kwargs in cache:
> return cache[kwargs]
> result = func(**kwargs)
> cache[kwargs] = result
> return result
> return cached_result
> 
> args_list is a list of all the argument names, so that they can be
> converted into keyword arguments.
> 

I'll take a look at the zip function, didn't know about that one, but 
your example also has the problem that dictionaries can't be used as 
dictionary keys, but that can be easily solved. I think I can simplify 
my solution with some of yours.

The parameter names can be gotten by doing a inspect.getargspec(fn)[0] 
so that can be done by the decorator function.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


List performance and CSV

2005-10-08 Thread Stephan
Hello,

I'm working on a simple project in Python that reads in two csv files
and compares items in one file with items in another for matches.  I
read the files in using the csv module, adding each line into a list.
Then I run the comparision on the lists.  This works fine, but I'm
curious about performance.

Here's the main part of my code:

##
file1 = open("CustomerList.csv")
CustomerList = csv.reader(file1)
Customers = []

#Read in the contents of the CSV file into memory
for CustomerRecord in CustomerList:
Customers.append(CustomerRecord)

#not shown here: the second file CustomersToMatch
#is loaded in a similar manner

#loop through each record and find matches on column 2
#breaking out of inner loop when a match is found
for loop1 in range(len(CustomersToMatch)):
for loop2 in range(len(Customers)):
if (CustomersToMatch[loop1][2] == Customers[loop2][2]) :
CustomersToMatch[loop1][1] = Customers[loop2][1]
break

##

With this code, it takes roughly 10 minutes on a 2Ghz x86 box to
compare two lists of 20,000 records.  Is that good?  Out of curiousity,
I tried psyco and saw no difference.  Is there a better Python synax to
use?

Thanks,
-Stephan

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


Re: Function decorator that caches function results

2005-10-08 Thread Fredrik Lundh
Lasse Vågsæther Karlsen wrote:

> Yeah, but as far as I can see it, this one too fails to recognize
> situations where the function is called twice with essentially the same
> values, except that in one call it uses named arguments:
>
> k1 = fibonacci(100)
> k2 = fibonacci(idx = 100)
>
> this is essentially the same call, except the second one uses a named
> argument, which means the function will be invoked and a second cache
> entry will be stored.

whoever writes code like that deserves to be punished.

I'd say this thread points to a misunderstanding of what keyword arguments
are, and how they should be used.  the basic rule is that you shouldn't mix and
match; use positional arguments for things that are documented to be positional
parameters, and keyword arguments for keyword parameters.  if you don't,
you'll end up with code that depends on implementation details.  and that's
never a good idea...

 



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

Re: Function decorator that caches function results

2005-10-08 Thread Lasse Vågsæther Karlsen
Lasse Vågsæther Karlsen wrote:
> Sam Pointon wrote:
> 
>> What about not storing args at all? Something like this:


Ok, here's my updated version:

class cache(object):
 def __init__(self, timeout=0):
 self.timeout = timeout
 self.cache = {}

 def __call__(self, fn):
 arg_names = inspect.getargspec(fn)[0]
 def cached_result(*args, **kwargs):
 # Update named arguments with positional argument values
 kwargs.update(dict(zip(arg_names, args)))

 # Work out key as a tuple of ('argname', value) pairs
 key = tuple(sorted(kwargs.items()))

 # Check cache and return cached value if possible
 if key in self.cache:
 (value, last_time) = self.cache[key]
 if self.timeout <= 0 or time.time() - last_time <= 
self.timeout:
 return value

 # Work out new value, cache it and return it
 result = fn(**kwargs)

 self.cache[key] = (result, time.time())
 return result

 # Return wrapper function
 return cached_result

Changed from previous versions:
- converted to class, must use () on decorator now
- added timeout, results will be recalculated when it expires
- timeout=0 means no timeout, results will always be reused
- now handles both positional and keyword arguments

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: readline installation problem

2005-10-08 Thread Jesper
Hi Jian,

I just struggled with the same problem - seems the python 2.4.2 does
not recognise readline 5

I finally "solved" the problem by installing readline 4.2, and
explicitly pointing out to configure where the readline library is

./configure --with-libs=/usr/local/lib/libreadline.a

That finally made it work ...

Cheers
Jesper

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


MD5 Help Page

2005-10-08 Thread Daniel 'Dang' Griffith
I'm referring to the text in
http://www.python.org/doc/2.4.2/lib/module-md5.html, which shows the
same thing I see in the Windows version of the help.

The two examples show:

'\xbbd\x9c\x83\xdd\x1e\xa5\xc9\xd9\xde\xc9\xa1\x8d\xf0\xff\xe9'

as the output, and that is indeed what I see when I run the examples.

But if I use hexdigest() instead of digest(), I get this result:

'bb649c83dd1ea5c9d9dec9a18df0ffe9'

I don't understand the difference.  Specifically, in the output of
digest, it shows a 'd' where I expect to see \x64.  What causes this
difference?

Thanks,
--dang

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


Re: Function decorator that caches function results

2005-10-08 Thread Lasse Vågsæther Karlsen
Fredrik Lundh wrote:

>>k1 = fibonacci(100)
>>k2 = fibonacci(idx = 100)

> whoever writes code like that deserves to be punished.
> 
> I'd say this thread points to a misunderstanding of what keyword arguments
> are, and how they should be used.  the basic rule is that you shouldn't mix 
> and
> match; use positional arguments for things that are documented to be 
> positional


I agree completely.
However, it turns out I have to communicate code with and from people 
that have a coding standard that dictates using keyword arguments for 
all interfaces. Those functions will also benefit from the cache system 
as many of them involves database lookups.

In any case, your response gave me another thing that my solution won't 
handle so I'm going to just leave it as it is and look at it if I ever 
need it for positional arguments, which I honestly don't believe I will.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When someone from Britain speaks, Americans hear a "British accent"...

2005-10-08 Thread Steve Holden
Steve Horsley wrote:
[...]
> 
> The one that always makes me grit my teeth is "You have got to, 
> don't you?". Well no, I do NOT got to, actually. Shudder!
> 
Shouldn't that be "I don't have to got to"?

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: MD5 Help Page

2005-10-08 Thread Daniel 'Dang' Griffith
Nevermind--chr(0x64) is 'd', as in duh.
--dang

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


[ANN] Dabo 0.4.2 released!

2005-10-08 Thread Ed Leafe
 We are pleased to announce the 0.4.2 release of Dabo, the 3-tier  
application framework for Python.

 The primary focus of our work for this release has been a  
tightening up of the various properties of many of the UI controls to  
create a more consistent interface. Since these controls were  
developed one at a time as needed, they had some subtle but  
significant differences in the way they worked. This release  
addresses a lot of those concerns.

 We've also added auto-binding of methods to events. For example,  
if you want to have your code react to MouseEnter event, all you need  
to do is add a method named onMouseEnter(), and Dabo will bind it to  
that event. Thanks to the PythonCard folks for this idea!

 Work on the Report Writer continues to proceed; it now supports  
groups and report variables. These improvements have been integrated  
it into the wizard-generated apps, too.

 Needless to say, there have also been a few bug fixes. A list of  
all the changes follows my sig. You can grab the latest, as always,  
from http://dabodev.com/download.

-- Ed Leafe
-- http://leafe.com
-- http://dabodev.com


- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Dabo-0.4.2 (2005-10-07) (Revision 1418):
Added PrimaryBizobj property to dForm, which can replace calls to  
getPrimaryBizobj().

Added Accepted property to dOkCancelDialog, which gets set  
automatically if the
user pressed "OK".

Added AutoSQL, UserSQL, CurrentSQL, LastSQL properties to dCursor and  
dBizobj.
When time to requery, the SQL will come from UserSQL if set, or  
AutoSQL will
be regenerated.

Fixed a bug that kept changes to a new record from getting committed.

Added DefaultValues property to bizobj.

Added ListSelection and ListDeselection events to dListControl. Added  
properties
MultipleSelect, HitIndex, LastSelectedIndex, HeaderVisible,  
HorizontalRules,
and VerticalRules. Changed the behavior of both dListControl and  
dListBox so that merely selecting an item doesn't raise the Hit  
event; instead, it raises a ListSelection event, and if another item  
had been previously selected, it raises a ListDeselection event. Hit  
is only raised from double-clicking on an item, or by pressing Enter.

Added new property to dTextBox: StrictDateEntry. Changed the code for
interpreting dates entered by the user to allow for some less explicit
formats (MMDD, YYMMDD, and MMDD). If StrictDateEntry is False (the
default), these other formats will be used when interpreting dates
entered by the user.

Added field-level validation to the framework.

Improved support for decimal.Decimal, both at the database level and in
dTextBox.

Added new auto event binding, which automatically binds events based  
on any
defined callback functions. For example, if you have a method  
onMouseEnter()
defined, the dEvents.MouseEnter will automatically be bound to that  
method.
Inspired by PythonCard.

Added RegID property to forms, that allows for object registration
with the form. Not all objects require RegIDs, but if they have one,
they must be unique among all objects in a form. A reference to that
object can then be gotten from any other object by calling
'self.Form.getObjectByRegID()'.

Linked RegID to the auto event binding, so that if a form has a method
of onHit_cmdOK(), and has a button with a RegID of 'cmdOK', the
cmdOk's Hit will get bound to the form's callback, automatically.

Improved dGrid and dColumn. Many properties added, and you are now in  
much
finer control over the display of grid column headers, grid cell  
attributes,
grid cell editors and renderers, and the grid itself.

Began work of allowing case-insensitive property values for  
properties that
take string values, and for properties that take a limited number of  
values
where the first letter is unique, you can set the property by just  
using the
first letter. dTextBox.Alignment = "c" sets the property to "Center",  
for
example.

Modified dBizobj, dCursorMixin, and dBackend so that the user can  
specify
the Unicode Encoding to use. Changed the default encoding from  
latin-1 to
utf-8.

Added feature to optionally draw sizer outlines on any form that uses  
dSizers.
This is currently accessible via an option in the View menu when the  
base
menu bar is in use, or you can turn it on/off programatically.

Grids now remember the column that is sorted, and resort when next  
instantiated.

Added support in dReportWriter for report groups and report  
variables, and
dynamic band heights (based on the height of contained objects).  
Added showExpr,
which is an expression that evaluates at runtime and if true, shows  
the object
in the report, and not if false.

Improved the automatic print preview report format in datanav. It now:

 + prints column headers

 + mirrors the font size, column width, cell vertical and horizontal
   alignment, and column height of the grid

 + mirrors the font size, header height, vertica

Automatic response to your mail (Error)

2005-10-08 Thread Webmaster
The automatic reply to this e-mail which you should have
received in response to your e-mail to [EMAIL PROTECTED] has not been defined.

Please contact [EMAIL PROTECTED] for assistance.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: noob question Letters in words?

2005-10-08 Thread Ivan Shevanski

Thanks everyone for helping once again, lots of good ideas there

Thanks,

-Ivan

_
FREE pop-up blocking with the new MSN Toolbar – get it now! 
http://toolbar.msn.click-url.com/go/onm00200415ave/direct/01/


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

Re: Python's Performance

2005-10-08 Thread Paul Boddie
Laszlo Zsolt Nagy wrote:
> There are benchmarks testing the *real performance* of Python.
>
> For example: http://www.osnews.com/story.php?news_id=5602

Just the observation that there are 166 comments to that article would
suggest that the methodology employed was somewhat debatable. (I don't
need to read them all - it is OSNews, after all.)

As for the "real performance" of Python, what do we learn from these
benchmarks which "...didn't test string manipulation, graphics, object
creation and management (for object oriented languages), complex data
structures, network access, database access, or any of the countless
other things that go on in any non-trivial program"? That Python
doesn't perform well executing loops involving mathematical operations?
Or something about "research and development" in the big consulting
houses?

Paul

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


Re: Force flushing buffers

2005-10-08 Thread Robert Wierschke
Madhusudan Singh schrieb:
> Hi
> 
> I have a python application that writes a lot of data to a bunch of 
> files
> from inside a loop. Sometimes, the application has to be interrupted and I
> find that a lot of data has not yet been writen (and hence is lost). How do
> I flush the buffer and force python to write the buffers to the files ? I
> intend to put this inside the loop.
> 
> Thanks.
disable the buffer!

open( filename[, mode[, bufsize]])

open takes an optional 3ed argument set bufsize = 0 means unbuffered. 
see the documentation of the in build file() mehtod as open is just 
another name

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


Re: List performance and CSV

2005-10-08 Thread jepler
You'll probably see a slight speed increase with something like
for a in CustomersToMatch:
for b in Customers:
if a[2] == b[2]:
a[1] = b[1]
break
But a really fast approach is to use a dictionary or other structure
that turns the inner loop into a fast lookup, not a slow loop through
the 'Customers' list.  Preparing the dictionary would look like
custmap = {}
for c in Customers:
k = c[2]
if k in custmap: continue
custmap[k] = c
and the loop to update would look like
for a in customerstomatch:
try:
a[1] = custmap[a[2]][1]
except KeyError:
continue

(all code is untested)

In "big-O" terms, I believe this changes the complexity from O(m*n) to O(m+n).

Jeff


pgpiNVhiQU0Jm.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread Tim Peters
[Alex Martelli]
>>> try it (and read the Timbot's article included in Python's sources, and the
>>> sources themselves)...

[Kay Schluehr]
>> Just a reading advise. The translated PyPy source
>> pypy/objectspace/listsort.py might be more accessible than the
>> corresponding C code.

[cfbolz]
> indeed. it is at
>
> http://codespeak.net/svn/pypy/dist/pypy/objspace/std/listsort.py

While the Python version is certainly easier to read, I believe Alex
had in mind the detailed English _explanation_ of the algorithm:

http://cvs.sf.net/viewcvs.py/python/python/dist/src/Objects/listsort.txt

It's a complex algorithm, dripping with subtleties that aren't
apparent from staring at an implementation.

Note that if a list has N elements, sorting it requires at least N-1
comparisons, because that's the minimum number of compares needed
simply to determine whether or not it's already sorted.  A heap-based
priority queue never requires more than O(log(N)) compares to push or
pop an element.  If N is small, it shouldn't make much difference.  As
N gets larger, the advantage of a heap grows without bound.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python for search engine development

2005-10-08 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Well, Google applies some Python in their implementation, see
> http://www-db.stanford.edu/~backrub/google.html

"Some" is correct.  As for writing a search engine in Python _only_,
hmmm -- I honestly don't know.  You could surely develop a working
implementation, but then, to make it perform well, you'd most likely
want to profile it and retune some CPU-intensive parts using pyrex, or
C.

So, if during your program development process you can find good
open-source C or C++ libraries offering a fast implementation of some of
the CPU-bound stuff you know you'll need, you would probably be better
off by wrapping those libraries (again using pyrex, or maybe SWIG, or
Boost Python for C++, ...) rather than redoing them from scratch in
Python (and probably later having to do some tuning on those parts).
One notably strong point of Python is that it "plays well with others",
and I would advise you to leverage this fact.


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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread Lasse Vågsæther Karlsen
Alex Martelli wrote:
> George Sakkis <[EMAIL PROTECTED]> wrote:

>>Yes, it's a little inconvenient that the builtin heap doesn't take a
>>comparison operation but you can easily roll your own heap by transforming
>>each item to a (key,item) tuple. Now that I'm thinking about it, it might
>>be a good addition to the cookbook.
> 
> 
> I believe Python 2.5 adds a key= argument to heapq's functions...


I will revisit the heapq solution when 2.5 is released then.

Thanks for the heads up. For the moment I will stay with the list 
solution that Mike came up with slightly changed to accomodate tips and 
pointers from others in this thread.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Weighted "random" selection from list of lists

2005-10-08 Thread Jesse Noller
Hello -

I'm probably missing something here, but I have a problem where I am
populating a list of lists like this:

list1 = [ 'a', 'b', 'c' ]
list2 = [ 'dog', 'cat', 'panda' ]
list3 = [ 'blue', 'red', 'green' ]

main_list = [ list1, list2, list3 ]

Once main_list is populated, I want to build a sequence from items
within the lists, "randomly" with a defined percentage of the sequence
coming for the various lists. For example, if I want a 6 item
sequence, I might want:

60% from list 1 (main_list[0])
30% from list 2 (main_list[1])
10% from list 3 (main_list[2])

I know how to pull a random sequence (using random()) from the lists,
but I'm not sure how to pick it with the desired percentages.

Any help is appreciated, thanks

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


Re: Python's Performance

2005-10-08 Thread Phillip J. Eby
Laszlo Zsolt Nagy wrote:
> Dave wrote:
>
> > Hello All,
> >
> > I would like to gather some information on Python's runtime
> > performance. As far as I understand, it deals with a lot of string
> > objects. Does it require a lot string processing during program
> > execution? How does it handle such time-consuming operations? Is there
> > a way to find out how many string operations (perhaps in the
> > underlying system) ) it does during program execution?
>
> Do you want to know how many internal string operations are done inside
> the Python interpreter? I believe it is not a useful information. There
> are benchmarks testing the *real performance* of Python.
>
> For example: http://www.osnews.com/story.php?news_id=5602

Actually, that benchmark shows something rather interesting.  The C and
Java versions of the benchmark are much faster than Python on so-called
"64-bit arithmetic", but only Python computes the *correct* answer to
the benchmark!  The others overflow 64 bits at some point and lose
precision, resulting in a nonsense result that the author failed to
notice.

So, without meaning to, the benchmark author has demonstrated something
important about Python, which is that writing the obvious thing in
Python tends to work correctly, even if it sometimes takes longer to
run than it would take for another language to produce the wrong
answer.  :)

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


Re: Python's Performance

2005-10-08 Thread Dave
Yes, I would like to know how many internal string operations are done inside the Python interpreter.
 
Thanks. Laszlo Zsolt Nagy <[EMAIL PROTECTED]> wrote:
Dave wrote:> Hello All,> > I would like to gather some information on Python's runtime > performance. As far as I understand, it deals with a lot of string > objects. Does it require a lot string processing during program > execution? How does it handle such time-consuming operations? Is there > a way to find out how many string operations (perhaps in the > underlying system) ) it does during program execution?Do you want to know how many internal string operations are done inside the Python interpreter? I believe it is not a useful information. There are benchmarks testing the *real performance* of Python.For example: http://www.osnews.com/story.php?news_id=5602Les
		 Yahoo! Music Unlimited - Access over 1 million songs. Try it free.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Jargons of Info Tech industry

2005-10-08 Thread Tim Tyler
Alan Balmer <[EMAIL PROTECTED]> wrote or quoted:
> On Tue, 04 Oct 2005 17:14:45 GMT, Roedy Green

> >I try to explain Java each day both on my website on the plaintext
> >only newsgroups. It is so much easier to get my point across in HTML.
> >
> >Program listings are much more readable on my website.
> 
> My copy of javac seems to prefer plain text, and so do I ;-)

Plain text is a badly impoverished medium for explaining things in.

For one thing, code on my web site tends to get syntax highlighted.
There's no way I could do that in plain text.
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


dis.dis question

2005-10-08 Thread Ron Adam

Can anyone show me an example of of using dis() with a traceback?

Examples of using disassemble_string() and distb() separately if 
possible would be nice also.


I'm experimenting with modifying the dis module so that it returns it's 
results instead of using 'print' it as it goes.  I want to make sure it 
works for all the current use cases (or as many as possible), but I 
haven't been able to find any examples of using dis with tracebacks 
using google.  I keep getting various copies of the current and older 
Python doc pages when I search, and not much else.

How much other python code depends on the dis() and disassembly() 
functions?  Is it used by other modules or is it meant to be a stand 
alone tool?

The changes I've made (for my own use so far) is to have disassembly() 
return a bare unformatted table, (list of list), that can easily be 
examined with python, and then to use a dis2str() function to return a 
nice formatted output-string from the table.  In order to have dis() 
display properly in an interactive shell as well as printing, I have 
dis() return a disassembly list object with a  __repr__() method to call 
dis2str().

class disobj(list):
 """ A disassembly list object """
 def __init__(self, dislist, name=None, lasti=-1):
 self[:] = dislist
 self.name = name
 self.lasti = lasti
 def __repr__(self):
 return dis2str(self, self.name, self.lasti)

That seems to work well in both the shell and with 'print'.  And it 
still allows direct table introspection without having to parse the 
output.  ;-)

For example the get_labels() function used was reduced to ...

def getlabels(dislist):
 """ Get labels from disassembly list table. """
 return [x[4] for x in dislist if type(x[4]) is str]

Another benefit, is to be able to get the results without having to 
redirect, capture, and then reset sys.stdout.

But I still need to rewrite disassemble_string() and need to test it 
with tracebacks.

Cheers,
Ron

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


Re: Weighted "random" selection from list of lists

2005-10-08 Thread Ron Adam
Jesse Noller wrote:


> 60% from list 1 (main_list[0])
> 30% from list 2 (main_list[1])
> 10% from list 3 (main_list[2])
> 
> I know how to pull a random sequence (using random()) from the lists,
> but I'm not sure how to pick it with the desired percentages.
> 
> Any help is appreciated, thanks
> 
> -jesse

Just add up the total of all lists.

 total = len(list1)+len(list2)+len(list3)
 n1 = .60 * total# number from list 1
 n2 = .30 * total# number from list 2
 n3 = .10 * total# number from list 3

You'll need to decide how to handle when a list has too few items in it.

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


Re: Continuous system simulation in Python

2005-10-08 Thread Sébastien Boisgérault

Simulink is a framework widely used by the control engineers ...
It is not *perfect* but the ODEs piece is probably the best
part of the simulator. Why were you not convinced ?

You may also have a look at Scicos and Ptolemy II. These
simulators are open-source ... but not based on Python.

Cheers,

SB





Nicolas Pernetty a écrit :

> Hello Phil,
>
> Yes I have considered Octave. In fact I'm already using Matlab and
> decided to 'reject' it for Python + Numeric/numarray + SciPy because I
> think you could do more in Python and in more simple ways.
>
> Problem is that neither Octave, Matlab and Python offer today a
> framework to build continuous system simulator (in fact Matlab with
> Simulink and SimMechanics, do propose, but I was not convinced at all).
>
> Regards,
>
> *** REPLY SEPARATOR  ***
>
> On 7 Oct 2005 11:00:54 -0700, [EMAIL PROTECTED] wrote :
>
> > Nicholas,
> >
> > Have you looked at Octave? It is not Python, but I believe it can talk
> > to Python.
> > Octave is comparable to Matlab for many things, including having ODE
> > solvers. I have successfully used it to model and simulate simple
> > systems. Complex system would be easy to model as well, provided that
> > you model your dynamic elements with (systems of) differential
> > equations.
> >

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


socket.setdefaulttimeout()

2005-10-08 Thread rtilley
Perhaps this is a dumb question... but here goes. Should a socket client 
and a socket server each have different values for 
socket.setdefaulttimeout() what happens? Does the one with the shortest 
timeout period end first?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread George Sakkis
"Lasse Vågsæther Karlsen" <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > George Sakkis <[EMAIL PROTECTED]> wrote:
> 
> >>Yes, it's a little inconvenient that the builtin heap doesn't take a
> >>comparison operation but you can easily roll your own heap by transforming
> >>each item to a (key,item) tuple. Now that I'm thinking about it, it might
> >>be a good addition to the cookbook.
> >
> >
> > I believe Python 2.5 adds a key= argument to heapq's functions...
> 
>
> I will revisit the heapq solution when 2.5 is released then.
>
> Thanks for the heads up. For the moment I will stay with the list
> solution that Mike came up with slightly changed to accomodate tips and
> pointers from others in this thread.

Just added a recipe at 
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440673. You can try
both and see if there's any significant performance difference for your data.

George


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

Re: os.access with wildcards

2005-10-08 Thread mike
ugly. i guess this thread shows that you are clueless regarding your
thread crapping.

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


Codetags (also Pylint/Pychecker + Variable declarations)

2005-10-08 Thread Fried Egg
* Codetag PEP:

**  I would like to comment on the codetags PEP, which I give a 0+.
 I think the end "<>" is bad; I would be in favor of a block system or
something that looks more like regular Python (e.g. "#
:FIXME(line_count=10, date='2005-08-09', ...) ").

**  As to the comments that say "Trac does the same functionality"
or "Eclipse/Eric/Emacs... has the same functionality" I think codetags
are orthogonal to that.  Also, some of us still use the old vi to edit
a system script in an emergency, and relying on bloated silliness like
Eclipse for documenting code seems, well, against all that is good and
true.

* Pylint:

**  I also agree that a lint system is the place to enforce or
otherwise use things like codetags.  A useful implementation would go a
long way to creating a standard organically.

* Variable declarations--a synthesis of codetags and lint:

** Perhaps a codetag system is the place to put variable
declarations, type checking, and the like.   The lint system could grab
these and evaluate the code with them without messing with the compiler
or quick and dirty code styles.  (Inferring properties of code from
static listings is for geniuses--not for me--so forgive any unrealistic
examples below).  As an added benefit, there wouldn't be any
non-explicit checking to impede performance (but if you want, you can
always add assert's to your heart's content when it really matters,
which is rarely).

** Example


str_var = '' # :DECLARE(type='string')
flt_var = 0 # :DECLARE(type='float')
line_index = 0 # :DECLARE(type='int', min=0, max=10)
for line_index in range(-10, 10) # "maximum exceeded" warning
mispelled_flt_var = 1ine_index / 2.5 # "undeclared variable"
warning
str_var = var + 1  # "type mismatch" warning


Thanks for everyone's patience in reading this--I hope it helps further
the Pythonic cause of graceful programming.

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


What about letting x.( ... ? ... ) be equivalent to ( ... x ... )

2005-10-08 Thread ddelay




Hello everybody,

I just like to know what all of you think of adding this functionnality
to python language, or  any other object oriented language in fact.

(English is not my natural language so please e-mail if you can improve this text...)

 x.( ... ? ... )  could be equivalent to ( ... x ... ) 

So an _expression_ such as :
(1)  html.stringtohtml(''.join(a.strip().split('/n')[:-1])).lower()

could be replaced with :
(2)   a.strip().split('/n')[:-1].(''.join(?)).(html.stringtohtml(?)).lower()

(in this example html would be a module containing the function stringtohtml) 
The advantages of such a notation :

- The order of operations always follows the (occidental?) reading
order, from left to right.  (in the formulation (1), we have a
mixed of right-to-left reading and left-to-right reading.)

- The number of nested levels  - limited to 2 levels of
parenthesis - does not grow with the number of successive operations
(it  soon gives problems with formulation (1)). 
This is a bit like in math you improve readability replacing
f(g(h(j(x))) with f o g o h o j (x), except here this would be roughly
looking like x.(j).(h).(g).(h)

Then you get other advantages :

- The growth of complexity in formulation (1) leads to the use of
intermediates computations which introduces unusefull intermediates
variables (they are just used once)
b = a.strip().split('/n')[:-1]
c = ''.join(b)
d = html.stringtohtml(c).lower()
These 3 intermediate variables used to improve readability can
introduce bugs : you have to check that b, c and d are not used
anywhere else in the code.
With notation (2), you minimise the use of unusefull intermediate variables.

- Builtins classes do not have to have many mumber fonctions. For
example, though string class does not have any member function "tohtml"
giving the ability to write s.tohtml() , you can still write
s.(html.texttohtml(?)) or simplier  s.(texttohtml(?)) after
an  import html.texttohtml

I'd like to have your opinions about that...

Daniel Delay.
 







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

Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread Lasse Vågsæther Karlsen
George Sakkis wrote:

> Just added a recipe at 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440673. You can try
> both and see if there's any significant performance difference for your data.


Thanks, will take a look at it later. The sort solution seems to work 
nicely. Might be a big difference if I have a lot of sources though as I 
bet the overhead in doing a sort of N items gets higher than doing a 
manipulation of a heap to place an item in the right spot, but with 4-5 
or a few more sources might not make an impact at all.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Function decorator that caches function results

2005-10-08 Thread George Sakkis
"Lasse Vågsæther Karlsen" <[EMAIL PROTECTED]> wrote:

> [snip]
>
> Ok, so I thought, how about creating a decorator that caches the
> function results and retrieves them from cache if possible, otherwise it
> calls the function and store the value in the cache for the next invokation.
>
> [snip]

Cool, you re-invented the memoization pattern:
http://en.wikipedia.org/wiki/Memoization
http://aspn.activestate.com/ASPN/search?query=memoize&x=0&y=0§ion=PYTHONCKBK&type=Subsection

Yes, it's kinda discouraging that most interesting ideas have already been 
conceived, implemented
and used by others...

George


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

RE: Will python never intend to support private, protected and public?

2005-10-08 Thread Robert Brewer
Title: RE: Will python never intend to support private, protected and public?






Alex Martelli wrote:
> I used to like [double-underscore private names], but as time
> goes by have come to like it less and less; right now,
> unless I have to respect existing coding standards,
> I entirely avoid the double-underscore usage,
> while single-underscores are OKish).

Hear, hear. I've been seriously considering a ban on double-underscore names as part of the coding standard for CherryPy.

And I am also glad you're back! I must say I opened several of your recent posts on topics which I would not otherwise have read. ;)


Robert Brewer
System Architect
Amor Ministries
[EMAIL PROTECTED]



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

Re: Jargons of Info Tech industry

2005-10-08 Thread David H Wild
In article <[EMAIL PROTECTED]>,
   Tim Tyler <[EMAIL PROTECTED]>  wrote:
> Plain text is a badly impoverished medium for explaining things in.

> For one thing, code on my web site tends to get syntax highlighted.
> There's no way I could do that in plain text.

On your web site the use of additional features is often, but not always,
justified - but we were talking about emails where the use of HTML bulks up
the email for very little gain.

-- 
David Wild using RISC OS on broadband
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's Performance

2005-10-08 Thread Fredrik Lundh
Paul Boddie wrote:

>> There are benchmarks testing the *real performance* of Python.
>>
>> For example: http://www.osnews.com/story.php?news_id=5602
>
> Just the observation that there are 166 comments to that article would
> suggest that the methodology employed was somewhat debatable. (I don't
> need to read them all - it is OSNews, after all.)
>
> As for the "real performance" of Python, what do we learn from these
> benchmarks which "...didn't test string manipulation, graphics, object
> creation and management (for object oriented languages), complex data
> structures, network access, database access, or any of the countless
> other things that go on in any non-trivial program"? That Python
> doesn't perform well executing loops involving mathematical operations?

fwiw, if you leave out the environments that compile to native machine code,
CPython is the fastest runtime in this floating-point benchmark:

http://www.fourmilab.ch/fbench/fbench.html

(I recently translated some satellite navigation code from a Python prototype
to C, and was a bit surprised to find that I only got a 7x speedup...)

 



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


Re: Merging sorted lists/iterators/generators into one stream of values...

2005-10-08 Thread George Sakkis
"Lasse Vågsæther Karlsen" <[EMAIL PROTECTED]> wrote:

> George Sakkis wrote:
> 
> > Just added a recipe at 
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440673. You can
try
> > both and see if there's any significant performance difference for your 
> > data.
> 
>
> Thanks, will take a look at it later. The sort solution seems to work
> nicely. Might be a big difference if I have a lot of sources though as I
> bet the overhead in doing a sort of N items gets higher than doing a
> manipulation of a heap to place an item in the right spot, but with 4-5
> or a few more sources might not make an impact at all.

Unless you're talking about hundreds or thousands sources, it probably
won't. I would still go for the heap solution since IMO the resulting
code it's more readable and easier to understand.

George

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


Re: Function decorator that caches function results

2005-10-08 Thread Lasse Vågsæther Karlsen
George Sakkis wrote:

> Cool, you re-invented the memoization pattern:
> http://en.wikipedia.org/wiki/Memoization
> http://aspn.activestate.com/ASPN/search?query=memoize&x=0&y=0§ion=PYTHONCKBK&type=Subsection
> 
> Yes, it's kinda discouraging that most interesting ideas have already been 
> conceived, implemented
> and used by others...


I know, I've been scouring over the ASPN recipes and digging through 
code like there's no tomorrow.

But, I don't view it as pointless even though there are existing 
implementations and solutions out there.

First of all, I don't like to stuff a lot of what is obviously library 
type of code into a project, unless I can reference a library that got 
that function or class or whatnot. Creates a rather big maintenance 
nightmare :)

So, I would have to stuff that into a library, which is what I did with 
my "own" function (thank you for helping btw). The recipe on ASPN is 
probably better than what I got, but... I understand how my solution 
came about and what makes it tick.

Secondly, I've been "programming" Python for, what, about 11 days now or 
so, so I want to re-implement as much as possibly right now, even to the 
point where I create a worse solution than an existing one, as long as 
it works for me, just to be able to learn the nuances of Python, because 
Python is ... different than what I'm used to.

For instance, in C# and .NET you got attributes, but they don't actually 
do anything on their own, in other words you can't tag a method and have 
the operation of that method deviate from a similar method without the 
attribute, unless you pick one of the attributes the compiler knows 
about, so it's just meta-data that sits silent until some other method 
goes around to look for it.

In Python I've now learned that a function is just an object like 
everything else and I can wrap a new object around it to modify its 
behaviour, and I can use the decorator pattern to do it.

I'm probably going to be back here in a few days or even hours with 
another "task" where you can probably cough up dozens of existing source 
code solutions that I could use.

For instance, there's this thing I've heard of called the "wheel".

:)

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python's Performance

2005-10-08 Thread Fredrik Lundh
Dave wrote:

> Yes, I would like to know how many internal string operations are done inside
> the Python interpreter.

when you're doing what?

how do you define "internal string operations", btw?

 



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


Re: Weighted "random" selection from list of lists

2005-10-08 Thread Peter Otten
Jesse Noller wrote:

> I'm probably missing something here, but I have a problem where I am
> populating a list of lists like this:
> 
> list1 = [ 'a', 'b', 'c' ]
> list2 = [ 'dog', 'cat', 'panda' ]
> list3 = [ 'blue', 'red', 'green' ]
> 
> main_list = [ list1, list2, list3 ]
> 
> Once main_list is populated, I want to build a sequence from items
> within the lists, "randomly" with a defined percentage of the sequence
> coming for the various lists. For example, if I want a 6 item
> sequence, I might want:
> 
> 60% from list 1 (main_list[0])
> 30% from list 2 (main_list[1])
> 10% from list 3 (main_list[2])
> 
> I know how to pull a random sequence (using random()) from the lists,
> but I'm not sure how to pick it with the desired percentages.


If the percentages can be normalized to small integral numbers, just make a
pool where each list is repeated according to its weight, e. g.
list1 occurs 6, list2 3 times, and list3 once:

pools = [list1, list2, list3]
weights = [6, 3, 1]
sample_size = 10

weighted_pools = []
for p, w in zip(pools, weights):
weighted_pools.extend([p]*w)

sample = [random.choice(random.choice(weighted_pools))
for _ in xrange(sample_size)]


Another option is to use bisect() to choose a pool:

pools = [list1, list2, list3]
sample_size = 10

def isum(items, sigma=0.0):
for item in items:
sigma += item
yield sigma

cumulated_weights = list(isum([60, 30, 10], 0))
sigma = cumulated_weights[-1]

sample = []
for _ in xrange(sample_size):
pool = pools[bisect.bisect(cumulated_weights, random.random()*sigma)]
sample.append(random.choice(pool))

(all code untested)

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


new forum -- homework help/chit chat/easy communication

2005-10-08 Thread csheppard91
I've launched a new forum not too long ago, and I invite you all to go
there: www.wizardsolutionsusa.com (click on the forum link).  We offer
all kinds of help, and for those of you who just like to talk, there's
a chit chat section just for you...Just remember that forum
communication is much easier, safer, and faster.

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


Re: new forum -- homework help/chit chat/easy communication

2005-10-08 Thread Lasse Vågsæther Karlsen
[EMAIL PROTECTED] wrote:
> I've launched a new forum not too long ago, and I invite you all to go
> there: www.wizardsolutionsusa.com (click on the forum link).  We offer
> all kinds of help, and for those of you who just like to talk, there's
> a chit chat section just for you...Just remember that forum
> communication is much easier, safer, and faster.
> 

Easier than what? Having to look into each forum to see if something is 
new? That's easier?
Safer than what? Using a web browser? That's safe?
Faster? That page loads 10 posts in the same speed I get 700 posts with 
usenet.

Don't think so matey.

Nice try though.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Contest snub?

2005-10-08 Thread [EMAIL PROTECTED]

Will McGugan wrote:
> [EMAIL PROTECTED] wrote:
> > Notice anything strange here? The Python entry seems to have edged the PHP
> > entries, but is not declared the victor. Source is missing as well (the 
> > archive
> > is empty.)
> >
> > http://www.apress.com/promo/fractal/seesource.html
> >
> > H... an irrational fear of snakes perhaps?
>
> Its not irrational if you are a gator!

Furthermore, just because you're paranoid doesn't mean people aren't
out
to get you.

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

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


Geocoding and python

2005-10-08 Thread Andrew Gwozdziewycz
Does anyone know of a python module that can read and search the  
tiger line data for geolocation?

Currently, I can use xmlrpc to query geocoder.us but I'd rather not  
be querying their server if I don't have to.

Thanks


---
Andrew Gwozdziewycz
[EMAIL PROTECTED]
http://ihadagreatview.org
http://plasticandroid.org


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


Re: new forum -- homework help/chit chat/easy communication

2005-10-08 Thread Michael Goettsche
On Saturday 08 October 2005 21:15, Lasse Vågsæther Karlsen wrote:
> [EMAIL PROTECTED] wrote:
> > I've launched a new forum not too long ago, and I invite you all to go
> > there: www.wizardsolutionsusa.com (click on the forum link).  We offer
> > all kinds of help, and for those of you who just like to talk, there's
> > a chit chat section just for you...Just remember that forum
> > communication is much easier, safer, and faster.
>
> Easier than what? Having to look into each forum to see if something is
> new? That's easier?
> Safer than what? Using a web browser? That's safe?
> Faster? That page loads 10 posts in the same speed I get 700 posts with
> usenet.

Besides that, it's cheap advertising. Would it have been harder to post the 
direct forum link than to link to his company's website?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new forum -- homework help/chit chat/easy communication

2005-10-08 Thread Fredrik Lundh
Lasse Vågsæther Karlsen wrote:

> Don't think so matey.

oh, come on.  a site run by some random guy in North Carolina has to be
safer, faster and more reliable than a distributed communication system that
has been around since that guy was born...

 



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

Re: new forum -- homework help/chit chat/easy communication

2005-10-08 Thread Fredrik Lundh
Michael Goettsche wrote:

> Besides that, it's cheap advertising. Would it have been harder to post the
> direct forum link than to link to his company's website?

company?

 



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


Re: noob question Letters in words?

2005-10-08 Thread Rob Cowie
Well.. that put me in my place!

Fredrik Lundh - I hadn't realised that 'is' does not test for
equivalence. Thanks for the advice.

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


Re: Help creating extension for C function

2005-10-08 Thread Fredrik Lundh
>seq = PySequence_Fast(data, "expected a sequence");
>if (!seq)
>return NULL;

here's some more information on the PySequence_Fast API:

http://www.effbot.org/zone/python-capi-sequences.htm

 



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


Re: how do you pronounce wxpython

2005-10-08 Thread Grant Edwards
On 2005-10-08, Alex <[EMAIL PROTECTED]> wrote:
> My native language is not English so I just wonder how you pronounce
> wxPython.
>
> vi-ex python
> double-you-ex python
> wax-python

The second one.

-- 
Grant Edwards   grante Yow!  HELLO, everybody,
  at   I'm a HUMAN!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new forum -- homework help/chit chat/easy communication

2005-10-08 Thread Grant Edwards
On 2005-10-08, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> I've launched a new forum not too long ago, and I invite you all to go
> there: www.wizardsolutionsusa.com (click on the forum link).  We offer
> all kinds of help, and for those of you who just like to talk, there's
> a chit chat section just for you...Just remember that forum
> communication is much easier, safer, and faster.

I disagree 100% with that last assertion.  Usenet is much,
much, easier, safer and faster.

-- 
Grant Edwards   grante Yow!  BARRY... That was
  at   the most HEART-WARMING
   visi.comrendition of "I DID IT
   MYWAY" I've ever heard!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new forum -- homework help/chit chat/easy communication

2005-10-08 Thread Lasse Vågsæther Karlsen
Fredrik Lundh wrote:
> Lasse Vågsæther Karlsen wrote:
> 
> 
>>Don't think so matey.
> 
> 
> oh, come on.  a site run by some random guy in North Carolina has to be
> safer, faster and more reliable than a distributed communication system that
> has been around since that guy was born...

Yes, of course, my mistake, it's rather obvious now that you point it out.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Daisy Daisy, give me your answer do

2005-10-08 Thread Xah Lee
there is a MacPerl program posted in 1998 that uses Mac's speech synth
to sing Daisy Bell.
See:

http://bumppo.net/lists/macperl/1998/11/msg00412.html

can anyone modify it so it runs out of the box on today's OS X?

PS i'm posting this also in python and lisp group, i hope it'd be some
general interest. For some background of this song, see
  http://xahlee.org/Periodic_dosage_dir/sanga_pemci/daisy_bell.html

i'm interested in getting versions that can sing the song in Windows,
Mac, Linux using whatever speech synth each OS may provide. Thanks.

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Weighted "random" selection from list of lists

2005-10-08 Thread Scott David Daniels
Jesse Noller wrote:

> Once main_list is populated, I want to build a sequence from items
> within the lists, "randomly" with a defined percentage of the sequence
> coming for the various lists. For example:
> 60% from list 1 (main_list[0]), 30% from list 2 (main_list[1]), 10% from list 
> 3 (main_list[2])


import bisect, random
main_list = [['a', 'b', 'c'],
  ['dog', 'cat', 'panda'],
  ['blue', 'red', 'green']]
weights = [60, 30, 10]

cumulative = []
total = 0
for index, value in enumerate(weights):
 total += value
 cumulative.append(total)

for i in range(20):
 score = random.random() * total
 index = bisect.bisect(cumulative, score)
 print random.choice(main_list[index]),


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


Re: Daisy Daisy, give me your answer do

2005-10-08 Thread Michael Goettsche
On Saturday 08 October 2005 22:10, Xah Lee wrote:
> there is a MacPerl program posted in 1998 that uses Mac's speech synth
> to sing Daisy Bell.
> See:
>
> http://bumppo.net/lists/macperl/1998/11/msg00412.html
>
> can anyone modify it so it runs out of the box on today's OS X?
>
> PS i'm posting this also in python and lisp group, i hope it'd be some
> general interest. For some background of this song, see
>   http://xahlee.org/Periodic_dosage_dir/sanga_pemci/daisy_bell.html
>
> i'm interested in getting versions that can sing the song in Windows,
> Mac, Linux using whatever speech synth each OS may provide. Thanks.
>
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/

You're asking "tech geekers" and "morons" to do this job? Isn't that a task 
for somebody more professional like you? 
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Daisy Daisy, give me your answer do

2005-10-08 Thread Lasse Vågsæther Karlsen
Leave Xah Lee alone, he's a troll, he got no interested in doing 
anything but to provoke people on usenet.

-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Jargons of Info Tech industry

2005-10-08 Thread Roedy Green
On Tue, 04 Oct 2005 17:57:13 -, [EMAIL PROTECTED] (Gordon
Burditt) wrote or quoted :

>HTML enables a heck of a lot of problems:  "web bugs" in email,
>links to fake sites that appear as real ones in what shows up
>on the screen, Javascript viruses, denial-of-service attacks
>(pages that open two windows when you close one), etc.
>
>>That is like hating all choirs because televangelists use them.
>
>I liken it more to hating all viruses because some of them 
>install keyloggers.

 I take it then you avoid browsers or use Lynx?  No you FIX the
problems rather than wear a hair shirt. Same for email. Why should
rich expressions only be permitted to those with websites.  

Some people use email PRIMARILY for sharing photos.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jargons of Info Tech industry

2005-10-08 Thread Roedy Green
On Wed, 05 Oct 2005 09:38:49 +1000, Steven D'Aprano
<[EMAIL PROTECTED]> wrote or quoted :

>Yes it is. HTML means that after I've specified my email client use my
>favourite font, in the size I like, people send me emails that over-ride
>my choice. Invariably they use a font I don't even have. 

I would suggest then a better solution is to implement CSS in email,
the way you do in browsers to deal with that same problem.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Jargons of Info Tech industry

2005-10-08 Thread Roedy Green
On Wed, 05 Oct 2005 09:38:49 +1000, Steven D'Aprano
<[EMAIL PROTECTED]> wrote or quoted :

>Even more invariably, they set the point size directly rather than in
>relative terms, and they are on Windows, where point sizes are about 20%
>oversized.

 that is like giving up Java because there was a bug in the Windows
JVM. FIX THE BUG.
-- 
Canadian Mind Products, Roedy Green.
http://mindprod.com Again taking new Java programming contracts.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socketServer questions

2005-10-08 Thread Paul Rubin
rbt <[EMAIL PROTECTED]> writes:
> Off-topic here, but you've caused me to have a thought... Can hmac be
> used on untrusted clients? Clients that may fall into the wrong hands?
> How would one handle message verification when one cannot trust the
> client? What is there besides hmac? Thanks, rbt

I don't understand the question.  HMAC requires that both ends share a
secret key; does that help?  What do you mean by verification?  Do you
mean you want to make sure that's really Bob logging into your
computer, even when Bob might have intentionally given his password to
someone else?  It sounds like you want something like DRM.  What
exactly are you trying to do?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Continuous system simulation in Python

2005-10-08 Thread Nicolas Pernetty
Simulink is well fitted for small simulators, but when you run into big
projects, I find many shortcomings appears which made the whole thing
next to unusable for our kind of projects.

That's why I'm interested in Python by the way, it is not a simple clone
like Scilab/Scicos. It is a real language which bring its own
advantages, and its own shortcomings, which I find well suited for our
activity.

If you want, I can send you a paper I wrote last year, detailing all
Simulink shortcomings. I doubt that this mailing list is interested in
such things...(and it's in French...).

Concerning Scilab/Scicos, I'm not really interested in a technology
primarily developed (INRIA and ENSPC) and used by France. Python and all
its libraries and communities are so much more dynamic !
And also I've heard that Scilab was developed in Fortran in a way which
make it rigid and that the sources are poorly documented, not a good
sign for an open source software (and Scilab isn't 'Free' for the FSF).

Regards,


*** REPLY SEPARATOR  ***

On 8 Oct 2005 11:06:25 -0700, "Sébastien Boisgérault"
<[EMAIL PROTECTED]> wrote :

> 
> Simulink is a framework widely used by the control engineers ...
> It is not *perfect* but the ODEs piece is probably the best
> part of the simulator. Why were you not convinced ?
> 
> You may also have a look at Scicos and Ptolemy II. These
> simulators are open-source ... but not based on Python.
> 
> Cheers,
> 
> SB
> 
> 
> 
> 
> 
> Nicolas Pernetty a écrit :
> 
> > Hello Phil,
> >
> > Yes I have considered Octave. In fact I'm already using Matlab and
> > decided to 'reject' it for Python + Numeric/numarray + SciPy because
> > I think you could do more in Python and in more simple ways.
> >
> > Problem is that neither Octave, Matlab and Python offer today a
> > framework to build continuous system simulator (in fact Matlab with
> > Simulink and SimMechanics, do propose, but I was not convinced at
> > all).
> >
> > Regards,
> >
> > *** REPLY SEPARATOR  ***
> >
> > On 7 Oct 2005 11:00:54 -0700, [EMAIL PROTECTED] wrote :
> >
> > > Nicholas,
> > >
> > > Have you looked at Octave? It is not Python, but I believe it can
> > > talk to Python.
> > > Octave is comparable to Matlab for many things, including having
> > > ODE solvers. I have successfully used it to model and simulate
> > > simple systems. Complex system would be easy to model as well,
> > > provided that you model your dynamic elements with (systems of)
> > > differential equations.
> > >
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Daisy Daisy, give me your answer do

2005-10-08 Thread Xah Lee
Dear Michael Goettsche,

why don't you lead the pack to be on-topic for a change, huh?

 Xah

Michael Goettsche wrote:
> On Saturday 08 October 2005 22:10, Xah Lee wrote:
> > there is a MacPerl program posted in 1998 that uses Mac's speech synth
> > to sing Daisy Bell.
> > See:
> >
> > http://bumppo.net/lists/macperl/1998/11/msg00412.html
> >
> > can anyone modify it so it runs out of the box on today's OS X?
> >
> > PS i'm posting this also in python and lisp group, i hope it'd be some
> > general interest. For some background of this song, see
> >   http://xahlee.org/Periodic_dosage_dir/sanga_pemci/daisy_bell.html
> >
> > i'm interested in getting versions that can sing the song in Windows,
> > Mac, Linux using whatever speech synth each OS may provide. Thanks.
> >
> >  Xah
> >  [EMAIL PROTECTED]
> > ∑ http://xahlee.org/
>
> You're asking "tech geekers" and "morons" to do this job? Isn't that a task
> for somebody more professional like you?

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

  1   2   >