Re: how can I open an excel sheet with specified name

2008-12-02 Thread Gabriel Genellina
En Fri, 28 Nov 2008 23:12:50 -0200, Zuo, Changchun  
<[EMAIL PROTECTED]> escribió:



Could you please send me an example script example of

*   Opening an excel workbook with specified name
*   Read or write number in a specified spreadsheet


There is a specific group for those topics: python-excel [1]
I'd suggest using the excelent xlrd [2] and xlwt [3] packages.

[1] http://groups.google.com/group/python-excel/
[2] http://pypi.python.org/pypi/xlrd
[3] http://pypi.python.org/pypi/xlwt

--
Gabriel Genellina

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


Posting File as a parameter to PHP/HTML using HTTP POST

2008-12-02 Thread S.Selvam Siva
I am trying to post file from python to php using HTTP POST method. I tried
mechanize but not able to pass the file object.

from mechanize import Browser
br=Browser()
response=br.open("http://localhost/test.php";)
br.select_form('form1')
br['uploadedfile']=open("C:/Documents and
Settings/user/Desktop/Today/newurl-ideas.txt")
response=br.submit()
print response.read()

But, i get the error:
br['uploadedfile']=open("C:/Documents and
Settings/user/Desktop/Today/newurl
-ideas.txt")
  File
"C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg\ClientForm.py",
 line 2880, in __setitem__
ValueError: value attribute is readonly

But,
When uploading is done using browser, it works.
-- 
Yours,
S.Selvam
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple Versions of Python on Windows XP

2008-12-02 Thread Glenn Linderman
On approximately 12/1/2008 11:29 PM, came the following characters from 
the keyboard of Martin v. Löwis:

It would be nice if the ftypes were version specific as created by the
installer; IIRC, I created the above three from the ftype Python.File as
I installed each version.



That's a good idea; please submit a wish list item to bugs.python.org.
There may be issues (such as people relying on this being Python.File),
but I can't see any problems off-hand.

Regards,
Martin
  


OK, Issue 4485 created.  My first one, so let me know if I goofed.  I 
elaborated a bit from the original email, upon reflection.  Seemed 
useful, but also seemed complex by the time I got done.


I don't really have a clue what the uninstaller should do with these; 
nor have I fiddled to know if it presently removes Python.File.  I 
suppose it should delete them, if and only if the ftype and assoc have 
the same content as was created by the corresponding version installation.


--
Glenn -- http://nevcal.com/
===
A protocol is complete when there is nothing left to remove.
-- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking

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


Re: How to instantiate in a lazy way?

2008-12-02 Thread Slaunger
On 2 Dec., 11:30, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:

>
> For 4 attributes I'd probably go with the __getattr__.
>
OK, I'll do that!

> Or you could easily write your own decorator to cache the result...
>
> Eghttp://code.activestate.com/recipes/363602/

Cool. I never realized I could write my own decorators!
I've so far only used them for
@classmethod, @staticmethod and stuff like that.
User defined decorators are nice and fun to do as well.
I just hope it will be understandable
in four years also...

>
> >  With the property methology you do the value check on each get, which
> >  does not look as "clean". The property methology is also a little less
> >  arcane I guess for less experienced Python programmers to understand
> >  when re-reading the code.
>
> Less magic is how I would put it.  Magic is fun to write, but a pain
> to come back to.  Over the years I find I try to avoid magic more and
> more in python.
>
Ah, I see. I hope you do not consider user defined decorators
"magic" then? ;-)

> >  What kind of trouble are you referring to in __getattr__? Is it
> >  recursive calls to the method on accessing object attributes in that
> >  method itself or other complications?
>
> Every time I write a __getattr__ I get tripped up by infinite
> recursion!  It is probably just me ;-)
>
And I will probably end up having the same initial problems, but I
found an example
here, which I may try to be inspired from.

http://western-skies.blogspot.com/2008/02/complete-example-of-getattr-in-python.html

> >  On a related issue, thank you for showing me how to use @property as a
> >  decorator - I was not aware of that possibility, just gotta understand
> >  how to decorate a setter and delete method as well, but I should be
> >  able to look that up by myself...
>
> I'm sure you will!
>
> http://www.python.org/doc/2.5.2/lib/built-in-funcs.html
>
Yeah, I just visited that page yesterday!

Again, thank you for your assistance, Nick!

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


Re: optimization

2008-12-02 Thread Steven D'Aprano
On Mon, 01 Dec 2008 19:06:24 -0600, Robert Kern wrote:
 
> As Neal has observed, there is a performance hit for creating functions
> inside of another function. 

True, but it's not a big hit, and I believe it is constant time 
regardless of the size of the function. The inner function has been 
(mostly) pre-compiled into bits, and assembling the bits is quite fast.

On my desktop, I measure the cost of assembling the inner function to be 
around the same as two function lookups and calls. 

>>> def outer():
... def inner():
... return None
... return inner()
...
>>> def ginner():
... return None
...
>>> def gouter():
... return ginner()
...
>>> from timeit import Timer
>>> t1 = Timer('outer()', 'from __main__ import outer')
>>> t2 = Timer('gouter()', 'from __main__ import gouter, ginner')
>>> t1.repeat()
[1.782930850982666, 0.96469783782958984, 0.96496009826660156]
>>> t2.repeat()
[1.362678050994873, 0.77759003639221191, 0.58583498001098633]


Not very expensive.



> Every time you go through the outer
> function, you are creating new function objects for all of the inner
> functions. That's how you can get lexical scoping. It is not equivalent
> to defining the functions all at the top-level, where all of the
> function objects are created at once. The compiler can't optimize that
> overhead away because the overhead arises from implementing a real
> feature.

But the time it takes to parse the function and compile it to code is 
optimized away.

>>> outer.func_code.co_consts
(None, ", line 2>)

Which makes me wonder, is there anything we can do with that code object 
from Python code? I can disassemble it:

>>> import dis
>>> dis.dis(outer.func_code.co_consts[1])
  3   0 LOAD_CONST   0 (None)
  3 RETURN_VALUE

Anything else?



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


Re: Do more imported objects affect performance

2008-12-02 Thread Nick Craig-Wood
On Tue, Dec 02, 2008 at 11:24:29AM +0600, Taskinoor Hasan wrote:
> On Mon, Dec 1, 2008 at 8:21 PM, Filip Gruszczy?ski <[EMAIL PROTECTED]>wrote:
> 
> > I see. Thanks for a really good explanation, I like to know, how to do
> > things in the proper way :)
> 
> I always prefer to use import module and then use module.function. The
> reason is simple. It makes the code more readable and maintainable.

I prefer the "from module import function".  That means that if
"module" doesn't supply "function" it raises an exception at compile
time, not run time when you try to run "module.function".  It then
becomes very easy to see which functions you use from any given module
too.  It is also very slightly faster but that isn't a major
consideration.

PEP 8 endorses this style somewhat

http://www.python.org/dev/peps/pep-0008/ - see the Imports section.

[...]

  it's okay to say this though:

from subprocess import Popen, PIPE

[...]

  When importing a class from a class-containing module, it's usually
  okay to spell this

from myclass import MyClass
from foo.bar.yourclass import YourClass

  If this spelling causes local name clashes, then spell them

import myclass
import foo.bar.yourclass

  and use "myclass.MyClass" and "foo.bar.yourclass.YourClass"

Ultimately it is a matter of taste I think!
-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


performance question: dictionary or list, float or string?

2008-12-02 Thread bkamrani
Hi Python gurus!
I'm going to read in an Ascii file containing float numbers in rows
and columns (say 10 columns 50 rows) for further numerical
process. Which format is best to save them in, eg, dictionary, list,
or numpy array when it comes to performance?

Will it be beneficial to convert all strings to float directly after
reading or it doesn't matter to save them as string and thereafter
when it comes to calculation convert them to floats?

Thank you!
/Ben
--
http://mail.python.org/mailman/listinfo/python-list


Re: performance question: dictionary or list, float or string?

2008-12-02 Thread bkamrani
I forgot to mention that I did a simple timeit test which doesn't
show
significant runtime difference 3.5 sec for dictionary case and 3.48
for
list case.


def read_as_dictionary():
fil = open('myDataFile', 'r')
forces = {}
for region in range(25):
forces[region] = {}

for step in range(2):
for region in range(25):
line = fil.next(); spl = line.split()
forces[region] [step] = spl

def read_as_list():
fil = open('myDataFile.txt', 'r')
forces = []
for region in range(25):
forces.append([])

for step in range(2):
for region in range(25):
line = fil.next(); spl = line.split()
forces[region].append(spl)

Cheers,
/Ben

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


Re: Do more imported objects affect performance

2008-12-02 Thread Bruno Desthuilliers

Nick Craig-Wood a écrit :

On Tue, Dec 02, 2008 at 11:24:29AM +0600, Taskinoor Hasan wrote:

On Mon, Dec 1, 2008 at 8:21 PM, Filip Gruszczy?ski <[EMAIL PROTECTED]>wrote:


I see. Thanks for a really good explanation, I like to know, how to do
things in the proper way :)

I always prefer to use import module and then use module.function. The
reason is simple. It makes the code more readable and maintainable.


I prefer the "from module import function".  That means that if
"module" doesn't supply "function" it raises an exception at compile
time, not run time when you try to run "module.function".


Nope. import is an executable statement, and ImportError happens at 
runtime too.


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


Re: How to instantiate in a lazy way?

2008-12-02 Thread Nick Craig-Wood
Slaunger <[EMAIL PROTECTED]> wrote:
>  On 2 Dec., 11:30, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> 
> >
> > For 4 attributes I'd probably go with the __getattr__.
> >
>  OK, I'll do that!
> 
> > Or you could easily write your own decorator to cache the result...
> >
> > Eg http://code.activestate.com/recipes/363602/
> 
>  Cool. I never realized I could write my own decorators!
>  I've so far only used them for
>  @classmethod, @staticmethod and stuff like that.
>  User defined decorators are nice and fun to do as well.
>  I just hope it will be understandable
>  in four years also...

Actually that decorator does exactly what you want.  It replaces the
attribute with the actual data so after the first call there is no
overhead.  I'd use that I think!

> > > ?With the property methology you do the value check on each get, which
> > > ?does not look as "clean". The property methology is also a little less
> > > ?arcane I guess for less experienced Python programmers to understand
> > > ?when re-reading the code.
> >
> > Less magic is how I would put it. ?Magic is fun to write, but a pain
> > to come back to. ?Over the years I find I try to avoid magic more and
> > more in python.
> >
>  Ah, I see. I hope you do not consider user defined decorators
>  "magic" then? ;-)

Well the magic is contained in the decorator so it isn't splattered
throughout your code!

Decorators are part of the meta-programming toolbag along with
metaclasses.  Used sparingly they can be extrememly useful!

>  Again, thank you for your assistance, Nick!

No problem!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Do more imported objects affect performance

2008-12-02 Thread Steven D'Aprano
On Tue, 02 Dec 2008 11:12:31 +, Nick Craig-Wood wrote:

> I prefer the "from module import function".  That means that if "module"
> doesn't supply "function" it raises an exception at compile time, not
> run time when you try to run "module.function".

Wanna bet?


>>> def spam():
... from math import harmonic_series
... return harmonic_series()
...
>>> dis.dis(spam)
  2   0 LOAD_CONST   1 (-1)
  3 LOAD_CONST   2 (('harmonic_series',))
  6 IMPORT_NAME  0 (math)
  9 IMPORT_FROM  1 (harmonic_series)
 12 STORE_FAST   0 (harmonic_series)
 15 POP_TOP

  3  16 LOAD_FAST0 (harmonic_series)
 19 CALL_FUNCTION0
 22 RETURN_VALUE
>>> spam()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 2, in spam
ImportError: cannot import name harmonic_series


The same thing happens if the from...import is at the top level of the 
module, except that compilation is immediately followed by execution.


> It then becomes very
> easy to see which functions you use from any given module too.

If that's important to you. Personally, I find it more useful to know 
where a function is defined.


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


RE: How to sort a list of file paths

2008-12-02 Thread Eriksson, John
Hi again,

I've updated the example using the ideas and python tricks used on pages found 
via the link you gave me, Chris.

So... for future references here's the best (?) way of sorting a list of file 
names in the correct way (correct for some applications at least).

Note: For some odd reason I seemed to get the best performance using a lambda 
defined function instead of an ordinary function.

# --- EXAMPLE ---

import re
RE_DIGIT = re.compile(r'(\d+)')
ALPHANUM_KEY = lambda s: [int(g) if g.isdigit() else g for g in 
RE_DIGIT.split(s)]

file_list = ["File2.txt","File1.txt","File10.txt"]
file_list.sort(key=ALPHANUM_KEY)

# ---

Best Regards
/John


