Re: Python obfuscation

2005-11-12 Thread Yu-Xi Lim
Alex Martelli wrote:
 It's interesting, in this context, that Civilization IV is mostly
 written in Python (interfaced to some C++ via BoostPython).
 
 It took me 12 seconds with a search engine to determine that CivIV's
 protection uses SafeDisc 4.60 and 30 more seconds to research that
 issue enough to convince myself that there's enough information out
 there that I could develop a crack for the thing (if I was interested in
 so doing), quite apart from any consideration of the languages and
 libraries used to develop it -- and I'm not even a particularly good
 cracker, nor am I wired into any underground channels, just looking at
 information easily and openly available out on the web and in the index
 of a major search engine.

Yes, I never said it's uncrackable. The cracks available are iffy and 
the alternatives are sufficiently inconvenient to dissuade the 
less-savvy user from attempting them. In which case, the copy protection 
has succeeded.

 What I think of this thesis is on a par of what I think of this way of
 spelling the possessive adjective its (and equally unprintable in
 polite company).  If I could choose to eradicate only one of these two
 from the world, I'd opt for the spelling -- the widespread and totally
 unfounded belief in the worth of obfuscation is also damaging, but less
 so, since it only steals some time and energy from developers who (if
 they share this belief) can't be all that good anyway;-).

The level of pedantry here is amazing and it doesn't apply only to 
programming languages. While we are discussing my typos, I'd like to 
note that I may accidentally interchange you're and your, there, 
they're, and their, and a bunch of other homonyms.

I hadn't seen any damage done from misusing it's. Certainly not on par 
with the Sony case which Mike Meyer cites as evidence against copy 
protection (and presumably obfuscation, which was the topic of the 
discussion)



This topic seems to be drifting. I thought I might clarify what I mean 
by code obfuscation to get things back on track.

Code obfuscation is a transformation of the program (whether at source 
code level, intermediate object code level, binary executable level, 
etc) to hinder (prevention seems impossible) reverse engineering 
(attempts to determine the workings of the code, to modify the function 
of the code, etc). While there are many possible transformations that 
can be done on programs (compression, run-time optimizations, etc), the 
key here is the intent to hinder reverse engineering. I hope this is 
agreeable to everyone.

Python already conveniently supports certain transformations on 
programs. Off the top of my head, I think of compiled bytecode (pyc and 
pyo files), and modules in zip archives. Any of these can be used as a 
means of obfuscation. (Compiled languages naturally undergo 
transformations which tend to have more effectiveness against reverse 
engineering)

Now, to address points made by Mike Meyer. He says that obfuscation adds 
steps to the release process and also cites Sony's XCP fiasco as an 
example of unseen costs of copy protection.

Indeed, everything has a cost, and I was wrong in saying free. 
However, if convenient language-supported transforms are used, the 
direct cost of using obfuscation would be miniscule in comparison to 
just about everything else. Implementing it should be one simple step, 
and testing it shouldn't be required (if you reasonably assume the 
language isn't broken).

I am going to ignore certain aspects of the Sony XCP case, such as the 
bad EULA and the bad PR (we shall leave that to the lawyers and 
marketing folk and stick to something we programmers can actually fix). 
What we have left is a broken software implementation of copy 
protection. If language-supported (or even OS-supported, which would 
have helped Sony*) transformations are used, we can expect to rule out 
such brokenness, i.e. no obfuscation-induced incompatibilities and 
related help-desk calls. This further reduces the unexpected costs of 
code obfuscation to zero (did I miss anything?)

This form of obfuscation is certainly weak, but given that the costs are 
so tiny, why not use it? Even if you could gain one customer (and a few 
dollars if you're a shareware developer), you have more than recuperated 
your costs. If you don't, you probably lost 5 minutes of development 
time. Is this a worthwhile gamble? I believe so.

Mike Meyer may reiterate his point about keeping honest people honest 
and thus such obfuscation has little (insignificant) benefit. Whether 
this little difference is insignificant is up to the 
developer/publisher/etc to decide. My thesis (to borrow Alex Martelli's 
language) is that it is possible to obtain *some* benefit from 
obfuscation with *minimal* costs.

There are physical examples of attempts to hinder reverse engineering: 
glueing the cases of devices shut and sealing integrated circuits in a 
blob of epoxy, among others. With such examples, I don't 

Re: about widget construction kit

2005-11-12 Thread Shi Mu
very hard for me to understand the difference between
try...except and try...finally
-- 
http://mail.python.org/mailman/listinfo/python-list


about try statement

2005-11-12 Thread Shi Mu
very hard for me to understand the difference between
try...except and try...finally
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-12 Thread Yu-Xi Lim
Alex Martelli wrote:
 There is no effective manner of protecting your code, except running it
 only on well-secured machines you control yourself.  If you distribute
 your code, in ANY form, and it's at all interesting to people with no
 interest in respecting the law, then, it WILL be cracked (and if users
 choose to respect the law, then you need no protecting).

Indeed. An this extends to web services too. If you have input which can 
be observed (or even better, controlled) and output that can be observed 
too, one would be able to infer the workings of the code (reverse 
engineering in one of its purest forms).

If your business strategy relies heavily on a proprietary algorithm or 
even something as weak as lock-in via a proprietary un-interoperable 
data format, then web services is not the final answer. It may work for 
certain applications (Microsoft's for example) where the cost of reverse 
engineering is equivalent to the cost of building from scratch.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: about try statement

2005-11-12 Thread Sybren Stuvel
Shi Mu enlightened us with:
 very hard for me to understand the difference between try...except
 and try...finally

Within a 'try' block, if an exception is called and a matching
'except' block is found, that block will be used to handle the
expression.

From the documentation of the return keyword: When return passes
control out of a try statement with a finally clause, that finally
clause is executed before really leaving the function. Note that
there is no talk about exceptions in this.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help make it faster please

2005-11-12 Thread Sybren Stuvel
Bengt Richter enlightened us with:
 I suspect it's not possible to get '' in the list from
 somestring.split()

Time to adjust your suspicions:

 ';abc;'.split(';')
['', 'abc', '']


countDict[w] += 1
else:
countDict[w] = 1
 does that beat the try and get versions? I.e., (untested)
  try: countDict[w] += 1
  except KeyError: countDict[w] = 1

OPs way is faster. A 'try' block is very fast, but trowing  handling
an exception is slow.

  countDict[w] = countDict.get(w, 0) + 1

I think this has the potential of being faster than OPs method,
because it's likely to be fully implemented in C.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


passing values from one form to another

2005-11-12 Thread eight02645999
hi

i have 3 python cgi scripts created, one is a login page(login.py),
another is the main page(main.py) with a lot of user inputs and the
last one is a python cgi script results.py to process main.py

In main.py, i am able to check for the value of the user and password
field, eg

if form.has_key(user) and form[button].value == Login and
form.has_key(password):
  # show all fields

how can i also check for the user field in the results.py script? ie ,
pass the value of the user to the python script..so that user must
always login to get to results.py

thanks..

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


JAPH

2005-11-12 Thread Lawrence D'Oliveiro
import sys
charset =  .JPacehknorstuy
modulo = 17
s = 69859911049503515105680510599913390885187193231927247909305172858127641629
num = iter(range(2, ))
while s != 1 :
n = num.next()
if s % n == 0 :
sys.stdout.write(%s % charset[(n - 1) % modulo])
s /= n
#end if
#end while
sys.stdout.write(\n)

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


Re: [ x for x in xrange(10) when p(x) ]

2005-11-12 Thread [EMAIL PROTECTED]

Peter Otten wrote:
 [EMAIL PROTECTED] wrote:

  However, I found something interesting which I don't quite understand :
 
  list((x for x in [1,2,3] if x2 or stop())) works
 
  but
 
  a = [ x for x in [1,2,3] if x 2 or stop() ] doesn't.

 Here's how  Carl Banks explained it to me when Bengt came up with this
 trick.

 http://mail.python.org/pipermail/python-list/2005-April/274051.html

Thanks, but that is even more confusing for me. I thought it is the
for that trap the StopIteration as in :

for x in iteratables: pass

But it said it is not ?

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


Re: help make it faster please

2005-11-12 Thread bearophileHUGS
Thank you Bengt Richter and Sybren Stuvel for your comments, my little
procedure can be improved a bit in many ways, it was just a first
quickly written version (but it can be enough for a basic usage).

Bengt Richter:
good way to prepare for split

Maybe there is a better way, that is putting in just the accepted
letters and accented letters, instead of the not accepted symbols.


I suspect it's not possible to get '' in the list from somestring.split()

You are probably right, the algorithm used is different if you don't
give a splitting string:
 ' abc  a '.split()
['abc', 'a']
 '.abc..a.'.split(.)
['', 'abc', '', 'a', '']


does that beat the try and get versions? I.e., (untested)

Yes.


countDict[w] = countDict.get(w, 0) + 1

I think the if-else version is the fastest, I have tested it a long
time ago... You can easely do a speed test to see if I am wrong.

Bear hugs,
bearophile

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


Re: [ x for x in xrange(10) when p(x) ]

2005-11-12 Thread Bengt Richter
On Sat, 12 Nov 2005 08:12:43 +0100, Peter Otten [EMAIL PROTECTED] wrote:

[EMAIL PROTECTED] wrote:

 However, I found something interesting which I don't quite understand :
 
 list((x for x in [1,2,3] if x2 or stop())) works
 
 but
 
 a = [ x for x in [1,2,3] if x 2 or stop() ] doesn't.

Here's how  Carl Banks explained it to me when Bengt came up with this
trick.

http://mail.python.org/pipermail/python-list/2005-April/274051.html

Thanks (I guess, or is guilt being pinned? ;-) for the attribution.
BTW, that thread is easier to follow on google:

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

But googling shows I wasn't the first to come up with iter([]).next() to raise 
Stopiteration. Usual suspect:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/41495e4f5d3e1c2a/84c158ff18d08ece#84c158ff18d08ece

It probably stuck subconsciously in my mind and just came back when I wanted a 
StopIteration expression
for terminating a generator expression.

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


about array,arange

2005-11-12 Thread Shi Mu
i got confused by the use of array and arange.
arange get array and range get list, why we need the two different types?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-12 Thread Paul Rubin
The Eternal Squire [EMAIL PROTECTED] writes:
 Without copyright, how could one possibly earn a living writing a
 novel?  

This guy seems to be doing ok:  http://craphound.com
His publishers are the only ones allowed to sell his novels commercially,
but you can download them all and print them out noncommercially for
your own personal enjoyment or to share with your friends.  No obfuscation
is needed.

 And I submit that many ISD's are only a single person burning with
 that one software idea of a lifetime, the equivalent of the Great
 American Novel.  Are we to punish that impulse by denying that
 person a legal monopoly on that idea?

You know, there's lots of people who would like to make a living as
actors or musicians or novelists or whatever, and maybe they even have
enough talent and skill to do it, but for whatever reason it's just
not in the cards for them, copyright or not.  So they do other things
instead.  Maybe it's also not in the cards for some people to be
programmers even though they'd like to be, so they do other things
instead too.  For the most part, I don't feel any sense of tragedy
about this.

 I believe piracy is bad for everyone:  the consumer, the writer, and
 the country as a whole.  I don't oppose copyleft, but then, I don't
 oppose copyright either.  Let's distribute the former for free, and
 honor the need for the writer of the latter to earn a living.

Everyone has the right to try to earn a living from programming, but
no one is entitled to be guaranteed success at it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help make it faster please

2005-11-12 Thread Bengt Richter
On Sat, 12 Nov 2005 10:46:53 +0100, Sybren Stuvel [EMAIL PROTECTED] wrote:

Bengt Richter enlightened us with:
 I suspect it's not possible to get '' in the list from
 somestring.split()

Time to adjust your suspicions:

 ';abc;'.split(';')
['', 'abc', '']
I know about that one ;-)
I meant somestring.split() just like that -- without a splitter argument.
My suspicion remains ;-)



countDict[w] += 1
else:
countDict[w] = 1
 does that beat the try and get versions? I.e., (untested)
  try: countDict[w] += 1
  except KeyError: countDict[w] = 1

OPs way is faster. A 'try' block is very fast, but trowing  handling
an exception is slow.
Yes, so it's data sensitive. Same with the other one not mentioned:
countDict.setdefault(w, [0])[0] += 1  # accum count in 
length one list vs as int
  # too much 
subscripting work though

  countDict[w] = countDict.get(w, 0) + 1

I think this has the potential of being faster than OPs method,
because it's likely to be fully implemented in C.

Not sure what you mean. Don't forget, all those expressions are evaluated 
dynamically
step by step with byte codes being switched on in c, but still a bunch of 
steps. I.e.,
  import dis
  dis.dis(compile('countDict[w] = countDict.get(w, 0) + 1', '', 'exec'))
   1   0 LOAD_NAME0 (countDict)
   3 LOAD_ATTR1 (get)
   6 LOAD_NAME2 (w)
   9 LOAD_CONST   0 (0)
  12 CALL_FUNCTION2
  15 LOAD_CONST   1 (1)
  18 BINARY_ADD
  19 LOAD_NAME0 (countDict)
  22 LOAD_NAME2 (w)
  25 STORE_SUBSCR
  26 LOAD_CONST   2 (None)
  29 RETURN_VALUE

