Re: HIRING: PHP Developer

2006-03-26 Thread Skeets
flash is over rated.  rethink that requirement.

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


Re: New-style Python icons

2006-03-26 Thread Robin Becker
Steven Bethard wrote:
...
>>
>>   http://www.doxdesk.com/img/software/py/icons.zip
> 
> I just wanted to say that I've been using these icons for almost a week 
> now and I love them!  I'd like to reiterate EuGeNe's request that these 
> go into the Python 2.5 release if at all possible.
> 
> STeVe

Whilst admitting that my preference is purely old fogeyism, I prefer the 
older icons. However, there is one aspect which seems to be forgotten. 
These logos/icons are much more abstract and so harder to describe 
verbally. It's pretty easy to describe the existing Python icons: "can 
you see a green snake on your desktop?". How does one describe these new 
icons?
-- 
Robin Becker
-- 
http://mail.python.org/mailman/listinfo/python-list


vxWorks port?

2006-03-26 Thread Miki
Hello All,

I saw some old posts about vxWorks port of Python.
Is there someone who can give me pointers to more recent efforts of
porting Python to wxWorks?

Thanks,
Miki

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


Re: OT: unix newbie questions

2006-03-26 Thread Joel Hedlund
 > * I'm using the tcsh shell and have no problems with it, but bash seems
 > more popular - any reason to change? (I don't intend writing many shell
 > scripts)

You can do this in bash:
$ python myprog > stdout.txt 2> stderr.txt

and have output to sys.stdout and sys.stderr go in separate files. Quite handy 
for separating output and debugging comments. I believe that this is impossible 
in tcsh (where you only can do $ python myprog &> stdout_and_stderr.txt to 
catch stdout and stderr at the same time).

Also: bash_completions. It keeps track of arguments and options for commonly 
used programs and commands. If you type "cd " and hit tab for completions you 
will only see directories, since bash_completions knows that this is all cd 
accepts. Don't know if tcsh has anything similar.

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


Re: Firedrop 0.2.0 - The Python Blog Client

2006-03-26 Thread Fuzzyman

Kent Johnson wrote:
> Fuzzyman wrote:
> > It has finally happened, the release of `Firedrop 0.2.0
>
> > * `ConfigObj `_ is
> > now used to edit all the config files.
>
> You should add this to the dependency list in the install page, it
> tripped me up.
>

Actually ConfigObj *is* included in the distribution - I just hadn't
edited a couple of the import statements to use the included one.

Unfortunately this didn't show up on *either* of the machines we tested
on, which both have ConfigObj installed. :-(

My apologies. The distribution has been corrected, so this shouldn't
bite anyone else.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Kent

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


Nevow LivePage tutorial

2006-03-26 Thread Mir Nazim
Hello,

Can any one direct me to some tutorials for:
 1. Nevow LivePage
 2. Form handling in Nevow


Any Help is greately appriciated. I have already googled for it but did
not get any thing helpfull.
Thankyou

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


Re: Module documentation

2006-03-26 Thread Georg Brandl
Tony Burrows wrote:
> Just getting to grips with Python, a great language BUT
> With something like Java I can find the syntax of a method call with no
> problems, how do I do the same with Python?
> 
> For example, using MySQLdb or SGMLParser I can see what the available
> methods are with dir, but how do I find out what parameters are needed and
> what they represent?

In case of extension modules and libraries not in the Python standard library,
they should have a documentation somewhere too.

And if they are implemented in Python, just look at the source to understand
how the methods work.

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


Re: access mbx files?

2006-03-26 Thread Donn Cave
Quoth "David Isaac" <[EMAIL PROTECTED]>:
| "Alan Isaac" <[EMAIL PROTECTED]> wrote in message
| news:[EMAIL PROTECTED]
|> Should I be able to access mail messages in Mahogany mail's mbx
|> format using the Python mailbox module? If so, can someone
|> please post a working example? If not, can you please
|> point me to documentation of the file format or better yet
|> Python code to parse it?
|
| OK, from what I have been able to learn (not a lot),
| my original question may boiled down to:
| has anyone wrapped the cclient library for Python?
...
| Will I need to pursue this, or is this functionality
| somewhere in the mailbox module.  (And if not,
| can someone please explain why not?)

In the end it depends on what you want to do.  But to simply read the
messages out of an MBX format folder, without necessarily accounting
for concurrent access from other applications, c-client is overkill.

If you look at the folder file - after the 4K header (2K? I forget),
the structure is <1-line-header>, and the header doesn't
carry a lot of information that's of supreme importance.  The one
thing you want to extract from it is the length field, which allows
you to index to the next header.  The message data is .  As
far as I can recall, that's all there is to it.

I suppose it isn't supported by the mailbox module basically because
it isn't all that commonly encountered.  It may be more common on mail
servers, but there it's email net protocol data, POP or IMAP.  If
Mahogany has been using this format for `local' folders (i.e., via
filesystem), I think that may have been kind of poor judgement on the
part of its developers.

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


Re: Python has a new Logo

2006-03-26 Thread Randal L. Schwartz
> "adapt" == adapt her [EMAIL PROTECTED] com <[EMAIL PROTECTED]> writes:

adapt> Yawn. Go start indenting, and stop using Perl. If Python has such a
adapt> nice logo, why waste any more time with Perl?

Chuck Norris can indent a Python program any way he wants, and it still works.

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
 http://www.stonehenge.com/merlyn/>
Perl/Unix/security consulting, Technical writing, Comedy, etc. etc.
See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training!
*** Free account sponsored by SecureIX.com ***
*** Encrypt your Internet usage with a free VPN account from 
http://www.SecureIX.com ***
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: maximum() efficency

2006-03-26 Thread Steve R. Hastings
On Mon, 27 Mar 2006 00:11:04 +, Paul McGuire wrote:
> The doc string is not correct.

The fault is mine, I'm afraid.  I had thought I was copying that from an
intact original version, but I must have edited it.  I don't remember
doing it, but I must have.

To check, I went to Sourceforge and downloaded goopy again.  Here, for
the record, is the original Google maximum():



def maximum(cmp, lst):
  """maximum(cmp, lst)

  Returns the maximal element in non-empty list LST with elements
  compared via CMP() which should return values with the same semantics
  as Python's cmp().  If there are several maximal elements, the last
  one is returned.
  """

  if not lst:
raise ValueError, 'empty list'

  maxval = lst[0]

  for i in xrange(1, len(lst)):
v = lst[i]
if cmp(maxval, v) <= 0:
  maxval = v

  return maxval



I apologize for the error.

P.S. I'm happy to see that Google uses "lst" for a list.  I do, too.  I
don't much like the convention of using "L" for a list, but I agree with
Guido that using "l" is bad (looks too much like a one: "1"), so "lst" it
is.

I would have put the "cmp" argument second, and made it default to the
built-in Python "cmp" function if not specified.  Oh, well.
-- 
Steve R. Hastings"Vita est"
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: How to learn python if I'm very familar with C++

2006-03-26 Thread bill pursell
[EMAIL PROTECTED] wrote:
> Hi,
>
> I've been using C++ for a few years and have developed a few projects
> in C++. And I'm familar with OO and template metaprogramming.
>
> There are some book like "Learning Perl". It is a little bit tedious
> for me, because more material in that book seems obvious for me. I want
> some book describe the difference between C++ and python such that I
> could grasp python quickly. Would you please give me some infomation on
> this?
>

Take a few hours to read through the tutorial at
http://docs.python.org/tut/tut.html

Then spend some time browsing the rest of the documentation.

After you have a basic understanding of the syntax, browse the Python
Cookbook.

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


Re: "For" loop and list comprehension similarity

2006-03-26 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> Why not combine the two:
>
> I guess because (at least in source code) you're doing a loop twice
> :-). I don't know what a compiler would do. I think though that the
> "for i in c if test:" construct is more readable and maybe can even be
> better optimized.

 There are also the filter and ifilter functions:

for i in filter(testfunc, c):

tjr



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


Re: What's the best way to learn perl for a python programmer?

2006-03-26 Thread Serge Orlov
vj wrote:
> I've been given a project which requires writing scripts that need to
> be run on over 3000 servers. Only about 15% of them have python
> installed on them. While all/most of them will have perl.

I used to work for a company with hundreds of development workstations
and build/test servers, different operating systems (add to the mixture
regular disk failures and regular hiring of new people). Everything was
controlled by pretty big perl scripts and people who maintained all the
tools found that using perl from distributions was a hassle because of
differences between perl versions and the need to install it if OS
doesn't have it. So they just built several (for different
OSes/archetectures) relocatable distributions of perl and put them on a
network drive. That turned out to be more reliable and more easy to
maintain.

You can do the same with python.

> I'll try and do as much as possible in pexpect but am sure I'll have do
> some significant perl. Any suggestions on what is the best way to get
> upto speed on perl?

Forget about perl :)

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


Re: a problem to solve

2006-03-26 Thread [EMAIL PROTECTED]
Clemens Hepper wrote:
> Hi,
>
> [EMAIL PROTECTED] wrote:
> > That's one way to do it. I did it that way because I have the
> > hex patterns memorized.
>
> You should be able to generate your numbers like this:
>
> number = int('001001000100100', 2)

Well, that would be another way, wouldn't it?

Thanks for the tip, but you're a bit late (pun intended),
we've both already solved the problem. And since base
conversion is a one-way street in Python, the fact that
you can do that doesn't eliminate the need for gmpy
(or something equivalent) if you want to go the other
way, decimal to binary.

And furthermore, having Python's bitwise operators
is nice, but it's not nice enough. I need the bitwise
functionality gmpy provides that's not available in
Python: scan for position of least significant 1 or 0,
count of 1 bits, Hamming distance, etc.

So, rather than point out that one can do

 number = int('001001000100100', 2)

I would rather advise that the person obtain gmpy
and use its conversion

 number = gmpy.mpz('001001000100100', 2)

They'll thank me eventually.

> 
> mfg
> - eth

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


Re: determine file type

2006-03-26 Thread Mark Gibson

> 
> 
> import os
> def test_file(filename, maxread=1024):
>if os.path.isdir(filename):
>  return 'directory'
>afile = open(filename) # open as text
>for achar in afile.read(maxread):
>  if ord(achar) > 127:
>return 'binary'
>return 'text'
> 
> 

Pefect, thanks!

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


Re: How to learn python if I'm very familar with C++

2006-03-26 Thread bitshadow
[EMAIL PROTECTED] wrote:
> >The book "Learning Python" worked for me (a long time C++ person).
>
> Me too. I programmed in nothing but C++ for years, but this book made
> learning Python easy.

there are tons of tutorials available on the web. if your familiar with
C++ then the tutorial that comes with the latest download of the
interpreter should be fine. for myself though i learned python with
this book: http://apress.com/book/bookDisplay.html?bID=10013

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


Re: wildcard exclusion in cartesian products

2006-03-26 Thread John Zenger
A quick fix:  change your last two functions to:

def generateNotMatching(A,n,P):
 for g in gen(A,n,P,[]):
 for x in g:
 yield x

def gen(A,n,P,acc):
 if any(imap((lambda p:  allStar(p) and notNullOrZero(p,n)), P)):
yield []
 else:
if n==0:
   yield map(rev,[acc])
else:
   for a in A:
   for xx in gen(A,n-1,advancePatterns(a,P),[a]+acc):
   yield xx

For the most part, just replace return with yield.

By the way:  you are reinventing the wheel with imap and rev.  imap is 
itertools.imap.  rev(L) is the same as L[:-1].