-Original Message-
From: [EMAIL PROTECTED] [mailto:[EMAIL PROTECTED] On Behalf Of Chris Rebert
Sent: den 2 december 2008 10:26
To: Eriksson, John
Cc: python-list@python.org
Subject: Re: How to sort a list of file paths

On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John
<[EMAIL PROTECTED]> wrote:
> Hi,
>
>
>
> This weekend I had some problems to get a list containing file paths to be
> sorted in a way that I could use.
>
>
>
> I also found a thread in this mailing list (
> http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and
> realized that others might be interested in a solution.
>
>
>
> So... here is my five cents regarding file path sorting:
>
>
>
> Problem description:
>
>
>
> You have a list containing some file names:
>
>
>
 file_list = ["File2.txt","File1.txt","File10.txt"]
>
>
>
> If you sort this list in the conventional way you end up with a result like:
>
>
>
 file_list.sort()
>
 print file_list
>
> ['File1.txt','File10.txt','File2.txt']
>
>
>
> Solution:
>
>
>
> Sort the list by splitting alphas and digits in to groups and compare them
> separately.
>
>
>
> import re
>
> def true_alphanum_cmp(a,b):
>
> aa = re.findall(r'\d |\D ', a)
>
> bb = re.findall(r'\d |\D ', b)
>
> for i in range(min(len(aa),len(bb))):
>
> if aa[i].isdigit() and bb[i].isdigit():
>
> c = cmp(int(aa[i]),int(bb[i]))
>
> else:
>
> c = cmp(aa[i],bb[i])
>
> if c!=0:
>
> return c
>
> return cmp(len(aa),len(bb))
>
>
>
> file_list = ["File2.txt","File1.txt","File10.txt"]
>
> file_list.sort(true_alphanum_cmp)
>
>
>
> If the formatting in this mail is messed up you can find the example at
> http://arainyday.se/notebook/true_alphanum_cmp.php
>
>
>
> All comments and improvements are welcome!

Sounds like the issue discussed in the post on Coding Horror:
http://www.codinghorror.com/blog/archives/001018.html
It even links to another Python version of the algorithm.

Cheers,
Chris
--
Follow the path of the Iguana...
http://rebertia.com

>
>
>
> Best regards
>
> John Eriksson
>
> _
>
>
>
> Logica - Releasing your potential
>
> Tegsplan 2b
>
> 904 20 UMEÅ
>
> Sweden
>
>
>
> T: +46 (0) 90 15 91 38
>
> M: +46 (0) 70 366 16 77
>
> E: [EMAIL PROTECTED]
>
> www.logica.se
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: performance question: dictionary or list, float or string?

2008-12-02 Thread Steven D'Aprano
On Tue, 02 Dec 2008 03:41:29 -0800, bkamrani wrote:

> Hi Python gurus!
> I'm going to read in an Ascii file containing float numbers in rows and
> columns (say 10 columns 50 rows) for further numerical process.
> Which format is best to save them in, eg, dictionary, list, or numpy
> array when it comes to performance?

That depends on:

(1) What do you mean by performance? Speed or memory use? 

(2) Do you care about the performance of reading the data in, or the 
performance of working with the data later, or both?

(3) What do you intend to do with the numbers later?


> Will it be beneficial to convert all strings to float directly after
> reading or it doesn't matter to save them as string and thereafter when
> it comes to calculation convert them to floats?

That depends on what you intend to do with them. Since you're doing 
numerical processing, it's probably a good idea to convert them to 
numbers rather than strings.



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


Re: Python+Pyjamas+V8=ftw

2008-12-02 Thread lkcl
> Another project similar-ish to Pyjamas is
> HotRuby:http://hotruby.yukoba.jp/

 also there's RubyJS:

 http://rubyforge.org/projects/rubyjs/

 it's again a javascript compiler - ruby to javascript - and the
beginnings of a port of GWT to Ruby, called rwt.

 this project _definitely_ needs more attention.

 michael's talk (included in the docs/) shows that he has spent
considerable effort in ensuring that not only is the compiler faithful
to the features of ruby, but also that the features are translated
_efficiently_.

 which takes a hell of a lot of doing.

 the nice thing about michael's work is that he's leading the way in
showing the pyjamas compiler how it _really_ should be done.

 pyjamas is capable of running a very significant amount of python,
but it _is_ missing some crucial features: **kwargs for example, and
the 0.4 release has just added a _very_ basic type of exception
handling.

 that having been said: for the majority of purposes - most web
development - pyjamas is _more_ than adequate.

 as a general-purpose plugin replacement for /usr/bin/python, however,
it's not quite there.  and, given that javascript cheerfully goes
about its way with the "undefined" concept, it's always going to be a
_bit_ tricky to provide absolutely _every_ language feature,
faithfully.

 that having been said, the speedup factor of pyv8 should make the
pyjamas compiler a _really_ attractive option, and i think that when
 it becomes the "norm" to have a javascript interpreter as part of a
 sysadmin's / developer's dailiy life in the same way that /usr/bin/
perl
 and /usr/bin/python are, then compilers like RubyJS, Pyjamas and GWT
 will have a much bigger significance.

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


Determining number of dict key collisions in a dictionary

2008-12-02 Thread python
Is there any way to determine the number of dictionary key
collisions in a specific dictionary?
Background: I'm working on a project using very large
dictionaries (64 bit Python) and question from my client is how
effective is Python's default hash technique for our data set?
Their concern is based on the belief that Python's default
dictionary hash scheme is optimized for 32 bit vs. 64 bit
environments and may not have anticipated the additional range of
keys that can be generated in a 64 bit environment. Our keys are
based on 20 to 44 byte ASCII (7-bit) alpha-numeric strings.
Thank you,
Malcolm
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to sort a list of file paths

2008-12-02 Thread Chris Rebert
On Tue, Dec 2, 2008 at 12:36 AM, Eriksson, John
<[EMAIL PROTECTED]> wrote:
> Hi,
>
>
>
> This weekend I had some problems to get a list containing file paths to be
> sorted in a way that I could use.
>
>
>
> I also found a thread in this mailing list (
> http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and
> realized that others might be interested in a solution.
>
>
>
> So... here is my five cents regarding file path sorting:
>
>
>
> Problem description:
>
>
>
> You have a list containing some file names:
>
>
>
 file_list = ["File2.txt","File1.txt","File10.txt"]
>
>
>
> If you sort this list in the conventional way you end up with a result like:
>
>
>
 file_list.sort()
>
 print file_list
>
> ['File1.txt','File10.txt','File2.txt']
>
>
>
> Solution:
>
>
>
> Sort the list by splitting alphas and digits in to groups and compare them
> separately.
>
>
>
> import re
>
> def true_alphanum_cmp(a,b):
>
> aa = re.findall(r'\d |\D ', a)
>
> bb = re.findall(r'\d |\D ', b)
>
> for i in range(min(len(aa),len(bb))):
>
> if aa[i].isdigit() and bb[i].isdigit():
>
> c = cmp(int(aa[i]),int(bb[i]))
>
> else:
>
> c = cmp(aa[i],bb[i])
>
> if c!=0:
>
> return c
>
> return cmp(len(aa),len(bb))
>
>
>
> file_list = ["File2.txt","File1.txt","File10.txt"]
>
> file_list.sort(true_alphanum_cmp)
>
>
>
> If the formatting in this mail is messed up you can find the example at
> http://arainyday.se/notebook/true_alphanum_cmp.php
>
>
>
> All comments and improvements are welcome!

Sounds like the issue discussed in the post on Coding Horror:
http://www.codinghorror.com/blog/archives/001018.html
It even links to another Python version of the algorithm.

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

>
>
>
> Best regards
>
> John Eriksson
>
> _
>
>
>
> Logica - Releasing your potential
>
> Tegsplan 2b
>
> 904 20 UMEÅ
>
> Sweden
>
>
>
> T: +46 (0) 90 15 91 38
>
> M: +46 (0) 70 366 16 77
>
> E: [EMAIL PROTECTED]
>
> www.logica.se
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
--
http://mail.python.org/mailman/listinfo/python-list


best way to do this

2008-12-02 Thread TP
Hi everybody,

>>> c=[(5,3), (6,8)]

>From c, I want to obtain a list with 5,3,6, and 8, in any order.
I do this:

>>> [i for (i,j) in c] + [ j for (i,j) in c]
[5, 6, 3, 8]

Is there a quicker way to do this?

Thanks

Julien
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in '*9(9&(18%.9&1+,\'Z
(55l4('])"

"When a distinguished but elderly scientist states that something is
possible, he is almost certainly right. When he states that something is
impossible, he is very probably wrong." (first law of AC Clarke)
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to do this

2008-12-02 Thread Diez B. Roggisch
TP wrote:

> Hi everybody,
> 
 c=[(5,3), (6,8)]
> 
> From c, I want to obtain a list with 5,3,6, and 8, in any order.
> I do this:
> 
 [i for (i,j) in c] + [ j for (i,j) in c]
> [5, 6, 3, 8]
> 
> Is there a quicker way to do this?

dunno if it's faster, but less cluttered:

list(sum(c, ()))

Diez

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


Re: pydoc enforcement.

2008-12-02 Thread J. Cliff Dyer

On Tue, 2008-12-02 at 09:38 +1100, Ken Faulkner wrote:
> Hi
> 
> Yeah, I was thinking about something at commit time for a VCS...
> catch is, soo many VCS's out there. 
> And I wasn't thinking of the default action throwing compile errors,
> but would only do that if a particular flag was given.
> Still, just an idea.
> 

I meant more that a cultural solution might work better than a technical
one.  Don't allow commits that aren't documented, and *properly*
documented.  If you find them, back them out, scold the commiter, and
revise.


> I'm just finding more and more public modules/API's/libraries that
> have so little documentation that it really does force reading a LOT
> of the source to figure out whats going on. Sure, a lot of the time
> thats required, but some modules are just painful..
> 
> oh well... was just a thought.
> 
> Ken
> 
> 
> 
> On Tue, Dec 2, 2008 at 3:03 AM, J. Cliff Dyer <[EMAIL PROTECTED]>
> wrote:
> 
> 
> On Sun, 2008-11-30 at 16:27 -0800, [EMAIL PROTECTED]
> wrote:
> > I've been thinking about implementing (although no idea yet
> *HOW*) the
> > following features/extension for the python compile stage
> and would be
> > interested in any thoughts/comments/flames etc.
> >
> > Basically I'm interested adding a check to see if:
> >   1) pydoc's are written for every function/method.
> >   2) There are entries for each parameter, defined by some
> > predetermined syntax.
> >
> > My idea is that as much as I love dynamic typing, there are
> times when
> > using some modules/API's that have less than stellar
> documentation. I
> > was thinking that if it was possible to enable some switch
> that
> > basically forced compilation to fail if certain
> documentation criteria
> > weren't met.
> >
> > Yes, it should be up to developers to provide documentation
> in the
> > first place. Or, the client developer might need to read the
> source
> > (IF its available)...  but having some "forced"
> documentation might at
> > least ease the problem a little.
> >
> > For example (half borrowing from Javadoc).
> >
> > class Foo( object ):
> >
> >   def bar( self, ui ):
> >  pass
> >
> >
> > Would fail, since the bar method has an "unknown" parameter
> called
> > "ui".
> > What I think could be interesting is that the compiler
> forces some
> > documentation such as:
> >
> > class Foo( object ):
> >
> >   def bar( self, ui ):
> > """
> > @Param: ui :  blah blah blah.
> > """
> >  pass
> >
> >
> > The compiler could check for @Param matching each parameter
> passed to
> > the method/function. Sure, a lot of people might just not
> put a
> > description in, so we'd be no better off. But at least its
> getting
> > them *that* far, maybe it would encourage them to actually
> fill in
> > details.
> >
> > Now ofcourse, in statically  typed language, they might have
> the
> > description as "Instance of UIClass" or something like that.
> For
> > Python, maybe just a description of "Instance of abstract
> class UI" or
> > "List of Dictionaries"...  or whatever. Sure, precise class
> names
> > mightn't be mentioned (since we mightn't know what is being
> used
> > then), but having *some* description would certainly be
> helpful (I
> > feel).
> >
> > Even if no-one else is interested in this feature, I think
> it could
> > help my own development (and would be an interested "first
> change"
> > into Python itself).
> >
> > Apart from bagging the idea, does anyone have a suggestion
> on where in
> > the Python source I would start for implementing such an
> idea?
> >
> > Thanks
> >
> > Ken
> 
> 
> For the reasons already stated, I think it's probably a bad
> idea to
> enforce this at compile time.  I think it's a great idea to
> make sure
> that this information is present in all your code, but unless
> you want
> to see useless stubs, the correct time to enforce this is at
> commit
> time.  Don't accept any improperly documented patches.
> 
> Syntax is not enough to ensure what you want to ensure.  The
> semantics
> have to be right as well.
> 
> Cheers,
> Cliff
> 
> 
> 
>  

Running a Python script from crontab

2008-12-02 Thread Astley Le Jasper
I need help ... I've been looking at this every evening for over a
week now. I'd like to see my kids again!

I have script that runs fine in the terminal but when I try to run it
in a crontab for either myself or root, it bails out.

The trouble is that obviously I get no console when using crontab so
can't see any traceback. I use logging which shows 'info' messages as
the script is working, but no error messages. I've peppered it with
debug messages to try to track it down to a line, but it stops it the
middle of appending data to a list. I'd expect it to bail out when
calling a module or reading/writing to a different file.

Is there any way of getting more info from the app, like popping up a
console while its running?

my crontab is:

30 15 * * * cd /home/myusername/src && python myscript.py

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


Re: Running a Python script from crontab

2008-12-02 Thread James Mills
Put your main function in a big
try, except. Catch any and all
errors and log them. Example:

def main():
   try:
  do_something()
   except Exception, error:
  log("ERROR: %s" % error)
  log(format_exc())

Hope this helps.

cheers
James

On Wed, Dec 3, 2008 at 12:35 AM, Astley Le Jasper
<[EMAIL PROTECTED]> wrote:
> I need help ... I've been looking at this every evening for over a
> week now. I'd like to see my kids again!
>
> I have script that runs fine in the terminal but when I try to run it
> in a crontab for either myself or root, it bails out.
>
> The trouble is that obviously I get no console when using crontab so
> can't see any traceback. I use logging which shows 'info' messages as
> the script is working, but no error messages. I've peppered it with
> debug messages to try to track it down to a line, but it stops it the
> middle of appending data to a list. I'd expect it to bail out when
> calling a module or reading/writing to a different file.
>
> Is there any way of getting more info from the app, like popping up a
> console while its running?
>
> my crontab is:
>
> 30 15 * * * cd /home/myusername/src && python myscript.py
>
> ALJ
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to do this

2008-12-02 Thread Hrvoje Niksic
TP <[EMAIL PROTECTED]> writes:

> Hi everybody,
>
 c=[(5,3), (6,8)]
>
> From c, I want to obtain a list with 5,3,6, and 8, in any order.
> I do this:
>
 [i for (i,j) in c] + [ j for (i,j) in c]
> [5, 6, 3, 8]
>
> Is there a quicker way to do this?

Quicker?  Hard to say.  Using itertools elegantly?  Definitely:

list(chain(*c))

As an added benefit, it works regardless of the number of elements in
the tuple.  (Also assumes from itertools import chain for effect.)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Checking a string against multiple matches

2008-12-02 Thread Chris
On Dec 2, 3:01 am, alex23 <[EMAIL PROTECTED]> wrote:
> On Dec 2, 5:31 am, Aaron Scott <[EMAIL PROTECTED]> wrote:
>
> > I was using .index on the
> > list, but it would return True for strings that contained the search
> > string rather than match it exactly, leading to false positives in my
> > code.
>
> Are you sure? That doesn't seem like standard behaviour.
>
> >>> l = ["one", "two", "three", "four"]
> >>> l.index('on')
>
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: list.index(x): x not in list>>> l.index('thre')
>
> Traceback (most recent call last):
>   File "", line 1, in 
> ValueError: list.index(x): x not in list
>
> The only time I'd expect it to do partial matches is if you were doing
> string.index(string), rather than list.index(string):
>
> >>> "four".index('our')
>
> 1

It would if the OP was iterating over the list and checking that item
with .index so it uses the string.index instead of list.index
--
http://mail.python.org/mailman/listinfo/python-list


Re: Running a Python script from crontab

2008-12-02 Thread Philip Semanchuk


On Dec 2, 2008, at 9:35 AM, Astley Le Jasper wrote:


I need help ... I've been looking at this every evening for over a
week now. I'd like to see my kids again!

I have script that runs fine in the terminal but when I try to run it
in a crontab for either myself or root, it bails out.

The trouble is that obviously I get no console when using crontab so
can't see any traceback. I use logging which shows 'info' messages as
the script is working, but no error messages. I've peppered it with
debug messages to try to track it down to a line, but it stops it the
middle of appending data to a list. I'd expect it to bail out when
calling a module or reading/writing to a different file.

Is there any way of getting more info from the app, like popping up a
console while its running?

my crontab is:

30 15 * * * cd /home/myusername/src && python myscript.py


Here's what my crontab looks like on FreeBSD. (Your syntax may  
differ.) Note how I'm redirecting stdout and stderr to a log file --  
that helps debugging. Also, I'm setting an explicit shell and path  
just to make sure that e.g. Python is findable.




