Re: Retrieve Tkinter listbox item by string, not by index

2006-12-23 Thread Godson

On 12/23/06, Kevin Walzer <[EMAIL PROTECTED]> wrote:


I'm trying to set the active item in a Tkinter listbox to my
application's currently-defined default font.

Here's how I get the fonts loaded into the listbox:

  self.fonts=list(tkFont.families())
  self.fonts.sort()

   for item in self.fonts:
 self.fontlist.insert(END, item)   #self.fontlist is the
ListBox instance


So far, so good. But I don't know how to set the active selection in the
listbox to the default font. All the methods for getting or setting a
selection in the listbox are based on index, not a string. And using
standard list search methods like this:

if "Courier" in self.fontlist:
 print "list contains", value
 else:
 print value, "not found"

returns an error:

TypeError: cannot concatenate 'str' and 'int' objects

So I'm stuck. Can someone point me in the right direction?
--
Kevin Walzer
Code by Kevin
http://www.codebykevin.com
--
http://mail.python.org/mailman/listinfo/python-list


to me self.fontlist to be a Listbox instance so you cant do a list search on
it, to get current selection from a list box use curselection method Listbox

self.fontlist.curselection()

returns a list of index numbers of  currently selected items in a list box,
following link has more to say on this

http://effbot.org/tkinterbook/listbox.htm

--
Godson Gera,
http://godson.auroinfo.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: httplib and socket.getaddrinfo

2006-12-23 Thread Gabriel Genellina

At Saturday 23/12/2006 04:21, [EMAIL PROTECTED] wrote:


I noticed the following lines from the connect() method of the
HTTPConnection class within httplib:

for res in socket.getaddrinfo(self.host, self.port, 0,
  socket.SOCK_STREAM):
af, socktype, proto, canonname, sa = res

This led me to the docs that describe the socket.getaddrinfo() method:

http://www.python.org/doc/2.4.1/lib/module-socket.html

Which leads me to these questions:
1) Is it correct to infer from the "Resolves the host/port argument,
into a sequence of 5-tuples that contain all the necessary argument for
the sockets manipulation" description in the docs (in particular the
reference to 'sequence of 5-tuples') that a single host/port
combination may be associated with multiple sets of address
information?


Yes. By example, multiple addresses for the same service are used for 
load balancing. Or an IPv4 address plus an IPv6 address.



2) In the very limited applications on which I've used
socket.getaddrinfo(), each a host/port combination that my application
passes to socket.getaddrinfo() has always returned a 1-entry list where
the list is a 5-tuple, in other words, each host/port combination has
always been associated with one set of address information.  Can
someone point me to a host/port combination that, when passed to
socket.getaddrinfo() will result in socket.getaddrinfo() returning a
list of > 1 entry, where each entry is a 5-tuple?


Try to relax your restrictions.

import socket
host = 'www.microsoft.com'
port = 'ftp'
for res in socket.getaddrinfo(host, port):
print res

Got 8 results:
(2, 1, 0, '', ('207.46.198.30', 21))
(2, 1, 0, '', ('207.46.198.60', 21))
(2, 1, 0, '', ('207.46.199.30', 21))
(2, 1, 0, '', ('207.46.225.60', 21))
(2, 1, 0, '', ('207.46.19.30', 21))
(2, 1, 0, '', ('207.46.19.60', 21))
(2, 1, 0, '', ('207.46.20.30', 21))
(2, 1, 0, '', ('207.46.20.60', 21))


--
Gabriel Genellina
Softlab SRL 







__ 
Preguntá. Respondé. Descubrí. 
Todo lo que querías saber, y lo que ni imaginabas, 
está en Yahoo! Respuestas (Beta). 
¡Probalo ya! 
http://www.yahoo.com.ar/respuestas 

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

Re: attribute decorators

2006-12-23 Thread Fredrik Lundh
Doug Holton wrote:

> Don't mind Fredrik's trolling.  Your examples are perfectly clear

if you understand how they would work, can you explain the semantics?

 > however, a similar call for extending the use of decorators to other
 > structures besides functions was rejected:
 > http://lambda-the-ultimate.org/node/1389

class objects and class attributes are two rather different things.  and 
given how decorators work, that difference is rather important.  can you 
perhaps figure out why ?



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


Re: One module per class, bad idea?

2006-12-23 Thread stdazi

Matias Jansson wrote:
> I come from a background of Java and C# where it is common practise to have
> one class per file in the file/project structure. As I have understood it,
> it is more common practice to have many classes in a Python module/file.
> What is the motivation behind it, would it be a bad idea to have a guideline
> in your project that promotes a one class per file structure (assuming most
> of the programmers a background similar to mine)?

IMO, even the Java practice is weird. I think classes should be split
into different files/modules due to their context and not their
number...

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


Gdmodule

2006-12-23 Thread Timothy Wu

Hi,

