Re: Help needed with python unicode cgi-bin script

2007-12-09 Thread Martin v. Löwis
> My problem is more complex than this, but how about I boil down one sticking 
> point for starters. I have a file with a Spanish word in it, "años", which I 
> wish to read with:

What is the encoding of that file? Without a correct answer to that
question, you will not be able to achieve what you want.

Possible answers are "iso-8859-1", "utf-8", "windows-1252", and "cp850"
(these all support the word "años")

> Instead of seeing "año" I see "a?o". BAD BAD BAD

I don't see anything here. Where do you see the question mark? Did you
perhaps run the CGI script in a web server, and pointed your web browser
to the web page, and saw the question mark in the web browser?

> WHAT GIVES?

Sending "Content-type: text/html" is not enough. The web browser needs
to know what the encoding is. So you should send

Content-type: text/html; charset="your-encoding-here"

Use "extras/page information" in Firefox to find out what the web
browser thinks the encoding of the page is.

Regards,
Martin

P.S. Please, stop shouting.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: Axon.STM 1.0.0 (beta) Minimalistic Software Transactional Memory

2007-12-09 Thread Michael Sparks
Hi,


I've packaged up the minimal STM discussed over the past couple of days as a
standalone package which I've now uploaded

Getting it
==
You can download a beta test version here:
http://thwackety.com/Axon.STM-1.0.0.tar.gz

Previewing it
=
You can look at the sourcecode online here:

https://kamaelia.svn.sourceforge.net/svnroot/kamaelia/branches/private_MPS_Scratch/Bindings/STM/Axon/STM.py

Installing it
=
~ > tar zxf Axon.STM-1.0.0.tar.gz
~ > cd Axon.STM-1.0.0/
~ > sudo python setup.py install

What IS it?
===
Software Transactional Memory (STM) is a technique for allowing multiple
threads to share data in such a way that they know when something has gone
wrong. It's been used in databases (just called transactions there really)
for some time and is also very similar to version control. Indeed, you can
think of STM as being like variable level version control.

Note: Because this is NOT intended to be persistent, this is not an ACID
store because it doesn't support the D - durability across a crash. (after
all, we don't save the state to disk) (The other aspects atomicity,
consistency & isolation are supported though)

I've written this to allow a part of Kamaelia to share & manage a dictionary
of atomic values between threads simply, and as a result this code is also
going into mainline Kamaelia. (Specifically into Axon Kamaelia's core)

However STM is something that should hopefully be of use to others doing
concurrent *things* whether or not they're using kamaelia, hence this stand
alone release.

This stand alone release should *not* be used alongside mainline Axon yet.
(Well you can, as long as you reinstall your Axon over the top, but that's
icky :-)

Why is it useful?
=
[ please skip this (or correct me :) if you understand concurrency
  already :-) ]

Why do you need it? Well, in normal code, Global variables are generally
shunned because it can make your code a pain to work with and a pain to be
certain if it works properly. Even with linear code, you can have 2 bits of
code manipulating a structure in surprising ways - but the results are
repeatable. Not-properly-managed-shared-data is to threaded systems as
not-properly-managed-globals are to normal code. (This code is one way of
helping manage shared data)

Well, with code where you have multiple threads active, having shared data
is like an even nastier version of globals. Why? Well, when you have 2 (or
more) running in parallel, the results of breakage can become hard to
repeat as two pieces of code "race" to update values.

With STM you make it explicit what the values are you want to update, and
only once you're happy with the updates do you publish them back to the
shared storage. The neat thing is, if someone else changed things since you
last looked, you get told (your commit fails), and you have to redo the
work. This may sound like extra work (you have to be prepared to redo the
work), but it's nicer than your code breaking :-)

The way you get that message is the .commit raises a ConcurrentUpdate
exception.

Also, it's designed to work happily in code that requires non-blocking
usage - which means you may also get a "BusyRetry" exception under load. If
you do, you should as the exception suggests retry the action that you just
tried. (With or without restarting the transaction)

Apologies if that sounds too noddy :)

Docs for it
===
http://kamaelia.sourceforge.net/STM

Using It


# Initialising a Store
from Axon.STM import Store

S = Store()

# Single values
greeting = S.usevar("hello")
print repr(greeting.value)
greeting.set("Hello World")
greeting.commit()
S.dump()

# Groups of values
D = S.using("account_one", "account_two", "myaccount")
D["account_one"].set(50)
D["account_two"].set(100)
D.commit()
S.dump()

D = S.using("account_one", "account_two", "myaccount")
D["myaccount"].set(D["account_one"].value+D["account_two"].value)
D["account_one"].set(0)
D["account_two"].set(0)
D.commit()
S.dump()

License
===
Take your pick of MPL V1.1, GPL 2.0, LGPL 2.1 :-)

Feedback

Feedback is very welcome, preferably via email to the Kamaelia List
* [EMAIL PROTECTED]

Feedback especially regarding bugs and logical errors is particularly
welcome. (hopefully there aren't any - but it's always hard to spot your
own)

Thanks
==
Many thanks to Fuzzyman, Duncan Booth, John J Lee & Sylvain Hellegouarch for
feedback whilst I was prototyping this.

Best Regards,


Michael.
--
Michael Sparks, Kamaelia Project
http://kamaelia.sourceforge.net/Developers/
http://yeoldeclue.com/blog

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


Re: Help needed with python unicode cgi-bin script

2007-12-09 Thread Jack
You probably need to set stdout mode to binary. They are not by default on 
Windows.


"weheh" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Dear web gods:
>
> After much, much, much struggle with unicode, many an hour reading all the 
> examples online, coding them, testing them, ripping them apart and putting 
> them back together, I am humbled. Therefore, I humble myself before you to 
> seek guidance on a simple python unicode cgi-bin scripting problem.
>
> My problem is more complex than this, but how about I boil down one 
> sticking point for starters. I have a file with a Spanish word in it, "años", 
> which I wish to read with:
>
>
> #!C:/Program Files/Python23/python.exe
>
> STARTHTML= u'''Content-Type: text/html
>
>  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
> http://www.w3.org/1999/xhtml"; lang="en" xml:lang="en">
> 
> 
> 
> '''
> ENDHTML = u'''
> 
> 
> '''
> print STARTHTML
> print open('c:/test/spanish.txt','r').read()
> print ENDHTML
>
>
> Instead of seeing "año" I see "a?o". BAD BAD BAD
> Yet, if I open the file with the browser (IE/Mozilla), I see "año." THIS 
> IS WHAT I WANT
>
> WHAT GIVES?
>
> Next, I'll get into codecs and stuff, but how about starting with this?
>
> The general question is, does anybody have a complete working example of a 
> cgi-bin script that does the above properly that they'd be willing to 
> share? I've tried various examples online but haven't been able to get any 
> to work. I end up seeing hex code for the non-ascii characters u'a\xf1o', 
> and later on 'a\xc3\xb1o', which are also BAD BAD BAD.
>
> Thanks -- your humble supplicant.
> 


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

Help needed with python unicode cgi-bin script

2007-12-09 Thread weheh
Dear web gods:

After much, much, much struggle with unicode, many an hour reading all the 
examples online, coding them, testing them, ripping them apart and putting 
them back together, I am humbled. Therefore, I humble myself before you to 
seek guidance on a simple python unicode cgi-bin scripting problem.

My problem is more complex than this, but how about I boil down one sticking 
point for starters. I have a file with a Spanish word in it, "años", which I 
wish to read with:


#!C:/Program Files/Python23/python.exe

STARTHTML= u'''Content-Type: text/html

http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
http://www.w3.org/1999/xhtml"; lang="en" xml:lang="en">



'''
ENDHTML = u'''


'''
print STARTHTML
print open('c:/test/spanish.txt','r').read()
print ENDHTML


Instead of seeing "año" I see "a?o". BAD BAD BAD
Yet, if I open the file with the browser (IE/Mozilla), I see "año." THIS IS 
WHAT I WANT

WHAT GIVES?

Next, I'll get into codecs and stuff, but how about starting with this?

The general question is, does anybody have a complete working example of a 
cgi-bin script that does the above properly that they'd be willing to share? 
I've tried various examples online but haven't been able to get any to work. 
I end up seeing hex code for the non-ascii characters u'a\xf1o', and later 
on 'a\xc3\xb1o', which are also BAD BAD BAD.

Thanks -- your humble supplicant. 


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

Re: help with pyparsing