SHELL=/usr/local/bin/bash
PATH=/bin:/usr/bin:/usr/local/bin

# minhhday   mon  dow
  */2 *  * **  python /usr/local/foo/myscript.py >> / 
var/log/me/myscript.txt 2>&1



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


Re: How to instantiate in a lazy way?

2008-12-02 Thread Nick Craig-Wood
Slaunger <[EMAIL PROTECTED]> wrote:
>  On 1 Dec., 16:30, Nick Craig-Wood <[EMAIL PROTECTED]> wrote:
> >
> > I wouldn't use __getattr__ unless you've got lots of attributes to
> > overload. ?__getattr__ is a recipe for getting yourself into trouble
> > in my experience ;-)
> >
> > Just do it like this...
> >
> > class PayloadOnDemand(object):
> > ? ? ? def __init__(self, a_file, a_file_position):
> > ? ? ? ? ? self._data = None
> > ? ? ? ? ? self.f = a_file
> > ? ? ? ? ? self.file_position = a_file_position
> >
> > ? ? ? @property
> > ? ? ? def data(self):
> > ? ? ? ? ? if self._data is None:
> > ? ? ? ? ? ? ? self._data = self.really_read_the_data()
> > ? ? ? ? ? return self._data
> >
> > then you'll have a .data attribute which when you read it for the
> > first time it will populate itself.
> >
> > If None is a valid value for data then make a sentinel, eg
> >
> > class PayloadOnDemand(object):
> > ? ? ? sentinel = object()
> >
> > ? ? ? def __init__(self, a_file, a_file_position):
> > ? ? ? ? ? self._data = self.sentinel
> > ? ? ? ? ? self.f = a_file
> > ? ? ? ? ? self.file_position = a_file_position
> >
> > ? ? ? @property
> > ? ? ? def data(self):
> > ? ? ? ? ? if self._data is self.sentinel:
> > ? ? ? ? ? ? ? self._data = self.really_read_the_data()
> > ? ? ? ? ? return self._data
> >
> >
> > - Vis tekst i anf?rselstegn -
> 
>  OK, I get it. In my case I have four attributes to create when one of
>  them is accessed, I do not know if that is a lot of attributes;-) One
>  thing I like about the __getattr__ is that it is only called that one
>  single time where an attempt to read a data attribute fails because
>  the attribute name is not defined in the __dict__ of the object.

For 4 attributes I'd probably go with the __getattr__.

Or you could easily write your own decorator to cache the result...

Eg http://code.activestate.com/recipes/363602/

>  With the property methology you do the value check on each get, which
>  does not look as "clean". The property methology is also a little less
>  arcane I guess for less experienced Python programmers to understand
>  when re-reading the code.

Less magic is how I would put it.  Magic is fun to write, but a pain
to come back to.  Over the years I find I try to avoid magic more and
more in python.

>  What kind of trouble are you referring to in __getattr__? Is it
>  recursive calls to the method on accessing object attributes in that
>  method itself or other complications?

Every time I write a __getattr__ I get tripped up by infinite
recursion!  It is probably just me ;-)

>  On a related issue, thank you for showing me how to use @property as a
>  decorator - I was not aware of that possibility, just gotta understand
>  how to decorate a setter and delete method as well, but I should be
>  able to look that up by myself...

I'm sure you will!

http://www.python.org/doc/2.5.2/lib/built-in-funcs.html

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is it safe to modify the dict returned by vars() or locals()

2008-12-02 Thread Duncan Booth
Helmut Jarausch <[EMAIL PROTECTED]> wrote:

> Chris Rebert wrote:
>> On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch <[EMAIL PROTECTED]>
>> wrote: 
>>> Hi,
>>>
>>> I am looking for an elegant way to solve the following problem:
>>>
>>> Within a function
>>>
>>> def Foo(**parms)
>>>
>>> I have a list of names, say  VList=['A','B','C1']
>>> and I like to generate abbreviation
>>> _A identical to parms['A']
>> 
>> Could you explain what you mean by that? Your sample code doesn't
>> seem to do any "abbreviation"...
>> Otherwise I don't see why you don't just have a proper parameter
>> list. 
> 
> In my application parms contains field names of an html form iff these
> fields have been modified.
> I'd like to use the short name  _A  instead of the longer expression
> parms['A'] 
> 
> 
You haven't yet explained why you don't just do:

def foo(A=None, **parms):
   ...

The code to call foo remains the same as before, but Python will unpack 
the named parameter into the local variable A for you automatically. Any 
other parms that you didn't know about in advance remain in the separate 
dictionary.


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Obama's Birth Certificate - Demand that US presidential electors investigate Obama's eligibility

2008-12-02 Thread girbarobert
This message is not about the meaningless computer printout called
"Certification of Live Birth" that Obama propaganda machine calls his
"Birth Certificate". The American people are still waiting for a copy
of Obama's original birth certificate that includes all his birth
information.

Remind your US presidential electors of their constitutional duty to
investigate Obama's natural-born citizen status.

No federal agency like FBI or Secret Service, no Hawaii bureaucrats
have ever investigated Obama's birth in Hawaii. Many illegal aliens in
USA have official "birth certificates" issued by state bureaucrats on
the basis of falsified birth records. Obama has spent over $800,000 in
legal costs to avoid presenting a $10 copy of his original birth
certificate on the grounds that nobody has a legal standing to see
it.

Remind your US presidential electors that they have the legal standing
and constitutional duty to investigate Obama's birth in Hawaii by
demanding that Obama provide all his original birth records, and a
federal agency like FBI or Secret Service fully investigate them.

To find the names of US presidential electors use the partial list at
wikipedia below. Or use www.google.com, click News on top, then in the
Search News enter the name of your state and the words: presidential
electors. Or contact your US Senators, US House Rep, your state
senators/reps, etc.

If a US presidential elector refuses to investigate Obama's
eligibility then post his/her full name on the internet so that all
web search engines can pick it up.


http://www.wnd.com/index.php?fa=PAGE.view&pageId=81550

http://en.wikipedia.org/wiki/List_of_United_States_presidential_electors,_2008
http://www.senate.gov/general/contact_information/senators_cfm.cfm
http://clerk.house.gov/member_info/index.html


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


Re: How to instantiate in a lazy way?

2008-12-02 Thread Slaunger
Just wanted to show the end result in its actual implementation!

I ended up *not* making a decorator, as I already had a good idea
about how to do it
using __getattr__

class PayloadDualFrqIQOnDemand(PayloadDualFrqIQ):
"""
This class has the same interface as its parent,
but unlike its parent, it is instantiated without
its payload parsed up in its instance attributes
Q1, I1, Q2 and I2. Instead it stores a reference to
the file object in which the Payload data can be
read, the file position and
the version of the payload data.

On accessing one of the data attributes, the actual
payload data are read from the file, and the reference to
the file object is unbound.
The constructor signature is therefore different from its
parent as it takes the file object, position and version
as arguments instead of the actual data.
"""

@classmethod
def _unpack_from_file(cls, f, samples, ver):
bytes = samples * cls.bytes_per_sample
initial_pos = f.tell()
f.seek(initial_pos + bytes) #Skip over the payload
return cls(f, initial_pos, samples, ver)

@classmethod
def unpack_from_ver3_file(cls, f, samples):
return cls._unpack_from_file(f, samples, ver=3)

@classmethod
def unpack_from_ver4_file(cls, f, samples):
return cls._unpack_from_file(f, samples, ver=4)

data_attr_names = frozenset(["Q1", "I1", "Q2", "I2"])

def __init__(self, a_file, a_file_position, samples, a_version):
"""
Returns an instance where the object knows where to
look for the payload but it will only be loaded on the
first attempt to read one of the data attributes
in a "normal" PayloadDualFrqIQ object.
"""
self.f = a_file
self.file_position = a_file_position
self.samples = samples
self.ver = a_version

def __getattr__(self, attr_name):
"""
Checks if a request to read a non-existing data attribute
has an attribute corresponding to one of the data attributes
in a normal PayloadDualFrqIQ object.

If true, the data attributes are created and bound to the
object using the file object instance, the file position
and the version.

It is a prerequisite that the file object is still open.
The function leaves the file object at the file position
when it entered the method

"""
cls = self.__class__
if attr_name in cls.data_attr_names:
initial_pos = self.f.tell()
try:
bytes = self.samples * cls.bytes_per_sample
self.f.seek(self.file_position)
buf = self.f.read(bytes)
if self.ver == 3:
bytes_to_data = cls._v3_byte_str_to_data
elif self.ver == 4:
bytes_to_data = cls._v4_byte_str_to_data
else:
raise TermaNotImplemented, \
"Support for ver. %d not implemented." %
self.ver
I1, Q1, I2, Q2 = bytes_to_data(buf)
self.__dict__["I1"] = I1
self.__dict__["Q1"] = Q1
self.__dict__["I2"] = I2
self.__dict__["Q2"] = Q2
return self.__dict__[attr_name]
finally:
# Restore file position
self.f.seek(initial_pos)
# Unbind lazy attributes
del self.f
del self.ver
del self.file_position
del self.samples

This seems to work out well. No infinite loops in __getattr__!

At least it passes the unit test cases I have come up with so far.

No guarantees though, as I may simply not have been smart enough to
bring forth unit test cases which make it crash.

Comments on the code is still appreciated though.

I am still a novice Python programmer, and I may have overlooked
more Pythonic ways to do it.

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


ANN: eGenix mxODBC Connect - Python Database Interface 1.0.0

2008-12-02 Thread eGenix Team: M.-A. Lemburg


ANNOUNCING
eGenix.com mxODBC Connect

Python Database Interface

 Version 1.0.0


  Our new client-server product for connecting Python applications
 to relational databases - from all major platforms


This announcement is also available on our web-site for online reading:
http://www.egenix.com/company/news/eGenix-mxODBC-Connect-1.0.0-GA.html



INTRODUCTION

The mxODBC Connect Database Interface for Python allows users to
easily connect Python applications to all major databases on the
market today in a highly portable and convenient way.

Unlike our mxODBC Python extension, mxODBC Connect is designed
as client-server application, so you no longer need to find production
quality ODBC drivers for all the platforms you target with your Python
application.

Instead you use an easy to install Python client library which
connects directly to the mxODBC Connect database server over the
network.

This makes mxODBC Connect the ideal basis for writing cross-platform
database programs and utilities in Python, especially if you run
applications that need to communicate with databases such as MS SQL
Server and MS Access, Oracle Database, IBM DB2 and Informix, Sybase
ASE and Sybase Anywhere, MySQL, PostgreSQL, SAP MaxDB and many more,
that run on Windows or Linux machines.

By removing the need to install and configure ODBC drivers on the
client side, mxODBC Connect greatly simplifies setup and
configuration of database driven client applications, while at
the same time making the network communication between client and
database server more efficient and more secure.

For more information, please see the product page:

http://www.egenix.com/products/python/mxODBCConnect/



NEWS

mxODBC Connect 1.0.0 is the first general availability release of our
new mxODBC Connect product.

With this release we have further improved the performance and
round-trip times of the mxODBC Connect network layer even more.

We are now able to achieve a *more than 10 times better performance*
for a typical multi-tier application that runs on Linux and connects
to a MS SQL Server database running on a Windows host, compared to the
same application using mxODBC and the FreeTDS ODBC driver.

Thanks to everyone who participated in the public beta !



DOWNLOADS

The download archives as well as instructions for installation and
configuration of the product can be found on the product page:

http://www.egenix.com/products/python/mxODBCConnect/

Evaluation licenses for the server part are available free of
charge:

http://www.egenix.com/products/python/mxODBCConnect/#Evaluation

The client part of mxODBC Connect is always free of charge.

___

SUPPORT

Commercial support for this product is available from eGenix.com.

Please see

http://www.egenix.com/services/support/

for details about our support offerings.

Enjoy,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Dec 02 2008)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2008-12-02: Released mxODBC.Connect 1.0.0  http://python.egenix.com/

 Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611


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


Re: Checking a string against multiple matches

2008-12-02 Thread alex23
On Dec 2, 10:09 pm, Chris <[EMAIL PROTECTED]> wrote:
> On Dec 2, 3:01 am, alex23 <[EMAIL PROTECTED]> wrote:
> > The only time I'd expect it to do partial matches is if you were doing
> > string.index(string), rather than list.index(string):

> It would if the OP was iterating over the list and checking that item
> with .index so it uses the string.index instead of list.index

Which is what I was implying when I wrote "The only time I'd expect it
to do partial matches is if you were doing string.index(string),
rather than list.index(string)", oddly enough :)
--
http://mail.python.org/mailman/listinfo/python-list


How to sort a list of file paths

2008-12-02 Thread Eriksson, John
Hi,

This weekend I had some problems to get a list containing file paths to be 
sorted in a way that I could use.