Is Gdmodule used much at all in the Python community or are there
alternative packages more suitable for the purpose? I seem to find
documentation for Gdmodule (
http://newcenturycomputers.net/projects/gd-ref.html) to require prior
experience with the GD library in another language. Or at least, it's too
difficult for me to grasp.

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

Multi-line docstrings

2006-12-23 Thread Lawrence D'Oliveiro
The Python docs recommend the use of triple-quoted string literals for
docstrings, e.g.

def Meet(Alice, Bob) :
"""arranges a meeting between Alice and Bob.
Returns a reference to the meeting booking object."""
...
#end Meet

However, these tend to get messed up by indentation whitespace, which gets
spuriously included as part of the string.

Another possibility is to use implicit concatenation of string literals,
e.g.

def Meet(Alice, Bob) :
"arranges a meeting between Alice and Bob." \
" Returns a reference to the meeting booking object."
...
#end Meet

This includes no spurious whitespace, or even any newlines; if you want
these, you must put them explicitly in the string:

def Meet(Alice, Bob) :
"arranges a meeting between Alice and Bob.\n" \
"Returns a reference to the meeting booking object."
...
#end Meet

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


Question on regex

2006-12-23 Thread Prabhu Gurumurthy

Hello all -

I have a file which has IP address and subnet number and I use regex to extract 
the IP separately from subnet.


pattern used for IP: \d{1,3}(\.\d{1,3}){3}
pattern used for subnet:((\d{1,3})|(\d{1,3}(\.\d{1,3}){1,3}))/(\d{1,2})

so I have list of ip/subnets strewn around like this

10.200.0.34
10.200.4.5
10.178.9.45
10.200/22
10.178/16
10.100.4.64/26,
10.150.100.0/28
10/8

with that above examples:
ip regex pattern works for all IP address
subnet regex pattern works for all subnets

problem now is ip pattern also matches the last 2 subnet numbers, because it 
falls under ip regex.


to fix this problem, i used negative lookahead with ip pattern:
so the ip pattern now changes to:
\d{1,3}(\.\d{1,3}){3}(?!/\d+)

now the problem is  10.150.100.0 works fine, 10.100.4.64 subnet gets matched 
with ip pattern with the following result:


10.100.4.6

Is there a workaround for this or what should change in ip regex pattern.

python script:
#!/usr/bin/env python

import re, sys

fh = 0
try:
   fh = open(sys.argv[1], "r")
except IOError, message:
   print "cannot open file: %s" %message
else:

   for lines in fh.readlines():
  lines = lines.strip()

  pattIp = re.compile("(\d{1,3}(\.\d{1,3}){3})(?!/\d+)")
  pattNet = re.compile("((\d{1,3})|(\d{1,3}(\.\d{1,3}){1,3}))/(\d{1,2})")

  match = pattIp.search(lines)
  if match is not None:
 print "ipmatch: %s" %match.groups()[0]

  match = pattNet.search(lines)
  if match is not None:
 print "subnet: %s" %match.groups()[0]

fh.close()

output with that above ip/subnet in a file

ipmatch: 10.200.0.34
ipmatch: 10.200.4.5
ipmatch: 10.178.9.45
subnet: 10.200
subnet: 10.178
ipmatch: 10.100.4.6
subnet: 10.100.4.64
subnet: 10.150.100.0
subnet: 10

TIA
Prabhu
begin:vcard
fn:Prabhu  Gurumurthy
n:Gurumurthy;Prabhu 
org:Silver Spring Networks;IT
adr:Suite 205;;2755 Campus Drive;San Mateo;CA;94403;USA
email;internet:[EMAIL PROTECTED]
title:Network Engineer
tel;work:(650) 357 8770 x134
tel;home:(650) 585 6527
tel;cell:(831) 224 0894
x-mozilla-html:FALSE
url:http://www.silverspringnet.com
version:2.1
end:vcard

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

Re: Xah's Edu Corner: Introduction to 3D Graphics Programing

2006-12-23 Thread Boris Borcic
Xah Lee wrote:
> Of Interest:

to which of comp.lang.perl.misc, comp.lang.python, comp.lang.lisp, 
comp.lang.java.programmer, comp.lang.functional ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-line docstrings

2006-12-23 Thread Duncan Booth
Lawrence D'Oliveiro <[EMAIL PROTECTED]> wrote:

> The Python docs recommend the use of triple-quoted string literals for
> docstrings, e.g.
> 
> def Meet(Alice, Bob) :
> """arranges a meeting between Alice and Bob.
> Returns a reference to the meeting booking object."""
> ...
> #end Meet
> However, these tend to get messed up by indentation whitespace, which
> gets spuriously included as part of the string.

Not spuriously included: included by design, but sometimes annoying. If you 
are just printing __doc__ in interactive mode then live with the extra 
whitespace. If you are printing out lots of docstrings as part of some 
documentation tool then use textwrap.dedent to remove the common leading 
spaces.

> 
> Another possibility is to use implicit concatenation of string
> literals, e.g.
> 


> This includes no spurious whitespace, or even any newlines; if you
> want these, you must put them explicitly in the string:


... which is why the triple-quoted format is recommended. BTW, you missed 
this way of doing it which ensures that all lines, even the first one have 
the same indentation (and therefore textwrap.dedent will strip it quite 
nicely):

def Meet(Alice, Bob) :
'''\
arranges a meeting between Alice and Bob.
Returns a reference to the meeting booking object.
'''

and if you want to do string concatenation you can always get rid of those 
pesky backslashes:

def Meet(Alice, Bob) :
("arranges a meeting between Alice and Bob.\n"
 "Returns a reference to the meeting booking object.")
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating all permutations from a regexp

2006-12-23 Thread Chris Johnson

BJörn Lindqvist wrote:
> With regexps you can search for strings matching it. For example,
> given the regexp: "foobar\d\d\d". "foobar123" would match. I want to
> do the reverse, from a regexp generate all strings that could match
> it.
>
> The regexp: "[A-Z]{3}\d{3}" should generate the strings "AAA000",
> "AAA001", "AAA002" ... "AAB000", "AAB001" ... "ZZZ999".
>
> Is this possible to do? Obviously, for some regexps the set of matches
> is unbounded (a list of everything that matches "*" would be very
> unpractical), but how would you do it for simple regexps like the one
> above?

For a very small number of characters, it would be feasible. For any
finite number of characters, it would be possible (though it wouldn't
take much to take longer than the age of the universe). For reference,
in your simple example, you have 17,576,000 matching strings.

I'm curious as to why you would wish to do this. I certainly understand
considering hard problems for their own sake, but when I formulate
them, there's always some impetus that makes me say "Huh. Now I
wonder..."

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


ANN: eric3 3.9.3 released

2006-12-23 Thread Detlev Offenbach
Hi,

this is to inform you about the availability of eric3 version 3.9.3. This
release fixes a few bugs and enhances compatibility with subversion 1.4.

It is available via
http://sourceforge.net/project/showfiles.php?group_id=119070.

What is eric3?
--
eric3 is an IDE for Python and Ruby. It is written using Python, PyQt and
QScintilla. eric3 includes debuggers for the a.m. languages, interfaces
to subversion and cvs, integration of the Qt tools and many more. For
details please see the eric home page at
http://www.die-offenbachs.de/detlev/eric.html.

Regards,
Detlev
-- 
Detlev Offenbach
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie: what is a usefull IDE for Python on Windows ?

2006-12-23 Thread Osiris
what is a usefull IDE for Python on Windows ?

I saw Eric mentioned.. is that WinXP  or Linux ?

What does "everybody" use ?

I was considering using old and very stable C-code in a new web
application via Python/Plone/Zope.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question on regex

2006-12-23 Thread Felix Benner
Prabhu Gurumurthy schrieb:

> to fix this problem, i used negative lookahead with ip pattern:
> so the ip pattern now changes to:
> \d{1,3}(\.\d{1,3}){3}(?!/\d+)
> 
> now the problem is  10.150.100.0 works fine, 10.100.4.64 subnet gets
> matched with ip pattern with the following result:
> 
> 10.100.4.6
> 
> Is there a workaround for this or what should change in ip regex pattern.
> 

I think what you want is that neither /d+ nor another digit nor a . follows:
\d{1,3}(\.\d{1,3}){3}(?!(/\d)|\d|\.)
This way 10.0.0.1234 won't be recognized as ip. Neither will 23.12.
which could be a problem if an ip is at the end of a sentence, so you
might want to omit that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: what is a usefull IDE for Python on Windows ?

2006-12-23 Thread Fredrik Lundh
Osiris wrote:

> what is a usefull IDE for Python on Windows ?
> 
> I saw Eric mentioned.. is that WinXP  or Linux ?
> 
> What does "everybody" use ?

http://effbot.org/pyfaq/tutor-whats-the-best-editor-ide-for-python



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


Re: Multi-line docstrings

2006-12-23 Thread bearophileHUGS
Duncan Booth:
> Not spuriously included: included by design, but sometimes annoying.

Then it's a design decision I don't understand...

Bye,
bearophile

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


Re: Decorator for Enforcing Argument Types

2006-12-23 Thread Bruno Desthuilliers
George Sakkis a écrit :
> John Machin wrote:
> 
> 
>>Peter  Wang wrote:
>>
>>>Bruno Desthuilliers wrote:
>>>

Python is dynamic, and fighting against the language is IMHO a really
bad idea. The only places where theres a real need for this kind of
stuff are when dealing with the "outside world" (IOW : inputs and
outputs). And then packages like formencode can do much more than mere
type-checking

>>>
(snip)
> I have also a very recent real-world example to share, from the other
> side of the fence this time. It's even worse because it's an error that
> passes silently. Cut-down version follows:
> 
> @cherrypy.expose
> def retrieve(self, **kwds):
> queries = kwds['q']
> rows = self._selectRows(*queries)
> # more stuff
> 
> 'q' here is a multiselect field that is binded to a list of selected
> strings. Or so I thought, until someone noticed bizarre results in some
> cases. Turns out that if you select a single item from the select box,
> 'q' is binded to a string instead of a list of length 1, so instead of
> retrieving 'apple', she got back the results for 'a', 'p', 'p',
> 'l','e'.

This is a typical case of converting/validating data from the "outside 
world" - something well covered by formencode.

> Bottom line, type checking is a tricky business.

Indeed. In fact, proper "type checking" would first require some 
agreement on what's a "type"...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusion over calling a nested function inside a parent function

2006-12-23 Thread Bruno Desthuilliers
MacDonald a écrit :
> Pyenos wrote:
> 
>>[code]
>>class WORK:
>>def getwork(self):
>>def choosetable(self):pass
>>choosetable() #TypeError: choosetable() takes exactly 1
>>  #argument (0 given)
>>[/code]
>>
>>Calling choosetable() at the above location gives me the error
>>described above.
> 
> 
> Although choosetable is a memeber of an instance method,

s/is a member of/is defined in/

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


Re: Newbie: what is a usefull IDE for Python on Windows ?

2006-12-23 Thread Osiris
btw:
my system is an AMD 1.8 GHz, 512 Mbyte with WinXPSP2.
 I saw that a system like Wing would be sluggish ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Confusion over calling a nested function inside a parent function

2006-12-23 Thread Bruno Desthuilliers
Pyenos a écrit :
> [code]

You already got the answer - just a pair of stylistic advices:

> class WORK:

1/ By convention, ALL_UPPER names denote (pseudo) symbolic constants. 
The convention for class names is CamelCase.

2/ better to use new-style classes.

=>
class Work(object):
   ...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: what is a usefull IDE for Python on Windows ?

2006-12-23 Thread Osiris
ok, thnx. Thread closed :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multi-line docstrings

2006-12-23 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> Duncan Booth:
>> Not spuriously included: included by design, but sometimes annoying.
> 
> Then it's a design decision I don't understand...
> 
I think the decision is that the doc string should reflect exactly what you 
entered in the string. i.e. the system shouldn't tamper with it behind the 
scenes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [ANN] pyparsing 1.4.5 released

2006-12-23 Thread Richard Townsend
On 22 Dec 2006 19:59:53 -0800, Paul McGuire wrote:

> 
> Download pyparsing 1.4.5 at http://pyparsing.sourceforge.net.  The
> pyparsing Wiki is at http://pyparsing.wikispaces.com
> 

When I click on the sourceforge link above, I get redirected to the wiki.

However, http://sourceforge.net/projects/pyparsing/

seems to work.

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


Elliptic Curve Library

2006-12-23 Thread Mike Tammerman
Hi,

I need an elliptic curve library that can be used by python. I googled
but couldn't find a one. I'll appreciate, if you could show me.

Mike

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


Re: How a script can know if it has been called with the -i command line option?

2006-12-23 Thread vasudevram

Peter  Wang wrote:
> Michele Simionato wrote:
> > The subject says it all, I would like a script to act differently when
> > called as
> > $ python script.py and when called as $ python -i script.py. I looked
> > at the sys module
> > but I don't see a way to retrieve the command line flags, where should
> > I look?
>
> I realize this is quite a hack, but the entire command line is
> preserved in the process's entry in the OS's  process table.  if you do
> "ps -ax" you will see that the interpreter was invoked with -i.  I
> didn't test this under windows, but it works on Mac and Linux.

That hack might not work - at least, as described, and on Linux or Mac
OS if the UNIX-based one, i.e. OS X). Because there could be other
users who ran python command lines with or without the -i option. As
described, there's no way for this user to know which python invocation
is his/hers, and which are of other users. There might be a way,
though, if we can get this user's python instance's process id and then
grep for a line containing that id (in the appropriate column) in the
ps output.