[EMAIL PROTECTED] wrote:
> The python code below is adapted from a Haskell program written by
> Tomasz
> Wielonka on the comp.lang.functional group. It's more verbose than his
> since I wanted to make sure I got it right.
> 
> http://groups.google.com/group/comp.lang.functional/browse_frm/thread...
> 
> Does anyone know how to turn it into a module (or whatever it's called)
> so that I can put it in a
> loop and not have to generate the whole list? I've already tried
> without success.
> 
> The program solves the following problem: generate the subset X of the
> cartesian product S^n that excludes n-tuples defined by wildcards. For
> example, if I want to exclude from [1,2,3]^3 the wc's [1,"*",2] and
> ["*",3,"*",3,"*"], where "*" stands for a sequence of zero or more
> elements of [1,2,3], then I just type
> 
> for x in generateNotMatching([1,2,3,4],4,[[1,'*',2],[3,'*',4]]): print
> x
> 
> and get the output
> 
>[1, 1, 1]
>[1, 1, 3]
>[1, 2, 1]
>[1, 2, 3]
>[1, 3, 1]
>[2, 1, 1]
>[2, 1, 2]
>[2, 1, 3]
>[2, 2, 1]
>[2, 2, 2]
>[2, 2, 3]
>[2, 3, 1]
>[2, 3, 2]
>[3, 1, 1]
>[3, 1, 2]
>[3, 2, 1]
>[3, 2, 2]
> 
> This is nice! But all elements are generated before they are printed.
> 
> ##
> import sys, os, string
> 
> def imap(function, source):
> for element in source:
> yield function(element)
> 
> def any(iterable):
>  '''True iff at least one element of the iterable is True'''
>  for element in iterable:
> if element:
> return True # or element and change the definition
>  return False
> 
> def all(iterable):
>  '''True iff no element of the iterable is True'''
>  '''SHOULD BE?: True iff all element of the iterable are True'''
>  for element in iterable:
> if not element:
> return False
>  return True
> 
> def rev(L):
> rL=[]
> for x in L: rL=[x]+rL
> return rL
> 
> def advancePattern(x,p):
> if p==[]: return []
> else:
>h=p[0]
>t=p[1:]
>if h != '*':
>   if h == x: return [t]
>   else: return []
>else: return [p] + [t] + advancePattern(x,t)
> 
> def advancePatterns(x,P):
> aP=[]
> for p in P:
> aP += advancePattern(x,p)
> return aP
> 
> #return [advancePattern(x,p) for p in P]
> 
> def allStar(p):
> return all( imap((lambda x: x=='*'),p) )
> 
> def notNullOrZero(p,n):
> return p !=[] or n==0
> 
> def generateNotMatching(A,n,P):
> return gen(A,n,P,[])
> 
> def gen(A,n,P,acc):
> if any(imap((lambda p:  allStar(p) and notNullOrZero(p,n)), P)):
>return []
> else:
>if n==0:
>   return map(rev,[acc])
>else:
>   aG=[]
>   for a in A:
>   aG += gen(A,n-1,advancePatterns(a,P),[a]+acc)
>   return aG
> 
> ##
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to learn python if I'm very familar with C++

2006-03-26 Thread [EMAIL PROTECTED]
>The book "Learning Python" worked for me (a long time C++ person).

Me too. I programmed in nothing but C++ for years, but this book made
learning Python easy.

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


Menu For The Command Line?

2006-03-26 Thread Michael Sperlle
When I bring up the command line interface, it looks like: [EMAIL PROTECTED]

Then I type in some command, and it works!

But there are lots of commands to type in, and I find it more and more
difficult to remember them.

Is there any way to build a menu of frequently-used commands, so that when
I bring up the command line interface, I can see this menu and be reminded
of what command does what?

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


Re: How to learn python if I'm very familar with C++

2006-03-26 Thread Jim Benson
On 26 Mar 2006, [EMAIL PROTECTED] wrote:

> Hi,
> 
> I've been using C++ for a few years and have developed a few projects
> in C++. And I'm familar with OO and template metaprogramming.
> 
> There are some book like "Learning Perl". It is a little bit tedious
> for me, because more material in that book seems obvious for me. I want
> some book describe the difference between C++ and python such that I
> could grasp python quickly. Would you please give me some infomation on
> this?
> 
> Thanks,
> Peng
> 
> 

The book "Learning Python" worked for me (a long time C++ person).

Jim

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


How to learn python if I'm very familar with C++

2006-03-26 Thread [EMAIL PROTECTED]
Hi,

I've been using C++ for a few years and have developed a few projects
in C++. And I'm familar with OO and template metaprogramming.

There are some book like "Learning Perl". It is a little bit tedious
for me, because more material in that book seems obvious for me. I want
some book describe the difference between C++ and python such that I
could grasp python quickly. Would you please give me some infomation on
this?

Thanks,
Peng

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


Re: a problem to solve

2006-03-26 Thread Clemens Hepper
Hi,

[EMAIL PROTECTED] wrote:
> That's one way to do it. I did it that way because I have the
> hex patterns memorized.

You should be able to generate your numbers like this:

number = int('001001000100100', 2)

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


Re: Python float representation error?

2006-03-26 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> try running this in python:
> 
> print [39.95]
> 
> the output i get is:
> [39.953]
> 
> what's up with that?

Why not start by reading the Python online tutorial?  Specifically
?


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


Re: Bitwise OR?

2006-03-26 Thread Clemens Hepper
Okay... pythons build-in methods are quite fast. so is hex().

with about 64 kb memory i can write it with a 16 bit dictionary
where the dictionary generation itself is not yet optimized:

def genBitList(exp):
  next = lambda now: [x+'0' for x in now]+[x+'1' for x in now]
  result = [""]

  for x in range(exp):
result = next(result)

  return result

_digits = genBitList(16)

def bitstring2(number):
  """lsb-->msb"""
  rlist = list()
  if number >= 0:
while number:
  rlist.append( _digits[number & 0x] )
  number >>= 16
return ''.join(rlist).rstrip('0')
  else:
while number != -1:
  rlist.append( _digits[number & 0x] )
  number >>= 16
return ''.join(rlist).rstrip('1')

this is quite fast and in lots of cases faster than the
hex()-version. however your method (with my inverses formatting) is
very fast, too and without so much memory expense:

_nibbles = {"0":"", "1":"0001", "2":"0010", "3":"0011",
"4":"0100", "5":"0101", "6":"0110", "7":"0111",
"8":"1000", "9":"1001", "a":"1010", "b":"1011",
"c":"1100", "d":"1101", "e":"1110", "f":"",
"l":"", "-":"", "x":""}

from string import maketrans, translate

_invert = maketrans('01', '10')

def bitstring3( number ):
  if number > 0:
return ''.join( [_nibbles[d] for d in
  hex(  number ).lower()] ).lstrip( '0' )
  else:
return translate(''.join( [_nibbles[d] for d in
  hex( ~number ).lower()] ).lstrip( '0' ), _invert)

Benchmark:
  for 0xa:
bitstring2: 0.61802315712
bitstring3: 0.91001200676

  for 0x:
bitstring2: 0.561501026154
bitstring3: 1.11787199974

  for 0x:
bitstring2: 1.2295820713
bitstring3: 1.61559510231

  for 0x:
bitstring2: 1.90036797523
bitstring3: 2.2683339119

  for -0x:
bitstring2: 2.81339716911
bitstring3: 2.74266886711

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


Re: access mbx files?

2006-03-26 Thread David Isaac
"Alan Isaac" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Should I be able to access mail messages in Mahogany mail's mbx
> format using the Python mailbox module? If so, can someone
> please post a working example? If not, can you please
> point me to documentation of the file format or better yet
> Python code to parse it?

OK, from what I have been able to learn (not a lot),
my original question may boiled down to:
has anyone wrapped the cclient library for Python?

The answer to that appears to be yes:
http://freshmeat.net/projects/python-cclient/

Will I need to pursue this, or is this functionality
somewhere in the mailbox module.  (And if not,
can someone please explain why not?)

Thanks,
Alan Isaac


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


Re: determine file type

2006-03-26 Thread James Stroud
Mark Gibson wrote:
> Is there an equivalent to the unix 'file' command?
> 
> [mark tmp]$ file min.txt
> min.txt: ASCII text
> [mark tmp]$ file trunk
> trunk: directory
> [mark tmp]$ file compliance.tgz
> compliance.tgz: gzip compressed data, from Unix
> 
> What I really want to do is determine if a file is 1) a directory, 2) a 
> text file 3) a binary file.
> 
> Is there a way to do this?
> 
> Mark

import os
def test_file(filename, maxread=1024):
   if os.path.isdir(filename):
 return 'directory'
   afile = open(filename) # open as text
   for achar in afile.read(maxread):
 if ord(achar) > 127:
   return 'binary'
   return 'text'


James



-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: maximum() efficency

2006-03-26 Thread Steven Bethard
Steve R. Hastings wrote:
> On Sun, 26 Mar 2006 10:34:16 -0700, Steven Bethard wrote:
>> What's the original?
> 
> def minimum(cmp, lst):
>   """minimum(cmp, lst)
> 
>   Returns the minimal element in non-empty list LST with elements
>   compared via CMP() which should return values with the same semantics
>   as Python's cmp().  If there are several minimal elements, the last
>   one is returned.
>   """
> 
>   if not lst:
> raise ValueError, 'empty list'
> 
>   minval = lst[0]
> 
>   for i in xrange(1, len(lst)):
> v = lst[i]
> if cmp(minval, v) > 0:
>   minval = v
> 
>   return minval
> 
> This is from Google's "goopy" package.
> 
> http://goog-goopy.sourceforge.net/

Ahh.  Yeah, nasty cmp= arguments certainly do screw that up.

If you're not just trying to implement a particular API, and you 
actually have a use-case you think you need this for, you might consider 
a key= argument instead of a cmp= argument.  It'll probably be at least 
as fast, and Python 2.5 will have one on both min() and max().  It'll 
work something like:
 http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/389659


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


Re: PIL & image size reduction script

2006-03-26 Thread nikie
Philippe Martin wrote:
> Hi,
>
> Thanks to the NG, I got the script hereunder working.
>
> 1) I am not certain that the call to convert does much (checking the doc)

I think you only need it if your source image comes in a format that
can't be stored into a jpeg file (e.g. 8-bit paletted). You'll need
that if you're converting from GIF files, for example. It shouldn't
hurt otherwise.

> 2) Can this be improved as far as the final image size in (X,Y) ?

I'm not sure if I get you: You tell the image object it's new
(X,Y)-size in the resize method, don't you?

> For instance, passing a large .jpg with a target byte size of 7000, I get
> final (X,Y) results around (213, 174) ... but might want to strech it a bit
> while keeping the byte size.

If I got you right, you want to compress the image to a certain file
size. Maybe you should try optimizing the additional save parameters
for the jpeg encoder.
(http://www.pythonware.com/library/pil/handbook/formats.htm). Try
reducing the "quality" parameter.
  l_image.save(l_tmp_file_name, quality=25) 

Hope this helps.

Niki

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


determine file type

2006-03-26 Thread Mark Gibson
Is there an equivalent to the unix 'file' command?

[mark tmp]$ file min.txt
min.txt: ASCII text
[mark tmp]$ file trunk
trunk: directory
[mark tmp]$ file compliance.tgz
compliance.tgz: gzip compressed data, from Unix

What I really want to do is determine if a file is 1) a directory, 2) a 
text file 3) a binary file.

Is there a way to do this?

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


Re: New-style Python icons

2006-03-26 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
> Personally, I *like* the new website look, and I'm glad to see Python
> having a proper logo at last!
> 
> I've taken the opportunity to knock up some icons using it, finally
> banishing the poor old standard-VGA-palette snake from my desktop. If
> you like, you can grab them from:
> 
>   http://www.doxdesk.com/img/software/py/icons.zip

I just wanted to say that I've been using these icons for almost a week 
now and I love them!  I'd like to reiterate EuGeNe's request that these 
go into the Python 2.5 release if at all possible.

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


Re: Python float representation error?

2006-03-26 Thread nikie
> try running this in python:
>
> print [39.95]
>
> the output i get is:
> [39.953]
>
> what's up with that?

That's perfectly normal - some numbers aren't exactly expressible as
binary floating points, just like 1/3 isn't expressible as a decimal
floating point number.