Looks like if you succeed most of the time without a KeyError, the try/except 
might be
a tad faster, depending on what the exception block setup/teardown costs.

  dis.dis(compile(\
 ... try: countDict[w] += 1
 ... except KeyError: countDict[w] = 1
 ... , '', 'exec'))
   1   0 SETUP_EXCEPT20 (to 23)
   3 LOAD_NAME0 (countDict)
   6 LOAD_NAME1 (w)
   9 DUP_TOPX 2
  12 BINARY_SUBSCR
  13 LOAD_CONST   0 (1)
  16 INPLACE_ADD
  17 ROT_THREE
  18 STORE_SUBSCR
  19 POP_BLOCK
  20 JUMP_FORWARD29 (to 52)

   223 DUP_TOP
  24 LOAD_NAME2 (KeyError)
  27 COMPARE_OP  10 (exception match)
  30 JUMP_IF_FALSE   17 (to 50)
  33 POP_TOP
  34 POP_TOP
  35 POP_TOP
  36 POP_TOP
  37 LOAD_CONST   0 (1)
  40 LOAD_NAME0 (countDict)
  43 LOAD_NAME1 (w)
  46 STORE_SUBSCR
  47 JUMP_FORWARD 2 (to 52)
50 POP_TOP
  51 END_FINALLY
52 LOAD_CONST   1 (None)
  55 RETURN_VALUE

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


Re: about widget construction kit

2005-11-12 Thread Fredrik Lundh
Shi Mu wrote:

 I tried again and got the follwoing message:
 *** cannot find Tcl/Tk headers and library files
 change the TCL_ROOT variable in the setup.py file
 but i have already installed TCL under python23

hmm.  I still think it would be easier if you used a prebuilt version, like
everyone else.

