[ANN] Leipzig Python User Group - Meeting, March 11, 2008, 08:00pm

2008-03-08 Thread Mike Müller
=== Leipzig Python User Group ===

We will meet on Tuesday, March 11 at 8:00 pm at the training
center of Python Academy in Leipzig, Germany
( http://www.python-academy.com/center/find.html ).

Our main topic will be the Chemnitzer Linux-Tage.
Our booth was pretty busy. Quite a few people were really
interested in our user group.

Many of us were there as presenters and/or helpers at booths of
other projects. Therefore, there will be lots things to talk about
such as visited presentations, talks at booths, or impressions.

Food and soft drinks are provided. Please send a short
confirmation mail to [EMAIL PROTECTED], so we can prepare
appropriately.

Everybody who uses Python, plans to do so or is interested in
learning more about the language is encouraged to participate.

While the meeting language will be mainly German, we will provide
English translation if needed.

Current information about the meetings are at
http://www.python-academy.com/user-group .

Mike



== Leipzig Python User Group ===

Wir treffen uns am Dienstag, 11.03.2008 um 20:00 Uhr
im Schulungszentrum der Python Academy in Leipzig
( http://www.python-academy.de/Schulungszentrum/anfahrt.html ).

Wir wollen über die Chemnitzer Linux-Tage sprechen.
Unseren Stand war recht gut besucht und wir haben doch
Einige für die User Group interessieren können.

Viele von uns waren als Vortragende und/oder Mitwirkende an
anderen Ständen dort. So gibt es sicher viel über besuchte
Vorträge, Gespräche und Eindrücke mitzuteilen.

Für das leibliche Wohl wird gesorgt. Eine Anmeldung unter
[EMAIL PROTECTED] wäre nett, damit wir genug Essen
besorgen können.

Willkommen ist jeder, der Interesse an Python hat, die Sprache
bereits nutzt oder nutzen möchte.

Aktuelle Informationen zu den Treffen sind unter
http://www.python-academy.de/User-Group zu finden.

Viele Grüße
Mike


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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Have Your City Host PyCon 2010!

2008-03-08 Thread Ted Pollari
The PyCon organizers are excited to announce the start of the PyCon  
2010 planning process!

Even more importantly, we're looking for motivated local groups to  
spearhead this volunteer-run, community-based conference.

In years past, the locale for the next year was arranged about a year  
in advance. That worked while we were a smaller conference with many  
venues to choose from. PyCon 2008, to be held soon in the Chicago  
area, has over 950 registered attendees at this time. That is over one  
and a half times the number of attendees from just the year before!  
We're excited to see PyCon grow, but it also means that how we plan  
PyCon needs to change just a little bit.

The first change is a change in the timeline. Starting with PyCon  
2010, we're aiming to begin planning two years ahead. To help us do  
that, PyCon 2009 will also be held in the Chicago area, at the same  
venue as 2008.

The second change is that the bid process will not be as detail-heavy  
and will not demand as much initial work by local groups. Instead,  
we're focusing on the heart and soul of PyCon: the community of  
volunteers -- we're looking to find excited and committed groups who  
want to be the backbone of PyCon 2010. The details will be worked out  
in a collaborative process, with local groups working in conjunction  
the volunteer PyCon organizers and the Python Software Foundation's  
Conference Committee.


Still interested? Curious? Do you want PyCon 2010 hosted in your area?  
Here's what to do:

• Form a group of people interested in helping with the conference  
planning.

• If you're attending PyCon 2008, join us for a kick-off meeting over  
lunch on Saturday, March 15th.

• Make sure at least one person from your group is on the PyCon  
organizer's list[1] and, as soon as possible, announce your interest  
in submitting a bid on the list. This process should be viewed as  
cooperative -- we're here to help and encourage any group that wants  
to take on hosting PyCon.

• Finally, assemble your official bid, referring to the PyCon Bid  
Guidelines [2] for information and deadlines and submit it to the  
PyCon organizer's list before the deadline listed in the PyCon Bid  
Guidelines. Posting your bid to a publicly viewable website wouldn't  
be a bad idea either...


If you have any questions or need any help, feel free to email the  
organizer's list and ask away!


[1] http://mail.python.org/mailman/listinfo/pycon-organizers

[2] http://wiki.python.org/moin/PyConPlanning/BidRequirements


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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


ANN: PyTables 2.0.3 released

2008-03-08 Thread Francesc Altet
===
 Announcing PyTables 2.0.3
===

PyTables is a library for managing hierarchical datasets and designed to
efficiently cope with extremely large amounts of data with support for
full 64-bit file addressing.  PyTables runs on top of the HDF5 library
and NumPy package for achieving maximum throughput and convenient use.

This is a maintenance release that mainly fixes a couple of important
bugs (bad update of multidimensional columns in table objects, and
problems using large indexes in 32-bit platforms), some small
enhancements, and most importantly, support for the latest HDF5 1.8.0 
library.  Also, binaries have been compiled against the latest stable 
version of HDF5, 1.6.7, released during the past February.  Thanks to 
the broadening PyTables community for all the valuable feedback.

In case you want to know more in detail what has changed in this
version, have a look at ``RELEASE_NOTES.txt``.  Find the HTML version
for this document at:
http://www.pytables.org/moin/ReleaseNotes/Release_2.0.3

You can download a source package of the version 2.0.3 with
generated PDF and HTML docs and binaries for Windows from
http://www.pytables.org/download/stable/

For an on-line version of the manual, visit:
http://www.pytables.org/docs/manual-2.0.3

Migration Notes for PyTables 1.x users
==

If you are a user of PyTables 1.x, probably it is worth for you to look
at ``MIGRATING_TO_2.x.txt`` file where you will find directions on how
to migrate your existing PyTables 1.x apps to the 2.x versions.  You can
find an HTML version of this document at
http://www.pytables.org/moin/ReleaseNotes/Migrating_To_2.x

Resources
=

Go to the PyTables web site for more details:

http://www.pytables.org

About the HDF5 library:

http://hdfgroup.org/HDF5/

About NumPy:

http://numpy.scipy.org/

To know more about the company behind the development of PyTables, see:

http://www.carabos.com/

Acknowledgments
===

Thanks to many users who provided feature improvements, patches, bug
reports, support and suggestions.  See the ``THANKS`` file in the
distribution package for a (incomplete) list of contributors.  Many
thanks also to SourceForge who have helped to make and distribute this
package!  And last, but not least thanks a lot to the HDF5 and NumPy
(and numarray!) makers. Without them, PyTables simply would not exist.

Share your experience
=

Let us know of any bugs, suggestions, gripes, kudos, etc. you may
have.

-- 
0,0   Francesc Altet     http://www.carabos.com/
V   V   Cárabos Coop. V.   Enjoy Data
 -
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


Re: Regarding coding style

2008-03-08 Thread Steven D'Aprano
On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote:

 x = get_stuff(store)  # Get the stuff what was brought at the store.
 
 Perfect example of an unnecessary comment.  The variable and function
 names are commentary enough.

x is a terrible name. What does it mean? Nothing. There's only three 
places x is an appropriate name:

(1) A meta-syntactic variable like foo, bar, spam, ham, parrot.

(2) Library functions, where x stands for a generic argument, usually a 
number, e.g. def sin(x).

(3) Throw-away code you don't need to maintain.

The function name also doesn't explain anything. How was the stuff got? 
Was it paid for, or stolen, or picked up on consignment, or what? Compare 
the above line with:

x = get_stuff(store)  # Steal stuff from the store.

or 

x = get_stuff(store)  # Pickup the stuff from the store for disposal.
# The amount paid by the store is stored in global variable pay_received
# and the name of the employee authorizing the pickup is stored in the
# global authorized_by.


But even if you were right that the comment was unnecessary, you have 
missed my point that even single sentences can be grammatically bogus and 
the writer could learn a lot from Strunk and White or equivalent.

(Often the writer will learn bad habits, but at least they'll be 
grammatically correct bad habits.)



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


Re: Want - but cannot get - a nested class to inherit from outer class

2008-03-08 Thread castironpi
On Mar 7, 7:46 pm, DBak [EMAIL PROTECTED] wrote:
  However I can't do this, because, of course, the name Tree isn't
  available at the time that the classes _MT and _Node are defined, so
  _MT and _Node can't inherit from Tree.

Not only is the name not defined, the class doesn't even exist yet.

   Yes, but, well - it certainly isn't usable yet, but some object (that
   will be the class when it is finished) is being built (its __dict__ is
   being populated, etc.) - so there's an object pointer available inside
   the interpreter that could be put somewhere.  But this is pedantic -
   you're right, the class really isn't available until after the class
   statement.

  There is no obvious solution-- What do you mean?  If there are any at
  all, there is significant competition without clear winners.

  dict dictA:
     membA= 0
     membB= 0

  dict dictB:
     membC= 0

 Thanks for your answer.  To the extent I understand it:  There is a
 difference between the class statements I was trying to nest, with the
 inner inheriting from the outer, and your dict example.  The main
 thing is that in the class example - when the inner class is being
 built (i.e., inside its class statement's block) there is no need (as
 I understand it) for the parent class to be functional at all WHILE I
 AM DEFINING METHODS on the inner class.  Sure, if the inner class had

An interesting observation.

 But in the case I'm talking about I just want to define methods on the
 inner class, using names such that when the method is eventually
 called on an instance of the inner class the attribute lookup will
 proceed with the outer class being the inner class' parent.  Creating

There are two possibilities I'm thinking of.  In both, cases you go
back after Tree is finished executing, and inform _Node and _MT of
their parentage.  I haven't tested either.

The first is, define a metaclass that allows __mro__ (method
resolution order) to be written to.  But does the look-up get
performed on the one you define?

The second is, cache _Node and _MT during creation, and go back and
reinstantiate them.

class Tree(object):
...class _MT( metaclass= placeholder ):
..def isEmpty(self): return True
..def insert(self, X): return Tree._Node(X)
...class _Node( metaclass= placeholder ):
..def isEmpty(self): return False
..def insert(self, X): return _Node(X, self, Tree._MT())
...def __init__(): return _MT()
...def merge(self, T):
..code for merging tree T into self
Tree._MT.complete( Tree )
Tree._Node.complete( Tree )

And similarly,

class Tree(object):
   @placeholder
...class _MT():
..def isEmpty(self): return True
..def insert(self, X): return Tree._Node(X)
   @placeholder
...class _Node( metaclass= placeholder( Tree ) ):
..def isEmpty(self): return False
..def insert(self, X): return _Node(X, self, Tree._MT())
...def __init__(): return _MT()
...def merge(self, T):
..code for merging tree T into self
Tree._MT.complete( Tree )
Tree._Node.complete( Tree )

Here the last lines might read:

Tree._MT= Tree._MT.complete( Tree )
Tree._Node= Tree._Node.complete( Tree )

But maybe not.  Here's a third, actually:

class Tree( placeholder ): pass
class Tree(object, metaclass= placeholderreplace( Tree ) ):
...class _MT(Tree):
..def isEmpty(self): return True
..def insert(self, X): return Tree._Node(X)
...class _Node(Tree):
..def isEmpty(self): return False
..def insert(self, X): return _Node(X, self, Tree._MT())
...def __init__(): return _MT()
...def merge(self, T):
..code for merging tree T into self

If you're using Python -3.0, you might even be able to get away
without metaclasses on the first one, or decorators on the second one:

class Tree(object):
...class _MT():
..def isEmpty(self): return True
..def insert(self, X): return Tree._Node(X)
   _MT= placeholder( _MT )
...class _Node( metaclass= placeholder( Tree ) ):
..def isEmpty(self): return False
..def insert(self, X): return _Node(X, self, Tree._MT())
   _Node= placeholder( _Node )
...def __init__(): return _MT()
...def merge(self, T):
..code for merging tree T into self
Tree._MT.complete( Tree )
Tree._Node.complete( Tree )

And once again I'm still not sure.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Timed execution in eval

2008-03-08 Thread castironpi
On Mar 7, 9:43 pm, George Sakkis [EMAIL PROTECTED] wrote:
 On Mar 7, 11:12 am, [EMAIL PROTECTED] wrote:

  I have various bits of code I want to interpret and run at runtime in
  eval ...

 Check out these two recipes:

 - Using signals:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/307871

 - Using threads:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/483752

 the second can't interrupt code that
 doesn't release the GIL and doesn't actually kill the function after
 the timeout.

Mine doesn't either, plus you need a C compiler.  I also learned today
that one of the import statements doesn't find the dll on Py 3.0.

Do you have a process kill ability?  That's another way to do it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help on file storage for split multi part download

2008-03-08 Thread coolman . guron
On Mar 7, 2:14 pm, Gabriel Genellina [EMAIL PROTECTED] wrote:
 En Fri, 07 Mar 2008 04:16:42 -0200, [EMAIL PROTECTED] escribi�:



  On Mar 7, 1:38 am, Gabriel Genellina [EMAIL PROTECTED] wrote:
  En Thu, 06 Mar 2008 14:34:27 -0200, [EMAIL PROTECTED] escribi�:

   storage class which can write the file splits that are currently being
   downloaded to the disk. this is exactly what otherdownload
   accelerators do, i guess.

  Uh, unless I misundersand you, a standard file object is enough. First
  create a file with the required size (open(...,'wb'), seek(n-1),
  write(chr(0))). For each downloaded chunk you have to know its position
  in
  the file; then just seek() and write() it.

  BUT the thing thats going in my mind is thread safety. i plan to start
  each part of the filedownloadin a different thread. and then when
  each thread had downloaded more than 100kb (or eof or boundary
  reached) write the buffer to the disk. can this be achieved using
  mutex ? i have never shared objects between threads.

 Use a different (single) thread to write the file; the others put write
 requests on a Queue.queue object, and the writer just gets the requests
 and processes them.

  is there a way to write this without using threads at all ???

 Using asyncore, and perhaps the Twisted framework.

 --
 Gabriel Genellina

asyncore is basically a server thing right?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: distutils - Is is possible to install without the .py extensions

2008-03-08 Thread Jari Aalto
* Fri 2008-03-07 Robert Kern [EMAIL PROTECTED] gmane.comp.python.general
* Message-Id: [EMAIL PROTECTED]

 setup(name='program',
 ...
   scripts = ['program,py'],
   )
 that the the result is:

 /usr/bin/program

 instead of:

 /usr/bin/program.py

 The easiest and best way is to just rename the file in your source tree to 
 program and be done with it.
 
 Is there any other way? This is the source package that I would like
 to keep intact and just patch the setup.py

 Not really, no. Why is it so important to only patch the setup.py
 file and not any others?

It has to do with generating a diff against the original package. If
the file is moved:

mv file.py file

prior setup.py run (which, according to answers, would have a change
to scripts = ['program']), the problem is the generated diff
against original sources:

+ would flag removal of 'file.py'
+ inclusion of 'file'

The ideal would be if setup.py could do all the destination install
postwork. The generated patch would be clean and only contain
changes in setup.py.

But I understand, if distutils does not support stripping the
extensions during install. It just cacuses exra work for utility
packagers.

Jari

-- 
Welcome to FOSS revolution: we fix and modify until it shines

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


Re: islice == [::]

2008-03-08 Thread bearophileHUGS
George Sakkis:
 I had posted some time ago an OO wrapper of itertools; slice notation
 for islice was one 
 motivation:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/498272

I think I did see that, but later I forgot of it. It looks nice.
Thank you,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Timed execution in eval

2008-03-08 Thread Guilherme Polo
2008/3/7, Steven D'Aprano [EMAIL PROTECTED]:
 On Fri, 07 Mar 2008 08:12:38 -0800, alex.pedwysocki wrote:

   I have various bits of code I want to interpret and run at runtime in
   eval ...


 I hope that code doesn't contain any data coming from an untrusted user.



   I want to be able to detect if they fail with error,


 That's what try...except blocks are for.

  try:
 x = eval('1 + 1 = 2')
  except SyntaxError:
 x = 3



   I want to be able to time them,


 That's what the timeit module is for.

  If you do time them, you will find that eval(expr) is MUCH MUCH slower
  than just executing expr as normal.

   from timeit import Timer
   Timer('1+1').timeit()
  0.25557518005371094
   Timer('eval(1+1)').timeit()
  21.816912174224854

  If you use eval() a lot, you will have a SLOW program.



   and I want to be able to stop them if they run too long.


 That's tricky. As far as I know, the only way for a Python program to
  stop an arbitrary calculation after a certain period of time it to run it
  in a thread. You then monitor the elapsed time, and when the timer
  expires, ask the thread to die. And hope it listens.


Or you could use setitimer (not available for now). I opened an issue
at roundup to add setitimer and getitimer wrappers to the signal
module.
It would be great if you could test on your platform. It was done for
py3k, but could easily be back ported to python 2.6.

http://bugs.python.org/issue2240



   I cannot add code to the eval'd strings that will help me accomplish
   this.


 You can't? Why ever not?

  Note: that's almost certainly the wrong way to solve your problem, but
  I'm curious as to why you can't.



  --

 Steven

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



-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


parralel downloads

2008-03-08 Thread John Deas
Hi,

I would like to write a python script that will download a list of
files (mainly mp3s) from Internet. For this, I thought to use urllib,
with

urlopen(myUrl).read() and then writing the resulting string to a
file

my problem is that I would like to download several files at the time.
As I have not much experience in programming, could you point me the
easier ways to do this in python ?

Thanks,

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


Writing Memory to File

2008-03-08 Thread Stefan Wagner
Hi,

I'm trying to do some memory analyzing stuff, i wrote me a small .c so
far to dump the memory to a file for later analysis,
the analyzing part itself is python code.
I wonder if any of you has an idea how to dump the whole memory in
Linux/Windows from python ?
Using the .c for this somehow doesn't look right and comfy ;-)

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


Re: Want - but cannot get - a nested class to inherit from outer class

2008-03-08 Thread marek . rocki
Everybody has already explained why this doesn't work and a possible
solution using metaclasses was suggested. I tried to implement it,
ended up with monkey-patching __bases__, which is certainly an
abomination (will it be possible in python 3.0?) but seems to do the
trick.

class _InheritFromOuterClass(object):
 This class is used as a marker. 
pass

class MetaFixInheritance(type):
 This metaclass, along with ordinary class creation, changes base
of
all the inner classes (marked as inheriting from
_InheritFromOuterClass)
to the class being created. 
def __new__(self, name, bases, members):
result = type(name, bases, members)
for member in members.itervalues():
if isinstance(member, type) and issubclass(member,
_InheritFromOuterClass):
member.__bases__ = result,
return result

class Outer(object):
 Test an inner class inheriting from the outer class. Inheritance
is
monkey-patched upon creation of the outer class. 
__metaclass__ = MetaFixInheritance
class Inner(_InheritFromOuterClass):
pass
def foo(self):
return 'Outer.foo()'

inner = Outer.Inner()
print 'Inner.foo() is in fact', inner.foo()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DOM parsing not working!

2008-03-08 Thread rbossy
Quoting Mike D [EMAIL PROTECTED]:

 Hello, I've spent the morning trying to parse a simple xml file and have the
 following:
 import sys
 from xml.dom import minidom

 doc=minidom.parse('topstories.xml')

 items = doc.getElementsByTagName(item)
 text=''
 for i in items:
 t = i.firstChild
 print t.nodeName
 if t.nodeType == t.TEXT_NODE:
 print TEXT_NODE
 print t.nodeValue
 text += t.data

 print text

 I can't figure out how to print the text value for a text node type. There
 must be something obvious I'm missing, any suggestions?

Yes quite a trivial thing. t is assigned to the first child node of item
which, in your example, is a text node containg just a newline.
It will be shown if you replace your print statements with something like:

print 't.nodeValue:', t.nodeValue, '### end of t.nodeValue'
...
print 'text:', text, '### end of text'


What is that you're trying to do? Do you want to extract all text nodes inside
item?


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


Re: os.chdir

2008-03-08 Thread rbossy
Quoting Maryam Saeedi [EMAIL PROTECTED]:

 I have a problem using os.chdir on linux. What should I do if I want to
 change to root directory? The below does not work:

 os.chdir(~/dir1)

It is not mentioned in the documentation but I'm pretty sure os.dir() doesn't do
tilde expansion since this is usually performed by a shell.

You should use instead:

os.chdir(os.join(os.environ['HOME'], 'dir1'))

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


Re: os.chdir

2008-03-08 Thread Martin v. Löwis
 os.chdir(~/dir1)
 
 It is not mentioned in the documentation but I'm pretty sure os.dir() doesn't 
 do
 tilde expansion since this is usually performed by a shell.
 
 You should use instead:
 
 os.chdir(os.join(os.environ['HOME'], 'dir1'))

Or

os.chdir(os.path.expanduser(~/dir1))

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


List as FIFO in for loop

2008-03-08 Thread malkarouri
Hi everyone,

I have an algorithm in which I need to use a loop over a queue on
which I push values within the loop, sort of:

while not(q.empty()):
x = q.get()
#process x to get zero or more y's
#for each y:
q.put(y)

The easiest thing I can do is use a list as a queue and a normal for
loop:

q = [a, b, c]

for x in q:
#process x to get zero or more y's
q.append(y)

It makes me feel kind of uncomfortable, though it seems to work. The
question is: is it guaranteed to work, or does Python expect that you
wouldn't change the list in the loop?

Regards,

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


Re: os.chdir

2008-03-08 Thread rbossy
Quoting Martin v. Löwis [EMAIL PROTECTED]:

  os.chdir(~/dir1)
 
  It is not mentioned in the documentation but I'm pretty sure os.dir()
 doesn't do
  tilde expansion since this is usually performed by a shell.
 
  You should use instead:
 
  os.chdir(os.join(os.environ['HOME'], 'dir1'))

 Or

 os.chdir(os.path.expanduser(~/dir1))

Well... duh!
Thanks for reminding me.
Cheers,
RB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-08 Thread dave_mikesell
On Mar 8, 2:38 am, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Fri, 07 Mar 2008 20:57:32 -0800, dave_mikesell wrote:
  x = get_stuff(store)  # Get the stuff what was brought at the store.

  Perfect example of an unnecessary comment.  The variable and function
  names are commentary enough.

 x is a terrible name. What does it mean? Nothing.

Right, that's a problem with the code.  A comment only masks the bad
smell.  'x' should be renamed to something meaningful, obviating the
need for comments to follow it around.

 There's only three places x is an appropriate name:

 (1) A meta-syntactic variable like foo, bar, spam, ham, parrot.

 (2) Library functions, where x stands for a generic argument, usually a
 number, e.g. def sin(x).

 (3) Throw-away code you don't need to maintain.

I use single letter variables where their scope is very small.  e.g.,
tight loops, small functions,  etc.  I even use them as class members
where they make sense in the domain.  x, y, z for 3d vectors, r, g, b,
a for colors, etc.

 The function name also doesn't explain anything. How was the stuff got?
 Was it paid for, or stolen, or picked up on consignment, or what? Compare
 the above line with:

 x = get_stuff(store)  # Steal stuff from the store.

 or

 x = get_stuff(store)  # Pickup the stuff from the store for disposal.
 # The amount paid by the store is stored in global variable pay_received
 # and the name of the employee authorizing the pickup is stored in the
 # global authorized_by.

Shouldn't get_stuff's comment be with its definition?   And just
rename the function to something more meaningful, like
purchase_goods(store), or whatever.


 But even if you were right that the comment was unnecessary, you have
 missed my point that even single sentences can be grammatically bogus and
 the writer could learn a lot from Strunk and White or equivalent.

I do agree with that 100%.  It's a chore reading design and
requirements docs where I work.

My problem is with excessive comments.  Comments are pathological
liars.  They almost invariably fall out of date with the code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-08 Thread egbert
The idea of the if-else is:
.  depending on some condition either do this or do something else, 
.  don't do them both.

If you approach a loop-else with this same idea, you get:
.  depending on the loop conditions either do the loop, 
.  or do something else, but not both.

However the loop-else really works more like this:
.  try to do the loop; 
.  if it starts but is interrupted by a break,
.  then do something else as well.

So they are completely different beasts, and if you try to use
or explain the one according to the rules of the other one,
you put a serious strain on your synapses.

The explanation that the if-else and the loop-else
follow the same pattern, runs more or less like this:
.  all conditions to run the loop to its completion were met,
.  which means that the loop-condition is not met (any more),
.  which means that we must do something else.
For me that is orwellian logic: success is failure.

The loop-else mechanism is not an easy one:
earlier in this thread Carl Banks turned it into an either/or construct
by omitting the crucial break; Jeffrey Barish initially found 
the loop-else surprising; Sion Arrowsmith found it comprehensible 
only after some hard thinking (as in the last paragraph).

The culprit is of course the keyword, else.
The idea of an easy follow-up after a loop is a good one.
But we need other keywords, I think at least three of them:
.  skipped - the loop did not run at all
.  broken - the loop was interrupted (by a break) 
.  exhausted - the loop ran to completion.
The last two as suggested by Laurence Tratt in his Convergence.
e
-- 
Egbert Bouwman - Keizersgracht 197 II - 1016 DS  Amsterdam - 020 6257991

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


Re: List as FIFO in for loop

2008-03-08 Thread Roel Schroeven
malkarouri schreef:
 Hi everyone,
 
 I have an algorithm in which I need to use a loop over a queue on
 which I push values within the loop, sort of:
 
 while not(q.empty()):
 x = q.get()
 #process x to get zero or more y's
 #for each y:
 q.put(y)
 
 The easiest thing I can do is use a list as a queue and a normal for
 loop:
 
 q = [a, b, c]
 
 for x in q:
 #process x to get zero or more y's
 q.append(y)
 
 It makes me feel kind of uncomfortable, though it seems to work. The
 question is: is it guaranteed to work, or does Python expect that you
 wouldn't change the list in the loop?

Changing a loop while iterating over it is to be avoided, if possible. 
In any case, a deque is more efficient for this kind of use. I'd use it 
like this:

from collections import deque

q = deque([a, b, c])
while q:
 x = q.popleft()
 # ...
 q.append(y)

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
   -- Isaac Asimov

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


extract multiple ranges from a list

2008-03-08 Thread pi . arctan
Hi guys,

One of my many project involves working with YUV-files, where I need
to reduce
the vertical resolution with a factor of two, i.e. remove every other
scan line.
Today I'm using two for-loops in the fashion shown below

y = []
for i in range(0, width*height, width*2):
for j in range(0,width):
y.append(Y[i+j])

This approach doesn't feel very pythonic but I can't come up with a
better idea to do it.
I've tried list comprehension and map together with lambda but I can't
get a flattened list
of every other scan-line...

CIF = 352x288 items for luminance and the aim is to have the list
below:
y = [0:352 704:1056 ... ]

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


Re: Regarding coding style

2008-03-08 Thread Grant Edwards
On 2008-03-08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 The function name also doesn't explain anything. How was the stuff got?
 Was it paid for, or stolen, or picked up on consignment, or what? Compare
 the above line with:

 x = get_stuff(store)  # Steal stuff from the store.

 or

 x = get_stuff(store)  # Pickup the stuff from the store for disposal.
 # The amount paid by the store is stored in global variable pay_received
 # and the name of the employee authorizing the pickup is stored in the
 # global authorized_by.

 Shouldn't get_stuff's comment be with its definition?

Probably, but better that comment shouldn't be anywhere.

get_stuff() should be 

 1) renamed, as you state below.

 2) written such that it's obvious from reading the source code