Vasudev Ram
~~
Dancing Bison Enterprises
http://www.dancingbison.com
http://dancingbison.blogspot.com
~~
Check out the cool Snap.com preview feature on my web site.
Free signup for anyone at www.snap.com
I'm not affiliated with it.

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


Re: Elliptic Curve Library

2006-12-23 Thread vasudevram

Mike Tammerman wrote:
> Hi,
>
> I need an elliptic curve library that can be used by python. I googled
> but couldn't find a one. I'll appreciate, if you could show me.
>
> Mike

What is the library you need supposed to do?

Vasudev Ram
Dancing Bison Enterprises
www.dancingbison.com

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


Re: How a script can know if it has been called with the -i command line option?

2006-12-23 Thread vasudevram

vasudevram wrote:
> Peter  Wang wrote:
> > Michele Simionato wrote:
> > > The subject says it all, I would like a script to act differently when
> > > called as
> > > $ python script.py and when called as $ python -i script.py. I looked
> > > at the sys module
> > > but I don't see a way to retrieve the command line flags, where should
> > > I look?
> >
> > I realize this is quite a hack, but the entire command line is
> > preserved in the process's entry in the OS's  process table.  if you do
> > "ps -ax" you will see that the interpreter was invoked with -i.  I
> > didn't test this under windows, but it works on Mac and Linux.
>
> That hack might not work - at least, as described, and on Linux or Mac
> OS if the UNIX-based one, i.e. OS X). Because there could be other
> users who ran python command lines with or without the -i option. As
> described, there's no way for this user to know which python invocation
> is his/hers, and which are of other users. There might be a way,
> though, if we can get this user's python instance's process id and then
> grep for a line containing that id (in the appropriate column) in the
> ps output.
>
> Vasudev Ram
> ~~
> Dancing Bison Enterprises
> http://www.dancingbison.com
> http://dancingbison.blogspot.com
> ~~
> Check out the cool Snap.com preview feature on my web site.
> Free signup for anyone at www.snap.com
> I'm not affiliated with it.

Just realized: getting the python process's process id is possible from
the Python program itself, using os.getpid().

Vasudev

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


Re: pyparsing 1.4.5 released

2006-12-23 Thread Paul McGuire
On Dec 23, 9:07 am, Richard Townsend <[EMAIL PROTECTED]> wrote:
> On 22 Dec 2006 19:59:53 -0800, Paul McGuire wrote:
>
>
>
> > Download pyparsing 1.4.5 athttp://pyparsing.sourceforge.net.  The
> > pyparsing Wiki is athttp://pyparsing.wikispaces.comWhen I click on the 
> > sourceforge link above, I get redirected to the wiki.
>
> However,http://sourceforge.net/projects/pyparsing/
>
> seems to work.
>
> --
> Richard

Thanks, I'll update my announcement template.

-- Paul

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


Re: Elliptic Curve Library

2006-12-23 Thread Mike Tammerman

I will try to implement an ID-Based Cryptography. I also need bilinear
pairing operations.

Mike

vasudevram wrote:
> Mike Tammerman wrote:
> > Hi,
> >
> > I need an elliptic curve library that can be used by python. I googled
> > but couldn't find a one. I'll appreciate, if you could show me.
> >
> > Mike
>
> What is the library you need supposed to do?
> 
> Vasudev Ram
> Dancing Bison Enterprises
> www.dancingbison.com

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


Add/Remove Channels in Asyncore?

2006-12-23 Thread Chris
I've implemented a real basic IRC client class in 100 lines using
asynchat (yes I know about Twisted). The problem I'm having is
arbitrarily starting and stopping multiple instances of this class
after I call loop().

The asyncore docs seem to imply everything's fixed in stone once loop()
is called, where they say, "Once the initial channel(s) is(are)
created, calling the loop() function activates channel service, which
continues until the last channel (including any that have been added to
the map during asynchronous service) is closed."

After I call asyncore.loop(), I'd like to be able to add/remove clients
("channels"?) to/from execution by asyncore. Is this possible?

Thanks,
Chris

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


Re: let me simplify my question on scope of vars