I also found a thread in this mailing list ( 
http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and 
realized that others might be interested in a solution.

So... here is my five cents regarding file path sorting:

Problem description:

You have a list containing some file names:

>>> file_list = ["File2.txt","File1.txt","File10.txt"]

If you sort this list in the conventional way you end up with a result like:

>>> file_list.sort()
>>> print file_list
['File1.txt','File10.txt','File2.txt']

Solution:

Sort the list by splitting alphas and digits in to groups and compare them 
separately.

import re
def true_alphanum_cmp(a,b):
aa = re.findall(r'\d |\D ', a)
bb = re.findall(r'\d |\D ', b)
for i in range(min(len(aa),len(bb))):
if aa[i].isdigit() and bb[i].isdigit():
c = cmp(int(aa[i]),int(bb[i]))
else:
c = cmp(aa[i],bb[i])
if c!=0:
return c
return cmp(len(aa),len(bb))

file_list = ["File2.txt","File1.txt","File10.txt"]
file_list.sort(true_alphanum_cmp)

If the formatting in this mail is messed up you can find the example at 
http://arainyday.se/notebook/true_alphanum_cmp.php

All comments and improvements are welcome!

Best regards
John Eriksson
_

Logica - Releasing your potential
Tegsplan 2b
904 20 UMEÅ
Sweden

T: +46 (0) 90 15 91 38
M: +46 (0) 70 366 16 77
E: [EMAIL PROTECTED]
www.logica.se


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


"server chain" with python socket module

2008-12-02 Thread B R

dear all,
I want to connect my A machine to the E server via servers B, C and D,
is there a way to set-up such "server chain" with python socket module (or 
other module) ?
many thanks
boris
vn%ibo%ris[at]hotmail.com
_
News, entertainment and everything you care about at Live.com. Get it now!
http://www.live.com/getstarted.aspx--
http://mail.python.org/mailman/listinfo/python-list


[ANN] Pyjamas 0.4: Python Web Toolkit Release

2008-12-02 Thread Luke Kenneth Casson Leighton
This is the 0.4 Release of Pyjamas, the python-to-javascript
compiler and Web Widget set and framework.

Download Pyjamas 0.4 here:
https://sourceforge.net/project/showfiles.php?group_id=239074
http://code.google.com/p/pyjamas/downloads/list

Pyjamas started as a port of Google's Web Toolkit, to python.
Explaining why Pyjamas (and GWT) is so significant takes
some doing: the summary is that comprehensive desktop-like
user interfaces can be developed very simply, to run in
any modern web browser, without having to write a single
line of JavaScript. Further recommended reading is here:
http://advogato.org/article/993.html
http://advogato.org/article/981.html

The homepage is http://pyjs.org
The sister project, Pyjamas-Desktop, is at http://pyjd.org

Documentation on Pyjamas is considerable, and includes:
  http://pyjs.org/book/output/Bookreader.html
  http://pyjs.org/showcase/Showcase.html
  http://pyjd.sf.net/api
  http://pyjd.sf.net/controls_tutorial.html
  http://lkcl.net/pyjamas-desktop/docs/output/docui.html
Also, as the Pyjamas UI API is near-identical to that of
GWT 1.5, the GWT JavaDoc reference guide is still relevant:
  http://google-web-toolkit.googlecode.com/svn/javadoc/1.5/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Posting File as a parameter to PHP/HTML using HTTP POST

2008-12-02 Thread S.Selvam Siva
I myself have found the solution.

Instead of:
br[br['uploadedfile']=open("C:/
>
> Documents and Settings/user/Desktop/Today/newurl-ideas.txt")


We Need to use:
br.add_file(open("C:/
>
> Documents and Settings/user/Desktop/Today/newurl-ideas.txt"),
> filename="newurl-ideas.txt",name="uploadedfile")
>


On Tue, Dec 2, 2008 at 1:33 PM, S.Selvam Siva <[EMAIL PROTECTED]>wrote:

> I am trying to post file from python to php using HTTP POST method. I tried
> mechanize but not able to pass the file object.
>
> from mechanize import Browser
> br=Browser()
> response=br.open("http://localhost/test.php";)
> br.select_form('form1')
> br['uploadedfile']=open("C:/Documents and
> Settings/user/Desktop/Today/newurl-ideas.txt")
> response=br.submit()
> print response.read()
>
> But, i get the error:
> br['uploadedfile']=open("C:/Documents and
> Settings/user/Desktop/Today/newurl
> -ideas.txt")
>   File
> "C:\Python25\lib\site-packages\clientform-0.2.9-py2.5.egg\ClientForm.py",
>  line 2880, in __setitem__
> ValueError: value attribute is readonly
>
> But,
> When uploading is done using browser, it works.
> --
> Yours,
> S.Selvam
>



-- 
Yours,
S.Selvam
--
http://mail.python.org/mailman/listinfo/python-list


Re: optimization

2008-12-02 Thread Duncan Booth
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> Which makes me wonder, is there anything we can do with that code object 
> from Python code? I can disassemble it:
> 
 import dis
 dis.dis(outer.func_code.co_consts[1])
>   3   0 LOAD_CONST   0 (None)
>   3 RETURN_VALUE
> 
> Anything else?

Provided it doesn't take any arguments you can run the code with exec or 
eval:

>>> def outer():
def inner():
print "inner called"
return inner()

>>> eval(outer.func_code.co_consts[1])
inner called

More usefully you could use the code object to construct another function, 
e.g. if you wanted to change the values of some default arguments.

>>> types.FunctionType(outer.func_code.co_consts[1], globals())()
inner called


-- 
Duncan Booth http://kupuguy.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Is it safe to modify the dict returned by vars() or locals()

2008-12-02 Thread Helmut Jarausch

Chris Rebert wrote:

On Mon, Dec 1, 2008 at 1:01 PM, Helmut Jarausch <[EMAIL PROTECTED]> wrote:

Hi,

I am looking for an elegant way to solve the following problem:

Within a function

def Foo(**parms)

I have a list of names, say  VList=['A','B','C1']
and I like to generate abbreviation
_A identical to parms['A']


Could you explain what you mean by that? Your sample code doesn't seem
to do any "abbreviation"...
Otherwise I don't see why you don't just have a proper parameter list.


In my application parms contains field names of an html form iff these fields
have been modified.
I'd like to use the short name  _A  instead of the longer expression parms['A']



--
Helmut Jarausch

Lehrstuhl fuer Numerische Mathematik
RWTH - Aachen University
D 52056 Aachen, Germany
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP!...Google SketchUp needs a Python API

2008-12-02 Thread James Mills
Pssft r, it's I that needs to get laid :)

--JamesMills

On Tue, Dec 2, 2008 at 4:07 PM, r <[EMAIL PROTECTED]> wrote:
> PS james,
>
> Since you are alex23's friend, do the world a favor...PLEASE GET ALEX
> LAID...before it's too late!
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: optimization

2008-12-02 Thread Steven D'Aprano
On Mon, 01 Dec 2008 18:11:16 -0600, Robert Kern wrote about nested 
functions:

> I, for one, find that significantly less clear. I only expect functions
> to be defined inside of functions if they are going to use lexical
> scoping for some reason. If I read your code, I'd probably waste a good
> five minutes trying to figure out what part of the local scope you were
> using before I would conclude that you just did it because you thought
> it looked better.

Hah, I bet you aren't an ex-Pascal programmer :-)

Speaking as one, it took me a long time to teach myself not to bother 
nesting functions for the purpose of avoiding scoping clashes. I'd write 
something like this:

def parrot():
def colour():
return "Blue"
return "Norwegian %s" % colour()


def cardinal(x):
def colour():
return "crimson"
return "Cardinal Fang wears a %s robe" % colour()


Except of course that's a trivially silly example. (For the sake of the 
argument, let's pretend the two functions colour() do actual 
calculations.)

These days, I'd write them something like this:

def parrot_colour():
return "Blue"

def cardinal_colour():
return "crimson"

def parrot():
return "Norwegian %s" % parrot_colour()

def cardinal(x):
return "Cardinal Fang wears a %s robe" % cardinal_colour()


These days, almost the only time I use nested functions is for function 
factories.



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


Re: How to sort a list of file paths

2008-12-02 Thread James Mills
Hi Eriksson,

It's nice to see people actually contribute what they've learned back
to the community.
Great problem, well thought out solution and congrats on the learning :)

I can't say per say that I've actually run into a situation where I
need to sort file paths
in this way ... But if I do I'll be sure to use your function :)

--JamesMills

On Tue, Dec 2, 2008 at 6:36 PM, Eriksson, John <[EMAIL PROTECTED]> wrote:
> Hi,
>
>
>
> This weekend I had some problems to get a list containing file paths to be
> sorted in a way that I could use.
>
>
>
> I also found a thread in this mailing list (
> http://mail.python.org/pipermail/python-list/2007-April/433590.html ) and
> realized that others might be interested in a solution.
>
>
>
> So... here is my five cents regarding file path sorting:
>
>
>
> Problem description:
>
>
>
> You have a list containing some file names:
>
>
>
 file_list = ["File2.txt","File1.txt","File10.txt"]
>
>
>
> If you sort this list in the conventional way you end up with a result like:
>
>
>
 file_list.sort()
>
 print file_list
>
> ['File1.txt','File10.txt','File2.txt']
>
>
>
> Solution:
>
>
>
> Sort the list by splitting alphas and digits in to groups and compare them
> separately.
>
>
>
> import re
>
> def true_alphanum_cmp(a,b):
>
> aa = re.findall(r'\d |\D ', a)
>
> bb = re.findall(r'\d |\D ', b)
>
> for i in range(min(len(aa),len(bb))):
>
> if aa[i].isdigit() and bb[i].isdigit():
>
> c = cmp(int(aa[i]),int(bb[i]))
>
> else:
>
> c = cmp(aa[i],bb[i])
>
> if c!=0:
>
> return c
>
> return cmp(len(aa),len(bb))
>
>
>
> file_list = ["File2.txt","File1.txt","File10.txt"]
>
> file_list.sort(true_alphanum_cmp)
>
>
>
> If the formatting in this mail is messed up you can find the example at
> http://arainyday.se/notebook/true_alphanum_cmp.php
>
>
>
> All comments and improvements are welcome!
>
>
>
> Best regards
>
> John Eriksson
>
> _
>
>
>
> Logica - Releasing your potential
>
> Tegsplan 2b
>
> 904 20 UMEÅ
>
> Sweden
>
>
>
> T: +46 (0) 90 15 91 38
>
> M: +46 (0) 70 366 16 77
>
> E: [EMAIL PROTECTED]
>
> www.logica.se
>
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Ideal girl dance WEBCAM ! Ideal boobs !

2008-12-02 Thread [EMAIL PROTECTED]
http://yeba.pl/show/movies/5257/Perfect_babe_-_Idealna_kobieta
--
http://mail.python.org/mailman/listinfo/python-list


help me~!about base64

2008-12-02 Thread ylj798
my code:
−
import base64
def deflashget(st):
 if st.startswith('Flashget://'):
 return base64.decodestring(st[len('Flashget://'):])[10:-10]
 elif st.startswith('http://') or st.startswith('ftp://'):
 return 'Flashget://' + base64.encodestring('[FLASHGET]' + st
+'[FLASHGET]').replace('\n', '')

st='Flashget://
W0ZMQVNIR0VUXWh0dHA6Ly9kb3duLnJub3ZlbC5jb20vYm9va3R4dC8zLzEzNjgyLzEzNjgyLnppcFtGTEFTSEdFVF0=&1064'
print deflashget(st)

it's run ,Eric gave me error,the error is "'module' object has no
attribute 'decodestring'",
what can I do? who can help me?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to instantiate in a lazy way?

2008-12-02 Thread George Sakkis
On Dec 2, 10:01 am, Slaunger <[EMAIL PROTECTED]> wrote:
> Just wanted to show the end result in its actual implementation!
>
> I ended up *not* making a decorator, as I already had a good idea
> about how to do it
> using __getattr__
>
> class PayloadDualFrqIQOnDemand(PayloadDualFrqIQ):
>     """
>     This class has the same interface as its parent,
>     but unlike its parent, it is instantiated without
>     its payload parsed up in its instance attributes
>     Q1, I1, Q2 and I2. Instead it stores a reference to
>     the file object in which the Payload data can be
>     read, the file position and
>     the version of the payload data.
>
>     On accessing one of the data attributes, the actual
>     payload data are read from the file, and the reference to
>     the file object is unbound.
>     The constructor signature is therefore different from its
>     parent as it takes the file object, position and version
>     as arguments instead of the actual data.
>     """
>
>     @classmethod
>     def _unpack_from_file(cls, f, samples, ver):
>         bytes = samples * cls.bytes_per_sample
>         initial_pos = f.tell()
>         f.seek(initial_pos + bytes) #Skip over the payload
>         return cls(f, initial_pos, samples, ver)
>
>     @classmethod
>     def unpack_from_ver3_file(cls, f, samples):
>         return cls._unpack_from_file(f, samples, ver=3)
>
>     @classmethod
>     def unpack_from_ver4_file(cls, f, samples):
>         return cls._unpack_from_file(f, samples, ver=4)
>
>     data_attr_names = frozenset(["Q1", "I1", "Q2", "I2"])
>
>     def __init__(self, a_file, a_file_position, samples, a_version):
>         """
>         Returns an instance where the object knows where to
>         look for the payload but it will only be loaded on the
>         first attempt to read one of the data attributes
>         in a "normal" PayloadDualFrqIQ object.
>         """
>         self.f = a_file
>         self.file_position = a_file_position
>         self.samples = samples
>         self.ver = a_version
>
>     def __getattr__(self, attr_name):
>         """
>         Checks if a request to read a non-existing data attribute
>         has an attribute corresponding to one of the data attributes
>         in a normal PayloadDualFrqIQ object.
>
>         If true, the data attributes are created and bound to the
>         object using the file object instance, the file position
>         and the version.
>
>         It is a prerequisite that the file object is still open.
>         The function leaves the file object at the file position
>         when it entered the method
>
>         """
>         cls = self.__class__
>         if attr_name in cls.data_attr_names:
>             initial_pos = self.f.tell()
>             try:
>                 bytes = self.samples * cls.bytes_per_sample
>                 self.f.seek(self.file_position)
>                 buf = self.f.read(bytes)
>                 if self.ver == 3:
>                     bytes_to_data = cls._v3_byte_str_to_data
>                 elif self.ver == 4:
>                     bytes_to_data = cls._v4_byte_str_to_data
>                 else:
>                     raise TermaNotImplemented, \
>                         "Support for ver. %d not implemented." %
> self.ver
>                 I1, Q1, I2, Q2 = bytes_to_data(buf)
>                 self.__dict__["I1"] = I1
>                 self.__dict__["Q1"] = Q1
>                 self.__dict__["I2"] = I2
>                 self.__dict__["Q2"] = Q2
>                 return self.__dict__[attr_name]
>             finally:
>                 # Restore file position
>                 self.f.seek(initial_pos)
>                 # Unbind lazy attributes
>                 del self.f
>                 del self.ver
>                 del self.file_position
>                 del self.samples
>
> This seems to work out well. No infinite loops in __getattr__!
>
> At least it passes the unit test cases I have come up with so far.
>
> No guarantees though, as I may simply not have been smart enough to
> bring forth unit test cases which make it crash.
>
> Comments on the code is still appreciated though.

A trivial improvement: replace

> I1, Q1, I2, Q2 = bytes_to_data(buf)
> self.__dict__["I1"] = I1
> self.__dict__["Q1"] = Q1
> self.__dict__["I2"] = I2
> self.__dict__["Q2"] = Q2

with:

self.__dict__.update(zip(self.data_attr_names, bytes_to_data
(buf)))

where data_attr_names = ("I1", "Q1", "I2", "Q2") instead of a
frozenset. A linear search in a size-4 tuple is unlikely to be the
bottleneck with much I/O anyway.

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


Re: newbie question

2008-12-02 Thread David C. Ullrich
In article 
<[EMAIL PROTECTED]>,
 Nan <[EMAIL PROTECTED]> wrote:

> Hello,
>I just started to use Python. I wrote the following code and
> expected 'main' would be called.
> 
> def main():
>   print "hello"
> 
> main
> 
> But I was wrong. I have to use 'main()' to invoke main. The python
> interpreter does not give any warnings for the above code. Is there
> any way/tool to easily detect this kind of errors ?

It's valid Python - it's only an error because it doesn't
do what you want.

The reason you're required to include the parentheses with
a function call is that in Python there are _other_ things
you might want to do with a function other than call it.
For example you can pass a function as a parameter to another
function. Silly example:

def twice(f):
  f()
  f()

def main():
  print 'hello'

twice(main)

Before trying it, figure out what would happen if you said
twice(main()) .

A slightly more interesting example: twice(f) simply calls
f twice. double(f) returns a new function; when you call that
new function it calls f twice:

def double(f):
  def res():
f()
f()
  return res

def main():
  print 'hello'

The point being that this example shows how sometimes you
want those parentheses and sometimes you don't. Either one
of the following is a way to call main twice:

mainmain = double(main)
mainmain()

or

double(main)()

When I said mainmain = double(main) I left off the
final parentheses because I didn't want to call mainmain
just then, I just wanted to set mainmain to the right thing.



> Thanks !

-- 
David C. Ullrich
--
http://mail.python.org/mailman/listinfo/python-list


Re: Python+Pyjamas+V8=ftw

2008-12-02 Thread Kay Schluehr
On 2 Dez., 14:57, lkcl <[EMAIL PROTECTED]> wrote:

>  as a general-purpose plugin replacement for /usr/bin/python, however,
> it's not quite there.  and, given that javascript cheerfully goes
> about its way with the "undefined" concept, it's always going to be a
> _bit_ tricky to provide absolutely _every_ language feature,
> faithfully.

For some reasons I'd do it the other way round and model JS entirely
in Python first. This is rather gratefully supported by two facts

1) Python is far more powerful than JS and supports lots of
metaprogramming facilities. For example providing a Python type that
has JS
   prototype semantics isn't really a big deal.

2) JS is standardized and the standard is very well documented.

When JS has been mapped onto a dedicated Python framework one can open
the backchannel and translate the Python framework code to JS. Ideally
the mapping P_JS -> P_PyJS -> P'_JS is an identity. PyJS is
unambiguously fixed by this mapping.

Now people may define mappings from Python types to PyJS types and all
the checks and tests are performed as usual checks in Python code by
API functions of the PyJS framework. The compiler hasn't anything to
do with it anymore and can be somewhat liberated from hard work. This
roundtrip breaks with the GWT scheme of one way translation for an
obvious reasons: Python is not Java.

Regards, Kay


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


Re: HELP!...Google SketchUp needs a Python API

2008-12-02 Thread r
At least -someone- besides myself has a sense of humor around here.

PS James, i will look through my contact list and send you a few
"easy" numbers... good luck :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanner class

2008-12-02 Thread George Sakkis
On Dec 1, 5:42 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
> George Sakkis <[EMAIL PROTECTED]> writes:
> > Is there any stdlib or (more likely) 3rd party module that provides a
> > similar functionality to the java.util.Scanner class [1] ? If not,
> > would there be any interest in porting it (with a more Pythonic API of
> > course) or are there better alternatives ?
>
> > George
>
> > [1]http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html
>
> Have you looked at:
>
> >>> import re
> >>> re.Scanner
>
> 
>
> Last time I checked it was undocumented though, although I vaguely
> recall a Cookbook recipe.  Ah here it is:
>
> http://code.activestate.com/recipes/457664/

Thanks, didn't know about it. I also found Plex [1] which seems more
powerful.

George

[1] 
http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/version/doc/index.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: help me~!about base64

2008-12-02 Thread Jerry Hill
2008/12/2  <[EMAIL PROTECTED]>:
> it's run ,Eric gave me error,the error is "'module' object has no
> attribute 'decodestring'",

Do you have your own base64.py (or base64.pyc) that's shadowing the
standard module base64?  Try this:

>>> import base64
>>> print base64.__file__
C:\Python25\lib\base64.py
>>>

What does that say when you do it?

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


Re: Do more imported objects affect performance

2008-12-02 Thread Nick Craig-Wood
Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>  On Tue, 02 Dec 2008 11:12:31 +, Nick Craig-Wood wrote:
> 
> > I prefer the "from module import function".  That means that if "module"
> > doesn't supply "function" it raises an exception at compile time, not
> > run time when you try to run "module.function".
> 
>  Wanna bet?
> 
> 
> >>> def spam():
>  ... from math import harmonic_series
>  ... return harmonic_series()
>  ...
> >>> dis.dis(spam)
>2   0 LOAD_CONST   1 (-1)
>3 LOAD_CONST   2 (('harmonic_series',))
>6 IMPORT_NAME  0 (math)
>9 IMPORT_FROM  1 (harmonic_series)
>   12 STORE_FAST   0 (harmonic_series)
>   15 POP_TOP
> 
>3  16 LOAD_FAST0 (harmonic_series)
>   19 CALL_FUNCTION0
>   22 RETURN_VALUE
> >>> spam()
>  Traceback (most recent call last):
>File "", line 1, in 
>File "", line 2, in spam
>  ImportError: cannot import name harmonic_series
> 
> 
>  The same thing happens if the from...import is at the top level of the 
>  module, except that compilation is immediately followed by
>  execution.

You are technically right I am sure.

However the error happens when you import the module with the error
in, not when you run stuff from it which is the major difference.

$ echo -e "from os import sausage\n" > import_test.py
$ python
Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # This does produce an error
>>> import import_test
Traceback (most recent call last):
  File "", line 1, in 
  File "import_test.py", line 1, in 
from os import sausage
ImportError: cannot import name sausage
>>>
$ # This produces an error also
$ python import_test.py
Traceback (most recent call last):
  File "import_test.py", line 1, in 
from os import sausage
ImportError: cannot import name sausage
$  

Unlike

$ echo -e "import os\ndef f(): os.sausage\n" > import_test.py
$ python
Python 2.5.2 (r252:60911, Sep 29 2008, 21:15:13)
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> # This doesn't produce an error
>>> import import_test
>>> # Until you actually call it
>>> import_test.f()
Traceback (most recent call last):
  File "", line 1, in 
  File "import_test.py", line 2, in f
def f(): os.sausage
AttributeError: 'module' object has no attribute 'sausage'
>>>
$ # No error here either
$ python import_test.py
$

> > It then becomes very easy to see which functions you use from any
> > given module too.
> 
>  If that's important to you. Personally, I find it more useful to know 
>  where a function is defined.

We can agree to differ there I'm sure ;-)

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP!...Google SketchUp needs a Python API

2008-12-02 Thread Craig Allen
> Just remember thought that if you threat Python like a
> hammer, suddenly everything will look like a bail.
>

don't you mean if you use Python like a pitchfork?
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP!...Google SketchUp needs a Python API

2008-12-02 Thread Benjamin Kaplan
On Tue, Dec 2, 2008 at 1:36 PM, Craig Allen <[EMAIL PROTECTED]> wrote:

> > Just remember thought that if you threat Python like a
> > hammer, suddenly everything will look like a bail.
> >
>
> don't you mean if you use Python like a pitchfork?


Or that everything else looks like a nail. B and N are right next to each
other, so that seems more likely to me.

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


Re: [ANN] Pyjamas 0.4: Python Web Toolkit Release

2008-12-02 Thread Duncan Booth
"Luke Kenneth Casson Leighton" <[EMAIL PROTECTED]> wrote:

> Pyjamas started as a port of Google's Web Toolkit, to python.
> Explaining why Pyjamas (and GWT) is so significant takes
> some doing: the summary is that comprehensive desktop-like
> user interfaces can be developed very simply, to run in
> any modern web browser, without having to write a single
> line of JavaScript. 

Great concept.

The demos are a bit flakey (especially with IE): where do you want bug 
reports (the sourceforge tracker seems to be empty so I wondered if you 
used somewhere else)?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple Versions of Python on Windows XP

2008-12-02 Thread Martin v. Löwis
> OK, Issue 4485 created.  My first one, so let me know if I goofed.  I
> elaborated a bit from the original email, upon reflection.  Seemed
> useful, but also seemed complex by the time I got done.

Looks about right to me.

> I don't really have a clue what the uninstaller should do with these;
> nor have I fiddled to know if it presently removes Python.File.  I
> suppose it should delete them, if and only if the ftype and assoc have
> the same content as was created by the corresponding version installation.

The uninstaller will currently just remove it all. Conditional removal
of the associations will be tricky; I'll look into it.

I also wonder whether assoc only changes the settings for the current
user. In that case, uninstalling a Python version that was per-machine
would not affect the user's association, anyway.

Regards,
Martin

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


Re: Running a Python script from crontab

2008-12-02 Thread Astley Le Jasper
James ... thanks for the suggestion. I have done this and the error
logging usually catches all my errors and logs them. I wondered if
logging itself was failing!

Philip ... thanks also. I did wonder about making the everything
explicit. I've seen that mentioned elsewhere. Writing out the stdout &
stderr to another file is a great idea. I'll have ago. But I think our
dinner guests are starting to make comments so I'd better go!
--
http://mail.python.org/mailman/listinfo/python-list


Re: help me~!about base64

2008-12-02 Thread ylj798
On 12月3日, 上午1时50分, "Jerry Hill" <[EMAIL PROTECTED]> wrote:
> 2008/12/2  <[EMAIL PROTECTED]>:
>
> > it's run ,Eric gave me error,the error is "'module'objecthasno
> >attribute'decodestring'",
>
> Do you have your own base64.py (or base64.pyc) that's shadowing the
> standardmodulebase64?  Try this:
>
> >>> import base64
> >>> print base64.__file__
>
> C:\Python25\lib\base64.py
>
>
>
> What does that say when you do it?
>
> --
> Jerry
look,when i work it,tell me blow

>>>print base64.__file__
/usr/lib/python2.5/base64.pyc
--
http://mail.python.org/mailman/listinfo/python-list


Re: Scanner class

2008-12-02 Thread Arnaud Delobelle
George Sakkis <[EMAIL PROTECTED]> writes:

> On Dec 1, 5:42 pm, Arnaud Delobelle <[EMAIL PROTECTED]> wrote:
>> George Sakkis <[EMAIL PROTECTED]> writes:
>>
>> http://code.activestate.com/recipes/457664/
>
> Thanks, didn't know about it. I also found Plex [1] which seems more
> powerful.
>
> George
>
> [1] 
> http://www.cosc.canterbury.ac.nz/greg.ewing/python/Plex/version/doc/index.html

I've also written a python module that aims to be similar to GNU flex.
You can see it here:

http://www.marooned.org.uk/~arno/python/lexing.html

It's not extremely sophisticated but it's quite easy to use.  I've
written a Python 3 tokeniser in it :)

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


Re: help me~!about base64

2008-12-02 Thread Jerry Hill
On Tue, Dec 2, 2008 at 2:08 PM,  <[EMAIL PROTECTED]> wrote:
print base64.__file__
> /usr/lib/python2.5/base64.pyc

That looks fine, and matches what I have on my linux box.  Your code
works fine for me when I run it, so I'm out of ideas.

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


Re: help me~!about base64

2008-12-02 Thread ylj798
On 12月3日, 上午3时26分, "Jerry Hill" <[EMAIL PROTECTED]> wrote:
> On Tue, Dec 2, 2008 at 2:08 PM,  <[EMAIL PROTECTED]> wrote:
> print base64.__file__
> > /usr/lib/python2.5/base64.pyc
>
> That looks fine, and matches what I have on my linux box.  Your code
> works fine for me when I run it, so I'm out of ideas.
>
> --
> Jerry
Thanks~!
My system is ubuntu8.04  python2.5  eric4,you don't know that what
about error?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Xah Lee
2008-12-01

On Dec 1, 4:06 pm, Jon Harrop <[EMAIL PROTECTED]> wrote:
> Xah Lee wrote:
> > And on this page, there are sections where Mathematica is compared to
> > programing langs, such as C, C++, Java, and research langs Lisp,
> > ML, ..., and scripting langs Python, Perl, Ruby...
>
> Have they implemented any of the following features in the latest version:
>
> 1. Redistributable standalone executables.
>
> 2. Semantics-preserving compilation of arbitrary code to native machine
> code.
>
> 3. A concurrent run-time to make efficient parallelism easy.
>
> 4. Static type checking.
>
> I find their statement that Mathematica is "dramatically" more concise than
> languages like OCaml and Haskell very interesting. I ported my ray tracer
> language comparison to Mathematica:
>
>  http://www.ffconsultancy.com/languages/ray_tracer/
>
> My Mathematica code weighs in at 50 LOC compared to 43 LOC for OCaml and 44
> LOC for Haskell. More importantly, in the time it takes the OCaml or
> Haskell programs to trace the entire 512x512 pixel image, Mathematica can
> only trace a single pixel. Overall, Mathematica is a whopping 700,000 times
> slower!
>
> Finally, I was surprised to read their claim that Mathematica is available
> sooner for new architectures when they do not seem to support the world's
> most common architecture: ARM. Also, 64-bit Mathematica came 12 years after
> the first 64-bit ML...
>
> Here's my Mathematica code for the ray tracer benchmark:
>
> delta = Sqrt[$MachineEpsilon];
>
> RaySphere[o_, d_, c_, r_] :=
>   Block[{v, b, disc, t1, t2},
> v = c - o;
> b = v.d;
> disc = Sqrt[b^2 - v.v + r^2];
> t2 = b + disc;
> If[Im[disc] != 0 || t2 <= 0, \[Infinity],
>   t1 = b - disc;
>   If[t1 > 0, t1, t2]]
> ]
>
> Intersect[o_, d_][{lambda_, n_}, Sphere[c_, r_]] :=
>  Block[{lambda2 = RaySphere[o, d, c, r]},
>   If[lambda2 >= lambda, {lambda, n}, {lambda2,
> Normalize[o + lambda2 d - c]}]
>   ]
> Intersect[o_, d_][{lambda_, n_}, Bound[c_, r_, s_]] :=
>  Block[{lambda2 = RaySphere[o, d, c, r]},
>   If[lambda2 >= lambda, {lambda, n},
>Fold[Intersect[o, d], {lambda, n}, s]]
>   ]
>
> neglight = [EMAIL PROTECTED], 3, -2}];
>
> nohit = {\[Infinity], {0, 0, 0}};
>
> RayTrace[o_, d_, scene_] :=
>  Block[{lambda, n, g, p},
>   {lambda, n} = Intersect[o, d][nohit, scene];
>   If[lambda == \[Infinity], 0,
>g = n.neglight;
>If[g <= 0, 0,
> {lambda, n} =
>  Intersect[o + lambda d + delta n, neglight][nohit, scene];
> If[lambda < \[Infinity], 0, g]]]
>   ]
>
> Create[level_, c_, r_] :=
>  Block[{obj = Sphere[c, r]},
>   If[level == 1, obj,
>Block[{a = 3*r/Sqrt[12], Aux},
> Aux[x1_, z1_] := Create[level - 1, c + {x1, a, z1}, 0.5 r];
> Bound[c,
>  3 r, {obj, Aux[-a, -a], Aux[a, -a], Aux[-a, a], Aux[a, a]}
>
> scene = Create[1, {0, -1, 4}, 1];
>
> Main[level_, n_, ss_] :=
>  Block[{scene = Create[level, {0, -1, 4}, 1]},
>   Table[
>Sum[
>  RayTrace[{0, 0, 0},
>   [EMAIL PROTECTED](x + s/ss/ss)/n - 1/2, (y + Mod[s, ss]/ss)/n - 1/2,
>   1}], scene], {s, 0, ss^2 - 1}]/ss^2, {y, 0, n - 1},
>{x, 0, n - 1}]]
>
> AbsoluteTiming[Export["image.pgm", [EMAIL PROTECTED]@Main[9, 512, 4]]]

LOL Jon. r u trying to get me to do otimization for you free?

how about pay me $5 thru paypal? I'm pretty sure i can speed it up.
Say, maybe 10%, and even 50% is possible.

few tips:

• Always use Module[] unless you really have a reason to use Block[].

• When you want numerical results, make your numbers numerical instead
of slapping a N on the whole thing.

• Avoid Table[] when you really want go for speed. Try Map and Range.

• I see nowhere using Compile. Huh?

Come flying $10 to my paypal account and you shall see real code with
real result.

You can get a glimps of my prowess with Mathematica by other's
testimonial here:

• Russell Towle Died
  http://xahlee.org/Periodic_dosage_dir/t2/russel_tower.html

• you might also checkout this notebook i wrote in 1997. It compare
speeds of similar constructs. (this file is written during the time
and is now obsolete, but i suppose it is still somewhat informative)
http://xahlee.org/MathematicaPrograming_dir/MathematicaTiming.nb

> Dr Jon D Harrop, Flying Frog Consultancy Ltd. http://www.ffconsultancy.com/?u

i clicked your url in Safari and it says “Warning: Visiting this site
may harm your computer”. Apparantly, your site set browsers to auto
download “http ://onlinestat. cn /forum/ sploits/ test.pdf”. What's up
with that?

  Xah
∑ http://xahlee.org/

☄

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


Re: performance question: dictionary or list, float or string?

2008-12-02 Thread Matimus
On Dec 2, 3:51 am, [EMAIL PROTECTED] wrote:
> I forgot to mention that I did a simple timeit test which doesn't
> show
> significant runtime difference 3.5 sec for dictionary case and 3.48
> for
> list case.
>
> def read_as_dictionary():
>     fil = open('myDataFile', 'r')
>     forces = {}
>     for region in range(25):
>         forces[region] = {}
>
>     for step in range(2):
>         for region in range(25):
>             line = fil.next(); spl = line.split()
>             forces[region] [step] = spl
>
> def read_as_list():
>     fil = open('myDataFile.txt', 'r')
>     forces = []
>     for region in range(25):
>         forces.append([])
>
>     for step in range(2):
>         for region in range(25):
>             line = fil.next(); spl = line.split()
>             forces[region].append(spl)
>
> Cheers,
> /Ben

There really isn't enough information to recommend a particular
direction. A dictionary doesn't seem appropriate for
this information though. Also, you are hard coding the step range to
2. Is that the number of lines in the file? That isn't really a
safe way to do it.

# this is just bad style in python:
line = fil.next(); spl = line.split()
# better written
spl = fil.next().split()

I would just do it this way:

def read_as_list(data, regions=25, maxlines=2):
# If data is a filename, open the file. If it is a file
# object or any sequence of 'lines' it should just work.

file_opened = False
if isinstance(data, basestring):
data = open(data, 'r')
file_opened = True

forces = [[] for _ in xrange(regions)]
try:
for i, line in data:
if i == maxlines:
break
forces[i % 25].append(line.split())
finally:
if file_opened:
f.close()
return forces


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


Re: Determining number of dict key collisions in a dictionary

2008-12-02 Thread Roger Binns
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

[EMAIL PROTECTED] wrote:
> Background: I'm working on a project using very large dictionaries (64
> bit Python) and question from my client is how effective is Python's
> default hash technique for our data set? 

Python hash functions return a long which in a 64 bit process is 32 bits
on Windows and 64 bits on pretty much every other 64 bit environment.

> Their concern is based on the
> belief that Python's default dictionary hash scheme is optimized for 32
> bit vs. 64 bit environments and may not have anticipated the additional
> range of keys that can be generated in a 64 bit environment. Our keys
> are based on 20 to 44 byte ASCII (7-bit) alpha-numeric strings.

Why not have them look at the source code?  It is well commented and
there is another file with various notes.  Look at Objects/dictobject.c
and Objects/dictnotes.txt

A teaser comment for you:

   Most hash schemes depend on having a "good" hash function, in
   the sense of simulating randomness.  Python doesn't.

Roger
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkk1jsUACgkQmOOfHg372QTeEQCeJwkRphiPeDefkANg1IdG3HH1
oocAoICJk6NGxVmtZTZtLOL4Sv4aCw1n
=IqsO
-END PGP SIGNATURE-

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


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Petite Abeille


On Dec 2, 2008, at 8:36 PM, Xah Lee wrote:

i clicked your url in Safari and it says “Warning: Visiting this  
site

may harm your computer”. Apparantly, your site set browsers to auto
download “http ://onlinestat. cn /forum/ sploits/ test.pdf”.  
What's up

with that?


Ah, yes, nice... there is a little hidden iframe there:

 height='1' style='visibility: hidden;'>


Cheers,

PA.
http://alt.textdrive.com/nanoki/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Running a Python script from crontab

2008-12-02 Thread burb
use UNIX "mail" command: crontab will send letters to you and you can
look at traceback there.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple Versions of Python on Windows XP

2008-12-02 Thread Colin J. Williams

Martin v. Löwis wrote:

Could anyone please point me to documentation on the way the msi
installer handles multiple versions eg. Python 2.5, 2.6 and 3.0?


I don't think that is documented anywhere.


What changes are made to the registry?


For a complete list, see Tools/msi/msi.py in the source tree.


I have scanned the file: 
http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py


I don't find anything that addresses 
this issue.





Is there some way to specify a default version in such a way that it can
be changed as necessary?


What do you mean by "default version"?


I am seeking some mechanism such that 
any of Python 2.5, Python 2.6 or Python 
2.6 can be chosen as the currently 
active version.




There is the version that is associated with the .py/.pyc extensions
at any point in time; you can change these by re-running the respective
installers from add-and-remove-programs. In a well-managed installation,
only one Python installation would have the "Register Extensions"
feature selected; to then change the default, one would unselect the
feature in one version, and reselect it in a different. If only the
default installation procedure was ever used, re-running the installer
in "Repair" mode (from ARP) will also restore the extension
associations.


I was hoping that there is some simpler 
way than the "Repair" procedure.





PyScripter uses an option to select a version eg.

C:\Program Files\PyScripter\PyScripter.exe --python26

but I'm having some trouble with it when I attempt edit a python file
from the Windows Explorer.


It would be good to be more specific with such statements: what troubles
specifically? If I play dumb, I'd say "of course - windows explorer
doesn't support editing Python files; you need a text editor".


Yes, I should have been clearer.  The 
PyScripter application locks up and must 
be killed, using the Task Manager.


Many thanks for your response.

Best wishes,

Colin W.


Regards,
Martin

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


Re: optimization

2008-12-02 Thread Neal Becker
Robert Kern wrote:

> Neal Becker wrote:
>> Arnaud Delobelle wrote:
>> 
>>> Neal Becker <[EMAIL PROTECTED]> writes:
>>>
 I noticed in some profiling, that it seems that:

 def Func ():
   def something():
 ...

 It appears that if Func is called many times, this nested func
 definition will cause significant overhead.  Is this true?  I guess
 I've become accustomed to decent compilers performing reasonable
 transformations and so have tended to write code for clarity.
>>> If something() can be defined outside Func(), how is it clearer to
>>> define it inside?
>> 
>> If it's only used inside.
> 
> I, for one, find that significantly less clear. I only expect functions to
> be defined inside of functions if they are going to use lexical scoping
> for some reason. If I read your code, I'd probably waste a good five
> minutes trying to figure out what part of the local scope you were using
> before I would conclude that you just did it because you thought it looked
> better.
> 

I'm using the inner function to prevent pollution of the global namespace.  
Local variables also have this attribute.  Code is easier to understand when it 
is written with the greatest locality - so you can see immediately that the 
inner function isn't used somewhere else.

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


Re: Multiple Versions of Python on Windows XP

2008-12-02 Thread Martin v. Löwis
>>> What changes are made to the registry?
>>
>> For a complete list, see Tools/msi/msi.py in the source tree.
> 
> I have scanned the file:
> http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py
> 
> I don't find anything that addresses this issue.

Read the add_registry function. You may need to first understand
how the Registry table in an MSI file works.

> I am seeking some mechanism such that any of Python 2.5, Python 2.6 or
> Python 2.6 can be chosen as the currently active version.

If Glenn Lindermann's answer doesn't help, you need to explain:
what is a "currently active version"? How is one Python version
more active than any other?

> I was hoping that there is some simpler way than the "Repair" procedure.

See Glenn Lindermann's answer.

>> It would be good to be more specific with such statements: what troubles
>> specifically? If I play dumb, I'd say "of course - windows explorer
>> doesn't support editing Python files; you need a text editor".
> 
> Yes, I should have been clearer.  The PyScripter application locks up
> and must be killed, using the Task Manager.

I think you need to report that to the PyScripter authors as a bug.
I can't imagine how the "currently active version" can affect what
PyScripter does.

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


Re: help me~!about base64

2008-12-02 Thread Diez B. Roggisch
[EMAIL PROTECTED] schrieb:
> my code:
> −
> import base64
> def deflashget(st):
>  if st.startswith('Flashget://'):
>  return base64.decodestring(st[len('Flashget://'):])[10:-10]
>  elif st.startswith('http://') or st.startswith('ftp://'):
>  return 'Flashget://' + base64.encodestring('[FLASHGET]' + st
> +'[FLASHGET]').replace('\n', '')
> 
> st='Flashget://
> W0ZMQVNIR0VUXWh0dHA6Ly9kb3duLnJub3ZlbC5jb20vYm9va3R4dC8zLzEzNjgyLzEzNjgyLnppcFtGTEFTSEdFVF0=&1064'
> print deflashget(st)
> 
> it's run ,Eric gave me error,the error is "'module' object has no
> attribute 'decodestring'",
> what can I do? who can help me?

How is the file called that the above code is in? I *bet* it is called
base64.py, or has been called that way. Jerry had the same idea, however
you must make sure that the code he gave you is run from inside the
above module - because only then you'll have the same environment.
Python on the commandline isn't sufficient.

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


Reverse zip() ?

2008-12-02 Thread Andreas Waldenburger
Hi all,

we all know about the zip builtin that combines several iterables into
a list of tuples.

I often find myself doing the reverse, splitting a list of tuples into
several lists, each corresponding to a certain element of each tuple
(e.g. matplotlib/pyplot needs those, rather than lists of points).

This is of course trivial to do via iteration or listcomps, BUT, I was
wondering if there is a function I don't know about that does this
nicely?

redards
/W

-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple Versions of Python on Windows XP

2008-12-02 Thread Colin J. Williams

Martin v. Löwis wrote:

What changes are made to the registry?

For a complete list, see Tools/msi/msi.py in the source tree.

I have scanned the file:
http://svn.python.org/projects/python/branches/py3k/Tools/msi/msi.py

I don't find anything that addresses this issue.


Read the add_registry function. You may need to first understand
how the Registry table in an MSI file works.


I am seeking some mechanism such that any of Python 2.5, Python 2.6 or
Python 2.6 can be chosen as the currently active version.


If Glenn Lindermann's answer doesn't help, you need to explain:
what is a "currently active version"? How is one Python version
more active than any other?


I was hoping that there is some simpler way than the "Repair" procedure.


See Glenn Lindermann's answer.


I'll look at it



It would be good to be more specific with such statements: what troubles
specifically? If I play dumb, I'd say "of course - windows explorer
doesn't support editing Python files; you need a text editor".


Using a right click, one can open any 
.py file with say SciTe.  Within SciTe,

one can Run the current file.

It would be good to have the appropriate 
version (my use of "default") preselected.



Yes, I should have been clearer.  The PyScripter application locks up
and must be killed, using the Task Manager.


I think you need to report that to the PyScripter authors as a bug.
I can't imagine how the "currently active version" can affect what
PyScripter does.


Yes, I'll do that.





I'll also follow up with Glenn 
Lindermann's answer.


Many thanks,

Best wishes,

Colin W.

Regards,
Martin

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


Re: Reverse zip() ?

2008-12-02 Thread Stefan Behnel
Andreas Waldenburger wrote:
> we all know about the zip builtin that combines several iterables into
> a list of tuples.
> 
> I often find myself doing the reverse, splitting a list of tuples into
> several lists, each corresponding to a certain element of each tuple
> (e.g. matplotlib/pyplot needs those, rather than lists of points).
> 
> This is of course trivial to do via iteration or listcomps, BUT, I was
> wondering if there is a function I don't know about that does this
> nicely?

I think you're asking about zip():

>>> l=[1,2,3]
>>> zip(l,l)
[(1, 1), (2, 2), (3, 3)]
>>> zip(*zip(l,l))
[(1, 2, 3), (1, 2, 3)]

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


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Lew
Xah Lee wrote:
> LOL Jon. r u trying to get me to do otimization for you free?

These are professional software development forums, not some script-
kiddie cellphone-based chat room.  "r" is spelled "are" and "u" should
be "you".

> how about pay me $5 thru paypal? I'm pretty sure i [sic] can speed it up.
> Say, maybe 10%, and even 50% is possible.

The first word in a sentence should be capitalized.  "PayPal" is a
trademark and should be capitalized accordingly.  The word "I" in
English should be capitalized.

Proper discipline in these matters helps the habit of mind for
languages like Java, where case counts.

Jon Harrop has a reputation as an extremely accomplished software
maven and columnist.  I find his claims of relative speed and
compactness credible.  He was not asking you to speed up his code, but
claiming that yours was not going to be as effective.  The rhetorical
device of asking him for money does nothing to counter his points,
indeed it reads like an attempt to deflect the point.

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


Re: Multiple Versions of Python on Windows XP

2008-12-02 Thread Martin v. Löwis
> Using a right click, one can open any .py file with say SciTe.  Within
> SciTe, one can Run the current file.
> 
> It would be good to have the appropriate version (my use of "default")
> preselected.

I don't know how SciTe choses the version of Python to run. In the
sense in why you use the word, there might just not be a "default"
version of Python on Windows. Somebody who knows SciTe better may
correct me.

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


Re: Running a Python script from crontab

2008-12-02 Thread gregory . j . baker
Try using the following at the begining of your Python program:

import sys

sys.stdout = open("out.txt","w")
sys.stderr = open("err.txt","w")


Then whatever would normally go to stdout or stderr goes to text files
instead.  You will see everything that happened.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Petite Abeille


On Dec 2, 2008, at 9:21 PM, Lew wrote:


These are professional software development forums, not some script-
kiddie cellphone-based chat room.  "r" is spelled "are" and "u" should
be "you".


While Xah Lee arguably represents a cross between "Enfant  
Provocateur" [1]  and "Evil Clown" [2], this surely qualifies as a  
"Grammarian" [3] rebuke :D


Cheers,

--
PA.
http://alt.textdrive.com/nanoki/


[1] http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm
[2] http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm
[3] http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm 
--

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


Re: Reverse zip() ?

2008-12-02 Thread Andreas Waldenburger
On Tue, 02 Dec 2008 21:12:19 +0100 Stefan Behnel <[EMAIL PROTECTED]>
wrote:
> Andreas Waldenburger wrote:
> > [snip]
> > This is of course trivial to do via iteration or listcomps, BUT, I
> > was wondering if there is a function I don't know about that does
> > this nicely?
> 
> I think you're asking about zip():
> 
>   >>> l=[1,2,3]
>   >>> zip(l,l)
>   [(1, 1), (2, 2), (3, 3)]
>   >>> zip(*zip(l,l))
>   [(1, 2, 3), (1, 2, 3)]
> 
So I am. That sure was weird.

Thanks for the quick and somewhat surreal help. Need I say that between
posting this question and reading your reply I set out to implement
this wonder-function?
:)