that the amount paid is stored in the global variable
pay_received and that the name of the employee authorizing
the pickup is stored in the global authorized by.

But, it's not really fare picking on an example like that...

 And just rename the function to something more meaningful,
 like purchase_goods(store), or whatever.

 But even if you were right that the comment was unnecessary,
 you have missed my point that even single sentences can be
 grammatically bogus and the writer could learn a lot from
 Strunk and White or equivalent.

That's true.  I don't know how many times I've seen a single
sentence comment that was just plain vague and ambiguous. And
most of the time they're just plain wrong as well because the
code had been changed but nobody changed the comment (possibly
because they couldn't understand what the comment was trying to
say).

-- 
Grant Edwards   grante Yow!  I was giving HAIR
  at   CUTS to th' SAUCER PEOPLE
   visi.com... I'm CLEAN!!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't get items out of a set?

2008-03-08 Thread Alan Isaac
Cruxic wrote:

 people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )

 ... 

 p = people.get_equivalent(2)  #method doesn't exist as far as I know 

 print p.name  #prints Sue 



def get_equivalent(test, container):

  for p in container:

if p == test:

  return p



hth,

Alan Isaac





#example (note change in __eq__ to match your case; fix if nec)



class Person:

  def __init__(self, id, name):

self.id = id

self.name = name

  def __hash__(self):