2006-12-23 Thread Colin J. Williams
Pyenos wrote:
> "code"
> var=1
> class CLASS:
> def METHOD1:
> def METHOD2:
> var+=var
> return var
> METHOD2()   #line8   
> return var
> METHOD1()   #line10
> "end code"
> 
> Q1: does class CLASS inherit var=0 from line1?
> Q2: does def METHOD1 inherit var=0 from line1?
> Q3: does def METHOD2 inherit var=0 from line1?
> Q3: does line8 return '2'?
> Q4: does line10 return '2\n2'?

Some print statements could verify, but my guess for your quiz are:
A1: Yes
A2: Yes
A3: Yes
A4: It should return 1, Method 2 is never called.

I've modified you code a little, so that you can experiment with print 
statements.

Colin W.

# Pyenos wrote:
"code"
var=1
print id(var)
class CLASS:
 def METHOD1(self):
 def METHOD2():
 var+=var
 print id(var)
 return var
 METHOD2()   #line8
 return var
c= CLASS()
print c.METHOD1()   #line10
"end code"


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


Re: Add/Remove Channels in Asyncore?

2006-12-23 Thread Fredrik Lundh
Chris wrote:

> I've implemented a real basic IRC client class in 100 lines using
> asynchat (yes I know about Twisted). The problem I'm having is
> arbitrarily starting and stopping multiple instances of this class
> after I call loop().
> 
> The asyncore docs seem to imply everything's fixed in stone once loop()
> is called, where they say, "Once the initial channel(s) is(are)
> created, calling the loop() function activates channel service, which
> continues until the last channel (including any that have been added to
> the map during asynchronous service) is closed."
> 
> After I call asyncore.loop(), I'd like to be able to add/remove clients
> ("channels"?) to/from execution by asyncore. Is this possible?

the usual way to do that is to add new channels in callbacks, in 
response to other server activities.

if you want to deal with this from the program calling asyncore.loop, 
use the "count" option to tell loop to return after N events.  e.g:

while 1:
asyncore.loop(0.05, count=20) # wait for max 1 second
add/remove channels here



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


Re: removing the header from a gzip'd string

2006-12-23 Thread debarchana . ghosh

Bjoern Schliessmann wrote:
> Rajarshi wrote:
>
> > Does anybody know how I can remove the header portion of the
> > compressed bytes, such that I only have the compressed data
> > remaining? (Obviously I do not intend to perform the
> > decompression!)
>
> Just curious: What's your goal? :) A home made hash function?

Actually I was implementing the use of the normalized compression
distance to evaluate molecular similarity as described in an article in
J.Chem.Inf.Model (http://dx.doi.org/10.1021/ci600384z, subscriber
access only, unfortunately).

Essentially, they note that the NCD does not always bevave like a
metric and one reason they put forward is that this may be due to the
size of the header portion (they were using the command line gzip and
bzip2 programs) compared to the strings being compressed (which are on
average 48 bytes long).

So I was interested to see if the NCD behaved like a metric if I
removed everything that was not the compressed string. And since I only
need to calculate similarity between two strings, I do not need to do
any decompression.

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


Re: removing the header from a gzip'd string

2006-12-23 Thread Bjoern Schliessmann
[EMAIL PROTECTED] wrote:

> Actually I was implementing the use of the normalized compression
> distance to evaluate molecular similarity as described in an
> article in J.Chem.Inf.Model (http://dx.doi.org/10.1021/ci600384z,
> subscriber access only, unfortunately).

Interesting. Thanks for the reply.

Regards,


Björn

-- 
BOFH excuse #438:

sticky bit has come loose

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


Re: Newbie: what is a usefull IDE for Python on Windows ?

2006-12-23 Thread BartlebyScrivener

in addition to the effbot link,

search the group

http://tinyurl.com/yyuxco

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


Re: Xah's Edu Corner: Introduction to 3D Graphics Programing

2006-12-23 Thread Jon Harrop
Xah Lee wrote:
> Introduction to 3D Graphics Programing
> http://xahlee.org/3d/index.html

You will probably find it more rewarding to use a more modern graphics
system, such as OpenGL or DirectX, with a suitable programming language
rather than Mathematica's. I would recommend any of OCaml, F#, Haskell,
Lisp, Scheme, Python or Ruby for graphics, you can do much more
sophisticated, animated, real time visualisations than you can with
Mathematica's primitives.

There are lots of great web pages out there. I've written some 2D and 3D
graphics examples in OCaml:

  http://www.ffconsultancy.com/products/ocaml_for_scientists/visualisation
  http://www.ffconsultancy.com/free/ray_tracer
  http://www.ffconsultancy.com/free/fractal
  http://www.ffconsultancy.com/free/maze

and more recently F#:

  http://www.ffconsultancy.com/dotnet/fsharp

I was very impressed with the tutorial videos on VPython at ShowMeDo:

  http://showmedo.com/videos/series?name=pythonThompsonVPythonSeries

For an introduction to OpenGL, look no further than the NeHe tutorials at
GameDev:

  http://nehe.gamedev.net

One of our future products at FF Consultancy is a suite of extensions for
the F# interactive mode that allows you to visualise 2D and 3D graphics in
real time with simplicity rivalling Mathematica but the sophistication and
performance of DirectX, whilst also having the power of the F# programming
language and .NET to analyse your data.

-- 
Dr Jon D Harrop, Flying Frog Consultancy
Objective CAML for Scientists
http://www.ffconsultancy.com/products/ocaml_for_scientists/index.html?usenet
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elliptic Curve Library

2006-12-23 Thread Jaap Spies
Mike Tammerman wrote:

> I need an elliptic curve library that can be used by python. I googled
> but couldn't find a one. I'll appreciate, if you could show me.
> 

You could look at http://sage.scipy.org/sage/
http://sage.scipy.org/sage/features.html

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


Re: textwrap.dedent replaces tabs?

2006-12-23 Thread Tom Plunket
Frederic Rentsch wrote:

> Following a call to dedent () it shouldn't be hard to translate leading 
> groups of so many spaces back to tabs.

Sure, but the point is more that I don't think it's valid to change to
tabs in the first place.

E.g.:

 input = ' ' + '\t' + 'hello\n' +
 '\t' + 'world'

 output = textwrap.dedent(input)