Here's a good link on floating point arithmetic:
http://docs.sun.com/source/806-3568/ncg_goldberg.html

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


Re: maximum() efficency

2006-03-26 Thread Paul McGuire
"Steve R. Hastings" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> On Sun, 26 Mar 2006 10:34:16 -0700, Steven Bethard wrote:
> > What's the original?
>
>
>
> def minimum(cmp, lst):
>   """minimum(cmp, lst)
>
>   Returns the minimal element in non-empty list LST with elements
>   compared via CMP() which should return values with the same semantics
>   as Python's cmp().  If there are several minimal elements, the last
>   one is returned.
>   """
>
>   if not lst:
> raise ValueError, 'empty list'
>
>   minval = lst[0]
>
>   for i in xrange(1, len(lst)):
> v = lst[i]
> if cmp(minval, v) > 0:
>   minval = v
>
>   return minval
>
>
>
> This is from Google's "goopy" package.
>
> http://goog-goopy.sourceforge.net/
>
> -- 
> Steve R. Hastings"Vita est"
> [EMAIL PROTECTED]http://www.blarg.net/~steveha
>

The doc string is not correct.  If there are several minimal elements, the
*first* one is returned.  See this example:

import math

class Vector(object):
def __init__(self,*x):
# x is list of n-dimensional coordinates
self.x = x

def magnitude(self):
return math.sqrt(sum(x**2 for x in self.x))

def __cmp__(self,other):
return cmp(self.magnitude(), other.magnitude())

def __str__(self):
return "Vector(%s)" % ",".join(str(x) for x in self.x)

a = Vector(0,1)
b = Vector(0,0)
c = Vector(1,0)

# these print 1, -1, and 0 to show that cmp() and Vector are doing the right
thing
print cmp(a,b)
print cmp(b,a)
print cmp(a,c)

print min(a,b)   # gives Vector(0,0), or b
print max(a,b,c)   # gives Vector(0,1) or a
print min(a,c)# gives Vector(0,1) or a

print minimum(Vector.__cmp__, [a,b])   # gives Vector(0,0), or b
print minimum(Vector.__cmp__, [a,c])# gives Vector(0,1) or a


-- Paul


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


Re: maximum() efficency

2006-03-26 Thread Steve R. Hastings
Actually, now that I think about it, the version using iter() has one
advantage over your version: it will work correctly if passed either a
list or an iterator.  So, for versions of Python that have iterators, I'd
use the iter() version, but for older versions of Python, I'd use your
version.

P.S. I benchmarked your version; it ran in 22.0 seconds, just a gnat's
whisker faster than the iter() version.
-- 
Steve R. Hastings"Vita est"
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: interactive programme (add a new line in Tk)

2006-03-26 Thread James Stroud
nigel wrote:
> somebody recently  showed me how to create a new line using \n which was 
> great.The thing is when i am creating the programme the text i wish to add is 
> quite long.and it ends up stretching the width of several pages,which i think 
> looks quite messy.Would it be possible for some one to show me how to create 
> another line while writing my programme.What i mean by this is where my text 
> ends "iv arrived"i wish to add a new line beneath to continue my text so i do 
> not reach the end of the page.
> 
> from Tkinter import *
> 
> root = Tk()
> 
> w = Label(root, text="\n Hello, world! \n iv arrived")
> w.pack()
> 
> root.mainloop()
> 
> Thanks nige

Try the Tkinter.Text widget. You can configure it to be read only, etc. 
so it behaves like a label. It will automatically wrap text for you and 
will put in line breaks ("\n") where you tell it. See

http://www.pythonware.com/library/tkinter/introduction/text.htm

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python float representation error?

2006-03-26 Thread James Stroud
[EMAIL PROTECTED] wrote:
> try running this in python:
> 
> print [39.95]
> 
> the output i get is:
> [39.953]
> 
> what's up with that?
> 

This comes from the imprecision in representing base-10 fractions as 
binary. Try "print [str(39.95)]".

If you want to print a list, maybe:

print map(str, alist)

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What's the best way to learn perl for a python programmer?

2006-03-26 Thread john_sips_tea
The online docs are very good. Just run "perldoc perl", and then go
through the various tutorial pages (starting with "perldoc perlintro").
You can also read them online here: http://perldoc.perl.org/perl.html .

Then go to http://www.perlmonks.org . They have many tutorial-style
articles there, as well as a very helpful and knowledgeable community.

If you absolutely need to write object-oriented Perl, you probably want
to keep things as simple as possible and just use regular old
hash-based objects. Writing OO Perl code is a whole nuther ball of wax
than just writing procedural Perl code.

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


Re: maximum() efficency

2006-03-26 Thread Steve R. Hastings
On Sun, 26 Mar 2006 10:34:16 -0700, Steven Bethard wrote:
> What's the original?



def minimum(cmp, lst):
  """minimum(cmp, lst)

  Returns the minimal element in non-empty list LST with elements
  compared via CMP() which should return values with the same semantics
  as Python's cmp().  If there are several minimal elements, the last
  one is returned.
  """

  if not lst:
raise ValueError, 'empty list'

  minval = lst[0]

  for i in xrange(1, len(lst)):
v = lst[i]
if cmp(minval, v) > 0:
  minval = v

  return minval



This is from Google's "goopy" package.

http://goog-goopy.sourceforge.net/

-- 
Steve R. Hastings"Vita est"
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: [ANN] Firedrop 0.2.0 - The Python Blog Client

2006-03-26 Thread Kent Johnson
Fuzzyman wrote:
> It has finally happened, the release of `Firedrop 0.2.0

> * `ConfigObj `_ is
> now used to edit all the config files.

You should add this to the dependency list in the install page, it 
tripped me up.

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


Python float representation error?

2006-03-26 Thread [EMAIL PROTECTED]
try running this in python:

print [39.95]

the output i get is:
[39.953]

what's up with that?

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


Re: maximum() efficency

2006-03-26 Thread Steve R. Hastings
On Sun, 26 Mar 2006 20:34:28 +0200, Mitja Trampus wrote:
> I would have done it in the same way, but probably without the iterators. 
> I.e., like this:
> 
> def maximum(lst):
>   try: m = lst[0]
>   except (TypeError, IndexError): raise Exception "Non-sequence or empty 
> sequence given to 
> maximum")
> 
>   # (you forgot the above sanity checks in your code.
>   # not strictly necessary, but nice to have.)
> 
>   for x in lst:
>   if x>m: m=x
>   return m

I left out the original sanity check, because I just wanted a streamlined
simple example.


I had a nagging feeling that I was missing something simple, and you have
put your finger on it.  That's perfect!  It's simple, it's clear, and it
will work on any version of Python.  Thanks!
-- 
Steve R. Hastings"Vita est"
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: py web-app-frameworks without a rdbms...

2006-03-26 Thread Michael Goettsche
On Wednesday 22 March 2006 02:06, [EMAIL PROTECTED] wrote:
> Hi folks,
>
> Of TurboGers & Django WAF candidates, which one would be easier to use
> in an environment where the data/content doesn't come an RDBMS, but
> from other server-side apps... If these are not good candidates, could
> you suggest appropriate ones...
>
> TIA,
> /venkat

Be sure to have a look at CherryPy: http://www.cherrypy.org

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


Re: Python multithreading problem

2006-03-26 Thread Serge Orlov
abhinav wrote:
> //A CRAWLER IMPLEMENTATION
> please run this prog. on the shell and under the control of debugger
> when this prog. is run normally the prog. does not terminate .It
> doesn't come out of the cond. if c<5: so this prog. continues
> infinitely

How do you know? Have you waited *infinitely* ;)


>   if c<5:
>   self.stdmutex.acquire()

The problem you have a lot of threads that has already checked c < 5
condition but has not acquired the lock yet. Besides you have another
problem: if a thread raises an exception you don't release the lock.
Why don't you use Queue module for sane thread management?

  Serge.

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


Re: "For" loop and list comprehension similarity

2006-03-26 Thread John Zenger
Rather than a list comprehension, it would be faster and more 
memory-efficient to use a generator comprehension.  Just change the 
square brackets to parentheses:

 for j in (i*2 for i in c if ):
print j


Grant Edwards wrote:
> On 2006-03-26, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> 
>>Hi All,
>>
>>I apologize if this was brought up before, I couldn't find any "prior
>>art" :-).
>>On more than one occasion, I found myself wanting to use a "conditional
>>loop" like this (with "Invalid syntax" error, of course):
>>
>>  for i in c if :
>>  print i*2
>>
>>...because it's similar to the list comprehension construct:
>>
>>  [i*2 for i in c if ]
>>-
>>
>>Is this the intended difference in constructs? The available equivalent
>>feels a bit awkward:
>>
>>  for i in c:
>>  if :
>>  print i*2
> 
> 
>for j in [i*2 for i in c if ]:
>   print j
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "For" loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
> Why not combine the two:

I guess because (at least in source code) you're doing a loop twice
:-). I don't know what a compiler would do. I think though that the
"for i in c if test:" construct is more readable and maybe can even be
better optimized.
Thanks!

Sergey.

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


PyPy is now able to compile efficient extension modules!

2006-03-26 Thread Luis M. González
"PyPy is now able to compile efficient extension modules!".

This was recently announced by Christian Tismer on Pypy's mailing list.
To learn more:
http://codespeak.net/pipermail/pypy-dev/2006q1/002911.html

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


Re: Bitwise OR?

2006-03-26 Thread Clemens Hepper
Adam DePrince wrote:
>> BTW: Is there something like a sizeof() method for int numbers?
> 
> import struct
> help( strict.calcsize )
Mh, that doesn't do what i want. I'd like to have something like:

def size(number):
  return sizeof(number)

> Why one bit at a time?

Good question...

Here my new approach based on your idea:

_digits = { 0:"", 1:"1000", 2:"0100", 3:"1100",
4:"0010", 5:"1010", 6:"0110", 7:"1110",
8:"0001", 9:"1001", 0xa:"0101", 0xb:"1101",
0xc:"0011", 0xd:"1011", 0xe:"0111", 0xf:""}

def bitstring2(number):
  """lsb-->msb"""
  rlist = list()
  if number >= 0:
while number:
  rlist.append( _digits[number & 0xF] )
  number >>= 4
  else:
while number != -1:
  rlist.append( _digits[number & 0xF] )
  number >>= 4

  return ''.join(rlist)

This was faster for positive numbers. For negative numbers yours was
faster, but my version handles those numbers different.

Your version fails for Large numbers since hex( long ) returns
something like "0xFFFL" instead of "0xfff".

> Cheers - Adam

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


work at home

2006-03-26 Thread magaznan

 
Collecter rapidement les informations nécessaires pour

   travailler de chez soi 


avec son ordinateur



et de ce fait amasser rapidement des rentrées  d'argents plus qu'honorables 





To collect the necessary information quickly for

   to work of at home 

with your computer

and of that made accumulate quickly of the returns of money more that honorable 






contact:
[EMAIL PROTECTED]



http://www.allsolutionsnetwork.com/RN/RN32579


http://10perday.com/?ref=5113



This message was sent with NNTP Scribbler (www.e-advertize.com).
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Accessing func_name from inside a function

2006-03-26 Thread Ron Adam
Alex Martelli wrote:
> Ron Adam <[EMAIL PROTECTED]> wrote:
> 
>> A "Current" key word would fix this.  Or possibly "This" which would be
>> short for "This object".
> 
> I think "This" would cause huge confusion, since in other popular
> language the keyword "this" means (a pointer/reference to) "the instance
> variable on which the method is being called" -- my use is instead for
> "the object of the immediate lexically enclosing scope" (a module,
> class, or function).  Implementation wouldn't be trivial in today's
> CPython, anyway: frames have no references at all to function objects
> (only to _code_ objects), and class objects don't even exist untill well
> after their top-level code has long finished running; to make Current
> possible, these subtle points of semantics would have to be changed in
> quite a revolutionary way, especially where classes are concerned.
> 
> 
> Alex

Yes, I figured it would not be an easy or simple addition.  An easier 
alternative might be to be able to limit specific name rebindings.  Then 
some names could be depended on to always point to a specific object. 
Something like that would need to be used sparingly I think.

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


interactive programme (add a new line in Tk)

2006-03-26 Thread nigel
somebody recently  showed me how to create a new line using \n which was 
great.The thing is when i am creating the programme the text i wish to add is 
quite long.and it ends up stretching the width of several pages,which i think 
looks quite messy.Would it be possible for some one to show me how to create 
another line while writing my programme.What i mean by this is where my text 
ends "iv arrived"i wish to add a new line beneath to continue my text so i do 
not reach the end of the page.

from Tkinter import *

root = Tk()

w = Label(root, text="\n Hello, world! \n iv arrived")
w.pack()

root.mainloop()

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


Re: "For" loop and list comprehension similarity

2006-03-26 Thread Ben Finney
[EMAIL PROTECTED] writes:

> On more than one occasion, I found myself wanting to use a "conditional
> loop" like this (with "Invalid syntax" error, of course):
>
>   for i in c if :
>   print i*2
>
> ...because it's similar to the list comprehension construct:
>
>   [i*2 for i in c if ]

Why not combine the two:

for i in [j for j in c if ]:
print i*2

-- 
 \   "I got food poisoning today. I don't know when I'll use it."  |
  `\  -- Steven Wright |