return self.id

  def __eq__(self, other):

return self.id == other



people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )



get_equivalent(2,people)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extract multiple ranges from a list

2008-03-08 Thread Paul Hankin
On Mar 8, 3:28 pm, [EMAIL PROTECTED] wrote:
 Hi guys,

 One of my many project involves working with YUV-files, where I need
 to reduce
 the vertical resolution with a factor of two, i.e. remove every other
 scan line.
 Today I'm using two for-loops in the fashion shown below

 y = []
 for i in range(0, width*height, width*2):
     for j in range(0,width):
         y.append(Y[i+j])

There's nothing really wrong with your code. Maybe it's a little nicer
written like this:

y = []
for i in range(0, height, 2):
y.extend(Y[i * width + j] for j in range(width))

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


wholesale and retail nike sports shoes,nike shox,air maxss,dunks

2008-03-08 Thread 333
our website:
http://www.FASHION4BIZ.com
our MSN:[EMAIL PROTECTED]
our EMAIL:[EMAIL PROTECTED]


paypal accept,wholesale and retail accept,dropship accept

sale new Nike Sneakers,Air Jordan Sneakers,AIR FORCE 1S,Nike Dunks SB,
Bape Sta from nike outlets and factory stores, also Nike wholesale -
Jordan Shoes we supply nike sneaker jordan sneaker air force 1s ...
Featuring unique gift ideas for birthdays, weddings, anniversaries 
holidays.Nike Air Max LTD-Nike Air Max Ltd Shoes, Nike Air Max Ltd
Trainers. ... We also sale and wholesale nike shoes other styles:nike
air max - nike air max Nike Air Max - Nike Air Max TN Plus,TN
BURBERRY,Gucci,TN L.V.. NIKE TN REQUINS CHAUSSURES, neuves hommes Nike
TN basketball shoes requins Chaussures : Nike Air Max TN Plus
men's ,Nike Shox - Mens, Womens Nike Shox basketball shoes wholesale
from china Nike Shox TL NZ R4 R5 Turbo Monster Nike shoes
wholesale,Puma - Puma Shoes. Nike shoes wholesale: Puma Shoes men's
women's trainers .. Puma Shoes cheap discount shoes nike wholesale and
sale to nike shop and nike We sell Nike Air Max shoes,nike air max
trainers for running and training- Nike Air Max 360 95 97 2003 Tn Plus
Nike shoes wholesale,air max2 cb 94,air max2 cb,air ...Nike
Wholesale,Nike Sneaker, jordan Sneaker, Air Force one 1s, Dunk Dunks
Jordan Jordans Air Max Shox Rift ... Timberland. Timberland
boots,Timberland shoes, Prada wholesale, Prada sale, Prada shop, Prada
store. we wholesale and sale cheap discount Timberland men's
women's ,We Wholesale Cheap Jordan Shoes, Michael Jordan Shoes, Nike
Jordan Basketball shoes, Nike Air Jordan ... Once again, thank you for
www.fashion4biz.com


Timberland - Timberland Boots. Nike shoes wholesale: Timberland Boots
men's women's trainers sneakers basketball shoes running shoes.
Timberland Boots cheap discount Nike Air Max 90-Nike Air Max 90 Shoes,
Nike Air Max 90 trainers. ... nikeshoes Nike Air Max - Nike Air Max
90 (Note Mens model size 41 42 43 44 45 46.Nike shoes buy, nike shoes
wholesale, buy nike shoes from china nike shoes wholesale ...
www.fashhion4biz.com ,Nike Running shoes,nike shox and nike air max
Running shoes, nike shox tl nz r4 turbo monster running shoes,nike air
max tn,Puma - Puma Speed Cat. Nike shoes wholesale: Puma Speed Cat
men's women's trainers sneakers basketball shoes running shoes,Nike
Air Max 2003-Nike Air Max 2003 Trainers,Nike Air Max 2003 Shoes. ...
Nike Air Max 2003 cheap discount shoes nike wholesale and sale to nike
shop and nike store.Nike Air Max - Nike Air Max 2004 trainers. Nike
shoes wholesale: Nike Air Max ... Nike Air Max 2003 cheap discount
shoes nike wholesale and sale to nike shop and nike factory.Nike Air
Jordan 3,nike jordan 3 retro shoes,nike air jordan 3 retro sneakers,
Nike air jordan 3 shoes wholesale: Nike Air Jordan 3 men's women's
trainers sneakers ,Nike Shox - Nike Shox TL NZ R4 R5 Turbo Monster
Nike shoes wholesale. We wholesale nike shoes: Nike Shox TL, Nike Shox
NZ, Nike Shox R4, Nike Shox R5, Nike Shox Nike Air Dunk - Nike Air
Dunk High. Nike shoes wholesale: Nike Air Dunk High men's women's
trainers sneakers running shoes.Nike Air Max 97, Nike Womens Air Max
97 trainers, nike mens air max 97 trainers, nike air max 97 running
shoes sell cheap with discount,Nike Air Force 1 - Nike ... Nike Air
force 1 High cheap discount shoes nike wholesale and ... We also sale
and wholesale nike shoes other styles:nike air we sell cheap Nike Air
Max 95 shoes and trainers for womens, mens and for running, trainning,
tennis with all black color, pink color,red, blue..with discount,Nike
air jordan shoes for wholesale, We wholesale ans sale nike air jordan
Basketball shoes, buy quality of nike air jordan running shoes
trainers sneakers for our ...Nike cheap shoes, we sale nike shoes in
cheap price, buy cheap nike shoes Adidas. Adidas shoes, Adidas
wholesale, Adidas shop, Adidas store, Adidas goodyear, Adidas TMAC,
Adidas Running shoes,we wholesale and sale cheap discount Adidas.Nike
Dunk - Nike Air Dunk. Nike Dunk Air Dunk Low Mid High Nike shoes
wholesale. We wholesale Nike Dunk Air Dunk Men's Women's shoes
wholesale at cheap discount price,Nike Air Rift - Nike Rift Air Rift
Nike shoes wholesale. We wholesale nike shoes; Nike Rift shoes, Nike
Air Rift shoes.Puma - Puma Joggers. Nike shoes wholesale: Puma Joggers
men's women's trainers ... Puma Joggers cheap discount shoes nike
wholesale and sale to nike shop and nike Adidas - Adidas Shoes. Nike
shoes wholesale: Adidas Shoes men's women's trainers ... Adidas Shoes
cheap discount shoes nike wholesale and sale to nike shop and nike
Shoes. Nike Air Max. Nike Air Max TN Plus. Nike Air Max 90. Nike Air
Max 91. Nike Air Max 95 ... Nike Air force 1 Low. Nike Air force 1
High. Nike Air Jordan Nike Air Max Nike Air Max 360 95 97 2003 Tn
Plus ... Nike Air Max 360, Nike Air Max 95, Nike Air Max 97, Nike Air
Max 2003, ... www.fashion4biz.com


,Nike Air Jordan 2, Nike Jordan 2 Retro Shoes Nike Air Jordan 2 shoes
wholesale: Nike Air Jordan 2 men's women's 

Re: List as FIFO in for loop

2008-03-08 Thread duncan smith
malkarouri wrote:
 Hi everyone,
 
 I have an algorithm in which I need to use a loop over a queue on
 which I push values within the loop, sort of:
 
 while not(q.empty()):
 x = q.get()
 #process x to get zero or more y's
 #for each y:
 q.put(y)
 
 The easiest thing I can do is use a list as a queue and a normal for
 loop:
 
 q = [a, b, c]
 
 for x in q:
 #process x to get zero or more y's
 q.append(y)
 
 It makes me feel kind of uncomfortable, though it seems to work. The
 question is: is it guaranteed to work, or does Python expect that you
 wouldn't change the list in the loop?
 

I have used exactly the same approach.  I think it's a clean (even 
elegant) solution.  I'd be surprised if it ceased to work in some future 
implementation of Python, but I don't know if that's absolutely guaranteed.

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


Re: List as FIFO in for loop

2008-03-08 Thread malkarouri
On Mar 8, 3:20 pm, Roel Schroeven [EMAIL PROTECTED]
wrote:
 malkarouri schreef:



  Hi everyone,

  I have an algorithm in which I need to use a loop over a queue on
  which I push values within the loop, sort of:

  while not(q.empty()):
      x = q.get()
      #process x to get zero or more y's
      #for each y:
      q.put(y)

  The easiest thing I can do is use a list as a queue and a normal for
  loop:

  q = [a, b, c]

  for x in q:
      #process x to get zero or more y's
      q.append(y)

  It makes me feel kind of uncomfortable, though it seems to work. The
  question is: is it guaranteed to work, or does Python expect that you
  wouldn't change the list in the loop?

 Changing a loop while iterating over it is to be avoided, if possible.
 In any case, a deque is more efficient for this kind of use. I'd use it
 like this:

 from collections import deque

 q = deque([a, b, c])
 while q:
      x = q.popleft()
      # ...
      q.append(y)

 --
 The saddest aspect of life right now is that science gathers knowledge
 faster than society gathers wisdom.
    -- Isaac Asimov

 Roel Schroeven

Thanks for your response. My same feeling, avoid loop variable, but no
explicit reason.
Thanks for reminding me of the deque, which I never used before.
Alas, in terms of efficiency - which I need - I don't really need to
pop the value on the list/deque.
This additional step takes time enough to slow the loop a lot. So its
not ideal here.

Still, why avoid changing loop variable? Does python treat looping
over a list differently from looping over an iterator, where it
doesn't know if the iterator future changes while loop running?

Regards,

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


Re: List as FIFO in for loop

2008-03-08 Thread malkarouri
On Mar 8, 3:52 pm, duncan smith [EMAIL PROTECTED] wrote:
 malkarouri wrote:
  Hi everyone,

  I have an algorithm in which I need to use a loop over a queue on
  which I push values within the loop, sort of:

  while not(q.empty()):
      x = q.get()
      #process x to get zero or more y's
      #for each y:
      q.put(y)

  The easiest thing I can do is use a list as a queue and a normal for
  loop:

  q = [a, b, c]

  for x in q:
      #process x to get zero or more y's
      q.append(y)

  It makes me feel kind of uncomfortable, though it seems to work. The
  question is: is it guaranteed to work, or does Python expect that you
  wouldn't change the list in the loop?

 I have used exactly the same approach.  I think it's a clean (even
 elegant) solution.  I'd be surprised if it ceased to work in some future
 implementation of Python, but I don't know if that's absolutely guaranteed.

 Duncan

Thanks Duncan, I think I will go ahead and use it. Though the Python
tutorial says otherwise in section 4.2:
It is not safe to modify the sequence being iterated over in the loop
(this can only happen for mutable sequence types, such as lists). If
you need to modify the list you are iterating over (for example, to
duplicate selected items) you must iterate over a copy..

More explicitly, in 7.3 of the Python Reference Manual:
Warning: There is a subtlety when the sequence is being modified by
the loop (this can only occur for mutable sequences, i.e. lists). An
internal counter is used to keep track of which item is used next, and
this is incremented on each iteration. When this counter has reached
the length of the sequence the loop terminates. This means that if the
suite deletes the current (or a previous) item from the sequence, the
next item will be skipped (since it gets the index of the current item
which has already been treated). Likewise, if the suite inserts an
item in the sequence before the current item, the current item will be
treated again the next time through the loop.
This can be interpreted as don't play with the past. However, the part
When this counter has reached the length of the sequence the loop
terminates. is interpretable as either the starting sequence length
or the running sequence length.

Testing:

In [89]: x=range(4)

In [90]: for i in x:
   : print i
   : x.append(i+4)
   : if i=8:break
   :
   :
0
1
2
3
4
5
6
7
8

So it is the running sequence length. But I am still not sure if that
is guaranteed.

Regards,

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


Re: Can't get items out of a set?

2008-03-08 Thread Cruxic
On Mar 7, 11:20 am, Raymond Hettinger [EMAIL PROTECTED] wrote:
 [Cruxic]

  Is it possible to get an object out of a set() given another object
  that has the same hash code and equality (__hash__() and __eq__()
  return the same)?

 Yes, but it requires an indirect 
 approach.http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299

 Raymond

That's a clever work around.  Thanks, Raymond.  Clearly you had a need
for this.  Do you feel it's a common need that should be submitted as
a Python feature request?  To me it seems like such a simple thing
that would increase the general utility of the set class.  I suppose I
could start another thread like feature request: New method for set -
get_equivalent.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't get items out of a set?

2008-03-08 Thread Cruxic
On Mar 8, 7:32 am, Alan Isaac [EMAIL PROTECTED] wrote:
 Cruxic wrote:
  people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )
  ...
  p = people.get_equivalent(2)  #method doesn't exist as far as I know
  print p.name  #prints Sue

 def get_equivalent(test, container):

   for p in container:

 if p == test:

   return p

 hth,

 Alan Isaac

 #example (note change in __eq__ to match your case; fix if nec)

 class Person:

   def __init__(self, id, name):

 self.id = id

 self.name = name

   def __hash__(self):

 return self.id

   def __eq__(self, other):

 return self.id == other

 people = set( [Person(1, 'Joe'), Person(2, 'Sue')] )

 get_equivalent(2,people)