will yield all of the leading whitespace stripped, which IMHO is a
violation of its stated function.  In this case, nothing should be
stripped, because the leading whitespace in these two lines does not
/actually/ match.  Sure, it visually matches, but that's not the point
(although I can understand that that's a point of contention in the
interpreter anyway, I would have no problem with it not accepting "1 tab
= 8 spaces" for indentation...  But that's another holy war.

> If I understand your problem, you want to restore the dedented line to 
> its original composition if spaces and tabs are mixed and this doesn't 
> work because the information doesn't survive dedent ().

Sure, although would there be a case to be made to simply not strip the
tabs in the first place?

Like this, keeping current functionality and everything...  (although I
would think if someone wanted tabs expanded, they'd call expandtabs on
the input before calling the function!):

def dedent(text, expand_tabs=True):
"""dedent(text : string, expand_tabs : bool) -> string

Remove any whitespace than can be uniformly removed from the left
of every line in `text`, optionally expanding tabs before altering
the text.

This can be used e.g. to make triple-quoted strings line up with
the left edge of screen/whatever, while still presenting it in the
source code in indented form.

For example:

def test():
# end first line with \ to avoid the empty line!
s = '''\
 hello
\t  world
'''
print repr(s) # prints ' hello\n\t  world\n'
print repr(dedent(s))  # prints ' hello\n\t  world\n'
"""
if expand_tabs:
text = text.expandtabs()
lines = text.split('\n')

margin = None
for line in lines:
if margin is None:
content = line.lstrip()
if not content:
continue
indent = len(line) - len(content)
margin = line[:indent]
elif not line.startswith(margin):
if len(line) < len(margin):
content = line.lstrip()
if not content:
continue
while not line.startswith(margin):
margin = margin[:-1]

if margin is not None and len(margin) > 0:
margin = len(margin)
for i in range(len(lines)):
lines[i] = lines[i][margin:]

return '\n'.join(lines)

import unittest

class DedentTest(unittest.TestCase):
def testBasicWithSpaces(self):
input = "\n   Hello\n  World"
expected = "\nHello\n   World"
self.failUnlessEqual(expected, dedent(input))

def testBasicWithTabLeadersSpacesInside(self):
input = "\n\tHello\n\t   World"
expected = "\nHello\n   World"
self.failUnlessEqual(expected, dedent(input, False))

def testAllTabs(self):
input = "\t\tHello\n\tWorld"
expected = "\tHello\nWorld"
self.failUnlessEqual(expected, dedent(input, False))

def testFirstLineNotIndented(self):
input = "Hello\n\tWorld"
expected = input
self.failUnlessEqual(expected, dedent(input, False))

def testMixedTabsAndSpaces(self):
input = "  \t Hello\n   \tWorld"
expected = "\t Hello\n \tWorld"
self.failUnlessEqual(expected, dedent(input, False))

if __name__ == '__main__':
unittest.main()
-tom!

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


Re: Xah's Edu Corner: Introduction to 3D Graphics Programing

2006-12-23 Thread J�rgen Exner
Boris Borcic wrote:
> Xah Lee wrote:
>> Of Interest:
>
> to which of comp.lang.perl.misc, comp.lang.python, comp.lang.lisp,
> comp.lang.java.programmer, comp.lang.functional ?

You must be new. Otherwise you would be familiar with this troll already.

jue 


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


Re: merits of Lisp vs Python

2006-12-23 Thread Fuzzyman

Lars Rune Nøstdal wrote:
> On Fri, 08 Dec 2006 03:07:09 -0800, Mark Tarver wrote:
>
> > How do you compare Python to Lisp?  What specific advantages do you
> > think that one has over the other?
> >
> > Note I'm not a Python person and I have no axes to grind here.  This is
> > just a question for my general education.
> >
> > Mark
>
> Kill this frakkin thread; Lisp rules -- while Python is boring (but better
> than many other alternatives). E.O.F.
>

Perhaps only with the addendum that although 'Lisp roolz', no-one uses
for anything of relevance anymore and it is continuing it's geriatric
decline into obscurity. ;-)

Python is dull, except to the ever increasing group of programmers who
use it for practical purposes.

Hmm... a fitting. EOF.

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

> -- 
> Lars Rune Nøstdal
> http://nostdal.org/

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


Re: PyExcelerator: how to set colours?

2006-12-23 Thread Waldemar Osuch

Gerry wrote:
> I'd like some cell to be a Blue "ABCDE".
>
> Here's come code thatv tries various values for pattern_for_colour and
> font.colour_index, to no avail.
>
> Can anyone suggest the right way to set colours?
>
> Thanks!
>
> Gerry
>
> ==
>
> from pyExcelerator import *
>
> w   = Workbook()
> ws  = w.add_sheet('alpha')
>
> style   = XFStyle()
> fore_colour = style.pattern.pattern_fore_colour
> back_colour = style.pattern.pattern_back_colour
>
> ws.write (1, 1, "fore_colour")
> ws.write (1, 2, fore_colour)
>
> ws.write (2, 1, "back_colour")
> ws.write (2, 2, back_colour)
>
> text= "ABCDE"
>
> row = 5
>
>
>
> for offset in range(-32,512):
>
> row += 1
>
> style.font.colour_index = fore_colour + offset
>
> ws.write(row,3, fore_colour + offset, style)
>
> ws.write(row,5,text,style)
>
> style.pattern.pattern_fore_colour = fore_colour + offset
>
> ws.write(row,6,text,style)
>
> w.save('test.xls')
>
> =
>
> shows no colour variation for any of these values of offset.

Is this what you were after?
--
from pyExcelerator import *

w = Workbook()
ws = w.add_sheet('boo')

style = XFStyle()
fore_colour = style.pattern.pattern_fore_colour
back_colour = style.pattern.pattern_back_colour

ws.write (1, 1, "fore_colour")
ws.write (1, 2, fore_colour)

ws.write (2, 1, "back_colour")
ws.write (2, 2, back_colour)

text = "ABCDE"

row = 5

for offset in range(-32,512):
row += 1

fnt = Font()
fnt.colour_index = fore_colour + offset
style.font = fnt
ws.write(row, 3, offset, style)
ws.write(row, 5, text, style)

p = Pattern()
p.pattern_fore_colour = fore_colour + offset
p.pattern = style.pattern.SOLID_PATTERN
style.pattern = p
ws.write(row, 6, text, style)

w.save('test.xls')


Waldemar

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


Re: merits of Lisp vs Python

2006-12-23 Thread defcon8
All of you are nazis!

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


Re: merits of Lisp vs Python

2006-12-23 Thread Fuzzyman

defcon8 wrote:
> All of you are nazis!

Hmmm... that might work. :-)

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

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


Getting the name of an assignment

2006-12-23 Thread Adam Atlas
Is it possible for an object, in its __init__ method, to find out if it
is being assigned to a variable, and if so, what that variable's name
is? I can think of some potentially ugly ways of finding out using
sys._getframe, but if possible I'd prefer something less exotic.
(Basically I have a class whose instances, upon being created, need a
'name' property, and if it's being assigned to a variable immediately,
that variable's name would be the best value of 'name'; to make the
code cleaner and less redundant, it would be best if it knew its own
name upon creation, just like functions and classes do, without the
code having to pass it its own name as a string.)

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


Re: Generating all permutations from a regexp

2006-12-23 Thread Thomas Ploch
Fredrik Lundh wrote:
> Nick Craig-Wood wrote:
> 
>> A regular expression matcher uses a state machine to match strings.
> 
> unless it's the kind of regular expression matcher that doesn't use a 
> state machine, like the one in Python.
> 
> 
> 

How is the matching engine implemented then?

I thought regular languages can be described by deterministic /
non-deterministic finite state machines. I am just curious ...

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


Re: Fall of Roman Empire

2006-12-23 Thread Thomas Ploch
Delaney, Timothy (Tim) wrote:
> Hendrik van Rooyen wrote:
> 
>> naaah - you don't have to worry - for real control He uses assembler.
>> with jump statements.
>> so the loops are closed.
>>
>> Unfortunately its not open source.  Yet.
> 
> People are working hard on reverse-engineering it though. I hope no one
> slaps them with a DMCA-style lawsuit ...
> 
> Tim Delaney

I heard Steve Ballmer recently made an offer to the pope for purchasing
the license for an apple and an egg (Apfel und Ei).

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


Re: Getting the name of an assignment

2006-12-23 Thread BJörn Lindqvist
On 23 Dec 2006 14:38:19 -0800, Adam Atlas <[EMAIL PROTECTED]> wrote:
> Is it possible for an object, in its __init__ method, to find out if it
> is being assigned to a variable, and if so, what that variable's name
> is? I can think of some potentially ugly ways of finding out using
> sys._getframe, but if possible I'd prefer something less exotic.
> (Basically I have a class whose instances, upon being created, need a
> 'name' property, and if it's being assigned to a variable immediately,
> that variable's name would be the best value of 'name'; to make the
> code cleaner and less redundant, it would be best if it knew its own
> name upon creation, just like functions and classes do, without the
> code having to pass it its own name as a string.)