(if you insist on using an old source release instead of the latest binaries,
follow the instructions, and make sure the TCL_ROOT variable points to
the location of the Tcl/Tk development libraries (the directory that con-
tains Tcl's include and lib directories, that is))

/F



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


911, need drvmcdb.sys desperately

2005-11-12 Thread James Hu
Hi, 
 

Sorry to post this message, but I need emergency help, please help me
out! 

I couldn't get drvmcdb.sys from internet, which I accidentally deleted
last night, my laptop (XP) couldn't reboot anymore, but I need to keep
my data.

If anybody can send me this file: which is located in
c:\windows\system32\drivers\drvmcdb.sys

Please send it to [EMAIL PROTECTED], coz I couldn't use this account
from tomorrow

I will appreciate your BIG HELP so much! You are my life saver!

 
Regards,
 

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


Re: JAPH

2005-11-12 Thread Szabolcs Nagy
charset, modulo, japh =  .JPacehknorstuy, 17, 
s =
69859911049503515105680510599913390885187193231927247909305172858127641629
for n in xrange(2,):
if s%n==0:
japh += charset[(n - 1) % modulo]
s /= n
if s==1:
break
print japh

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


Re: Recommendation please: forming an XML toolkit

2005-11-12 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

 I guess you're right... I think its just cold feet from the possibility
 of getting involved and discovering specific gotchas later.

 What I'm hearing you tell me is *go and play it*.

uche posted an interesting taxonomy here:

http://article.gmane.org/gmane.comp.python.xml/3605

once you decide what kind of XML processing you're doing, you can
usually find one or two best-of-breed toolkits within each category.

/F



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


Re: about try statement

2005-11-12 Thread Bengt Richter
On Sat, 12 Nov 2005 10:20:08 +0100, Sybren Stuvel [EMAIL PROTECTED] wrote:

Shi Mu enlightened us with:
 very hard for me to understand the difference between try...except
 and try...finally

Within a 'try' block, if an exception is called and a matching
'except' block is found, that block will be used to handle the
expression.

From the documentation of the return keyword: When return passes
control out of a try statement with a finally clause, that finally
clause is executed before really leaving the function. Note that
there is no talk about exceptions in this.

Which is because in the finally block the exception is still live
and will take effect as soon as the finally block is left, e.g.,

  try:
 ... try: 1/0
 ... finally: print 'exception can not bypass finally'
 ... except Exception, e:
 ... print '%s: %s' %(e.__class__.__name__, e)
 ...
 exception can not bypass finally
 ZeroDivisionError: integer division or modulo by zero

Or to make the point about return
  def foo(den):
 ... try:
 ... try: return 1/den
 ... finally: print 'exception can not bypass finally'
 ... except Exception, e:
 ... print '%s: %s' %(e.__class__.__name__, e)
 ... return 'succeeded in returning something'
 ...
  foo(0)
 exception can not bypass finally
 ZeroDivisionError: integer division or modulo by zero
 'succeeded in returning something'
  foo(1)
 exception can not bypass finally
 1

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


Re: about array,arange

2005-11-12 Thread Robert Kern
Shi Mu wrote:
 i got confused by the use of array and arange.
 arange get array and range get list, why we need the two different types?

When you're asking questions about a third-party module, it's a good
idea to mention the module. In this case you're asking about scipy_core
(hopefully) or else numarray or Numeric.

The answer to your question is that sometimes we need to get largish
arrays (not lists) of consecutive numbers quickly. array(range(N)) is
wasteful of memory and time because it has to create a list of Python
ints that are simply going to be thrown away once we're done converting
to the needed array.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die.
  -- Richard Harter

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


Re: about array,arange

2005-11-12 Thread Shi Mu
On 11/12/05, Robert Kern [EMAIL PROTECTED] wrote:
 Shi Mu wrote:
  i got confused by the use of array and arange.
  arange get array and range get list, why we need the two different types?

 When you're asking questions about a third-party module, it's a good
 idea to mention the module. In this case you're asking about scipy_core
 (hopefully) or else numarray or Numeric.

 The answer to your question is that sometimes we need to get largish
 arrays (not lists) of consecutive numbers quickly. array(range(N)) is
 wasteful of memory and time because it has to create a list of Python
 ints that are simply going to be thrown away once we're done converting
 to the needed array.

 --
 Robert Kern
 [EMAIL PROTECTED]
sorry to forget to mention the module name : Numeric
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weird problem with os.chmod

2005-11-12 Thread Fredrik Lundh
Mike Meyer wrote:

 Strange that int doesn't recognize the leading 0. But you can use the
 second argument to int:

  int(0600, 16)
 1536
 

int is designed for humans, not C programmers.  humans tend to view
e.g. 08 as a valid decimal number (*), not a ValueError.

to get programmer behaviour, pass in 0 as the base:

 int(10, 0)
10
 int(010, 0)
8
 int(0x10, 0)
16

/F

*) unless you're living in sweden, in which case 08 is quite often used
as an insult.



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


Re: about widget construction kit

2005-11-12 Thread Shi Mu
On 11/12/05, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Shi Mu wrote:

  I tried again and got the follwoing message:
  *** cannot find Tcl/Tk headers and library files
  change the TCL_ROOT variable in the setup.py file
  but i have already installed TCL under python23

 hmm.  I still think it would be easier if you used a prebuilt version, like
 everyone else.

 (if you insist on using an old source release instead of the latest binaries,
 follow the instructions, and make sure the TCL_ROOT variable points to
 the location of the Tcl/Tk development libraries (the directory that con-
 tains Tcl's include and lib directories, that is))

what is Tcl/Tk development libraries? I have a tcl folder under c:\python23.
Is that what you mean?
Regards,
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-12 Thread Ben Finney
Yu-Xi Lim [EMAIL PROTECTED] wrote:
 Code obfuscation is a transformation of the program (whether at
 source code level, intermediate object code level, binary executable
 level, etc) to hinder (prevention seems impossible) reverse
 engineering (attempts to determine the workings of the code, to
 modify the function of the code, etc). While there are many possible
 transformations that can be done on programs (compression, run-time
 optimizations, etc), the key here is the intent to hinder reverse
 engineering.

That's a workable definition.

 I hope this is agreeable to everyone.

The definition is agreeably solid.

The intention is disagreeably sickening.

-- 
 \ Room service? Send up a larger room.  -- Groucho Marx |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tutorial example

2005-11-12 Thread Ruben Charles
That is the diference between a method and a function.
A method do something and a function return something.

Example:

def psum(n, m):
print (n + m)

def rsum(n, m):
return (n +m)

Then try this...


  psum(2, 3)

 a = psum(2, 3)

 a

 a = rsum(2, 3)

 a

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


Re: What do you use as symbols for Python ?

2005-11-12 Thread Chris Smith
 Gary == Gary Herron [EMAIL PROTECTED] writes:

Gary Erik Max Francis wrote:
 Pierre Barbier de Reuille wrote:   
When you need some symbols in your program, what do you use in
 Python ?
 
 For example, an object get a state. This state is more
 readable if expressed as a symbols, for example opened,
 closed, error.  Typically, in C or C++, I would use an
 enum for that: enum OBJECT_STATE { opened, closed, error
 }
 
 

 OPENED, CLOSED, ERROR = range(3)
 
 object.state = OPENED
 
 
Gary Another similar approach that keeps those values together in
Gary a single namespace is this (my favorite):

Gary   class State: OPENED, CLOSED, ERROR = range(3)

Gary Then you can refer to the values as State.OPENED
Gary State.CLOSED State.ERROR

Gary The extra clarity (and slight wordiness) of the dotted
Gary notation seems, somehow, quite Pythonic to me.

Gary Gary Herron

I think Zoran Isailovski has the last word on the topic:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486

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


Re: about widget construction kit

2005-11-12 Thread Fredrik Lundh
Shi Mu wrote:

   I tried again and got the follwoing message:
   *** cannot find Tcl/Tk headers and library files
   change the TCL_ROOT variable in the setup.py file
   but i have already installed TCL under python23
 
  hmm.  I still think it would be easier if you used a prebuilt version, like
  everyone else.
 
  (if you insist on using an old source release instead of the latest 
  binaries,
  follow the instructions, and make sure the TCL_ROOT variable points to
  the location of the Tcl/Tk development libraries (the directory that con-
  tains Tcl's include and lib directories, that is))

 what is Tcl/Tk development libraries?

the stuff you get if you install tcl-devel/tk-devel on unix, or a complete
Tcl/Tk distribution on Windows (e.g. ActiveTcl).

 I have a tcl folder under c:\python23. Is that what you mean?

if you set TCL_ROOT to that directory and setup still says that it cannot
find the development files, the answer is most likely no.

can you explain why you cannot use a prebuilt version?

/F



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


Re: about array,arange

2005-11-12 Thread Shi Mu
On 11/12/05, Robert Kern [EMAIL PROTECTED] wrote:
 Shi Mu wrote:
  i got confused by the use of array and arange.
  arange get array and range get list, why we need the two different types?

 When you're asking questions about a third-party module, it's a good
 idea to mention the module. In this case you're asking about scipy_core
 (hopefully) or else numarray or Numeric.

 The answer to your question is that sometimes we need to get largish
 arrays (not lists) of consecutive numbers quickly. array(range(N)) is
 wasteful of memory and time because it has to create a list of Python
 ints that are simply going to be thrown away once we're done converting
 to the needed array.

 --
 Robert Kern
 [EMAIL PROTECTED]
still not clear. can you give an example?
Thanks! it is from numeric module (really confused by the documentation)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tutorial example

2005-11-12 Thread Max Erickson

Not in python.

For example, what would you call the following?

def rsum(n, m):
print n+m
return n+m


In python a method is callable attached to an object. A function is a 
callable object constructed with a def statement.

max

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


Re: about array,arange

2005-11-12 Thread Robert Kern
Shi Mu wrote:
 On 11/12/05, Robert Kern [EMAIL PROTECTED] wrote:
 
Shi Mu wrote:

i got confused by the use of array and arange.
arange get array and range get list, why we need the two different types?

When you're asking questions about a third-party module, it's a good
idea to mention the module. In this case you're asking about scipy_core
(hopefully) or else numarray or Numeric.

The answer to your question is that sometimes we need to get largish
arrays (not lists) of consecutive numbers quickly. array(range(N)) is
wasteful of memory and time because it has to create a list of Python
ints that are simply going to be thrown away once we're done converting
to the needed array.

 still not clear. can you give an example?
 Thanks! it is from numeric module (really confused by the documentation)

An example of what? How to use arange()? I can't explain it any more
clearly than the docstring does.

In [1]: from Numeric import arange

In [2]: arange?
Type:   builtin_function_or_method
Base Class: type 'builtin_function_or_method'
String Form:built-in function arange
Namespace:  Interactive
Docstring:
arange(start, stop=None, step=1, typecode=None)

 Just like range() except it returns an array whose type can be
specified by the keyword argument typecode.

-- 
Robert Kern
[EMAIL PROTECTED]

In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die.
  -- Richard Harter

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


Re: tutorial example

2005-11-12 Thread Ruben Charles
On 11/12/05, Max Erickson [EMAIL PROTECTED] wrote:

 Not in python.

 For example, what would you call the following?

 def rsum(n, m):
 print n+m
 return n+m


 In python a method is callable attached to an object. A function is a
 callable object constructed with a def statement.

You are right, i was trying to explain the concept outside the objects.

PD: I would call your example: a function. Without the return
declaration, a routine or a method.
-- 
http://mail.python.org/mailman/listinfo/python-list


SciPy python 2.4 wintel binaries

2005-11-12 Thread jelle
Hi,

I dearly miss having the power of SciPy on my python 2.4 installation.
The topic of SciPy python 2.4 wintel binaries has been discussed before
on this list, but I haven't been able to find a compiled binary. I'm
one of the 'compiled-challenged'; anything more complex than 'python
setup.py build' leaves me at the grace of the non-challenged... SciPy
is a complex software engineering project, so I'm hangin on the mercy
of others here...

Is anyone on this list aware of such a binary?

Thanks,

-jelle

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


convert string to the escaped string

2005-11-12 Thread Petr Jakes
Hi,
I am trying to convert string to the escaped string.
example: from 0xf I need \0xf
I am able to do it like:

a=0xf
escaped_a=(\%s % a ).decode(string_escape)

But it looks a little bit complicated in this beautiful language to me


Regards

Petr Jakes

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


Re: convert string to the escaped string

2005-11-12 Thread Petr Jakes
small mistake in my previous posting, sorry
from 0xf I need \xf of course
and mentioned code gives me \0xf of course.

Thanks for your postings

Petr Jakes

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


Re: convert string to the escaped string

2005-11-12 Thread Fredrik Lundh
Petr Jakes wrote:

 I am trying to convert string to the escaped string.
 example: from 0xf I need \0xf

 I am able to do it like:

 a=0xf
 escaped_a=(\%s % a ).decode(string_escape)

 But it looks a little bit complicated in this beautiful language to me

I suspect that optimizing for people who want to turn 0xf into
chr(0) + xf isn't exactly a priority...

if that's really what you want, of course.  are you sure you didn't
mean to write, say

chr(int(0xf, 0))

(that is, convert 0xf to a character) or

repr(chr(int(0xf, 0)))

(that is, convert 0xf to a character, and convert that character to a
string literal)

?

/F 



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


Re: changeing users on linux

2005-11-12 Thread jepler
On Fri, Nov 11, 2005 at 11:25:56PM -0500, Mike Meyer wrote:
 You didn't say what the password was for, so I skipped asking for it.

You're a real comedian.

Jeff


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

Re: tutorial example

2005-11-12 Thread Colin J. Williams
Ruben Charles wrote:
 That is the diference between a method and a function.
 A method do something and a function return something.
 
This is not quite correct. The difference between a method and a 
function is that the method is associated with a type or class object, a 
function is not.

A method can be bound to a particular instance of an object or it can be 
unbound.  In the latter case the first argument of the method call 
should be an instance of the type or class object.  However, there is no 
builtin check to ensure that the first argument is in fact an instance.

Please see the little example below.

Colin W.
# areaToy.py

class Point(object):
   def __init__(self, x, y):
 self.x= x
 self.y= y

class Area(object):
   def __init__(self, *pts):
 ''' pts is a list of points describing the enclosing polygon,
 in clockwise order, instances of Point. '''
 self.pts= pts[0]

   def size(self):
 nPts= len(self.pts)
 if nPts  3:
   return 0
 elif nPts == 3:
   return 0.5   # replace this with triangle area calc
 else:
   pts= self.pts
   return Area(pts[0:2] + [pts[-1]]).size() +\
  Area(pts[1:]).size()

pts= [Point(*pt) for pt in [(0, 1), (1, 1), (1, 0), (0, 0)]]
area= Area(pts)
size= area.size()
print 'points:', pts
print 'size:', size
print 'Area.size:', Area.size
print 'area.size:', area.size
 Example:
 
 def psum(n, m):
 print (n + m)
 
 def rsum(n, m):
 return (n +m)
 
 Then try this...
 
 
 
 psum(2, 3)
 
 
a = psum(2, 3)
 
 
a
 
 
a = rsum(2, 3)
 
 
a
 
 
 You see it?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What do you use as symbols for Python ?

2005-11-12 Thread Daniel Evers
Peter Otten wrote:
 
 You should ditch what follows and instead add just
 
   def __iter__(self):
   return  iter(self.__keys)

Mhh. I should start learning the builtins ... :)

 To see the problem with your original code (an object serving as its own
 iterator) try the following example:
 
 friends = Enum(Eric, Kyle, Stan, Kenny)
 if Kyle in friends:
 print Hi Kyle
 print My friends:, , .join(friends)
 
 Only Stan and Kenny show up in the last print statement because the
 containment test did not iterate over all friends.

Never would have thought of this... Makes it even easier.

 Also, Type.__name seems redundant. Just
 
 class Type(str): pass
 
 should do the job.

Right, works just fine. I'm not used to types, meanwhile I replaced
Type(str) by a simple class Type, works as well.

Thanks a lot, I was starting to integrate this solution in my code, now I
can fix it before it's even used :)

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


Re: Dynamically Update Class Definitions?

2005-11-12 Thread Chris Spencer
Jean-Paul Calderone wrote:

 There are lots of cases where you cannot rebind the __class__ 
 attribute.  For a comprehensive treatment of this idea (but still not a 
 completely functionality implementation), take a look at 
 http://cvs.twistedmatrix.com/cvs/trunk/twisted/python/rebuild.py?view=markuprev=11450.
   
 On another note, the usage of threads in this code is totally insane and 
 unsafe.  Even for strictly development purposes, I would expect it to 
 introduce so many non-deterministic and undebuggable failures as to make 
 it cost more time than it saves.  You really want to stop the rest of 
 the program, then update things, then let everything get going again.

I used a thread to quickly detect changes in the source code, but you're 
absolutely right. In any non-toy application you'll definitely need 
control over when the upgrade process occurs. Thanks for the help.

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


Tkinter and the re/sizing of columns in a grid

2005-11-12 Thread noman

I'm using grid() to lay out a column of Labels and a column of Entries
in a frame. If the user changes an Entry so that it's bigger than its
allotted space, i'd like to widen that column to show the entire
string. I've tried parentFrame.columnconfigure(1, minsize=newSize),
but that doesn't change anything. I'm obviously missing something. How
should i go about this?

More generally, can anyone point me to info on how to do calculated
sizing and resizing of grids?

thanks,
Eric

-- 
A strong smell of turpentine prevails throughout.
   -- Dr. Oliver Wendell Holmes
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weird problem with os.chmod

2005-11-12 Thread Roel Schroeven
Gary Herron wrote:
 James Colannino wrote:
 
 James Colannino wrote:

  

 So then I entered the command print 0600, and saw that the actual
 number being output was 384 (why would it output 384?!)


   


 Ok, so further research revealed that 0600 is actually the octal
 representation for 384 (which makes sense.)  So then, I guess my
 question would have to be, is there a way for me to make Python aware
 that the 0600 I'm passing to int() is octal and not decimal so that I
 will get 384 instead of 600?
  

 int('0600',8) will do, but why would you want to do that?
 
 Any of
 x = 0600
 x = 384
 x = 0x180
 x = int('0600',8)
 will bind x to the same value (11000 in binary if you care).
 
 But once you've got the valued defined, through whatever human readable
 representation you want, the command
 chmod(filename, x)
 can be issued without further thought.

He reads the string ('0600' in this case, but I guess it can be any
permission) from a file. So he doesn't have the numerical value to begin
with.

BTW, I guess it's safer to do int(permission, 8) than int(permission,
0), since the first digit isn't guaranteed to be zero: it is used for
set user ID, set group ID and the sticky bit.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: tutorial example

2005-11-12 Thread Roel Schroeven
Ruben Charles wrote:
 That is the diference between a method and a function.
 A method do something and a function return something.

I'd rather say it's the difference between a procedure and a function,
as it is used in e.g. Pascal. Procedures in Pascal don't return
anything, more or less analogue to functions returning void in C/C++.

-- 
If I have been able to see further, it was only because I stood
on the shoulders of giants.  -- Isaac Newton

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


Re: passing values from one form to another

2005-11-12 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:
 hi
 
 i have 3 python cgi scripts created, one is a login page(login.py),
 another is the main page(main.py) with a lot of user inputs and the
 last one is a python cgi script results.py to process main.py
 
 In main.py, i am able to check for the value of the user and password
 field, eg
 
 if form.has_key(user) and form[button].value == Login and
 form.has_key(password):
   # show all fields
 
 how can i also check for the user field in the results.py script? ie ,
 pass the value of the user to the python script..so that user must
 always login to get to results.py

Use a session. Or pass the values as hidden form-fields, which gets 
pretty tedious.

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


ANN: pynakotheka v1.0

2005-11-12 Thread Iñigo Serna
Hello out there,

I'm really pleased to announce the first public release of Pynakotheka.

Pynakotheka is a simple GPL-licensed python script which generates
static HTML photo albums to be added to web sites or to be burnt in CDs.
It includes some templates and it's easy to create more.

It depends on python, CheetahTemplate, EXIF and PIL.

Read more and download it from:

http://inigo.katxi.org/devel/pynakotheka

or http://www.terra.es/personal7/inigoserna/pynakotheka


Of course, all comments, suggestions etc. are welcome.


Best regards,
-- 
Iñigo Serna [EMAIL PROTECTED]
Katxijasotzaileak


signature.asc
Description: Esta parte del mensaje está firmada	digitalmente
-- 
http://mail.python.org/mailman/listinfo/python-list

newbie how do I interpret this?

2005-11-12 Thread bobueland
Here's a small session

 import re
 p=re.compile('[a-z]+')
 m=p.match('abb1a')
 dir(m)
['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict',
'groups', 'span', 'start']
 help(m.groups)
Help on built-in function groups:

groups(...)



My question is. How do I interpret the hiven help info
groups(...)

alt1. Tough luck. There's no help. People are to busy to write
reference manuals.
alt 2. There are no parameters. The only possibility is m.groups()
alt3. Something else

Thanks Bob

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


Re: Python obfuscation

2005-11-12 Thread Mike Meyer
Yu-Xi Lim [EMAIL PROTECTED] writes:
 Indeed, everything has a cost, and I was wrong in saying
 free. However, if convenient language-supported transforms are used,
 the direct cost of using obfuscation would be miniscule in comparison
 to just about everything else. Implementing it should be one simple
 step, and testing it shouldn't be required (if you reasonably assume
 the language isn't broken).

Failng to test what you ship is simply poor engineering and poor
marketing. If you're incompetent, you might skip those
steps. Otherwise, you have to test with obfuscation in place.

 I am going to ignore certain aspects of the Sony XCP case, such as the
 bad EULA and the bad PR (we shall leave that to the lawyers and
 marketing folk and stick to something we programmers can actually
 fix). What we have left is a broken software implementation of copy
 protection. If language-supported (or even OS-supported, which would
 have helped Sony*) transformations are used, we can expect to rule out
 such brokenness, i.e. no obfuscation-induced incompatibilities and
 related help-desk calls. This further reduces the unexpected costs of
 code obfuscation to zero (did I miss anything?)

You ignored the fact that the *act* of copy protection cost them
customers. It wasn't the poor implementation or the EULA, it was the
fact that people who were denied their fair use rights returned or
refused to buy their product. The rest of it merely made it widely
publicized.

 This form of obfuscation is certainly weak, but given that the costs
 are so tiny, why not use it? Even if you could gain one customer (and
 a few dollars if you're a shareware developer), you have more than
 recuperated your costs. If you don't, you probably lost 5 minutes of
 development time. Is this a worthwhile gamble? I believe so.

And if instead you lose one customer because you've denied them their
fair use rights, then your copy protection has lost you more in the
form of a cost that you overlooked than all the costs you actually
considered.

 Mike Meyer may reiterate his point about keeping honest people
 honest and thus such obfuscation has little (insignificant)
 benefit. Whether this little difference is insignificant is up to
 the developer/publisher/etc to decide. My thesis (to borrow Alex
 Martelli's language) is that it is possible to obtain *some* benefit
 from obfuscation with *minimal* costs.

Actually, obfuscation by itself has *no* benefit. If all you do is
obfuscate the code, none of the pirates will ever notice - they'll
just copy the code without ever trying to read it. It's the copy
protection mechanisms you're trying to obfuscate that gains you the
alleged benefit. Once you provide a copy protection mechanism,
obfuscation has some benefit, though the costs aren't clearly minimal,
not if you're a cometent engineer. It's the benefits of the copy
protection that I claim are insignificant.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: changeing users on linux

2005-11-12 Thread Mike Meyer
[EMAIL PROTECTED] writes:

 the password is for loging into root

The setuid call will fail unless you're already root. You can't, as
some user other than root, change your userid, so the answer to
the original question with the added restriction is You can't.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: newbie how do I interpret this?

2005-11-12 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

  help(m.groups)
 Help on built-in function groups:

 groups(...)

 

 My question is. How do I interpret the hiven help info
 groups(...)

 alt1. Tough luck. There's no help. People are to busy to write
 reference manuals.

they're busy writing reference manuals, you mean:

http://docs.python.org/lib/match-objects.html

 alt 2. There are no parameters. The only possibility is m.groups()

in this case, that happens to be the most common way to use
the method.

 alt3. Something else

the words built-in function means that the function is im-
plemented in C, and is therefore outside the reach of Python's
introspection mechanisms.  In this case, there don't seem to
be any custom docstring associated with this method, so the
above is all help() can tell you at the moment.  This may of
course change in future releases.

/F



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


Re: convert string to the escaped string

2005-11-12 Thread Petr Jakes
Fredrik, thanks  for your posting. I really appretiate your reply and
your way how you kindly answer even stupid newbie's questions on this
mailing list.
I was trying: int(0xf) but I did not have idea about the optional
base parameter for the int function.
Thanks a lot.
Petr

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


Re: passing values from one form to another

2005-11-12 Thread Mike Meyer
[EMAIL PROTECTED] writes:
 In main.py, i am able to check for the value of the user and password
 field, eg

 if form.has_key(user) and form[button].value == Login and
 form.has_key(password):
   # show all fields

 how can i also check for the user field in the results.py script? ie ,
 pass the value of the user to the python script..so that user must
 always login to get to results.py

This isn't really a Python question. The canonical solution is to set
a cookie to get the browser to pass the required information to the
next form.

 mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python obfuscation

2005-11-12 Thread Alex Martelli
Yu-Xi Lim [EMAIL PROTECTED] wrote:

 Alex Martelli wrote:
  There is no effective manner of protecting your code, except running it
  only on well-secured machines you control yourself.  If you distribute
  your code, in ANY form, and it's at all interesting to people with no
  interest in respecting the law, then, it WILL be cracked (and if users
  choose to respect the law, then you need no protecting).
 
 Indeed. An this extends to web services too. If you have input which can
 be observed (or even better, controlled) and output that can be observed
 too, one would be able to infer the workings of the code (reverse 
 engineering in one of its purest forms).

...unless you have nonobservable state, of course, in which case the
inference is conceptually impossible.  For example, say that you have
developed a new and revolutionary system to predict weather, much better
than anything the competition has.  You offer it as a for-pay web
service, the customer-supplied inputs being the space-time coordinates
at which prediction is required, while the customer-provided outputs are
a vector of possible weather conditions each with an attached
probability, just as they might be for ANY weather-prediction web
service, except that (by hypothesis, or else you won't make much money
on this;-) the outputs of your weather predictor match reality much
better than the competitors'.  To infer whatever would essentially
mean to reinvent your whole revolutionary system from scratch.

Much the same would apply if what your system is able to predict better
than your competitors' is any other kind of phenomenon of economic
interest in a sufficiently complex real-world system -- from interest
rates to the probability that two would-be online daters will like each
other.  And it doesn't have to be prediction -- one famous system where
ESR, as a consultant, advised his clients to keep their program a trade
secret, was just a better heuristic than any of their competitors' for
cutting a set of given shapes with automated tools out of a slab of
wood, if I recall correctly... a problem that's computationally
intractable to solve anything but heuristically, and a better heuristic
saves wood, worktime, and/or wear and tear on the tools, therefore is
worth money.

In practice, you ARE going to be able to operate your system
successfully bases on keeping a good innovative algorithm or heuristic
secret, for a while -- until somebody else independently reinvents it
(or, invents something even better, in which case your secret may become
irrelevant).  IP protection is a possibility, but copyright per se might
be too weak, and whether patents apply in any given case is always
controversial (Europe soundly defeated a proposed software patent
directive, after a bitter fight, less than a year ago).

 
 If your business strategy relies heavily on a proprietary algorithm or
 even something as weak as lock-in via a proprietary un-interoperable
 data format, then web services is not the final answer. It may work for
 certain applications (Microsoft's for example) where the cost of reverse
 engineering is equivalent to the cost of building from scratch.

...and the latter is going to be the case for many important
proprietary algorithms, as above exemplified.

A cryptographically sound proprietary data format may be essentially
impossible to break, too -- although, differently from many potential
algorithms, it has per se no added value, and may run afoul of sensible
legislation (or sensible would-be customers), such as Massachussets',
mandating the use of standard data formats.


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


Re: Python obfuscation

2005-11-12 Thread Alex Martelli
Yu-Xi Lim [EMAIL PROTECTED] wrote:

 I hadn't seen any damage done from misusing it's. Certainly not on par

You should see my pharmacy bill for Maalox... and my liver ain't too
happy about it either;-)


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


Re: Python obfuscation

2005-11-12 Thread Alex Martelli
Paul Rubin http://[EMAIL PROTECTED] wrote:

 The Eternal Squire [EMAIL PROTECTED] writes:
  Without copyright, how could one possibly earn a living writing a
  novel?  
 
 This guy seems to be doing ok:  http://craphound.com
 His publishers are the only ones allowed to sell his novels commercially,
 but you can download them all and print them out noncommercially for
 your own personal enjoyment or to share with your friends.  No obfuscation
 is needed.

One might also quip (not truthfully in Cory's specific case, I hasten to
add!-) that many of today's novels are intrinsically obfuscated enough
to need no further technological help on that front;-).

Quips aside, the question is a sensible one to ask -- not as a
rhetorical question, as TES apparently intended, of course, and not just
about novels (many different creative endeavours may require different
answers).  The novel as a specific literary form is not that old, just
a few centuries, but the issues were not very different for many other
literary forms over the ages and cultures, and many different answers
have been given or attempted.

For example, Virgil was writing poems (epic and otherwise), not novels,
but that's not very relevant to the question of how he made a living;
the classic solution, in his case, was to find rich patrons willing to
pay him to do so.  Of course, there are obvious problems with this
model... for example, Virgil was paid to write the Aeneid because his
patrons liked its patriotism (as well as its towering artistic
qualities), but a work with equally good art but an anti-patriotic
ideology would have been much harder to monetize at that time (and also
risked landing the author in the soup, as Ovid found out, but that's
another issue, quite unrelated to monetization).

Zooming forwards a couple of millennia, we see the model of
serialization -- having the novel published in periodic installments
by a magazine.  Avid readers, we're told, crowded the piers of New York
waiting for ship to land which carried the magazine with the latest
installment of some Dickens novel -- and Dumas and Sue, in France, had
fully comparable success in similar ways.  At that time, copyright
existed, in theory, but practically wasn't very well enforced (most
particularly, I believe, in the USA, where the probability of a British
publisher of actually enforcing a copyright was laughably low...) --
nevertheless, the reasonable cheapness of magazines coupled with the
readers' urgency for the next installment let these authors earn a
comfortable living anyway.  Here, the problem is presumably that you
need VERY popular novels for this to work -- but then, a tiny fraction
of novelists actually make a comfortable living from just their novels,
even with today's monetization approaches.

Modern equivalent of serialization (publishing one chapter at a time on
the web, the next chapter to come only if the author receives enough
payment for the previous one) have been attempted, but without much
success so far; however, the holy grail of micropayments might yet
afford a rebirth for such a model -- if paying for a chapter was
extremely convenient and cheap, enough people might choose to do so
rather than risk the next chapter never appearing.  Remember that, by
totally disintermediating publishers and bookstores, a novelist may
require maybe 1/10th of what the book would need to gross in stores, in
order to end up with the same amount of cash in his or her pockets.

One could go on for a long time, but the key point is that there may or
may not exist viable monetization models for all sorts of endeavours,
including the writing of novels, depending on a lot of other issues of
social as well as legal structures.  Let's not be blinded by one model
that has worked sort of decently for a small time in certain sets of
conditions, into believing that model is the only workable one today or
tomorrow, with conditions that may be in fact very different.


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


Re: newbie how do I interpret this?

2005-11-12 Thread Mike Meyer
[EMAIL PROTECTED] writes:

 Here's a small session

 import re
 p=re.compile('[a-z]+')
 m=p.match('abb1a')
 dir(m)
 ['__copy__', '__deepcopy__', 'end', 'expand', 'group', 'groupdict',
 'groups', 'span', 'start']
 help(m.groups)
 Help on built-in function groups:

 groups(...)



 My question is. How do I interpret the hiven help info
 groups(...)

 alt1. Tough luck. There's no help. People are to busy to write
 reference manuals.
 alt 2. There are no parameters. The only possibility is m.groups()
 alt3. Something else

alt 3, specifically: No doc string, time to check the reference manual.

URL: http://docs.python.org/lib/match-objects.html  says:

groups( [default])
Return a tuple containing all the subgroups of the match, from
1 up to however many groups are in the pattern. The default
argument is used for groups that did not participate in the
match; it defaults to None. (Incompatibility note: in the
original Python 1.5 release, if the tuple was one element
long, a string would be returned instead. In later versions
(from 1.5.1 on), a singleton tuple is returned in such cases.)

Since you don't have any groups in your re, groups is always going to
return (). You probably want group().

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Proposal for adding symbols within Python

2005-11-12 Thread Pierre Barbier de Reuille
Please, note that I am entirely open for every points on this proposal
(which I do not dare yet to call PEP).

Abstract


This proposal suggests to add symbols into Python.

Symbols are objects whose representation within the code is more
important than their actual value. Two symbols needs only to be
equally-comparable. Also, symbols need to be hashable to use as keys of
dictionary (symbols are immutable objects).

Motivations
===

Currently, there is no obvious way to define constants or states or
whatever would be best represented by symbols. Discussions on
comp.lang.python shows at least half a dozen way to replace symbols.

Some use cases for symbols are : state of an object (i.e. for a file
opened/closed/error) and unique objects (i.e. attributes names could be
represented as symbols).

Many languages propose symbols or obvious ways to define symbol-like
values. For examples in common languages:

In C/C++ : Symbols are emulated using Enums.
In Haskell/OCaml : Symbols are defined by union types with empty
constructors. Symbols are local to modules.
In Prolog : Symbols are called atoms ... they are local to modules (at
least in swi-prolog)
In Ruby : Symbols are introduced be the : notation. :open is a
symbol. Symbols are global.
In LISP : Symbols are introduced by '. 'open is a symbol. Symbols
are local to modules.

Proposal


First, I think it would be best to have a syntax to represent symbols.
Adding some special char before the name is probably a good way to
achieve that : $open, $close, ... are $ymbols.

On the range of symbols, I think they should be local to name space
(this point should be discussed as I see advantages and drawbacks for
both local and global symbols). For example, for the state of the file
object I would write :

 file.$open, file.$close, file.$error

Then, given some other objects (say some other device which also may be
opened) :

 assert f.state != dev.state

would always hold if both objects use locally-defined symbols. The only
way for these states to be equal would be, for example, for the device
object to explicitly assign the file symbols :

 dev.state = file.$open

By default, symbols should be local to the current module. Then, being
in the module device_manager, this would hold:

 assert $opened == device_manager.$opened

There should be a way to go from strings to symbols and the other way
around. For that purpose, I propose:

 assert symbol(opened) == $opened
 assert str($opened) == opened

Implementation
==

One possible way to implement symbols is simply with integers resolved
as much as possible at compile time.

The End
===

Thanks to those who read entirely this proposal and I hope this proposal
will gather enough interests to become a PEP and someday be implemented,
maybe (probably?) in a completely different way ;)

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


Re: newbie how do I interpret this?

2005-11-12 Thread bobueland
Thanks for the reply

I didn't realise the meaning of built-in function. Also I thought
that help( ) mirrored the info in reference manual, which it obviously
does not. Thanks again for a good answer and the link.
Bob

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


Re: Python obfuscation

2005-11-12 Thread Mike Meyer
Paul Rubin http://[EMAIL PROTECTED] writes:
 The Eternal Squire [EMAIL PROTECTED] writes:
 Without copyright, how could one possibly earn a living writing a
 novel?  
 This guy seems to be doing ok:  http://craphound.com
 His publishers are the only ones allowed to sell his novels commercially,
 but you can download them all and print them out noncommercially for
 your own personal enjoyment or to share with your friends.  No obfuscation
 is needed.

Not really a good counterexample, because His publishers are the only
ones allowed to sell his novels commercially is only possible because
of copyright. Without that, anyone could take the downloadable copy of
his novels and start competing with his publishers - presumably with
lower overhead, because they didn't have to pay Cory.

Asking about novels is an excellent question - it's one of the few
forms of copyrightable material where it's not the final end product
and you have to give the public access to the media for them to use
it. If either one of those isn't true, you can probably find a
business model that doesn't depend on copyright.

   mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: weird problem with os.chmod

2005-11-12 Thread Mardy
On Fri, 11 Nov 2005 16:49:23 -0800, James Colannino wrote:
 Ok, so now I have a very interesting problem, this time related to 
 os.chmod.  I have the following in a text file: 0600.  My script reads 
 that number as a string and converts it to an integer for use with 
 chmod.  However, when I do this, instead of the rw-- permissions 

0600 is the octal representation of 384. man chmod should help you.
Just use
   perm = int(string, 8)
instead of
   perm = int(string)
when converting to int the string you read from the file.


-- 
Saluti,
Mardy
http://interlingua.altervista.org

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


Re: Hash map with multiple keys per value ?

2005-11-12 Thread Alex Martelli
Chris Stiles [EMAIL PROTECTED] wrote:

 snoe [EMAIL PROTECTED] writes:
  Are you looking for this type of thing?
 
  class Test:
  value = 900
 
 No, what I'm trying to do is this, assume two sets of aliases:
 
 a, b, c, d and e
 
 x, y and z
 
 a returns b c d and e, b returns a c d and e, x returns y and z, y returns x
 and z etc.
 
 Where any of the sets of aliases can grow or shrink at any time.

So, it seems a reasonable underlying representation would be a mapping
from item to set of items.  Keeping N different sets for a set of N
aliases would appear a bit wasteful of memory (it's hard to say without
knowing usecases and performance desiderata...), so you might have all
aliases map to the same set of aliases and dynamically construct the
required result by subtracting the lookup key itself.

Another design issue is, however, how do you identify, when adding an
alias, what it's an alias of -- from previous posts I'll assume that all
aliases are 'names' for some (hopefully hashable) object, so we'll also
need a mapping from said object back to its set of aliases.  Or, would
alias insertion just be of the form x aliases to y rather than x
names object XXX?

Also not clarified in terms of specs: when an alias is inserted, do you
need to check if it was already an alias for something else (in another
set) and [a] raise an exception or [b] silently remove it from the
previous set?  That applies to the x names object XXX style but not
necessarily to the x aliases y style, unless in the latter case you
want to say ...replacing any previous aliases of x to change rather
than merge alias-sets.  But it would then seem simpler to simply have a
separate removal function x doesn't alias to anything any longer, to
be optionally called before the insertion method.

So, I think there are enough questions open about the specs to warrant
more exploration.  Under some given set of interpretations for the above
open questions, you might have, e.g. (untested code, and no special
attention paid to performance):

class Aliases(object):
  def __init__(self):
 self.d = {}
  def lookup(self, x):
 if x in self.d:
   return self.d[x]-set([x])
 else:
   return set()
  def alias(self, x, y):
 dx = self.d.get(x,set([x]))
 dy = self.d.get(y,set([y]))
 self.d[x]=self.d[y]=dx+dy
  def unalias(self, x):
  if x in self.d:
  self.d[x].remove(x)
  if not self.d[x]: del self.d[x]

Perhaps by working on this concrete example (which likely has bugs,
being untested, and even more likely misinterpret some specs, since I'm
having to guess at quite a few details) you can nail down the exact kind
of API syntax and semantics that you require...?  Once the specs are
entirely clear, we might (if needed) worry about efficiency, but that
seems somewhat premature at this stage...


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


Re: Hash map with multiple keys per value ?

2005-11-12 Thread Bengt Richter
On Fri, 11 Nov 2005 22:55:53 +, Chris Stiles [EMAIL PROTECTED] wrote:

Hi --

I'm working on something that includes the concept of multiple aliases for a
particular object, where a lookup for any of the aliases has to return all the
others.  The hack way of doing this was to have a dictionary where each 
entry consisted of a list of all the aliases - with multiple references to the
same list from the various dictionary entries corresponding to each alias.
What about the particular object in this? If all the aliases refer to the
particular object, what does return all the others mean? All _what_ 
others?
All refer to the same particular object. Or do you want the names? If so,
What about the particular object? Or do you want a dict back that has all the
other alias names as keys all referring to the particular object? E.g.,

  class Aliad(dict):
 ... def __getitem__(self, key):
 ... keyval = dict.__getitem__(self, key)
 ... return Aliad((k,v) for k,v in self.items() if k!=key and v is 
keyval)
 ...
  po = 'particular object'
  ad = Aliad(x=po, y=po, z=po)
  ad
 {'y': 'particular object', 'x': 'particular object', 'z': 'particular object'}
  ad['x']
 {'y': 'particular object', 'z': 'particular object'}
  ad['y']
 {'x': 'particular object', 'z': 'particular object'}
  ad['z']
 {'y': 'particular object', 'x': 'particular object'}
 
  po2 = 'alpha'
  ad.update(a=po2, b=po2, c=po2, d=po2, e=po2)
  ad['x']
 {'y': 'particular object', 'z': 'particular object'}
  ad['a']
 {'c': 'alpha', 'b': 'alpha', 'e': 'alpha', 'd': 'alpha'}
  ad['b']
 {'a': 'alpha', 'c': 'alpha', 'e': 'alpha', 'd': 'alpha'}

And since an Aliad instance is being returned,

  ad['a']
 {'c': 'alpha', 'b': 'alpha', 'e': 'alpha', 'd': 'alpha'}
  ad['a']['e']
 {'c': 'alpha', 'b': 'alpha', 'd': 'alpha'}
  ad['a']['e']['b']
 {'c': 'alpha', 'd': 'alpha'}
  ad['a']['e']['b']['c']
 {'d': 'alpha'}
  ad['a']['e']['b']['d']
 {'c': 'alpha'}


Is there an easier and cleaner way of doing this ?  Is there example code
floating around that I might have a look at ?
Please show _any_ example code that does (tested ;-) _exactly_ what you want.
Then we can try for an easier and cleaner way ;-)

Hope the above helps to clarify requirements one way or another ;-)

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


