Re: Dynamically created objects

2007-12-27 Thread Steven D'Aprano
On Fri, 28 Dec 2007 08:14:43 +0100, Michael Bernhard Arp Sørensen wrote:

> Hi there.
> 
> I need to create objects on the fly in my program. The names of the
> objects must be unique, obviously, and I need to put them in a list for
> later use.

Why do you think they need names? If you have them in a list, just refer 
to them by the list and index. Or a dict and a key.

E.g. instead of this:


# this doesn't work
for i in range(10):
"foo" + i = "some data here"  # variables like foo0, foo1 ...
process(foo0, foo1, foo2)



do this:

foo = []
for i in range(10):
foo.append("some data here")
process(foo[0], foo[1], foo[2])




> How do i set the name of an object if the name is stored in another
> variable?


If you really need to do this, and I doubt that you do, here's one way:


>>> bird
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'bird' is not defined
>>> globals()["bird"] = "a parrot with beautiful plumage"
>>> bird
'a parrot with beautiful plumage'


If you're tempted to try the same trick with locals(), don't bother -- it 
won't reliably work.

If you are absolutely sure that the data is safe (i.e. you control it, 
not random users via a web form) you can also use exec.



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

Re: Dynamically created objects

2007-12-27 Thread Gabriel Genellina
En Fri, 28 Dec 2007 04:14:43 -0300, Michael Bernhard Arp Sørensen  
<[EMAIL PROTECTED]> escribió:

> I need to create objects on the fly in my program. The names of the
> objects must be unique, obviously, and I need to put them in a list for
> later use.
>
> How do i set the name of an object if the name is stored in another
> variable?
>
> I've looked in the O'Reiley Python Cookbook and on google, but no joy.

Use a dictionary as a container.

py> ns = {}
py> name = "Joe"
py> o = object()
py> ns[name] = o
py> another = set("another")
py> ns["another"] = another
py> ns
{'Joe': ,
  'another': set(['a', 'e', 'h', 'o', 'n', 'r', 't'])}

-- 
Gabriel Genellina

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


Re: Happy Christmas Pythoneers

2007-12-27 Thread Hendrik van Rooyen
"Steven D'Aprano"  wrote:


> On Thu, 27 Dec 2007 09:09:49 +0200, Hendrik van Rooyen wrote:
> 
> > "Zentrader"  wrote:
> > 
> >> And if you're not a Christian it would be Type Error bug.  Anyway,
> >> happy New Years as well to all in the group.
> > 
> > Followers of Shushla celebrate the new year at the time of the spring
> > equinox.
> > 
> > This has been the cause of  bloody wars between the Northern and
> > Southern sects, as She was born in Equador.
> 
> 
> I wish you were taking the mickey, but I suspect you're not...
> 
> Got any more information? Googling doesn't come up with anything that 
> looks promising.
> 

The reason Google does not show anything is because I have not allowed
them a link into my cerebral cortex - yet.

Compliments of the season to A/all on the group.

- Hendrik


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


Dynamically created objects

2007-12-27 Thread Michael Bernhard Arp Sørensen
Hi there.

I need to create objects on the fly in my program. The names of the 
objects must be unique, obviously, and I need to put them in a list for 
later use.

How do i set the name of an object if the name is stored in another 
variable?

I've looked in the O'Reiley Python Cookbook and on google, but no joy.

Thanks in advance.

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


Re: os.fork leaving processes behind

2007-12-27 Thread Gabriel Genellina
En Thu, 27 Dec 2007 21:36:36 -0300, Falcolas <[EMAIL PROTECTED]> escribió:

> This may be more of a Linux question, but it relates to how Python
> forks...

Yes; every book describing how to use fork tells about zombie processes  
and the wait/waitpid functions. Just do the same thing in Python.

> Today, I implemented a pretty simple listener script using os.fork.
> The script runs fine, and performs as expected, but the process table
> is left with an odd entry for every fork called.

A "zombie".

> I'm running on Slackware 9, under the 2.4 kernel, Python 2.5.1.
>
> while True:
> conn, addr  = s.accept()
> if os.fork():
> continue
> else:
> handle_connection(conn)
> sys.exit(0)

I'd try to use any of the existing server implementations in  
SocketServer.py, but if you insist on using your own, look at the  
ForkingMixin class as an example of using waitpid() to avoid having zombie  
processes.

-- 
Gabriel Genellina

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


Re: Happy Christmas Pythoneers

2007-12-27 Thread Aahz
In article <[EMAIL PROTECTED]>,
Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
>On Wed, 26 Dec 2007 21:32:54 -0800, [EMAIL PROTECTED] wrote:
>> 
>> Hey, my version of the person module doesn't have an is_appropriate_sex
>> attribute, but an is_opposite_sex attribute instead. Is this a new
>> version?
>
>Generally instances use:
>
>person.is_appropriate_sex = person.is_opposite_sex
>
>but some instances define it as:
>
>person.is_appropriate_sex = not person.is_opposite_sex
>
>It's an implementation detail, you shouldn't worry about it.

Then again, some instances define it as

person.is_appropriate_sex = True
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"Typing is cheap.  Thinking is expensive."  --Roy Smith
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: list in a tuple

2007-12-27 Thread Gabriel Genellina
En Thu, 27 Dec 2007 16:38:07 -0300, <[EMAIL PROTECTED]> escribió:
> On Dec 27, 8:20 pm, Wildemar Wildenburger
> <[EMAIL PROTECTED]> wrote:
>>  >
>>
>>  From that post:
>>  > Ok, I do admit that doing
>>  >
>>  > a = ([1], 2)
>>  > a[0].append(2)
>>  >
>>  > also doesn't throw an error, but this only confuses me more.
>>  >
>> Why? You mutate thelist, but thetupledoes not change. It is still  
>> atupleof alistand an int. At least that's how I think about it, and I
>> seem to recall reading that beavior justified like this (don't ask me
>> where though (might have been "Dive Into Python", but maybe not)).
>
> That part is ok, I mean it doesn't confuse me I just wanted to say
> that this is somewhat confusing behavior.
> I agree that its not best put... But I was thinking about the last
> part of the post, the part
> that talks about trying to print a tuple and getting an error.

Instead of trying to explain it myself, I'll refer you to this little  
essay [1] by Michael Hudson including some nice ASCII art, and a long  
reply from Alex Martelli from which I'll quote just a few memorable  
paragraphs. (Just replace "dictionary" with "tuple" in your example)

"""There is [...] a huge difference
between changing an object, and changing (mutating) some
OTHER object to which the first refers.

In Bologna over 100 years ago we had a statue of a local hero
depicted pointing forwards with his finger -- presumably to
the future, but given where exactly it was placed, the locals
soon identified it as "the statue that points to Hotel
Belfiore".  The one day some enterprising developer bought
the hotel's building and restructured it -- in particular,
where the hotel used to be was now a restaurant, Da Carlo.

So, "the statue that points to Hotel Belfiore" had suddenly
become "the statue that points to Da Carlo"...!  Amazing
isn't it?  Considering that marble isn't very fluid and the
statue had not been moved or disturbed in any way...?

This is a real anecdote, by the way (except that I'm not
sure of the names of the hotel and restaurant involved --
I could be wrong on those), but I think it can still help
here.  The dictionary, or statue, has not changed at all,
even though the objects it refers/points to may have been
mutated beyond recognition, and the name people know it
by (the dictionary's string-representation) may therefore
change.  That name or representation was and is referring
to a non-intrinsic, non-persistent, "happenstance"
characteristic of the statue, or dictionary...
"""

[1] http://python.net/crew/mwh/hacks/objectthink.html

-- 
Gabriel Genellina

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


Understanding tempfile.TemporaryFile

2007-12-27 Thread Brad
Wondering if someone would help me to better understand tempfile. I 
attempt to create a tempfile, write to it, read it, but it is not 
behaving as I expect. Any tips?

 >>> x = tempfile.TemporaryFile()
 >>> print x
', mode 'w+b' at 0xab364968>
 >>> print x.read()

 >>> print len(x.read())
0
 >>> x.write("1234")
 >>> print len(x.read())
0
 >>> x.flush()
 >>> print len(x.read())
0

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


Re: Python DLL in Windows Folder

2007-12-27 Thread Ross Ridge
Ross Ridge writes:
> No, that doesn't follow from the requirements given.  The only exception
> for something that isn't a service or device driver is for backwards
> compatibility.  Also, pretty much any DLL supports side-by-side
> installation.

<[EMAIL PROTECTED]> wrote:
>Hmm. How do I have to build and install python25.dll exactly to make
>that work? How do applications have to link against it?

As I said before, I know how futile it is to argue that Python should
change it's behaviour.  I'm not going to waste my time telling you what
to do.  If you really want to know how side-by-side installation works,
you can try reading the Windows SDK documentation.

>> The backwards compatibility exception doesn't apply when the name of
>> the DLL changes.
>
>Chapter and verse of the spec?

It's a logical conclusion that results from the fact an application
can't have a dependecy on a DLL that doesn't exist yet.  Putting FOO.DLL
in a different directory than BAR.DLL was installed in won't break any
existing application that uses BAR.DLL.

>> If the name of the DLL changes, the shared location
>> its installed to can also change.
>
>No. The existing applications still require Python to be located on
>the path, even if they are rebuilt against the new DLL.  This is
>source backwards compatibility, not binary backwards compatibility.

No, simply by changing the name you've prevented backwards compatiblity
with the old DLL.  You can't argue you're trying to maintain backwards
compatibilty with an old DLL when you've already broken compatibility
with it.  Since the existing applications have to be rebuilt to use the
new DLL they also can be changed to use it from a new shared location.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding tempfile.TemporaryFile

2007-12-27 Thread Shane Geiger
Yes, I knew this.  Good call, it was just a bad copy and paste example
of lines that showed up close together in a file.  My apologies.

>> import tempfile
>> tmp = tempfile.mktemp()
>>
>> import os
>> os.remove(tmp)
>> 
>
> Not only does that not answer the Original Poster's question, but I don't 
> think it does what you seem to think it does.
>
>
>   
 tmp = tempfile.mktemp()
 tmp
 
> '/tmp/tmpZkS0Gj'
>   
 type(tmp)
 
> 
>   
 import os
 os.remove(tmp)
 
> Traceback (most recent call last):
>   File "", line 1, in 
> OSError: [Errno 2] No such file or directory: '/tmp/tmpZkS0Gj'
>
>
>
>
> You might like to read help(tempfile.mktemp).
>
> (By the way... the whole point of using tempfile is to avoid needing to 
> delete the file by hand afterwards.)
>
>
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

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


Re: Understanding tempfile.TemporaryFile

2007-12-27 Thread Steven D'Aprano
On Thu, 27 Dec 2007 21:17:01 -0600, Shane Geiger wrote:

> import tempfile
> tmp = tempfile.mktemp()
> 
> import os
> os.remove(tmp)

Not only does that not answer the Original Poster's question, but I don't 
think it does what you seem to think it does.


>>> tmp = tempfile.mktemp()
>>> tmp
'/tmp/tmpZkS0Gj'
>>> type(tmp)

>>> import os
>>> os.remove(tmp)
Traceback (most recent call last):
  File "", line 1, in 
OSError: [Errno 2] No such file or directory: '/tmp/tmpZkS0Gj'




You might like to read help(tempfile.mktemp).

(By the way... the whole point of using tempfile is to avoid needing to 
delete the file by hand afterwards.)



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


Re: Understanding tempfile.TemporaryFile

2007-12-27 Thread byte8bits
On Dec 27, 10:12 pm, John Machin <[EMAIL PROTECTED]> wrote:

> Check out the seek method.

Ah yes... thank you:

>>> import tempfile
>>> x = tempfile.TemporaryFile()
>>> x.write("test")
>>> print x.read()

>>> x.seek(0)
>>> print x.read()
test


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


Re: Understanding tempfile.TemporaryFile

2007-12-27 Thread Steven D'Aprano
On Thu, 27 Dec 2007 18:49:06 -0800, byte8bits wrote:

> Wondering if someone would help me to better understand tempfile. I
> attempt to create a tempfile, write to it, read it, but it is not
> behaving as I expect. Any tips?

You need to seek to the part of the file you want to read:

>>> x = tempfile.TemporaryFile()
>>> x.read()  # file is empty to start with
''
>>> x.write('Nobody expects the Spanish Inquisition!')
>>> x.read()  # current file is at the end of the file, so nothing to read
''
>>> x.seek(0)  # move to the beginning of the file
>>> x.read()
'Nobody expects the Spanish Inquisition!'
>>> x.seek(7)
>>> x.write('EXPECTS')
>>> x.tell()  # where are we?
14L
>>> x.seek(0)
>>> x.read()
'Nobody EXPECTS the Spanish Inquisition!'


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


Re: Taxicab Numbers

2007-12-27 Thread Steven D'Aprano
I hate having to correct myself...

On Fri, 28 Dec 2007 02:31:50 +, Steven D'Aprano wrote:

> You seem to be treating n as the number to be split into the sum of
> cubes, 

Not quite...  in your code, n appears to be the largest number to test. 
That is, if n is twelve, you test up to 12 cubed.

> but that's not what n is supposed to be. n is the number of
> distinct sums.

That remains true.

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


Re: Understanding tempfile.TemporaryFile

2007-12-27 Thread Shane Geiger
import tempfile
tmp = tempfile.mktemp()

import os
os.remove(tmp)



[EMAIL PROTECTED] wrote:
> Wondering if someone would help me to better understand tempfile. I
> attempt to create a tempfile, write to it, read it, but it is not
> behaving as I expect. Any tips?
>
>   
 x = tempfile.TemporaryFile()
 print x
 
> ', mode 'w+b' at 0xab364968>
>   
 print x.read()
 
>
>   
 print len(x.read())
 
> 0
>   
 x.write("1234")
 print len(x.read())
 
> 0
>   
 x.flush()
 print len(x.read())
 
> 0
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

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


Re: Understanding tempfile.TemporaryFile

2007-12-27 Thread John Machin
On Dec 28, 1:49 pm, [EMAIL PROTECTED] wrote:
> Wondering if someone would help me to better understand tempfile. I
> attempt to create a tempfile, write to it, read it, but it is not
> behaving as I expect. Any tips?
>
> >>> x = tempfile.TemporaryFile()
> >>> print x
>
> ', mode 'w+b' at 0xab364968>
>
> >>> print x.read()
> >>> print len(x.read())
> 0
> >>> x.write("1234")
> >>> print len(x.read())
> 0
> >>> x.flush()
> >>> print len(x.read())
>
> 0

This is nothing particular to your subject; it applies to all files.

x.read() starts reading at the CURRENT POSITION, not at the start of
the file. In all cases above, the then current position was the END of
the file, so x.read() returned a zero-length string.

Check out the seek method.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python DLL in Windows Folder

2007-12-27 Thread Martin v. Löwis
> No, that doesn't follow from the requirements given.  The only exception
> for something that isn't a service or device driver is for backwards
> compatibility.  Also, pretty much any DLL supports side-by-side
> installation.

Hmm. How do I have to build and install python25.dll exactly to make
that work? How do applications have to link against it?

> The backwards compatibility exception doesn't apply when the name of
> the DLL changes.

Chapter and verse of the spec?

> If the name of the DLL changes, the shared location
> its installed to can also change.

No. The existing applications still require Python to be located on
the path, even if they are rebuilt against the new DLL. This is
source backwards compatibility, not binary backwards compatibility.

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


Re: Pivot Table/Groupby/Sum question

2007-12-27 Thread John Machin
On Dec 28, 11:48 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Dec 28, 10:05 am, [EMAIL PROTECTED] wrote:
>
>
> > If you have any ideas about how to solve this pivot table issue, which
> > seems to be scant on Google, I'd much appreciate it.  I know I can do
> > this in Excel easily with the automated wizard, but I want to know how
> > to do it myself and format it to my needs.
>
> Watch this space.

Tested as much as you see:

8<---
class SimplePivotTable(object):

def __init__(
self,
row_order=None, col_order=None, # see example
missing=0, # what to return for an empty cell. Alternatives:
'', 0.0, None, 'NULL'
):
self.row_order = row_order
self.col_order = col_order
self.missing = missing
self.cell_dict = {}
self.row_total = {}
self.col_total = {}
self.grand_total = 0
self.headings_OK = False

def add_item(self, row_key, col_key, value):
self.grand_total += value
try:
self.col_total[col_key] += value
except KeyError:
self.col_total[col_key] = value
try:
self.cell_dict[row_key][col_key] += value
self.row_total[row_key] += value
except KeyError:
try:
self.cell_dict[row_key][col_key] = value
self.row_total[row_key] += value
except KeyError:
self.cell_dict[row_key] = {col_key: value}
self.row_total[row_key] = value

def _process_headings(self):
if self.headings_OK:
return
self.row_headings = self.row_order or
list(sorted(self.row_total.keys()))
self.col_headings = self.col_order or
list(sorted(self.col_total.keys()))
self.headings_OK = True

def get_col_headings(self):
self._process_headings()
return self.col_headings

def generate_row_info(self):
self._process_headings()
for row_key in self.row_headings:
row_dict = self.cell_dict[row_key]
row_vals = [row_dict.get(col_key, self.missing) for
col_key in self.col_headings]
yield row_key, self.row_total[row_key], row_vals

def get_col_totals(self):
self._process_headings()
row_dict = self.col_total
row_vals = [row_dict.get(col_key, self.missing) for col_key in
self.col_headings]
return self.grand_total, row_vals

if __name__ == "__main__":

data = [
['Bob', 'Morn', 240],
['Bob', 'Aft',  300],
['Joe', 'Morn',  70],
['Joe', 'Aft',   80],
['Jil', 'Morn', 100],
['Jil', 'Aft',  150],
['Bob', 'Aft',   40],
['Bob', 'Aft',5],
['Dozy', 'Aft',   1], # Dozy doesn't show up till lunch-time
]
NAME, TIME, AMOUNT = range(3)

print
ptab = SimplePivotTable(
col_order=['Morn', 'Aft'],
missing='uh-oh',
)
for s in data:
ptab.add_item(row_key=s[NAME], col_key=s[TIME],
value=s[AMOUNT])
print ptab.get_col_headings()
for x in ptab.generate_row_info():
print x
print 'Tots', ptab.get_col_totals()
8<---
-- 
http://mail.python.org/mailman/listinfo/python-list


Understanding tempfile.TemporaryFile

2007-12-27 Thread byte8bits
Wondering if someone would help me to better understand tempfile. I
attempt to create a tempfile, write to it, read it, but it is not
behaving as I expect. Any tips?

>>> x = tempfile.TemporaryFile()
>>> print x
', mode 'w+b' at 0xab364968>
>>> print x.read()

>>> print len(x.read())
0
>>> x.write("1234")
>>> print len(x.read())
0
>>> x.flush()
>>> print len(x.read())
0
-- 
http://mail.python.org/mailman/listinfo/python-list


Remove namespace declaration from ElementTree in lxml

2007-12-27 Thread Zero Piraeus
:

I want to remove an unused namespace declaration from the root element
of an ElementTree in lxml.

There doesn't seem to be any documented way to do this, so at the
moment I'm reduced to sticking the output through str.replace() ...
which is somewhat inelegant.

Is there a better way?

 -[]z.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Taxicab Numbers

2007-12-27 Thread Steven D'Aprano
On Thu, 27 Dec 2007 13:48:36 -0800, rgalgon wrote:

> I'm new to Python and have been putting my mind to learning it over my
> holiday break. I've been looking over the functional programming aspects
> of Python and I'm stuck trying to come up with some concise code to find
> Taxicab numbers (http://mathworld.wolfram.com/TaxicabNumber.html).
> 
> "Taxicab(n), is defined as the smallest number that can be expressed as
> a sum of two positive cubes in n distinct ways"
> 
> In Haskell something like this could easily be done with: cube x = x * x
> * x
> 
> taxicab n = [(cube a + cube b, (a, b), (c, d))
> | a <- [1..n],
>   b <- [(a+1)..n],
>   c <- [(a+1)..n],
>   d <- [(c+1)..n],
>   (cube a + cube b) == (cube c + cube d)]
> 
> Output::
> *Main> taxicab 10
> []
> *Main> taxicab 12
> [(1729,(1,12),(9,10))]
> *Main> taxicab 20
> [(1729,(1,12),(9,10)),(4104,(2,16),(9,15))]


I think you have COMPLETELY misunderstood what the taxicab numbers are, 
and in particular note the meaning of the argument n. I suggest you re-
read the Mathworld page:

http://mathworld.wolfram.com/TaxicabNumber.html


and pay special attention to the examples given.

You seem to be treating n as the number to be split into the sum of 
cubes, but that's not what n is supposed to be. n is the number of 
distinct sums.

Your example of taxicab 12 is wrong. According to Mathworld, only the 
first five taxicab numbers are known, and the 6th is suspected but not 
proven. The 12th taxicab number should be the number which can be written 
as twelve distinct sums of two cubes, that is something like:



Note: there is a slightly different definition of taxicab number, which 
does not take an "n" argument. In that case, if you list the taxicab 
numbers in order from smallest to largest, the 12th is 110808, not 1729.


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


Re: Python DLL in Windows Folder

2007-12-27 Thread Ross Ridge
<[EMAIL PROTECTED]> wrote:
> I think Python perfectly meets the specification (i.e. is designed
>for Windows XP) in this respect (*):
>- python25.dll is a shared component
>- it is not private to a single software vendor
>- it is not a control panel item
>- it is not a service or device driver
>- it does not support side-by-side installation
>- hence, it can be placed in the System directory.

No, that doesn't follow from the requirements given.  The only exception
for something that isn't a service or device driver is for backwards
compatibility.  Also, pretty much any DLL supports side-by-side
installation.

>The backwards compatibility with "those applications" is necessary, in
>particular with PythonWin (but also with any other software that embeds
>Python).

The backwards compatibility exception doesn't apply when the name of
the DLL changes.  If the name of the DLL changes, the shared location
its installed to can also change.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python DLL in Windows Folder

2007-12-27 Thread Martin v. Löwis
> It's one of Microsoft guidelines.  The "'Designed for Microsoft Windows
> XP' Application Specification" only allows DLLs to be installed in the
> system directory if it's required for backwards compatiblity.

I guess you are referring to 2.6 here. I think Python perfectly meets
the specification (i.e. is designed for Windows XP) in this respect (*):
- python25.dll is a shared component
- it is not private to a single software vendor
- it is not a control panel item
- it is not a service or device driver
- it does not support side-by-side installation
- hence, it can be placed in the System directory.

The backwards compatibility with "those applications" is necessary, in
particular with PythonWin (but also with any other software that embeds
Python).

Regards,
Martin

(*) Python fails to meet other requirements; in addition, it has not
formally been certified, so it is not "Designed for Microsoft Windows
XP".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic DNS with a python script

2007-12-27 Thread Delta
Some registrars provide a Dynamic DNS service. The one I use
(namecheap) provides it and I think all I had to do was edit my
ddclient.conf to use it instead of dyndns once I got my domain.
However, if you're going to use ipcheck you'll have to change some of
the args to use the registrars utilities to change your IP, I believe.

On 12/27/07, Marcelo de Moraes Serpa <[EMAIL PROTECTED]> wrote:
> Thank you!
>
> What if I would like to use my own DNS server for this (considereing I've
> got my own domain names)?
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Python-URL! - weekly Python news and links (Dec 28)

2007-12-27 Thread Gabriel Genellina
QOTW:  "However, inspection of a vast corpus of code might lead one to believe
that any commenting capability was completely unnecessary." - Jim B. Wilson

"The Python people also piped [up] to say 'everything's just fine here', but
then they always do; I really must learn that language." - Tim Bray


A variation on a classic problem: 5 Queens control an 8x8 board
without attacking themselves

http://groups.google.com/group/comp.lang.python/browse_thread/thread/151f57ac8dc8036c/

Copyright law may undermine our cultural heritage; thoughts by
Steven D'Aprano.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/f4ccf53b8da9b365/5530b9eda7d4b7ee?#5530b9eda7d4b7ee
specially:
http://groups.google.com/group/comp.lang.python/msg/35490df9d4d6d4f1

The difference between sequences, iterables, iterators and generic
containers succintly explained by Terry Reedy:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/c32908c0abc26cab/

How can an extension module use a non-standard memory manager?

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ab35cf336660b7af/

Notify an object when one of its attributes is changed
indirectly (a.x[0] = 1)

http://groups.google.com/group/comp.lang.python/browse_thread/thread/7acf713dc5d6625f/

Implementing fibers (cooperative threads)

http://groups.google.com/group/comp.lang.python/browse_thread/thread/2363b861393b1547/

Caching property values to avoid calling expensive code more than once

http://groups.google.com/group/comp.lang.python/browse_thread/thread/5b71896c06bd0f76/

"Inner" classes in Python don't behave like they do in other languages

http://groups.google.com/group/comp.lang.python/browse_thread/thread/b1176328926441fb/

The shortest explanation of what metaclasses do that I've seen!
by Steven Bethard

http://groups.google.com/group/comp.lang.python/browse_thread/thread/fe77dd2c97837541/

Monkey-patching a class that inherits from old- and
new-style base classes doesn't work as expected

http://groups.google.com/group/comp.lang.python/browse_thread/thread/7f63d6e1ad78553f/

Basic guidelines about usage of local variables, globals and
function arguments

http://groups.google.com/group/comp.lang.python/browse_thread/thread/2a632f7bb5f7097d/

.NET and Python integration

http://groups.google.com/group/comp.lang.python/browse_thread/thread/9bd3798f3f0bb4ba/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-

Re: Taxicab Numbers

2007-12-27 Thread Paul Hankin
On Dec 27, 9:48 pm, rgalgon <[EMAIL PROTECTED]> wrote:
> I'm new to Python and have been putting my mind to learning it over my
> holiday break. I've been looking over the functional programming
> aspects of Python and I'm stuck trying to come up with some concise
> code to find Taxicab numbers (http://mathworld.wolfram.com/
> TaxicabNumber.html).
>
> "Taxicab(n), is defined as the smallest number that can be expressed
> as a sum of two positive cubes in n distinct ways"
>
> In Haskell something like this could easily be done with:
> cube x = x * x * x
>
> taxicab n = [(cube a + cube b, (a, b), (c, d))
>             | a <- [1..n],
>               b <- [(a+1)..n],
>               c <- [(a+1)..n],
>               d <- [(c+1)..n],
>               (cube a + cube b) == (cube c + cube d)]
>
> Output::
> *Main> taxicab 10
> []
> *Main> taxicab 12
> [(1729,(1,12),(9,10))]
> *Main> taxicab 20
> [(1729,(1,12),(9,10)),(4104,(2,16),(9,15))]
>
> I'm looking for a succinct way of doing this in Python. I've been
> toying around with filter(),map(), and reduce() but haven't gotten
> anything half-way decent yet.
>
> So, how would you implement this taxicab(n) function in Python?
> Thanks in advance :-)