I guess you mean something like this:

>>> olle = Person()
>>> olle.name
"olle"

Instead of:

>>> olle = Person("olle")
>>> olle.name
"olle"

It is not possible without ugly hacks. What you could use instead is
some kind of registry approach:

reg = {}
class Person:
def __init__(self, name):
self.name = name
reg[name] = self

>>> Person("olle")
>>> reg["olle"].name
"olle"

I think there are thousand different ways you could solve it.

-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Generating all permutations from a regexp

2006-12-23 Thread Chris Johnson

Thomas Ploch wrote:
> Fredrik Lundh wrote:
> > Nick Craig-Wood wrote:
> >
> >> A regular expression matcher uses a state machine to match strings.
> >
> > unless it's the kind of regular expression matcher that doesn't use a
> > state machine, like the one in Python.
> >
> > 
> >
>
> How is the matching engine implemented then?
>
> I thought regular languages can be described by deterministic /
> non-deterministic finite state machines. I am just curious ...

Regular expressions are described by N?DFAs, but Perl-compatible
regular expressions (which pretty much every language implements now)
are not true regular expressions. They are actually Turing complete,
and thus have features that cannot be implemented in N?DFAs.

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


Re: Getting the name of an assignment

2006-12-23 Thread Adam Atlas
On Dec 23, 5:58 pm, "BJörn Lindqvist" <[EMAIL PROTECTED]> wrote:
> On 23 Dec 2006 14:38:19 -0800, Adam Atlas <[EMAIL PROTECTED]> wrote:
>
> > Is it possible for an object, in its __init__ method, to find out if it
> > is being assigned to a variable, and if so, what that variable's name
> > is? I can think of some potentially ugly ways of finding out using
> > sys._getframe, but if possible I'd prefer something less exotic.
> > (Basically I have a class whose instances, upon being created, need a
> > 'name' property, and if it's being assigned to a variable immediately,
> > that variable's name would be the best value of 'name'; to make the
> > code cleaner and less redundant, it would be best if it knew its own
> > name upon creation, just like functions and classes do, without the
> > code having to pass it its own name as a string.)I guess you mean something 
> > like this:
>
> >>> olle = Person()
> >>> olle.name"olle"
>
> Instead of:
>
> >>> olle = Person("olle")
> >>> olle.name"olle"
>
> It is not possible without ugly hacks. What you could use instead is
> some kind of registry approach:
>
> reg = {}
> class Person:
> def __init__(self, name):
> self.name = name
> reg[name] = self
>
> >>> Person("olle")
> >>> reg["olle"].name"olle"
>
> I think there are thousand different ways you could solve it.

Yeah, I've thought of ways like that. I was just hoping to make the
syntax as minimal and Pythonic as possible.

I have the following working:

> import sys
>
> class c:
> def __init__(self):
> f = sys._getframe(1)
> names = [n for n in f.f_code.co_names if n not in f.f_locals]
> if len(names) > 0:
> name = names[0]
> print name
>
> a = c() # prints 'a'
> b = 'blah'
> b = c() # prints nothing

Question: too evil?

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


Re: Getting the name of an assignment

2006-12-23 Thread Steven D'Aprano
On Sat, 23 Dec 2006 14:38:19 -0800, Adam Atlas wrote:

> Is it possible for an object, in its __init__ method, to find out if it
> is being assigned to a variable, and if so, what that variable's name
> is? 

What should the variable name be set to if you do one of the following?


john = eric = graham = terry = Named_Instance()

some_list = [None, 1, "string", Named_Instance()]

fred = Named_Instance(); barney = fred; del fred


Name assignment is not a one-to-one operation. An object can have no name,
one name or many names. If your code assumes such a one-to-one
relationship between names and objects, it is wrong.


> I can think of some potentially ugly ways of finding out using
> sys._getframe, but if possible I'd prefer something less exotic.
> (Basically I have a class whose instances, upon being created, need a
> 'name' property, and if it's being assigned to a variable immediately,
> that variable's name would be the best value of 'name'; to make the code
> cleaner and less redundant, it would be best if it knew its own name
> upon creation, just like functions and classes do, without the code
> having to pass it its own name as a string.)

I suggest rethinking your data model, and accept that the name
attribute of an object is not necessarily the same as the name it is
bound to. 

If you still want a convenience function that names the object and binds
it to a name at the same time, try something like this:

def Make_A_Named_Instance(name, *args, **kwargs):
globals()[name] = Named_Instance(*args, **kwargs)
globals()[name].name = name


You might be tempted to replace globals() with locals() in the above.
Don't -- it doesn't generally work:

http://docs.python.org/lib/built-in-funcs.html


-- 
Steven.

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


Re: Class constant for extension

2006-12-23 Thread Martin Miller
[EMAIL PROTECTED] wrote:
> Hi,
>
>   I have written a small prototype Python extension for a C-library.
>
>   I have the methods all sorted out and it is working fine.
>
>   In the C-library, they are various constants of types like string,
> integer, float and matrix. I'd like to expose them as READONLY values.
>
>   Is the use of PyMemberDefs a suitable way to provide such access?
>
>   I'd like the user of the extension to be able to do something like
> the follow
>
>   import MyExtension
>
>   MyExtension.begin()
>   mv = MyExtension.minValue
>   MyExtension.process(MyExtension.versionStr)
>   MyExtension.end()
>
>   Is someone able to point me to an example code of how I can write my
> extension so that the references to those constants can be used in the
> above way.
>
> Regards

A couple of years ago I wanted to do something similar for a project I
was working on.
Below is a snippet of some sample C code from the module's
initialization function which should give you an idea of the approach
used. It's a limited example and only creates module identifiers for
simple integer values, not the more complex types you are interested
in, nor does it do anything to make them read only, but it might help
get you started.

If you find something that addresses these deficiencies, please post
your findings.

Best,
-Martin

// snippet
#include "Python.h"

enum METAtags
{
kMETA_MojikumiX4051 = 0,
kMETA_UNIUnifiedBaseChars = 1,
kMETA_BaseFontName = 2
}