Re: weird problem with os.chmod

2005-11-12 Thread Bengt Richter
On Sat, 12 Nov 2005 12:53:17 +0100, Fredrik Lundh [EMAIL PROTECTED] wrote:
[...]
int is designed for humans, not C programmers.  humans tend to view
e.g. 08 as a valid decimal number (*), not a ValueError.
[...]
/F

*) unless you're living in sweden, in which case 08 is quite often used
as an insult.

I am always curious about languages, and considering my name, I think I'd
like to know this definition ;-) Is it telephone-exchange-related?
Or a police code for something? Can you say, delicately?
(jag stavar daligt, men det gar bra pa Svenska om det ar omogligt at oversatta 
;-)

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


Re: Tkinter and the re/sizing of columns in a grid

2005-11-12 Thread jepler
Normally, an entry widget requests horizontal space equal to the value of the
width= option times the average character width of the font it displays.

Setting it to 0 makes the entry request exactly enough width to show the string
it contains.

Making them sticky to the east and west sides of their areas make them grow
to the size of the grid cell, if it is larger than their requested size.

Making the grid column have nonzero weight means that if the user resizes
the window to be wider, extra space will be given to the entry widgets.

Perhaps this program does what you're looking for:
#---
from Tkinter import *

t = Tk()
l1 = Label(t, text=String 1:)
l2 = Label(t, text=String 2:)
e1 = Entry(t, width=0); e1.insert(end, eggs); e1.focus()
e2 = Entry(t, width=0); e2.insert(end, spam)