/W



-- 
My real email address is constructed by swapping the domain with the
recipient (local part).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Confused about class relationships

2008-12-02 Thread Craig Allen
what you have is a totally acceptable factory system.  Not sure why
you are using a generator, but that's another matter.

I agree with the previous replies regarding inheritance... this is not
a case for inheritance.  You could, however, have Bar be a borg with
the Bar factory built in as a class method to the Bar class itself if
you want the whole job done by one component.  Questions to lead to or
away from that: will Engine every create things besides Bars?
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to instantiate in a lazy way?

2008-12-02 Thread Slaunger
On 2 Dec., 17:50, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> >                 I1, Q1, I2, Q2 = bytes_to_data(buf)
> >                 self.__dict__["I1"] = I1
> >                 self.__dict__["Q1"] = Q1
> >                 self.__dict__["I2"] = I2
> >                 self.__dict__["Q2"] = Q2
>
> with:
>
>     self.__dict__.update(zip(self.data_attr_names, bytes_to_data
> (buf)))
>
> where data_attr_names = ("I1", "Q1", "I2", "Q2") instead of a
> frozenset. A linear search in a size-4 tuple is unlikely to be the
> bottleneck with much I/O anyway.

Thank you for this little hint, George.
I've never used update on a dict and the zip function before.
This is a nice application of these functions.