That works fine for small data sets but my goal is to avoid a linear
search, instead leveraging the O(1) lookup time for a hash based set.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: parralel downloads

2008-03-08 Thread poof65
For your problem you have to use threads.

You can have more information here.
http://artfulcode.nfshost.com/files/multi-threading-in-python.html


On Sat, Mar 8, 2008 at 1:11 PM, John Deas [EMAIL PROTECTED] wrote:
 Hi,

  I would like to write a python script that will download a list of
  files (mainly mp3s) from Internet. For this, I thought to use urllib,
  with

  urlopen(myUrl).read() and then writing the resulting string to a
  file

  my problem is that I would like to download several files at the time.
  As I have not much experience in programming, could you point me the
  easier ways to do this in python ?

  Thanks,

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

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


Re: extract multiple ranges from a list

2008-03-08 Thread Peter Otten
[EMAIL PROTECTED] wrote:

 One of my many project involves working with YUV-files, where I need
 to reduce
 the vertical resolution with a factor of two, i.e. remove every other
 scan line.
 Today I'm using two for-loops in the fashion shown below
 
 y = []
 for i in range(0, width*height, width*2):
 for j in range(0,width):
 y.append(Y[i+j])
 
 This approach doesn't feel very pythonic but I can't come up with a
 better idea to do it.
 I've tried list comprehension and map together with lambda but I can't
 get a flattened list
 of every other scan-line...
 
 CIF = 352x288 items for luminance and the aim is to have the list
 below:
 y = [0:352 704:1056 ... ]

 width = 3; height = 5
 Y = range(width*height)
 y = []
 for i in range(0, width*height, 2*width):
... y.extend(Y[i:i+width])
...
 y
[0, 1, 2, 6, 7, 8, 12, 13, 14]

Probably more efficient, but needs numpy:

 import numpy
 width = 3
 height = 5
 Y = range(width*height)
 a = numpy.array(Y).reshape(height, width)
 a
array([[ 0,  1,  2],
   [ 3,  4,  5],
   [ 6,  7,  8],
   [ 9, 10, 11],
   [12, 13, 14]])
 b = a[::2]
 b
array([[ 0,  1,  2],
   [ 6,  7,  8],
   [12, 13, 14]])
 list(b.reshape(len(b)*width))
[0, 1, 2, 6, 7, 8, 12, 13, 14]

Peter

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


Re: float / rounding question

2008-03-08 Thread Mark Dickinson
On Mar 7, 11:23 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote:
  Sorry to come in so late in this discussion. Although it is correct to
  say that many real numbers that have an exact decimal representation
  cannot be exactly represented in binary, that is no excuse to print 53.6
  as 53.601. This is just lousy printing and the fact that
  this kind of question comes up every week shows that it is confusing to
  many people.

 Good. That's a feature, not a bug.

Even so, it's not clear that Python's current behaviour couldn't be
improved.  I have a mild dislike of the lack of consistency in the
following, which arises from Python arbitrarily stripping trailing
zeros from the result returned by the C library functions:

 10.1
10.1
 10.2
10.199
 10.3
10.301
 10.4
10.4

Piet van Oostrum's suggestion gives one nice way of dealing with
this inconsistency.  Unfortunately it doesn't look easy to
implement this in practice:  the main difficulty seems to be
that to ensure float(repr(x))==x round-tripping you'd
need to write routines to take control of both str - float and
float - str conversions, not forgetting that those routines
have to be reasonably fast, and work correctly on various
non IEEE 754 platforms as well as the usual ones.  This means
adding, maintaining and testing hundreds of lines of
complicated code,  where right now a few C library calls suffice.

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


Re: List as FIFO in for loop

2008-03-08 Thread Martin v. Löwis
 Still, why avoid changing loop variable? Does python treat looping
 over a list differently from looping over an iterator, where it
 doesn't know if the iterator future changes while loop running?

Take a look at Objects/listobject.c:listiterobject. It contains
an it_index, which is the index into the list of the current
iterator position.

So if you delete items with indices smaller than the iterator
index, the iterator index won't change, causing the iterator
to skip over elements, e.g.

L=range(10)
for i in L:
   print i
   del L[0]

Appending to lists will cause the new elements to
be iterated over later. Whether that's desirable or not depends
on the application. E.g. the following loop never terminates

L=range(10:
for i in L:
   L.append(i)

Notice that the language specification *deliberately* does not
distinguish between deletion of earlier and later items, but
makes modification of the sequence undefined behavior to allow
alternative implementations. E.g. an implementation that would
crash, erase your hard disk, or set your house in flames if you
confront it with your code still might be a conforming Python
implementation.

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


Re: parralel downloads

2008-03-08 Thread Gary Herron
poof65 wrote:
 For your problem you have to use threads.
   
Not at all true.  Thread provide one way to solve this, but another is 
the select function.  For this simple case, select() may (or may not) be 
easier to write.  Pseudo-code would look something like this:

  openSockets = list of sockets one per download file:
  while openSockets:
readySockets = select(openSockets ...) # Identifies sockets with 
data to be read
for each s in readSockets:
  read from s and do whatever with the data
  if s is at EOF: close and remove s from openSockets

That's it.  Far easier than threads.

Gary Herron

 You can have more information here.
 http://artfulcode.nfshost.com/files/multi-threading-in-python.html


 On Sat, Mar 8, 2008 at 1:11 PM, John Deas [EMAIL PROTECTED] wrote:
   
 Hi,

  I would like to write a python script that will download a list of
  files (mainly mp3s) from Internet. For this, I thought to use urllib,
  with

  urlopen(myUrl).read() and then writing the resulting string to a
  file

  my problem is that I would like to download several files at the time.
  As I have not much experience in programming, could you point me the
  easier ways to do this in python ?

  Thanks,

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

 

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


SQL problem in python

2008-03-08 Thread aiwarrior
class db:
def __init__(self): #constructor
conn = sqlite3.connect(:memory:)
conn.isolation_level = None
self.cursor = conn.cursor()
self.cursor.execute(CREATE TABLE database (album,filepath))

def add_entry(self, eone , etwo): #Add entry to database
self.cursor.execute(INSERT INTO database (album,filepath)
VALUES (?,?), ( eone , etwo ) )
return 1 #TODO: exception handler

def get_mediadb(self, print_db = False):
self.cursor.execute('SELECT * FROM database')
if (print_db == True):
print self.cursor.fetchall()

def get_value( self, column ):
self.cursor.execute( SELECT (?) FROM database, column )
for n in self.cursor:
 print n

def destructor(self):
self.cursor.close()

if __name__ == __main__:
f = db()
f.add_entry( Pinkk Floyd, fdgf )
f.add_entry( Pink, fdgf )
   # f.get_mediadb(print_db=True)
f.get_value(('filepath',))
f.destructor()

When i run it the get_value() returns 'filepath' instead of the
columns. But if i dont use any variable and make the expression static
all goes on as its supposed to. What am i doing wrong?

PS: Dont mind the bad code
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to the most probable type

2008-03-08 Thread Lie
On Mar 8, 12:19 am, rockingred [EMAIL PROTECTED] wrote:
 Dates can be a pain.  I wrote my own date program, simply because
 there are so many different ways to write a date:

 Mar 8, 2008
 March 8th, 08
 03/08/08
 03-08-2008

 And so on and so forth.  The tricky bit is how to tell the difference
 between Day, Month and Year.

 I wrote a program to check the format used for a date.  I assumed that
 any 4 digits together in a single group were the year.  Then I had a
 list of Months, with the first 3 characters of each and compared that
 to the field being checked, if found, then that was the month.  Then I
 assumed any number greater than 12 was a day.  If I couldn't match
 those criteria I assumed Month Day Year (the standard at the company I
 worked for).

If humans are sometimes confused about this, how could a computer
reliably tells the correct date? I don't think it's possible (to
_reliably_ convert string to date), unless you've got an agreed
convention on how to input the date.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: float / rounding question

2008-03-08 Thread Mark Dickinson
On Mar 8, 11:34 am, Mark Dickinson [EMAIL PROTECTED] wrote:
 following, which arises from Python arbitrarily stripping trailing
 zeros from the result returned by the C library functions:

Correction: on closer examination it's not Python doing the
stripping of trailing zeros; it's the C library.

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


Re: SQL problem in python

2008-03-08 Thread Carsten Haese
On Sat, 2008-03-08 at 08:57 -0800, aiwarrior wrote:
 def get_value( self, column ):
 self.cursor.execute( SELECT (?) FROM database, column )
 for n in self.cursor:
  print n

 
 When i run it the get_value() returns 'filepath' instead of the
 columns. But if i dont use any variable and make the expression static
 all goes on as its supposed to. What am i doing wrong?

Using parameter binding wherever possible is a Good Idea, but parameter
binding can only be used to provide values. It can not be used to
provide syntax elements, table names, or column names. Basically, only
pieces that don't influence the query plan can be provided by
parameters.

To build a select query with a variable column name, you'll have to
resort to some kind of string building mechanism:

def get_value( self, column ):
self.cursor.execute( SELECT %s FROM database % column )
for n in self.cursor:
 print n

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: SQL problem in python

2008-03-08 Thread Peter Otten
aiwarrior wrote:

 When i run it the get_value() returns 'filepath' instead of the
 columns. But if i dont use any variable and make the expression static
 all goes on as its supposed to. What am i doing wrong?

 self.cursor.execute( SELECT (?) FROM database, column )

In this case you have to use Python's string interpolation, or the column
will be interpreted as a const value. The following should work:

self.cursor.execute( SELECT %s FROM database % column)

If you must sanitize the column name you can prepend something like

if column not in allowed_names: raise ValueError

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


Re: Converting a string to the most probable type

2008-03-08 Thread Lie
On Mar 8, 8:34 am, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Fri, 07 Mar 2008 16:13:04 -0800, Paul Rubin wrote:
  Pierre Quentel [EMAIL PROTECTED] writes:
  I would like to know if there is a module that converts a string to a
  value of the most probable type

      Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
       import this
      The Zen of Python, by Tim Peters
      ...
      In the face of ambiguity, refuse the temptation to guess.

 Good advice, but one which really only applies to libraries. At the
 application level, sometimes (but not always, or even most times!)
 guessing is the right thing to do.

Guessing should only be done when it have to be done. Users should
input data in an unambiguous way (such as using 4 digit years and
textual month name, this is the most preferred solution, as
flexibility is retained but ambiguity is ruled out) or be forced to
use a certain convention or be aware of how to properly input the
date. Guessing should be done at the minimum. Personally, when I'm
working with spreadsheet applications (in MS Office or OpenOffice) I
always input dates in an unambiguous way using 4-digit year and
textual month name (usually the 3-letter abbrevs for quicker
inputting), then I can confidently rely the spreadsheet to convert it
to its internal format correctly.

The general parsers like the OP wanted are easy to create if dates
aren't involved.

 E.g. spreadsheet applications don't insist on different syntax for
 strings, dates and numbers. You can use syntax to force one or the other,
 but by default the application will auto-detect what you want according
 to relatively simple, predictable and intuitive rules:

 * if the string looks like a date, it's a date;
 * if it looks like a number, it's a number;
 * otherwise it's a string.

The worse thing that can happen is when we input a date in a format we
know but the application can't parse and it consider it as a string
instead. This kind of thing can sometimes easily pass our nose. I
remembered I once formatted a column in Excel to write date with
certain style, but when I tried to input the date with the same style,
Excel can't recognize it, making the whole column rendered as useless
string and requiring me to reinput the dates again.

 Given the user-base of the application, the consequences of a wrong
 guess, and the ease of fixing it, guessing is the right thing to do.

 Auto-completion is another good example of guessing in the face of
 ambiguity. It's not guessing that is bad, but what you do with the guess.

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


Re: SQL problem in python

2008-03-08 Thread aiwarrior
Thanks a lot.
In the Python documentation, the sqlite module documentation doesn't
mention that special rule. I really thought that every variable to be
included in a query had to use that special method.

Again thanks a lot
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intelligent Date Time parsing

2008-03-08 Thread castironpi
On Mar 7, 9:23 pm, [EMAIL PROTECTED] wrote:
 I figured I might as well share the code I ended up using, in case
 anyone else wants an easy way to get strings to, for instance, SQL-
 storable datetimes.

 [EMAIL PROTECTED]:~$ cat test.py
 #!/usr/bin/python
 from datetime import datetime
 import subprocess

 def parsedate( date ):
     p = subprocess.Popen(['date','+%s.%N',--date=%s %
 date],stdout=subprocess.PIPE)
     out = float(p.stdout.read())
     return %s % datetime.fromtimestamp(out)

 [EMAIL PROTECTED]:~$ python -i test.py parsedate(today)

 '2008-03-07 21:20:31.870489' parsedate(tomorrow)

 '2008-03-08 21:20:40.516243' parsedate(next monday)

 '2008-03-10 00:00:00' parsedate(10pm last week)

 '2008-02-29 22:00:00' parsedate(last tuesday)

 '2008-03-04 00:00:00'

I am a GNU newbie.  (I know C o.)  Can you point me to a place to
find the source for 'date'?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tcp

2008-03-08 Thread Dan Stromberg
On Sun, 02 Mar 2008 23:05:27 -0500, Roy Smith wrote:

 In article
 [EMAIL PROTECTED],
  Gabriel Genellina [EMAIL PROTECTED] wrote:
 
 On 2 mar, 17:21, [EMAIL PROTECTED] wrote:
 
  This worked:
 
  import socket
  from time import time
 
  for i in range( 20 ):
      HOST = ''
      PORT = 80 #
      s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
      s.bind((HOST, PORT))
      print( 'listen' )
      s.listen(1)
      conn, addr = s.accept()
      print( 'connected', addr )
      print( conn.recv( 4096 ) ) #
      conn.send( bytes('htmlbodytest %f/body/
  html'%time(),'ascii') )
      conn.close() #
      s.close()
 
  ... and connect with a browser:  http://localhost/if it's internet
  exploder.
 
 Note that there is no need (nor is desirable) to close and rebind the
 listening socket for each connection.
 
 I'd say, nor is desirable, is an understatement.  On most systems, an
 attempt to re-bind to a given port number soon after it was unbound will
 fail (unless you utter magic ioctl incantations).  This will manifest
 itself in the s.bind() call raising an exception on the *second* pass
 through the loop.

I believe the incantation may be setsockopt(), not ioctl(), but if 
there's an ioctl() way of doing it, i'd be interested in seeing it.

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

Re: Regarding coding style

2008-03-08 Thread castironpi
On Mar 8, 9:31 am, Grant Edwards [EMAIL PROTECTED] wrote:
 On 2008-03-08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

  The function name also doesn't explain anything. How was the stuff got?
  Was it paid for, or stolen, or picked up on consignment, or what? Compare
  the above line with:

  x = get_stuff(store)  # Steal stuff from the store.

  or

  x = get_stuff(store)  # Pickup the stuff from the store for disposal.
  # The amount paid by the store is stored in global variable pay_received
  # and the name of the employee authorizing the pickup is stored in the
  # global authorized_by.

  Shouldn't get_stuff's comment be with its definition?

 Probably, but better that comment shouldn't be anywhere.

 get_stuff() should be

  1) renamed, as you state below.

  2) written such that it's obvious from reading the source code
     that the amount paid is stored in the global variable
     pay_received and that the name of the employee authorizing
     the pickup is stored in the global authorized by.

 But, it's not really fare picking on an example like that...

  And just rename the function to something more meaningful,
  like purchase_goods(store), or whatever.
  But even if you were right that the comment was unnecessary,
  you have missed my point that even single sentences can be
  grammatically bogus and the writer could learn a lot from
  Strunk and White or equivalent.

 That's true.  I don't know how many times I've seen a single
 sentence comment that was just plain vague and ambiguous. And
 most of the time they're just plain wrong as well because the
 code had been changed but nobody changed the comment (possibly
 because they couldn't understand what the comment was trying to
 say).

There are bad comments and bad variable names.

fcrg= dothingthatgoesplace( qkjwvm ).  # that thing I talked about
# in last Tuesday's code for searching qkjwvm and returning its
attribute.

Does one side of this hold that there are no -good- comments?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-08 Thread Lie
Personally I preferred a code that has chosen good names but have
little or no comments compared to codes that makes bad names and have
twenty pages of comments to read and understand what it's about.
Personally, I think comments should be made as short and as concise as
possible and codes should try to be self-understandable if the
comments aren't accessible.
-- 
http://mail.python.org/mailman/listinfo/python-list


Help xxx.py Program Recognition problem

2008-03-08 Thread crashbangboom
Hi...

I was using Python 2.4 and installed 2.5...I copied all my .py files
from the Python24\ root directory to the Python25\ root
directory...when I try to run them by double clicking I get:
X.py is not a valid Win32 application...

Also, the files do not appear to be associated with python...?

I can run them from IDLE...but that is it...

How do I fix this...?

Thanks..

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


Re: What is a class?

2008-03-08 Thread castironpi
On Mar 7, 6:16 am, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote:
  you
  could say exec( open( 'modA.py' ).read() ) == import modA

 Yes, you could say that, but you'd be wrong. Please test your code before
 making such claims in the future.

Aye aye.  -1 response not phrased in the form of a question.

Is it correct that exec( open( 'modA.py' ).read() ) -and- from modA
import * create effectively same results, such as in the remaning
program not checking __module__ attributes?

Is there a slight modification of both sides that does cover a non-
trivial volume of programs, such as maybe,
exec( open( 'modA.py' ).read(), locals= dict( __module__= 'modA' ) ) -
and- from modA import *, or something?  I notice that

from toimp import *
f()

exec( open( 'toimp.py' ).read() )
f()

generate the same output so far.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Intelligent Date Time parsing

2008-03-08 Thread Tim Chase
 I am a GNU newbie.  (I know C o.)  Can you point me to a
 place to find the source for 'date'?

It's part of the GNU Coreutils:

http://ftp.gnu.org/gnu/coreutils/

Within the file, you're likely interested in lib/getdate.*

It helps if you have a working knowledge of Yacc.

-tkc


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


Re: Difference between 'function' and 'method'

2008-03-08 Thread castironpi
On Mar 7, 1:34 pm, [EMAIL PROTECTED] wrote:
 On Mar 7, 6:44 am, Sion Arrowsmith [EMAIL PROTECTED]
 wrote:

  Gabriel Genellina [EMAIL PROTECTED] wrote:
  En Thu, 06 Mar 2008 23:46:43 -0200, [EMAIL PROTECTED] escribi�:
   [ ... ]
  You may look at the SimpleXMLRPCServer class and see how it implements  
  introspection. It's rather easy (and doesn't require metaclasses nor  
  decorators nor any other fancy stuff; I think it works the same since  
  Python 2.1). Apparently you're doing a similar thing, but using pickles  
  instead of xmlrpc.

  It's not that difficult to graft pickles into SimpleXMLRPCServer --
  I've done it, and if you're trying to sling large data structures
  over the connection it's a massive performance win (even with
  sgmlop in place to speed up XML parsing).
     her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump

 Yeah, but I'd be grafting a non-blocking RPC sequence too.

 -Instantiate- attributes of ISS upon instantiation.

 class C:
   d= D

 c= C()
 assert isinstance( c.d, D )
 assert c.d is c.d

 Which ones?