_o__)  |
Ben Finney

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


Re: New development windows, IronPython or PythonWin

2006-03-26 Thread Fuzzyman

[EMAIL PROTECTED] wrote:
> IronPython is currently nowhere near production quality. I would not
> recommend it.

I know at least one firm developing production quality software using
IronPython, so your statement 'nowhere near' is a bit off.

They're pretty close to a full Python 2.4 implementation , and the list
of bugs shrinks daily.

It's not a project that's about to disappear either.

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


Re: What's The Best Editor for python

2006-03-26 Thread Charles Krug
On 2006-03-26, Andrew Gwozdziewycz <[EMAIL PROTECTED]> wrote:
> If you want something that won't get in your way, you should really  
> use /bin/ed. It's probably simpler to use then searching the archives.
> /bin/ed will also run in cygwin for windows.
>
>>> Can one of you say to me what's the best editor for
>>> editing the python programs( for linux or windows )
>

The best editor is the one you like best.

I'm a vim user with taglist--I'm not fully happy with how ctags does
Python, but it's more than Good Enough.

But editors are religious, and not worth arguing about, generally.
-- 
http://mail.python.org/mailman/listinfo/python-list


regimes

2006-03-26 Thread magaznan

 
Collecter rapidement les informations nécessaires pour

   travailler de chez soi 


avec son ordinateur



et de ce fait amasser rapidement des rentrées  d'argents plus qu'honorables 





To collect the necessary information quickly for

   to work of at home 

with your computer

and of that made accumulate quickly of the returns of money more that honorable 






contact:
[EMAIL PROTECTED]



http://www.allsolutionsnetwork.com/RN/RN32579


http://10perday.com/?ref=5113



This message was sent with NNTP Scribbler (www.e-advertize.com).
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: MVC in Python for web app dev

2006-03-26 Thread Robert Hicks
http://www.myghty.org/

That one is excellent.

Robert

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


Re: wildcard exclusion in cartesian products

2006-03-26 Thread [EMAIL PROTECTED]
Michael,

Yes! That is precisely what I had in mind! 

Thanks,

Walter Kehowski

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


Re: Python types

2006-03-26 Thread Salvatore
Thank's Bruno.

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


Re: wildcard exclusion in cartesian products

2006-03-26 Thread Michael Spencer
[EMAIL PROTECTED] wrote:
> The python code below is adapted from a Haskell program written by
> Tomasz
> Wielonka on the comp.lang.functional group. It's more verbose than his
> since I wanted to make sure I got it right.
> 
> http://groups.google.com/group/comp.lang.functional/browse_frm/thread...
> 
> Does anyone know how to turn it into a module (or whatever it's called)
> so that I can put it in a
> loop and not have to generate the whole list? I've already tried
> without success.

I know next to nothing about Haskell, but I believe that it evaluates sequences 
lazily by default.  Python can certainly do lazy evaluation, but you'll have to 
ask for it explicitly.
> 
> The program solves the following problem: generate the subset X of the
> cartesian product S^n that excludes n-tuples defined by wildcards. For
> example, if I want to exclude from [1,2,3]^3 the wc's [1,"*",2] and
> ["*",3,"*",3,"*"], where "*" stands for a sequence of zero or more
> elements of [1,2,3], then I just type
> 

[I think your example and test case may have become mixed up]
...

Here's an iterative "lazy" solution.  While we're at it, why not use re for 
pattern matching, rather than rolling our own matcher (this does restrict the 
set members to characters, maybe that's OK):

import re

def cp_excl_wc(alpha, N, *exclusions):
 RE0, RE1 = compile_re(exclusions)
 def add_one(outer, RE_PATTS):
 if RE_PATTS:
 for partial in outer:
 for a in alpha:
 next = partial + a
 if not RE_PATTS.match(next):
 yield next
 else: # if there's no pattern to match at this length
   # don't waste time trying
 for partial in outer:
 for a in alpha:
 yield partial+a
 cpgen = "",
 # RE0 holds the patterns that match at the beginning, so are tested
 # against all iterations less than full length
 for n in range(N-1):
 cpgen = add_one(cpgen, RE0)
 # For the last place, test the full-length patterns
 cpgen = add_one(cpgen, RE1)
 return cpgen


def compile_re(exclusions):
 re0 = [] # patterns that can be matched anywhere
 re1 = [] # patterns that match only the full-length
 for pattern in exclusions:
 pattern = pattern.replace("*", ".*")
 if pattern.endswith(".*"):
 re0.append(pattern)
 re1.append(pattern+"$")

 re0 = re0 and re.compile("|".join(re0)) or None
 re1 = re1 and re.compile("|".join(re1)) or None
 return re0, re1

 >>> nm = cp_excl_wc("123",3,"1*2","3*1")
 >>> nm.next()
'111'
 >>> nm.next()
'113'
 >>> nm.next()
'121'
 >>> nm.next()
'123'
 >>> list(nm)
['131', '133', '211', '212', '213', '221', '222', '223', '231', '232', '233', 
'312', '313', '322', '323', '332', '333']
 >>>

Is this the sort of thing you had in mind?

Michael

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


Re: Accessing func_name from inside a function

2006-03-26 Thread Eyal Lotem
Steven D'Aprano wrote:

> On Sun, 26 Mar 2006 10:19:36 +1000, Ben Finney wrote:
> 
>> "James Thiele" <[EMAIL PROTECTED]> writes:
>> 
>>> I'd like to access the name of a function from inside the function.
>> 
>> A function, like most other objects in Python, can have any number of
>> names bound to it without the object being informed. Any of those
>> names can then be used to reference the object, and the object has no
>> way of knowing by what name it was referenced.
>> 
>> Because of this fallacy,
> 
> "You keep using that word. I do not think it means what you think it
> means."
> 
> *wink*
> 
>> it's generally considered bad programming
>> style to want to know "the" name of the current object from inside
>> that object.
> 
> I agree whole-heartedly with Ben's sentiments here, although I can also
> point out by example why it might be useful for a function to know it's
> own name:
> 
> def Ackermann(i, j):
> """Returns the Ackermann function of integers i and j.
> 
> The Ackermann function is an example of a function which grows at a
> much faster than exponential rate. Ackermann(i, j) for i > 2 grows
> even more quickly than 2**2**2**...**2 (where there are j exponents).
> It is an example of a recursive function which is not primitively
> recursive and was discovered by the German mathematician Wilhelm
> Ackermann in 1928.
> 
> >>> Ackermann(1, 1)
> 2
> >>> Ackermann(2, 2)
> 16
> >>> Ackermann(2, 3)
> 65536
> 
> The Ackermann function is not defined for i,j <= 0.
> 
> See http://en.wikipedia.org/wiki/Ackermann_function
> and 'Introduction to Algorithms' by Thomas H Cormen, Charles E
> Leiserson, Ronald L Rivest, pp. 451-453.
> """
> if i < 0 or j < 0:
> raise ValueError(
> "arguments to the Ackermann function must be positive")
> if i == 1:
> return 2**j
> if j == 1:
> return Ackermann(i-1, 2)
> return Ackermann(i-1, Ackermann(i, j-1))
> 
> Notice that if you change the name of the function, you have to change it
> in no less than three places in the function definition and four places
> in the __doc__ string, but a global search and replace is too greedy and
> will change too much. As a general principle, it is considered best
> practice to code in such a way that if you change something, you only need
> to change it in one place.
> 
> I guess that the Original Poster wants some magic that allows functions to
> do this:
> 
> def Ackermann(i, j):
> """Returns the Ackermann function of integers i and j.
> 
> The Ackermann function is an example of a function which grows at a
> much faster than exponential rate. %MAGIC(i, j) for i > 2 grows
> even more quickly than 2**2**2**...**2 (where there are j exponents).
> It is an example of a recursive function which is not primitively
> recursive and was discovered by the German mathematician Wilhelm
> Ackermann in 1928.
> 
> >>> %MAGIC(1, 1)
> 2
> >>> %MAGIC(2, 2)
> 16
> >>> %MAGIC(2, 3)
> 65536
> 
> The Ackermann function is not defined for i,j <= 0.
> 
> See http://en.wikipedia.org/wiki/Ackermann_function
> and 'Introduction to Algorithms' by Thomas H Cormen, Charles E
> Leiserson, Ronald L Rivest, pp. 451-453.
> """
> if i < 0 or j < 0:
> raise ValueError(
> "arguments to the Ackermann function must be positive")
> if i == 1:
> return 2**j
> if j == 1:
> return %MAGIC(i-1, 2)
> return %MAGIC(i-1, %MAGIC(i, j-1))

Another possibility would be:

def recursive_func(func):
def new_func(*args, **kw):
return func(new_func, *args, **kw)
return new_func

@recursive_func
def Ackermann(recurse, i, j):
# yadda yadda
recurse(i-1, ...), recurse(y-2, ...)

> Now he can easily rename "Ackermann" to "Ack" and need only make the
> change in one place.
> 
> I suspect that the correct solution to the O.P.'s problem is to think
> carefully about the names of your functions in advance.

By the way, the "real" problem here is referencing by name, rather than
using "true" references. Which is the result of using a textual language.
The "real" solution would be to store real-references to the function and
only present the name in a graphical interface.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing func_name from inside a function

2006-03-26 Thread Alex Martelli
James Thiele <[EMAIL PROTECTED]> wrote:

> I'd like to access the name of a function from inside the function. My
> first idea didn't work.
> 
> >>> def foo():
> ... print func_name
> ...
> >>> foo()
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 2, in foo
> NameError: global name 'func_name' is not defined

So, define it -- as a function, of course:

def func_name():
import sys
return sys._getframe(1).f_code.co_name

def foo():
print func_name()

def bar():
print func_name()

No doubt you'll object that the internals of func_name are "ugly", but
the point is that it can be hidden anywhere you like, so its internals
are as irrelevant as they would be if it was a built-in.


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


Re: "For" loop and list comprehension similarity

2006-03-26 Thread Grant Edwards
On 2006-03-26, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I apologize if this was brought up before, I couldn't find any "prior
> art" :-).
> On more than one occasion, I found myself wanting to use a "conditional
> loop" like this (with "Invalid syntax" error, of course):
>
>   for i in c if :
>   print i*2
>
> ...because it's similar to the list comprehension construct:
>
>   [i*2 for i in c if ]
> -
>
> Is this the intended difference in constructs? The available equivalent
> feels a bit awkward:
>
>   for i in c:
>   if :
>   print i*2

   for j in [i*2 for i in c if ]:
  print j

-- 
Grant Edwards   grante Yow!  .. I wonder if I
  at   ought to tell them about my
   visi.comPREVIOUS LIFE as a COMPLETE
   STRANGER?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Accessing func_name from inside a function

2006-03-26 Thread Alex Martelli
Ron Adam <[EMAIL PROTECTED]> wrote:

> A "Current" key word would fix this.  Or possibly "This" which would be
> short for "This object".

I think "This" would cause huge confusion, since in other popular
language the keyword "this" means (a pointer/reference to) "the instance
variable on which the method is being called" -- my use is instead for
"the object of the immediate lexically enclosing scope" (a module,
class, or function).  Implementation wouldn't be trivial in today's
CPython, anyway: frames have no references at all to function objects
(only to _code_ objects), and class objects don't even exist untill well
after their top-level code has long finished running; to make Current
possible, these subtle points of semantics would have to be changed in
quite a revolutionary way, especially where classes are concerned.


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


Re: maximum() efficency

2006-03-26 Thread Paul McGuire
"Steve R. Hastings" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> I was looking at a Python function to find the maximum from a list.
> The original was more complicated; I simplified it.  The built-in max()
> function can replace the simplified example, but not the original.
>
>
If you are interested in both the min and max values, here is an algorithm
that performs only 3 comparisons for every 2 list items, instead of the
brute force method's 4 comparisons.  This walks the input list in pairs,
compares the two items to each other, then compares the lesser with the
current min and the greater with the current max.

def minMax(L):
lenL = len(L)
if lenL == 0:
return None,None
if lenL == 1:
return L[0],L[0]

min_ = max_ = L[0]

if lenL % 2:
i = 1
else:
i = 0
while i < lenL:
a,b = L[i],L[i+1]
if a > b:
a,b = b,a
if a < min_: min_ = a
if b > max_: max_ = b
i += 2

return min_,max_

Of course, this much Python bytecode is not near as fast as simply calling
the builtins min() and max().  But, if you add psyco to the mix, things
aren't so cut-and-dried.  I tested this method using a list of
randomly-generated strings, and after the list length exceeds 100-500 or so,
minMax starts to outperform the compiled min() and max().  The following
table shows the timing for the brute force min() and max() calls, followed
by minMax():

List length  1: 0.229 0.612
List length  2: 0.056 0.0001081
List length 10: 0.059 0.707
List length100: 0.154 0.087
List length500: 0.589 0.534
List length   1000: 0.0001176 0.670
List length  1: 0.0011485 0.0008954
List length 10: 0.0126720 0.0077379

Using the OP's test of 1 million zeros with the first zero changed to a 1,
here is the performance of minMax vs. min() and max():

List length 100:  0.1235953 0.0126896

minMax is 10X faster!  Ironically, it's faster calling minMax() than either
min() or max().

If your list contains objects that are expensive to compare, the crossover
list length may be much shorter.

-- Paul


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


Re: image reduction script

2006-03-26 Thread Philippe Martin
Kamilche wrote:

> Be sure and use mode = P instead of RGB, like you have in your other
> code. P is for palettized images. Don't palettize if you're storing as
> JPG, only if you're storing as PNG or some other format that can handle
> 256 color images.


My problem is this:

1) If I use a save to jpg after a convert('P') I get an exception (what you
are refering to I assume)
2) If I use a save to png (I start with a jpg), then the (X,Y) size of the
output is much smaller than convert('RGB') and save to jpg - (and I want to
opposit: as small as possible in byte size and as large as possible in
(X,Y)  ):