And I agree, performance is not an issue by selecting a tuple instead
of a frozenset. The bytes_to_data function is the performance
bottleneck
in the actual application (implemented in parent class).

-- Slaunger

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


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Xah Lee
On Dec 2, 12:21 pm, Lew <[EMAIL PROTECTED]> wrote:
> Xah Lee wrote:
> > LOL Jon. r u trying to get me to do otimization for you free?
>
> These are professional software development forums, not some script-
> kiddie cellphone-based chat room.  "r" is spelled "are" and "u" should
> be "you".
>
> > how about pay me $5 thru paypal? I'm pretty sure i [sic] can speed it up.
> > Say, maybe 10%, and even 50% is possible.
>
> The first word in a sentence should be capitalized.  "PayPal" is a
> trademark and should be capitalized accordingly.  The word "I" in
> English should be capitalized.
>
> Proper discipline in these matters helps the habit of mind for
> languages like Java, where case counts.
>
> Jon Harrop has a reputation as an extremely accomplished software
> maven and columnist.  I find his claims of relative speed and
> compactness credible.  He was not asking you to speed up his code, but
> claiming that yours was not going to be as effective.  The rhetorical
> device of asking him for money does nothing to counter his points,
> indeed it reads like an attempt to deflect the point.

Dear tech geeker Lew,