Two options: instantiate all attributes, or ones with a certain
property, such as name or superclass.

class C:
   inst_d= D
   #actually gets bound to 'd', optionally

class C:
   d= inst( D )

I think what I'm looking for is an attribute wrapper.

class C:
   @inst
   d= D

But the closest the syntax goes is:

class C:
   class d( D ): pass

(which takes us back to one of Steven's posts some days ago.)  ( def
f(x=None):/class C:/x= X/return C. ) and the d= inst( D ) solution.)

You either need to assign something to assign something to its name,

class C:
   d= X

or declare it, but that only allows def and class statements
(correct?).

class C:
   attr d: D

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


Re: multiplication of lists of strings

2008-03-08 Thread castironpi
On Mar 5, 2:16 am, Bruno Desthuilliers bruno.
[EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] a écrit :
 (snip)

  That reminds me:  Is there a generic 'relation' pattern/recipie, such
  as finding a computer that's paired with multiple users, each of who
  are paired with multiple computers, without maintaining dual-
  associativity?

 Yes : use a relational database.

No performance hit.  Can I write an ad hoc relational class structure?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a string to the most probable type

2008-03-08 Thread Pierre Quentel
  def convert(x):

         if '.' in x:
                 try: return float(x)
                 except ValueError: return x
         else:
                 try: return int(x)
                 except: return x

  convert('123')
 123
  convert('123.99')
 123.98
  convert('hello')

Hi,

That's fine for people who write floats with a . ; but others learn
to enter them with ,