Python's list comprehensions are quite similar to haskell's, so this
code can be translated almost word-for-word.

def cube(x):
return x * x * x

def taxicab(n):
return [(cube(a) + cube(b), (a, b), (c, d))
for a in range(1, n + 1)
for b in range(a + 1, n + 1)
for c in range(a + 1, n + 1)
for d in range(c + 1, n + 1)
if cube(a) + cube(b) == cube(c) + cube(d)]

for n in (10, 12, 20):
print list(taxicab(n))

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


Re: Taxicab Numbers

2007-12-27 Thread Terry Jones
> "rgalgon" == rgalgon  <[EMAIL PROTECTED]> writes:

rgalgon> I'm new to Python and have been putting my mind to learning it
rgalgon> over my holiday break. I've been looking over the functional
rgalgon> programming aspects of Python and I'm stuck trying to come up with
rgalgon> some concise code to find Taxicab numbers
rgalgon> (http://mathworld.wolfram.com/ TaxicabNumber.html).

rgalgon> "Taxicab(n), is defined as the smallest number that can be
rgalgon> expressed as a sum of two positive cubes in n distinct ways"

rgalgon> In Haskell something like this could easily be done with:
rgalgon> cube x = x * x * x

rgalgon> taxicab n = [(cube a + cube b, (a, b), (c, d))
rgalgon> | a <- [1..n],
rgalgon> b <- [(a+1)..n],
rgalgon> c <- [(a+1)..n],
rgalgon> d <- [(c+1)..n],
rgalgon> (cube a + cube b) == (cube c + cube d)]

rgalgon> I'm looking for a succinct way of doing this in Python. I've been
rgalgon> toying around with filter(),map(), and reduce() but haven't gotten
rgalgon> anything half-way decent yet.

rgalgon> So, how would you implement this taxicab(n) function in Python?

To give a fairly literal translation of your Haskell, you could just use
this:

def cube(n): return n ** 3

def taxicab(n):
n += 1
return [(cube(a) + cube(b), (a, b), (c, d))
for a in xrange(1, n)
for b in xrange(a + 1, n)
for c in xrange(a + 1, n)
for d in xrange(c + 1, n)
if cube(a) + cube(b) == cube(c) + cube(d)]

If you print the return value of this you get the same results as your
Haskell examples. I added the following to my Python file:

if __name__ == '__main__':
import sys
print taxicab(int(sys.argv[1]))

Then I see 

$ time taxicab.py 20
[(1729, (1, 12), (9, 10)), (4104, (2, 16), (9, 15))]

real0m0.098s
user0m0.046s
sys 0m0.046s


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


Re: Pivot Table/Groupby/Sum question

2007-12-27 Thread John Machin
On Dec 28, 10:05 am, [EMAIL PROTECTED] wrote:
> On Dec 27, 10:59 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
> > On Dec 28, 4:56 am, [EMAIL PROTECTED] wrote:
>
> > > from itertools import groupby
>
> > You seem to have overlooked this important sentence in the
> > documentation: "Generally, the iterable needs to already be sorted on
> > the same key function"
>
> Yes, but I imagine this shouldn't prevent me from using and
> manipulating the data.

You imagine correctly (and pointlessly) in general; however in
particular it prevents you using itertools.groupby simplistically to
manipulate the data in the way you want to manipulate it.

> It also doesn't explain why the names get
> sorted correctly and the time does not.

The names in your example were NOT sorted, "correctly" or otherwise.
The output order is the same as the input order: Bob, Joe, Jil.

>>> seq = ['Bob', 'Joe', 'Jil']
>>> sorted(seq)
['Bob', 'Jil', 'Joe']
>>> seq == sorted(seq)
False
>>>

>
> I was trying to do this:
>
> count_tot = []
> for k, g in groupby(data, key=lambda r: r[NAME]):
> for record in g:
> count_tot.append((k,record[SALARY]))
> for i in count_tot:
> here I want to say add all the numbers for each person, but I'm
> missing something.
>
> If you have any ideas about how to solve this pivot table issue, which
> seems to be scant on Google, I'd much appreciate it.  I know I can do
> this in Excel easily with the automated wizard, but I want to know how
> to do it myself and format it to my needs.

Watch this space.


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


os.fork leaving processes behind

2007-12-27 Thread Falcolas
Hi all,

This may be more of a Linux question, but it relates to how Python
forks...

Today, I implemented a pretty simple listener script using os.fork.
The script runs fine, and performs as expected, but the process table
is left with an odd entry for every fork called.

I'm running on Slackware 9, under the 2.4 kernel, Python 2.5.1.

while True:
conn, addr  = s.accept()
if os.fork():
continue
else:
handle_connection(conn)
sys.exit(0)

Running ps -ef results in a slew of '[ python  ]' entries
(or something similar, I no longer have the actual output).

Will these clean themselves up if I leave the process running, and
what causes these?

Thanks in advance, G
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic DNS with a python script

2007-12-27 Thread Marcelo de Moraes Serpa
Thank you!

What if I would like to use my own DNS server for this (considereing I've
got my own domain names)?

On Dec 27, 2007 3:58 PM, Shane Geiger <[EMAIL PROTECTED]> wrote:

> Marcelo de Moraes Serpa wrote:
> > Hello list,
> >
> > I'd like to set up ssh access to my home computer so that I will be
> > able to access it from work - for this no problem, installing sshd is
> > straightforward.
> >
> > The issue here is that I don't have a fixed IP connection at home.
> > Also, I wouldn't like to use services such as no-ip or similar.
> >
> > What I thought was of writing a python program that would detect when
> > the internet network interface was restarted/started for the first
> > time and then update a DNS record at my DNS server where I would have
> > a subdomain that for my home machine's host.
> >
> > However, I have no idea on how I could detect if the network has been
> > restarted nor how I could update this DNS record. Any suggestion would
> > be greatly appreciated :)
> >
> > Thanks in advance,
> >
> > Marcelo.
>
> How to deal with networking depends on the system you use.  For Debian:
>
>Debian uses ifupdown (see ifup(8), ifdown(8) and interfaces(5)) to
>manipulate network interfaces. Each interface is provided with
>several scripting hooks: pre-up, up, down, and post-down. These
>hooks are available to each interface as in-line directives in
>/etc/network/interfaces and also as *.d/ directories called with
>run-parts (see run-parts(8)):
>
>   /etc/network/if-up.d/
>   /etc/network/if-pre-up.d/
>   /etc/network/if-down.d/
>   /etc/network/if-post-down.d/
>
>
>
>
> SETTING UP A DOMAIN NAME WITH DYNDNS.ORG
>
> Go to their site and set up an account.  While doing that (or perhaps
> after--I don't remember), you can choose a domain name.  You *could*
> think of what they are giving you is a subdomain--not actually a
> domain.  You will be able to choose something like foo.mine.nu where
> "foo" is the name you choose for the name of your subdomain and
> "mine.nu" is the domain they already own.  (You can choose from many
> domains they already own.)  Since they manage these domains themselves,
> they do not have to pay a registrar to set up a subdomain...and
> therefore they can give you a subdomain for free.  (Actually, I'm using
> the term "subdomain" loosely here...but I'm sure you get the point I'm
> trying to make--which is that you don't have to pay for this name.)
>
> Once you have your name (foo.mine.nu, for example), you can set up a
> program on your computer to update their DNS servers with your new
> domain name whenever it changes.
>
> --
>
>
> SETTING UP IPCHECK WITH DYNDNS.ORG
>
> I have been satisfied with my first choice (dyndns.org), so I haven't
> tried the others.  They probably work well, too.
>
> Set up an account on dyndns.org, and record the username, password, and
> domain name in your notes.  In the following examples, I use the
> following values:
>
> username:  sgeiger
> pass:  asdfasdf
> domain name:  sgeiger.mine.nu
>
>
> apt-get install ipcheck
>
> You might want to run this first so that you are in the directory cron
> will use when you run ipcheck:
> sudo su; cd ~;
>
> HERE'S HOW TO CONFIGURE IT:
> [EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py -l -r
> checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
> ipcheck.py: No ipcheck.dat file found.
> ipcheck.py: Use same command+options ONCE with --makedat to create from
> DNS lookup.
> [EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py --makedat -l -r
> checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
> ipcheck.py: ip1 looking up sgeiger.mine.nu
> ipcheck.py: result: 'sgeiger.mine.nu'[]['139.55.232.72']
> [EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py -l -r
> checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine
> .nu
> [EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py -l -r
> checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
> [EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py -l -r
> checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
> [EMAIL PROTECTED]:~$
>
> When you run this manually and it works you will see no output.
>
> To add a cron job to update this automatically once a day at 10 am:
>
> ###  Note:  This script should be run once a day from cron, like this
> (which runs it at 10:15 am every day)
> 15 10 * * * /usr/bin/python /usr/sbin/ipcheck.py -l -r
> checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
>
>
> To add another names (foobar.mine.nu):
> sudo /usr/sbin/ipcheck.py --makedat -l -r checkip.dyndns.org:8245
> shanerg rQ9ll0 sgeiger.mine.nu,foobar.mine.nu
>
> ...and then put this into the cron tab:
> 15 10 * * * /usr/bin/python /usr/sbin/ipcheck.py -l -r
> checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
>
>
>
>
> Check the mail messages on the computer you are using in case there were
> errors.
>
> Note:  This creates a file named /root/ipcheck.dat and /root/ipcheck.log
> on my comput

Re: "Impure" Python modules

2007-12-27 Thread Martin v. Löwis
> Is there some way to get a list of "impure" Python modules/extensions
> from PyPI?

Not easily. To create a full list, you will have to download all
packages, and check their respective setup.py files for occurrences
of Extension.

A subset can probably be found by looking at all packages classified
as Programming Language :: C

http://pypi.python.org/pypi?:action=browse&c=181

or Programming Language :: C++

http://pypi.python.org/pypi?:action=browse&show=all&c=183

Of course, some of those may only generate C, or deal with C in
some other sense than being written in it.

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


Re: mysqldb SELECT COUNT reurns 1

2007-12-27 Thread Ian Clark
On 2007-12-27, SMALLp <[EMAIL PROTECTED]> wrote:
> connectionString = {"host":"localhost", "user":"root", 
> "passwd":"pofuck", "db":"fileshare"}
> dataTable = "files"
> conn = mysql.connect(host=connectionString["host"],
> user=connectionString["user"], passwd=connectionString["passwd"],
> db=connectionString["db"])

Just to let you know, that last line can be rewritten as:

conn = mysql.connect(**connectionString)


Ian

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


Re: Python DLL in Windows Folder

2007-12-27 Thread Ross Ridge
Ross Ridge writes:
> Whatever you want to call it, the Python DLL is not part of the operating
> system, it's not a driver and doesn't belong in the system directory.

<[EMAIL PROTECTED]> wrote:
>Is that just your personal opinion, or a guideline from the operating
>system vendor?

It's one of Microsoft guidelines.  The "'Designed for Microsoft Windows
XP' Application Specification" only allows DLLs to be installed in the
system directory if it's required for backwards compatiblity.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pivot Table/Groupby/Sum question

2007-12-27 Thread patrick . waldo
On Dec 27, 10:59 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Dec 28, 4:56 am, [EMAIL PROTECTED] wrote:
>
> > from itertools import groupby
>
> You seem to have overlooked this important sentence in the
> documentation: "Generally, the iterable needs to already be sorted on
> the same key function"

Yes, but I imagine this shouldn't prevent me from using and
manipulating the data.  It also doesn't explain why the names get
sorted correctly and the time does not.

I was trying to do this:

count_tot = []
for k, g in groupby(data, key=lambda r: r[NAME]):
for record in g:
count_tot.append((k,record[SALARY]))
for i in count_tot:
here I want to say add all the numbers for each person, but I'm
missing something.

If you have any ideas about how to solve this pivot table issue, which
seems to be scant on Google, I'd much appreciate it.  I know I can do
this in Excel easily with the automated wizard, but I want to know how
to do it myself and format it to my needs.


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


Re: list in a tuple

2007-12-27 Thread montyphyton
Carl Banks wrote:
> On Dec 27, 12:38 pm, [EMAIL PROTECTED] wrote:
>> After some tought I must agree that this is a wart more than
>> a bug and that it will probably be best not to mess with it.
>> However, what do you guys think about the print wart in Py3k
>> described 
>> athttp://filoxus.blogspot.com/2007/12/python-3000-how-mutable-is-immuta...
>> (im not trying to advertise my blog, I just don't feel like
>> typing the whole problem all over again)?
>
>
> 1. Tuples are immutable.  None of the tuples in your example were
> modified.
>
> The behavior you want (which is not immutability of tuples, which
> Python already has, but *recursive* immutability of all objects
> contained within the tuple) is not an unreasonable thing to ask for,
> but the design of Python and common usage of tuples makes it all but
> impossible at this point.
>
> There is no general way to determine whether an object is mutable or
> not.  (Python would have to add this capability, an extremely
> substantial change, to grant your wish.  It won't happen.)

like I said, I don't think that this behavior should be changed...
therefore, no wish-granting is needed, thank you :)


>
> Tuples are used internally to represent the arguments of a function,
> which are often mutable.
>
> Tuples are sometimes used to return multiple values from a function,
> which could include mutable values.
>
> Tuples are used to specify multiple arguments to a format string, some
> of which could be mutable, though I guess this is going away in Python
> 3.
>
>
> 2. The issue with print in your example is a bug, not a wart.  It'll
> be fixed.
>
> (This is just a guess, but I think it might have something to do with
> the flux of the new bytes type.  The behavior manifested itself when
> trying to print a self-referencing structure probably only because
> that section of code was lagging behind.)
>
>
> 3. You're still top posting, which goes against this group's
> conventions and annoys quite a few people.  When you reply to a
> message, please move your cursor to below the quoted message before
> you begin typing.  Thank you

sorry for top posting...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cheat sheet

2007-12-27 Thread James Matthews
Looks good thanks!

On Dec 27, 2007 11:06 PM, Scott David Daniels <[EMAIL PROTECTED]> wrote:

> Riccardo T. wrote:
> > I wrote a little cheat sheet for this wonderful language, but because of
> > my still little experience with it, I would like to have a feedback
> > Could you have a look at it and tell me what do you think about, please?
> >
> > http://greyfox.imente.org/index.php?id=73
> >
> > --
> > GreyFox
>
> [in the .png]
>  > ...
>  > Callable types
>  >...
>  >User-definet methods
>
> I personally prefer "User-defined methods"
>
>  >...
>  >Class instances
> I'd try:
>  Class instances with a __call__ method.
>
>  > ...
>  > Classes
>  > Classes Instances
>
> This probably wants to be
>   Class Instances
>
> "file" objects are generally supposed to be built with the
> open function, not instantiated as shown.
> Also note iterating on a file gets the lines.
>
> Do you know about seq[i:] and seq[::-1]?
>
> --Scott David Daniels
> [EMAIL PROTECTED]
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: "Impure" Python modules

2007-12-27 Thread James Matthews
I don't quite understand what the word "impure" means here!

On Dec 27, 2007 10:53 PM, <[EMAIL PROTECTED]> wrote:

> Hi,
>
> Is there some way to get a list of "impure" Python modules/extensions
> from PyPI?  I know the mySQL module is a good example, but I am
> working on creating some decent instructions on how to create Windows
> installers from impure modules and am having a hard time finding them.
>
> Thanks!
>
> Mike
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to generate html table from "table" data?

2007-12-27 Thread Ricardo Aráoz
Bruno Desthuilliers wrote:
> [EMAIL PROTECTED] a écrit :
>  > Vasudev Ram wrote:
>>> Why not try writing your own code for this first?
>>> If nothing else, it'll help you learn more, and may also help you
>>> understand better, the other options.
>>>
>> Thanks for your reply even it was not really helpful.
> 
> The answers boil down to:
> - use the templating engine that comes with your web framework
> or
> - use whatever templating engine you like
> or
> - just do it by hand
> 
> The remaining work is obviously such a no-brainer that there's no need 
> for a specific package, and so application specific that there's 
> probably nothing like a one-size-fits-all answer. IOW : you're not 
> likely to find more "helpful" answer - and your above comment won't 
> help. FWIW, I just wrote a function generating an html table from a list 
> of header and a list of rows. I wrote the most Q&D, straightforward, 
> braindead way, it's 17 lines long, doesn't even need an import 
> statement, and took me less than 2 minutes to write - that is, far less 
> work than reading your post and answering it.

Hi.
Bruno, could you please post those 17 lines? I'm not actually doing HTML
work but I would find it interesting going through your code.

TIA



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


Re: Cheat sheet

2007-12-27 Thread Scott David Daniels
Riccardo T. wrote:
> I wrote a little cheat sheet for this wonderful language, but because of
> my still little experience with it, I would like to have a feedback
> Could you have a look at it and tell me what do you think about, please?
> 
> http://greyfox.imente.org/index.php?id=73
> 
> --
> GreyFox

[in the .png]
 > ...
 > Callable types
 >...
 >User-definet methods

I personally prefer "User-defined methods"

 >...
 >Class instances
I'd try:
  Class instances with a __call__ method.

 > ...
 > Classes
 > Classes Instances

This probably wants to be
   Class Instances

"file" objects are generally supposed to be built with the
open function, not instantiated as shown.
Also note iterating on a file gets the lines.

Do you know about seq[i:] and seq[::-1]?

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


Re: Performance on local constants?

2007-12-27 Thread Matthew Franz
Thanks, that makes more sense. I got tripped up by the function
returning a function thing and (for a while) thought _ was some sort
of spooky special variable.

- mdf

> On Dec 28, 7:53 am, "Matthew Franz" <[EMAIL PROTECTED]> wrote:
> > I get class Searcher(object) but can't for the life of me see why
> > (except to be intentionally obtuse) one would use the def
> > searcher(rex) pattern which I assure you would call with
> > searcher(r)(t) right?
> >
>
> The whole point of the thread was performance across multiple searches
> for the one pattern. Thus one would NOT do
> searcher(r)(t)
> each time a search was required; one would do
> s = searcher(r)
> ONCE, and then do
> s(t)
> each time ...
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matthew Franz
http://www.threatmind.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pivot Table/Groupby/Sum question

2007-12-27 Thread John Machin
On Dec 28, 4:56 am, [EMAIL PROTECTED] wrote:

> from itertools import groupby

You seem to have overlooked this important sentence in the
documentation: "Generally, the iterable needs to already be sorted on
the same key function"
-- 
http://mail.python.org/mailman/listinfo/python-list


"Impure" Python modules

2007-12-27 Thread kyosohma
Hi,

Is there some way to get a list of "impure" Python modules/extensions
from PyPI?  I know the mySQL module is a good example, but I am
working on creating some decent instructions on how to create Windows
installers from impure modules and am having a hard time finding them.

Thanks!

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


Taxicab Numbers

2007-12-27 Thread rgalgon
I'm new to Python and have been putting my mind to learning it over my
holiday break. I've been looking over the functional programming
aspects of Python and I'm stuck trying to come up with some concise
code to find Taxicab numbers (http://mathworld.wolfram.com/
TaxicabNumber.html).

"Taxicab(n), is defined as the smallest number that can be expressed
as a sum of two positive cubes in n distinct ways"

In Haskell something like this could easily be done with:
cube x = x * x * x

taxicab n = [(cube a + cube b, (a, b), (c, d))
| a <- [1..n],
  b <- [(a+1)..n],
  c <- [(a+1)..n],
  d <- [(c+1)..n],
  (cube a + cube b) == (cube c + cube d)]

Output::
*Main> taxicab 10
[]
*Main> taxicab 12
[(1729,(1,12),(9,10))]
*Main> taxicab 20
[(1729,(1,12),(9,10)),(4104,(2,16),(9,15))]

I'm looking for a succinct way of doing this in Python. I've been
toying around with filter(),map(), and reduce() but haven't gotten
anything half-way decent yet.

So, how would you implement this taxicab(n) function in Python?
Thanks in advance :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance on local constants?

2007-12-27 Thread John Machin
On Dec 28, 7:53 am, "Matthew Franz" <[EMAIL PROTECTED]> wrote:
> I get class Searcher(object) but can't for the life of me see why
> (except to be intentionally obtuse) one would use the def
> searcher(rex) pattern which I assure you would call with
> searcher(r)(t) right?
>

The whole point of the thread was performance across multiple searches
for the one pattern. Thus one would NOT do
searcher(r)(t)
each time a search was required; one would do
s = searcher(r)
ONCE, and then do
s(t)
each time ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building Python statically on linux

2007-12-27 Thread Micah Elliott
On Dec 27, 8:32 am, Zentrader <[EMAIL PROTECTED]> wrote:

> I think you can just add -static to the gcc Flag line in the
> makefile.

Doing that (or CFLAGS=-static, or LDFLAGS=-static, or other Makefile
tweaks) gets me linker errors.  Sounds like there's not a simple
prescribed means to do this (that anyone has documented).  So now I'm
open to hearing about other hacks people have done to get this to
work.  (Hopefully a config weenie heard my plea for --enable-all-
static)

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


Re: Python for web...

2007-12-27 Thread Steve Lianoglou
It's also worthwhile to note that the apress django book listed is
also accessible free online here:

http://www.djangobook.com/en/1.0/

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


Re: parallel processing in standard library

2007-12-27 Thread Robert Kern
Emin.shopper Martinian.shopper wrote:
> Dear Experts,
> 
> Is there any hope of a parallel processing toolkit being incorporated
> into the python standard library? I've seen a wide variety of toolkits
> each with various features and limitations. Unfortunately, each has its
> own API. For coarse-grained parallelism, I suspect I'd be pretty happy
> with many of the existing toolkits, but if I'm going to pick one API to
> learn and program to, I'd rather pick one that I'm confident is going to
> be supported for a while.
> 
> So is there any hope of adoption of a parallel processing system into
> the python standard library? If not, is there any hope of something like
> the db-api for coarse grained parallelism (i.e, a common API that
> different toolkits can support)?

The problem is that for SQL databases, there is a substantial API that they can
all share. The implementations are primarily differentiated by other factors
like speed, in-memory or on-disk, embedded or server, the flavor of SQL, etc.
and only secondarily differentiated by their extensions to the DB-API. With
parallel processing, the API itself is a key differentiator between toolkits and
approaches. Different problems require different APIs, not just different
implementations.

I suspect that one of the smaller implementations like processing.py might get
adopted into the standard library if the author decides to push for it. The ones
I am thinking of are relatively new, so I imagine that it might take a couple of
years of vigorous use by the community before it gets into the standard library.

My recommendation to you is to pick one of the smaller implementations that
solves the problems in front of you. Read and understand that module so you
could maintain it yourself if you had to. Post to this list about how you use
it. Blog about it if you blog. Write some Python Cookbook recipes to show how
you solve problems with it. If there is a lively community around it, that will
help it get into the standard library. Things get into the standard library
*because* they are supported, not the other way around.

-- 
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: Happy Christmas Pythoneers

2007-12-27 Thread Robert Kern
Gabriel Genellina wrote:
> En Thu, 27 Dec 2007 02:32:54 -0300, [EMAIL PROTECTED]  
> <[EMAIL PROTECTED]> escribió:
> 
>> On Dec 26, 9:43 pm, Steven D'Aprano
>> <[EMAIL PROTECTED]> wrote:
> 
>>> watch_fireworks()
>>> try:
>>> champagne
>>> except NameError:
>>> champagne = any_fizzy_alcoholic_drink_will_do()
>>> champagne.drink()
>>> shout("Happy New Years!!!")
>>> for person in adults_nearby:
>>> if (person.is_appropriate_sex and person.is_pretty):
>> Hey, my version of the person module doesn't have
>> an is_appropriate_sex attribute, but an
>> is_opposite_sex attribute instead. Is this a new version?
> 
> The default is_appropriate_sex implementation just happens to call  
> is_opposite_sex, but this is an implementation detail and you should not  
> rely on that, even more so if you didn't create that particular person  
> instance.

Although the coding standards in most shops prevent you from querying the
is_appropriate_sex interface if you create that particular person instance.

-- 
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: Cheat sheet

2007-12-27 Thread Riccardo T.
Carl Banks ha scritto:
> On Dec 27, 12:38 pm, "Riccardo T." <[EMAIL PROTECTED]> wrote:
>> I wrote a little cheat sheet for this wonderful language, but because of
>> my still little experience with it, I would like to have a feedback
>> Could you have a look at it and tell me what do you think about, please?
>>
>> http://greyfox.imente.org/index.php?id=73
> 
> Nice work.

I'm very glad you liked it :)

> Only questionable thing I could see is listing dict.has_key(): I'm not
> sure of it's officially deprecated but the recommended practice these
> days is to to use "key in dict_obj".

I listed it because of help(dict.has_key) doesn't show any warning about
that. However, if "in" works as well, I'll remove it very soon.

> Also, consider adding a line or two about the set objects.  (It's
> probably at least better than listing internal objects.)

I forgot it... thank you very much. I hope I'll find some more space to
write on.

> Carl Banks

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


Re: Performance on local constants?

2007-12-27 Thread Matthew Franz
I get class Searcher(object) but can't for the life of me see why
(except to be intentionally obtuse) one would use the def
searcher(rex) pattern which I assure you would call with
searcher(r)(t) right?

- mdf


> >
> > 'Most flexible' in a different way is
> >
> > def searcher(rex):
> > crex = re.compile(rex)
> > def _(txt):
> > return crex.search(txt)
> > return _
> >
>
> I see your obfuscatory ante and raise you several dots and
> underscores:
>
> class Searcher(object):
> def __init__(self, rex):
> self.crex = re.compile(rex)
> def __call__(self, txt):
> return self.crex.search(txt)
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysqldb SELECT COUNT reurns 1

2007-12-27 Thread John Machin
On Dec 28, 7:03 am, SMALLp <[EMAIL PROTECTED]> wrote:
> Hy! I nave another problem I can't solve!
> 
>
> import MySQLdb as mysql
>
> connectionString = {"host":"localhost", "user":"root",
> "passwd":"pofuck", "db":"fileshare"}
> dataTable = "files"
> conn = mysql.connect(host=connectionString["host"],
> user=connectionString["user"], passwd=connectionString["passwd"],
> db=connectionString["db"])
>
> cursor = conn.cursor()
> sql = "SELECT COUNT(*) FROM " + dataTable
> res = cursor.execute(sql)
> print res
>
> 
> It prints 1, and there are 88 rows in table.

What makes you think that it should return 88?

> SELECT works fine, but

In what sense does a bare "SELECT" work fine??

> SELECT COUNT(*) makes problems.
>
> Help! Thanks in advance!

Consider helping yourself, e.g.:
(1) search the web for "mysqldb tutorial"
(2) read the MySQLdb documentation
(3) read http://www.python.org/dev/peps/pep-0249/

You need to use one of the cursor.fetch methods to get your
results. The result from a call to cursor.execute is NOT defined in
the Python DBAPI. If you are interested in portability of your code
across database software, you should not rely on it. The value 1
probably just means that the execute call succeeded.

Do read carefully the descriptions of what is returned by each of the
cursor.fetch methods.
-- 
http://mail.python.org/mailman/listinfo/python-list


Removing compile option in distutils

2007-12-27 Thread jeremito
Hello all,

I am using distutils for building/compiling my Python extensions.  The
default configuration tells the compiler to generate debug information
with the "-g" flag.  I don't want this, but I can't seem to figure out
how to get rid of it.  Does anyone now how?

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


Re: Cheat sheet

2007-12-27 Thread Carl Banks
On Dec 27, 12:38 pm, "Riccardo T." <[EMAIL PROTECTED]> wrote:
> I wrote a little cheat sheet for this wonderful language, but because of
> my still little experience with it, I would like to have a feedback
> Could you have a look at it and tell me what do you think about, please?
>
> http://greyfox.imente.org/index.php?id=73

Nice work.

Only questionable thing I could see is listing dict.has_key(): I'm not
sure of it's officially deprecated but the recommended practice these
days is to to use "key in dict_obj".

Also, consider adding a line or two about the set objects.  (It's
probably at least better than listing internal objects.)


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


Re: mysqldb SELECT COUNT reurns 1

2007-12-27 Thread SMALLp
Rob Williscroft wrote:
> SMALLp wrote in news:[EMAIL PROTECTED] in comp.lang.python:
> 
>> Hy! I nave another problem I can't solve!
>> 
>>
>>  import MySQLdb as mysql
> 
>> cursor = conn.cursor()
>> sql = "SELECT COUNT(*) FROM " + dataTable
>> res = cursor.execute(sql)
> 
> I think you need to do:
> res = cursor.fetchone()[0]
> 
> 
>> print res
>>
>> 
>> It prints 1, and there are 88 rows in table. SELECT works fine, but 
>> SELECT COUNT(*) makes problems.
>  
> Rob.
Of course! Thanks!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mysqldb SELECT COUNT reurns 1

2007-12-27 Thread Rob Williscroft
SMALLp wrote in news:[EMAIL PROTECTED] in comp.lang.python:

> Hy! I nave another problem I can't solve!
> 
> 
>  import MySQLdb as mysql

> cursor = conn.cursor()
> sql = "SELECT COUNT(*) FROM " + dataTable
> res = cursor.execute(sql)

I think you need to do:
res = cursor.fetchone()[0]


> print res
> 
> 
> It prints 1, and there are 88 rows in table. SELECT works fine, but 
> SELECT COUNT(*) makes problems.
 
Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cheat sheet

2007-12-27 Thread Riccardo T.
Markus Gritsch ha scritto:
> On Dec 27, 11:38 am, "Riccardo T." <[EMAIL PROTECTED]> wrote:
>> I wrote a little cheat sheet for this wonderful language, but because of
>> my still little experience with it, I would like to have a feedback
>> Could you have a look at it and tell me what do you think about, please?
>>
>> http://greyfox.imente.org/index.php?id=73
> 
> Since Python 2.5 "try except else" and "try finally" got unified:
>   http://docs.python.org/ref/try.html
>   http://docs.python.org/whatsnew/pep-341.html

Thank you, but that cheat sheet is about Python 2.4, not 2.5, so it
should be correct.
It's written into the article, maybe I should write it on the sheet too.

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


mysqldb SELECT COUNT reurns 1

2007-12-27 Thread SMALLp
Hy! I nave another problem I can't solve!


import MySQLdb as mysql

connectionString = {"host":"localhost", "user":"root", 
"passwd":"pofuck", "db":"fileshare"}
dataTable = "files"
conn = mysql.connect(host=connectionString["host"],
user=connectionString["user"], passwd=connectionString["passwd"],
db=connectionString["db"])  

cursor = conn.cursor()
sql = "SELECT COUNT(*) FROM " + dataTable
res = cursor.execute(sql)
print res


It prints 1, and there are 88 rows in table. SELECT works fine, but 
SELECT COUNT(*) makes problems.

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


Re: Cheat sheet

2007-12-27 Thread Markus Gritsch
On Dec 27, 11:38 am, "Riccardo T." <[EMAIL PROTECTED]> wrote:
> I wrote a little cheat sheet for this wonderful language, but because of
> my still little experience with it, I would like to have a feedback
> Could you have a look at it and tell me what do you think about, please?
>
> http://greyfox.imente.org/index.php?id=73

Since Python 2.5 "try except else" and "try finally" got unified:
  http://docs.python.org/ref/try.html
  http://docs.python.org/whatsnew/pep-341.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cheat sheet

2007-12-27 Thread kyosohma
On Dec 27, 1:44 pm, "Riccardo T." <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] ha scritto:
>
> > Looks cool, but you might find these interesting too:
>
> >http://www.limsi.fr/Individu/pointal/python/pqrc/
> >http://mail.python.org/pipermail/python-list/2006-June/386662.html
>
> > Mike
>
> Thanks :)
> I'll read them to improve my python knowledge, but I prefere to have a
> very small cheat sheet to keep near me.
>
> --
> GreyFox

Yeah...they can be handy. I like that Quick Reference card, but it is
a little unwieldy.

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


Re: list in a tuple

2007-12-27 Thread Carl Banks
On Dec 27, 12:38 pm, [EMAIL PROTECTED] wrote:
> After some tought I must agree that this is a wart more than
> a bug and that it will probably be best not to mess with it.
> However, what do you guys think about the print wart in Py3k
> described 
> athttp://filoxus.blogspot.com/2007/12/python-3000-how-mutable-is-immuta...
> (im not trying to advertise my blog, I just don't feel like
> typing the whole problem all over again)?


1. Tuples are immutable.  None of the tuples in your example were
modified.

The behavior you want (which is not immutability of tuples, which
Python already has, but *recursive* immutability of all objects
contained within the tuple) is not an unreasonable thing to ask for,
but the design of Python and common usage of tuples makes it all but
impossible at this point.

There is no general way to determine whether an object is mutable or
not.  (Python would have to add this capability, an extremely
substantial change, to grant your wish.  It won't happen.)

Tuples are used internally to represent the arguments of a function,
which are often mutable.

Tuples are sometimes used to return multiple values from a function,
which could include mutable values.

Tuples are used to specify multiple arguments to a format string, some
of which could be mutable, though I guess this is going away in Python
3.


2. The issue with print in your example is a bug, not a wart.  It'll
be fixed.

(This is just a guess, but I think it might have something to do with
the flux of the new bytes type.  The behavior manifested itself when
trying to print a self-referencing structure probably only because
that section of code was lagging behind.)


3. You're still top posting, which goes against this group's
conventions and annoys quite a few people.  When you reply to a
message, please move your cursor to below the quoted message before
you begin typing.  Thank you


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


Re: standalone python web server

2007-12-27 Thread Jason Earl
eric <[EMAIL PROTECTED]> writes:

> Hi all,
>
> I want to setup simple python web server and I want it to just unzip
> and run, without any installation steps (have no right to do it).
>
> I've tried to write by myself, however, I find I am getting into more
> details like processing image file, different file type(like FLV) ..
> etc. Any recommendation or tools suggested for me?

CherryPy has a built in web server that can be installed without admin
rights (it is pure Python), and can easily be configured to serve up
static files.

Just something to think about.

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


Re: Cheat sheet

2007-12-27 Thread Riccardo T.
[EMAIL PROTECTED] ha scritto:
> Looks cool, but you might find these interesting too:
> 
> http://www.limsi.fr/Individu/pointal/python/pqrc/
> http://mail.python.org/pipermail/python-list/2006-June/386662.html
> 
> Mike

Thanks :)
I'll read them to improve my python knowledge, but I prefere to have a
very small cheat sheet to keep near me.

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


ANNOUNCE: Spiff Integrator 0.1

2007-12-27 Thread Samuel
Introduction

Spiff Integrator is a small but powerful library for adding plugin 
support to Python applications. It is in some ways comparable to Debian's 
dpkg and handles packing/unpacking, installation/updates/removal, and 
dependency management and provides a bus over which plugins may 
communicate.

Spiff Integrator is free software and distributed under the GNU GPLv2.

This is the initial release.

Dependencies
-
sqlalchemy (http://www.sqlalchemy.org/)
Spiff Guard (http://pypi.python.org/pypi/Spiff%20Guard)

Download
-
Tarball:
http://pypi.python.org/packages/source/S/Spiff%20Integrator/Spiff%20Integrator-0.1.tar.gz

SVN:
svn checkout http://spiff.googlecode.com/svn/trunk/libs/Integrator/

Links:
---
Documentation: http://spiff.googlecode.com/svn/trunk/libs/Integrator/README
API Documentation: 
http://spiff.debain.org/static/docs/spiff_integrator/index.html
Example: http://spiff.googlecode.com/svn/trunk/pkg.py
Spiff project page: http://code.google.com/p/spiff/
Mailing list: http://groups.google.com/group/spiff-devel
Bug tracker: http://code.google.com/p/spiff/issues/list
Browse the source: http://spiff.googlecode.com/svn/trunk/libs/Integrator/

If you have any questions, please do not hesitate to ask or file a bug.

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


Re: list in a tuple

2007-12-27 Thread montyphyton


On Dec 27, 8:20 pm, Wildemar Wildenburger
<[EMAIL PROTECTED]> wrote:
>  >
>
>  From that post:
>  > Ok, I do admit that doing
>  >
>  > a = ([1], 2)
>  > a[0].append(2)
>  >
>  > also doesn't throw an error, but this only confuses me more.
>  >
> Why? You mutate thelist, but thetupledoes not change. It is still atupleof 
> alistand an int. At least that's how I think about it, and I
> seem to recall reading that beavior justified like this (don't ask me
> where though (might have been "Dive Into Python", but maybe not)).

That part is ok, I mean it doesn't confuse me I just wanted to say
that this is somewhat confusing behavior.
I agree that its not best put... But I was thinking about the last
part of the post, the part
that talks about trying to print a tuple and getting an error.


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


Re: list in a tuple

2007-12-27 Thread Wildemar Wildenburger
Subject:   Re: list in a tuple
To:
Cc:
Bcc:
Reply-To:
Newsgroup: comp.lang.python
-=-=-=-=-=-=-=-=-=# Don't remove this line #=-=-=-=-=-=-=-=-=-
[EMAIL PROTECTED] wrote:
 > After some tought I must agree that this is a wart more than
 > a bug and that it will probably be best not to mess with it.
 > However, what do you guys think about the print wart in Py3k
 > described at 
http://filoxus.blogspot.com/2007/12/python-3000-how-mutable-is-immutable.html#links
 > (im not trying to advertise my blog, I just don't feel like
 > typing the whole problem all over again)?
 >

 From that post:
 > Ok, I do admit that doing
 >
 > a = ([1], 2)
 > a[0].append(2)
 >
 > also doesn't throw an error, but this only confuses me more.
 >
Why? You mutate the list, but the tuple does not change. It is still a 
tuple of a list and an int. At least that's how I think about it, and I 
seem to recall reading that beavior justified like this (don't ask me 
where though (might have been "Dive Into Python", but maybe not)).

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


Re: Extracting images from a PDF file

2007-12-27 Thread Max Erickson
Doug Farrell <[EMAIL PROTECTED]> wrote:

> Hi all,
> 
> Does anyone know how to extract images from a PDF file? What I'm
> looking to do is use pdflib_py to open large PDF files on our
> Linux servers, then use PIL to verify image data. I want to do
> this in order to find corrupt images in the PDF files. If anyone
> could help me out, or point me in the right direction, it would
> be most appreciated!
> 
> Also, does anyone know of a way to validate a PDF file? 
> 
> Thanks in advance,
> Doug

There is some discussion here: 

http://nedbatchelder.com/blog/200712.html#e20071210T064608



max

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


SDTimes - Trends From 2007: "Dynamic languages are on the rise."

2007-12-27 Thread walterbyrd
This according to SDTimes:

http://www.sdtimes.com/article/story-20071215-13.html

They don't specifically mention Python. But, I think Python qualifies
as a dynamic language.

"1. Dynamic languages are on the rise. We went into 2007 knowing that
Ruby would be a popular topic, thanks to Ruby on Rails, and that
JavaScript was resurgent, thanks to AJAX-based rich Internet
applications. However, we did not anticipate that there would be such
broad big-company support for dynamic languages--and there was, from
everyone from Microsoft to Sun, CodeGear to Eclipse. If you were
learning a new language in 2007, it wasn't Java or C#; it was a
dynamic language."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cheat sheet

2007-12-27 Thread kyosohma
On Dec 27, 11:38 am, "Riccardo T." <[EMAIL PROTECTED]> wrote:
> I wrote a little cheat sheet for this wonderful language, but because of
> my still little experience with it, I would like to have a feedback
> Could you have a look at it and tell me what do you think about, please?
>
> http://greyfox.imente.org/index.php?id=73
>
> --
> GreyFox

Looks cool, but you might find these interesting too:

http://www.limsi.fr/Individu/pointal/python/pqrc/
http://mail.python.org/pipermail/python-list/2006-June/386662.html

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


Blasting new year

2007-12-27 Thread sfrabe
Wishes for the new year
http://newyearcards2008.com/

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


Re: unicode(s, enc).encode(enc) == s ?

2007-12-27 Thread Martin v. Löwis
> Given no UnicodeErrors, are there any cases for the following not to
> be True?
> 
> unicode(s, enc).encode(enc) == s

Certainly. ISO-2022 is famous for having ambiguous encodings. Try
these:

unicode("Hallo","iso-2022-jp")
unicode("\x1b(BHallo","iso-2022-jp")
unicode("\x1b(JHallo","iso-2022-jp")
unicode("\x1b(BHal\x1b(Jlo","iso-2022-jp")

or likewise

unicode("[EMAIL PROTECTED]","iso-2022-jp")
unicode("\x1b$BBB","iso-2022-jp")

In iso-2022-jp-3, there are even more ways to encode the same string.

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


Re: Bug in htmlentitydefs.py with Python 3.0?

2007-12-27 Thread Martin v. Löwis
>> I would not write it this way, but as
>>
>> for name,codepoint in htmlentitydefs.name2codepoint:
>>   entity_map[name] = unichr(codepoint)
> 
> has dictionary iteration changed in 3.0?  if not, your code doesn't
> quite work.

Right - I forgot to add .items().

> and even if you fix that, it doesn't work for all Python
> versions that ET works for...

That's true. However, the OP seemed to care only about Python 3.0
initially.

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


Pivot Table/Groupby/Sum question

2007-12-27 Thread patrick . waldo
Hi all,

I tried reading http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334695
on the same subject, but it didn't work for me.  I'm trying to learn
how to make pivot tables from some excel sheets and I am trying to
abstract this into a simple sort of example.  Essentially I want to
take input data like this:

Name  Time of day  Amount
Bob   Morn240
Bob   Aft   300
Joe   Morn 70
Joe   Aft80
Jil   Morn  100
Jil   Aft 150

And output it as:

Name  TotalMorning  Afternoon
Bob540  240300
Joe 150  70  80
Jil   250 100150
Total   940  410530

The writing the output part is the easy part.  However, I have a
couple problems.  1) Grouping by name seems to work perfectly, but
working by time does not.  ie

I will get:
Bob
240
300
Joe
70
80
Jil
100
150
which is great but...
Morn
240
Aft
300
Morn
70
Aft
80
Morn
100
Aft
150
And not
Morn
240
70
100
Aft
   300
   80
   150

2) I can't figure out how to sum these values because of the
iteration.  I always get an error like: TypeError: iteration over non-
sequence

Here's the code:

from itertools import groupby

data = [['Bob', 'Morn', 240],['Bob', 'Aft', 300],['Joe', 'Morn', 70],
['Joe', 'Aft', 80],\
['Jil', 'Morn', 100],['Jil', 'Aft', 150]]

NAME, TIME, AMOUNT=range(3)
for k, g in groupby(data, key=lambda r: r[NAME]):
print k
for record in g:
print "\t", record[AMOUNT]
for k, g in groupby(data, key=lambda r: r[TIME]):
print k
for record in g:
print "\t", record[AMOUNT]

Thanks for any comments
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic DNS with a python script

2007-12-27 Thread Shane Geiger
Marcelo de Moraes Serpa wrote:
> Hello list,
>
> I'd like to set up ssh access to my home computer so that I will be
> able to access it from work - for this no problem, installing sshd is
> straightforward.
>
> The issue here is that I don't have a fixed IP connection at home.
> Also, I wouldn't like to use services such as no-ip or similar.
>
> What I thought was of writing a python program that would detect when
> the internet network interface was restarted/started for the first
> time and then update a DNS record at my DNS server where I would have
> a subdomain that for my home machine's host.
>
> However, I have no idea on how I could detect if the network has been
> restarted nor how I could update this DNS record. Any suggestion would
> be greatly appreciated :)
>
> Thanks in advance,
>
> Marcelo.

How to deal with networking depends on the system you use.  For Debian:

Debian uses ifupdown (see ifup(8), ifdown(8) and interfaces(5)) to
manipulate network interfaces. Each interface is provided with
several scripting hooks: pre-up, up, down, and post-down. These
hooks are available to each interface as in-line directives in
/etc/network/interfaces and also as *.d/ directories called with
run-parts (see run-parts(8)):

   /etc/network/if-up.d/
   /etc/network/if-pre-up.d/
   /etc/network/if-down.d/
   /etc/network/if-post-down.d/




SETTING UP A DOMAIN NAME WITH DYNDNS.ORG

Go to their site and set up an account.  While doing that (or perhaps
after--I don't remember), you can choose a domain name.  You *could*
think of what they are giving you is a subdomain--not actually a
domain.  You will be able to choose something like foo.mine.nu where
"foo" is the name you choose for the name of your subdomain and
"mine.nu" is the domain they already own.  (You can choose from many
domains they already own.)  Since they manage these domains themselves,
they do not have to pay a registrar to set up a subdomain...and
therefore they can give you a subdomain for free.  (Actually, I'm using
the term "subdomain" loosely here...but I'm sure you get the point I'm
trying to make--which is that you don't have to pay for this name.)

Once you have your name (foo.mine.nu, for example), you can set up a
program on your computer to update their DNS servers with your new
domain name whenever it changes.

--


SETTING UP IPCHECK WITH DYNDNS.ORG

I have been satisfied with my first choice (dyndns.org), so I haven't
tried the others.  They probably work well, too.

Set up an account on dyndns.org, and record the username, password, and
domain name in your notes.  In the following examples, I use the
following values:

username:  sgeiger
pass:  asdfasdf
domain name:  sgeiger.mine.nu


apt-get install ipcheck

You might want to run this first so that you are in the directory cron
will use when you run ipcheck:
sudo su; cd ~;

HERE'S HOW TO CONFIGURE IT:
[EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py -l -r
checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
ipcheck.py: No ipcheck.dat file found.
ipcheck.py: Use same command+options ONCE with --makedat to create from
DNS lookup.
[EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py --makedat -l -r
checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
ipcheck.py: ip1 looking up sgeiger.mine.nu
ipcheck.py: result: 'sgeiger.mine.nu'[]['139.55.232.72']
[EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py -l -r
checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine
.nu
[EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py -l -r
checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
[EMAIL PROTECTED]:~$ sudo /usr/sbin/ipcheck.py -l -r
checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu
[EMAIL PROTECTED]:~$

When you run this manually and it works you will see no output.

To add a cron job to update this automatically once a day at 10 am:

###  Note:  This script should be run once a day from cron, like this
(which runs it at 10:15 am every day)
15 10 * * * /usr/bin/python /usr/sbin/ipcheck.py -l -r
checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu


To add another names (foobar.mine.nu):
sudo /usr/sbin/ipcheck.py --makedat -l -r checkip.dyndns.org:8245
shanerg rQ9ll0 sgeiger.mine.nu,foobar.mine.nu

...and then put this into the cron tab:
15 10 * * * /usr/bin/python /usr/sbin/ipcheck.py -l -r
checkip.dyndns.org:8245 shanerg asdfasdf sgeiger.mine.nu




Check the mail messages on the computer you are using in case there were
errors.

Note:  This creates a file named /root/ipcheck.dat and /root/ipcheck.log
on my computer.




STEPS FOR ADDING ANOTHER HOST:
  - add the host on dnydns.org
  - run the script with makedat option
  - run the script to update the server

In the example below, ipcheck will update the dyndns.org servers for the
names "sgeiger.mine.nu" and for "myothername.mine.nu":

[EMAIL PROTECTED]:/root$ sudo /usr/sbin/ipcheck.py --makedat -l -r
checkip.dyndns.org:8245 shanerg asdfasdf
sgei

RE: I want to set up a simple web server

2007-12-27 Thread lloyd
Hi,

Try Karrigell  (http://karrigell.sourceforge.net/)


> I want to setup simple python web server and I want it to just unzip

> and run, without any installation steps (have no right to do it).



> I've tried to write by myself, however, I find I am getting into more

> details like processing image file, different file type(like FLV) ..

> etc. Any recommendation or tools suggested for me?

All the best,

Lloyd


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

Re: Dynamic DNS with a python script

2007-12-27 Thread Jean-Paul Calderone
On Thu, 27 Dec 2007 15:27:37 -0200, Marcelo de Moraes Serpa <[EMAIL PROTECTED]> 
wrote:
>Hello list,
>
>I'd like to set up ssh access to my home computer so that I will be able to
>access it from work - for this no problem, installing sshd is
>straightforward.
>
>The issue here is that I don't have a fixed IP connection at home. Also, I
>wouldn't like to use services such as no-ip or similar.
>
>What I thought was of writing a python program that would detect when the
>internet network interface was restarted/started for the first time and then
>update a DNS record at my DNS server where I would have a subdomain that for
>my home machine's host.
>
>However, I have no idea on how I could detect if the network has been
>restarted nor how I could update this DNS record. Any suggestion would be
>greatly appreciated :)
>

This depends on platform details.  For example, some Linux distros include
/etc/network/if-up.d/ which can contain arbitrary programs which will be
run after an interface is brought up.

Other platforms may have other ways to get notification of this event, or
they may require you to poll at some interval.

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


Re: list in a tuple

2007-12-27 Thread montyphyton
After some tought I must agree that this is a wart more than
a bug and that it will probably be best not to mess with it.
However, what do you guys think about the print wart in Py3k
described at 
http://filoxus.blogspot.com/2007/12/python-3000-how-mutable-is-immutable.html#links
(im not trying to advertise my blog, I just don't feel like
typing the whole problem all over again)?

On 26 pro, 19:11, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> On Dec 26, 1:08 am, Steven D'Aprano <[EMAIL PROTECTED]
>
> cybersource.com.au> wrote:
> > On Mon, 24 Dec 2007 18:01:53 -0800, Raymond Hettinger wrote:
> [...]
> > > The first succeeds and the second fails.
>
> > And this is a good idea?
>
> > Shouldn't the tuple assignment raise the exception BEFORE calling
> > __iadd__ on the item, instead of after?
>
> If you look at the bytecode generated, this doesn't seem possible:
>
> >>> def f():
>
> ...     a = ([1],)
> ...     a[0] += [2]
> ...>>> import dis
> >>> dis.dis(f)
>
>   2           0 LOAD_CONST               1 (1)
>               3 BUILD_LIST               1
>               6 BUILD_TUPLE              1
>               9 STORE_FAST               0 (a)
>
>   3          12 LOAD_FAST                0 (a)
>              15 LOAD_CONST               2 (0)
>              18 DUP_TOPX                 2
>              21 BINARY_SUBSCR
>              22 LOAD_CONST               3 (2)
>              25 BUILD_LIST               1
>              28 INPLACE_ADD
>              29 ROT_THREE
>              30 STORE_SUBSCR
>              31 LOAD_CONST               0 (None)
>              34 RETURN_VALUE
>
> BINARY_SUBSCR puts a[0] on the stack, it has no way to know that a[0]
> will be changed in place.  To allow an exception to be thrown before
> the in-place modification of a[0], there should be a new bytecode
> instruction, say BINARY_SUBSCR_WITH_A_VIEW_TO_CHANGE_IN_PLACE, which
> checks that the subscriptable object supports STORE_SUBSCR (;-).
>
> [...]
>
> > I was never a big fan of augmented assignments. I think it goes against
> > the Python grain: it's an implied operation, using punctuation, for the
> > sole (?) benefit of saving a keystroke or three.
>
> > But I think this behaviour counts as a wart on the language, rather than
> > a bug.
>
> Yes.  I didn't realise this before you mentioned it, but the culprit
> here seems to be the augmented assignment which acts differently on
> mutable and immutable objects:
>
> b = a  # say a is immutable
> a += c # equivalent to a = a + c
> b is a # -> False
>
> b = a  # Now say a is mutable
> a += c # equivalent to a.__iadd__(c)
> b is a # -> True
>
> OTOH augmented assignent are a slight optimisation:
>
> a[i] += 1
>
> will look for the value of a and i only once and duplicate them on the
> stack, whereas
>
> a[i] = a[i] + 1
>
> will need to resolve a and i twice (which can be costly if a and i are
> globals)
>
> --
> Arnaud

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


Cheat sheet

2007-12-27 Thread Riccardo T.
I wrote a little cheat sheet for this wonderful language, but because of
my still little experience with it, I would like to have a feedback
Could you have a look at it and tell me what do you think about, please?

http://greyfox.imente.org/index.php?id=73

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


Dynamic DNS with a python script

2007-12-27 Thread Marcelo de Moraes Serpa
Hello list,

I'd like to set up ssh access to my home computer so that I will be able to
access it from work - for this no problem, installing sshd is
straightforward.

The issue here is that I don't have a fixed IP connection at home. Also, I
wouldn't like to use services such as no-ip or similar.

What I thought was of writing a python program that would detect when the
internet network interface was restarted/started for the first time and then
update a DNS record at my DNS server where I would have a subdomain that for
my home machine's host.

However, I have no idea on how I could detect if the network has been
restarted nor how I could update this DNS record. Any suggestion would be
greatly appreciated :)

Thanks in advance,

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

Re: Python mouse EVT_COMMAND_LEFT_CLICK, EVT_LEFT_DOWN

2007-12-27 Thread kyosohma
On Dec 27, 10:59 am, SMALLp <[EMAIL PROTECTED]> wrote:
> Hy!
> I'm not able to tu bind mouse click event. Code:
>
> class MouseClass(wx.Panel):
> def __init__(self, parent, id):
>
> wx.Panel.__init__(self, parent, id, size=(500, 300))
> self.SetBackgroundColour("WHITE")
>
> sizer = wx.BoxSizer(wx.VERTICAL)
>
> testPanel.SetBackgroundColour("BLACK")
> self.Bind(wx.EVT_COMMAND_LEFT_CLICK, self.open, 
> id=testPanel.GetId())
> sizer.Add(testPanel, 0, wx.EXPAND)
> self.SetSizerAndFir(sizer)
>
> def open(self, event):
> print "yea"
>
> U  tried EVT_LEFT_DOWN as I found on goofle and couldnt get it to work.
> Please help.


It would help if you included working code, for one thing. Maybe I'm
blind, but I don't see a sub-panel getting instantiated with the name
"testPanel".

SetSizerAndFir is not a valid wx command.

All you need can be found here: 
http://www.wxpython.org/docs/api/wx.MouseEvent-class.html

If you do the following, it works:



import wx

class MouseClass(wx.Panel):
def __init__(self, parent, id):

wx.Panel.__init__(self, parent, id, size=(500, 300))
self.SetBackgroundColour("WHITE")

self.Bind(wx.EVT_LEFT_DOWN, self.open, id=self.GetId())


def open(self, event):
print "yea"

if __name__ == '__main__':
app = wx.PySimpleApp()
frm = wx.Frame(None, wx.ID_ANY, 'Mouse-click test')
panel = MouseClass(frm, wx.ID_ANY)
frm.Show()
app.MainLoop()



One other note: wxPython issues should be reported to the wxPython
user's group.

HTH

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


Python mouse EVT_COMMAND_LEFT_CLICK, EVT_LEFT_DOWN

2007-12-27 Thread SMALLp
Hy!
I'm not able to tu bind mouse click event. Code:

class MouseClass(wx.Panel):
def __init__(self, parent, id):

wx.Panel.__init__(self, parent, id, size=(500, 300))
self.SetBackgroundColour("WHITE")

sizer = wx.BoxSizer(wx.VERTICAL)

testPanel.SetBackgroundColour("BLACK")
self.Bind(wx.EVT_COMMAND_LEFT_CLICK, self.open, 
id=testPanel.GetId())
sizer.Add(testPanel, 0, wx.EXPAND)
self.SetSizerAndFir(sizer)

def open(self, event):
print "yea"

U  tried EVT_LEFT_DOWN as I found on goofle and couldnt get it to work. 
Please help.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building Python statically on linux

2007-12-27 Thread Zentrader
On Dec 27, 8:21 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Micah Elliott wrote:
> > I'm ./configure-ing with "--disable-shared" (because this must mean
> > "enable static", right?)

I think you can just add -static to the gcc Flag line in the
makefile.  "man gcc" should also be helpful but that is a pile of docs
to wade through.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building Python statically on linux

2007-12-27 Thread Christian Heimes
Micah Elliott wrote:
> I'm ./configure-ing with "--disable-shared" (because this must mean
> "enable static", right?), and (based on some other posts here) tried
> adding "*static*" near the top of Modules/Setup.  I'd like to see ldd
> tell me "not a dynamic executable", but alas, it's presently:

--disabled-shared is the default value. It does not mean that the Python
interpreter is a static linked executable. --enable-shared builds a
libpython??.so and --disable-shared links libpython into the python binary.

Christian

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


Building Python statically on linux

2007-12-27 Thread Micah Elliott
Are there instructions somewhere on how to build Python (on linux)
statically?  This seems like a common thing to do want to do, but my
searching isn't turning up much.  If it is common, it would be nice to
see a configure option like I've seen in other tools:

  --enable-all-static Build completely static (standalone)
binaries.

I'm ./configure-ing with "--disable-shared" (because this must mean
"enable static", right?), and (based on some other posts here) tried
adding "*static*" near the top of Modules/Setup.  I'd like to see ldd
tell me "not a dynamic executable", but alas, it's presently:

$ ldd /path/to/new/bin/python
libpthread.so.0 => /lib/tls/libpthread.so.0 (0x008e9000)
libdl.so.2 => /lib/libdl.so.2 (0x007f)
libutil.so.1 => /lib/libutil.so.1 (0x00df6000)
libm.so.6 => /lib/tls/libm.so.6 (0x007cb000)
libc.so.6 => /lib/tls/libc.so.6 (0x0069f000)
/lib/ld-linux.so.2 (0x00682000)

Do I just need to be passing something like LDFLAGS="-static ???" to
configure?  I just tried that and got a bunch of "symbol rename"
warnings during the compilation, and then "make install" mysteriously
failed.

Thanks for any pointers.
--
Micah
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interactive mode in python with ctypes???

2007-12-27 Thread ajaksu
You should get it to work with this loop (from run()):
   while libbuf != "quit":
  lib.libCallCommand(libinf,libbuf,0,pointer(result))
  print "result: ",result.value
  if libbuf == "Exit":
  break
  libbuf = raw_input("lib>")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in htmlentitydefs.py with Python 3.0?

2007-12-27 Thread Fredrik Lundh
Martin v. Löwis wrote:

>> entity_map = htmlentitydefs.entitydefs.copy()
>> for name, entity in entity_map.items():
>> if len(entity) != 1:
>> entity_map[name] = unichr(int(entity[2:-1]))
>>
>> (entitydefs is pretty unusable as it is, but it was added to Python
>> before Python got Unicode strings, and changing it would break ancient
>> code...)
> 
> I would not write it this way, but as
> 
> for name,codepoint in htmlentitydefs.name2codepoint:
>   entity_map[name] = unichr(codepoint)

has dictionary iteration changed in 3.0?  if not, your code doesn't 
quite work.  and even if you fix that, it doesn't work for all Python 
versions that ET works for...



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


Re: getting n items at a time from a generator

2007-12-27 Thread Shane Geiger
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496958

from itertools import *
def group(lst, n):
"""group([0,3,4,10,2,3], 2) => iterator

Group an iterable into an n-tuples iterable. Incomplete tuples
are padded with Nones e.g.

>>> list(group(range(10), 3))
[(0, 1, 2), (3, 4, 5), (6, 7, 8), (9, None, None)]
"""
iters = tee(lst, n)
iters = [iters[0]] + [chain(iter, repeat(None))
 for iter in iters[1:]]
return izip(
 *[islice(iter, i, None, n) for i, iter
  in enumerate(iters)])

import string
for grp in list(group(string.letters,25)):
   print grp

"""
('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y')
('z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M',
'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X')
('Y', 'Z', None, None, None, None, None, None, None, None, None, None,
None, None, None, None, None, None, None, None, None, None, None, None,
None)

"""




Kugutsumen wrote:
> On Dec 27, 7:24 pm, Terry Jones <[EMAIL PROTECTED]> wrote:
>   
>>> "Kugutsumen" == Kugutsumen  <[EMAIL PROTECTED]> writes:
>>>   
>> Kugutsumen> On Dec 27, 7:07 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
>>
>> 
 On Dec 27, 11:34 am, Kugutsumen <[EMAIL PROTECTED]> wrote:
 
> I am relatively new the python language and I am afraid to be missing
> some clever construct or built-in way equivalent to my 'chunk'
> generator below.
>   
>> Kugutsumen> Thanks, I am going to take a look at itertools.  I prefer the
>> Kugutsumen> list version since I need to buffer that chunk in memory at
>> Kugutsumen> this point.
>>
>> Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705
>>
>> def chop(iterable, length=2):
>> return izip(*(iter(iterable),) * length)
>>
>> Terry
>> 
>
>   
>> [snip code]
>>
>> Try this instead:
>>
>> import itertools
>>
>> def chunk(iterator, size):
>> # I prefer the argument order to be the reverse of yours.
>> while True:
>> chunk = list(itertools.islice(iterator, size))
>> if chunk: yield chunk
>> else: break
>>
>> 
>
> Steven, I really like your version since I've managed to understand it
> in one pass.
> Paul's version works but is too obscure to read for me :)
>
> Thanks a lot again.
>
>
>   


-- 
Shane Geiger
IT Director
National Council on Economic Education
[EMAIL PROTECTED]  |  402-438-8958  |  http://www.ncee.net

Leading the Campaign for Economic and Financial Literacy

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


Re: Writing Oracle Output to a File

2007-12-27 Thread Ralf Schönian
t_rectenwald schrieb:
> Hello,
> 
> I attempting to execute an Oracle query, and write the results to a
> file in CSV format.  To do so, I've done the following:
> 
> import cx_Oracle
> db = cx_Oracle.connect('user/[EMAIL PROTECTED]')
> cursor = db.cursor()
> cursor.arraysize = 500
> cursor.execute(sql)
> result = cursor.fetchall()
> 
> The above works great.  I'm able to connect to the database and print
> out the results as a list of tuples.  Here is where I get lost.  How
> do I work with a "list of tuples?"  My understanding is that a "list"
> is basically an array (I don't come from a Python background).  Tuples
> are a "collection of objects."  So, if I do...
> 
> print result[0]
> 
> I get the first row of the query, which would make sense.  The problem
> is that I cannot seem to write tuples to a file.  I then do this...
> 
> csvFile = open("output.csv", "w")
> csvFile = write(result[0])
> csvFile.close
> 
> This generates an exception:
> 
> TypeError: argument 1 must be string or read-only character buffer,
> not tuple
> 
> So, I'm a bit confused as to the best way to do this.  I guess I could
> try to convert the tuples into strings, but am not sure if that is the
> proper way to go.  Any help would be appreciated.  I've also seen a
> csv module out there, but am not sure if that is needed in this
> situation.
> 
> Best Regards,
> Tom

Hi,

have a look at the csv Module: http://docs.python.org/lib/csv-examples.html

Just iterate over your result.

# Untested
import csv
writer = csv.writer(open("some.csv", "wb"))

for row in result:
 row = map(str,row)
 writer.writerows(row)
writer.close()


Ralf Schoenian




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


Re: Writing Oracle Output to a File

2007-12-27 Thread Ralf Schönian
Ralf Schönian schrieb:
> t_rectenwald schrieb:
>> Hello,
>>
>> I attempting to execute an Oracle query, and write the results to a
>> file in CSV format.  To do so, I've done the following:
>>
>> import cx_Oracle
>> db = cx_Oracle.connect('user/[EMAIL PROTECTED]')
>> cursor = db.cursor()
>> cursor.arraysize = 500
>> cursor.execute(sql)
>> result = cursor.fetchall()
>>
>> The above works great.  I'm able to connect to the database and print
>> out the results as a list of tuples.  Here is where I get lost.  How
>> do I work with a "list of tuples?"  My understanding is that a "list"
>> is basically an array (I don't come from a Python background).  Tuples
>> are a "collection of objects."  So, if I do...
>>
>> print result[0]
>>
>> I get the first row of the query, which would make sense.  The problem
>> is that I cannot seem to write tuples to a file.  I then do this...
>>
>> csvFile = open("output.csv", "w")
>> csvFile = write(result[0])
>> csvFile.close
>>
>> This generates an exception:
>>
>> TypeError: argument 1 must be string or read-only character buffer,
>> not tuple
>>
>> So, I'm a bit confused as to the best way to do this.  I guess I could
>> try to convert the tuples into strings, but am not sure if that is the
>> proper way to go.  Any help would be appreciated.  I've also seen a
>> csv module out there, but am not sure if that is needed in this
>> situation.
>>
>> Best Regards,
>> Tom
> 
> Hi,
> 
> have a look at the csv Module: http://docs.python.org/lib/csv-examples.html
> 
> Just iterate over your result.
> 
> # Untested
> import csv
> writer = csv.writer(open("some.csv", "wb"))
> 
> for row in result:
> row = map(str,row)
# should be
   myRow = list(row)
   row = map(str,myRow)
> writer.writerows(row)
> writer.close()
> 
> 
> Ralf Schoenian
> 

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


Re: Extracting images from a PDF file

2007-12-27 Thread writeson
On Dec 27, 1:12 am, Carl K <[EMAIL PROTECTED]> wrote:
> Doug Farrell wrote:
> > Hi all,
>
> > Does anyone know how to extract images from a PDF file? What I'm looking
> > to do is use pdflib_py to open large PDF files on our Linux servers,
> > then use PIL to verify image data. I want to do this in order
> > to find corrupt images in the PDF files. If anyone could help
> > me out, or point me in the right direction, it would be most
> > appreciated!
>
> If you are ok shelling out to a binary:
>
> pdfimages  -  Portable  Document  Format (PDF) image extractor (version
> 3.00)http://packages.ubuntu.com/gutsy/text/xpdf-utils
>
> I am trying to convert the pdf to a png, but without having to run external
> commands.  so I will understand if you arn't happy with pdfimages.
>
> Carl K

Carl,

Thanks for the feedback, and I don't mind shelling out to an external
command if it gets the job done. Thanks for the link to xpdf-utils,
I'm going to look into it this morning.

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


Re: convert pdf to png

2007-12-27 Thread Lie
On Dec 27, 7:33 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> > Good point.  Not that I am willing to risk it (just using the pdf is not
> > such a bad option)  but I am wondering if it would make sense to create
> > a ramdrive for something like this.  if memory is needed, swap would
> > happen, which should be better than creating files.
>
> You mean permanently deprivating your server of it's precious ram than
> only temporarily? And so far, swapping has always been the worst thing
> to happen for me - whereas mere disk-IO didn't slow _everything_ down.
>
> You should really check your premises on what is affecting performance,
> and what not. And get a faster server...
>
> Diez

What resources this server is lacking currently?
Harddisk space
Harddisk bandwidth (the server just wouldn't stop reading/writing at
peak times)
RAM
Network
CPU

In short, what resource is the most precious and what resources you
still have spares?

Possible option:
* Serve the PDFs directly
--> Harddisk space - low, as it's not converted
--> Harddisk bandwidth - low, depends on how much its requested
--> RAM - low, virtually no RAM usage
--> Network - low, depends on how much its requested
--> CPU - low, virtually no processing is done
--> The simplest to implement, moderate difficulty for users that
don't have PDF reader
--> Users that don't have a PDF reader might experience difficulties,
nowadays most people have Adobe Reader on their computer, and most
people at least know about it. Many computers are also preinstalled
with a pdf reader.

* Preconvert to PNGs, the conversion is done at another computer to
not restrain the server
--> Harddisk space - High, as file is saved as image file
--> Harddisk bandwidth - Moderate, as there are many files and overall
are big
--> RAM - low, virtually no RAM usage
--> Network - Moderate, as the total file served is big
--> CPU - Low, virtually no processing is done
--> Simple

* Serve a precompressed, preconverted PNGs
--> Harddisk space - Moderate-high, should be smaller than just PNG
--> Harddisk bandwidth - Moderate-High, as files can't be served in
chunks
--> RAM - Low, Virtually no RAM usage
--> Network - High, as files can't be served in chunks
--> CPU - Low, virtually no processing is done
--> Moderately-Simple
--> Might be problem if users don't have unzipper (XP, Vista, and most
Linux provides unzipper on default installation, older OSes might not)
--> Files can't be served in chunks, users have to download whole zip
before opening any

* Convert the PDFs to PNG on the fly:
--> Harddisk space - Low, take as much as serving direct PDF
--> Harddisk bandwidth - Moderate to Low, depending on implementation
--> RAM - Moderate, as processing is done, RAM is clearly needed
--> Network - Moderate, as the files served as PNG
--> CPU - High, complex processing is done on the CPU before the file
can be sent to the network
--> Complex to implement

Seeing these options, I think it is much better to serve the PDFs
directly, it's very simple, and very efficient on the server. If
you're afraid that not everyone have PDF readers, direct them to
Adobe's site or serve the installation files on the server. The
installation for the reader is a one-off download, so it should only
choke the server for the first several weeks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python DLL in Windows Folder

2007-12-27 Thread Martin v. Löwis
>> Instead of being upset about cutting your word (which was not my
>> intention, sorry about that), it would be nice if you could make a
>> statement concerning the problem I mentioned: Having an object being
>> created by one MSVC runtime, msvcr80.dll and passing it to another
>> one, msvcr71.dll.
> 
> The C runtime doesn't create objects. 

Depends on your definition of "object". fopen will create objects,
and passing those to a different CRT will cause crashes.

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


Re: Python DLL in Windows Folder

2007-12-27 Thread Martin v. Löwis
> Whatever you want to call it, the Python DLL is not part of the operating
> system, it's not a driver and doesn't belong in the system directory.

Is that just your personal opinion, or a guideline from the operating
system vendor?

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


Re: standalone python web server

2007-12-27 Thread Markus Gritsch
On 27/12/2007, eric <[EMAIL PROTECTED]> wrote:
> Hi all,
>
> I want to setup simple python web server and I want it to just unzip
> and run, without any installation steps (have no right to do it).
>
> I've tried to write by myself, however, I find I am getting into more
> details like processing image file, different file type(like FLV) ..
> etc. Any recommendation or tools suggested for me?

If you do not want to use/extend SimpleHTTPServer from the standard
library and want to have something more like Django (i.e. a Web
Framework) give Gluon http://mdp.cti.depaul.edu/ a try.  It does not
require installation.  For Windows just extract the .zip archive and
launch runme.exe.  Everything is included, even Python.  Same for Mac.
 For Linux the source tarball requires Python 2.4 or newer.

No installation, no configuration, everything can be done from within
the browser.  Watch the screencast at the Gluon homepage for a quick
overview.

Have fun,
Markus
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: standalone python web server

2007-12-27 Thread Tim Chase
> Actually, I've considered to use django, however it required to run
> command (which I don't have right to do it)
> python setup.py install
> 
> Btw, is it possible to use without running setup.py ?

Yes, it's quite possible...Django is pure Python, so you just have to 
have its directory in your runtime path.  I've got several machines that 
have never used "setup.py install" to get Django...I just use a SVN 
checkout, but an untar/gzip would do just as well.

-tkc



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


Re: Subject changed: Bug in combining htmlentitydefs.py and ElementTree?

2007-12-27 Thread Martin v. Löwis
> Sorry for the top posting - I found out that the problem I encountered
> was not something new in Python 3.0.

See Fredrik's message. The problem is not with htmlentitydefs, but with
your usage of ElementTree - in ElementTree, the .entity dictionary
values are not again parsed, apparently causing the '&' to be taken
as a literal ampersand, and not as markup.

That said, it *would* be possible to change htmlentitydefs in Python
3.0, to always map to Unicode characters; this would not be possible for
2.x (as Fredrik points out).

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


Re: Bug in htmlentitydefs.py with Python 3.0?

2007-12-27 Thread Martin v. Löwis
> entity_map = htmlentitydefs.entitydefs.copy()
> for name, entity in entity_map.items():
> if len(entity) != 1:
> entity_map[name] = unichr(int(entity[2:-1]))
> 
> (entitydefs is pretty unusable as it is, but it was added to Python
> before Python got Unicode strings, and changing it would break ancient
> code...)

I would not write it this way, but as

for name,codepoint in htmlentitydefs.name2codepoint:
  entity_map[name] = unichr(codepoint)

I don't find that too unusable, although having yet another dictionary
name2char might be more convenient, for use with ElementTree.

(side note: I think it would be better if ElementTree treated the
.entity mapping similar to DTD ENTITY declarations, assuming internal
entities. The the OP's code might have worked out of the box. That
would be an incompatible change also, of course.)

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


Re: interactive mode in python with ctypes???

2007-12-27 Thread digitnctu
On 12月27日, 下午4�r40分, "Gabriel Genellina" <[EMAIL PROTECTED]>
wrote:
> En Wed, 26 Dec 2007 12:57:44 -0300, <[EMAIL PROTECTED]> escribió:
>
> >  libdll.dll is a third-party library. The below code segment will
> > run well under the batch mode(ie. python test.py 11060)
> >  but when I type sequencially it doesn't work as usual.  Can any
> > give me a hand??
>
> Define "doesn't work as usual"; at least describe what actually happens
> and what you expected to happen instead. If you get an exception, post the
> full traceback.
>
> >   run(string.atoi(sys.argv[1]))
>
> string.atoi is deprecated eons ago; use int() instead
>
> --
> Gabriel Genellina

"doesn't work" means there is no result without exception. The python
interpretter still run without complains; but when running under batch
mode it run as the expectation.  Are there difference for python
interpretter between batch mode and interactive mode ?

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

parallel processing in standard library

2007-12-27 Thread Emin.shopper Martinian.shopper
Dear Experts,

Is there any hope of a parallel processing toolkit being incorporated into
the python standard library? I've seen a wide variety of toolkits each with
various features and limitations. Unfortunately, each has its own API. For
coarse-grained parallelism, I suspect I'd be pretty happy with many of the
existing toolkits, but if I'm going to pick one API to learn and program to,
I'd rather pick one that I'm confident is going to be supported for a while.

So is there any hope of adoption of a parallel processing system into the
python standard library? If not, is there any hope of something like the
db-api for coarse grained parallelism (i.e, a common API that different
toolkits can support)?

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

unicode(s, enc).encode(enc) == s ?

2007-12-27 Thread mario
I have checks in code, to ensure a decode/encode cycle returns the
original string.

Given no UnicodeErrors, are there any cases for the following not to
be True?

unicode(s, enc).encode(enc) == s

mario

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


Re: getting n items at a time from a generator

2007-12-27 Thread Kugutsumen
On Dec 27, 7:24 pm, Terry Jones <[EMAIL PROTECTED]> wrote:
> > "Kugutsumen" == Kugutsumen  <[EMAIL PROTECTED]> writes:
>
> Kugutsumen> On Dec 27, 7:07 pm, Paul Hankin <[EMAIL PROTECTED]> wrote:
>
> >> On Dec 27, 11:34 am, Kugutsumen <[EMAIL PROTECTED]> wrote:
>
> >> > I am relatively new the python language and I am afraid to be missing
> >> > some clever construct or built-in way equivalent to my 'chunk'
> >> > generator below.
>
> Kugutsumen> Thanks, I am going to take a look at itertools.  I prefer the
> Kugutsumen> list version since I need to buffer that chunk in memory at
> Kugutsumen> this point.
>
> Also consider this solution from O'Reilly's Python Cookbook (2nd Ed.) p705
>
>     def chop(iterable, length=2):
>         return izip(*(iter(iterable),) * length)
>
> Terry

> [snip code]
>
> Try this instead:
>
> import itertools
>
> def chunk(iterator, size):
> # I prefer the argument order to be the reverse of yours.
> while True:
> chunk = list(itertools.islice(iterator, size))
> if chunk: yield chunk
> else: break
>

Steven, I really like your version since I've managed to understand it
in one pass.
Paul's version works but is too obscure to read for me :)

Thanks a lot again.


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


  1   2   >