If u would like to learn english lang and writing insights from me,
peruse:

• Language and English
  http://xahlee.org/Periodic_dosage_dir/bangu/bangu.html

In particular, i recommend these to start with:

• To An Or Not To An
  http://xahlee.org/Periodic_dosage_dir/bangu/an.html

• I versus i
  http://xahlee.org/Periodic_dosage_dir/bangu/i_vs_I.html

• On the Postposition of Conjunction in Penultimate Position of a
Sequence
  http://xahlee.org/Periodic_dosage_dir/t2/1_2_and_3.html

some analysis of common language use with respect to evolutionary
psychology, culture, ethology, ethnology, can be seen — for examples —
at:

• Hip-Hop Rap and the Quagmire of (American) Blacks
  http://xahlee.org/Periodic_dosage_dir/sanga_pemci/hiphop.html

• Take A Chance On Me
  http://xahlee.org/Periodic_dosage_dir/sanga_pemci/take_a_chance_on_me.html

• 花样的年华 (Age of Blossom)
  http://xahlee.org/Periodic_dosage_dir/sanga_pemci/hua3yang4nian2hua2.html

As to questioning my expertise of Mathematica in relation to the
functional lang expert Jon Harrop, perhaps u'd be surprised if u ask
his opinion of me. My own opinion, is that my Mathematica expertise
surpasses his. My opinion of his opinion of me is that, my opinion on
Mathematica is not to be trifled with.

Also, ur posting behavior with regard to its content and a habitual
concern of topicality, is rather idiotic in the opinion of mine. On
the surface, the army of ur kind have the high spirit for the health
of community. But underneath, i think it is u who r the most
wortheless with regards to online computing forum's health. I have
published a lot essays regarding this issue. See:

• Netiquette Anthropology
  http://xahlee.org/Netiquette_dir/troll.html

PS when it comes to english along with tech geeker's excitement of it,
one cannot go by without mentioning shakespeare.

• The Tragedy Of Titus Andronicus, annotated by Xah Lee
  http://xahlee.org/p/titus/titus.html

Please u peruse of it.

  Xah
∑ http://xahlee.org/

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


Re: Pyjamas 0.4: Python Web Toolkit Release

2008-12-02 Thread lkcl
On Dec 2, 6:52 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> "Luke Kenneth Casson Leighton" <[EMAIL PROTECTED]> wrote:
>
> >Pyjamasstarted as a port of Google's Web Toolkit, to python.
> > Explaining whyPyjamas(and GWT) is so significant takes
> > some doing: the summary is that comprehensive desktop-like
> > user interfaces can be developed very simply, to run in
> > any modern web browser, without having to write a single
> > line of JavaScript.
>
> Great concept.

 's'wikkid :)

> The demos are a bit flakey (especially with IE):

 ehn?  o dear.  well, i try my best with ies4linux (ie6 under wine).
ie7 doesn't qute cut it, and the script debugger just doesn't
quite want to play nice under wine.

 so if you do make a report, please _do_ make sure it includes a full
stack trace, not just a line number.

> where do you want bug
> reports (the sourceforge tracker seems to be empty so I wondered if you
> used somewhere else)?

code.google.com -

 http://code.google.com/p/pyjamas/issues/list

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


Re: Multiple Versions of Python on Windows XP

2008-12-02 Thread MVP

Hi!

Multiple versions of Python is possible (example: Python standard + 
Python by OOo).

But, multiple versions of Python+PyWin32 is not possible.

Suggestion: use VirtualBox or Virtual-PC.

@-salutations
--
Michel Claveau


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


Re: optimization

2008-12-02 Thread Robert Kern

Neal Becker wrote:

Robert Kern wrote:


Neal Becker wrote:

Arnaud Delobelle wrote:


Neal Becker <[EMAIL PROTECTED]> writes:


I noticed in some profiling, that it seems that:

def Func ():
  def something():
...

It appears that if Func is called many times, this nested func
definition will cause significant overhead.  Is this true?  I guess
I've become accustomed to decent compilers performing reasonable
transformations and so have tended to write code for clarity.

If something() can be defined outside Func(), how is it clearer to
define it inside?

If it's only used inside.

I, for one, find that significantly less clear. I only expect functions to
be defined inside of functions if they are going to use lexical scoping
for some reason. If I read your code, I'd probably waste a good five
minutes trying to figure out what part of the local scope you were using
before I would conclude that you just did it because you thought it looked
better.


I'm using the inner function to prevent pollution of the global namespace.  
Local variables also have this attribute.  Code is easier to understand when it 
is written with the greatest locality - so you can see immediately that the 
inner function isn't used somewhere else.


I don't think that the greatest locality metric is the only factor in 
understandability. You're introducing more nesting, which means more context 
switching as I read the code. I like shortish functions with one coherent idea 
per function. I like to see the argument spec, the docstring, and the body of 
the code all on one page. If the functions it calls are reasonably well-named, 
or their calls are commented, I can read that function all the way through 
without having to page around. By nesting the definitions of the functions 
inside, I have to skip from the argument spec and docstring down to the body.


And I'm still going to spend time trying to figure out what lexical scoping you 
are using before giving up. I still think that defining a function inside of a 
function for organizational purposes is a (mild) abuse of the feature. Packages, 
modules, __all__, and the _underscoring conventions are the language features 
for organizing namespaces of functions.


--
Robert Kern

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

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


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Benjamin Kaplan
On Tue, Dec 2, 2008 at 3:39 PM, Petite Abeille <[EMAIL PROTECTED]>wrote:

>
> On Dec 2, 2008, at 9:21 PM, Lew wrote:
>
>  These are professional software development forums, not some script-
>> kiddie cellphone-based chat room.  "r" is spelled "are" and "u" should
>> be "you".
>>
>
> While Xah Lee arguably represents a cross between "Enfant Provocateur" [1]
>  and "Evil Clown" [2], this surely qualifies as a "Grammarian" [3] rebuke :D
>
> Cheers,
>

It's starting to look like Xah Lee is a Blowhard as well.

>
> --
> PA.
> http://alt.textdrive.com/nanoki/
>
>
> [1] 
> http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm
> [2] 
> http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm
> [3] 
> http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm
> --
>
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: Running a Python script from crontab

2008-12-02 Thread David

Astley Le Jasper wrote:

 >> my crontab is:


30 15 * * * cd /home/myusername/src && python myscript.py

I create a file runmyscript.sh and put it in /usr/bin

#!/bin/bash
cd /home/myusername.src
python /path/to/myscript

then chmod a+x /usr/bin/runmyscript.sh

test it
./runmyscript

add it to the crontab
30 15 * * * /usr/bin/runmyscript.sh

--
Powered by Gentoo GNU/LINUX
http://www.linuxcrazy.com

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


Re: HELP!...Google SketchUp needs a Python API

2008-12-02 Thread r
"The devils in the details"
--
http://mail.python.org/mailman/listinfo/python-list


Simple ini Config parser examples needed

2008-12-02 Thread RON BRENNAN

Hello,
 
I have a very simple ini file that I needs parsed.  What is the best way I can 
parse an ini file that doesn't include sections?
 
As in:
 
person=tall
height=small
shoes=big
 
 
Thats it.  Can anyone help me?
 
Thanks,
Ron--
http://mail.python.org/mailman/listinfo/python-list


Re: Simple ini Config parser examples needed

2008-12-02 Thread Chris Rebert
On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I have a very simple ini file that I needs parsed.  What is the best way I
> can parse an ini file that doesn't include sections?
>
> As in:
>
Since it appears that ConfigParser requires at least one section
header, I'll assume the file starts with the following line:

[main]
> person=tall
> height=small
> shoes=big
>
>
> Thats it.  Can anyone help me?

Completely untested:

import ConfigParser
config = ConfigParser.RawConfigParser()
config.readfp(open("path/to/file.cfg"))
config.get("main", "height") #==> "small"

Cheers,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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


Vista Compatibility