l1.grid(row=0, column=0, sticky=w)
l2.grid(row=1, column=0, sticky=w)
e1.grid(row=0, column=1, sticky=ew)
e2.grid(row=1, column=1, sticky=ew)

t.grid_columnconfigure(1, weight=1, minsize=120)
t.wm_title(entry width demo)
t.mainloop()
#---


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

Re: directory listing

2005-11-12 Thread [EMAIL PROTECTED]
Shi Mu:

Before all you were doing was defining a function with:
import os

def buildList( directory='c:\TEMP' ):
dirs = [ ]
listing = os.listdir(directory)
for x in listing:
x = os.path.join(directory, x)
print x
if os.path.isdir(x):
dirs.append(x)
return dirs

when you python this file, it does not execute the function, it only
defines it.
Later Lundh told you to add:
print buildList()

to the end of the file.  Not only does this execute buildList() but it
also prints out the list dirs that buildList returns.  So the first
time it wasn't that print x wasn't printing anything, it was only
that you weren't executing the function buildList().  If, at the end of
the file, you put buildList()  you will only see output values
corresponding to the print x statement

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


Re: how to present Python's OO feature in design?

2005-11-12 Thread Florian Diesch
Ben Sizer [EMAIL PROTECTED] wrote:
 I don't know if there are any tools that convert UML to Python code,

dia2code http://dia2code.sourceforge.net


   Floriaa
-- 
Einen Troll zu füttern ist das gleiche als würde man einen Haufen
Hundescheisse sehen, absichtlich reinsteigen und sich dann beschweren.
(Christian Schneider in [EMAIL PROTECTED])
-- 
http://mail.python.org/mailman/listinfo/python-list


Problem with __str__ if baseclass is list

2005-11-12 Thread Edward C. Jones
#! /usr/bin/env python

class A(list):
 def __init__(self, alist, n):
 list.__init__(self, alist)
 self.n = n

 def __str__(self):
 return 'AS(%s, %i)' % (list.__str__(self), self.n)

 def __repr__(self):
 return 'AR(%s, %i)' % (list.__repr__(self), self.n)

a = A(['x', 'y'], 7)

print 1, a
print 2, repr(a)
print 3, list.__str__(a)
print 4, list.__repr__(a)


The output is:

1 AS(AR(['x', 'y'], 7), 7)
2 AR(['x', 'y'], 7)
3 AR(['x', 'y'], 7)
4 ['x', 'y']

Why is list.__str__(a) == AR(['x', 'y'], 7)?

Note: The problem goes away if list.__str__(a) is replaced with
list.__repr__(self).

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


XUL behavior in Python via XPCOM, Mozilla

2005-11-12 Thread Terry Hancock
I recently saw a claim that Mozilla XUL behaviors (normally
scripted in Javascript) can (or perhaps will) be scriptable
in Python.

Also, other languages such as Java or Python are supported
through XPCOM, said about Mozilla (from Luxor website).

Yes, I know several ways to *generate* XUL from Python, and
at least one way to use XUL to create interfaces for Python
programs, but in this case, I'm talking about defining
button action behavior in XUL by calling Python scripts.

I know that Javascript is the preferred language, but I've
seen several references to being able to do this in Python,
including a claim that a release was targeted for early
November (2005), to provide this.

Now I can't find it again.  Anyway, I was hoping someone
on c.l.p / python.org would have a reliable reference on
this.

Thanks,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: SciPy python 2.4 wintel binaries

2005-11-12 Thread Peter Maas
jelle schrieb:
 I dearly miss having the power of SciPy on my python 2.4 installation.
 The topic of SciPy python 2.4 wintel binaries has been discussed before
 on this list, but I haven't been able to find a compiled binary.

If you really need SciPy, you should install Python 2.3 (Enthought Edition)
in a separate directory as long as a Python 2.4 SciPy binary is not available.
Python 2.3 EE comes with a bunch of useful additions, e.g. SciPy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: XUL behavior in Python via XPCOM, Mozilla

2005-11-12 Thread Jean-Paul Calderone
On Sat, 12 Nov 2005 14:25:51 -0600, Terry Hancock [EMAIL PROTECTED] wrote:
I recently saw a claim that Mozilla XUL behaviors (normally
scripted in Javascript) can (or perhaps will) be scriptable
in Python.

Also, other languages such as Java or Python are supported
through XPCOM, said about Mozilla (from Luxor website).

Yes, I know several ways to *generate* XUL from Python, and
at least one way to use XUL to create interfaces for Python
programs, but in this case, I'm talking about defining
button action behavior in XUL by calling Python scripts.

I know that Javascript is the preferred language, but I've
seen several references to being able to do this in Python,
including a claim that a release was targeted for early
November (2005), to provide this.

Now I can't find it again.  Anyway, I was hoping someone
on c.l.p / python.org would have a reliable reference on
this.

I'm not sure which claim you read, but perhaps it was in reference to PyXPCOM?  
http://aspn.activestate.com/ASPN/Downloads/Komodo/PyXPCOM/

I'm not quite sure if you are looking for the product itself or the 
announcement about it.  Anyway, hope this helps.

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


Re: XUL behavior in Python via XPCOM, Mozilla

2005-11-12 Thread Fredrik Lundh
Terry Hancock wrote:

I recently saw a claim that Mozilla XUL behaviors (normally
 scripted in Javascript) can (or perhaps will) be scriptable
 in Python.

 Also, other languages such as Java or Python are supported
 through XPCOM, said about Mozilla (from Luxor website).

 Yes, I know several ways to *generate* XUL from Python, and
 at least one way to use XUL to create interfaces for Python
 programs, but in this case, I'm talking about defining
 button action behavior in XUL by calling Python scripts.

 I know that Javascript is the preferred language, but I've
 seen several references to being able to do this in Python,
 including a claim that a release was targeted for early
 November (2005), to provide this.

 Now I can't find it again.  Anyway, I was hoping someone
 on c.l.p / python.org would have a reliable reference on
 this.

mozilla xul python + I feel lucky =

http://weblogs.mozillazine.org/roadmap/archives/008865.html

Python for XUL will be available in the Mozilla 1.9 milestone time
frame, when the DOM_AGNOSTIC_BRANCH is landed some
time this calendar year for sure /.../ The next major Firefox release
based on the 1.9 milestone (Firefox 1.5 is based on the Mozilla 1.8
milestone) will include Mark's work -- but not a C-Python en-
vironment by default.

also see

http://www.mozilla.org/roadmap/gecko-1.9-roadmap.html#Python_for_XUL

(which says the same thing)

/F 



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


Re: XUL behavior in Python via XPCOM, Mozilla

2005-11-12 Thread Devan L
Terry Hancock wrote:
 I recently saw a claim that Mozilla XUL behaviors (normally
 scripted in Javascript) can (or perhaps will) be scriptable
 in Python.

 Also, other languages such as Java or Python are supported
 through XPCOM, said about Mozilla (from Luxor website).

 Yes, I know several ways to *generate* XUL from Python, and
 at least one way to use XUL to create interfaces for Python
 programs, but in this case, I'm talking about defining
 button action behavior in XUL by calling Python scripts.

 I know that Javascript is the preferred language, but I've
 seen several references to being able to do this in Python,
 including a claim that a release was targeted for early
 November (2005), to provide this.

 Now I can't find it again.  Anyway, I was hoping someone
 on c.l.p / python.org would have a reliable reference on
 this.

 Thanks,
 Terry

 --
 Terry Hancock ([EMAIL PROTECTED])
 Anansi Spaceworks http://www.AnansiSpaceworks.com

Nufox?
http://trac.nunatak.com.au/projects/nufox

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


Re: tutorial example

2005-11-12 Thread Colin J. Williams
Max Erickson wrote:
 Not in python.
 
 For example, what would you call the following?
 
 def rsum(n, m):
 print n+m
 return n+m
 
I would call it a python function with a side-effect.

Colin W.
 
 In python a method is callable attached to an object. A function is a 
 callable object constructed with a def statement.
 
 max
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Proposal for adding symbols within Python

2005-11-12 Thread Ben Finney
Pierre Barbier de Reuille [EMAIL PROTECTED] wrote:
 This proposal suggests to add symbols into Python.

I still don't think symbol is particularly descriptive as a name;
there are too many other things already in the language that might
also be called a symbol.

 Symbols are objects whose representation within the code is more
 important than their actual value.

An interesting 

 Two symbols needs only to be equally-comparable.

I believe it would be more useful to have enumerated types in Python,
which would also allow values from the same type to be cmp() compared.

 Currently, there is no obvious way to define constants or states or
 whatever would be best represented by symbols.