void initPyExtension()
{
PyObject *m, *d, *o;
m = Py_InitModule4("PyExtension", pyis_methods,
PySING_module_documentation,
(PyObject*)NULL, PYTHON_API_VERSION);

// Add some symbolic constants to the module
d = PyModule_GetDict(m); // get modules dictionary

PyObject* o = PyInt_FromLong(kMETA_MojikumiX4051);
PyDict_SetItemString(d, "idMojikumiX4051", o);
Py_INCREF(o); // for dictionary ref

PyObject* o = PyInt_FromLong(kMETA_UNIUnifiedBaseChars);
PyDict_SetItemString(d, "idUNIUnifiedBaseChars", obj);
Py_INCREF(o);

PyObject* o = PyInt_FromLong(kMETA_BaseFontName);
PyDict_SetItemString(d, "idBaseFontName", obj);
Py_INCREF(o);
   .
   .
   .

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


Re: Use a Thread to reload a Module?

2006-12-23 Thread Gregory Piñero
On 12/23/06, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
> have you looked at putting the data into a persistent dict?
>
> - Hendrik
>
What is that exactly?

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


Help please using telnetlib module

2006-12-23 Thread dudds
Hi Guys,

I just started learning Python a couple of days ago and to put some of
what I learnt into practice. As such I thought I might try and write a
simple program (based on examples I had seen) that would allow me to
log into a Cisco router, enter configuration mode, change an interface
description and also grab a snapshot of the running configuration.

So far I've managed to be able to log in and change the interface
configuration. The tn.read_until() function seems to work pretty much
as I expected however for the life of me I cannot get the running
configuration to display with any of the read functions.

Suggestion pleasemy code thus far follows:
import getpass
import sys
import telnetlib

#This can actually log in and change an interface description on a
router


HOST = "xxx.xxx.xxx.xxx"
#user = raw_input("Enter your remote account: ")
#password = getpass.getpass()
password = "tacis345int"

tn = telnetlib.Telnet(HOST)
#tn.interact()
tn.read_until("Password:")
tn.write(password + "\n")
#if password:
#tn.read_until("Password: ")
#tn.write(password + "\n")
tn.read_until("port>")
#tn.write("show version\n")
#tn.write("\n\n")
#tn.read_until("port>")
tn.write("enable\n")
tn.read_until("assword: ")
tn.write("tacis345int\n")
tn.read_until("port#")
tn.write("conf t\n")
tn.read_until("config)#")
tn.write("int ethernet0\n")
tn.read_until("config")
tn.write("desc This was written by my script\n")
tn.write("show run\n")
print tn.read_very_lazy()
tn.write("exit\n")
tn.read_until("#")
tn.write("quit\n")
tn.close()
print tn.read_all()


The only output I get from this is:
-if)#
show

I have tried the other read options but nothing seems to work for me.
I'm obviously missing something, so if anyone could shed some light
that would be great.

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


Re: regular expression

2006-12-23 Thread Joe Kesselman
Reminder: anything crossposted across this many newsgroups, especially 
asking an inherently bogus question, is probably just trolling.

If it's equally on topic everywhere, that means it's on topic nowhere.

-- 
() ASCII Ribbon Campaign  | Joe Kesselman
/\ Stamp out HTML e-mail! | System architexture and kinetic poetry
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting the name of an assignment

2006-12-23 Thread Steven Bethard
Adam Atlas wrote:
> Is it possible for an object, in its __init__ method, to find out if it
> is being assigned to a variable, and if so, what that variable's name
> is? I can think of some potentially ugly ways of finding out using
> sys._getframe, but if possible I'd prefer something less exotic.
> (Basically I have a class whose instances, upon being created, need a
> 'name' property, and if it's being assigned to a variable immediately,
> that variable's name would be the best value of 'name'; to make the
> code cleaner and less redundant, it would be best if it knew its own
> name upon creation, just like functions and classes do, without the
> code having to pass it its own name as a string.)

As others have mentioned, in general the answer is no.  However, class 
statements do have access to the name they're assigned, so you could 
abuse a class statement like this::

 >>> # your class whose instances need a name property
 >>> class C(object):
 ... def __init__(self, name):
 ... self.name = name
 ... @classmethod
 ... def from_class_block(cls, name, bases, blockdict):
 ... return cls(name)
 ...
 >>> # instances of your class with the appropriate names
 >>> class instance:
 ... __metaclass__ = C.from_class_block
 ...
 >>> instance.name
 'instance'

Though it doesn't rely on private functions like sys._getframe, it's 
still sure to confuse the hell out of your users. ;-)

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


split string with hieroglyphs

2006-12-23 Thread Belize
Hi.
Essence of problem in the following:
Here is lines in utf8 of this form "BZ?ツーリTV%ツキDVD"
Is it possible to split them into the fragments that contain only latin
printable symbols (aplhabet + "?#" etc)
and fragments with the hieroglyphs, so it could be like this
['BZ?', '\xe3\x83\x84\xe3\x83\xbc\xe3\x83\xaa', 'TV%',
'\xe3\x83\x84\xe3\x82\xad', 'DVD'] ?
Then, after translate of hieroglyphs, necessary to join line, so it
could be like this 
"BZ? navigation TV% display DVD"
Thanks.

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

Re: Getting the name of an assignment

2006-12-23 Thread Adam Atlas
Thanks, Steven and Steven.

@Bethard:
Isn't it a bit convoluted to use metaclasses?
someinstance.__class__.__name__ does the same thing.

@D'Aprano:
Thanks for the advice to rethink my data model. I'm doing so right now,
and I've already come up with a way that makes more sense. :)

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


some OT: how to solve this kind of problem in our program?

2006-12-23 Thread oyster
1. first of all, what is the English jargon (Optimize? But I think
this is not a very good keyword :( )for this problem? So I can use it
to search on the internet
2. is there any free/open lib for this?
3. I know for some questions(case 1, case 2, and sudoku), we can use
bundles of "FOR...NEXT" loop to program. however I think it is clumsy
and inconvenient, especially when there is many vars
4. I don't know how to deal with case 3 and case 4


case:
1. choose x0~x9 from 1~9, and must use all of 1~9, let
x0/(10*x1+x2)+x3/(10*x4+x5)+x6/(10*x7+x8)=1/2

2. choose x0~x15 from 1~16, and must use all of 1~16, let
+-+-+-+-+
|  x0 |  x1 |  x2 |  x3 |
+-+-+-+-+
|  x4 |  x5 |  x6 |  x7 |
+-+-+-+-+
|  x8 |  x9 | x10 | x11 |
+-+-+-+-+
| x12 | x13 | x14 | x15 |
+-+-+-+-+

sum of every column =sum of of every row
= x0+x5+x10+x11 =x3+x6+x9+x12

3: calculate the minimum of
sin((z*x-0.5)^2 + x*2*y^2-z/10)*exp(-((x-0.5-exp(-y+z))^2 + y^2-z/5+3))
where x in [-1,7], y in [-2,2]

4: calculate the root [x,y,z], let
(x-0.3)^y^z+x/y/z-x*y*sin(z)+(x+y-z)^cos(x-1) = 1
(y-0.2)^z^x+y/z/x-y*z*sin(x)+(y+z-x)^cos(y-2) = 2
(z-0.1)^x^y+z/x/y-z*x*sin(y)+(z+x-y)^cos(z-3) = 3


I have written the case 1 in python, it needs 90 seconds on my pc, and
the same approach in www.freebasic.net takes less than 1 seconds
[code for python]
import sets
import time
try:
  import psyco
  psyco.full()
except:
  pass

d0, d1=1, 2

st=time.time()
result=[]
for a0 in range(1,10):
  for a1 in sets.Set(range(1,10))-sets.Set([a0]):
for a2 in sets.Set(range(1,10))-sets.Set([a0,a1]):
  a1a2=a1*10+a2
  if 2*a0< a1a2:
for b0 in sets.Set(range(1,10))-sets.Set([a0,a1,a2]):
  for b1 in sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0]):
for b2 in sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0, b1]):
  b1b2=b1*10+b2
  if 2*a0*b1b2 + 2*b0*a1a2 < a1a2*b1b2:
for c0 in sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0, b1, b2]):
  for c1 in
sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0, b1, b2, c0]):
for c2 in
sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0, b1, b2, c0, c1]):
  c1c2=c1*10+c2
  if d1*a0*b1b2*c1c2 + d1*b0*a1a2*c1c2 +
d1*c0*a1a2*b1b2 == d0*a1a2*b1b2*c1c2:
aresult=[[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]]
aresult.sort()
if aresult not in result:
  result.append(aresult)
et=time.time()
print 'time elapsed: %s s' % (et-st)
for [[a0, a1, a2], [b0, b1, b2], [c0, c1, c2]] in result:
  print '  %0d %0d %0d %0d' % (a0, b0, c0, d0)
  print '--- + --- + --- = ---'
  print ' %0d%0d%0d%0d%0d%0d %0d' %(a1, a2, b1, b2, c1,c2, d1)
  print