*** SAME INPUT FILE.JPG *** 
***convert('P') save to PNG
/home/philippe/tmp/tmprpdfEO is a 65x87 Raw PPM image with 256 levels
  Default gamma for ITRUE image is  1.00
  Building XImage...done
  Have adjusted image from 1.00 to display gamma of 2.20

Versus:
***convert('RGB') save to JPG
/home/philippe/tmp/tmpYCLrQR is a 173x231 Raw PPM image with 256 levels
  Default gamma for ITRUE image is  1.00
  Building XImage...done
  Have adjusted image from 1.00 to display gamma of 2.20


Philippe



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


Re: Accessing func_name from inside a function

2006-03-26 Thread Bruno Desthuilliers
James Thiele a écrit :
> I'd like to access the name of a function from inside the function. My
> first idea didn't work.
> 
> 
def foo():
> 
> ... print func_name
> ...
> 
foo()
> 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 2, in foo
> NameError: global name 'func_name' is not defined
> 
> My second attempt works but looks ugly.
> 
> 
def foo():
> 
> ... import inspect
> ... print inspect.stack()[0][3]
> ...
> 
foo()
> 
> foo
> 
> Is there a standard way of getting the name of a function from inside
> the function?
> 

You've already got good answers. Now here's another workaround:

class _FooFunction(object):
   def __call__(self):
 print self.__class__.__name__
foo = _FooFunction()

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


Re: wired md5 hashing problem

2006-03-26 Thread Paul Rubin
Matthias Güntert <[EMAIL PROTECTED]> writes:
> i am in the process of writing a python script to backup my data. Now I
> would like to implement md5/sha1 hashes.  

Try editing as follows: change

> f = open(fname, "rb")
> while 1:
> block = f.read(1024*1024)
> if not block:
> break
> # generate the hash
> m.update(block)
> f.close()

to:

 f = open(fname, "rb")
 nbytes = 0
 while 1:
 block = f.read(1024*1024)
 nbytes += len(block)
 if not block:
 break
 # generate the hash
 m.update(block)
 f.close()
 print '%d bytes processed'

As Adam DePrince noticed, the md5 checksum you generated was that of
an empty file.  So the above should tell you whether you're actually
processing any input; if you don't get the expected number of bytes,
debug from there.
-- 
http://mail.python.org/mailman/listinfo/python-list


Python multithreading problem

2006-03-26 Thread abhinav
//A CRAWLER IMPLEMENTATION
please run this prog. on the shell and under the control of debugger
when this prog. is run normally the prog. does not terminate .It
doesn't come out of the cond. if c<5: so this prog. continues
infinitely
but if this prog is run under the control of debugger the prog
terminates when the cond. if c<5: becomes false
i think this prob. may be due to multithreading pls help.


from sgmllib import SGMLParser
import threading
import re
import urllib
import pdb
import time
class urlist(SGMLParser):
def reset(self):
SGMLParser.reset(self)
self.list=[]

def start_a(self,attr):
href=[v for k,v in attr if k=="href"]
if href:
self.list.extend(href)
mid=2
c=0
class mythread(threading.Thread):
 stdmutex=threading.Lock()
 global threads
 threads=[]
 def __init__(self,u,myid):
self.u=u
self.myid=myid
threading.Thread.__init__(self)
 def run(self):
global c
global mid
if c<5:
self.stdmutex.acquire()
self.usock=urllib.urlopen(self.u)
self.p=urlist()
self.s=self.usock.read()
self.p.feed(self.s)
self.usock.close()
self.p.close()
c=c+1
fname="/root/" + str(c) + ".txt"
self.f=open(fname,"w")
self.f.write(self.s)
self.f.close()
print c
print self.p.list
print self.u
print self.myid
for j in self.p.list:
k=re.search("^https?:",j)
if k:
   i=mythread(j,mid)
   i.start()
   threads.append(i)
   mid=mid+1
self.stdmutex.release()






if __name__=="__main__":
thread=mythread("http://www.google.co.in/",1)
thread.start()
threads.append(thread)
for thread in threads:
  thread.join()
print "main thread exits"

































































































































































































































































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


Re: Python types

2006-03-26 Thread Bruno Desthuilliers
Salvatore a écrit :
> Thank's everybody :-)
> 
> 
> Here is a type définition I've found on the net which I agree with :
> 
> Attribute of a variable which determines the set of the values this
> variabe can take and the
> operations we can apply on it.

Then - as already pointed by Alex - there is no type in Python, since 
there is no variable (even if this term is often improperly used for 
bindings) !-)

Ok, let's s/variable/object/g and define some objects and operations:

def myop(obj):
   return obj.foo * 2

class Bar(object):
   pass

b = Bar()

Can we apply the myop() operation on the object name 'b' is bound to ?

myop(b)
Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'


Well... but wait a minute:
b.foo = []
myop(b)
-> []

Err... Wait another minute:

b2 = Bar()
type(b) is type(b2)
-> True
myop(b2)
Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'

Ok, so even if Python itself declares b and b2 (read: objects that names 
b and b2 are bound to) to be of the same type,  you cannot apply the 
myop() operation on b2...

Also:

del b.foo
myop(b)
Traceback (most recent call last):
   File "", line 1, in ?
   File "", line 1, in myop
AttributeError: 'Bar' object has no attribute 'foo'


So *sometimes* you can apply myop() to b, and sometimes you can't.

Now if we come back to your original post:
"""
All objects seem to have a perfectly defined
type
"""

"Perfectly defined" ? Really ? Not for your current definition of 'type' 
at least !-)

I still mostly agree with the given definition of type. But the fact is 
that in Python, the type*s* of an object are not so perfectly defined - 
they're mostly implicits, and can vary during the object's lifetime.

Note that it does'nt make Python weakly typed - you cannot perform any 
arbitrary operation on a given object, only the operations this object 
can support at a given moment. FWIW, if you want a weakly typed 
language, take a look at C.
-- 
http://mail.python.org/mailman/listinfo/python-list


wildcard exclusion in cartesian products

2006-03-26 Thread [EMAIL PROTECTED]
The python code below is adapted from a Haskell program written by
Tomasz
Wielonka on the comp.lang.functional group. It's more verbose than his
since I wanted to make sure I got it right.

http://groups.google.com/group/comp.lang.functional/browse_frm/thread...