constants isn't a good equivalent here, since constants in most
other languages are all about the name-to-value mapping, which you
said was unimportant for this concept.

 Discussions on comp.lang.python shows at least half a dozen way to
 replace symbols.

s/replace/implement/

 Some use cases for symbols are : state of an object (i.e. for a file
 opened/closed/error) and unique objects (i.e. attributes names could
 be represented as symbols).

That pretty much covers the common use cases. Nicely done.

 First, I think it would be best to have a syntax to represent
 symbols.

I disagree. Namespaces would be fine, and would also make clear which
values were related to each other; e.g. for your state of an object
use case, it's useful to have all the states in one namespace,
separate from unrelated states of other classes of objects.

 Adding some special char before the name is probably a good way to
 achieve that : $open, $close, ... are $ymbols.

Counterproposal:

FileState = SomeTypeDefiningStates( 'open', 'closed' )

thefile.state = FileState.open
if thefile.state == FileState.closed:
print File is closed

So all that's needed here is the type SomeTypeDefiningStates, not a
new syntax.

 One possible way to implement symbols is simply with integers
 resolved as much as possible at compile time.

I believe all your requirements and motivations could be met with an
Enum type in the language. Here's an implementation using a sequence
of integers for the underlying values:

First Class Enums in Python
URL:http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486

An enumerated type would also allow values from that type to be
compared with cmp() if their sequence was considered important. e.g.
for object state, the normal sequence of states could be represented
in the enumeration, and individual states compared to see if they are
later that each other. If sequence was not considered important, of
course, this feature would not get in the way.