For the same float, the French write the literal 123.456.789,99 when
others write 123,456,789.99 ; for us, today is 8/3/2008 (or
08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8

Popular spreadsheets know how to guess literals ; if the guess is
not correct users can usually specify the pattern to use. My question
was just to know if something similar had already been developed in
Python ; I understand that the answer is no

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


Re: multiplication of lists of strings

2008-03-08 Thread castironpi
On Mar 8, 12:04 pm, [EMAIL PROTECTED] wrote:
 On Mar 5, 2:16 am, Bruno Desthuilliers bruno.

 [EMAIL PROTECTED] wrote:
  [EMAIL PROTECTED] a écrit :
  (snip)

   That reminds me:  Is there a generic 'relation' pattern/recipie, such
   as finding a computer that's paired with multiple users, each of who
   are paired with multiple computers, without maintaining dual-
   associativity?

  Yes : use a relational database.

 No performance hit.  Can I write an ad hoc relational class structure?

What do you think of this solution?

http://jtauber.com/blog/2005/11/10/relational_python:_basic_class_for_relations/

http://www.google.com/search?hl=enq=python+relational+class+-database
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List as FIFO in for loop

2008-03-08 Thread rockingred
On Mar 8, 9:43 am, malkarouri [EMAIL PROTECTED] wrote:
 Hi everyone,

 I have an algorithm in which I need to use a loop over a queue on
 which I push values within the loop, sort of:

 while not(q.empty()):
     x = q.get()
     #process x to get zero or more y's
     #for each y:
     q.put(y)

 The easiest thing I can do is use a list as a queue and a normal for
 loop:

 q = [a, b, c]

 for x in q:
     #process x to get zero or more y's
     q.append(y)

 It makes me feel kind of uncomfortable, though it seems to work. The
 question is: is it guaranteed to work, or does Python expect that you
 wouldn't change the list in the loop?

 Regards,

 Muhammad Alkarouri

I think it's a bad practice to get into.  Did you intend to do the
process step again over the added variables?  If not I would set a
new variable, based on your awful naming convention, let's call it z.
Then use z.append(y) within the for loop and after you are out of your
for loop, q.append(z).
-- 
http://mail.python.org/mailman/listinfo/python-list


del class with recursive list

2008-03-08 Thread duccio
Hello!
Will someone have time to tell me why this code don't work as I expect?
And what should I do to make the del n delete all the lower nodes?  
Thanks!

class Node:
 def __init__(self):
 self.childs=[]
 def appendNode(self, n):
 self.childs.append(n)
 def __del__(self):
 print 'del', id(self)

n = Node()
for i in range(5):
 n.appendNode(Node())
for nodes in n.childs:
 nodes.appendNode(Node())

del n

print 'end'


gives this:


del 10965280
del 10965440
del 10965640
del 10965400
del 10965600
del 10965360
del 10965560
del 10965320
del 10965520
end
del 10965480
del 10965680

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


Re: SQL problem in python

2008-03-08 Thread Carsten Haese
On Sat, 2008-03-08 at 10:11 -0800, Dennis Lee Bieber wrote:
 On Sat, 8 Mar 2008 09:28:23 -0800 (PST), aiwarrior
 [EMAIL PROTECTED] declaimed the following in comp.lang.python:
 
  Thanks a lot.
  In the Python documentation, the sqlite module documentation doesn't
  mention that special rule. I really thought that every variable to be
  included in a query had to use that special method.
 
   It's not sqlite specific -- it is common to all of the db-api
 compatible adapters. 
 
   The explanation for why you were getting 'filename' (or whatever the
 field was is: parameter substitution ensures that the parameter value is
 properly quoted and escaped to be safe for use as a value.

It's called parameter binding, not parameter substitution.
Parameter binding ensures that the value is passed to the database
safely. That need not necessarily be a quoting-and-escaping exercise.
Depending on the API module, it may use a mechanism that transmits the
query string and the parameters to the database engine separately.

Also note that SQL standard doesn't even allow parameters in the
projection clause of a select statement. SQLite is just more relaxed
about the standard than for example Informix:

 import informixdb
 conn = informixdb.connect(stores_demo)
 cur = conn.cursor()
 cur.execute(select ? from customer, (customer_num,) )
Traceback (most recent call last):
  File stdin, line 1, in module
_informixdb.ProgrammingError: SQLCODE -201 in PREPARE: 
42000: Syntax error or access violation

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: del class with recursive list

2008-03-08 Thread Peter Otten
duccio wrote:

 Will someone have time to tell me why this code don't work as I expect?
 And what should I do to make the del n delete all the lower nodes?
 Thanks!
 
 class Node:
  def __init__(self):
  self.childs=[]
  def appendNode(self, n):
  self.childs.append(n)
  def __del__(self):
  print 'del', id(self)
 
 n = Node()
 for i in range(5):
  n.appendNode(Node())
 for nodes in n.childs:
  nodes.appendNode(Node())

# you forgot a reference to a child node and its child:
del nodes

 del n
 
 print 'end'
 
 
 gives this:
 
 
 del 10965280
 del 10965440
 del 10965640
 del 10965400
 del 10965600
 del 10965360
 del 10965560
 del 10965320
 del 10965520
 end
 del 10965480
 del 10965680

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


Image Libraries

2008-03-08 Thread PB
I have been using PIL for generating images, however it does not
easily support operations with transparency etc.

I tried to install aggdraw but it wouldn't compile.

Ideally I'd like something open source so I can adapt it, hopefully
mostly written in python rather than C.

Is there any other decent image libraries for python?

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


Re: Can't get items out of a set?

2008-03-08 Thread Raymond Hettinger
   Is it possible to get an object out of a set() given another object
   that has the same hash code and equality (__hash__() and __eq__()
   return the same)?

  Yes, but it requires an indirect 
  approach.http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/499299

  Raymond

 That's a clever work around.  Thanks, Raymond.  Clearly you had a need
 for this.  Do you feel it's a common need that should be submitted as
 a Python feature request?  To me it seems like such a simple thing
 that would increase the general utility of the set class.  I suppose I
 could start another thread like feature request: New method for set -
 get_equivalent.

Glad you liked the recipe. :-)  FWIW, it is not specific to sets. The
recipe works with any container including dictionaries and lists.  The
approach is easily extended to any situation with equality testing.
For example, it can be used with list.remove(x) to find the identity
of the removed object.

Long ago, I rejected adding get_equivalent() to the set API.  The
existing API has a near zero learning curve and it would be nice to
keep it that way.

For most use cases, the obvious, explicit approach is better.  Just
make a dictionary where the value is the canonical representative of
the equivalence class:

d = {1:1, 2:2, 3:3}
d[2.0]
   2

The intern() builtin uses this approach:

   interned = {}
   def intern(s):
if s in interned:
return interned[s]
interned[s] = s
return s

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


Re: Converting a string to the most probable type

2008-03-08 Thread castironpi
On Mar 8, 12:05 pm, Pierre Quentel [EMAIL PROTECTED] wrote:
   def convert(x):

          if '.' in x:
                  try: return float(x)
                  except ValueError: return x
          else:
                  try: return int(x)
                  except: return x

   convert('123')
  123
   convert('123.99')
  123.98
   convert('hello')

 Hi,

 That's fine for people who write floats with a . ; but others learn
 to enter them with ,

 For the same float, the French write the literal 123.456.789,99 when
 others write 123,456,789.99 ; for us, today is 8/3/2008 (or
 08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8

 Popular spreadsheets know how to guess literals ; if the guess is
 not correct users can usually specify the pattern to use. My question
 was just to know if something similar had already been developed in
 Python ; I understand that the answer is no

 Thanks,
 Pierre

In particular, you can retain access to the user/interface, and always
just query when probabilities aren't 100%.  In general, retain access
to a higher power, such as offering a hook ( def butdonotguess( raw,
guesses ):).  If you're making the decision, and a case-by-case is too
expensive, then you've made a policy, and someone gets shaft 'cause
policy.  You can throw an exception that's guaranteed to be handled
or exits.  '121212' isn't as bad as '121110'!  If you want to find out
who and when writes dates like that, apply to PR.  Obviously a person
knew at one point what the string was; how much is left?

P.S.  def welltheydidthatthistime( raw, guesses ):.
-- 
http://mail.python.org/mailman/listinfo/python-list


Intra-Package References

2008-03-08 Thread xkenneth
Does your python module have to exist in the path in order for intra-
package references to work?

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


Re: Python CGI Webpage with an Image

2008-03-08 Thread rodmc

 Is the cgi script in the same directory? The user's browser looks
 for the jpg relative to the URL it used to get the page, which in
 the case of the CGI script is the path to the script, not the
 path to the html file.


No the CGI script is in a different folder, I could move everything to
the same folder I guess.


 If server logs are hard to get or read, try my runcgi.py script:

  http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/550822

Thanks, I will try this.

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


Re: Regarding coding style

2008-03-08 Thread Grant Edwards
On 2008-03-08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

 Does one side of this hold that there are no -good- comments?

I wouldn't say there are _no_ good comments, but I would say
that 90+% of the comments I've seen in my lifetime were bad.
Most of them were bad to the extent that anybody new to the
code would be best served by deleting them before trying to
understand what was going on.

I do think that a comment at the beginning of a function/module
that describes its general purpose can be a good thing.  A
comment explaining a particularly opaque algorithm can be
useful as well.

rant
What I really can't stand are the pointy-haired comment blocks
at the beginnings of C/C++ functions that do things like tell
you the name and return type of the function and list the names
and types of the parameters. Gee, thanks.  I never could have
figured that out from looking at the source code itself. IMO,
comments explaining what the parameters are used for usually
indicates that the parameter names were poorly chosen.

I'm also a bit baffled by people who put a comment at the top
of every file that tells you what the filename is.  I sometimes
wonder how/where these files were created. All of the OSes I've
ever used had a feature called a filesystem which kept track
of info like the names of files.  It must be a bitch-and-a-half
to work on an computer that doesn't keep track of filenames and
makes the user do it.

When was the last time you thought to yourself: Gee, I wonder
what's the the name of that file over there? I guess I'd better
open the file and look at the comment at the top to see what
the filename is?
/rant

-- 
Grant Edwards   grante Yow!  .. does your DRESSING
  at   ROOM have enough ASPARAGUS?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


identifying and parsing string in text file

2008-03-08 Thread [EMAIL PROTECTED]
I have a large file that has many lines like this,

element tag=300a,0014 vr=CS vm=1 len=4
name=DoseReferenceStructureTypeSITE/element

I would like to identify the line by the tag (300a,0014) and then grab
the name (DoseReferenceStructureType) and value (SITE).

I would like to create a file that would have the structure,

 DoseReferenceStructureType = Site
 ...
 ...

Also, there is a possibility that there are multiple lines with the
same tag, but different values.  These all need to be recorded.

So far, I have a little bit of code to look at everything that is
available,

 for line in open(str(sys.argv[1])):
  i_line = line.split()
  if i_line:
   if i_line[0] == element:
a = i_line[1]
b = i_line[5]
print %s | %s %(a, b)

but do not see a clever way of doing what I would like.

Any help or guidance would be appreciated.

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


Re: SQL problem in python

2008-03-08 Thread petr . jakes . tpc
Maybe you should try SQLObject :-)

from sqlobject import *
from sqlobject.sqlbuilder import Select
#from sqlobject.sqlbuilder import *
from datetime import datetime
# === sqlite ==
#connection = connectionForURI('sqlite:///dev/shm/ourdata.db')
connection = connectionForURI('sqlite:/:memory:')
sqlhub.processConnection = connection

class MyTable(SQLObject):
album= StringCol(length=20, default=None)
filepath = StringCol(length=50, default=None)

#MyTable.dropTable(ifExists=True)
#MyTable._connection.debug = True # you can switch debuging ON, so you
can see SQL commands generated by SQLObject
MyTable.createTable(ifNotExists=True)

MyTable(album =Pinkk Floyd, filepath= qwst )
MyTable(album =Pinkk, filepath= gbfbd )
MyTable(album =Floyd, filepath= fdgf )

q = MyTable.select()
for row in q:
print row.album,  row.filepath
for row in MyTable.select(MyTable.q.album == Pinkk Floyd):
print row.album,  row.filepath

HTH

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


Re: Regarding coding style

2008-03-08 Thread castironpi
On Mar 8, 1:31 pm, Grant Edwards [EMAIL PROTECTED] wrote:
 On 2008-03-08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

  Does one side of this hold that there are no -good- comments?

 I wouldn't say there are _no_ good comments, but I would say
 that 90+% of the comments I've seen in my lifetime were bad.

Limit your comments, in other words.  emLIM-IT/em.

 comment explaining a particularly opaque algorithm can be
 useful as well.

But can't the name do that?  wink

 at the beginnings of C/C++ functions that do things like tell
 you the name and return type of the function and list the names
 and types of the parameters. Gee, thanks.  I never could have
 figured that out from looking at the source code itself. IMO,

Sometimes void*s are guaranteed to be HTHREADs.

 I'm also a bit baffled by people who put a comment at the top
 of every file that tells you what the filename is.  I sometimes
 wonder how/where these files were created. All of the OSes I've
 ever used had a feature called a filesystem which kept track
 of info like the names of files.  It must be a bitch-and-a-half
 to work on an computer that doesn't keep track of filenames and
 makes the user do it.

 When was the last time you thought to yourself: Gee, I wonder
 what's the the name of that file over there? I guess I'd better
 open the file and look at the comment at the top to see what
 the filename is?

What file did you open?

To Lie:

 Personally I preferred a code that has chosen good names but have
 little or no comments compared to codes that makes bad names and have

Personally I don't.  Show me a good one.  Until you do, it's not that
I won't like it, it's that I can't.  You know, in linguistics, there's
what's called 'code switching', which is switching between two
languages you know midstream.  People can understand 'hear' a language
but not speak it.  If you speak it, leaves open.  If comments aren't
the 'short version', then patience is the problem.  There's not one
word for lots and lots of things.  Examples on backorder.

Good comments are better than bad names.
Good names are better than bad comments.

And enter multi-word identifiers.  wink
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: identifying and parsing string in text file

2008-03-08 Thread Bernard
Hey Brian,

It seems the text you are trying to parse is similar to XML/HTML.
So I'd use BeautifulSoup[1] if I were you :)

here's a sample code for your scraping case:

from BeautifulSoup import BeautifulSoup

python

# assume the s variable has your text
s = whatever xml or html here
# turn it into a tasty  parsable soup :)
soup = BeautifulSoup(s)
# for every element tag in the soup
for el in soup.findAll(element):
 # print out its tag  name attribute plus its inner value!
 print el[tag], el[name], el.string

/python

that's it!

[1] http://www.crummy.com/software/BeautifulSoup/

On 8 mar, 14:49, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:
 I have a large file that has many lines like this,

 element tag=300a,0014 vr=CS vm=1 len=4
 name=DoseReferenceStructureTypeSITE/element

 I would like to identify the line by the tag (300a,0014) and then grab
 the name (DoseReferenceStructureType) and value (SITE).

 I would like to create a file that would have the structure,

  DoseReferenceStructureType = Site
  ...
  ...

 Also, there is a possibility that there are multiple lines with the
 same tag, but different values.  These all need to be recorded.

 So far, I have a little bit of code to look at everything that is
 available,

  for line in open(str(sys.argv[1])):
   i_line = line.split()
   if i_line:
if i_line[0] == element:
 a = i_line[1]
 b = i_line[5]
 print %s | %s %(a, b)

 but do not see a clever way of doing what I would like.

 Any help or guidance would be appreciated.

 Bryan

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


Re: identifying and parsing string in text file

2008-03-08 Thread Nemesis
[EMAIL PROTECTED] wrote:

 I have a large file that has many lines like this,

 element tag=300a,0014 vr=CS vm=1 len=4
 name=DoseReferenceStructureTypeSITE/element

 I would like to identify the line by the tag (300a,0014) and then grab
 the name (DoseReferenceStructureType) and value (SITE).

 I would like to create a file that would have the structure,

  DoseReferenceStructureType = Site
  ...
  ...

You should try with Regular Expressions or if it is something like xml there
is for sure a library you can you to parse it ...
anyway you can try something simpler like this:

   elem_dic=dict()
   for line in open(str(sys.argv[1])):
   line_splitted=line.split()
   for item in line_splitted:
   item_splitted=item.split(=)
   if len(item_splitted)1:
   elem_dic[item_splitted[0]]=item_splitted[1]

... then you have to retrieve from the dict the items you need, for example,
with the line you posted you obtain these items splitted:

['element']
['tag', '300a,0014']
['vr', 'CS']
['vm', '1']
['len', '4']
['name', 'DoseReferenceStructureTypeSITE/element']

and elem_dic will contain the last five, with the keys
'tag','vr','vm','len','name' and teh values 300a,0014 etc etc
i.e. this:

{'vr': 'CS', 'tag': '300a,0014', 'vm': '1', 'len': '4', 'name': 
'DoseReferenceStructureTypeSITE/element'}




-- 
Age is not a particularly interesting subject. Anyone can get old. All
you have to do is live long enough.

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


SV: Regarding coding style

2008-03-08 Thread K Viltersten
 What I really can't stand are the 
 pointy-haired comment blocks at the 
 beginnings of C/C++ functions that do 
 things like tell you the name and return 
 type of the function and list the names
 and types of the parameters. Gee, thanks. 
 I never could have figured that out from 
 looking at the source code itself.

Coming from C++/Java camp i can't help 
noticing that in most cases, when i'm 
using a class written by somebody else, 
i don't want to see his/her code. I only
want to know WHAT the function does (is
intended to be doing, at least).

I don't want to look at the source code 
(in some cases i can't even see the code 
because it's compiled). I only care that
when i execute

  SomeType obj = SomeType();
  obj.aggregate();

the object gets aggregated. How it's done
will be up to the author. I'm just a user 
of the product.

Now, i'm getting the signal that it's 
done in a different way in Python. Please
elaborate. I'm very new to snakeology.


--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Adjust a canvas as the window is resized

2008-03-08 Thread K Viltersten
Do i need to set a callback to a canvas
in order to listen to the root window
being resized in order to make it adjust
its contents?

If so, how? If not, how do i make the
canvas draw a line from one corner to
an other?



from Tkinter import *

class Demo(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.grid()
self.doLayout()
master.geometry(800x600)

def doLayout(self):
canvas = Canvas(self, bd = 3, bg = #93F)
canvas.grid(column = 0, row = 0)
canvas.create_line(0, 0, 100, 200, fill = #FFF)

def callback(self):
print callback from canvas

root = Tk()
demo = Demo(root)
root.mainloop()




--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: Regarding coding style

2008-03-08 Thread castironpi
On Mar 8, 1:31 pm, Grant Edwards [EMAIL PROTECTED] wrote:
 On 2008-03-08, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:

  Does one side of this hold that there are no -good- comments?

 I wouldn't say there are _no_ good comments, but I would say
 that 90+% of the comments I've seen in my lifetime were bad.

Limit your comments, in other words.  emLIM-IT/em.

 comment explaining a particularly opaque algorithm can be
 useful as well.

But can't the name do that?  wink

 at the beginnings of C/C++ functions that do things like tell
 you the name and return type of the function and list the names
 and types of the parameters. Gee, thanks.  I never could have
 figured that out from looking at the source code itself. IMO,

Sometimes void*s are guaranteed to be HTHREADs.

 I'm also a bit baffled by people who put a comment at the top
 of every file that tells you what the filename is.  I sometimes
 wonder how/where these files were created. All of the OSes I've
 ever used had a feature called a filesystem which kept track
 of info like the names of files.  It must be a bitch-and-a-half
 to work on an computer that doesn't keep track of filenames and
 makes the user do it.

 When was the last time you thought to yourself: Gee, I wonder
 what's the the name of that file over there? I guess I'd better
 open the file and look at the comment at the top to see what
 the filename is?

What file did you open?

To Lie:

 Personally I preferred a code that has chosen good names but have
 little or no comments compared to codes that makes bad names and have

Personally I don't.  Show me a good one.  Until you do, it's not that
I won't like it, it's that I can't.  You know, in linguistics, there's
what's called 'code switching', which is switching between two
languages you know midstream.  People can understand 'hear' a language
but not speak it.  If you speak it, leaves open.  If comments aren't
the 'short version', then patience is the problem.  There's not one
word for lots and lots of things.  Examples on backorder.

Good comments are better than bad names.
Good names are better than bad comments.

And enter multi-word identifiers.  wink
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: for-else

2008-03-08 Thread castironpi
 The idea of the if-else is:
 .  depending on some condition either do this or do something else,
 .  don't do them both.

yes = the loop completed.

'else' isn't rechecking a piece of the loop, it's checking the loop.
Does it test successfully--- not the loop condition, the loop?  What
is 'if a loop'?  Make sense, I hold it does.  (Holding is good--
something I can drop and give to someone else.)  If 'else' gets hit, I
didn't do the loop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't get items out of a set?

2008-03-08 Thread castironpi
 something something equivalence class.

 The intern() builtin uses this approach:

    interned = {}
    def intern(s):
         if s in interned:
             return interned[s]
         interned[s] = s
         return s

If you've seen it before, and have the old one, return the old one.
Do I have this straight?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List as FIFO in for loop

2008-03-08 Thread castironpi
 Notice that the language specification *deliberately* does not
 distinguish between deletion of earlier and later items, but
 makes modification of the sequence undefined behavior to allow
 alternative implementations. E.g. an implementation that would
 crash, erase your hard disk, or set your house in flames if you
 confront it with your code still might be a conforming Python
 implementation.

Actually, PEP 4122 makes this a SetHouseInFlames error.  Do you want
to include this one?  Just use _toaddafter= type( container )().

P.S.  Equivalence class light, on the rocks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: distutils - Is is possible to install without the .py extensions

2008-03-08 Thread Robert Kern
Jari Aalto wrote:
 * Fri 2008-03-07 Robert Kern [EMAIL PROTECTED] gmane.comp.python.general
 * Message-Id: [EMAIL PROTECTED]
 
 setup(name='program',
 ...
   scripts = ['program,py'],
   )
 that the the result is:

 /usr/bin/program

 instead of:

 /usr/bin/program.py
 The easiest and best way is to just rename the file in your source tree to 
 program and be done with it.
 Is there any other way? This is the source package that I would like
 to keep intact and just patch the setup.py
 Not really, no. Why is it so important to only patch the setup.py
 file and not any others?
 
 It has to do with generating a diff against the original package. If
 the file is moved:
 
 mv file.py file
 
 prior setup.py run (which, according to answers, would have a change
 to scripts = ['program']), the problem is the generated diff
 against original sources:
 
 + would flag removal of 'file.py'
 + inclusion of 'file'
 
 The ideal would be if setup.py could do all the destination install
 postwork. The generated patch would be clean and only contain
 changes in setup.py.
 
 But I understand, if distutils does not support stripping the
 extensions during install. It just cacuses exra work for utility
 packagers.

What build system are you using that doesn't let you execute

   cp file.py file

before running the setup.py?

-- 
Robert Kern

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

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


Re: for-else

2008-03-08 Thread Terry Reedy

egbert [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| However the loop-else really works more like this:
| .  try to do the loop;
| .  if it starts but is interrupted by a break,
| .  then do something else as well.

This is NOT how loop-else works for Python.
If you want to do something special on breaks,
put the break-only code before the break.

while loop_condition:
  loop statements
  if break_condition:
break-only statements
break
  more loop stuff

| So they are completely different beasts, and if you try to use
| or explain the one according to the rules of the other one,
| you put a serious strain on your synapses.

I did not mean to broke your brain.

| The explanation that the if-else and the loop-else
| follow the same pattern, runs more or less like this:
| .  all conditions to run the loop to its completion were met,
| .  which means that the loop-condition is not met (any more),
| .  which means that we must do something else.
| For me that is orwellian logic: success is failure.

I gave a clear and coherent explanation of how while derives from if,
and correspondingly, how while-else derives from if-else, to help those who 
want to read and write Python code.  Building on the pseudo-snippet above, 
one can write

while loop_condition:
  loop statements
  if break_condition:
break-only statements
break
  more loop stuff
else:
  completion-only statements

Python allows one to have both break-only and completion-only sections 
together in one compound statement and *without* having to fiddle with a 
special flag variable.  I am sorry if you cannot appreciate such elegance 
and can only spit on it as 'orwellian'.

If the sense of else were reversed, one would have to write the clumbsier

complete = True # though false at this point
while loop_condition:
  loop statements
  if break_condition:
complete = False
break
  more loop stuff
else:
  break-only statements
if complete:
  completion-only statements

Terry Jan Reedy



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


Re: Regarding coding style

2008-03-08 Thread dave_mikesell
On Mar 8, 1:31 pm, Grant Edwards [EMAIL PROTECTED] wrote:

hilarious rant snipped

LOL.  Thanks for the laughs.  I share your frustration.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Regarding coding style

2008-03-08 Thread dave_mikesell
On Mar 8, 2:27 pm, [EMAIL PROTECTED] wrote:

 Good comments are better than bad names.
 Good names are better than bad comments.

If you're taking the time to write good comments, why not just fix the
bad names?  The compiler/interpreter can never, ever catch bad
comments.

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


Re: SV: Regarding coding style

2008-03-08 Thread Grant Edwards
On 2008-03-08, K Viltersten [EMAIL PROTECTED] wrote:

 What I really can't stand are the pointy-haired comment blocks
 at the beginnings of C/C++ functions that do things like tell
 you the name and return type of the function and list the
 names and types of the parameters. Gee, thanks.  I never could
 have figured that out from looking at the source code itself.

 Coming from C++/Java camp i can't help noticing that in most
 cases, when i'm using a class written by somebody else, i
 don't want to see his/her code. I only want to know WHAT the
 function does (is intended to be doing, at least).

If you can't/don't look at the source file, then comments
aren't going to help (except in the case of something like
docstrings in Python).

 I don't want to look at the source code (in some cases i can't
 even see the code because it's compiled). I only care that
 when i execute

   SomeType obj = SomeType();
   obj.aggregate();

 the object gets aggregated. How it's done will be up to the
 author. I'm just a user of the product.

If you don't look at the source file, then I guess the question
of whether comments are good, bad, or indifferent is irrelevent
to you.

 Now, i'm getting the signal that it's done in a different way
 in Python.

I'm not sure how you concluded that from this thread.  

I very rarely look at the source files for the standard
library. I usually just look at the library reference document.
The only times I look at the source code are the rare occasion
that the function doesn't seem to be working correctly or when
I can't understand what the reference docs are saying.  The
cases where I suspect the former generally turn out to be the
latter.

Comments in source code are for people maintaining the code,
not for people using a standard library API (again, except for
docstrings).

-- 
Grant Edwards   grante Yow! YOU PICKED KARL
  at   MALDEN'S NOSE!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: identifying and parsing string in text file

2008-03-08 Thread Paul McGuire
On Mar 8, 2:02 pm, Nemesis [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  I have a large file that has many lines like this,

  element tag=300a,0014 vr=CS vm=1 len=4
  name=DoseReferenceStructureTypeSITE/element

  I would like to identify the line by the tag (300a,0014) and then grab
  the name (DoseReferenceStructureType) and value (SITE).

 You should try with Regular Expressions or if it is something like xml there
 is for sure a library you can you to parse it ...
snip

When it comes to parsing HTML or XML of uncontrolled origin, regular
expressions are an iffy proposition.  You'd be amazed what kind of
junk shows up inside an XML (or worse, HTML) tag.

Pyparsing includes a builtin method for constructing tag matching
parsing patterns, which you can then use to scan through the XML or
HTML source:

from pyparsing import makeXMLTags, withAttribute, SkipTo

testdata = 
blah
element tag=300a,0014 vr=CS vm=1 len=4
name=DoseReferenceStructureTypeSITE/element
element tag=300Z,0019 vr=CS vm=1 len=4
name=DoseReferenceStructureTypeSITEXXX/element
element tag=300a,0014 vr=CS vm=1 len=4
name=DoseReferenceStructureTypeSITE2/element
blahblah


elementStart,elementEnd = makeXMLTags(element)
elementStart.setParseAction(withAttribute(tag=300a,0014))
search = elementStart + SkipTo(elementEnd)(body)

for t in search.searchString(testdata):
print t.name
print t.body

Prints:

DoseReferenceStructureType
SITE
DoseReferenceStructureType
SITE2

In this case, the parse action withAttribute filters element tag
matches, accepting *only* those with the attribute tag and the value
300a,0014.  The pattern search adds on the body of the element/
element tag, and gives it the name body so it is easily accessed
after parsing is completed.

-- Paul
(More about pyparsing at http://pyparsing.wikispaces.com.)
-- 
http://mail.python.org/mailman/listinfo/python-list


off topic: 2 videos on source control and open source development

2008-03-08 Thread Aaron Watters
I just wanted to send out links to 2 informative videos
regarding open source and change control systems.

The first is Linus Torvalds on git and how it contrasts
with subversion and other approaches (where he says
some nice things about Mercurial, btw).

http://www.youtube.com/watch?v=4XpnKHJAok8

This one is about managing the community dynamics
in the subversion project.

http://video.google.nl/videoplay?docid=-4216011961522818645

It only made me a little uncomfortable at certain moments :).

Good viewing.
   -- Aaron Watters

===
http://www.xfeedme.com/nucular/pydistro.py/go?FREETEXT=mileage
-- 
http://mail.python.org/mailman/listinfo/python-list


Parse specific text in email body to CSV file

2008-03-08 Thread dpw . asdf
I have been searching all over for a solution to this. I am new to
Python, so I'm a little lost. Any pointers would be a great help. I
have a couple hundred emails that contain data I would like to
incorporate into a database or CSV file. I want to search the email
for specific text.

The emails basically look like this:



random text _important text:_15648 random text random text random text
random text
random text random text random text _important text:_15493 random text
random text
random text random text _important text:_11674 random text random text
random text
===Date: Wednesday March 5, 2008
name1: 15name5: 14

name2: 18name6: 105

name3: 64name7: 2

name4: 24name8: 13



I want information like name1: 15 to be placed into the CSV with the
name name1 and the value 15. The same goes for the date and
_important text:_15493.

I would like to use this CSV or database to plot a graph with the
data.

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


Re: List as FIFO in for loop

2008-03-08 Thread malkarouri
On Mar 8, 4:44 pm, Martin v. Löwis [EMAIL PROTECTED] wrote:
...
 Notice that the language specification *deliberately* does not
 distinguish between deletion of earlier and later items, but
 makes modification of the sequence undefined behavior to allow
 alternative implementations. E.g. an implementation that would
 crash, erase your hard disk, or set your house in flames if you
 confront it with your code still might be a conforming Python
 implementation.

Really appreciated, Martin. It was exactly the *deliberately* part I
am interested in. Settles it for me.

Thanks,

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


Re: extract multiple ranges from a list

2008-03-08 Thread pi . arctan
On 8 Mar, 17:32, Peter Otten [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  One of my many project involves working with YUV-files, where I need
  to reduce
  the vertical resolution with a factor of two, i.e. remove every other
  scan line.
  Today I'm using two for-loops in the fashion shown below

  y = []
  for i in range(0, width*height, width*2):
  for j in range(0,width):
  y.append(Y[i+j])

  This approach doesn't feel very pythonic but I can't come up with a
  better idea to do it.
  I've tried list comprehension and map together with lambda but I can't
  get a flattened list
  of every other scan-line...

  CIF = 352x288 items for luminance and the aim is to have the list
  below:
  y = [0:352 704:1056 ... ]
  width = 3; height = 5
  Y = range(width*height)
  y = []
  for i in range(0, width*height, 2*width):

 ... y.extend(Y[i:i+width])
 ... y

 [0, 1, 2, 6, 7, 8, 12, 13, 14]

 Probably more efficient, but needs numpy:

  import numpy
  width = 3
  height = 5
  Y = range(width*height)
  a = numpy.array(Y).reshape(height, width)
  a

 array([[ 0,  1,  2],
[ 3,  4,  5],
[ 6,  7,  8],
[ 9, 10, 11],
[12, 13, 14]]) b = a[::2]
  b

 array([[ 0,  1,  2],
[ 6,  7,  8],
[12, 13, 14]]) list(b.reshape(len(b)*width))

 [0, 1, 2, 6, 7, 8, 12, 13, 14]

 Peter

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


Fwd: [PyQt] Popen + poll pid

2008-03-08 Thread Kevin
Hi, I sent the question below to the wrong list.  I was wondering if  
someone here could help?


Kevin

Sent from my iPhone

Begin forwarded message:


From: Kevin [EMAIL PROTECTED]
Date: March 8, 2008 11:53:39 AM PST
To: [EMAIL PROTECTED] [EMAIL PROTECTED]
Subject: [PyQt] Popen + poll  pid



I've been trying to use the poll and pid attributes of popen to  
determine if mplayer is finished playing an audio track. I've tried  
using popen, popen2, popen3, etc but it tells me that there is no  
poll or PID module.


Could anyone help me with a proper method to determine if a process  
is running or ended so that I can move to the next track and start  
another iteration?


Either that or does someone know how to change audio cd tracks in  
mplayer slave mode?  ;)


Kevin


Sent from my iPhone
___
PyQt mailing list[EMAIL PROTECTED]
http://www.riverbankcomputing.com/mailman/listinfo/pyqt
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: List as FIFO in for loop

2008-03-08 Thread malkarouri
On Mar 8, 6:24 pm, rockingred [EMAIL PROTECTED] wrote:
 I think it's a bad practice to get into.  Did you intend to do the
 process step again over the added variables?  If not I would set a
 new variable, based on your awful naming convention, let's call it z.
 Then use z.append(y) within the for loop and after you are out of your
 for loop, q.append(z).

Thanks, rockingred, for the advice. I hope that you didn't assume that
I was a newbie, even if my question looks so. What I was trying to do
is write some Python code which I need to optimize as much as
possible. I am using Cython (Pyrex) and would probably end up
rewriting my whole module in C at one point, but it is really hard to
beat Python data structures at their home turf. So meanwhile, I am
making use of dubious optimizations - on my own responsibility. There
have been a lot of these along the years - like using variables
leaking from list expressions (not anymore). Think of it as a goto.
Yes, I intend to do the process step again over the added variables.
The suggested deque is probably the best, though I need the speed
here.
What are the variable naming you would suggest, for a throwaway -
probably anonymized for the same of publishing on the web - code?

Cheers,

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


Re: List as FIFO in for loop

2008-03-08 Thread Carl Banks
On Mar 8, 9:43 am, malkarouri [EMAIL PROTECTED] wrote:
 Hi everyone,

 I have an algorithm in which I need to use a loop over a queue on
 which I push values within the loop, sort of:

 while not(q.empty()):
 x = q.get()
 #process x to get zero or more y's
 #for each y:
 q.put(y)

Why not just do it like that?  With a few changes it'll work fine:

while q:
x = q.pop(0)
for y in process(x):
q.append(y)


And consider collections.deque for q instead of a list, though it
shouldn't make much of a difference if the queue remains small.


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


SV: SV: Regarding coding style

2008-03-08 Thread K Viltersten
 If you can't/don't look at the source file, 
 then comments aren't going to help (except 
 in the case of something like docstrings in 
 Python).

I strongly disagree. Now, perhaps we're 
talking about different things, here?
Usually, in the header file (C++), there
won't be any source code, except for 
method declarations. A common example:

/** Projects an object from 3D to 2D using
the method of Alexander The Great.
\param 3D structure to be projected
\returns 2D projection
*/
public Proj2D get2Dfrom3D(Proj3D param);

The above is, to me, very clear and 
consistent. Not to mention, easily 
handled with e.g. Doxygen to create a
readable documentation.

I don't see how this is dislikeable. Please 
explain. Perhaps the above IS what you 
ment by docstrings? For Java, one has the
JavaDocs, a great tool, provided one will
comment each method and variable used.

 Now, i'm getting the signal that it's done 
 in a different way in Python.
 
 I'm not sure how you concluded that from this thread.  

The below, more or less.   :)

What I really can't stand are the
pointy-haired comment blocks at the
beginnings of C/C++ functions that do
things like tell you the name and return
type of the function and list the names
and types of the parameters.

Please note that i DO NOT argue against one
way or another. I simply expressed surprise
since i've been tought otherwise earlier
and, maybe, there's a larger picture than
what i've seen this far. As stated before, 
snakeology is a very new area to me. Yet.   ;)

--
Regards
Konrad Viltersten

sleep- a substitute for coffee for the poor
ambition - lack of sense to be lazy

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


Re: SV: Quit-command not quiting

2008-03-08 Thread Gabriel Genellina
En Fri, 07 Mar 2008 13:56:45 -0200, K Viltersten [EMAIL PROTECTED]  
escribi�:

 The window itself vanishes if i click the
 cross in the upper-right corner but pressing
 the quit-button only makes it pressed.
 Then, the program freezes.

 How did you run it? From inside IDLE? IDLE itself is written
 using Tk, and  I think that your mainloop interferes with the
 one inside it. If you run your program from the command line
 it should work fine.

 I press F5 while in the editor window. Is there a way to run the
 program without going to the console window?
 Perhaps i'm just making things unneccesarily complicated
 and Python IS supposed to be run from console window?

No, use IDLE if you prefer, or any other editor/IDE. But in your case  
there is an unfortunate coupling between IDLE and your script. Fix: change  
the quit method as suggested in this thread:  
http://groups.google.com/group/comp.lang.python/browse_thread/thread/92bee52a3e2a325e/

 def quit(self):
 self.master.destroy()

This is OK if used on the top level widget on the application (your Demo  
class, for instance). A more general solution:

 def quit(self):
 parent = self
 while parent.winfo_class() != 'Tk':
 if parent.master is None:
 break;
 parent = parent.master
 else:
 parent.destroy()

(from  
https://sourceforge.net/tracker/index.php?func=detailaid=661324group_id=9579atid=109579
  
)

This appears to work fine. But the loop, as written, could exit without  
calling destroy() on anything; perhaps some other people knowing better  
how Tkinter and Tk work could improve it or confirm it's fine as it is.

-- 
Gabriel Genellina

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

Arbitrary precision integer arithmetic: ceiling?

2008-03-08 Thread Alasdair
I need to apply the ceiling function to arbitrary sized (long) integers. 
However, division automatically returns the type of its operands, so that,
for example: math.ceil(7/4) returns 1.  I can use float, as in:
math.ceil(7/float(4)), except that for very large integers float causes an
unacceptable loss of precision.

What is the best way of finding a ceiling of a quotient of arbitrary sized
integers?

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


Re: Arbitrary precision integer arithmetic: ceiling?

2008-03-08 Thread Paul Rubin
Alasdair [EMAIL PROTECTED] writes:
 What is the best way of finding a ceiling of a quotient of arbitrary sized
 integers?

ceiling(a/b) = (a+b-1)//b
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Arbitrary precision integer arithmetic: ceiling?

2008-03-08 Thread Robert Kern
Alasdair wrote:
 I need to apply the ceiling function to arbitrary sized (long) integers. 
 However, division automatically returns the type of its operands, so that,
 for example: math.ceil(7/4) returns 1.  I can use float, as in:
 math.ceil(7/float(4)), except that for very large integers float causes an
 unacceptable loss of precision.
 
 What is the best way of finding a ceiling of a quotient of arbitrary sized
 integers?

Use divmod() to get the quotient and the remainder at the same time. Add 1 to 
the quotient if and only the remainder is greater than 0.


In [11]: def qceil(x, y):
:  Find the ceiling of a quotient x/y.
:
: This is especially useful for very large Python long integers.
: 
: q, r = divmod(x, y)
: if r  0:
: q += 1
: return q
:

In [13]: qceil(7, 4)
Out[13]: 2

In [14]: qceil(8, 4)
Out[14]: 2

In [15]: qceil(9, 4)
Out[15]: 3

In [16]: qceil(103, 10)
Out[16]: 11L

-- 
Robert Kern

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

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


Re: SV: SV: Regarding coding style

2008-03-08 Thread Ben C
On 2008-03-08, K Viltersten [EMAIL PROTECTED] wrote:
 If you can't/don't look at the source file, 
 then comments aren't going to help (except 
 in the case of something like docstrings in 
 Python).

 I strongly disagree. Now, perhaps we're 
 talking about different things, here?
 Usually, in the header file (C++), there
 won't be any source code, except for 
 method declarations. A common example:

 /** Projects an object from 3D to 2D using
 the method of Alexander The Great.
 \param 3D structure to be projected
 \returns 2D projection
 */
 public Proj2D get2Dfrom3D(Proj3D param);

 The above is, to me, very clear and 
 consistent. Not to mention, easily 
 handled with e.g. Doxygen to create a
 readable documentation.

 I don't see how this is dislikeable. Please 
 explain. Perhaps the above IS what you 
 ment by docstrings? For Java, one has the
 JavaDocs, a great tool, provided one will
 comment each method and variable used.

The problem is that tools like Doxygen and JavaDocs generate warnings
and errors and things if everything isn't documented completely. So
you end up with a lot of silly boilerplate.

I see this kind of nonsense a lot:

/**
 * Get the width of a box
 *
 * @param box   the box
 * @returns its width
 */
extern int box_get_width(box box);

You are right that is it often useful to document what to pass to a
method and what to expect back and that if this is done well in many
cases it isn't necessary to see the implementation.

But in many other cases it's obvious, and in other cases it's obvious if
you just look at the source which you've got.

What's needed is just a bit of common sense and pragmatism: APIs need
more documentation if the source of the implementation isn't being
released with them, and some APIs just need more documentation than
others anyway.

Python docstrings, like most things in Python, demonstrate this kind of
common sense: you write what you want in them and as far as I can tell
nothing complains if you don't write them at all.

The lack of fascism is the big innovation. It sounds simple but it makes
a huge difference: it's much easier to find (and keep up to date) the
real documentation if it's not hidden in a forest of bogus
documentation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: float / rounding question

2008-03-08 Thread Roel Schroeven
Mark Dickinson schreef:
 On Mar 7, 11:23 pm, Steven D'Aprano [EMAIL PROTECTED]
 cybersource.com.au wrote:
 On Fri, 07 Mar 2008 23:12:27 +0100, Piet van Oostrum wrote:
 Sorry to come in so late in this discussion. Although it is correct to
 say that many real numbers that have an exact decimal representation
 cannot be exactly represented in binary, that is no excuse to print 53.6
 as 53.601. This is just lousy printing and the fact that
 this kind of question comes up every week shows that it is confusing to
 many people.
 Good. That's a feature, not a bug.
 
 Even so, it's not clear that Python's current behaviour couldn't be
 improved.  I have a mild dislike of the lack of consistency in the
 following, which arises from Python arbitrarily stripping trailing
 zeros from the result returned by the C library functions:
 
 10.1
 10.1
 10.2
 10.199
 10.3
 10.301
 10.4
 10.4

Actually I don't see what all the fuss is about. If you want a nicely 
rounded number, use print or str() or the % operator.

*Only* when you use repr() or when the interactive interpreter uses it 
to print the value of the expression, you get something that doesn't 
look as nice.

-- 
The saddest aspect of life right now is that science gathers knowledge
faster than society gathers wisdom.
   -- Isaac Asimov

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


Green's Function

2008-03-08 Thread olusina eric
Hi All,
  I am new to Python and trying to solve the Hamiltonian of a linear chair of 
atoms using green’s function. 
  Does anyone know any pre-existing library functions and literature that could 
be helpful?
  Thanks
  EOF 

   
-
Looking for last minute shopping deals?  Find them fast with Yahoo! Search.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: List as FIFO in for loop

2008-03-08 Thread Paul Hankin
On Mar 8, 10:42 pm, Carl Banks [EMAIL PROTECTED] wrote:
 On Mar 8, 9:43 am, malkarouri [EMAIL PROTECTED] wrote:

  Hi everyone,

  I have an algorithm in which I need to use a loop over a queue on
  which I push values within the loop, sort of:

  while not(q.empty()):
      x = q.get()
      #process x to get zero or more y's
      #for each y:
      q.put(y)

 Why not just do it like that?  With a few changes it'll work fine:

 while q:
     x = q.pop(0)
     for y in process(x):
         q.append(y)

Or (almost) equivalently...
while q:
x = q.pop(0)
q.extend(process(x))

--
Paul Hankin

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


Re: What is a class?

2008-03-08 Thread Steven D'Aprano
On Sat, 08 Mar 2008 09:52:41 -0800, castironpi wrote:

 On Mar 7, 6:16 am, Steven D'Aprano [EMAIL PROTECTED]
 cybersource.com.au wrote:
 On Thu, 06 Mar 2008 08:40:47 -0800, castironpi wrote:
  you
  could say exec( open( 'modA.py' ).read() ) == import modA

 Yes, you could say that, but you'd be wrong. Please test your code
 before making such claims in the future.
 
 Aye aye.  -1 response not phrased in the form of a question.

All the words in that sentence are English, but as a whole it makes no 
sense.


 Is it correct that exec( open( 'modA.py' ).read() ) -and- from modA
 import * create effectively same results,

You're getting closer now. (By the way, exec is a statement, so you don't 
need brackets around its arguments.)

exec open('modA.py').read()

gives *almost* the same results as

from modA import *


The differences I can think of:

(1) The exec version doesn't cache the results, so if you execute the 
line repeatedly you will execute the same code over and over again, 
possibly causing unexpected side-effects. import caches the results, and 
so will be faster.

(2) The import version may read from modA.pyc, modA.pyo or modA.so even 
if there is a modA.py file. The exec version can't import from anything 
but modA.py. 

(3) The exec version as written always puts the results in the global 
scope, even if you execute it inside a function. (In the future, from 
modA import * will be forbidden inside functions, but at the moment it 
is still legal.)

(4) The exec version doesn't search sys.path for modA; import does.

(5) The exec version can't read modules inside a zip file; import can.

There may be other differences I haven't thought of.



 such as in the remaning
 program not checking __module__ attributes?

Again, I don't understand what you are saying.


 Is there a slight modification of both sides that does cover a non-
 trivial volume of programs, such as maybe, exec( open( 'modA.py'
 ).read(), locals= dict( __module__= 'modA' ) ) - and- from modA import
 *, or something?


*Slight* modification, no.

I'm sure that with sufficient effort, you could add caching, search 
sys.path, and look inside zip files. Those three things wouldn't be 
horribly difficult, but it wouldn't be a one-liner -- off the top of my 
head, I'd guess fifty to a hundred lines of code to re-invent those 
particular wheels correctly.

However, recreating the rest of the import mechanism would be terribly 
complicated. I'm not really sure it could be done. For example, how would 
you deal with modules written in C from within Python? You'd need access 
to Python internals that, as far as I know, aren't available.



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

Re: Regarding coding style

2008-03-08 Thread Steven D'Aprano
On Sat, 08 Mar 2008 19:31:47 +, Grant Edwards wrote:

 I'm also a bit baffled by people who put a comment at the top of every
 file that tells you what the filename is.
[snip rant]

You've never printed out a source file on pieces of dead tree to read on 
the train on the way home, or in bed or the bath?

Yes, some editors will print a header or footer showing the file name, 
but not all will, or are configured to do so.


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


Re: SV: Regarding coding style

2008-03-08 Thread Steven D'Aprano
On Sat, 08 Mar 2008 21:21:48 +0100, K Viltersten wrote:

 Coming from C++/Java camp i can't help noticing that in most cases, when
 i'm using a class written by somebody else, i don't want to see his/her
 code. I only want to know WHAT the function does (is intended to be
 doing, at least).
 
 I don't want to look at the source code (in some cases i can't even see
 the code because it's compiled). I only care that when i execute
 
   SomeType obj = SomeType();
   obj.aggregate();
 
 the object gets aggregated. How it's done will be up to the author. I'm
 just a user of the product.
 
 Now, i'm getting the signal that it's done in a different way in Python.
 Please elaborate. I'm very new to snakeology.


I think even Grant would agree that when you call help(make_widget), 
you should see something like:

make_widget(styleID, material) - widget or 
raise ValueError on failure

styleID: numeric ID or string name of the widget style
material: WidgetMaterial instance or None to use default


rather than:

See source code for details.



*wink*



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


  1   2   >