Does anyone know how to turn it into a module (or whatever it's called)
so that I can put it in a
loop and not have to generate the whole list? I've already tried
without success.

The program solves the following problem: generate the subset X of the
cartesian product S^n that excludes n-tuples defined by wildcards. For
example, if I want to exclude from [1,2,3]^3 the wc's [1,"*",2] and
["*",3,"*",3,"*"], where "*" stands for a sequence of zero or more
elements of [1,2,3], then I just type

for x in generateNotMatching([1,2,3,4],4,[[1,'*',2],[3,'*',4]]): print
x

and get the output

   [1, 1, 1]
   [1, 1, 3]
   [1, 2, 1]
   [1, 2, 3]
   [1, 3, 1]
   [2, 1, 1]
   [2, 1, 2]
   [2, 1, 3]
   [2, 2, 1]
   [2, 2, 2]
   [2, 2, 3]
   [2, 3, 1]
   [2, 3, 2]
   [3, 1, 1]
   [3, 1, 2]
   [3, 2, 1]
   [3, 2, 2]

This is nice! But all elements are generated before they are printed.

##
import sys, os, string

def imap(function, source):
for element in source:
yield function(element)

def any(iterable):
 '''True iff at least one element of the iterable is True'''
 for element in iterable:
if element:
return True # or element and change the definition
 return False

def all(iterable):
 '''True iff no element of the iterable is True'''
 '''SHOULD BE?: True iff all element of the iterable are True'''
 for element in iterable:
if not element:
return False
 return True

def rev(L):
rL=[]
for x in L: rL=[x]+rL
return rL

def advancePattern(x,p):
if p==[]: return []
else:
   h=p[0]
   t=p[1:]
   if h != '*':
  if h == x: return [t]
  else: return []
   else: return [p] + [t] + advancePattern(x,t)

def advancePatterns(x,P):
aP=[]
for p in P:
aP += advancePattern(x,p)
return aP

#return [advancePattern(x,p) for p in P]

def allStar(p):
return all( imap((lambda x: x=='*'),p) )

def notNullOrZero(p,n):
return p !=[] or n==0

def generateNotMatching(A,n,P):
return gen(A,n,P,[])

def gen(A,n,P,acc):
if any(imap((lambda p:  allStar(p) and notNullOrZero(p,n)), P)):
   return []
else:
   if n==0:
  return map(rev,[acc])
   else:
  aG=[]
  for a in A:
  aG += gen(A,n-1,advancePatterns(a,P),[a]+acc)
  return aG

##

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


Advice for Python and Web Server/Services?

2006-03-26 Thread Ron Davis

I have recently discovered Python and like it quite a bit. I would like to
use it on a new project I am starting. 

The project will gather data from several web services and present the
collected data to browser users through a web server.

So basically I need a full-time web server and a separate way to poll web
services for their data. There is no database involved.

The problem is that I have tried several Python web servers (CherryPy,
Karrigell, etc) and they all have problems getting out through my Comcast
cable modem. There is a 3 second pause every 10th file. Never the 9th or
11th, but always the 10th file. 

I thought maybe Comcast was limiting incomming HTTP but Apache does not do
this so I'm stumped as to why it is happening with the Python servers. All
servers work fine over the LAN.

Anyway, I wanted to get some advice on what type of setup would be best
for this using Apache. The web service polling needs to be going all the
time so a straight CGI-type thing is not an option. 

I've looked in to fastcgi and mod_python but I'm not sure either is what I
need. What I want is for my Python program to be polling the web
services 24/7 and Apache to serve static pages by itself but call
a function in my already running Python program for files with a certain
extension (.xml for example).

Have any of you done something like this before?

Ideally, I'd like to figure out why the Python servers are having
problems. This is a very low volume system so straight Python would be
great if I can get it working.

Thanks for any advice you can give.

--
Ron Davis






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


Re: image reduction script

2006-03-26 Thread Kamilche
Be sure and use mode = P instead of RGB, like you have in your other
code. P is for palettized images. Don't palettize if you're storing as
JPG, only if you're storing as PNG or some other format that can handle
256 color images.

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


Re: "For" loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
Thank you for replying, Mitja! That *is* a nice alternative.

Do you think it's a good idea to ask on comp.python.devel if they would
be interested in a PEP about this (provided there is none)?

Cheers,
Sergey.

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


[ANN] Firedrop 0.2.0 - The Python Blog Client

2006-03-26 Thread Fuzzyman
It has finally happened, the release of `Firedrop 0.2.0
`_.

The impatient can download the new release here :

`Firedrop 0.2.0 (1.3mb)
`_

.. note::

The first time you run version 0.2.0 it will convert your weblog
config file to the new format.

**Firedrop2** is the Python blog client with a host of features. These
include :

* RSS feed generation
* Categories
* Automatic archive generation
* A powerful set of plugins, including spell checker and emailer
* Entries can be made in text, HTML, ReST, textile, sextile or markdown
markup
* HTML templating system and macros for all sorts of tricks
* Built in FTP capability for uploading your blog to a server
* Because it's written in Python, it is easy to extend Firedrop or
create new plugins for it

This new release has been made possible by the hard work of `Stewart
Midwinter `_.

The changes and new features include :

* Firedrop will now start up by opening a default site.
* You can set the default site using the GUI.
* Main file name changed to ``firedrop.pyw``
* `ConfigObj `_ is
now used to edit all the config files.
* Full support for all style elements (e.g. underline, bold) in four
  major markup formats: ReST, Sextile, Textile, Markdown (plus HTML).
* New entries are created in a separate dialog that takes care of the
markup.
* Links are available to websites for the markup styles.
* You can reset the app to a null site, and/or delete all entries.
* You can force a full build of your site, or just update your site.
* You can now create sites serving Article Collections or Items Lists
(e.g. FAQs)
  in addition to Weblogs.
* Firedrop2 now runs on Mac OS X and Linux in addition to Windows.
* You can view logfile contents using the GUI.
* Documentation has been updated to reflect these changes.

There is a roadmap for future releases on the `Firedrop2 Trac Site
`_.

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


Re: New development windows, IronPython or PythonWin

2006-03-26 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Dan wrote:
> 
>> I realise its in beta. But long term, do you think that the win32com,
>>win32gui etc... will have no support because everyone jumps on the
>>Microsoft bandwagon? Aren't the windows support extensions supported
>>primarily by one guy, Mark Hammond? As a developer, this seams to leave
>>me with a vulnerability long term. Thanks for the advise.
> 
> 
> Bruno Desthuilliers wrote:
> 
>>Well, from what we've seen so far, I'd rather rely on open source
>>software than on proprietary one. An oss project lives as long as
>>someone is willing to maintain it, and anyone can pick it up. And I
>>wouldn't count on "every one jumping on MS wagon" neither.
> 
> 
> I find this comment curious, as IronPython *is* an open source
> software.

based on a proprietary runtime (yes, I know, Mono... but there again, 
there are legal issues to consider). And what will happen when MS 
discontinue dotnet ???
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MVC in Python for web app dev

2006-03-26 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> Thanks Rune. I've already checked out Django and TG and have found both
> the projects to be a little misguided. I think the one great thing they
> have over Rails is the use of SQLObject 

Then you haven't really checked Django - it doesn't use SQLObject.

> Having said that, neither TG or Django seem to have the learning
> material available on an equivilent standard to Rails.

I found Django's doc to be mostly good, even if a bit terse on some 
points (but then there's the mailing-list).

> Maybe it's just
> because they're more immature and thus Rails has got the head start
> here.

Django has been 'extracted' from existing software (3+ years of use in 
production), so I wouldn't call it 'immature'. It certainly has warts 
(the most obvious one - the ORM - will be fixed in 0.92, that is in few 
weeks), but I found it mostly usable, and (this ORM issue apart, but 
transition should not be a big issue) stable enough to start using it on 
real-life projects.

> I guess more than pointing out a few URLs I was looking for some
> peoples honest opinion on why they would chose one over the other
> (besides the basis of language alone).

Well, the 'language' criteria is already enough for me. Ruby is fine 
too, but I've already been programming in Python for 5+ years - talking 
about 'head start' !-)

> I'm just trying to source the
> most viable option at the moment, trying to find something to offer
> quickly without resorting to *shudders* Spring or the like.
> 

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


Re: Accessing func_name from inside a function

2006-03-26 Thread Ron Adam
Alex Martelli wrote:

> Personally, I'd rather have a 3.0 keyword referring to "the current
> object" (module for module toplevel code, class for classbody toplevel
> code, function for code within a function) -- say for the sake of
> argument the keyword is 'current'; this would allow current.__name__ to
> have the obvious meaning, and would also allow a few more neat things
> (such as natural access to current.__doc__).

That was my thought too, that what is really desired is a *obvious* way 
to get a dependable reference to the current function as you describe here.

A quick experiment...  with an obvious result:

 def foo(): print foo.__name__
> ...
 foo()
> foo
 boo = foo
 boo()
> foo
 boo.__name__
> 'foo'
 foo = None
 boo()
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "", line 1, in foo
> AttributeError: 'NoneType' object has no attribute '__name__'

A "Current" key word would fix this.  Or possibly "This" which would be 
short for "This object".

This may also relate to suggestions to reduce the need for having self 
in the argument list of methods.  So if a keyword "This" could mean this 
method or function, then "Self" could mean this class.  Hmmm, methods 
that use "Self" in this way might run into problems, but I havn't had 
enough coffee to think it though. ;-)

Cheers,
Ron

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


Re: String To Dict Problem

2006-03-26 Thread Kamilche
Ah, finally, that's exactly what I need! Thanks bunches. I was
attempting to modify your first code to fit my needs, but mine was much
longer, and not yet working, a sure clue that yours is a better
solution. :-D

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


Re: object references

2006-03-26 Thread Bruno Desthuilliers
DrConti a écrit :
> Dear Python developer community,
> I'm quite new to Python, so perhaps my question is well known and the
> answer too.
> 
> I need a variable alias ( what in other languages you would call  "a
> pointer" (c) or "a reference" (perl))

Well, that's the only kind of "variable"[1] in Python.

[1] the correct name in Python is 'binding', since it's about 'binding' 
a reference to a name, not labelling an in-memory address and storing 
data there.

> I read some older mail articles and I found that the offcial position
> about that was that variable referencing wasn't implemented because
> it's considered bad style.
> There was also a suggestion to write a real problem where referencing
> is really needed.
> I have one...:

You *think* you have one.

> I'm trying to  generate dynamically class methods which works on
> predefined sets of object attributes.
> one of these is the set of attributes identfying uniquely the object
> (primary key).
> A naïve attempt to do the job:
> 
> class ObjectClass:
>   """ Test primary Key assignment """
> 
> if __name__ == "__main__":
> 
>   ObjectClassInstantiated=ObjectClass()
>   ObjectClassInstantiated.AnAttribute='First PK Elem'
>   ObjectClassInstantiated.AnotherOne='Second PK Elem'
>   ObjectClassInstantiated.Identifier=[]
>   
> ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
>   
> ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnotherOne)
>   print ObjectClassInstantiated.Identifier
>   ObjectClassInstantiated.AnAttribute='First PK Elem Changed'
>   print ObjectClassInstantiated.Identifier
> 
> leads a wrong result
> 
>>./test.py
> 
> ['First PK Elem', 'Second PK Elem']
> ['First PK Elem', 'Second PK Elem']
> --> wrong! It should write  ['First PK Elem Changed', 'Second PK Elem']

Nope, it's exactly what you asked for !-)

> 
> i.e. the assgnment
> 
> ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
> 
> assigns only the attribute value, not the reference.

1/ it's not an assignement
2/ it does not store the attribute "value", it stores the reference to 
the object the attribute is bound to. When you later rebind the 
attribute, it only impact this binding - there's no reason it should 
impact other bindings.


> so my question is:
> is it still true that there is no possibilty to get directly object
> references?

But object references *are* what you have.

> Is there a solution for the problem above ?

Yes : keep a reference to the attribute name, not to the value bound to 
that name. There are many ways to do it, here's one:

ObjectClass.Identifier = property(
   fget=lambda self: [self.AnAttribute, self.AnotherOne]
   )

and here's another one:

ObjectClassInstantiated._identifier_parts = []
# note the use of strings, not symbols
ObjectClassInstantiated._identifier_parts.append("AnAttribute")
ObjectClassInstantiated._identifier_parts.append("AnotherOne")

ObjectClass.Identifier = property(
   fget=lambda self: [getattr(self, name) \
for name in self._identifier_parts]
   )


> Thank you for any feedback 

May I add some ? Your naming conventions are highly unpythonic. We 
usually use CamelCase for classes names, and (in order of preference) 
all_lower_with_underscores or mixedCaps for 
variables/attributes/functions etc.

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


Re: SSH, remote login, and command output

2006-03-26 Thread Tim Parkin
Tim Parkin wrote:
> Spire 01 wrote:
> 
>>Greetings!
>>
...
>>Thanks a million!
>>Spire
> 
> 
> 
> I wrote a small tool to implement cron like functionality over ssh using
>  twisted (with public/private keys). This was written to scratch a small
> itch but also to learn how twisted works with conch, it's ssh module.
> 
> http://crontorted-project.pollenation.net/cgi-bin/trac.cgi
> 
> Feel free to use, I haven't put a license on it but it would be MIT/BSD
> .. contact me if you want an explicit confirmation.
Actually, unless you are happy to implement a BSD/MIT (or your own)
license crontab parser (crontorted/crontab.py) the whole will have to be
GPL? The current crontab.py is from Bothan (Thomas Herve ) if you're interested, I'll write my own
crontab parser and release it.

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


Re: Cookbook for beginners?

2006-03-26 Thread Rune Strand

Aahz wrote:
> If you were going to name three or five essential recipes from the
> Python Cookbook suitable for beginners, what would you pick?
>
> Yes, this is for _Python for Dummies_, so idioms that aren't in the
> Cookbook are also fine.

If it's for _beginners_ / _dummies_, I would expect things like

1.6
names = ['George', 'Saddam', 'Osama']
name_string = ', '.join(names)

4.10
dict.setdefault(k, v)

?.?
dict = dict(zip(list_a, list_b))

- listcomps

2.1 / 2.2
reading/writing from/to files