-- 
 \  I put instant coffee in a microwave oven and almost went back |
  `\   in time.  -- Steven Wright |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


How to avoid f.close (no parens) bug?

2005-11-12 Thread o



plez send me

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

Re: Proposal for adding symbols within Python

2005-11-12 Thread Mike Meyer
Pierre Barbier de Reuille [EMAIL PROTECTED] writes:
 Please, note that I am entirely open for every points on this proposal
 (which I do not dare yet to call PEP).

 Abstract
 

 This proposal suggests to add symbols into Python.

You're also proposing adding a syntax to generate symbols. If so, it's
an important distinction, as simply addig symbols is a lot more
straightforward than adding new syntax.

 Symbols are objects whose representation within the code is more
 important than their actual value. Two symbols needs only to be
 equally-comparable. Also, symbols need to be hashable to use as keys of
 dictionary (symbols are immutable objects).

The values returned by object() meet this criteria. You could write
LISPs gensym as:

  gensym = object

As you've indicated, there are a number of ways to get such
objects. If all you want is symbols, all that really needs to happen
is that one of those ways be blessed by including an implementation in
the distribution.

 In LISP : Symbols are introduced by '. 'open is a symbol.

No, they're not. '(a b c) is *not* a symbol, it's a list. Symbols in
LISP are just names. open is a symbol, but it's normally evaluated.
The ' is syntax that keeps the next expression from being evaluated,
so that 'open gets you the symbol rather than it's value. Since
you're trying to introduce syntax, I think it's important to get
existing practice in other languages right.

 Proposal
 

 First, I think it would be best to have a syntax to represent symbols.

That's half the proposal.

 Adding some special char before the name is probably a good way to
 achieve that : $open, $close, ... are $ymbols.

$ has bad associations for me - and for others that came from an
earlier P-language. Also, I feel that using a magic character to
introduce type information doesn't feel very Pythonic.

While you don't make it clear, it seems obvious that you intend that
if $open occurs twice in the same scope, it should refer to the same
symbol. So you're using the syntax for a dual purpose. $name checks to
see if the symbol name exists, and references that if so. If not, it
creates a new symbol and with that name. Having something that looks
like a variables that instantiates upon reference instead of raising
an exception seems like a bad idea.

 On the range of symbols, I think they should be local to name space
 (this point should be discussed as I see advantages and drawbacks for
 both local and global symbols).

Agreed. Having one type that has different scoping rules than
everything else is definitely a bad idea.

 There should be a way to go from strings to symbols and the other way
 around. For that purpose, I propose:

 assert symbol(opened) == $opened
 assert str($opened) == opened

So the heart of your proposal seems to be twofold: The addition of
symbol as a type, and the syntax that has the lookup/create behavior
I described above.

 Implementation
 ==

 One possible way to implement symbols is simply with integers resolved
 as much as possible at compile time.

What exactly are you proposing be resolved at compile time? How is
this better than using object, as illustratd above?

Suggested changes:

Provide a solid definition for the proposed builtin type symbol.
Something like:

  symbol objects support two operations: is and equality
  comparison. Two symbol objects compare equal if and only if
  they are the same object, and symbol objects never compare
  equal to any other type of object. The result of other
  operations on a symbol object is undefined, and should raise
  a TypeError exception.

  symbol([value]) - creates a symbol object. Two distinct
  calls to symbol will return two different symbol objects
  unless the values passed to them as arguments are equal, in
  which case they return the same symbol object. If symbol is
  called without an argument, it returns a unique symbol.

I left the type of the value argument unspecified on purpose. Strings
are the obvious type, but I think it should be as unrestricted as
possible. The test on value is equality, not identity, because two
strings can be equal without being the same string, and we want that
case to give us the same symbol. I also added gensym-like behavior,
because it seemed useful. You could do without equality comparison,
but it seems like a nice thing to have.

Now propose a new syntax that means symbol, ala {} meaning dict
and [] meaning list. Don't use $name ( and ^ are also probably
bad, but not as; pretty much everything else but ? is already in
use). Python does seem to be moving away from this kind of thing,
though.

Personally, I think that the LISP quote mechanism would be a better
addition as a new syntax, as it would handle needs that have caused a
number of different proposals to be raised.  It would require that
symbol know about the internals of the implementation so that ?name
and 

Re: Can't uninstall wxPython

2005-11-12 Thread Robert Hicks

Justin wrote:
 I have two versions of wxPython installed on my Mac (OS X Tiger).  One
 is version 2.6.1.0 and the other is version 2.6.0.0.  I want to keep
 the newer version, but I can't seem to uninstall either one using the
 uninstall_wxPython.py script.

 When I run that script, I get this error message:
   $ sudo: uninstall_wxPython.py: command not found

 Is there any way I could delete one, or both, of these installations
 manually?  For some reason, whenever I try to run a wxPython script, it
 uses the older version of wxPython and it doesn't always run correctly.

 Thanks in advance.

If it has the x bit set  you will have to do something like this:

sudo ./uninstall_wxPython.py

Otherwise pass python explicitly:

sudo python uninstall_wxPython.py

I think that it is going to wipe out all your wxPython installs...so
you will need to reinstall the version you wanted.

HTH,

Robert

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


Re: weird problem with os.chmod

2005-11-12 Thread Fredrik Lundh
Bengt Richter wrote:

 *) unless you're living in sweden, in which case 08 is quite often used
 as an insult.

 I am always curious about languages, and considering my name, I think I'd
 like to know this definition ;-) Is it telephone-exchange-related?

it's the area code for Stockholm. I think you can figure the rest out
yourself ;-)

 ... det gar bra pa Svenska om det ar omogligt at oversatta ;-)

här finns lite mer bakgrund:

http://susning.nu/Noll%E5tta
http://susning.nu/Stockholmare

/F



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

Re: Proposal for adding symbols within Python

2005-11-12 Thread Bengt Richter
On Sat, 12 Nov 2005 16:52:12 -0500, Mike Meyer [EMAIL PROTECTED] wrote:
[...]
Personally, I think that the LISP quote mechanism would be a better
addition as a new syntax, as it would handle needs that have caused a
number of different proposals to be raised.  It would require that
symbol know about the internals of the implementation so that ?name
and symbol(name) return the same object, and possibly exposing said
object to the programmer. And this is why the distinction about how
LISP acts is important.
I wonder if the backquote could be deprecated and repurposed.
It could typographically serve nicely as a lisp quote then. But in python,
how would 'whatever be different from lambda:whatever ?
(where of course whatever could be any expression parenthesized
as necessary)

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


Re: XUL behavior in Python via XPCOM, Mozilla

2005-11-12 Thread Terry Hancock
On Sat, 12 Nov 2005 15:27:01 -0500
Jean-Paul Calderone [EMAIL PROTECTED] wrote:

 On Sat, 12 Nov 2005 14:25:51 -0600, Terry Hancock
 [EMAIL PROTECTED] wrote:
 I recently saw a claim that Mozilla XUL behaviors
 (normally scripted in Javascript) can (or perhaps will)
 be scriptable in Python.
 
 Also, other languages such as Java or Python are
 supported through XPCOM, said about Mozilla (from Luxor
 website).

 I'm not sure which claim you read, but perhaps it was in
 reference to PyXPCOM? 
 http://aspn.activestate.com/ASPN/Downloads/Komodo/PyXPCO
 M/
 
 I'm not quite sure if you are looking for the product
 itself or the announcement about it.  Anyway, hope this
 helps.

Really, I'm just fact-checking. It was the Brenden Eich
article that Fredrik Lundh pointed to that I had found
before, I was trying to recover it (turns out python xul
mozilla + I feel lucky does NOT find it ;-), though it is
on the first page, I admit).

I wanted to get an idea of 

1) When it would *really* be available

2) What developers or users would need to install in
order to actually use a Python/XUL/Mozilla application.

3) Whether there was a version available that anyone here
had tried, and what their experience was like.

4) Can you do this now, using PyXPCOM and the regular
Mozilla/XUL?

I'm refering to this in an article in press for Free
Software Magazine, and I wanted to see just how close this
really was to happening. If it's likely to be released in
the next month or three, then it will probably come out
before the article goes to press. It's not a huge point, but
I hate to get stuff like this wrong.

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: XUL behavior in Python via XPCOM, Mozilla

2005-11-12 Thread Terry Hancock
On 12 Nov 2005 12:47:58 -0800
Devan L [EMAIL PROTECTED] wrote:
 Nufox?
 http://trac.nunatak.com.au/projects/nufox
Nufox is a server-side tool to *generate* XUL from Python.

Luxor
http://luxor-xul.sourceforge.net/
is a XUL-interpreter written in Python, which
therefore *replaces* Mozilla for XUL-based GUI applications.
It scripts in Python or Java by default.

But then there's the announcement at
http://weblogs.mozillazine.org/roadmap/archives/008865.html
by Brenden Eich that will use the PyXPCOM work by Mark
Hammond to put python scripting capability into the Mozilla
XUL engine, so that you can use
script=application/x-python in order to do behavior
scripting in Python from within XUL running on top of
Mozilla.

I was also a little foggy about the relationship between
these components (which I hope I've just spelled out for the
record).

Thanks for the replies,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: UART parity setting as mark or space (using Pyserial???)

2005-11-12 Thread Petr Jakes
To provide feedback:

I have found the way how to control serial port parity bit on the Linux
(how to set the parity bit to the mark or space parity) within
Python using termios module.

With the help of:
http://www.lothosoft.ch/thomas/libmip/markspaceparity.php
===
import serial
import termios
import TERMIOS

ser=serial.Serial('/dev/ttyS0', 9600, 8, N, timeout=1)

iflag, oflag, cflag, lflag, ispeed, ospeed, cc = termios.tcgetattr(ser)

cflag |= PARENB | CMSPAR # To select SPACE parity
cflag = ~PARODD

cflag |= PARENB | CMSPAR | PARODD # to select MARK parity

termios.tcsetattr(ser, termios.TCSANOW, [iflag, oflag, cflag, lflag,
ispeed, ospeed, cc])
===
Using above mentioned it is possible to establish 9bit serial
communication according to the given protocol specifics. It is
necessary to control parity bit setting before sending each
communication byte.

Regards

Petr Jakes

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


Re: gmpy 1.01 rc near... anybody wanna test

2005-11-12 Thread [EMAIL PROTECTED]

[EMAIL PROTECTED] wrote:
 What processor are you running?

Drat, didn't see this before I left work. I'm fairly certain it was a
Pentium 4, definitely 1.7GHz, Win2000 and Python 2.3.

So I thought I would run the test again on my home computers,
a Pentium 4 1.5 GHz WinXP Python 2.3 and a laptop with a
Celeron 2.8 GHz WinXP Python 2.4.

Here are the Celeron/Python2.4 numbers (and original test times)

BF: 27.89 sec  gen6  (31.92)
CF: 0.203 sec  gen9  (0.234)
 V: 5.062 sec  gen9  (8.766)


 I only have Windows running on an old Pentium 3. It is easy for me to
 build a version that will running on almost any recent processor. I'm
 willing to try and override the CPU detection and make a processor
 specific build for you. I won't be able to test it, though.
 
 Thanks for the testing!
 
 Case

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


Multikey Dict?

2005-11-12 Thread David Rasmussen
If I have a collection of dicts like:

john = {'id': 1, 'name': John Cleese, 'year': 1939}
graham = {'id': 2, 'name': Graham Chapman, 'year': 1941}

I could store all of them in a list. But for easy lookup, I might store 
all these in a dict instead, like

people = {'1': john, '2': graham}

or maybe

people = {'John Cleese': john, 'Graham Chapman': graham}

or whatever key I might choose. Now, first of all, it seems a bit 
annoying that I have to keep that redundant data in the second dict that 
is already in the individual dicts within people. Secondly (and this is 
my question), it is annoying that I have to choose one of several 
unambiguous keys as a key.

I would like to be able to say:

people['1'].year

in some case and in other cases I want to say

people['John Cleese'].year

That is, sometimes I have the name at hand and would like to look up 
data based on that. Other times, I have the ID at hand and would like to 
look up data based on that instead.

Also, I would like if I didn't have to keep the key data both in the 
dict of dicts and in the dicts :)

If I could just say to Python: john and graham (and ...) are all a part 
of a superdict and either their id or their name can be used as keys.

Can I do that somehow?

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


ANN: askmgr

2005-11-12 Thread aum
Hi all,

I've just released a gui-based management utility for Active Spam Killer
(ASK) installations.

ASKmgr gives a quick and convenient way to manage one's ASK installation,
including whitelists, ignorelists, blacklists, message queue and message
log.

(Fqr those not familiar, ASK is a powerful anti-spam system that works on
whitelists, blacklists and a challenge-response system. It leaves
Bayesian-based spamfilters in the dust, and has reduced my spam inflow
from 4k+/week to 15/week.

Posted on-topic here because both ASK and ASKmgr are written in
Python.

http://www.freenet.org.nz/askmgr2

-- 
Cheers
aum


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


Re: gmpy 1.01 rc near... anybody wanna test

2005-11-12 Thread [EMAIL PROTECTED]
[EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  What processor are you running?

 Drat, didn't see this before I left work. I'm fairly certain it was a
 Pentium 4, definitely 1.7GHz, Win2000 and Python 2.3.

 So I thought I would run the test again on my home computers,
 a Pentium 4 1.5 GHz WinXP Python 2.3 and a laptop with a
 Celeron 2.8 GHz WinXP Python 2.4.

 Here are the Celeron/Python2.4 numbers (and original test times)

 BF: 27.89 sec  gen6  (31.92)
 CF: 0.203 sec  gen9  (0.234)
  V: 5.062 sec  gen9  (8.766)


Oops, accidentally hit the send button. I didn't give you the
results from my home desktop machine. And those are
interesting.

I did not intend for this test to be a benchmark, simply to
make sure gmpy (and my library of Collatz Functions) were
working properly. Can you imagine my shock at the reults
of the closed form test:

gmpy.version: 1.01

Closed form: Type12MH(k,i)
Find ith, kth Generation Type [1,2] Mersenne Hailstone
using the closed form equation

2**(6*((i-1)*9**(k-1)+(9**(k-1)-1)/2+1)-1)-1

2**5-1  generation: 1 0 seconds
   2**29-1  generation: 2 0 seconds
  2**245-1  generation: 3 0.015 seconds
 2**2189-1  generation: 4 0 seconds
2**19685-1  generation: 5 0 seconds
   2**177149-1  generation: 6 0.219 seconds
  2**1594325-1  generation: 7 29.22 seconds
 2**14348909-1  generation: 8 5295 seconds

That's 88 minutes for the gen8 test alone (gen9 is still running).
I was expecting a quarter second for the entire test! I realize that
my office pc and my home pc are configured differently but there
shouldn't be that much difference with the same version of Python
and gmpy.

At first I thought it was locking up, but it didn't have the symptoms
of a lockup: menus still worked, Task manager didn't report not
responding, and sure enough, it completed gen7 eventually.

I finally figured it out, though. I had been toying with my Collatz
Functions and made what I thought was a trivial change:

Original function
def Type12MH(k,i):
Find ith, kth Generation Type [1,2] Mersenne Hailstone
using the closed form equation

Type12MH(k,i)
k: generation
i: member of generation
returns Hailstone (a)

if (k1) or (i1): return 0
a = (i-1)*9**(k-1) + (9**(k-1) - 1)/2 + 1
return 2**(6*a - 1) - 1

Now I know better than to allow coersion to mpz's to take place
inside a loop, but this function doesn't loop. Nevertheless, I changed
it to

def Type12MH(k,i):
Find ith, kth Generation Type [1,2] Mersenne Hailstone
using the closed form equation

Type12MH(k,i)
k: generation
i: member of generation
returns Hailstone (a)

ONE = gmpy.mpz(1)
TWO = gmpy.mpz(2)
SIX = gmpy.mpz(6)
NIN = gmpy.mpz(9)

if (k1) or (i1): return 0

i = gmpy.mpz(i)
k = gmpy.mpz(k)

# a = (i-1)*9**(k-1) + (9**(k-1) - 1)/2 + 1
# return 2**(6*a - 1) - 1

a = (i-ONE)*NIN**(k-ONE) + (NIN**(k-ONE) - ONE)/TWO + ONE
return TWO**(SIX*a - ONE) - ONE

And this was what is making my home desktop run so slow
(at least with mega-bit sized numbers). As soon as I updated the
Collatz Library, I got normal reults:

BF: 37.11 sec  gen6
CF: 0.563 sec  gen9
 V: 1.093 sec  gen9

(Verified by setting it back to original.)

Wow. Didn't realize things were that sensitive. Looks like I'll
have to review a lot of my programs.

 
  I only have Windows running on an old Pentium 3. It is easy for me to
  build a version that will running on almost any recent processor. I'm
  willing to try and override the CPU detection and make a processor
  specific build for you. I won't be able to test it, though.
  
  Thanks for the testing!
  
  Case

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


Re: Python obfuscation

2005-11-12 Thread Steven D'Aprano
On Sat, 12 Nov 2005 12:22:21 -0500, Mike Meyer wrote:

 And if instead you lose one customer because you've denied them their
 fair use rights, then your copy protection has lost you more in the
 form of a cost that you overlooked than all the costs you actually
 considered.

In a competitive marketplace, why would I choose to buy DRMed software if
there is a non-DRMed equivalent with the same functionality and equivalent
cost? DRM is both an extra cost and a lower functionality applied to the
software: an extra cost because if I can only run three simultaneous
instances when I want four, then I need to pay more; lower functionality
because things I may wish to do (like lock the original disk in the
fireproof safe and install off a backup copy) may be impossible.

If you are supplying to a non-competitive market, you may decide that you
don't mind losing some sales. In non-competitive markets, the pressure to
improve the ratio of functionality to cost is weak.

[snip]

 Actually, obfuscation by itself has *no* benefit. If all you do is
 obfuscate the code, none of the pirates will ever notice - they'll just
 copy the code without ever trying to read it. It's the copy protection
 mechanisms you're trying to obfuscate that gains you the alleged
 benefit. 

I don't think you mean copy protection, as in preventing copies -- it is
difficult for an application to prevent the OS from making physical
copies, and by difficult I mean essentially impossible. Perhaps you mean
access control, for example the software will only run for three people
simultaneously.

 Once you provide a copy protection mechanism, obfuscation has
 some benefit, though the costs aren't clearly minimal, not if you're a
 cometent engineer. It's the benefits of the copy protection that I claim
 are insignificant.

That's not quite true -- there may be instances where there is a real or
perceived benefit from keeping the algorithms used secret: perhaps you
have found a more efficient way to do something, or perhaps you just want
to hide from your users just how bad your code really is, or perhaps
you've conned^H^H^H^H convinced them to pay a premium price for reduced
functionality and don't want them bypassing your access control mechanisms.

The problem is, developers often have a ridiculously over-inflated opinion
of the worth of their code, and the business people behind them even more
so. Everybody[1] thinks that their two-bit Visual Basic calculator app is
going to be the next Microsoft Windows and make them a fortune, but only
if they keep the source code secret. Because so much code is secret,
people fail to appreciate just how little innovation there really is in
the IT industry, and imagine that just because they personally sweated
blood for months writing the code, it must be valuable.

Anyway, I think this is all a storm in a teacup. With the possible
exception of game console software, I think the idea of shrink-wrapped
software generally and software licencing particularly is a temporary
aberration. In a decade, software obfuscation will only exist as a way for
hackers to prove how clever they are, as in the Obfuscated C Contest.
Until then, well, if you think you can a commercial advantage by annoying
your customers, knock yourselves out.





[1] By everyone I mean lots of people who should know better.

-- 
Steven.

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


Re: Iterator addition

2005-11-12 Thread Tom Anderson
On Thu, 9 Nov 2005, it was written:

 [EMAIL PROTECTED] (Alex Martelli) writes:

 Is there a good reason to not define iter1+iter2 to be the same as

 If you mean for *ALL* built-in types, such as generators, lists, files,
 dicts, etc, etc -- I'm not so sure.

 Hmm, there might also be __add__ operations on the objects, that would 
 have to take precedence over iterator addition.  Iterator addition 
 itself would have to be a special kludge like figuring out  from 
 __cmp__, etc.

 Yeah, I guess the idea doesn't work out that well.  Oh well.

How about if we had some sort of special sort of iterator which did the 
right thing when things were added to it? like an iterable version of The 
Blob:

class blob(object):
def __init__(self, it=None):
self.its = []
if (it != None):
self.its.append(iter(it))
def __iter__(self):
return self
def next(self):
try:
return self.its[0].next()
except StopIteration:
# current iterator has run out!
self.its.pop(0)
return self.next()
except IndexError:
# no more iterators
raise StopIteration
def __add__(self, it):
self.its.append(iter(it))
return self
def __radd__(self, it):
self.its.insert(0, iter(it))

Then we could do:

all_lines = blob(file1) + file2 + file3
candidate_primes = blob((2,)) + (1+2*i for i in itertools.count(1))

Which, although not quite as neat, isn't entirely awful.

Another option would be a new operator for chaining - let's use $, since 
that looks like the chain on the fouled anchor symbol used by navies etc:

http://www.diggerhistory.info/images/badges-asstd/female-rels-navy.jpg

Saying a $ b would be equivalent to chain(a, b), where chain (which 
could even be a builtin if you like) is defined:

def chain(a, b):
if (hasattr(a, __chain__)):
return a.__chain__(b)
elif (hasattr(b, __rchain__)): # optional
return b.__rchain__(a)
else:
return itertools.chain(a, b) # or equivalent

Whatever it is that itertools.chain or whatever returns would be modified 
to have a __chain__ method which behaved like blob.__add__ above. This 
then gets you:

all_lines = file1 $ file2 $ file3
candidate_primes = (2,) $ (1+2*i for i in itertools.count(1))

And we're halfway to looking like perl already! Perhaps a more pythonic 
thing would be to define a then operator:

all_lines = file1 then file2 then file3
candidate_primes = (2,) then (1+2*i for i in itertools.count(1))

That looks quite nice. The special method would be __then__, of course.

tom

-- 
if you can't beat them, build them
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multikey Dict?

2005-11-12 Thread Sam Pointon
 If I could just say to Python: john and graham (and ...) are all a part
 of a superdict and either their id or their name can be used as keys.

 Can I do that somehow?

Sure you can. There are two obvious ways to do this - enlist the aid of
a Superdict (or similar) class to take care of the details. A simple
implementation would be:

class Superdict(object):

def __init__(self, by_id, by_name):
self.by_id = by_id
self.by_name = by_name

def __getitem__(self, value):
if value.isdigit():
return self.by_id[value]
else:
return self.by_name[value]


The alternative is to use some sort of database for storing these
values. It doesn't really matter which (hell, you could even reinvent a
relational wheel pretty simply in Python), as any DB worth its salt
will do exactly what you need.

Hope that helps,
 -Sam

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


elementtree.ElemenTree barfs on my Safari Cookies file

2005-11-12 Thread skip

Safari stores its cookies in XML format.  Looking to try and add support for
it to cookielib I started by first trying to parse it with Fredrik Lundh's
elementtree package.  It complained about an invalid token.  Looking at the
spot it indicated in the file, I found a non-ASCII, but (as far as I can
tell) perfectly valid utf-8 string.

I whittled the plist file down to what I've attached.  With it I get

 e = elementtree.ElementTree.parse(Cookies.plist)
Traceback (most recent call last):
  File stdin, line 1, in ?
  File 
/Users/skip/local/lib/python2.5/site-packages/elementtree/ElementTree.py, 
line 864, in parse
tree.parse(source, parser)
  File 
/Users/skip/local/lib/python2.5/site-packages/elementtree/ElementTree.py, 
line 588, in parse
parser.feed(data)
  File 
/Users/skip/local/lib/python2.5/site-packages/elementtree/ElementTree.py, 
line 1132, in feed
self._parser.Parse(data, 0)
xml.parsers.expat.ExpatError: not well-formed (invalid token): line 17, 
column 12

I had no trouble decoding that string as unicode.  Any ideas what's wrong?

Thx,

Skip



binfeFbX4goN0.bin
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: derived / base class name conflicts

2005-11-12 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
 Your suggestion ('_name' - implementation, 'name' - API) 

This is not my convention, it's *the* (mostly agreed upon) Python 
convention. Like 'self', or CONSTANT, or a whole lot of things in Python.

 makes sense
 as a convention between programmers that know a fair amount about each
 other's classes before using them.

No need to know much. dir(modulename.ClassName) is enough.

 I don't think it is reasonable in general to only subclass from base
 classes you have studied the full API of, however. 

Depends on your definition of studying the full API !-)

Now if your fear is to accidentally override something in the base 
class, it's just a matter of:
print API:
print [name for name in dir(modulename.ClassName) \
if not name.startswith('_')]

print IMPLEMENTATION:
print [name for name in dir(modulename.ClassName) \
if not name.startswith('_')]

 The double
 underscore is a decent solution to my problem.

Possibly. It can also become a PITA. But it's you who know what your 
code need !-)

 I imagine  it must be used a lot in domains where people are making
 heavy use of third party python code.

I almost never used it (perhaps half-a-dozen times, and only in 
frameworks abstract base classes), and rarely saw it in 3rd part source 
code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: elementtree.ElemenTree barfs on my Safari Cookies file

2005-11-12 Thread skip

skip I had no trouble decoding that string as unicode.

*sigh* I need some new proofreading glasses.  Should be ... string as
utf-8.

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


Re: Multikey Dict?

2005-11-12 Thread Mike Meyer
David Rasmussen [EMAIL PROTECTED] writes:

 If I have a collection of dicts like:
 john = {'id': 1, 'name': John Cleese, 'year': 1939}
 graham = {'id': 2, 'name': Graham Chapman, 'year': 1941}
 I could store all of them in a list. But for easy lookup, I might
 store all these in a dict instead, like
 people = {'1': john, '2': graham}
 or maybe
 people = {'John Cleese': john, 'Graham Chapman': graham}

 or whatever key I might choose. Now, first of all, it seems a bit
 annoying that I have to keep that redundant data in the second dict
 that is already in the individual dicts within people.

I don't see any redundant data in the dictionary. The *keys* might be
redundant, but that's because of the way you chose to store them.

 Secondly (and this is my question), it is annoying that I have to
 choose one of several unambiguous keys as a key.

So use them all. No big deal.

 I would like to be able to say:
 people['1'].year
 in some case and in other cases I want to say
 people['John Cleese'].year

This syntax looks like the values of the dictionary are objects, and
you're referencing attributes as opposed to looking up values in a
dictonary.

 Also, I would like if I didn't have to keep the key data both in the
 dict of dicts and in the dicts :)

Then don't. Dictionary keys are references objects. Make sure you
reference use the same object in both dictionaries.

 If I could just say to Python: john and graham (and ...) are all a
 part of a superdict and either their id or their name can be used as
 keys.

 Can I do that somehow?

It's easy enough to build your superdict class:

# Untested code
class SuperDict(dict):
  def __init__(self, *keys):
  dict.__init__(self)
  self.keys = *keys

  def __setitem__(self, key, item):
  # Set the explicit key
  dict.__setitem__(self, key, item)

  # Set the implicit keys
  for k in self.keys:
  dict.__setitem__(self, item[k], item)

I think that gives you the behavior you want, except you have to use
the index syntax for both indices, instead of beinng able to use the
attribute syntax for the object returned by the dictionary.

  mike
-- 
Mike Meyer [EMAIL PROTECTED]  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multikey Dict?

2005-11-12 Thread Bruno Desthuilliers
David Rasmussen a écrit :
 If I have a collection of dicts like:
 
 john = {'id': 1, 'name': John Cleese, 'year': 1939}
 graham = {'id': 2, 'name': Graham Chapman, 'year': 1941}
 
 I could store all of them in a list. But for easy lookup, I might store 
 all these in a dict instead, like
 
 people = {'1': john, '2': graham}
  or maybe
 
  people = {'John Cleese': john, 'Graham Chapman': graham}

You can use integers as keys in a dict. And building an index is not 
that difficult:

peoples = [
{'id': 1, 'name': John Cleese, 'year': 1939},
{id': 2, 'name': Graham Chapman, 'year': 1941},
]

peoples_name_idx = dict((p['name'], p) for p in peoples)
peoples_id_idx = dict((p['id'], p) for p in peoples)

which generalize to:
def mk_index(index_field, records):
 return dict((rec[index_field], rec) for rec in records)

(snip)
  would like to be able to say: 
 people['1'].year
 
 in some case and in other cases I want to say 
 people['John Cleese'].year 

This should be:
   people['John Cleese']['year']

(If you want transform your dicts to objects so you use dotted notation, 
there are recipes for this in the Python Cookbook.)

 If I could just say to Python: john and graham (and ...) are all a part 
 of a superdict and either their id or their name can be used as keys.
 
 Can I do that somehow?

Writing a dict-like object is quite easy. Look for UserDict, or directly 
subclass Dict.

Now, how could the superdict implementation decide which key to use ?

Here, you have a numeric 'id' and a string 'name', so you could test on 
it in __getitem__, but what if you want to use 2 different string keys? 
Computers are usually very bad at guessing, that's why we are 
programming them.



My 2 cents
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multikey Dict?

2005-11-12 Thread Bruno Desthuilliers
Sam Pointon a écrit :
If I could just say to Python: john and graham (and ...) are all a part
of a superdict and either their id or their name can be used as keys.
 
 
Can I do that somehow?
 
 
 Sure you can. There are two obvious ways to do this - enlist the aid of
 a Superdict (or similar) class to take care of the details. A simple
 implementation would be:
 
 class Superdict(object):
 
 def __init__(self, by_id, by_name):
 self.by_id = by_id
 self.by_name = by_name
 
 def __getitem__(self, value):
 if value.isdigit():
 return self.by_id[value]
 else:
 return self.by_name[value]

What if the OP now wants non numeric id fields ?

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


[OT] Copyright [was Re: Python obfuscation]

2005-11-12 Thread Steven D'Aprano
On Fri, 11 Nov 2005 23:22:45 -0800, The Eternal Squire wrote:

 Without copyright, how could one possibly earn a living writing a
 novel?  

I don't know. How did William Shakespeare make a living from writing plays
and sonnets and poems? How did Sir Walter Scott make a living from writing
novels? How do chefs make a living from creating new recipes, and stand-up
comedians from telling jokes?

Perhaps there is no way to make a living from writing novels without
copyright. There is no way to make a living from playing solitaire either
-- should the government pass a law giving a legal monopoly on playing red
queen on a black king to my granny, so that everyone playing that move
has to pay her ten cents? That would make her old age so much more
comfortable. If you object to my proposal, I can ask But without it, how
could one possibly make a living playing solitaire?

Do we care if novelists can make a living writing novels? Most of them
don't anyway. The Stephen Kings, Tom Clancys and J.K. Rowlings are the
exception, not the rule -- for every Terry Pratchett who has had to
change banks because [he] filled the first one up, there are a hundred
thousand who never make a living from writing at all.

If you've been involved in writing novels, you will know that the real
difference between an interesting idea and a great novel is usually a good
editor. A good editor does maybe a quarter or a third of the intellectual
labour of creating a novel -- not the grunt work of hitting typewriter
keys and putting ink to paper, but the brain work of making sure that the
story actually tells a story well. Why should the author get the monopoly
and the editor nothing? How do editors make money without a monopoly
granted by the government like copyright?

How do magazine and newspaper writers make a living when they don't get
the copyright on the things they write?

These are all important questions, and you will notice I deliberately am
not giving answers -- but they are also irrelevant because I didn't say
that I was against copyright. What I asked was why the artificial rights
of creators are given more importance than the natural rights of users.



 And I submit that many ISD's are only a single person burning
 with that one software idea of a lifetime, the equivalent of the Great
 American Novel.

If their one software idea of a lifetime is as pointless, useless and
just *bad* as the average would-be Great American Novel, then copyright
or no copyright nobody will want their poxy code. Sourceforge is full of
software projects, 90% of which go nowhere. The world is filled with
millions of wanna-be poets, writers and creators whose sum total
contribution to the artistic wealth of the world is negative. 

I'm not just using hyperbole. By poisoning the well with their garbage,
they just make it that little bit harder for genuinely talented artists to
be heard. Only 2% of books sell more than 5,000 copies, ever, and many
wonderful books never get a second print-run because they just can't get
people's attention.

Despite this, people keep trying to write the Great American Novel.
Creative artists will create, even if they would be economically better
off washing dishes at Greasy Joe's Diner for a buck an hour. Michaelangelo
didn't stop painting because he had no copyright protection.


 Are we to punish that impulse by denying that person
 a legal monopoly on that idea?

Who's talking about *punishment*?

The natural state of things is not copyright. No copyright is not
punishing the author any more than no flying unicorns is punishing
little girls with a fantasy for flying through the sky on the back of a
horned horse. It is just the way things are.

Copyright is a gift granted by the government, not the natural state of
the world. When kings and emperors and presidents give commercial and
economic gifts, like monopolies, they rarely are for the benefit of the
majority.

Lots of ideas have no legal monopoly. There is no legal monopoly on (say)
good gardening skills, or the specific way of mixing the batter to make
extra light and fluffy bread. Why should some ideas be privileged over
others?

Lack of copyright doesn't need to be defended, as it is the natural state
of the world. Copyright is the special state which needs to be defended,
and there is precious little evidence that copyright makes sense
economically for *anyone*, author, publisher, readers or society as a
whole.

That's not to say that copyright isn't good for one or more of the above:
I have my intuitions as to who copyright benefits. But my point is that
there is a serious lack of evidence one way or the other, and what
evidence there is suggests strongly that over-strong copyright laws (like
we have now) are bad for *everyone*, and that weaker copyright (as in the
early 20th century) would be better.



 I believe piracy is bad for everyone:  the consumer, the writer, and
 the country as a whole.  I don't oppose copyleft, but then, I don't
 oppose 

tutorial example?????

2005-11-12 Thread john boy
OK...I have the following program

i = 1
while i = 6:
 print 2 * i,' ',
 i = i + 1
print

this is supposed to give you a "new"blank line after the program runs instead it just gives:
2 4 6 8 10 12


instead of:
2 4 6 8 10 12



to get the above return I have to type in "print" twice,this can't be right?..ANY SUGGESTIONS?

i = 1
while i = 6:
 print 2 * i,' ',
 i = i + 1
print
print
		 Yahoo! FareChase - Search multiple travel sites in one click.

 

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

Re: Proposal for adding symbols within Python

2005-11-12 Thread Steven D'Aprano
On Sat, 12 Nov 2005 18:59:39 +0100, Pierre Barbier de Reuille wrote:

 First, I think it would be best to have a syntax to represent symbols.
 Adding some special char before the name is probably a good way to
 achieve that : $open, $close, ... are $ymbols.

I think your chances of convincing Guido to introduce new syntax is slim
to none. (Not quite zero -- he did accept @ for decorators.)

I think symbols should simply be an immutable object, one with state and
limited or no behaviour, rather than a brand new syntactical element.
Being an object, you can reference them in whatever namespace you define
them in.

Personally, I think rather than adding a new language feature (...slim to
none...) there is more hope of getting something like this added to the
standard library:

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



-- 
Steven.

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


Re: tutorial example

2005-11-12 Thread Steven D'Aprano
On Sat, 12 Nov 2005 13:42:37 +, Max Erickson wrote:

 
 Not in python.
 
 For example, what would you call the following?
 
 def rsum(n, m):
 print n+m
 return n+m
 
 
 In python a method is callable attached to an object. A function is a 
 callable object constructed with a def statement.

That's not *quite* right, because methods are also usually constructed
with a def statement as well, and you can attach functions to objects by
assignment:

py def spam(n):
... return spam  * n
...
py class Viking:
... pass
...
py eric_the_red = Viking()
py eric_the_red.spam = spam
py eric_the_red.spam(4)
'spam spam spam spam '
py type(eric_the_red.spam)
type 'function'


There is surely some technical definition that distinguishes between
methods and functions, and between class, instance and static methods. At
this level, the technical difference is not important.

What is important is that, to a first approximation, functions
and methods are the same thing. To a second approximation, functions
belong to modules and methods belong to any other object.

So in a module that looks like this:

X = 1

def frob(x):
Return the frobised value of x.
return x

class Parrot:
def frob(self):
Returns the frobised value of self.
return self

the top-level frob is a function and Parrot.frob is a method.

Others have suggested that the difference between methods and functions is
that methods do something and functions return a result. That's not quite
true: both methods and functions can do something (something is known as
a side-effect, and is *usually* but not always a Bad Idea), and both
methods and functions *always* return an object, even if that object is
just None.

By convention, methods often (but not always) operate by side-effect:

L = [1, 4, 2, 7]
L.sort()

But methods frequently return a value:

s = Hello World
s = s.upper()

In fact even L.sort() returns a value: it returns None:

who_cares = L.sort()
# who_cares is now None; L is now sorted

Languages such as Pascal have procedures, which don't return a value, and
functions, which do. Python does not have procedures.



-- 
Steven.

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


Re: Iterator addition

2005-11-12 Thread bearophileHUGS
Tom Anderson:
 And we're halfway to looking like perl already! Perhaps a more pythonic
 thing would be to define a then operator:
 all_lines = file1 then file2 then file3

Or a chain one:
 all_lines = file1 chain file2 chain file3

Bearophile

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


Re: Hash map with multiple keys per value ?

2005-11-12 Thread Alex Martelli
Chris Stiles [EMAIL PROTECTED] wrote:
   ...
  alias insertion just be of the form x aliases to y rather than x
  names object XXX?
 
 In this case, strictly speaking there are no such thing as an 'object XXX',
 all the aliases are names for the object, each as important as each other.

Fine, but, quite apart from names, IS there a Python object with a given
identity, of which these aliases are names of?  Or is that object
something which does NOT exist as a Python object (in which case maybe
calling it an entity, or some other name that's not used for specific
purposes in Python, might be clearer!)...?


def alias(self, x, y):
   dx = self.d.get(x,set([x]))
   dy = self.d.get(y,set([y]))
   self.d[x]=self.d[y]=dx+dy
^
 
 Will that end up with two(many) references to the same set? [Though in any
 case I would be iterating over all values in the set).

Yes, but it's buggy (doesn't modify the self.d[z] entries for all the
z's which aren't either x nor y but alias either of them).


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


Re: Python obfuscation

2005-11-12 Thread Alex Martelli
Steven D'Aprano [EMAIL PROTECTED] wrote:

 In a competitive marketplace, why would I choose to buy DRMed software if
 there is a non-DRMed equivalent with the same functionality and equivalent
 cost?

The only explanation I can think of is, their marketing must be
AWEsome!-)


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


  1   2   >