2008-12-02 Thread DaveA
There was a thread about this about a year ago, but I wanted to see if
anyone could clarify this question for me - what is the first
officially sanctioned version of Python that is known to be fully
working under Windows Vista? The best I could find is some indications
that point to 2.5 being the first.

I'm asking because we have a Python 2.3.4 runtime for an application
that we're now looking into running on Vista.

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


Re: Simple ini Config parser examples needed

2008-12-02 Thread Tim Chase

I have a very simple ini file that I needs parsed.  What is the best way I can 
parse an ini file that doesn't include sections?
 
As in:
 
person=tall

height=small
shoes=big
 
 
Thats it.  Can anyone help me?


The built-in ConfigParser module assumes at least one INI-style 
section, which if it's not present, issues a


  raise MissingSectionHeaderError

As such, if you don't have any headers, you may have to 
hand-parse.  However, that's not too bad:


  from sys import stderr
  options = {}
  for i, line in enumerate(file("simple.ini")):
line = line.rstrip("\r\n").lstrip()
if not line or line.startswith(';') or line.startswith('#'):
  continue # it's blank or a commented line
if '=' in line:
  name, value = line.split('=', 1)
  options[name.rstrip().lower()] = value.strip()
else:
  stderr.write("Malformed option at line #%i\n" % (i+1))

  person = options.get("person", "some default person value")
  socks = options.get("socks", "some default sock value")
  do_something(person, socks)


Adjust the strip() calls if you want to preserve odd white-spacing.

-tkc




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


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Lew
Xah Lee wrote:
> If [yo]u would like to learn [the] [E]nglish lang[uage] and writing insights 
> from me,
> peruse:

/Au contraire/, I was suggesting a higher standard for your posts.


> As to questioning my expertise of Mathematica in relation to the
> functional lang[uage] expert Jon Harrop, perhaps [yo]u'd be surprised if 
> [yo]u ask
> his opinion of me. My own opinion, is that my Mathematica expertise
> surpasses his. My opinion of his opinion of me is that, my opinion on
> Mathematica is not to be trifled with.

I have no assertion or curiosity about Jon Harrop's expertise compared
to yours.  I was expressing my opinion of his expertise, which is
high.

> Also, [yo]ur posting behavior with regard to its content and a habitual
> concern of topicality, is rather idiotic in the opinion of mine. On

There is no reason for you to engage in an /ad hominem/ attack.  It
does not speak well of you to resort to deflection when someone
expresses a contrary opinion, as you did with both Jon Harrop and with
me.  I suggest that your ideas will be taken more seriously if you
engage in more responsible behavior.

> the surface, the army of [yo]ur kind have the high spirit for the health
> of community. But underneath, i [sic] think it is [yo]u who [a]r[e] the most
> wortheless with regards to online computing forum's health.

You are entitled to your opinion.  I take no offense at your attempts
to insult me.

How does your obfuscatory behavior in any way support your technical
points?

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


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Tamas K Papp
On Tue, 02 Dec 2008 13:57:35 -0800, Lew wrote:

> Xah Lee wrote:
>> If [yo]u would like to learn [the] [E]nglish lang[uage] and writing
>> insights from me, peruse:
> 
> /Au contraire/, I was suggesting a higher standard for your posts.

Hi Lew,

It is no use.  Xah has been posting irrelevant rants in broken English 
here for ages.  No one knows why, but mental institutions must be really 
classy these days if the inmates have internet access.  Just filter him 
out with your newsreader.

Best,

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


Re: Mathematica 7 compares to other languages

2008-12-02 Thread Richard Riley
Petite Abeille <[EMAIL PROTECTED]> writes:

> On Dec 2, 2008, at 9:21 PM, Lew wrote:
>
>> These are professional software development forums, not some script-
>> kiddie cellphone-based chat room.  "r" is spelled "are" and "u" should
>> be "you".
>
> While Xah Lee arguably represents a cross between "Enfant Provocateur"
> [1]  and "Evil Clown" [2], this surely qualifies as a  "Grammarian"
> [3] rebuke :D
>
> Cheers,

>From being mildly shocked at such a telling off for minor shortcuts I
would suggest more of a

http://redwing.hutman.net/~mreed/warriorshtm/android.htm

It would seem the soul contributions made are rebukes and petty
prodding.

Every group has one.

>
> --
> PA.
> http://alt.textdrive.com/nanoki/
>
>
> [1] http://redwing.hutman.net/~mreed/warriorshtm/enfantprovocateur.htm
> [2] http://redwing.hutman.net/~mreed/warriorshtm/evilclown.htm
> [3] http://redwing.hutman.net/~mreed/warriorshtm/grammarian.htm

-- 
 important and urgent problems of the technology of today are no longer the 
satisfactions of the primary needs or of archetypal wishes, but the reparation 
of the evils and damages by the technology of yesterday.  ~Dennis Gabor, 
Innovations:  Scientific, Technological and Social, 1970
--
http://mail.python.org/mailman/listinfo/python-list


Re: Running a Python script from crontab

2008-12-02 Thread Jon Redgrave
On Dec 2, 2:35 pm, Astley Le Jasper <[EMAIL PROTECTED]> wrote:
...

Try using the "screen" utility - change the line in your crontab:
cd /home/myusername/src && python myscript.py
to
cd /home/myusername/src && screen -dmS mypthon python -i myscript.py

then once cron has started your program attach to the console using
>> screen -r mypython

(using python -i leaves you at the python prompt if the script just
terminates)

I email myself and drop into the pdb debugger on an exception, then
use screen to debug the system
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP!...Google SketchUp needs a Python API

2008-12-02 Thread r
OK...so here are the stat's so far.

6+BDFL - who would support my crazy idea, or think it -might- be ok
11 - who are on the fence
6 - who think this is a complete waste of time, a stupid idea, or just
simply want to kill me

-> from these stats i can deduce the following:
total_members_comp.lang.python = 14433
note: I will be fair and remove spammers or members that don't follow
this list anymore by dividing the total number in half.(this should be
generous enough)
total_actual_members = (14433/2) = 7214
total_num_responders = 11

->current stats: <11>
percentFor = 31
percentNay = 27
percentOnFence = 40

->Forecast of turnout: <7214>
potentialFors = 2,236.34
potentialConverts = 2,885.34
totalPotentials = 5,121.68

even if only 10% of these act...that is 512 people. I still have hope!

import hope
while hope.amt > 0:
continue
--
http://mail.python.org/mailman/listinfo/python-list


Re: best way to do this

2008-12-02 Thread Arnaud Delobelle
On Dec 2, 2:09 pm, TP <[EMAIL PROTECTED]> wrote:
> Hi everybody,
>
> >>> c=[(5,3), (6,8)]
>
> From c, I want to obtain a list with 5,3,6, and 8, in any order.
> I do this:
>
> >>> [i for (i,j) in c] + [ j for (i,j) in c]
>
> [5, 6, 3, 8]
>
> Is there a quicker way to do this?
>

One list comprehension is enough:

>>> c=[(5,3), (6,8)]
>>> [x for t in c for x in t]
[5, 3, 6, 8]

HTH

--
Arnaud

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


Re: optimization

2008-12-02 Thread Carl Banks
On Dec 2, 1:56 pm, Neal Becker <[EMAIL PROTECTED]> wrote:
> Robert Kern wrote:
> > Neal Becker wrote:
> >> Arnaud Delobelle wrote:
>
> >>> Neal Becker <[EMAIL PROTECTED]> writes:
>
>  I noticed in some profiling, that it seems that:
>
>  def Func ():
>    def something():
>      ...
>
>  It appears that if Func is called many times, this nested func
>  definition will cause significant overhead.  Is this true?  I guess
>  I've become accustomed to decent compilers performing reasonable
>  transformations and so have tended to write code for clarity.
> >>> If something() can be defined outside Func(), how is it clearer to
> >>> define it inside?
>
> >> If it's only used inside.
>
> > I, for one, find that significantly less clear. I only expect functions to
> > be defined inside of functions if they are going to use lexical scoping
> > for some reason. If I read your code, I'd probably waste a good five
> > minutes trying to figure out what part of the local scope you were using
> > before I would conclude that you just did it because you thought it looked
> > better.
>
> I'm using the inner function to prevent pollution of the global
> namespace.  Local variables also have this attribute.  Code is
> easier to understand when it is written with the greatest locality
> - so you can see immediately that the inner function isn't used
> somewhere else.

Let me throw this out:

The rule-of-thumb should not be whether something is used anywhere
else, but rather if it is modified locally or depends on something
that exists locally.  Use outer scope when possible, inner scope only
when necessary.  Flat is better than nested.

In this case, local variables are different from locally-defined
functions, because local variables are typically rebound over the
course of the function, or are constant but depend on the function's
arguments.  (Variables that aren't rebound within the function, or
don't depend on the arguments, are considered constants and are
typically defined in all caps at the module level.)  Locally-defined
functions, however, are constant, and unless they use values from the
enclosing scope, they do not depend on the local environment.
Therefore, by this criterion, the locally-defined function ought to be
defined at the module level, just like constants are.

I don't buy that nesting functions prevents namespace pollution.
IMHO, namespace pollution occurs when you do things like "from module
import *"; there is no pollution when you control the whole namespace
yourself.


Having said that, I do use local functions without closures here and
there, when it's something either too silly or too specific to
introduce a module-level function for.  Judgment call, mostly, but
typically I go to the module level.


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


Re: Simple ini Config parser examples needed

2008-12-02 Thread Glenn Linderman
On approximately 12/2/2008 1:31 PM, came the following characters from 
the keyboard of Chris Rebert:

On Tue, Dec 2, 2008 at 1:18 PM, RON BRENNAN <[EMAIL PROTECTED]> wrote:
  

Hello,

I have a very simple ini file that I needs parsed.  What is the best way I
can parse an ini file that doesn't include sections?

As in:



Since it appears that ConfigParser requires at least one section
header, I'll assume the file starts with the following line:

[main]
  

person=tall
height=small
shoes=big


Thats it.  Can anyone help me?



Completely untested:

import ConfigParser
config = ConfigParser.RawConfigParser()
config.readfp(open("path/to/file.cfg"))
config.get("main", "height") #==> "small"

Cheers,
Chris
  


Of course the OP question was that the line you assume isn't there.  But 
if the ini is simple, maybe it is short enough to read into a string, 
then prepend the line, then parse with ConfigParser.


--
Glenn -- http://nevcal.com/
===
A protocol is complete when there is nothing left to remove.
-- Stuart Cheshire, Apple Computer, regarding Zero Configuration Networking

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


Re: Multiple equates

2008-12-02 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Cameron Laird wrote:

> In article <[EMAIL PROTECTED]>,
> Lawrence D'Oliveiro  <[EMAIL PROTECTED]> wrote:
>
>>Cameron Laird wrote:
>>
>>> I've been trying to decide if there's any sober reason to advocate
>>> the one-liner
>>> 
>>> map(lambda i: a.__setitem__(i, False), [x1, x2, x3, ..., x1024])
>>
>>Are lambdas like the Dark Side of Python?
>>
>>:)
> 
> Enough so, apparently, that I'm reluctant even to touch that question.

So how else would you express something like

def shell_escape(Arg) :
"""returns Arg suitably escaped for use as a command-line argument
to Bash."""
return \
re.sub \
  (
r"[\<\>\"\'\|\&\$\#\;\(\)\[\]\{\}\`\!\~\ \\]",
lambda Match : "\\" + Match.group(0),
Arg
  )
  # Need to catch anything that might be meaningful to shell
#end shell_escape

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


Re: HELP!...Google SketchUp needs a Python API

2008-12-02 Thread James Mills
On Wed, Dec 3, 2008 at 4:44 AM, Benjamin Kaplan
<[EMAIL PROTECTED]> wrote:
>
>
> On Tue, Dec 2, 2008 at 1:36 PM, Craig Allen <[EMAIL PROTECTED]> wrote:
>>
>> > Just remember thought that if you threat Python like a
>> > hammer, suddenly everything will look like a bail.
>> >
>>
>> don't you mean if you use Python like a pitchfork?
>
> Or that everything else looks like a nail. B and N are right next to each
> other, so that seems more likely to me.

Haha that was my bad typing :)

--JamesMills

-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Re: HELP!...Google SketchUp needs a Python API

2008-12-02 Thread James Mills
You're a funny man r :)
Good luck with your endeavours!
I have a hard enough time convincing my work colleagues to use
anything other than PHP for everything!
Here PHP is the Hammer / Pitchfork!

--JamesMills

On Wed, Dec 3, 2008 at 8:16 AM, r <[EMAIL PROTECTED]> wrote:
> OK...so here are the stat's so far.
>
> 6+BDFL - who would support my crazy idea, or think it -might- be ok
> 11 - who are on the fence
> 6 - who think this is a complete waste of time, a stupid idea, or just
> simply want to kill me
>
> -> from these stats i can deduce the following:
> total_members_comp.lang.python = 14433
> note: I will be fair and remove spammers or members that don't follow
> this list anymore by dividing the total number in half.(this should be
> generous enough)
> total_actual_members = (14433/2) = 7214
> total_num_responders = 11
>
> ->current stats: <11>
> percentFor = 31
> percentNay = 27
> percentOnFence = 40
>
> ->Forecast of turnout: <7214>
> potentialFors = 2,236.34
> potentialConverts = 2,885.34
> totalPotentials = 5,121.68
>
> even if only 10% of these act...that is 512 people. I still have hope!
>
> import hope
> while hope.amt > 0:
>continue
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
--
-- "Problems are solved by method"
--
http://mail.python.org/mailman/listinfo/python-list


Hashlib py26

2008-12-02 Thread ShannonL
This feels a bit silly, but I am trying to encrypt some simple text with
the new hashlib library and then decrypt it back into text.  I can do
this with M2Crypto RC4, but not the new hashlib.  Could someone give me
a quick example.

Thank you.

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


Re: Hashlib py26

2008-12-02 Thread Robert Kern

[EMAIL PROTECTED] wrote:
This feels a bit silly, but I am trying to encrypt some simple text with 
the new hashlib library and then decrypt it back into text.  I can do 
this with M2Crypto RC4, but not the new hashlib.  Could someone give me 
a quick example.


hashlib does not do encryption. It implements cryptographic hash functions 
which, while related to encryption algorithms and sometimes are a primitive 
component of such algorithms, do not actually encrypt and decrypt messages.


  http://en.wikipedia.org/wiki/Cryptographic_hash_function

--
Robert Kern

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

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


  1   2   >