?.?
string-methods like .split(), .upper(), endswith(), startswith(),
isalpha() ...

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


Re: object references

2006-03-26 Thread Mitja Trampus
DrConti wrote:
> class ObjectClass:
>   """ Test primary Key assignment """
> 
> if __name__ == "__main__":
>   ObjectClassInstantiated=ObjectClass()
>   ObjectClassInstantiated.AnAttribute='First PK Elem'
>   ObjectClassInstantiated.AnotherOne='Second PK Elem'
>   ObjectClassInstantiated.Identifier=[]
>   
> ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
>   
> ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnotherOne)
>   print ObjectClassInstantiated.Identifier
>   ObjectClassInstantiated.AnAttribute='First PK Elem Changed'
>   print ObjectClassInstantiated.Identifier
> 
> leads a wrong result
>> ./test.py
> ['First PK Elem', 'Second PK Elem']
> ['First PK Elem', 'Second PK Elem']
> --> wrong! It should write  ['First PK Elem Changed', 'Second PK Elem']
> 
> i.e. the assgnment
> ObjectClassInstantiated.Identifier.append(ObjectClassInstantiated.AnAttribute)
> assigns only the attribute value, not the reference.

Nono, it assigns the reference alright. In python, EVERYTHING gets assigned 
only a 
reference, .AnAttribute as well. So when you do .AnAttribute = 'Changed', you 
make it a 
reference to a NEW string 'Changed', while .Identifier[0] keeps referencing the 
'First PK' 
string object.
Strings are an unfortunate example, since they're immutable - once you create a 
string 
object, you cant't modify it any more. But if you had a more complex object, 
you could do 
.AnAttribute.changeYourself(), and .Identifier[0] would change accordingly as 
well, 
because .AnAttribute would keep pointing to the same object (albeit changed).

In your case, try .AnAttribute = ['First']; .Identifier[0] = .AnAttribute; 
.AnAttribute[0] 
= 'First changed'; - this will work the way you want it to, because 
.AnAttribute doesn't 
get rebound (only the content of the object (list) it's pointing to change, but 
it's still 
the same object).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String To Dict Problem

2006-03-26 Thread Michael Spencer
Kamilche wrote:
> Thanks! It's interesting, and nearly what I want, but not quite there.
> 
> When I run my sample code through it, I get a syntax error because it's
> not a valid expression. If I were to put a 'dict(' in front and a ')'
> at the end, THEN it nearly works - but it gives me an
> 'Unsafe_Source_Error: Line 1.  Unsupported source construct:
> compiler.ast.CallFunc' error.
> 
> How do I let one measly function in (dict), without letting them all in?
> 
You could add a Keyword node, and use it something like this:

import compiler

class SafeEval(object):

 def visit(self, node,**kw):
 cls = node.__class__
 meth = getattr(self,'visit'+cls.__name__,self.default)
 return meth(node, **kw)

 def default(self, node, **kw):
 for child in node.getChildNodes():
 return self.visit(child, **kw)

 visitExpression = default

 def visitConst(self, node, **kw):
 return node.value

 def visitDict(self,node,**kw):
 return dict([(self.visit(k),self.visit(v)) for k,v in node.items])

 def visitTuple(self,node, **kw):
 return tuple(self.visit(i) for i in node.nodes)

 def visitList(self,node, **kw):
 return [self.visit(i) for i in node.nodes]

 def visitKeyword(self,node,**kw):
 return node.name, self.visit(node.expr)

def safe_dict(source):
 source = "dict(%s)" % source # funcname is actually ignored
 walker = SafeEval()

 ast = compiler.parse(source,"eval")

 kwargs = {}
 args = ast.node.args
 for arg in args:
 if isinstance(arg, compiler.ast.Keyword):
 keyword, value = walker.visit(arg)
 kwargs[keyword] = value
 else:
 raise Exception, "only keywords"
 return dict(**kwargs)

 >>> source=  """gid = 'FPS', type = 'Label', pos = [0, 20], text = 'FPS', 
 >>> text2 
= 'more text without quotes', fmtline = "@VALUE @SIGNAL", signals = 
[('FPS',None), ('FPS2', 'something')]"""
 >>> safe_dict(source)
{'signals': [('FPS', None), ('FPS2', 'something')], 'text2': 'more text without 
quotes', 'gid': 'FPS', 'fmtline': '@VALUE @SIGNAL', 'text': 'FPS', 'type': 
'Label', 'pos': [0, 20]}
 >>>

Michael

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


Re: "For" loop and list comprehension similarity

2006-03-26 Thread Mitja Trampus
[EMAIL PROTECTED] wrote:

> On more than one occasion, I found myself wanting to use a "conditional
> loop" like this (with "Invalid syntax" error, of course):
> 
>   for i in c if :
>   print i*2

Maybe there's been a PEP, don't really know...
Currently, the only sensible alternative is what you've written below:

> The available equivalent
> feels a bit awkward:
> 
>   for i in c:
>   if :
>   print i*2


This indeed doesn't look nice, especially if you've got lots of code instead of 
just 
print. An alternative which avoids double indentation is

for i in c:
if not : continue
print i*2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Module documentation

2006-03-26 Thread Bruno Desthuilliers
Tony Burrows a écrit :
> Just getting to grips with Python, a great language BUT
> With something like Java I can find the syntax of a method call with no
> problems, how do I do the same with Python?
> 
> For example, using MySQLdb or SGMLParser I can see what the available
> methods are with dir, but how do I find out what parameters are needed and
> what they represent?

In the python shell, typing 'help()' should get you started most 
of the time.

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


Re: maximum() efficency

2006-03-26 Thread Mitja Trampus
Steve R. Hastings wrote:
> I was looking at a Python function to find the maximum from a list. 
> The original was more complicated; I simplified it.  The built-in max()
> function can replace the simplified example, but not the original.

But you forgot to shuw us the original...

[snip several implementations]

> Of course, it's a little ugly to use a[0] instead of "maxval".  And I'm
> trying not to index a list, and here I am indexing another list.  So:
> 
> def maximum(lst):
>   for v in lst:
> try:
>   if maxval > v:
> maxval = v
> except NameError:
>   maxval = v
>   return maxval
> 
> In my testing on my computer, the above function works perfectly.  Even
> if you do this:
> 
 maxval = 100
 print maximum(cmp, [2, 0, 3, 1])
> 3
> 
> In other words, you get a NameError in the function even if there is a
> global variable with that name.  That's with Python 2.4, however... is
> this function guaranteed to work in all Python versions?  

Not 100% sure, but I think yes. People with longer experience in python can 
answer 
definitely. Or you can try it out yourself.
The reason it works is that this:
def f():
print a
a=7; f()
works and prints 7 (global a is used), while this
def f():
print a
a = 12
a=7; f()
does NOT work. Python notices that a is going to get assigned to inside f and 
treats it as 
a local variable. This is also the case with your code. Try out the above 
examples without 
a=7 and notice the different error messages...

> The clear winner was the iterator version. It was much faster than the
> others, and in my opinion it is simpler and easier to understand than any
> of the others.

I would have done it in the same way, but probably without the iterators. I.e., 
like this:

def maximum(lst):
try: m = lst[0]
except (TypeError, IndexError): raise Exception "Non-sequence or empty 
sequence given to 
maximum")

# (you forgot the above sanity checks in your code.
# not strictly necessary, but nice to have.)

for x in lst:
if x>m: m=x
return m
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookbook for beginners?

2006-03-26 Thread Bruno Desthuilliers
Aahz a écrit :
> If you were going to name three or five essential recipes from the
> Python Cookbook suitable for beginners, what would you pick?
> 
> Yes, this is for _Python for Dummies_, so idioms that aren't in the
> Cookbook are also fine.


1/ tuple- and dict-based dispatch, ie:
x = (result_if_false, result_if_true)[boolexpr]
y = {key1: result1, key2:result2, ...}[keyexpr]

2/ functions (and methods etc) as first-class objects (two main obvious 
uses : callbacks and decorators)

+ (bonus) the combination of 1/ and 2/ !-)

3/ name-based lookups and affectations (getattr() / setattr()) and their 
implementation ( __getattr__ / __setattr__)



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


Re: String To Dict Problem

2006-03-26 Thread Kamilche
Thanks! It's interesting, and nearly what I want, but not quite there.

When I run my sample code through it, I get a syntax error because it's
not a valid expression. If I were to put a 'dict(' in front and a ')'
at the end, THEN it nearly works - but it gives me an
'Unsafe_Source_Error: Line 1.  Unsupported source construct:
compiler.ast.CallFunc' error.

How do I let one measly function in (dict), without letting them all in?

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


Re: SSH, remote login, and command output

2006-03-26 Thread Tim Parkin
Spire 01 wrote:
> Greetings!
> 
> I'm working on a Python program for a small LAN of Linux systems running
> Gentoo, and I need a little help figuring out what I need to do it.  So
> what I'd like to do is, from any given computer, log on to every other
> computer, run a certain command (which normally outputs text to the
> terminal), and store the output so I can use the aggregate statistics
> later in the program.  I would normally something along the lines of SSH
> to do it, but I don't know what I would need to pull that off in
> Python.  There's also one complication: the systems could be Gentoo
> systems, or they could be logged into Windows since they're dual
> booted.  Considering all of this, can anyone give me some recommendation
> as to what library I should learn how to use to pull this off? I admit,
> I haven't done too much in the way of networks, but if someone can tell
> me what I need to do remote logins in this way, I'll do what I can to
> make it work.
> 
> Thanks a million!
> Spire


I wrote a small tool to implement cron like functionality over ssh using
 twisted (with public/private keys). This was written to scratch a small
itch but also to learn how twisted works with conch, it's ssh module.

http://crontorted-project.pollenation.net/cgi-bin/trac.cgi

Feel free to use, I haven't put a license on it but it would be MIT/BSD
.. contact me if you want an explicit confirmation.

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


"For" loop and list comprehension similarity

2006-03-26 Thread s . lipnevich
Hi All,

I apologize if this was brought up before, I couldn't find any "prior
art" :-).
On more than one occasion, I found myself wanting to use a "conditional
loop" like this (with "Invalid syntax" error, of course):

for i in c if :
print i*2

...because it's similar to the list comprehension construct:

[i*2 for i in c if ]
-

Is this the intended difference in constructs? The available equivalent
feels a bit awkward:

for i in c:
if :
print i*2

Just curious. Thanks!

Sergey.

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


PIL & image size reduction script

2006-03-26 Thread Philippe Martin
Hi,

Thanks to the NG, I got the script hereunder working.

1) I am not certain that the call to convert does much (checking the doc)
2) Can this be improved as far as the final image size in (X,Y) ?


For instance, passing a large .jpg with a target byte size of 7000, I get
final (X,Y) results around (213, 174) ... but might want to strech it a bit
while keeping the byte size.

Thanks,

Philippe




 
#***
  def Image_Reduce(self, p_filename, p_size):
BASE_SIZE = 400.0
l_im = Image.open(p_filename)

l_size = l_im.size

if l_size[0] > l_size[1]:
  l_ratio = BASE_SIZE / l_size[0] 
  l_x_size = l_ratio * l_size[0]
  l_y_size = l_ratio * l_size[1]
else:
  l_ratio = BASE_SIZE / l_size[1] 
  l_x_size = l_ratio * l_size[0]
  l_y_size = l_ratio * l_size[1]
  

#l_im.show()
l_image = l_im.resize( (l_x_size, l_y_size))
l_image = l_image.convert(mode="RGB", palette=Image.ADAPTIVE)

l_done = False

l_tmp_file_name = 'sc_tmp_file.jpg'

while False == l_done:
  l_image.save(l_tmp_file_name)
  l_st = os.stat(l_tmp_file_name)
  print 'HERE ', l_st
  if p_size < l_st[6]:

l_ratio -= 0.005
print 'NEW RATIO = ', l_ratio
l_x_size = l_ratio * l_size[0]
l_y_size = l_ratio * l_size[1]
l_image = l_im.resize( (l_x_size, l_y_size))



  else:
l_done = True


l_image.show()
print l_image.size


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


Re: image reduction script

2006-03-26 Thread Philippe Martin
Kamilche,

I am posting the code in another thread but am not certain that convert does
anything to the picture color depth ... still searching in the doc.

Philippe




Kamilche wrote:

> 
> To reduce the color depth of an image in PIL:
> im = im.convert(mode="P", palette=Image.ADAPTIVE)

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


Re: String To Dict Problem

2006-03-26 Thread Michael Spencer
Kamilche wrote:
> Hi everyone. I'm trying to convert a string that looks like this:
> 
> gid = 'FPS', type = 'Label', pos = [0, 20], text = 'FPS', text2 = 'more
> text without quotes', fmtline = "@VALUE @SIGNAL", signals = [('FPS',
> None), ('FPS2', 'something')]
> 
> to a dict that looks like this:
> 
> {'signals': [('FPS', None), ('FPS2', 'something')], 'text': 'FPS',
> 'pos': [0, 20], 'text2': 'more text without quotes', 'gid': 'FPS',
> 'type': 'Label', 'fmtline': '@VALUE @SIGNAL'}
> 
> I've got a home-rolled routine that was 'good enough', until I added
> the list of tuples in there. Now it's failing. I have a hack to
> 'special case' it, but you know that will come up to bite me in the
> future.
> 
> Does anyone have a thought on how I can turn what are basically
> function keyword arguments in string form, to a dict, without using
> exec or eval?
> 
> --Kamilche
> 

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

HTH

Michael

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


Re: is mysqlsb compatible with MySQL 5.0?

2006-03-26 Thread John Salerno
Dennis Lee Bieber wrote:

>   Check the Windows services control for MySQL and try from it...

How do I do that?

> 
>   You might (since it sounds like this is a first attempt) need to
> uninstall everything -- and make sure you delete the mysql database (in
> case you have a garbaged root login)

Ugh, if this is the case, is there more to uninstall than just using the 
Add/Remove programs? Where do I delete the database?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Cookbook for beginners?

2006-03-26 Thread Rene Pijlman
Aahz:
>If you were going to name three or five essential recipes from the
>Python Cookbook suitable for beginners, what would you pick?
>Yes, this is for _Python for Dummies_, so idioms that aren't in the
>Cookbook are also fine.

Constants

Static methods / Class methods

Bunch

TaskQueue (Queue for easy and safe multithreading)

A decorator for type checking of function arguments, and/or for
require/ensure, and/or for similar features of other languages that people
find missing in Python.

Properties and in particular lazy properties. Why and how to avoid
getters/setters.

Dynamically import a module (name known at runtime, may or may not be
present).

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


Re: maximum() efficency

2006-03-26 Thread Steven Bethard
Steve R. Hastings wrote:
> I was looking at a Python function to find the maximum from a list. 
> The original was more complicated; I simplified it.  The built-in max()
> function can replace the simplified example, but not the original.

What's the original?  Are you sure max can't solve it with an 
appropriate decorate-sort-undecorate (DSU) or the key= argument coming 
in Python 2.5?

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


Re: wired md5 hashing problem

2006-03-26 Thread Matthias Güntert
On Sun, 2006-03-26 at 11:48 -0500, Adam DePrince wrote:
> 
> What do you get when you type 
> 
> md5sum backup.tar.bz2?  

it is working. Don't know what went wrong. But now I have another
question: How am I able to execute an external program, like mysqldump?
I had a look into the mysql module it didn't fit my needs. 

-- 
Mit freundlichen Grüßen

Matthias Güntert

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


Re: pondering about the essence of types in python

2006-03-26 Thread Steven Bethard
gangesmaster wrote:
> i dont think it's possible, to create proxy classes, but even if i did,
> calling remote methods with a `self` that is not an instance of the
> remote class would blow up.

I don't understand you here.  Why can't you just do something like:

 >>> class RemoteClass(object):
... def __init__(self, name):
... self.name = name
... def __repr__(self):
... return '%s(name=%s)' % (type(self).__name__, self.name)
...
 >>> rc = RemoteClass('foo')
 >>> rc
RemoteClass(name=foo)
 >>> class ProxyClass(object):
... def __init__(self, name):
... self.remote = RemoteClass(name)
... def __repr__(self):
... return repr(self.remote)
...
 >>> pc = ProxyClass('foo')
 >>> pc
RemoteClass(name=foo)

Note that when I call methods on the remote class, I don't pass them an 
instance of the proxy class -- I pass them an instance of the 
appropriate, RemoteClass type.  Of course my code is simplified because 
I'm not actually doing something remote, but assuming things get, say, 
pickled and unpickled appropriately, I'm not sure I understand why the 
above won't work.

Could you give some more details?

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


String To Dict Problem

2006-03-26 Thread Kamilche
Hi everyone. I'm trying to convert a string that looks like this:

gid = 'FPS', type = 'Label', pos = [0, 20], text = 'FPS', text2 = 'more
text without quotes', fmtline = "@VALUE @SIGNAL", signals = [('FPS',
None), ('FPS2', 'something')]

to a dict that looks like this:

{'signals': [('FPS', None), ('FPS2', 'something')], 'text': 'FPS',
'pos': [0, 20], 'text2': 'more text without quotes', 'gid': 'FPS',
'type': 'Label', 'fmtline': '@VALUE @SIGNAL'}

I've got a home-rolled routine that was 'good enough', until I added
the list of tuples in there. Now it's failing. I have a hack to
'special case' it, but you know that will come up to bite me in the
future.

Does anyone have a thought on how I can turn what are basically
function keyword arguments in string form, to a dict, without using
exec or eval?

--Kamilche

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


maximum() efficency

2006-03-26 Thread Steve R. Hastings
I was looking at a Python function to find the maximum from a list. 
The original was more complicated; I simplified it.  The built-in max()
function can replace the simplified example, but not the original.


def maximum(lst):
  maxval = lst[0]

  for i in xrange(1, len(lst)):
v = lst[i]
if maxval > v:
  maxval = v

  return maxval



Immediately I started thinking about ways to make this more efficient.  My
first thought was to use iterators:


def maximum(lst):
  itr = iter(lst)
  maxval = itr.next()

  for v in itr:
if maxval > v:
  maxval = v

  return maxval



Then I thought, I wonder if there is a faster solution that *doesn't* use
iterators, for use with older versions of Python.  I came up with:


def maximum(lst):
  a = []
  for v in lst:
try:
  if a[0] > v:
a[0] = v
except IndexError:
  a.append(v)
  return a[0]



Of course, it's a little ugly to use a[0] instead of "maxval".  And I'm
trying not to index a list, and here I am indexing another list.  So:


def maximum(lst):
  for v in lst:
try:
  if maxval > v:
maxval = v
except NameError:
  maxval = v
  return maxval



And we come at last to my actual question:  Is this guaranteed to work on
all versions of Python?

In my testing on my computer, the above function works perfectly.  Even
if you do this:

>>> maxval = 100
>>> print maximum(cmp, [2, 0, 3, 1])
3

In other words, you get a NameError in the function even if there is a
global variable with that name.  That's with Python 2.4, however... is
this function guaranteed to work in all Python versions?  I am very
comfortable with the a[0] version, since I explicitly set a to an empty
list, I know a[0] will always raise that IndexError.


P.S. I went ahead and benchmarked the above functions, plus one more
that is similar to the a[0] solution but used an empty dictionary instead
of a zero-length list.  I created a list of a million zeroes, and then
stored a 1 at the beginning of the list.  Thus the maximum functions would
spend all their time iterating through values and comparing them, and very
little time updating maxval or its equivalent.  Times to run each function
100 times on the large list:

36.8 seconds  xrange
22.3 seconds  iterator
39.2 seconds  IndexError on a[0]
31.5 seconds  NameError with maxval
43.4 seconds  KeyError on empty dictionary


The conclusions I draw from these numbers:

The sneaky tricks with exceptions don't bring enough speed to be worth
using; two of them were actually slower than the xrange solution.  Even
the NameError one was only a little bit faster, and simple is better than
complex, so I don't think I'd ever actually use it.

The clear winner was the iterator version. It was much faster than the
others, and in my opinion it is simpler and easier to understand than any
of the others.
-- 
Steve R. Hastings"Vita est"
[EMAIL PROTECTED]http://www.blarg.net/~steveha

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


Re: wired md5 hashing problem

2006-03-26 Thread Adam DePrince
On Sun, 2006-03-26 at 16:56 +0200, Matthias Güntert wrote:
> Hello list-members
> 
> i am in the process of writing a python script to backup my data. Now I
> would like to implement md5/sha1 hashes.  
> 
> # do md5 fingerprinting 
> if config.get("global", "crc") == "md5":
> m = md5.new()
> # open the file 
> f = open(fname, "rb")
> while 1:
> block = f.read(1024*1024)
> if not block:
> break
> # generate the hash
> m.update(block)
> f.close()
>   
> # write the results properly formated to a file
> fd = file(fname + ".md5", "w")
> fd.write(m.hexdigest())
> fd.write("  " + fname + "\n")
> fd.close()
> 
> 
> [EMAIL PROTECTED] > md5sum -c backup.tar.bz2.md5   
> /fileservice/temp/backup.tar.bz2: FAILED
> md5sum: WARNING: 1 of 1 computed checksum did NOT match
> 
> [EMAIL PROTECTED] > cat backup.tar.bz2.md5 
> d41d8cd98f00b204e9800998ecf8427e  /fileservice/temp/backup.tar.bz2


Hey, I found an md5 collision for your file! 

>>> import md5
>>> md5.new().hexdigest()
'd41d8cd98f00b204e9800998ecf8427e'
>>>
[EMAIL PROTECTED] Include]$ md5sum # hit ^d at start
d41d8cd98f00b204e9800998ecf8427e  -

Your file was empty when scanned. 

Without more information, I'd say that your file was empty when you ran
your python code.

But your code does work ... 

import md5
m = md5.new()
# open the file
fname="Python-2.4.2.tar.bz2"
f = open(fname, "rb" )
while 1:
block = f.read(1024*1024)
if not block:
break
# generate the hash
m.update(block)
f.close()
fd = file(fname + ".md5", "w")
fd.write(m.hexdigest())
fd.write("  " + fname + "\n")
fd.close()

[EMAIL PROTECTED] ~]$ python test2.py
[EMAIL PROTECTED] ~]$ md5sum -c Python-2.4.2.tar.bz2.md5
Python-2.4.2.tar.bz2: OK

- Adam

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

Re: wired md5 hashing problem

2006-03-26 Thread Adam DePrince
What do you get when you type 

md5sum backup.tar.bz2? 

- Adam

On Sun, 2006-03-26 at 16:56 +0200, Matthias Güntert wrote:
> Hello list-members
> 
> i am in the process of writing a python script to backup my data. Now I
> would like to implement md5/sha1 hashes.  
> 
> # do md5 fingerprinting 
> if config.get("global", "crc") == "md5":
> m = md5.new()
> # open the file 
> f = open(fname, "rb")
> while 1:
> block = f.read(1024*1024)
> if not block:
> break
> # generate the hash
> m.update(block)
> f.close()
>   
> # write the results properly formated to a file
> fd = file(fname + ".md5", "w")
> fd.write(m.hexdigest())
> fd.write("  " + fname + "\n")
> fd.close()
> 
> 
> [EMAIL PROTECTED] > md5sum -c backup.tar.bz2.md5   
> /fileservice/temp/backup.tar.bz2: FAILED
> md5sum: WARNING: 1 of 1 computed checksum did NOT match
> 
> [EMAIL PROTECTED] > cat backup.tar.bz2.md5 
> d41d8cd98f00b204e9800998ecf8427e  /fileservice/temp/backup.tar.bz2
> 
> so the format should be okay, but whats wrong with my piece of code?!
> 
> Greetings
> 
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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

  1   2   >