[/code]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: split string with hieroglyphs

2006-12-23 Thread Steven D'Aprano
On Sat, 23 Dec 2006 19:28:48 -0800, Belize wrote:

> Hi.
> Essence of problem in the following:
> Here is lines in utf8 of this form "BZ???TV%??DVD"
> Is it possible to split them into the fragments that contain only latin
> printable symbols (aplhabet + "?#" etc)

Of course it is possible, but there probably isn't a built-in function to
do it. Write a program to do it.

> and fragments with the hieroglyphs, so it could be like this
> ['BZ?', '\xe3\x83\x84\xe3\x83\xbc\xe3\x83\xaa', 'TV%',
> '\xe3\x83\x84\xe3\x82\xad', 'DVD'] ?

def split_fragments(s):
"""Split a string s into Latin and non-Latin fragments."""
# Warning -- untested.
fragments = []  # hold the string fragments
latin = []  # temporary accumulator for Latin fragment
nonlatin = []  # temporary accumulator for non-Latin fragment
for c in s:
if islatin(c):
if nonlatin:
fragments.append(''.join(nonlatin))
nonlatin = []
latin.append(c)
else: 
if latin:
fragments.append(''.join(latin))
latin = []
nonlatin.append(c)
return fragments


I leave it to you to write the function islatin.

Hints: 

There is a Perl module to guess the encoding:
http://search.cpan.org/~dankogai/Encode-2.18/lib/Encode/Guess.pm

You might like to read this too:
http://effbot.org/pyfaq/what-does-unicodeerror-ascii-decoding-encoding-error-ordinal-not-in-range-128-mean.htm

I also recommend you read this recipe:
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/251871

And look at the module unicodedata.


> Then, after translate of hieroglyphs, necessary to join line, so it
> could be like this 
> "BZ? navigation TV% display DVD"

def join_fragments(fragments)
accumulator = []
for fragment in fragments:
if islatin(fragment):
accumulator.append(fragment)
else:
accumulator.append(translate_hieroglyphics(fragment))
return ''.join(accumulator)


I leave it to you to write the function translate_hieroglyphics.



-- 
Steven.

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


Re: some OT: how to solve this kind of problem in our program?

2006-12-23 Thread John Machin

oyster wrote:
[snip]
> I have written the case 1 in python, it needs 90 seconds on my pc, and
> the same approach in www.freebasic.net takes less than 1 seconds
> [code for python]
> import sets
> import time
> try:
>   import psyco
>   psyco.full()
> except:
>   pass
>
> d0, d1=1, 2
>
> st=time.time()
> result=[]
> for a0 in range(1,10):
>   for a1 in sets.Set(range(1,10))-sets.Set([a0]):
> for a2 in sets.Set(range(1,10))-sets.Set([a0,a1]):
>   a1a2=a1*10+a2
>   if 2*a0< a1a2:
> for b0 in sets.Set(range(1,10))-sets.Set([a0,a1,a2]):
>   for b1 in sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0]):
> for b2 in sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0, b1]):
>   b1b2=b1*10+b2
>   if 2*a0*b1b2 + 2*b0*a1a2 < a1a2*b1b2:
> for c0 in sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0, b1, 
> b2]):
>   for c1 in
> sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0, b1, b2, c0]):
> for c2 in
> sets.Set(range(1,10))-sets.Set([a0,a1,a2,b0, b1, b2, c0, c1]):

Has it not occurred to you to "calculate" sets.Set(range(1,10)) *ONCE*,
store it, and reuse it?

For the remaining uses of sets.Set, do
   set = sets.Set
once up the front, and remember to remove it when (as you should!) you
upgrade off Python 2.3.

HTH,
John

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


Re: Getting the name of an assignment

2006-12-23 Thread Steven Bethard
Adam Atlas wrote:
> Isn't it a bit convoluted to use metaclasses?

Yep. It's a well known fact that putting "convoluted" and "metaclasses" 
in the same sentence is repetitively redundant. ;-)

> someinstance.__class__.__name__ does the same thing.

No, not really::

 >>> class C(object):
 ... def __init__(self, name):
 ... self.name = name
 ... @classmethod
 ... def from_class_block(cls, name, bases, blockdict):
 ... return cls(name)
 ...
 >>> c = C('foo')
 >>> c.name
 'foo'
 >>> type(c)
 
 >>> c.__class__.__name__
 'C'
 >>> class foo:
 ... __metaclass__ = C.from_class_block
 ...
 >>> foo.name
 'foo'
 >>> type(foo)
 
 >>> foo.__class__.__name__
 'C'

Note that the ``class foo`` statement is not creating a class.  It's 
creating an instance of ``C``.  So it really is doing something pretty 
different.

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


Re: Fall of Roman Empire

2006-12-23 Thread Hendrik van Rooyen
"Thomas Ploch" <[EMAIL PROTECTED]> wrote:


> Delaney, Timothy (Tim) wrote:
> > Hendrik van Rooyen wrote:
> > 
> >> naaah - you don't have to worry - for real control He uses assembler.
> >> with jump statements.
> >> so the loops are closed.
> >>
> >> Unfortunately its not open source.  Yet.
> > 
> > People are working hard on reverse-engineering it though. I hope no one
> > slaps them with a DMCA-style lawsuit ...
> > 
> > Tim Delaney
> 
> I heard Steve Ballmer recently made an offer to the pope for purchasing
> the license for an apple and an egg (Apfel und Ei).
> 

LOL! 

For the sake of those unfortunates who have no grounding in the Germanic
Languages - when you buy something for "an apple and an egg" or in Afrikaans
an "apple and an onion" - you are getting it excessively cheaply...

- Hendrik

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


Re: Use a Thread to reload a Module?

2006-12-23 Thread Hendrik van Rooyen
"Gregory Piñero" <[EMAIL PROTECTED]> wrote:


> On 12/23/06, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
> > have you looked at putting the data into a persistent dict?
> >
> > - Hendrik
> >
> What is that exactly?
>
> -Greg

from the docs:

3.17 shelve -- Python object persistence

A ``shelf'' is a persistent, dictionary-like object. The difference with ``dbm''
databases is that the values (not the keys!) in a shelf can be essentially
arbitrary Python objects -- anything that the pickle module can handle. This
includes most class instances, recursive data types, and objects containing lots
of shared sub-objects. The keys are ordinary strings.


open( filename[,flag='c'[,protocol=None[,writeback=False[,binary=None)

Open a persistent dictionary. The filename specified is the base filename for
the underlying database. As a side-effect, an extension may be added to the
filename and more than one file may be created. By default, the underlying
database file is opened for reading and writing. The optional flag parameter has
the same interpretation as the flag parameter of anydbm.open.

hth - Hendrik

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


Re: Use a Thread to reload a Module?

2006-12-23 Thread Gregory Piñero
On 12/24/06, Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:
> "Gregory Piñero" <[EMAIL PROTECTED]> wrote:
...
> open( filename[,flag='c'[,protocol=None[,writeback=False[,binary=None)
>
> Open a persistent dictionary. The filename specified is the base filename for
> the underlying database. As a side-effect, an extension may be added to the
> filename and more than one file may be created. By default, the underlying
> database file is opened for reading and writing. The optional flag parameter 
> has
> the same interpretation as the flag parameter of anydbm.open.
>
> hth - Hendrik

So how is that better than using marshal as I am now?  Is it faster to
load?  Perhaps I could do speed tests to compare.

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