2007-12-09 Thread Paul McGuire
On Dec 9, 11:01 pm, Prabhu Gurumurthy <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> All,
>
> I have the following lines that I would like to parse in python using
> pyparsing, but have some problems forming the grammar.
>
> Line in file:
> table  const { 207.135.103.128/26, 207.135.112.64/29 }
> table  persist { ! 10.200.2/24, 10.200/22 }
> table  const { 192.168/16, ! 172.24.1/29, 172.16/12, 169.254/16 }
> table  persist { 10.202/22 }
> table  const { 10.206/22 }
> table  const {   \
>10.205.1/24,  \
>169.136.241.68,   \
>169.136.241.70,   \
>169.136.241.71,   \
>169.136.241.72,   \
>169.136.241.75,   \
>169.136.241.76,   \
>169.136.241.77,   \
>169.136.241.78,   \
>169.136.241.79,   \
>169.136.241.81,   \
>169.136.241.82,   \
>169.136.241.85 }
>
> I have the following grammar defn.
>
> tableName = Word(alphanums + "-" + "_")
> leftClose = Suppress("<")
> rightClose = Suppress(">")
> key = Suppress("table")
> tableType = Regex("persist|const")
> ip4Address = OneOrMore(Word(nums + "."))
> ip4Network = Group(ip4Address + Optional(Word("/") +
> OneOrMore(Word(nums
> temp = ZeroOrMore("\\" + "\n")
> tableList = OneOrMore(Optional("\\") |
>ip4Network | ip4Address | Suppress(",") | Literal("!"))
> leftParen = Suppress("{")
> rightParen = Suppress("}")
>
> table = key + leftClose + tableName + rightClose + tableType + \
>   leftParen + tableList + rightParen
>
> I cannot seem to match sixth line in the file above, i.e table name with
> KS, how do I form the grammar for it, BTW, I still cannot seem to ignore
> comments using table.ignore(Literal("#") + restOfLine), I get a parse error.
>
> Any help appreciated.
> Thanks
> Prabhu

Prabhu -

This is a good start, but here are some suggestions:

1. ip4Address = OneOrMore(Word(nums + "."))

Word(nums+".") will read any contiguous set of characters in the
string nums+".", so OneOrMore is not necessary for reading in an
ip4Address.  Just use:

ip4Address = Word(nums + ".")


2. ip4Network = Group(ip4Address + Optional(Word("/") +
OneOrMore(Word(nums

Same comment, OneOrMore is not needed for the added value to the
ip4Address:

ip4Network = Group(ip4Address + Optional(Word("/") + Word(nums


3. tableList = OneOrMore(Optional("\\") |
   ip4Network | ip4Address | Suppress(",") |
Literal("!"))

The list of ip4Networks is just a comma-delimited list, with some
entries preceded with a '!' character.  It is simpler to use
pyparsing's built-in helper, delimitedList, as in:

tableList = Group( delimitedList(Group("!"+ip4Network)|ip4Network) )


Yes, I know, you are saying, "but what about all those backslashes?"
The backslashes look like they are just there as line continuations.
We can define an ignore expression, so that the table expression, and
all of its contained expressions, will ignore '\' characters as line
continuations:

table.ignore( Literal("\\") + LineEnd() )

And I'm not sure why you had trouble with ignoring '#' + restOfLine,
it works fine in the program below.

If you make these changes, your program will look something like this:

tableName = Word(alphanums + "-" + "_")
leftClose = Suppress("<")
rightClose = Suppress(">")
key = Suppress("table")
tableType = Regex("persist|const")
ip4Address = Word(nums + ".")
ip4Network = Group(ip4Address + Optional(Word("/") + Word(nums)))
tableList = Group(delimitedList(Group("!"+ip4Network)|ip4Network))
leftParen = Suppress("{")
rightParen = Suppress("}")

table = key + leftClose + tableName + rightClose + tableType + \
  leftParen + tableList + rightParen
table.ignore(Literal("\\") + LineEnd())
table.ignore(Literal("#") + restOfLine)

# parse the input line, and pprint the results
result = OneOrMore(table).parseString(line)
from pprint import pprint
pprint(result.asList())

Prints out:
['ALINK',
 'const',
 [['207.135.103.128', '/', '26'], ['207.135.112.64', '/', '29']],
 'INTRANET',
 'persist',
 [['!', ['10.200.2', '/', '24']], ['10.200', '/', '22']],
 'RFC_1918',
 'const',
 [['192.168', '/', '16'],
  ['!', ['172.24.1', '/', '29']],
  ['172.16', '/', '12'],
  ['169.254', '/', '16']],
 'DIALER',
 'persist',
 [['10.202', '/', '22']],
 'RAVPN',
 'const',
 [['10.206', '/', '22']],
 'KS',
 'const',
 [['10.205.1', '/', '24'],
  ['169.136.241.68'],
  ['169.136.241.70'],
  ['169.136.241.71'],
  ['169.136.241.72'],
  ['169.136.241.75'],
  ['169.136.241.76'],
  ['169.136.241.77'],
  ['169.136.241.78'],
  ['169.136.241.79'],
  ['169.136.241.81'],
  ['169.136.241.82'],
  ['169.136.241.85']]]

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


Best way to protect my new commercial software.

2007-12-09 Thread farsheed
I wrote a software and I want to protect it so can not be cracked
easily. I wrote it in python and compile it using py2exe. what is the
best way in your opinion?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help with pyparsing

2007-12-09 Thread Chris
On Dec 10, 7:01 am, Prabhu Gurumurthy <[EMAIL PROTECTED]> wrote:
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> All,
>
> I have the following lines that I would like to parse in python using
> pyparsing, but have some problems forming the grammar.
>
> Line in file:
> table  const { 207.135.103.128/26, 207.135.112.64/29 }
> table  persist { ! 10.200.2/24, 10.200/22 }
> table  const { 192.168/16, ! 172.24.1/29, 172.16/12, 169.254/16 }
> table  persist { 10.202/22 }
> table  const { 10.206/22 }
> table  const {   \
>10.205.1/24,  \
>169.136.241.68,   \
>169.136.241.70,   \
>169.136.241.71,   \
>169.136.241.72,   \
>169.136.241.75,   \
>169.136.241.76,   \
>169.136.241.77,   \
>169.136.241.78,   \
>169.136.241.79,   \
>169.136.241.81,   \
>169.136.241.82,   \
>169.136.241.85 }
>
> I have the following grammar defn.
>
> tableName = Word(alphanums + "-" + "_")
> leftClose = Suppress("<")
> rightClose = Suppress(">")
> key = Suppress("table")
> tableType = Regex("persist|const")
> ip4Address = OneOrMore(Word(nums + "."))
> ip4Network = Group(ip4Address + Optional(Word("/") +
> OneOrMore(Word(nums
> temp = ZeroOrMore("\\" + "\n")
> tableList = OneOrMore(Optional("\\") |
>ip4Network | ip4Address | Suppress(",") | Literal("!"))
> leftParen = Suppress("{")
> rightParen = Suppress("}")
>
> table = key + leftClose + tableName + rightClose + tableType + \
>   leftParen + tableList + rightParen
>
> I cannot seem to match sixth line in the file above, i.e table name with
> KS, how do I form the grammar for it, BTW, I still cannot seem to ignore
> comments using table.ignore(Literal("#") + restOfLine), I get a parse error.
>
> Any help appreciated.
> Thanks
> Prabhu
> - -
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v2.0.4-svn0 (GNU/Linux)
> Comment: Using GnuPG with SUSE -http://enigmail.mozdev.org
>
> iD8DBQFHXMhFTkjpaeKzB9YRAmZYAJ9Lyys6+xCrGEsyy33AoRWVdUOXQwCfTG9Q
> /f7JZ2pAW6WDSzs79jbDFQE=
> =CGb0
> -END PGP SIGNATURE-

Shouldn't tableList be 'ZeroOrMore' instead...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to convert 3 byte to float

2007-12-09 Thread Hendrik van Rooyen
 "Mario M. Mueller" <[EMAIL PROTECTED]> wrote:


> I uploaded a short sample data file under
> http://www.FastShare.org/download/test.bin - maybe one can give me another
> hint... In a full data example max value is 1179760 (in case one looks only
> at the eye-cathing "65535"+- values).

I clicked on the link and got nothing but rubbish trying to predict how old
I would get, so I gave up and am flying blind.

Some A to D's are not two's complement, but have strange formats with an 
independent sign bit in the highest order.

And of course there is big and little endian - so there are something like
2x2 = 4 things to try - twos compl. big and little, and signed big and little.

Unless there is a protocol interfering - how do you know, in the byte stream, 
where a value starts and stops - is it cr,lf delimited?

- Hendrik

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


Re: regular expression for nested parentheses

2007-12-09 Thread John Machin
On Dec 10, 12:22 pm, MRAB <[EMAIL PROTECTED]> wrote:
> On Dec 9, 10:12 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Dec 10, 8:53 am, Noah Hoffman <[EMAIL PROTECTED]> wrote:
>
> > > On Dec 9, 1:41 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
> > > > A pattern that can validly be described as a "regular expression"
> > > > cannot count and thus can't match balanced parentheses. Some "RE"
> > > > engines provide a method of tagging a sub-pattern so that a match must
> > > > include balanced () (or [] or {}); Python's doesn't.
>
> > > Okay, thanks for the clarification. So recursion is not possible using
> > > python regular expressions?
>
> > > > Ummm ... even if Python's re engine did do what you want, wouldn't you
> > > > need flags=re.VERBOSE in there?
>
> > > Ah, thanks for letting me know about that flag; but removing
> > > whitespace as I did with the no_ws lambda expression should also work,
> > > no?
>
> > Under a very limited definition of "work". That technique would not
> > produce correct answers on patterns that contain any *significant*
> > whitespace e.g. you want to match "foo" and "bar" separated by one or
> > more spaces (but not tabs, newlines etc) 
> > pattern = r"""
> > foo
> > [ ]+
> > bar
> > """
>
> You can also escape a literal space:
>
> pattern = r"""
> foo
> \ +
> bar
> """

I know that. *Any* method of putting in a literal significant space is
clobbered by the OP's "trick" of removing *all* whitespace instead of
using the VERBOSE flag, which also permits comments:
pattern = r"""
\ + # ugly
[ ]+ # not quite so ugly
"""
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ZODB List

2007-12-09 Thread Gabriel Genellina
En Sun, 09 Dec 2007 21:03:50 -0300, Flavio <[EMAIL PROTECTED]> escribió:

> I am a big fan of ZODB and use it stand alone on many project of mine.
> One of the things I miss is a community around it. I don't care much
> about ZOPE (though I admire it) and have not being able  to find  a
> ZODB focused community. Is there one?

It's mostly for developers, but I've seen "user" questions answered on  
zodb-dev too:
http://mail.zope.org/mailman/listinfo/zodb-dev

-- 
Gabriel Genellina

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


Re: Distinguishing attributes and methods

2007-12-09 Thread Marc 'BlackJack' Rintsch
On Sun, 09 Dec 2007 12:44:46 -0800, MonkeeSage wrote:

> On Dec 8, 4:11 pm, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
>> MonkeeSage a écrit :
> You're talking about the result of calling a.a(), I'm talking about
> what the attribute "a" on the object "a" is. Which is a callable
> attribute, which by definition is called a "method" in the standard
> sense [1].  You can make a distinction between a "method object" and
> "any other possible callable object," but I wasn't using such a
> distinction, I was using the standard definition. So my point holds.
> When you see a.a(), because of pythons calling convention "()" you
> know that "a" is a method of object "a".

No you don't know that.  It's only a method of object `a` if it is really
a method bound to object `a` and not just a "data attribute" that happens
to be callable.

> Again, I am using the common definition. I understand that you can
> make an attribute callable in different ways than just the standard
> machinery of "def symbol(self):" (those other techniques are what I
> was referring to above by "metaprogramming"). But how it is made
> callable doesn't matter (nor does how it is looked up). Once it is
> callable, it fits the defintion of "method" I'm using. In future, I'll
> try to be clear when I'm referring to something python specific or to
> a general CS concept.

Your definition of "method" is a bit odd then.  The general CS sense of
"method" requires the method to be bound to the object and not just be a
random callable.  Let's see an example:

In [469]: a = collections.defaultdict(int)

In [470]: callable(a.default_factory)
Out[470]: True

In [471]: a.default_factory(42)
Out[471]: 42

`a.default_factory` is callable but hardly a method of `a` or `defaultdict`
but a "data attribute" that happens to be callable.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: how to get module globals into a class ?

2007-12-09 Thread Gabriel Genellina
En Sun, 09 Dec 2007 20:53:38 -0300, stef mientki <[EMAIL PROTECTED]>  
escribió:

> this question may look a little weird,
> but I want to create library shells that are a simple as possible.
>
> So I've a module where one base class is defined,
> which looks like this (and might be complex)
>
> base_class_file.py
> class brick_base ( object ) :
> 
>
> now I've a lot of library files,
> in each library file are a lot of classes,
> and each library-file, has some specific parameters, like  
> "library_color",
> so something like this:
>
> library_file.py
> library_color = ...
>
> class brick_do_something1( brick_base ) :
> init :
> self.Library_Color = Library_Color
> 
>
> class brick_do_something2( brick_base ) :
> init :
> self.Library_Color = Library_Color
> 
>
> Now this works fine, ...
> ... but the statement "self.Library_Color = Library_Color"
> is completely redundant, because it should be in every class of every
> librray file.
> So I would like to move this statement to the base-class-file,
> but I can't figure out how to accomplish that.

Ok, let's see if I understand your question. Classes defined in  
library_file.py have some attributes in common (like library_color). Other  
classes defined in other files (but also inheriting from brick_base)  
don't. You can use an intermediate class to hold all the common attributes:

library_file.py

 class Library(brick_base):
 library_color = WHITE

 class brick_do_something1(Library):
 

 class brick_do_something2(Library):
 

Note that I don't even wrote an __init__ method; using a class attribute  
serves as a default instance attribute (until you actually assign  
something to the instance).

x = brick_do_something2()
print x.library_color # prints WHITE

-- 
Gabriel Genellina

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


Re: python/regex question... hope someone can help

2007-12-09 Thread Gabriel Genellina
En Sun, 09 Dec 2007 16:45:53 -0300, charonzen <[EMAIL PROTECTED]>  
escribió:

>> [John Machin] Another suggestion is to ensure that the job  
>> specification is not
>> overly simplified. How did you parse the text into "words" in the
>> prior exercise that produced the list of bigrams? Won't you need to
>> use the same parsing method in the current exercise of tagging the
>> bigrams with an underscore?
>
> Thank you John, that definitely puts things in perspective!  I'm very
> new to both Python and text parsing, and I often feel that I can't see
> the forest for the trees.  If you're asking, I'm working on a project
> that utilizes Church's mutual information score.  I tokenize my text,
> split it into a list, derive some unigram and bigram dictionaries, and
> then calculate a pmi dictionary based on x,y from the bigrams and
> unigrams.  The bigrams that pass my threshold then get put into my
> list of x_y strings, and you know the rest.  By modifying the original
> text file, I can view 'x_y', z pairs as x,y and iterate it until I
> have some collocations that are worth playing with.  So I think that
> covers the question the same parsing method.  I'm sure there are more
> pythonic ways to do it, but I'm on deadline :)

Looks like you should work with the list of tokens, collapsing consecutive  
elements, not with the original text. Should be easier, and faster because  
you don't regenerate the text and tokenize it again and again.

-- 
Gabriel Genellina

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


Re: callback confusion

2007-12-09 Thread Gabriel Genellina
En Sat, 08 Dec 2007 14:46:46 -0300, Donn Ingle <[EMAIL PROTECTED]>  
escribió:

> UnboundLocalError: local variable 'kills' referenced before assignment
>
> I'm amazed that I've spent so much time with Python and something like  
> that
> totally stumps me!?
>
>> FWIW, this is a FAQ.
> If you have a link, that'll help.

See  

  
and the next question.

-- 
Gabriel Genellina

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


help with pyparsing

2007-12-09 Thread Prabhu Gurumurthy
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

All,

I have the following lines that I would like to parse in python using
pyparsing, but have some problems forming the grammar.

Line in file:
table  const { 207.135.103.128/26, 207.135.112.64/29 }
table  persist { ! 10.200.2/24, 10.200/22 }
table  const { 192.168/16, ! 172.24.1/29, 172.16/12, 169.254/16 }
table  persist { 10.202/22 }
table  const { 10.206/22 }
table  const {   \
   10.205.1/24,  \
   169.136.241.68,   \
   169.136.241.70,   \
   169.136.241.71,   \
   169.136.241.72,   \
   169.136.241.75,   \
   169.136.241.76,   \
   169.136.241.77,   \
   169.136.241.78,   \
   169.136.241.79,   \
   169.136.241.81,   \
   169.136.241.82,   \
   169.136.241.85 }

I have the following grammar defn.

tableName = Word(alphanums + "-" + "_")
leftClose = Suppress("<")
rightClose = Suppress(">")
key = Suppress("table")
tableType = Regex("persist|const")
ip4Address = OneOrMore(Word(nums + "."))
ip4Network = Group(ip4Address + Optional(Word("/") +
OneOrMore(Word(nums
temp = ZeroOrMore("\\" + "\n")
tableList = OneOrMore(Optional("\\") |
   ip4Network | ip4Address | Suppress(",") | Literal("!"))
leftParen = Suppress("{")
rightParen = Suppress("}")

table = key + leftClose + tableName + rightClose + tableType + \
  leftParen + tableList + rightParen

I cannot seem to match sixth line in the file above, i.e table name with
KS, how do I form the grammar for it, BTW, I still cannot seem to ignore
comments using table.ignore(Literal("#") + restOfLine), I get a parse error.

Any help appreciated.
Thanks
Prabhu
- -
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.4-svn0 (GNU/Linux)
Comment: Using GnuPG with SUSE - http://enigmail.mozdev.org

iD8DBQFHXMhFTkjpaeKzB9YRAmZYAJ9Lyys6+xCrGEsyy33AoRWVdUOXQwCfTG9Q
/f7JZ2pAW6WDSzs79jbDFQE=
=CGb0
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is a "real" C-Python possible?

2007-12-09 Thread C. ARA


on 12/10/2007 05:14 AM Jack wrote :

> I wonder if it's possible to have a Python that's completely (or at
> least for the most part) implemented in C, just like PHP - I think
> this is where PHP gets its performance advantage. Or maybe I'm wrong
> because the core modules that matter are already in C and those Python
> files are really a think wrapper. Anyhow, if would be ideal if Python
> has performance similar to Java, with both being interpreted languages.

to compare the speed of the two u need a lot of normalization, it is 
completely two different vector quantities --irrational. There is no way 
for an absolute comparison.

both php and python are excellent but each has some application in which 
it defeats the other..

if u want something really fast use assembly.. what??? why are u 
shocked!! you don't want to pay tax ;)

it's a matter of preference and need after all.. don't be misled by all 
the fuss about speed or the mightiness of any programming language they 
are just tools .. u r the secret!!


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


Re: Is a "real" C-Python possible?

2007-12-09 Thread Chris M
On Dec 9, 10:04 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Dec 9, 6:07 pm, "Jack" <[EMAIL PROTECTED]> wrote:
>
> > Plus, Psyco is not the
> > main stream and has stopped development.
>
> 
>
> What makes you think it has stopped development?  I just swung by the
> SF project page, and its most recent news post was just 2 months ago.
>
> Psyco may not be in the standard Python distribution, but it is
> definitely a fixture of the Python landscape, which is about as close
> to main stream as you can get.
>
> -- Paul

Maybe because of this line:

"Psyco is a reasonably complete project. I will not continue to
develop it beyond making sure it works with future versions of Python.
My plans for 2006 are to port the techniques implemented in Psyco to
PyPy. PyPy will allow us to build a more flexible JIT specializer,
easier to experiment with, and without the overhead of having to keep
in sync with the evolutions of the Python language."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is a "real" C-Python possible?

2007-12-09 Thread Terry Reedy

"Jack" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| The second articple does have a column for Psyco. It helps in some areas
| but still not good enough to stand up against Java. Plus, Psyco is not 
the
| main stream and has stopped development.

It further development is effectively part of the PyPy project, which 
includes some jit work.

| I'm also wondering, if Psyco is the right way to do, any reason it's not
| being integrated into standard Python?

It does not accelerate everything and may slow somethings, it was (is?) 
not compatible with everything, it bloats space requirements, it competes 
with C/Fortran coded extensions (such as NumPy), it was originally I386 
specific, its development cycle was much faster than Python's release 
cycle, ...

The cutoff between what goes in the core/stdlib is arbitrary in borderline 
cases, but some cutoff is necessary.

tjr



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


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Adonis Vargas
Seongsu Lee wrote:
> Hi,
> 
> I have a dictionary with million keys. Each value in the
> dictionary has a list with up to thousand integers.
> Follow is a simple example with 5 keys.
> 
> dict = {1: [1, 2, 3, 4, 5],
>2: [10, 11, 12],
>90: [100, 101, 102, 103, 104, 105],
>91: [20, 21, 22],
>99: [15, 16, 17, 18, 19]}
> 
> I want to find out the key value which has a specific
> integer in the list of its value. For example, if I search
> 104 in the list, 90 must be returned.
> 
> How can I do this with Python? Ideas?

You can try this:

items = {1: [1, 2, 3, 4, 5],
  2: [10, 11, 12],
  90: [100, 101, 102, 103, 104, 105],
  91: [20, 21, 22],
  99: [15, 16, 17, 18, 19]}

def findItem(item, dictionary):
 for key, value in dictionary.iteritems():
 if item in value:
 print key, value

findItem(104, items)

This will allow you to work with the existing dataset without needing to 
duplicate it. It will print all occurrances.

Also, you should never use reserved words like 'dict' this creates 
confusion and can cause Python to misbehave since you are rebinding the 
name.

Hope this helps.

Adonis Vargas

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


Re: Is a "real" C-Python possible?

2007-12-09 Thread Paul McGuire
On Dec 9, 6:07 pm, "Jack" <[EMAIL PROTECTED]> wrote:
> Plus, Psyco is not the
> main stream and has stopped development.
>



What makes you think it has stopped development?  I just swung by the
SF project page, and its most recent news post was just 2 months ago.

Psyco may not be in the standard Python distribution, but it is
definitely a fixture of the Python landscape, which is about as close
to main stream as you can get.

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


Re: Newbie edit/compile/run cycle question

2007-12-09 Thread Jan Claeys
Op Sun, 09 Dec 2007 01:11:28 +, schreef Jeremy C B Nicoll:

> What command (in XP) does one need to issue to syntax check a saved
> python script without running it?
> 
> Does a syntax check report all syntax errors or just the first one
> found?

python -c "import py_compile; py_compile.compile(r'FILENAME')"

... where FILENAME is the filename of the python script you want to check.

What this does in practice is (trying to) compile the source, and any 
errors or warnings will be reported.


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


Re: Distinguishing attributes and methods

2007-12-09 Thread Steve Howell

--- Jan Claeys <[EMAIL PROTECTED]> wrote:
> 
> To conclude this discussion:
> 
>  * in Python, methods are attributes
>  * in Ruby, attributes are methods
> 

So clearly one of the languages has it all wrong. ;)




  

Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distinguishing attributes and methods

2007-12-09 Thread Jan Claeys
Op Sun, 09 Dec 2007 12:44:46 -0800, schreef MonkeeSage:

> The point is that just because the attributes are "looked up the same
> way" or whatever, doesn't make them the same *kind* of attribute. To say
> that all attributes are the same in python muddies the water. They are
> the same in a generic sense that they are attributes, but not in their
> particular qualities. Like saying "all humans are the same" -- yes, in a
> general sense of being human. But to leave it at that is not very
> helpful.

Well, I guess Python is a language for human being...  ;-)


To conclude this discussion:

 * in Python, methods are attributes
 * in Ruby, attributes are methods


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


Re: dictionary of dictionaries

2007-12-09 Thread kettle
On Dec 9, 5:49 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sun, 09 Dec 2007 00:35:18 -0800, kettle wrote:
> > Hi,
> >  I'm wondering what the best practice is for creating an extensible
> > dictionary-of-dictionaries in python?
>
> >  In perl I would just do something like:
>
> > my %hash_of_hashes;
> > for(my $i=0;$i<10;$i++){
> > for(my $j=0;$j<10;$j++){
> >${$hash_of_hashes{$i}}{$j} = int(rand(10));
> > }
> > }
>
> > but it seems to be more hassle to replicate this in python.  I've
> > found a couple of references around the web but they seem cumbersome.
> > I'd like something compact.
>
> Use `collections.defaultdict`:
>
> from collections import defaultdict
> from random import randint
>
> data = defaultdict(dict)
> for i in xrange(11):
> for j in xrange(11):
> data[i][j] = randint(0, 10)
>
> If the keys `i` and `j` are not "independent" you might use a "flat"
> dictionary with a tuple of both as keys:
>
> data = dict(((i, j), randint(0, 10)) for i in xrange(11) for j in xrange(11))
>
> And just for completeness: The given data in the example can be stored in a
> list of lists of course:
>
> data = [[randint(0, 10) for dummy in xrange(11)] for dummy in xrange(11)]
>
> Ciao,
> Marc 'BlackJack' Rintsch

Thanks for the heads up.  Indeed it's just as nice as perl.  One more
question though, this defaultdict seems to only work with python2.5+
in the case of python < 2.5 it seems I have to do something like:
#!/usr/bin/python
from random import randint

dict_dict = {}
for x in xrange(10):
for y in xrange(10):
r = randint(0,10)
try:
dict_dict[x][y] = r
except:
if x in dict_dict:
dict_dict[x][y] = r
else:
dict_dict[x] = {}
dict_dict[x][y] = r

what I really want to / need to be able to do is autoincrement the
values when I hit another word.  Again in perl I'd just do something
like:

my %my_hash;
while(){
  chomp;
  @_ = split(/\s+/);
  grep{$my_hash{$_}++} @_;
}

and this generalizes transparently to a hash of hashes or hash of a
hash of hashes etc.  In python < 2.5 this seems to require something
like:

for line in file:
  words = line.split()
  for word in words:
my_dict[word] = 1 + my_dict.get(word, 0)

which I guess I can generalize to a dict of dicts but it seems it will
require more if/else statements to check whether or not the higher-
level keys exist.  I guess the real answer is that I should just
migrate to python2.5...!

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


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Jeremy C B Nicoll
Seongsu Lee <[EMAIL PROTECTED]> wrote:

> The reason I use the dict for my data is to speed up the search by key.

Ok, I understand that once the overhead of creating the dict has been done,
getting access to values within it is quick.  And taking the time to create
a set of reverse keys speeds up the reverse access.

Rather than scanning the whole dict and creating reverse keys for everything
in it first, there might be an advantage in making search logic test if
there is a reverse key for the negative integer to be searched for, and if
so use it, otherwise scan the dict creating and examining reverse keys until
the integer is found.  That way if the integer you're looking for is early
in the dict you'd only create reverse keys for the integers from the start
of the dict until the required one.  


We don't know what external(?) process created the data that you've stored
in the dict, nor what you use it for - or more to the point - how often.  If
you're going to make just one search of that data then there's little point
in having a fast search after a slow dict creation.  On the other hand if
you have many many searches to do the initial overhead might be acceptable.


(I don't know how slow creating the dict would be for a typical example of a
million keys each keying lists of 1-1000 integers.) 
 
> The code could create also a reverse index (a reverse dict) at the
> time. But as you said, it waste the space and I wanted to ask someone
> who may know some way to reduce the waste of space while searching
> fast.

Is the dict used by anything else?  If the data in it was held in some other
form would that cause your program (or other programs) lots of problems?  If
the range of values of the integers being stored is suitable, you might
sensibly use several or many smaller dicts to store all the data (and thus
save time reverse-keying much less of it).

-- 
Jeremy C B Nicoll - my opinions are my own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Seongsu Lee
On 12월10일, 오전6시49분, Jeremy C B Nicoll <[EMAIL PROTECTED]> wrote:
> Seongsu Lee <[EMAIL PROTECTED]> wrote:
> > Hi,
>
> > I have a dictionary with million keys. Each value in the
> > dictionary has a list with up to thousand integers.
> > Follow is a simple example with 5 keys.
>
> > dict = {1: [1, 2, 3, 4, 5],
> >2: [10, 11, 12],
> >90: [100, 101, 102, 103, 104, 105],
> >91: [20, 21, 22],
> >99: [15, 16, 17, 18, 19]}
>
> > I want to find out the key value which has a specific
> > integer in the list of its value. For example, if I search
> > 104 in the list, 90 must be returned.
>
> Are the integers in the lists unique?  I mean, could 104 occur in more than
> one list?  If it did, would it matter which key was returned?

Yes, the intergers in the lists are unique.

> > How can I do this with Python? Ideas?
>
> When I see something like this my natural response is to think that the data
> structure is inappropriate for the use it's being put to.  
>
> The code someone else posted to reverse the keys is all very well, but
> surely hugely wasteful on cpu, maybe storage, and elapsed time.
>
> Even if the dict in this form is needed for some other reason, couldn't the
> code that created it also create a reverse index at the same time?

The reason I use the dict for my data is to speed up the search by
key.

The code could create also a reverse index (a reverse dict) at the
time. But as you said, it waste the space and I wanted to ask someone
who may know some way to reduce the waste of space while searching
fast.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Are Python deques linked lists?

2007-12-09 Thread Neil Cerutti
On 2007-12-09, Just Another Victim of the Ambient Morality
<[EMAIL PROTECTED]> wrote:
> I'm looking for a linked list implementation.  Something
> iterable with constant time insertion anywhere in the list.  I
> was wondering if deque() is the class to use or if there's
> something else.  Is there?

The deque is implemented as a list of arrays. See 5.12.1 Recipes
for the trick of using rotate to delete an item from within the
deque. The docs don't spell out the efficiency (in terms of O
notation) of the rotate method, though. You'll have check the
source, or perhaps Raymond is reading and could explain.

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


Re: a Python person's experience with Ruby

2007-12-09 Thread Steve Howell

--- MonkeeSage <[EMAIL PROTECTED]> wrote:

> On Dec 9, 6:23 pm, MonkeeSage <[EMAIL PROTECTED]>
> wrote:
> > Hi Bruno,
> >
> > I think that we've been having a mainly "semantic"
> (pun intended)
> > dispute. I think you're right, that we've been
> using the same words
> > with different meanings.
> >

I think Ruby and Python have lots of false cognates,
or faux amis.

> > 
> > But at the same time, I can see how my python
> example can be seen as
> > *wildly* different (WTF?) as well. Maybe there is
> no easy way to
> > provide a true formally equivalent translation due
> to the
> > implementation differences of the languages (or if
> Saphir-Whorf is
> > right, maybe we just can't think of it! ;)
> >

I think that there is an inherent difficulty in
translation here.  To give a metaphor, it's
impossible, or at least very difficult, to explain, in
French, how certain English phrases translate to
French, without your French sounding a little English,
or just downright wrong.  And vice versa.






  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ 

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


Re: regular expression for nested parentheses

2007-12-09 Thread MRAB
On Dec 9, 10:12 pm, John Machin <[EMAIL PROTECTED]> wrote:
> On Dec 10, 8:53 am, Noah Hoffman <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 9, 1:41 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
> > > A pattern that can validly be described as a "regular expression"
> > > cannot count and thus can't match balanced parentheses. Some "RE"
> > > engines provide a method of tagging a sub-pattern so that a match must
> > > include balanced () (or [] or {}); Python's doesn't.
>
> > Okay, thanks for the clarification. So recursion is not possible using
> > python regular expressions?
>
> > > Ummm ... even if Python's re engine did do what you want, wouldn't you
> > > need flags=re.VERBOSE in there?
>
> > Ah, thanks for letting me know about that flag; but removing
> > whitespace as I did with the no_ws lambda expression should also work,
> > no?
>
> Under a very limited definition of "work". That technique would not
> produce correct answers on patterns that contain any *significant*
> whitespace e.g. you want to match "foo" and "bar" separated by one or
> more spaces (but not tabs, newlines etc) 
> pattern = r"""
> foo
> [ ]+
> bar
> """

You can also escape a literal space:

pattern = r"""
foo
\ +
bar
"""
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Zepo Len
> I have a dictionary with million keys. Each value in the
> dictionary has a list with up to thousand integers.
> Follow is a simple example with 5 keys.
>
> dict = {1: [1, 2, 3, 4, 5],
>2: [10, 11, 12],
>90: [100, 101, 102, 103, 104, 105],
>91: [20, 21, 22],
>99: [15, 16, 17, 18, 19]}
>
> I want to find out the key value which has a specific
> integer in the list of its value. For example, if I search
> 104 in the list, 90 must be returned.
>
> How can I do this with Python? Ideas?

def find_key(dict, num):
   for k in dict:
 if num in dict[k]:
   return k
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Capturing global input?

2007-12-09 Thread nomihn0
Thanks to all, you were very helpful.  I suppose I'll use Jython after
all.

On Dec 6, 10:17 pm, MonkeeSage <[EMAIL PROTECTED]> wrote:
> On Dec 6, 9:16 pm, MonkeeSage <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Dec 6, 3:51 pm, nomihn0 <[EMAIL PROTECTED]> wrote:
>
> > > I'd like to accept mouse gestures and keyboard shortcuts as input to a
> > > program. The nature of this program requires that these commands be
> > > issued regardless of the currently active window. Here's the rub: I
> > > need a platform-independent solution.
>
> > > Java supports with its MouseInfo class, but I'd like a Python
> > > equivalent without turning to Jython.  Is this possible?
>
> > > Thanks in advance.
>
> > There is no cross-platform way to do that. You have to use whatever
> > interface the OS provides for that (e.g., Xlib events for X11). You
> > could probably write a platform independent way by testing the OS and
> > using the appropriate apis for that OS (assuming that there are python
> > modules like python-xlib for other OS). I wonder why you'd want to
> > though, if Java already provides a solution? If you don't want to muck
> > with Java syntax, what about Jython?
>
> > Regards,
> > Jordan
>
> Ps. I saw you said you didn't want Jython, but I can't see why.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
On Dec 9, 6:23 pm, MonkeeSage <[EMAIL PROTECTED]> wrote:
> Hi Bruno,
>
> I think that we've been having a mainly "semantic" (pun intended)
> dispute. I think you're right, that we've been using the same words
> with different meanings.
>
> I would like to say firstly that I've been using python for a few
> years now (about three I think), and I think I have a basic grasp of
> the object system and so forth (e.g., I understood your example with
> the apply decorator and properties). I read the docs when I first
> started learning python (along with Fredrik Lundh's page about python
> objects and more recently "call by object"). But I also own up to my
> ignorance. I'm not a guru by any means. So you'll have to forgive me
> if my ignorance has gotten in the way. I'll definitely re-read the
> docs tonight.
>
> I would like to (try to) clarify a little about my use of wording. By
> "attribute" I was referring to a member of an object (*other than*
> toplevel). I was of course using "method" to refer to callable
> attributes (and I would use "function" for callable attributes bound
> to toplevel), and I was using "variable" to refer to non-callable
> attributes. By "tagging" I meant that attributes without a
> "tag" (e.g., __call__) are not included in the MRO for an object; they
> must be "tagged" as something other than a "variable".
>
> As for ruby, I think the opcodes will help me clarify...
>
> >> require 'parse_tree'
> => true
> >> ParseTree.translate(%q{
>
> class A
>   def foo
> "bar"
>   end
> end
> A.new.foo})
>
> => [:block, [:class, :A, nil, [:scope, [:defn, :foo, [:scope, [:block,
> [:args], [:str, "bar"]], [:call, [:call,
> [:const, :A], :new], :foo]]
>
> Notice that #new and #foo are both CALL ops. All attribute access is
> CALL (i.e., "method"). There really is no such thing as a non-callable
> "attribute" in ruby. Within the scope of a class (block, &c), there
> can be non-callable members of course (LVAL), but "foo" can mean
> either LVAL *or* FCALL, because there is no "tagging", it's just
> whatever is in context and/or parsed first as a given type of object
> (well there are a few other rules, but that's the main idea), with
> "()" is a hint to help the parser when the expression is ambiguous:
>
> a = 1
> def a; 2; end
> a   # [:lval :a] == a = 1
> a() # [:fcall :a] == def ...
>
> Given this, I see the addition the instance variable also being an
> attribute as a *huge* difference between the ruby code and your
> initial example. An attribute can be named the same as an lval and
> return or set the value of the lval (e.g., @a), but it's no different
> from any other method.
>
> class A
>   def initialize; @a = "blah"; end
>   attr_reader :a
>   def cheese; @a; end # exactly equivalent
> end
>
> But at the same time, I can see how my python example can be seen as
> *wildly* different (WTF?) as well. Maybe there is no easy way to
> provide a true formally equivalent translation due to the
> implementation differences of the languages (or if Saphir-Whorf is
> right, maybe we just can't think of it! ;)
>
> Anyhow, sorry for the confusion.
>
> Regards,
> Jordan

Ps. To answer a question you asked, "callable" objects don't generally
implement a #call method--just Proc objects and method references
[class Method instances] do, which even though they have a #call
method, aren't usually considered "callable" since you can't call them
directly--the #call method could as easily be named #run or #evaluate
or whatever. Accessing a name in ruby basically does something like:
VCALL name (== if parens on name like a() skip to call step, otherwise
check for LVAL in scope and return value if found, otherwise FCALL/
CALL and return result). You can use the #define_method method to
create a new "callable."

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


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
Hi Bruno,

I think that we've been having a mainly "semantic" (pun intended)
dispute. I think you're right, that we've been using the same words
with different meanings.

I would like to say firstly that I've been using python for a few
years now (about three I think), and I think I have a basic grasp of
the object system and so forth (e.g., I understood your example with
the apply decorator and properties). I read the docs when I first
started learning python (along with Fredrik Lundh's page about python
objects and more recently "call by object"). But I also own up to my
ignorance. I'm not a guru by any means. So you'll have to forgive me
if my ignorance has gotten in the way. I'll definitely re-read the
docs tonight.

I would like to (try to) clarify a little about my use of wording. By
"attribute" I was referring to a member of an object (*other than*
toplevel). I was of course using "method" to refer to callable
attributes (and I would use "function" for callable attributes bound
to toplevel), and I was using "variable" to refer to non-callable
attributes. By "tagging" I meant that attributes without a
"tag" (e.g., __call__) are not included in the MRO for an object; they
must be "tagged" as something other than a "variable".

As for ruby, I think the opcodes will help me clarify...

>> require 'parse_tree'
=> true
>> ParseTree.translate(%q{
class A
  def foo
"bar"
  end
end
A.new.foo
})
=> [:block, [:class, :A, nil, [:scope, [:defn, :foo, [:scope, [:block,
[:args], [:str, "bar"]], [:call, [:call,
[:const, :A], :new], :foo]]

Notice that #new and #foo are both CALL ops. All attribute access is
CALL (i.e., "method"). There really is no such thing as a non-callable
"attribute" in ruby. Within the scope of a class (block, &c), there
can be non-callable members of course (LVAL), but "foo" can mean
either LVAL *or* FCALL, because there is no "tagging", it's just
whatever is in context and/or parsed first as a given type of object
(well there are a few other rules, but that's the main idea), with
"()" is a hint to help the parser when the expression is ambiguous:

a = 1
def a; 2; end
a   # [:lval :a] == a = 1
a() # [:fcall :a] == def ...

Given this, I see the addition the instance variable also being an
attribute as a *huge* difference between the ruby code and your
initial example. An attribute can be named the same as an lval and
return or set the value of the lval (e.g., @a), but it's no different
from any other method.

class A
  def initialize; @a = "blah"; end
  attr_reader :a
  def cheese; @a; end # exactly equivalent
end

But at the same time, I can see how my python example can be seen as
*wildly* different (WTF?) as well. Maybe there is no easy way to
provide a true formally equivalent translation due to the
implementation differences of the languages (or if Saphir-Whorf is
right, maybe we just can't think of it! ;)

Anyhow, sorry for the confusion.

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


Re: a Python person's experience with Ruby

2007-12-09 Thread Steve Howell

--- Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:

> Steve Howell a écrit :
> (snip)
> > 
> > Jordan and others, thanks for all your posts; I am
> > learning a lot about both languages.
> > 
> > This is what I've gathered so far.
> > 
> > Python philosophy:
> >passing around references to methods should be
> > natural (i.e. my_binary_op = math.add)
> >calling methods should be explicit (use parens)
> >the use of setters/getters varies among Python
> > programmers; properties, decorators, special
> methods,
> > etc. can be used judiciously to affect the
> interface
> 
> You can forget decorators here - the examples in
> this thread were mostly 
> tricky ways to define properties. To be more
> general, the Python way to 
> implement transparent computed attributes is to hook
> into the lookup 
> mechanism, usually thru the descriptor protocol (the
> property class 
> being one possible implementation), but also using
> the __getattr__ / 
> __getattribute / __setattr__ hooks.
>

Ok, that makes sense.
 
> > Ruby philosophy:
> >a method itself should be callable without
> parens
> >you can get a reference to a chunk of code, but
> > then you need a little extra syntax, beyond just a
> > variable name and parens, to eventually call it
> > (yield, &, call, etc.)
> >when referring to methods, you can use :symbols
> to
> > name the method you're interested in without
> actually
> > calling it
> > 
> > My personal experience:
> > 
> (snip)
>  >
> >I was surprised in Ruby by how seldom I really
> pass
> > references to methods around,
> 
> This probably has to do with this nice feature named
> 'blocks' !-)
> 

Partly.  It's also due to the fact that my experience
so far in Ruby has mostly been writing code at the top
layer of a fairly vanilla Rails MVC app, whereas in
Python I've done a much wider variety of tasks.




  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ 

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


Re: changing fonts?

2007-12-09 Thread greg
[EMAIL PROTECTED] wrote:

> I took Greg's idea and found this web-site:
> 
> http://www.unicode.org/charts/PDF/U0370.pdf
> 
> which gave me all the unicode characters for the Greek font.

You can also use the MacOSX Character Palette to go hunting
for unicode characters. You can get to it from Terminal using
"Special Characters..." on the Edit menu. There's a search
box down the bottom where you can enter part of the unicode
name of a character, e.g. "GREEK" will get you into the greek
alphabet area.

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


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Jeremy C B Nicoll
[EMAIL PROTECTED] wrote:

> Jeremy C B Nicoll:
> > The code someone else posted ...
> 
> If you are talking about my D code then I know it...

No I meant the code that used python to iterate over the dict and create
zillions of extra keys.  I've deleted earlier posts in the thread and wasn't
sure who suggested that.

-- 
Jeremy C B Nicoll - my opinions are my own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is a "real" C-Python possible?

2007-12-09 Thread Jack

>> I think most Java-Python benchmarks you can find online will indicate
>> that Java is a 3-10 times faster. A few here:
>> http://mail.python.org/pipermail/python-list/2002-January/125789.html
>> http://blog.snaplogic.org/?p=55
>
> There are lies, damn lies and benchmarks. :)
>
> Pure Python code is not going to beat Java code until the Python core
> gets a  JIT compiler. If you want fair results you have to either
> disable the JIT in Java or use Psyco for Python. Otherwise you are
> comparing the quality of one language implementation to the quality of a
> JIT compiler.

The second articple does have a column for Psyco. It helps in some areas
but still not good enough to stand up against Java. Plus, Psyco is not the
main stream and has stopped development.

I'm also wondering, if Psyco is the right way to do, any reason it's not
being integrated into standard Python? 


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


ZODB List

2007-12-09 Thread Flavio
Hi,

I am a big fan of ZODB and use it stand alone on many project of mine.
One of the things I miss is a community around it. I don't care much
about ZOPE (though I admire it) and have not being able  to find  a
ZODB focused community. Is there one?

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


how to get module globals into a class ?

2007-12-09 Thread stef mientki
hello,

this question may look a little weird,
but I want to create library shells that are a simple as possible.

So I've a module where one base class is defined,
which looks like this (and might be complex)

base_class_file.py
class brick_base ( object ) :
  

now I've a lot of library files,
in each library file are a lot of classes,
and each library-file, has some specific parameters, like "library_color",
so something like this:

library_file.py
library_color = ...

class brick_do_something1( brick_base ) :
init :
self.Library_Color = Library_Color


class brick_do_something2( brick_base ) :
init :
self.Library_Color = Library_Color


Now this works fine, ...
... but the statement "self.Library_Color = Library_Color"
is completely redundant, because it should be in every class of every 
librray file.
So I would like to move this statement to the base-class-file,
but I can't figure out how to accomplish that.

thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Are Python deques linked lists?

2007-12-09 Thread John Machin
On Dec 10, 9:43 am, "Just Another Victim of the Ambient Morality"
<[EMAIL PROTECTED]> wrote:
> I'm looking for a linked list implementation.  Something iterable with
> constant time insertion anywhere in the list.

It's on the shelf between the jar of phlogiston and the perpetual
motion machine.

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


Are Python deques linked lists?

2007-12-09 Thread Just Another Victim of the Ambient Morality
I'm looking for a linked list implementation.  Something iterable with 
constant time insertion anywhere in the list.  I was wondering if deque() is 
the class to use or if there's something else.  Is there?
Thank you... 


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


Re: Is a "real" C-Python possible?

2007-12-09 Thread Terry Reedy

"Jack" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I understand that the standard Python distribution is considered
| the C-Python. Howerver, the current C-Python is really a combination
| of C and Python implementation. There are about 2000 Python files
| included in the Windows version of Python distribution.

About half or fewer are modules meant to be imported into programs.  The 
rest comprise utility programs and test programs.  The core interpreter is 
all C.

| because the core modules that matter are already in C

Correct.  There are about 20 'builtin' modules written is C either because 
they need low level access to the machine or for speed concerns.  Third 
party modules not included in the standard distribution but definitely part 
of the Python universe are also a mix.

If people wrote everything in C for speed, there would be no need for 
Python!!

And don't say that you want everyone else to write in C while you enjoy the 
pleasures of Python ;-).

tjr



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


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread bearophileHUGS
Jeremy C B Nicoll:
> The code someone else posted to reverse the keys is all very well, but
> surely hugely wasteful on cpu, maybe storage, and elapsed time.

If you are talking about my D code then I know it, the creation of the
first dict has to be skipped, if possible... The code I have posted
must be adapted.

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is a "real" C-Python possible?

2007-12-09 Thread Christian Heimes
Jack wrote:
> I guess this is subjective :) - that's what I felt in my experience
> with web applications developed in Python and PHP. I wasn't able to
> find a direct comparison online.

Please compare the number of serious bugs and vulnerabilities in PHP and
Python.

> I understand. Python modules implemented in Python - this is how
> Python gets its really rich library.

Correct
Python code is much easier to write and multiple times easier to get
right than C code. Everybody with a few months of Python experience can
contribute to the core but it requires multiple years of C and Python
experience to contribute to the C implementation.

> I think most Java-Python benchmarks you can find online will indicate
> that Java is a 3-10 times faster. A few here:
> http://mail.python.org/pipermail/python-list/2002-January/125789.html
> http://blog.snaplogic.org/?p=55

There are lies, damn lies and benchmarks. :)

Pure Python code is not going to beat Java code until the Python core
gets a  JIT compiler. If you want fair results you have to either
disable the JIT in Java or use Psyco for Python. Otherwise you are
comparing the quality of one language implementation to the quality of a
JIT compiler.

> Here's an article that shows the new version of Ruby is
> faster than Python in some aspects (they are catching up :)
> http://antoniocangiano.com/2007/11/28/holy-shmoly-ruby-19-smokes-python-away/ 

The Ruby developers are allowed to be proud. They were able to optimize
some aspects of the implementation to get one algorithm about 14 times
faster. That's good work. But why was it so slow in the first place?

Nevertheless it is just one algorithm that beats Python in an area that
is well known to be slow. Python's numbers are several factors slower
than C code because the overhead of the dynamic language throws lots of
data out of the cache line. If you need fast and highly optimized int
and floating point operations you can rewrite the algorithm in C and
create a Python interface for it.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: changing fonts?

2007-12-09 Thread jyoung79
Hi Doug,

> I'm not *that* familiar with the Terminal program on OS/X, but regardless
> perhaps I can point out a possibly useful path to explore...

Wow!!  Thanks for all this info!!  This is some good stuff!!!  :-)

Well, I got to experimenting with a lot of different stuff, as well as doing a 
lot
of research on the net, and I think I've found what I was looking for.  It's not
perfect, but I'm thrilled I was able to do this!  I never could find anything on
changing the actual font (or character set) on-line, and looking through the
man pages I couldn't figure out if it was possible there either, although I'm
still new to this stuff so a lot of it could just be my ignorance.

I took Greg's idea and found this web-site:

http://www.unicode.org/charts/PDF/U0370.pdf

which gave me all the unicode characters for the Greek font.  I wrote a simple 
Python script to test this (only on Mac OS X 10.5 at the moment):

--
import os

os.system("clear")
print '\033[36m', u'\u03B1\u03C1\u03C4\u03BF\u03C2', '\033[37m', 'This is
the Greek word for "Bread"', '\033[0m'
--

As you can see, I also added some escape sequences to color the text in the
Terminal window as well.  And it works great!!  Note that I have Terminal
set up with the 'Monaco' font.

Thanks again, Greg and Doug, for your incredible help of not only steering
me in the right direction, but also teaching me new techniques which are
definitely going to come in handy!  :-)

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


Re: Is a "real" C-Python possible?

2007-12-09 Thread Shadowsithe
That first article is five years old... I wouldn't give too much
weight to it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Recommendations for writing a user guide with examples?

2007-12-09 Thread Terry Reedy

"Paddy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| On Dec 8, 9:22 pm, Neal Becker <[EMAIL PROTECTED]> wrote:
| > I'm looking for recommendations for writing a user manual.  It will 
need
| > lots of examples of command line inputs and terminal outputs.
| >
| > I'd like to minimize the effort to integrate the terminal input/output 
into
| > my document.  I have lots of experience with latex, but I wonder if 
there
| > may be some other choices.  Maybe docutils, pydoc, something else?  The
| > code I'm documenting is written in python, if that matters.
|
| Doctest and restructuredtext.
| http://docutils.sourceforge.net/docs/user/rst/quickref.html

Doctest is definitely the way to go to test input/output examples.
It can be used with text output from any editor/word processor that 
preserves the example block.  I have used it with .txt versions of an 
OpenOffice .odt file.

The Python docs master copies are, I believe, changing from Latex to RST 
for 2.6.  So that seems like a plausible choice for someone who wants 
visible markup instead of wysiwyg.

tjr






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


Re: regular expression for nested parentheses

2007-12-09 Thread John Machin
On Dec 10, 8:53 am, Noah Hoffman <[EMAIL PROTECTED]> wrote:
> On Dec 9, 1:41 pm, John Machin <[EMAIL PROTECTED]> wrote:
>
> > A pattern that can validly be described as a "regular expression"
> > cannot count and thus can't match balanced parentheses. Some "RE"
> > engines provide a method of tagging a sub-pattern so that a match must
> > include balanced () (or [] or {}); Python's doesn't.
>
> Okay, thanks for the clarification. So recursion is not possible using
> python regular expressions?
>
> > Ummm ... even if Python's re engine did do what you want, wouldn't you
> > need flags=re.VERBOSE in there?
>
> Ah, thanks for letting me know about that flag; but removing
> whitespace as I did with the no_ws lambda expression should also work,
> no?

Under a very limited definition of "work". That technique would not
produce correct answers on patterns that contain any *significant*
whitespace e.g. you want to match "foo" and "bar" separated by one or
more spaces (but not tabs, newlines etc) 
pattern = r"""
foo
[ ]+
bar
"""
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread Bruno Desthuilliers
Steve Howell a écrit :
(snip)
> 
> Jordan and others, thanks for all your posts; I am
> learning a lot about both languages.
> 
> This is what I've gathered so far.
> 
> Python philosophy:
>passing around references to methods should be
> natural (i.e. my_binary_op = math.add)
>calling methods should be explicit (use parens)
>the use of setters/getters varies among Python
> programmers; properties, decorators, special methods,
> etc. can be used judiciously to affect the interface

You can forget decorators here - the examples in this thread were mostly 
tricky ways to define properties. To be more general, the Python way to 
implement transparent computed attributes is to hook into the lookup 
mechanism, usually thru the descriptor protocol (the property class 
being one possible implementation), but also using the __getattr__ / 
__getattribute / __setattr__ hooks.

> Ruby philosophy:
>a method itself should be callable without parens
>you can get a reference to a chunk of code, but
> then you need a little extra syntax, beyond just a
> variable name and parens, to eventually call it
> (yield, &, call, etc.)
>when referring to methods, you can use :symbols to
> name the method you're interested in without actually
> calling it
> 
> My personal experience:
> 
(snip)
 >
>I was surprised in Ruby by how seldom I really pass
> references to methods around,

This probably has to do with this nice feature named 'blocks' !-)

> but it is definitely
> something I want to understand better.
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regular expression for nested parentheses

2007-12-09 Thread Noah Hoffman
On Dec 9, 1:41 pm, John Machin <[EMAIL PROTECTED]> wrote:

> A pattern that can validly be described as a "regular expression"
> cannot count and thus can't match balanced parentheses. Some "RE"
> engines provide a method of tagging a sub-pattern so that a match must
> include balanced () (or [] or {}); Python's doesn't.

Okay, thanks for the clarification. So recursion is not possible using
python regular expressions?

> Ummm ... even if Python's re engine did do what you want, wouldn't you
> need flags=re.VERBOSE in there?

Ah, thanks for letting me know about that flag; but removing
whitespace as I did with the no_ws lambda expression should also work,
no?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Jeremy C B Nicoll
Seongsu Lee <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I have a dictionary with million keys. Each value in the
> dictionary has a list with up to thousand integers.
> Follow is a simple example with 5 keys.
> 
> dict = {1: [1, 2, 3, 4, 5],
>2: [10, 11, 12],
>90: [100, 101, 102, 103, 104, 105],
>91: [20, 21, 22],
>99: [15, 16, 17, 18, 19]}
> 
> I want to find out the key value which has a specific
> integer in the list of its value. For example, if I search
> 104 in the list, 90 must be returned.

Are the integers in the lists unique?  I mean, could 104 occur in more than
one list?  If it did, would it matter which key was returned?

> How can I do this with Python? Ideas?

When I see something like this my natural response is to think that the data
structure is inappropriate for the use it's being put to.  

The code someone else posted to reverse the keys is all very well, but
surely hugely wasteful on cpu, maybe storage, and elapsed time.

Even if the dict in this form is needed for some other reason, couldn't the
code that created it also create a reverse index at the same time?

-- 
Jeremy C B Nicoll - my opinions are my own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread Bruno Desthuilliers
MonkeeSage a écrit :
> On Dec 9, 1:58 pm, MonkeeSage <[EMAIL PROTECTED]> wrote:
> 
> 
>> Sure. But as I understand, every attribute in python is a value,
> 
> 
> sorry...*references* a value
> 
So make it: 'reference an object'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread Bruno Desthuilliers
MonkeeSage a écrit :
> On Dec 8, 4:54 pm, Bruno Desthuilliers
> <[EMAIL PROTECTED]> wrote:
> 
>>MonkeeSage a écrit :
>>
>>
>>
>>
>>>On Dec 8, 12:42 pm, Bruno Desthuilliers
>>><[EMAIL PROTECTED]> wrote:
>>
MonkeeSage a écrit :
>>
>On Dec 7, 11:08 pm, Steve Howell <[EMAIL PROTECTED]> wrote:
>>
(snip)
>>
>>4) Ruby forces you to explicitly make attributes for
>>instance variables.  At first I found this clumsy, but
>>I've gotten used to it, and I actually kind of like it
>>in certain circumstances.
>>
>4.) Yeah, it's hard when learning ruby, especially if coming from
>languages that distinguish between methods and attributes,
>>
which is not the case in Python
>>
>>>It is, I just wasn't absolutely precise (uh-oh, here comes the
>>>semantics police! -- don't pass GO, don't collect $200, go strait to
>>>jail!). Python *does* distinguish between instance/class vars and
>>>instance/class methods. But in ruby no such distinction exists.
>>>Accessing a "variable" in ruby == calling object.var. I.e., in ruby,
>>>when you say "blah.x" that translates to "blah.send(:x)", whether :x
>>>is a "variable" or a "method," since *everything* is a method. The
>>>call model of ruby is more like smalltalk.
>>
>>I'm sorry to have to insist: Python doesn't distinguish between methods
>>and attributes. Calling a method in Python is really 1/ looking up an
>>attribute then 2/ applying the call operator on what the lookup eval'd
>>to. As a matter of fact, you can stop at the first step, and you'll have
>>a reference to whatever the lookup mechanism yielded for the given
>>attribute name on the given object. FWIW, Python's functions are plain
>>objects, and when used as attributes are stored in the same place as any
>>other attribute.
> 
> 
> Except that pthon does differentiate, as python variables are not
> callable, 

I beg your pardon ?

Python 2.4.3 (#1, Mar 12 2007, 23:32:01)
[GCC 3.3.4 20040623 (Gentoo Linux 3.3.4-r1, ssp-3.3.2-2, pie-8.7.6)] on 
linux2
Type "help", "copyright", "credits" or "license" for more information.
 >>> class Toto(object):
... def test(self): print self
... def __call__(self): print self
...
 >>> def boo(): print "boo"
...
 >>> Toto

 >>> # Toto is a variable. Is it callable ?
...
 >>> callable(Toto)
True
 >>> Toto()
<__main__.Toto object at 0x4033492c>
 >>> t = Toto()
 >>> t
<__main__.Toto object at 0x403344cc>
 >>> # t is a variable. Is it callable ?
... callable(t)
True
 >>> t()
<__main__.Toto object at 0x403344cc>
 >>> t.test
>
 >>> # t.test is a variable. is it callable ?
... callable(t.test)
True
 >>> t.test()
<__main__.Toto object at 0x403344cc>
 >>> t.foo
Traceback (most recent call last):
   File "", line 1, in ?
AttributeError: 'Toto' object has no attribute 'foo'
 >>> t.foo = boo
 >>> t.foo

 >>> # t.foo is a variable. Is it callable ?
... callable(t.foo)
True
 >>> t.foo()
boo
 >>>

> whereas everything in ruby is callable. blah.a in ruby means
> blah.send(:a). 

Ok, I see where the problem is. We definitively don't have the same 
definition of 'callable'. In Python, a callable is an object that can be 
called - that is, you can apply the call operator to it. You'd better 
get use to this definition when talking about Python, FWIW !-)

What you say is that in Ruby, you're *always* going thru a method call 
when accessing an attribute (from outside at least). The fact is that 
Ruby is built on 'true' (ie: à la Smalltalk) message passing, when 
Python is built on the attribute lookup operator and the call operator. 
As I said, while Python and Ruby have similarities, they are built on 
totally disjoint object models - different ways to get at the same thing...

> Which is why you need an accessor to get at instance
> variables, since as variables they exist in the scope scope of the
> class, but they are not callable so they are not attributes of the
> instance.

I would certainly not define it that way, but anyway...


>to get used
>to thinking of "a.a" and "a.a=" as method calls and defining accessors
>for those methods  (or using one of the attr_* keywords) in the class
>body.
>>
Python has an equivalent support for computed attributes, using property
or a custom descriptors. While it's a bit lower-level than Ruby, it's
still quite easy to use and IMHO a bit more powerful.
>>
>The equivalent python idiom is something like:
>>
>class A:
> __a = "foo"
> def __init__(self):
>   self.a = A.__a
>>
WTF ???
>>
>Which roughly translates to this in ruby:
>>
>class A
> attr_accessor :a
> def initialize
>   @a = "foo"
> end
>end
>>
The Python translation of the above Ruby snippet is actually way more
simple:
>>
class A(object):
  def __init__(self):
self.a = "foo"
>>
>>>Not really.
>>
>>Yes, really. Sorry to have to insist, but...
>>
>>
>>>In ruby an ivar is accessible within the class *only*, but
>>>not from without (like a mangled python class var), un

Re: Is a "real" C-Python possible?

2007-12-09 Thread Jorge Godoy
Jack wrote:

> I wonder if it's possible to have a Python that's completely (or at
> least for the most part) implemented in C, just like PHP - I think
> this is where PHP gets its performance advantage. Or maybe I'm wrong

PHP is slower than Python.

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


Re: [Python-3000] Possible Duck Typing Problem in Python 2.5?

2007-12-09 Thread Guilherme Polo
2007/12/9, hashcollision <[EMAIL PROTECTED]>:
> From http://ivory.idyll.org/blog/dec-07/conversions.html:
> class X:
>  internal = [5,6,7,8]
>  def __getitem__(self, i):
>  return self.internal[i]
>
> x = X()
>
> l = [1,2,3]
> print l + x
>
>
>
> fails withTypeError: can only concatenate list (not "instance") to list
> I tried:
> class X(list):
>  internal = [5, 6, 7, 8]
>
>  def __getitem__(self, i):
>   return self.internal[i]
>  def __len__(self):
>   return internal
>  def __iter__(self):
>   return internal.__iter__()
> but this fails also.

Try this:

class X(list):
  internal = [5, 6, 7, 8]
  def __init__(self):
list.__init__(self, self.internal)

x = X()
l = [1,2,3]
print l + x

> IMHO, this is a problem. Is it? If so, I suggest that it be fixed in python
> 3000.
>
> ___
> Python-3000 mailing list
> [EMAIL PROTECTED]
> http://mail.python.org/mailman/listinfo/python-3000
> Unsubscribe:
> http://mail.python.org/mailman/options/python-3000/ggpolo%40gmail.com
>
>


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


Re: Is a "real" C-Python possible?

2007-12-09 Thread Jack

>> I'm not sure
>>how much of the C-Python is implemented in C but I think the more
>>modules implemented in C, the better performance and lower memory
>>footprint it will get.
>
> Prove it.  ;-)

I guess this is subjective :) - that's what I felt in my experience
with web applications developed in Python and PHP. I wasn't able to
find a direct comparison online.

> Seriously, switching to more C code will cause development to bog down
> because Python is so much easier to write than C.

I understand. Python modules implemented in Python - this is how
Python gets its really rich library.

>>I wonder if it's possible to have a Python that's completely (or at
>>least for the most part) implemented in C, just like PHP - I think
>>this is where PHP gets its performance advantage. Or maybe I'm wrong
>>because the core modules that matter are already in C and those Python
>>files are really a thin wrapper. Anyhow, it would be ideal if Python
>>has performance similar to Java, with both being interpreted languages.
>
> Could you provide some evidence that Python is slower than Java or PHP?

I think most Java-Python benchmarks you can find online will indicate
that Java is a 3-10 times faster. A few here:
http://mail.python.org/pipermail/python-list/2002-January/125789.html
http://blog.snaplogic.org/?p=55

Here's an article that shows the new version of Ruby is
faster than Python in some aspects (they are catching up :)
http://antoniocangiano.com/2007/11/28/holy-shmoly-ruby-19-smokes-python-away/ 


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


Re: Is a "real" C-Python possible?

2007-12-09 Thread Diez B. Roggisch
Jack schrieb:
> I understand that the standard Python distribution is considered
> the C-Python. Howerver, the current C-Python is really a combination
> of C and Python implementation. There are about 2000 Python files
> included in the Windows version of Python distribution. I'm not sure
> how much of the C-Python is implemented in C but I think the more
> modules implemented in C, the better performance and lower memory
> footprint it will get.
> 
> I wonder if it's possible to have a Python that's completely (or at
> least for the most part) implemented in C, just like PHP - I think
> this is where PHP gets its performance advantage. Or maybe I'm wrong
> because the core modules that matter are already in C and those Python
> files are really a think wrapper. Anyhow, if would be ideal if Python
> has performance similar to Java, with both being interpreted languages.

Writing everything in C might be possible - but is a daunting task & not 
justified by the results. And wherever the standard libraries make use 
of the flexibility of Python, it's questionable if there really was any 
performance gain at all.

But what REALLY is questionable is the alleged performance advantage - 
how do you back that up? According to the well-known (and surely 
limited) computer language shootout

http://shootout.alioth.debian.org/gp4/benchmark.php?test=all&lang=all


Python is roughly 25% faster than PHP. Granted, this is just one 
benchmark, with questionable real-life relevance. But where do you get 
the impression from that PHP is faster than Python then?

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


Re: regular expression for nested parentheses

2007-12-09 Thread John Machin
On Dec 10, 8:13 am, Noah Hoffman <[EMAIL PROTECTED]> wrote:
> I have been trying to write a regular expression that identifies a
> block of text enclosed by (potentially nested) parentheses. I've found
> solutions using other regular expression engines (for example, my text
> editor, BBEdit, which uses the PCRE library), but have not been able
> to replicate it using python's re module.

A pattern that can validly be described as a "regular expression"
cannot count and thus can't match balanced parentheses. Some "RE"
engines provide a method of tagging a sub-pattern so that a match must
include balanced () (or [] or {}); Python's doesn't.

Looks like you need a parser; try pyparsing.

[snip]
> py> rexp = r"""(?P
> ... \(
> ... (?>
> ... (?> [^()]+ ) |
> ... (?P>parens)
> ... )*
> ... \)
> ... )"""
> py> print re.findall(no_ws(rexp), text)

Ummm ... even if Python's re engine did do what you want, wouldn't you
need flags=re.VERBOSE in there?

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


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
On Dec 9, 3:10 pm, I V <[EMAIL PROTECTED]> wrote:
> On Sun, 09 Dec 2007 11:58:05 -0800, MonkeeSage wrote:
> > class A
> >   attr_accessor :a # == self.a,
> ># accessible to instances of A
> >   def initialize
> > @a = "foo" # A.__a
> ># only accessible from class scope of A
> >   end
> > end
>
> > Once again, there is no such thing as an attribute that is not a method
> > in ruby, and there is no such thing as setting an *attribute* ("=" is a
> > method also). You're trying to *re-implement* rubys mechanism in python
> > in your example, but in pythons mechanism, all attributes already have
> > built-in getter/setter. So the correct analogy is a variable that is
> > accessible from within the classes scope only (A.__a), and then exposed
> > to instances through an attribute (self.a). Your example leaves out a
> > variable accessible only from within the scope of the class, and adds a
> > new attribute accessible from the instance (_a).
>
> Either I'm not understanding you, or you're not understanding what A.__a
> means in python. A.__a is a class attribute, not an instance attribute -
> it's equivalent to @@a in ruby, not @a.

I said previously that A.__a is a class variable. Since I was only
using it to show that @a is not exposed as an attribute, I just used
A.__a, but you're right, it would have been better to use self.__a.

> If I understand what you're
> saying, a better python example to make your point might be:
>
> class A(object):
> def __init__(self):
> self.__a = "foo" # equivalent to @a
> self.a = self.__a # exposes self.__a

Thanks.

> Except that this only allows you to access '__a' via the exposed
> attribute 'a', not bind it to a new object. If you do:
>
> inst = A()
> inst.a = "bar"
>
> you don't modify inst.__a, unlike the following ruby code, which does
> modify @a .
>
> inst = A.new
> inst.a = "bar"

I understand. That's why I said it was a rough translation of the ruby
code. I was only trying to say that it's strange when learning ruby,
to get your head around the idea that instance (and class) variables
are not attributes; that all attributes are callable. The example was
merely to demonstrate the distinction between instance method and
instance variable in ruby. The python isn't supposed to have the exact
same behavior, just a similar semantic.

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


Re: Is a "real" C-Python possible?

2007-12-09 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jack <[EMAIL PROTECTED]> wrote:
>
>I understand that the standard Python distribution is considered
>the C-Python. Howerver, the current C-Python is really a combination
>of C and Python implementation. There are about 2000 Python files
>included in the Windows version of Python distribution. I'm not sure
>how much of the C-Python is implemented in C but I think the more
>modules implemented in C, the better performance and lower memory
>footprint it will get.

Prove it.  ;-)

Seriously, switching to more C code will cause development to bog down
because Python is so much easier to write than C.

>I wonder if it's possible to have a Python that's completely (or at
>least for the most part) implemented in C, just like PHP - I think
>this is where PHP gets its performance advantage. Or maybe I'm wrong
>because the core modules that matter are already in C and those Python
>files are really a think wrapper. Anyhow, if would be ideal if Python
>has performance similar to Java, with both being interpreted languages.

Could you provide some evidence that Python is slower than Java or PHP?
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

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


Is a "real" C-Python possible?

2007-12-09 Thread Jack
I understand that the standard Python distribution is considered
the C-Python. Howerver, the current C-Python is really a combination
of C and Python implementation. There are about 2000 Python files
included in the Windows version of Python distribution. I'm not sure
how much of the C-Python is implemented in C but I think the more
modules implemented in C, the better performance and lower memory
footprint it will get.

I wonder if it's possible to have a Python that's completely (or at
least for the most part) implemented in C, just like PHP - I think
this is where PHP gets its performance advantage. Or maybe I'm wrong
because the core modules that matter are already in C and those Python
files are really a think wrapper. Anyhow, if would be ideal if Python
has performance similar to Java, with both being interpreted languages.

Jack


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


regular expression for nested parentheses

2007-12-09 Thread Noah Hoffman
I have been trying to write a regular expression that identifies a
block of text enclosed by (potentially nested) parentheses. I've found
solutions using other regular expression engines (for example, my text
editor, BBEdit, which uses the PCRE library), but have not been able
to replicate it using python's re module.

Here's a version that works using the PCRE syntax, along with the
python error message. I'm hoping for this to identify the string '(foo
(bar) (baz))'

% python -V
Python 2.5.1
% python
py> import re
py> text = 'buh (foo (bar) (baz)) blee'
py> no_ws = lambda s: ''.join(s.split())
py> rexp = r"""(?P
... \(
... (?>
... (?> [^()]+ ) |
... (?P>parens)
... )*
... \)
... )"""
py> print re.findall(no_ws(rexp), text)
Traceback (most recent call last):
  File "", line 1, in 
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/re.py", line 167, in findall
return _compile(pattern, flags).findall(string)
  File "/Library/Frameworks/Python.framework/Versions/2.5/lib/
python2.5/re.py", line 233, in _compile
raise error, v # invalid expression
sre_constants.error: unexpected end of pattern

>From what I understand of the PCRE syntax, the (?>) construct is a non-
capturing subpattern, and (?P>parens) is a recursive call to the
enclosing (named) pattern. So my best guess at a python equivalent is
this:

py> rexp2 = r"""(?P
... \(
... (?=
... (?= [^()]+ ) |
... (?P=parens)
... )*
... \)
... )"""
py> print re.findall(no_ws(rexp2), text)
[]

...which results in no match. I've played around quite a bit with
variations on this theme, but haven't been able to come up with one
that works.

Can anyone help me understand how to construct a regular expression
that does the job in python?

Thanks -

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


Re: Newbie edit/compile/run cycle question

2007-12-09 Thread Jeremy C B Nicoll
Steve Howell <[EMAIL PROTECTED]> wrote:

> 
> --- Jeremy C B Nicoll <[EMAIL PROTECTED]> wrote:
> 
> > Steve Howell <[EMAIL PROTECTED]> wrote:
> >  
> > > --- Jeremy C B Nicoll <[EMAIL PROTECTED]>
> > wrote:
> > 
> > > > What command (in XP) does one need to issue to syntax check a saved
> > > > python script without running it?
> > > 
> > > Perhaps oversimplifying a bit, running "python" does a syntax check,
> > > and if it passes, moves on the next steps of interpretation/execution.
> > 
> > Ah, I've been using IDLE so far (but would probably prefer to write
> > Python in my normal text editor).  In IDLE Alt-X syntax checks the saved
> > copy of the file being edited (at least it seems to), and I was
> > wondering how to replicate that elsewhere.
> 
> What's your normal text editor?  You might want try googling to see if it
> has a Python mode.  Also, look into seeing if it has a way to
> automatically invoke external programs.

Mansfield Software's Kedit, but that's not the problem.  

You said that running python does a syntax check and then goes on to run the
program. I would want to replicate IDLE's check process which syntax checks
a program and then, even if it is ok, doesn't go on to run it.

I see nothing on the python.exe CLI options that offers that.  

The only way I can think of doing it is to copy the file to be
syntax-checked to a temporary file (presumably in the same directory though,
or search paths won't be right) and append a line with a guaranteed syntax
error in it, then ask python to 'execute' the dummy file.  If the original
file was ok then it will fail the syntax check on the final deliberate-error
line, whereas, obviously any other syntax error is a genuine one.  But that
seems a crazy way to go about things.


-- 
Jeremy C B Nicoll - my opinions are my own.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Different kinds of Import Errors

2007-12-09 Thread Jeremy C B Nicoll
Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> On Sun, 09 Dec 2007 00:25:53 +, Jeremy C B Nicoll wrote:
> 
> > >   for app_name in settings.INSTALLED_APPS:
> > >   try:
> > >   __import__(app_name + '.management', {}, {}, [''])
> > >   except ImportError, exc:
> > >   if exc.args[0]!='No module named management':
> > >   raise
> ...
> > I want to ask a possibly related question.  My impression is
> > that while writing and testing something like the above code one has
> > somehow to know that "ImportError" can be raised, so one can explicitly
> > define how it is to be treated.  How does one find that out?
> 
> Reading the docs. Trial and error. Background knowledge about what the 
> function is doing. There's no perfect solution; unfortunately many 
> functions fail to document what exceptions they can be expected to raise.
> 
> In principle, any exception that isn't documented is a bug. You can't be 
> expected to recover from bugs, all you can do is report it to the 
> function author.

While I've always been an advocate of (in other languages) checking return
codes from things, that's been when generally there's only been a small
number of those documented, or at least they could be split into "it wored
ok", "it almost worked", "minor problem", "huge problem".  So quite often
one could write some fairly generic error handling based only on rc being 0,
or <8, or <20 or something.  That's not to say that within that one couldn't
record the exact rc, error messages that went with them etc and pass them on
(to the caller, say).


Python's system seems messier.


> 
> 
> > While in this case, one might hope that an import action could only fail
> > with ImportError, isn't it possible that - say - one might get an
> > IOError because of a problem on the module search path ... and maybe
> > there are lots of other less obvious exceptions that could be raised?
> 
> The author of a function has a choice to make: 
> 
> (1) expose any exceptions that are raised by his code to the caller; or
> 
> (2) swallow those exceptions and raise one or two known exceptions.
> 
> Neither is the "right" answer in all circumstances. Sometimes you might 
> want to just propagate exceptions, especially if the caller is in a 
> position to do something about them. Sometimes the right solution is to 
> hide those exceptions, and just expose a single MyModuleError exception 
> to callers.
> 
> Sometimes neither is ideal.
> 
> 
> > How does one write a try/except piece of code that works (ie traps
> > whatever exception occurs, though obviously it can't necessarily fix an
> > arbitrary exception) for any exception, even those not known of in
> > advance by the author?
> 
> Generally, you don't. If you can't recover from an exception, there's 
> little point in trapping it. 

The reason I want to trap them is so as not to have a more naive user
suddenly be faced with an unfriendly traceback.  I'd want my program to save
details of what it'd been doing, the exception type etc, do its own cleanup
of whatever it was doing, report it had a problem, and then stop in a
'clean' fashion.  I can look at the details later on... 


> Exceptions are:
> 
> (1) You're writing some sort of library function and you want to hide the 
> internal errors that occur, so you might write:
> 
> def function():
> try:
> processing()
> except (IndexError, NameError):
> raise MyModuleError("bad things happened")
> except (IOError, MemoryError):
> raise MyModuleError("your computer is broken")
> 
> 
> (But notice how much potentially useful information you've thrown away by 
> doing this. Are you sure you want to hide that?)

It seems to me that I'd generally want something like:

 def function():
 try:
 processing()
 except (IndexError, NameError):
 raise MyModuleError("bad things happened")
 except (IOError, MemoryError):
 raise MyModuleError("your computer is broken")
 except (*):
 raise MyModuleError("wallop! :" + details() )

where in the last section I want to trap any exception that wasn't one of
the named/expected ones.  Your 

 raise MyModuleError("blah")

examples suggest that an exception can have just one string of details,
presuably passed back up the line...  Is that the case or can one pass a
list/tuple of symptoms?

I did see a example somewhere something like:

 except (SomeError), s:

in which 's' was then set to a list of - I think - two subsidiary values
which the exception handler could look at.  But I don't know if the
equivalent of 's' for any exception always has just 2 values.  And I
couldn't get anything like:

 except s:

or

 except *, s:

or

 except (), s:

etc to work meaning "match an arbitrary exception but give me access to
whatever symptoms or location-of-error or whatever" info is available.



I also find that if the function concerned actually is a func

Re: a Python person's experience with Ruby

2007-12-09 Thread I V
On Sun, 09 Dec 2007 11:58:05 -0800, MonkeeSage wrote:
> class A
>   attr_accessor :a # == self.a,
># accessible to instances of A
>   def initialize
> @a = "foo" # A.__a
># only accessible from class scope of A
>   end
> end
> 
> Once again, there is no such thing as an attribute that is not a method
> in ruby, and there is no such thing as setting an *attribute* ("=" is a
> method also). You're trying to *re-implement* rubys mechanism in python
> in your example, but in pythons mechanism, all attributes already have
> built-in getter/setter. So the correct analogy is a variable that is
> accessible from within the classes scope only (A.__a), and then exposed
> to instances through an attribute (self.a). Your example leaves out a
> variable accessible only from within the scope of the class, and adds a
> new attribute accessible from the instance (_a).

Either I'm not understanding you, or you're not understanding what A.__a 
means in python. A.__a is a class attribute, not an instance attribute - 
it's equivalent to @@a in ruby, not @a. If I understand what you're 
saying, a better python example to make your point might be:

class A(object):
def __init__(self):
self.__a = "foo" # equivalent to @a
self.a = self.__a # exposes self.__a

Except that this only allows you to access '__a' via the exposed 
attribute 'a', not bind it to a new object. If you do:

inst = A()
inst.a = "bar"

you don't modify inst.__a, unlike the following ruby code, which does 
modify @a .

inst = A.new
inst.a = "bar"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Minimalistic Software Transactional Memory

2007-12-09 Thread Michael Sparks
John J. Lee wrote:

> Durus might be worth a look too (though I doubt it's suitable for your
> situation):
> 
> http://www.mems-exchange.org/software/durus/
> 
> The link to their paper about it seems to be broken, but I think it
> was based somewhat on ZODB, but is simpler (67k tarball :-).

Much appreciated. I've downloaded this and it looks more suitable,
however it still looks like overkill... After all, I'm just after a
simple system for concurrent update of in-memory shared values by
multiple threads - how hard can that be ?[1] ;-) :-)

 [1] Yes, yes, for those who don't know me, I know, I know... :-)

Thanks to Fuzzyman's comments and a code review on IRC I think I've got what
I think is a minimally sufficient system - though I'll extend to include
Fuzzyman's suggestion regarding concurrent update of multiple independent
values :-)

Code is here for those curious/wanting something similar/similarly
lightweight:

https://kamaelia.svn.sourceforge.net/svnroot/kamaelia/trunk/Sketches/MPS/Experiments/NewSTM.py

I'll package it up independently of the rest of Kamaelia as well probably
once I've made the addition noted above :-)

Regards,


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


Re: a strange SyntaxError

2007-12-09 Thread Steve Howell

--- CoolGenie <[EMAIL PROTECTED]> wrote:

> OK, sorry, this was about indents. Stupid VIM!

One more piece of VIM advice.  You can use "set list"
to show where tabs are.  I prefer to convert my own
tabs to spaces automatically, but you inevitably come
across code that you don't own where it's nice to see
the tabs.


  

Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  
http://tools.search.yahoo.com/newsearch/category.php?category=shopping
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a strange SyntaxError

2007-12-09 Thread Steve Howell

--- CoolGenie <[EMAIL PROTECTED]> wrote:

> OK, sorry, this was about indents. Stupid VIM!

No prob.  Add something like this (untested) to your
~/.vimrc:

set expandtab
set sw=4
set ts=4






  

Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  
http://tools.search.yahoo.com/newsearch/category.php?category=shopping
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Distinguishing attributes and methods

2007-12-09 Thread MonkeeSage
On Dec 8, 4:11 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> MonkeeSage a écrit :
>
>
>
> > On Dec 8, 12:56 pm, Bruno Desthuilliers
> > <[EMAIL PROTECTED]> wrote:
>
> >>MonkeeSage a écrit :
>
> >>>On Dec 8, 2:10 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
>
> On Fri, 07 Dec 2007 23:19:40 -0800, tjhnson wrote:
>
> >With properties, attributes and methods seem very similar.  I was
> >wondering what techniques people use to give clues to end users as to
> >which 'things' are methods and which are attributes.
>
> Methods are attributes.  So the decision is easy -- everything on an
> object is an attribute.  ;-)
>
> Ciao,
>    Marc 'BlackJack' Rintsch
>
> >>>I think he means callable attributes (methods) and non-callable
> >>>attributes (variables).
>
> >>callable attributes are not necessarily methods, and are still
> >>'variables' anyway.
>
> > I think it muddies the water to say that a.a() and a.a are the same
> > thing--obviously they are not.
>
> Indeed. a.a yields the object bound to name 'a' in object a, while a.a()
> yields the value returned by calling the object bound to name 'a' in
> object a.
>
> > In the common case, the first is a
> > method,
>
> Nope, it's the value returned by the call to a callable - remember that
> in Python, the parens are the call operator, so the expression a.a()
> evals to the value returned by the call to a.a - which is either the
> method object returned by the collaboration of the lookup mechanism and
> the descriptor protocol or any other possible callable object bound to
> that name or returned by the lookup mechanism for that name.

You're talking about the result of calling a.a(), I'm talking about
what the attribute "a" on the object "a" is. Which is a callable
attribute, which by definition is called a "method" in the standard
sense [1]. You can make a distinction between a "method object" and
"any other possible callable object," but I wasn't using such a
distinction, I was using the standard definition. So my point holds.
When you see a.a(), because of pythons calling convention "()" you
know that "a" is a method of object "a".

The point is that just because the attributes are "looked up the same
way" or whatever, doesn't make them the same *kind* of attribute. To
say that all attributes are the same in python muddies the water. They
are the same in a generic sense that they are attributes, but not in
their particular qualities. Like saying "all humans are the same" --
yes, in a general sense of being human. But to leave it at that is not
very helpful.

[1] http://en.wikipedia.org/wiki/Method_%28computer_science%29

> > and the second is a variable.
>
> The second is whatever the lookup mechanism will yield for this name.
>
> > Yes, you can do silly stuff,
> > such that this rule will not hold, but in general it does. Or am I
> > wrong?
>
> You're wrong. Python's "methods" are thin wrappers around an instance
> (or class) and a function. These wrappers are "built" *at lookup time*
> by the __get__ method of the function object itself when it's looked up
> as an attribute of a class, thanks to the lookup mechanism and the
> descriptor protocol.
>
> Now the fact that an attribute is callable doesn't make it a "method".
>
> Also, anyone can implement it's own callable type that will act as a
> true function - that is, implement the descriptor protocol to return a
> wrapper around the instance or class and the callable - without
> necessarily yielding an instance of types.MethodType. This is all fairly
> trivial.

Again, I am using the common definition. I understand that you can
make an attribute callable in different ways than just the standard
machinery of "def symbol(self):" (those other techniques are what I
was referring to above by "metaprogramming"). But how it is made
callable doesn't matter (nor does how it is looked up). Once it is
callable, it fits the defintion of "method" I'm using. In future, I'll
try to be clear when I'm referring to something python specific or to
a general CS concept.

> And note that none of the two above cases are necessarily "silly".
> Python exposes most of it's object model so you can hook into it and
> taylor it to your needs. This results in some constructs that may seem
> weird at first, but make sens once you understand them and learn to use
> them.

"Silly" in the sense that in this context, they only serve to show
that TIMTOWTDI, but don't actually change a callable attribute from
being a callable attribute ("method" in the general CS sense) to being
some magical "something else". For the purpose of distinguishing an
object variable (non-callable attribute) and an object method
(callable attribute), they don't add anything.

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


Re: a strange SyntaxError

2007-12-09 Thread Samuel
On Sun, 09 Dec 2007 12:35:46 -0800, CoolGenie wrote:

> OK, sorry, this was about indents. Stupid VIM!

$ mkdir -p $HOME/.vim/ftplugin/

$ echo "setlocal sw=4
setlocal ts=4
noremap  py o/**/
" >> ~/.vim/ftplugin/python.vim

$ echo "syntax on
set sw=2
set ts=2
set nu
set nuw=3
set autoindent
set expandtab" >> $HOME/.vimrc
--- 

Problem solved, never to be found again.

Bye,
-Sam
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a strange SyntaxError

2007-12-09 Thread Steve Howell

--- CoolGenie <[EMAIL PROTECTED]> wrote:
> self.feed = self.config['feedsrc']
> self.numfeeds = self.config['numfeeds']
> self.numlines = self.config['numlines']
> 
>   self.w = 520
>   self.h = 12*self.numfeeds*(self.numlines+1)
> adesklets.window_resize(self.w, self.h)
>
> Unfortunately, I'm getting this bug for some time
> now and I just don't
> know what's going on:
> 
>   File "./fparser.py", line 40
> self.w = 520
> ^
> SyntaxError: invalid syntax
> 

Indentation.  See above how the code arrived to me.  I
recommend configuring your editor to convert tabs to
spaces.



  

Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a strange SyntaxError

2007-12-09 Thread John Machin
On Dec 10, 7:15 am, CoolGenie <[EMAIL PROTECTED]> wrote:
> Hi!
> I'm trying to write a small adesklet that will read newsfeeds. Here's
> the code:
>
> #
> #
> # fparser.py
> #
> # P. Kaminski <[EMAIL PROTECTED]>
> # Time-stamp: <>
> ##
> import feedparser
> import adesklets
> from os import getenv, spawnlp, P_NOWAIT
> from os.path import join, dirname
>
> class Config(adesklets.ConfigFile):
> cfg_default = { 'feedsrc' : 'http://slashdot.org/index.rss',
> 'numfeeds' : 5,
> 'numlines' : 4
> }
>
> def __init__(self, id, filename):
> adesklets.ConfigFile.__init__(self, id, filename)
>
> class Events(adesklets.Events_handler):
> def __init__(self, basedir):
> if len(basedir)==0:
> self.basedir='.'
> else:
> self.basedir=basedir
> adesklets.Events_handler.__init__(self)
>
> def __del__(self):
> adesklets.Events_handler.__del__(self)
>
> def ready(self):
> self.config = Config(adesklets.get_id(),
>  join(self.basedir, 'config.txt'))
> self.feed = self.config['feedsrc']
> self.numfeeds = self.config['numfeeds']
> self.numlines = self.config['numlines']
>
> self.w = 520
> self.h = 12*self.numfeeds*(self.numlines+1)
> adesklets.window_resize(self.w, self.h)
> adesklets.window_reset(adesklets.WINDOW_UNMANAGED)
> adesklets.window_set_transparency(True)
> adesklets.window_show()
>
> def quit(self):
> print 'Quitting...'
>
> def alarm(self):
> print 'Alarm. Next in 360 seconds.'
> self._display()
> return 360
>
> def _display(self):
> print "Getting feed..."
> y = 0
> x = 0
> d = feedparser.parse(self.feed)
> print d.channel.title
> print d.channel.description
>
> # clear the buffer
> buffer = adesklets.create_image(self.w, self.h)
> adesklets.context_set_image(buffer)
> adesklets.context_set_blend(False)
> adesklets.context_set_color(0,0,0,0)
> adesklets.image_fill_rectangle(0,0,self.w,self.h)
> adesklets.context_set_blend(True)
>
> adesklets.context_set_font(adesklets.load_font('Vera/7'))
> adesklets.context_set_color(255, 0, 0, 255)
> adesklets.text_draw(0, y, str(d.channel.title))
> y+=12
> l = len(d.entries)
> l = min(l, self.numfeeds)
> for i in range(l):
> ent=d.entries[i]
> adesklets.context_set_color(255, 255, 0, 255)
> adesklets.text_draw(0, y, str(ent.title))
> print ent.title
> y+=12
> adesklets.context_set_color(255, 255, 255, 255)
> for k in range(0, min(len(ent.summary)/100,
> self.numlines)):
> print str(ent.summary)[k*100:(k+1)*100]
> adesklets.text_draw(0, y, str(ent.summary)[k*100:(k
> +1)*100])
> y+=12
> adesklets.free_font(0)
> adesklets.free_image(buffer)
>
> Events(dirname(__file__)).pause()
>
> Unfortunately, I'm getting this bug for some time now and I just don't
> know what's going on:
>
>   File "./fparser.py", line 40
> self.w = 520
> ^
> SyntaxError: invalid syntax
>

As viewed with Google Groups, lines 40/41, 63/69, and 89 are indented
8 spaces more than they should be.

When I save your file and try to run it, I get this:
C:\junk>coolgenie.py
  File "C:\junk\coolgenie.py", line 40
self.w = 520
^
IndentationError: unexpected indent

Possibilities:
(1) Your file contains junk like tabs or no-break spaces. Use a text
editor that will not mask what is really there to find the junk and
edit it out.
(2) You don't understand that:
if some_condition:
blah1
blah2
blah3
is not valid. Blah2 has to be at the same level as blah1 and blah3.

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


Re: a strange SyntaxError

2007-12-09 Thread CoolGenie
OK, sorry, this was about indents. Stupid VIM!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread Steve Howell

--- MonkeeSage <[EMAIL PROTECTED]> wrote:
> 
> Not just callable, but interchangeable. My point was
> that in ruby, if
> you use a block or a lambda as a HOF, you have to
> use #call / #[] /
> yield keyword on it to call it.
> 
> def foo(a)
>   puts a
> end
> bar = lambda { | a | puts a }
> 
> # these do the same thing
> [1,2,3].each(&bar)
> [1,2,3].each(&method(:foo))
> 
> That's not to say it's better than python (like I
> said, I personally I
> like pythons referencing / calling convention a
> little better), it's
> just that since Proc objects already have that call
> syntax in ruby,
> making method references use it also allows them to
> be interchanged (w/
> o having to do method(:foo).to_proc).
> 

Jordan and others, thanks for all your posts; I am
learning a lot about both languages.

This is what I've gathered so far.

Python philosophy:
   passing around references to methods should be
natural (i.e. my_binary_op = math.add)
   calling methods should be explicit (use parens)
   the use of setters/getters varies among Python
programmers; properties, decorators, special methods,
etc. can be used judiciously to affect the interface
   
Ruby philosophy:
   a method itself should be callable without parens
   you can get a reference to a chunk of code, but
then you need a little extra syntax, beyond just a
variable name and parens, to eventually call it
(yield, &, call, etc.)
   when referring to methods, you can use :symbols to
name the method you're interested in without actually
calling it

My personal experience:

   Even after doing lots of Python, I occasionally got
bitten by the pitfall of omitting the parens when I
meant to call something, but it was never major pain.
(I never made the opposite mistake, in case you're
wondering.)

   Despite the pitfall above, I always liked the
tradeoff that Python gave me more natural syntax for
passing around methods.  (And, more fundamentally, I
like the Python notion of binding "general" things to
a  name.)

   As somebody just starting to use Ruby, I actually
like omitting parens in method calls, which I view as
the more common case.  I admit some cost here, though,
in simple churn of the code due to the fact that some
people like having parens for aesthetic reasons.

   I was surprised in Ruby by how seldom I really pass
references to methods around, but it is definitely
something I want to understand better.

I hope this adds a little perspective, and please feel
free to correct me in cases where I'm either imprecise
or just flat out wrong.



  

Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs
-- 
http://mail.python.org/mailman/listinfo/python-list


a strange SyntaxError

2007-12-09 Thread CoolGenie
Hi!
I'm trying to write a small adesklet that will read newsfeeds. Here's
the code:

#
#
# fparser.py
#
# P. Kaminski <[EMAIL PROTECTED]>
# Time-stamp: <>
##
import feedparser
import adesklets
from os import getenv, spawnlp, P_NOWAIT
from os.path import join, dirname

class Config(adesklets.ConfigFile):
cfg_default = { 'feedsrc' : 'http://slashdot.org/index.rss',
'numfeeds' : 5,
'numlines' : 4
}

def __init__(self, id, filename):
adesklets.ConfigFile.__init__(self, id, filename)

class Events(adesklets.Events_handler):
def __init__(self, basedir):
if len(basedir)==0:
self.basedir='.'
else:
self.basedir=basedir
adesklets.Events_handler.__init__(self)

def __del__(self):
adesklets.Events_handler.__del__(self)

def ready(self):
self.config = Config(adesklets.get_id(),
 join(self.basedir, 'config.txt'))
self.feed = self.config['feedsrc']
self.numfeeds = self.config['numfeeds']
self.numlines = self.config['numlines']

self.w = 520
self.h = 12*self.numfeeds*(self.numlines+1)
adesklets.window_resize(self.w, self.h)
adesklets.window_reset(adesklets.WINDOW_UNMANAGED)
adesklets.window_set_transparency(True)
adesklets.window_show()

def quit(self):
print 'Quitting...'

def alarm(self):
print 'Alarm. Next in 360 seconds.'
self._display()
return 360

def _display(self):
print "Getting feed..."
y = 0
x = 0
d = feedparser.parse(self.feed)
print d.channel.title
print d.channel.description

# clear the buffer
buffer = adesklets.create_image(self.w, self.h)
adesklets.context_set_image(buffer)
adesklets.context_set_blend(False)
adesklets.context_set_color(0,0,0,0)
adesklets.image_fill_rectangle(0,0,self.w,self.h)
adesklets.context_set_blend(True)

adesklets.context_set_font(adesklets.load_font('Vera/7'))
adesklets.context_set_color(255, 0, 0, 255)
adesklets.text_draw(0, y, str(d.channel.title))
y+=12
l = len(d.entries)
l = min(l, self.numfeeds)
for i in range(l):
ent=d.entries[i]
adesklets.context_set_color(255, 255, 0, 255)
adesklets.text_draw(0, y, str(ent.title))
print ent.title
y+=12
adesklets.context_set_color(255, 255, 255, 255)
for k in range(0, min(len(ent.summary)/100,
self.numlines)):
print str(ent.summary)[k*100:(k+1)*100]
adesklets.text_draw(0, y, str(ent.summary)[k*100:(k
+1)*100])
y+=12
adesklets.free_font(0)
adesklets.free_image(buffer)

Events(dirname(__file__)).pause()

Unfortunately, I'm getting this bug for some time now and I just don't
know what's going on:

  File "./fparser.py", line 40
self.w = 520
^
SyntaxError: invalid syntax

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


Re: how to convert 3 byte to float

2007-12-09 Thread John Machin
On Dec 10, 3:40 am, [EMAIL PROTECTED] wrote:
> Mario M. Mueller napisa³(a):
>
> > Personally I would expect simple counts (since other seismic formats don't
> > even think of using floats because most digitizers deliver counts). But I
> > was told that there are floats inside.
>
> > But if I assume counts I get some reasonable numbers out of the file.
>
> I looked at the data and it seems to be 24-bit big-endian integers.

Agreed. The first byte is only 0x00 or 0xFF. Where the first byte is
0x00, the 2nd byte is only 0 or 1. Where the first byte is 0xFF, the
second byte is only 0xFE or 0xFF. The 3rd byte is more-or-less
uniformly distributed. In other words, I see no indications that the
data is other than 24-bit big-endian twos-complement integers. The
actual range of the sample needs only 10 bits.

*If* it is floating point, it's either unnormalised or a weird format
or both.

> I even plotted it and the graph looks quite reasonable (though I have no
> expertise in seismic data at all).

Same here.

>
> > But I'm experiencing some strange jumps in the data (seismic data is mostly
> > quite smooth at 40 Hz sampling rate). I think I did some mistake in the
> > byte order...
>
> Probably. In your code sample, when you pad it to 32-bits, why are you
> inserting every third byte, instead of the most significant one? Maybe
> the following will work:
>
> if sign:
> s = struct.unpack('>i','%c%c%c%c' % (chr(0xFF),s0,s1,s2))[0]
> else:
> s = struct.unpack('>i','%c%c%c%c' % (chr(0x00),s0,s1,s2))[0]
>

s/Probably/Definitely/
s/Maybe/Definitely/
:-)
Cheers,
John
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
On Dec 9, 1:58 pm, MonkeeSage <[EMAIL PROTECTED]> wrote:

>  Sure. But as I understand, every attribute in python is a value,

sorry...*references* a value

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


Re: a Python person's experience with Ruby

2007-12-09 Thread MonkeeSage
On Dec 8, 4:54 pm, Bruno Desthuilliers
<[EMAIL PROTECTED]> wrote:
> MonkeeSage a écrit :
>
>
>
> > On Dec 8, 12:42 pm, Bruno Desthuilliers
> > <[EMAIL PROTECTED]> wrote:
>
> >>MonkeeSage a écrit :
>
> >>>On Dec 7, 11:08 pm, Steve Howell <[EMAIL PROTECTED]> wrote:
>
> >>(snip)
>
>  4) Ruby forces you to explicitly make attributes for
> instance variables.  At first I found this clumsy, but
> I've gotten used to it, and I actually kind of like it
> in certain circumstances.
>
> >>>4.) Yeah, it's hard when learning ruby, especially if coming from
> >>>languages that distinguish between methods and attributes,
>
> >>which is not the case in Python
>
> > It is, I just wasn't absolutely precise (uh-oh, here comes the
> > semantics police! -- don't pass GO, don't collect $200, go strait to
> > jail!). Python *does* distinguish between instance/class vars and
> > instance/class methods. But in ruby no such distinction exists.
> > Accessing a "variable" in ruby == calling object.var. I.e., in ruby,
> > when you say "blah.x" that translates to "blah.send(:x)", whether :x
> > is a "variable" or a "method," since *everything* is a method. The
> > call model of ruby is more like smalltalk.
>
> I'm sorry to have to insist: Python doesn't distinguish between methods
> and attributes. Calling a method in Python is really 1/ looking up an
> attribute then 2/ applying the call operator on what the lookup eval'd
> to. As a matter of fact, you can stop at the first step, and you'll have
> a reference to whatever the lookup mechanism yielded for the given
> attribute name on the given object. FWIW, Python's functions are plain
> objects, and when used as attributes are stored in the same place as any
> other attribute.

Except that pthon does differentiate, as python variables are not
callable, whereas everything in ruby is callable. blah.a in ruby means
blah.send(:a). Which is why you need an accessor to get at instance
variables, since as variables they exist in the scope scope of the
class, but they are not callable so they are not attributes of the
instance.

> >>>to get used
> >>>to thinking of "a.a" and "a.a=" as method calls and defining accessors
> >>>for those methods  (or using one of the attr_* keywords) in the class
> >>>body.
>
> >>Python has an equivalent support for computed attributes, using property
> >>or a custom descriptors. While it's a bit lower-level than Ruby, it's
> >>still quite easy to use and IMHO a bit more powerful.
>
> >>>The equivalent python idiom is something like:
>
> >>>class A:
> >>>  __a = "foo"
> >>>  def __init__(self):
> >>>self.a = A.__a
>
> >>WTF ???
>
> >>>Which roughly translates to this in ruby:
>
> >>>class A
> >>>  attr_accessor :a
> >>>  def initialize
> >>>@a = "foo"
> >>>  end
> >>>end
>
> >>The Python translation of the above Ruby snippet is actually way more
> >>simple:
>
> >>class A(object):
> >>   def __init__(self):
> >> self.a = "foo"
>
> > Not really.
>
> Yes, really. Sorry to have to insist, but...
>
> > In ruby an ivar is accessible within the class *only*, but
> > not from without (like a mangled python class var), unless you declare
> > an accessor (or write the accessor methods yourself).
>
> Your Ruby snippets uses attr_accessor, which gives direct, uncontrolled
> read/write access to the attribute. So I maintain that the *exact*
> semantic equivalent in Python of your Ruby snippet is a plain attribute.
>
> > So my example is
> > closer, and is not a WTF, if you know how ruby works.
>
> I know enough about Ruby to understand this snippet, and enough about
> Python to tell your Python example is a WTF.
>
> FWIW, your Python snippet ends up doing the same thing as mine - that
> is, it defines a plain instance attribute named 'a' - but uses a
> reference to class attribute instead of a string literal as the initial
> value of the instance attribute. Since Python strings are immutable, the
> final result is the same wrt/ the instance attribute - it's just overly
> complicated, hence the WTF label.
>
> OTHO, your Python code also defines a class attribute which doesn't
> exist in the Ruby snippet. Mine doesn't imply any class attribute. So my
> Python translation is way closer to the Ruby original !-)
>
> If you what you had in mind was an example of a computed attribute,
> here's the correct code:
>
> class A(object):
>@apply
>def a():
>  def fget(self):
>return self._a
>  def fset(self, val):
>self._a = val
>  return property(**locals())
>def __init__(self):
>  self.a = "foo"
>
> Now since we're just getting/setting the attribute, all these
> indirection levels are totally useless, so in such a case we just use a
> plain attribute. So my first exemple (plain attribute) is effectively
> the *exact* semantic equivalent of your Ruby snippet. CQFD.

No, it's not at all.

class A
  attr_accessor :a # == self.a,
   # accessible to instances of A
  def initialize
@a = "foo" # A.__a
 

Re: python/regex question... hope someone can help

2007-12-09 Thread charonzen

> Another suggestion is to ensure that the job specification is not
> overly simplified. How did you parse the text into "words" in the
> prior exercise that produced the list of bigrams? Won't you need to
> use the same parsing method in the current exercise of tagging the
> bigrams with an underscore?
>
> Cheers,
> John

Thank you John, that definitely puts things in perspective!  I'm very
new to both Python and text parsing, and I often feel that I can't see
the forest for the trees.  If you're asking, I'm working on a project
that utilizes Church's mutual information score.  I tokenize my text,
split it into a list, derive some unigram and bigram dictionaries, and
then calculate a pmi dictionary based on x,y from the bigrams and
unigrams.  The bigrams that pass my threshold then get put into my
list of x_y strings, and you know the rest.  By modifying the original
text file, I can view 'x_y', z pairs as x,y and iterate it until I
have some collocations that are worth playing with.  So I think that
covers the question the same parsing method.  I'm sure there are more
pythonic ways to do it, but I'm on deadline :)

Thanks again!

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


Islamic Manners (1): Sidq (Truthfulness

2007-12-09 Thread abdo911

Allâh, Exalted is He says, "You who have faith! Have taqwâ of Allâh
and be with the truthful"; "...being true to Allâh would be better
for
them"; "... men and women who are truthful...Allâh has prepared for
them
forgiveness and an immense reward"; "Among the believers are those
who
have been true to the contract they made with Allâh. Some of them
have
fulfilled their pact by death and some are still waiting to do so,
not
having changed in any way at all. So that Allâh might recompense the
truthful for their sincerity..."
Truthfulness is the conformity of the outer with the inner, speech
with deed, and narrative with reality. [1]
Therefore truthfulness occurs in intention, speech and deed and not
just speech as many people may think. As such a person who informs of
something that is not in conformity to reality is not truthful, a
person who does a good deed intending to show off is not being
truthful, a hypocrite who shows faith but conceals disbelief is not
being truthful, a person who shows one face here and another face
there is not being truthful etc.
Read this complete Article click here
http://islamzprotector.php0h.com/viewtopic.php?p=352&sid=7c25c28fc1dc...
Related Articles
Islamic Manners (2): Fulfilling the Trusts by Abû Rumaysah -
Islamic Manners (3): Justice (Insâf) by Abû Rumaysah -
Islamic Manners (4): Good Treatment of Parents (Birr al-Wâlidayn)

Join forum
www.islamsprotector.co.nr
MSN group
http://groups.msn.com/ISLAMzProtector/join
Visit website
www.islamzprotector.co.nr
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary instantiation?

2007-12-09 Thread Bruno Desthuilliers
Steven D'Aprano a écrit :
> On Fri, 07 Dec 2007 11:56:14 +0100, Bruno Desthuilliers wrote:
> 
> 
>>Also, modifying a sequence in place while iterating over it is a *very*
>>bad idea.
> 
> 
> That's somewhat of an exaggeration, surely.

Somewhat of a shortcut if you want - given the context, I obviously 
meant adding/removing items to/from the sequence while iterating over it.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: searching a value of a dict (each value is a list)

2007-12-09 Thread bearophileHUGS
Seongsu Lee:
> What do you think of this? Ideas with less space complexity?

You can put the second group of keys in a second dictionary, so you
don't have to mangle them, and it may be a bit faster.

Regarding the space complexity, I don't know how you can reduce it
with Python. Probably you can create a list of long, sort it and use
bisect on it to find the keys. Such longs can be a combination of
shifted integer OR the other integer that is the key of the original
dict. But I don't how much you can gain like this.

Another solution to reduce space is to use a tiny external module
written in C, Pyrex or D. Here follows some simple D code you can
modify a bit to make it work with Pyd (http://pyd.dsource.org/):


import std.traits: ReturnType;
import std.stdio: writefln;

struct TyInt_int {
int el, n;
int opCmp(TyInt_int other) {
if (el == other.el)
return 0;
return (el < other.el) ? -1 : 1;
}
}

int bisect(TyElem, TyData, TyFun)(TyElem[] a, TyData x, TyFun key) {
int lo = 0;
int hi = a.length;
while (lo < hi) {
int mid = (lo + hi) / 2;
if (x < key(a[mid]))
hi = mid;
else
lo = mid + 1;
}
return lo;
}

void main() {
int[][int] int_arr;
int_arr[1] = [1, 2, 3, 4, 5];
int_arr[1] = [10, 11, 12],
int_arr[90] = [100, 101, 102, 103, 104, 105],
int_arr[91] = [20, 21, 22],
int_arr[99] = [15, 16, 17, 18, 19];

int tot_len = 0;
foreach(arr; int_arr)
tot_len += arr.length;

auto data_arr = new TyInt_int[](tot_len);
int i = 0;
foreach(n, arr; int_arr)
foreach(el; arr)
data_arr[i++] = TyInt_int(el, n);

data_arr.sort;
writefln(bisect(data_arr, 100, (TyInt_int ii){return ii.el;}));
}

Bye,
bearophile
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Bruno Desthuilliers
Seongsu Lee a écrit :
> Hi,
> 
> I have a dictionary with million keys. Each value in the
> dictionary has a list with up to thousand integers.
> Follow is a simple example with 5 keys.
> 
> dict = {1: [1, 2, 3, 4, 5],
>2: [10, 11, 12],
>90: [100, 101, 102, 103, 104, 105],
>91: [20, 21, 22],
>99: [15, 16, 17, 18, 19]}
> 
> I want to find out the key value which has a specific
> integer in the list of its value. For example, if I search
> 104 in the list, 90 must be returned.
> 
> How can I do this with Python? Ideas?

A common solution is to build a reversed index - that is, a dict mapping 
values to lists of keys. Now if you have a really huge dataset, this may 
become cumbersome.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread Bruno Desthuilliers
Lou Pecora a écrit :
> In article <[EMAIL PROTECTED]>,
>  Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> 
> 
>>>Thus: close;
>>>could replace close();

*Please* give proper attribution. I'd *never* suggest such a thing.

> 
> Wouldn't this give an ambiguity?  
> 
> afcn=close   # make an "alias" to the close function
> val=close()  # set val to the return value of the close function
> 

The point of Colin (who was the one making this suggestion) was that 
parens could be omitted if there was no LHS.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: a Python person's experience with Ruby

2007-12-09 Thread Steve Howell
After starting this discussion thread, I found the
link below:

http://www.b-list.org/weblog/2006/jun/18/lets-talk-about-python-and-ruby/

If you're like me--struggling to learn Ruby while
having Python as your primary point of reference--you
might find some of the points informative.  I suspect
vice versa as well.





  

Be a better friend, newshound, and 
know-it-all with Yahoo! Mobile.  Try it now.  
http://mobile.yahoo.com/;_ylt=Ahu06i62sR8HDtDypao8Wcj9tAcJ 

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


Re: a way to keep track of # of clicks

2007-12-09 Thread Shawn Minisall
Is there a way to keep track of the number of times someone clicks on a 
menu item in a prorgam?  What I want to do is make the rectangle 
disappear after they click on it at the main menu 3 times so visually 
show them they can't do it any longer.
>
> Since I appended the button to a main menu list, I would think 
> undrawing it would have something like pop.mainMenuList[8] in it after 
> they click on it three times.  (not in succession, after it takes them 
> to the questions screen and then back to the main menu)
>
> Any suggestions?
>
> thx
>

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


Re: Minimalistic Software Transactional Memory

2007-12-09 Thread John J. Lee
Michael Sparks <[EMAIL PROTECTED]> writes:

> Duncan Booth wrote:
>
>> Michael Sparks <[EMAIL PROTECTED]> wrote:
>> 
>>> I'm interested in writing a simple, minimalistic, non persistent (at
>>> this stage) software transactional memory (STM) module. The idea being
>>> it should be possible to write such a beast in a way that can be made
>>> threadsafe fair easily.
[...]
>> Unless you really are desperate to reinvent the wheel, have you looked at
>> ZODB? https://launchpad.net/zodb
[...]
> That seems somewhat overkill for my needs. ZODB's distribution is 3.3MB in
> size, whereas the system I want a minimalistic, non-persistant[1]
> transactional memory for is 345K in size. (The Axon part of kamaelia)
> I'll take a look though.
[...]

Durus might be worth a look too (though I doubt it's suitable for your
situation):

http://www.mems-exchange.org/software/durus/


The link to their paper about it seems to be broken, but I think it
was based somewhat on ZODB, but is simpler (67k tarball :-).


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


Re: a Python person's experience with Ruby

2007-12-09 Thread Lou Pecora
In article <[EMAIL PROTECTED]>,
 Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:

> > Thus: close;
> > could replace close();

Wouldn't this give an ambiguity?  

afcn=close   # make an "alias" to the close function
val=close()  # set val to the return value of the close function

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


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Seongsu Lee
On 12월10일, 오전1시53분, Pablo Ziliani <[EMAIL PROTECTED]> wrote:
> Seongsu Lee escribió:
>
> > Hi,
>
> > I have a dictionary with million keys. Each value in the
> > dictionary has a list with up to thousand integers.
> > (...)
>
> > I want to find out the key value which has a specific
> > integer in the list of its value.
>
> Sorry if this is unhelpful, but have you considered moving your data
> model a proper database?
> I ask because unless someone knows of a specific module, I think we are
> in DB's authentic realm. Is the fastest solution, probably not just for
> this particular operation you are trying to do.
>
> Regards,
> Pablo

Hi Pablo,

Thank you for your posting! I wanted to solve the problem within
a given environment, python, and I think it is solved by
a dictionary with bidirectional key. I have posted it and want to
know if other knows more elegant way to do it.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Converting Excel time-format (hours since 1.1.1901)

2007-12-09 Thread [EMAIL PROTECTED]
On Dec 9, 8:52�am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
> On 7 Dez., 22:36, John Machin <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Dec 8, 12:20 am, Dirk Hagemann <[EMAIL PROTECTED]> wrote:
>
> > > Hello,
>
> > > From a zone-file of a Microsoft Active Directory integrated DNS server
> > > I get the date/time of the dynamic update entries in a format, which
> > > is as far as I know the hours since january 1st 1901.
>
> > As Tim Golden has guessed, it is the number of hours since
> > 1601-01-01T00:00:00. Weird but true. See (for 
> > example)http://www.netpro.com/forum/messageview.cfm?catid=15&threadid=457
>
> > > For Example: the number 3566839 is 27.11.07 7:00.
>
> > Y2K bug! The number 3566839 is a representation of
> > 2007-11-27T07:00:00.
>
> > > To calculate this in
> > >ExcelI use this:
> > > ="01.01.1901"+(A1/24-(REST(A1;24)/24))+ZEIT(REST(A1;24);0;0) �(put
> > > 3566839 in field A1 and switch the format of the result-field to the
> > > corresponding date-time format).
>
> > "01.01.1901" => date(1901, 1, 1)
>
> > (A1/24-(REST(A1;24)/24)) => (A1/24-(MOD(A1,24)/24))
> > which simplifies to INT(A1/24)
>
> > ZEIT(REST(A1;24);0;0) => TIME(MOD(A1,24),0,0)
>
> > This is a convoluted way of writing DATE(1901, 1, 1) + A1 / 24
>
> > Your result is "correct" apart from the century. This is the result of
> > two canceling errors (1) yours in being 3 centuries out of kilter (2)
> > Microsoft's in perpetuating the Lotus 123 "1900 is a leap year" bug.
>
> > If you must calculate this inExcel, this formula might be better:
>
> > =DATE(2001, 1, �1) + A1 / 24 - 146097
>
> > (146097 is the number of days in a 400-year cycle, 400 * 365 + 100 - 4
> > + 1)
>
> > > You might guess what I need now: I want to calculate this somehow in
> > > python.
>
> > > Sorry, but I couldn't find anything in the module time or something
> > > else to get this calculated.
>
> > > Does anyone know how to convert this time in python to something
> > > usable or how to convert this formula in python?
>
> > One very slight change to what Tim Golden suggested: make the result a
> > datetime, not a date.
>
> > >>> dnsdatetime2py = lambda x: datetime.datetime(1601,1,1,0,0,0) + 
> > >>> datetime.timedelta(hours=x)
> > >>> dnsdatetime2py(3566839) # your example
>
> > datetime.datetime(2007, 11, 27, 7, 0)>>> dnsdatetime2py(3554631) # example 
> > in cited web posting
>
> > datetime.datetime(2006, 7, 6, 15, 0)
>
> > HTH,
> > John
>
> YES - that's it!
> Thanks a lot to John, Tim and all the others who helped me to handle
> this time format!!!
>
> I was irritated by the date of 01.01.1901 in the Excel formula, but in
> the end it was obvious that it has to be hours since 1601. Who knows
> how Excel calculates in the background...

Everyone knows. Excel assumes an integer is
DAYS SINCE 1900 and all it's calculations
are based on that assumption.

It's YOUR fault if you give Excel an integer
that represents HOURS SINCE 1601, so don't
expect meaningful calculations from Excel if
you give it an incorrect data type.

>
> Enjoy the sunday and have a great week!
> Dirk

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

Re: Best ways of managing text encodings in source/regexes?

2007-12-09 Thread tvn
Please see the correction from Cliff pasted here after this excerpt.
Tim

> the byte string is ASCII which is a subset of Unicode (IS0-8859-1
> isn't).)

The one comment I'd make is that ASCII and ISO-8859-1 are both subsets
of Unicode, (which relates to the abstract code-points) but ASCII is
also a subset of UTF-8, on the bytestream level, while ISO-8859 is not
a
subset of UTF-8, nor, as far as I can tell, any other unicode
*encoding*.

Thus a file encoded in ascii *is* in fact a utf-8 file.  There is no
way
to distinguish the two.  But an ISO-8859-1 file is not the same (on
the
bytestream level) as a file with identical content in UTF-8 or any
other
unicode encoding.
-- 
http://mail.python.org/mailman/listinfo/python-list


Tkinter weird (and randomly inconsistant) crashes

2007-12-09 Thread wolfonenet

Hi All,

My setup is:

WinXP
Python 2.5.1
TKinter version: $Revision: 50704 $
Tcl: 8.4
Debugger: WinPdb

My program uses some Tkinter code written by someone else, that
creates a basic 24x80 terminal across different platforms. The
terminal worked fine in earlier versions of Python (version 1.5.2 and
2.2.1) but it's doing the weirdest stuff under 2.5.1 (so far I've only
been testing in Windows XP).

I've been playing with this problem for several days now and it's got
me stumped. When I step through the code on the debugger it works just
fine--but when I run the program without breakpoints *or* run it
straight from Python the Tkinter module starts throwing exceptions.

The weird part is, the exceptions occur in different parts of the
Tkinter module at different times. I can run the program 5 times and
no problem then I can have a dozen attempts where it never finishes
printing the game introduction--and worse it stops at *different*
points (and different parts of the Tkinter code) every time. There's
no pattern I can see. I do nothing different each time, and the
program crashes long before any user inputs.

There are a few commonalities:

1) It's always Tkinter throwing the exceptions

2) Using WConio or a "glass tty" terminal there are never any
problems.

3) As best I can determine, it seems to be some sort of timing issue.
For example, one exception occurs in the "see" method because of a bad
passed index. In the debugger I can see that the string "None" was
passed--but the code doing the passing uses Tkinter.END! Worse, the
debugger clearly shows that Tkinter.END should be "end", not "None"
when evaluated right after the exception is thrown.

I got a similar problem from the Pane.text.GetYX() function--it also
returned "None" (randomly) instead of the coordinate pair it normally
does.

Has anybody ever heard of anything like this? I'm an experienced
Python programmer, but I never deal with Tkinter and the randomness of
this is really bizarre.

Any help would be greatly appreciated!

Wolf
Respectfully,

Wolf

"The world is my home, it's just that some rooms are draftier than
others". -- Wolf
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Seongsu Lee
On 12월10일, 오전1시23분, Seongsu Lee <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have a dictionary with million keys. Each value in the
> dictionary has a list with up to thousand integers.
> Follow is a simple example with 5 keys.
>
> dict = {1: [1, 2, 3, 4, 5],
>2: [10, 11, 12],
>90: [100, 101, 102, 103, 104, 105],
>91: [20, 21, 22],
>99: [15, 16, 17, 18, 19]}
>
> I want to find out the key value which has a specific
> integer in the list of its value. For example, if I search
> 104 in the list, 90 must be returned.
>
> How can I do this with Python? Ideas?

Hi,

I just let the dict work in bidirectional fashion so that
I can find out what I want by both key and value. A mark
or prefix was needed to distinguish between keys originated
from keys and keys originated from values. (value * (-1))

from pprint import pprint
dict = {1: [1, 2, 3, 4, 5],
   2: [10, 11, 12],
   90: [100, 101, 102, 103, 104, 105],
   91: [20, 21, 22],
   99: [15, 16, 17, 18, 19]}
for k, v in dict.items():
for x in v:
dict[x * -1] = k
pprint(dict)

{-105: 90,
 -104: 90,
 -103: 90,
 -102: 90,
 -101: 90,
 -100: 90,
 -22: 91,
 -21: 91,
 -20: 91,
 -19: 99,
 -18: 99,
 -17: 99,
 -16: 99,
 -15: 99,
 -12: 2,
 -11: 2,
 -10: 2,
 -5: 1,
 -4: 1,
 -3: 1,
 -2: 1,
 -1: 1,
 1: [1, 2, 3, 4, 5],
 2: [10, 11, 12],
 90: [100, 101, 102, 103, 104, 105],
 91: [20, 21, 22],
 99: [15, 16, 17, 18, 19]}

What do you think of this? Ideas with less space complexity?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: searching a value of a dict (each value is a list)

2007-12-09 Thread Pablo Ziliani
Seongsu Lee escribió:
> Hi,
>
> I have a dictionary with million keys. Each value in the
> dictionary has a list with up to thousand integers.
> (...)
>
> I want to find out the key value which has a specific
> integer in the list of its value.

Sorry if this is unhelpful, but have you considered moving your data 
model a proper database?
I ask because unless someone knows of a specific module, I think we are 
in DB's authentic realm. Is the fastest solution, probably not just for 
this particular operation you are trying to do.

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


Re: how to convert 3 byte to float

2007-12-09 Thread marek . rocki
Mario M. Mueller napisał(a):
> Personally I would expect simple counts (since other seismic formats don't
> even think of using floats because most digitizers deliver counts). But I
> was told that there are floats inside.
>
> But if I assume counts I get some reasonable numbers out of the file.

I looked at the data and it seems to be 24-bit big-endian integers. I
even plotted it and the graph looks quite reasonable (though I have no
expertise in seismic data at all).

> But I'm experiencing some strange jumps in the data (seismic data is mostly
> quite smooth at 40 Hz sampling rate). I think I did some mistake in the
> byte order...

Probably. In your code sample, when you pad it to 32-bits, why are you
inserting every third byte, instead of the most significant one? Maybe
the following will work:

if sign:
s = struct.unpack('>i','%c%c%c%c' % (chr(0xFF),s0,s1,s2))[0]
else:
s = struct.unpack('>i','%c%c%c%c' % (chr(0x00),s0,s1,s2))[0]

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


Re: reading list of list to a file

2007-12-09 Thread Pablo Ziliani
Hi Croliina,

caroliina escribió:
> i made a list of lists

Please notice that this problem:

> but i cant write it into a file.

has nothing to do with this other one:
> how do i get the
> first string in a sublist?
>   

For the first one, it is impossible to answer without seeing some actual 
code. How are you opening/saving the "list"? are you using Pickle or 
some serializer? are you just trying to write on regular a text file? 
Also, it would really help you to get appropriate answers from the list 
if you try to explain a little further what is your actual goal.

For the latter, you already got good answers.

Regards,
Pablo

PS: I'm mostly in read-only mode in this list, but admittedly, I 
couldn't resist to write to a hot.ee girl :)
-- 
http://mail.python.org/mailman/listinfo/python-list


searching a value of a dict (each value is a list)

2007-12-09 Thread Seongsu Lee
Hi,

I have a dictionary with million keys. Each value in the
dictionary has a list with up to thousand integers.
Follow is a simple example with 5 keys.

dict = {1: [1, 2, 3, 4, 5],
   2: [10, 11, 12],
   90: [100, 101, 102, 103, 104, 105],
   91: [20, 21, 22],
   99: [15, 16, 17, 18, 19]}

I want to find out the key value which has a specific
integer in the list of its value. For example, if I search
104 in the list, 90 must be returned.

How can I do this with Python? Ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading list of list to a file

2007-12-09 Thread Ismail Dönmez
Sunday 09 December 2007 18:11:00 tarihinde caroliina şunları yazmıştı:
> i made a list of lists but i cant write it into a file. how do i get the
> first string in a sublist?

An easy example:

>>> a=[[1,2,3],[4,5,6]]
>>> a[0][0]
1
>>> a[1][0]
4
>>>

-- 
Never learn by your mistakes, if you do you may never dare to try again.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: reading list of list to a file

2007-12-09 Thread Steve Howell

--- caroliina <[EMAIL PROTECTED]> wrote:

> 
> i made a list of lists but i cant write it into a
> file. how do i get the
> first string in a sublist?
> -- 

Try doing this:

print list_of_lists
print list_of_lists[0]
print list_of_lists[0][0]
print list_of_lists[0][0][0]

It might give you some insight.  If you're still stuck
after that, it would help if you posted a little bit
of your code.  Good luck!




  

Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  
http://tools.search.yahoo.com/newsearch/category.php?category=shopping
-- 
http://mail.python.org/mailman/listinfo/python-list


reading list of list to a file

2007-12-09 Thread caroliina

i made a list of lists but i cant write it into a file. how do i get the
first string in a sublist?
-- 
View this message in context: 
http://www.nabble.com/reading-list-of-list-to-a-file-tp14239876p14239876.html
Sent from the Python - python-list mailing list archive at Nabble.com.

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


  1   2   >