large dictionary creation takes a LOT of time.

2005-04-28 Thread possibilitybox
this code here:


def wordcount(lines):
for i in range(len(lines)/8):
words = lines[i].split(" ")
if not locals().has_key("frequency"):
frequency = {}
for word in words:
if frequency.has_key(word):
frequency[word] += 1
else:
frequency[word] = 1
return frequency
wordcount(lines)

is taking over six minutes to run on a two megabyte text file.  i
realize that's a big text file, a really big one (it's actually the
full text of don quixote.).  i'm trying to figure out how.  is there a
better way for me to do a frequency count of all the words in the text?
 it seems to me like this should scale linearly, but perhaps it isn't?
i don't know much about algorithmic complexity.  if someone could give
a breakdown of this functions complexity as well i'd be much obliged.

lines is expected to be a list of lines as provided by file.readline()

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


Non-anonymous function arguments

2005-04-28 Thread cjm_usenet
I had an idea for passing functions as arguments:
Allow a block syntax (like with class definition)
for keyword arguments, attached to a statement
that includes a function call but doesn't need
the block for something else (like loops and ifs).
Apologies for the contrived examples.

  squares = map(*):
def function(x): return x*x
list=[1,2,3]

  def odds_and_evens(list, on_odd, on_even):
for i in list:
  if (i % 2 == 0):
on_even(i)
  else:
on_odd(i)

  odds_and_evens([1,2,3,4,5],*):
def on_odd(i):
  print (i/2) " * 2 + 1"
def on_even(i):
  print "2 * " (i/2)

  some_numbers=filter(*):
sequence=[1,2,3,4,5]
def function(x):
  return x > 2

  strange_list=sorted(["hello","world",7],*):
def key(x):
  if (x==7):
return "SEVEN"
  else:
return upper(x)

Unlike with lambda, the functions have names.
The marker inside the function call helps make
it obvious where the keywords go, especially
if the statement contains multiple function
calls.
There could be a keyword before the colon:

  some_numbers=filter(*) using:
sequence=[1,2,3,4,5]
def function(x):
  return x > 2

The marker is an asterisk because it's like
doing footnotes, alternatives are a plus sign
and multiple asterisks.
-- 
Caspian Maclean

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


Re: win32ui CreateFileDialog SLOW (since the SP2 Windows XP patch?)

2005-04-28 Thread Thomas Ganss
MsKitty schrieb:
Neil -
Interesting theory, but I installed brand new versions of Python
(2.4.1) and the win32 extensions on a machine that had no Python and
got the the same 4 minute response time, so that does not seem a likely
explanation, although its possible.
  - Kitty
Standalone machine or connected to a network ?
By any chance an older server (W2K,NT4) there ?
There were some issues...
HTH
thomas
--
http://mail.python.org/mailman/listinfo/python-list


Re: Shutting down twisted reacotr

2005-04-28 Thread Jason Mobarak
You might not need threads to get user input from the console. Jp
posted this in response to a similar query on the twisted-python
mailing list:

http://article.gmane.org/gmane.comp.python.twisted/9019

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


uploading large file 100mb

2005-04-28 Thread Thomas








Hi I am getting the following error when uploading large
files…

 

Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit
(Intel)] on win32

Type "help", "copyright",
"credits" or "license" for more information.

>>> ## working on region in file
c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py...

Traceback (most recent call last):

  File "", line 1, in ?

  File
"c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py", line 79, in ?

   
post_multipart("192.168.100.233","/UploaderHttp/",[('test','valTest')],[('FILE1','TM_A5_Bulk.pdf',data)]);

  File "c:/DOCUME~1/ADMINI~1/LOCALS~1/Temp/python-1156QtG.py",
line 17, in post_multipart

    h.send(body)

  File "C:\Python23\lib\httplib.py", line 576, in
send

    self.sock.sendall(str)

  File "", line 1, in sendall

socket.error: (10055, 'No buffer space available')

>>> 

 

 

Thanks

Thomas

 

 

 

The code that I am using

--

import httplib, mimetypes

 

def post_multipart(host, selector, fields, files):

    """

    Post fields and files to an http host as
multipart/form-data.

    fields is a sequence of (name, value) elements for
regular form fields.

    files is a sequence of (name, filename, value) elements
for data to be uploaded as files

    Return the server's response page.

    """

    content_type, body = encode_multipart_formdata(fields,
files)

    h = httplib.HTTP(host)

    h.putrequest('POST', selector)

    h.putheader('content-type', content_type)

    h.putheader('content-length', str(len(body)))

    h.endheaders()

    #print body;

    h.send(body)

    errcode, errmsg, headers = h.getreply()

    return h.file.read()

 

def encode_multipart_formdata(fields, files):

    """

    fields is a sequence of (name, value) elements for
regular form fields.

    files is a sequence of (name, filename, value) elements
for data to be uploaded as files

    Return (content_type, body) ready for httplib.HTTP
instance

    """

    BOUNDARY = '--ThIs_Is_tHe_bouNdaRY_$'

    CRLF = '\r\n'

    L = []

    for (key, value) in fields:

    L.append('--' + BOUNDARY)

    L.append('Content-Disposition: form-data;
name="%s"' % key)

    L.append('')

    L.append(value)

    for (key, filename, value) in files:

    L.append('--' + BOUNDARY)

    L.append('Content-Disposition: form-data;
name="%s"; filename="%s"' % (key, filename))

    L.append('Content-Type: %s' %
get_content_type(filename))

    L.append('')

    L.append(value)

    L.append('--' + BOUNDARY + '--')

    L.append('')

    body = CRLF.join(L)

    content_type = 'multipart/form-data; boundary=%s' %
BOUNDARY

    return content_type, body

 

def get_content_type(filename):

    return mimetypes.guess_type(filename)[0] or
'application/octet-stream'

 

FILE= 'c:/Documents and
Settings/Administrator/Desktop/TM_A5_Bulk.pdf';

f = file(FILE, "rb")

data = "">

f.close()

post_multipart("192.168.100.233","/UploaderHttp/",[('test','valTest')],[('FILE1','TM_A5_Bulk.pdf',data)]);






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

python.org mail flowing again

2005-04-28 Thread webmaster
Thanks to Thomas Wouters for quickly getting mail.python.org back up
once he was notified.  The mail backlog seems to be mostly finished.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"It's 106 miles to Chicago.  We have a full tank of gas, a half-pack of
cigarettes, it's dark, and we're wearing sunglasses."  "Hit it."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous function objects?

2005-04-28 Thread Michele Simionato
Uwe Mayer:
> Why does the "print" statement return a syntax error here?

Google for "Python regrets" where Guido admits that
'print' should have been a function.

   Michele Simionato

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


Re: Fast plotting?

2005-04-28 Thread Patrick Ellis
William Park <[EMAIL PROTECTED]> typed:
> Russell E. Owen <[EMAIL PROTECTED]> wrote:
>> Can anyone recommend a fast cross-platform plotting package for 2-D
>> plots?
>>
>> Our situation:
>> We are driving an instrument that outputs data at 20Hz. Control is
>> via an existing Tkinter application (which is being extended for
>> this new instrument) that runs on unix, mac and windows. We wish to
>> update 5-10 summary plots at approximately 2 Hz and will be offering
>> controls to control the instrument and the plots, preferably (but
>> not necessarily) mixed in with the plots.
>
> That's 10-20 plots per second.  The only GUI plotter that I know is
> 'gnuplot', and I don't know if it will spit out anything at 10-20Hz.
> For character plots (like old days terminal), it has speed but ugly to
> look at.
>
>>
>> Ideally the package would create plots in the Tkinter application.
>> But we realize we're unlikely to get the speed we need that way. So
>> we are willing to have the Tkinter app send data to the plotting
>> package  (e.g. via a socket) and have it display the plots in a
>> separate process.
>>
>> We started out with matplotlib, which is a wonderful package (and
>> well integrated with most or all GUI toolkits). Unfortunately it is
>> just too slow -- at least when driving plots integrated with the
>> Tkinter app. (It is getting faster and so are computers, so at some
>> point this will be a great way to go. But for now...)
>>
>> Any suggestions?
>>
>> -- Russell

disipyl is a wrapper around dislin. It includes a class that lets plots
appear inside tkinter frames. I did a quick test and the first demo plot
(run tkdisipyl.py) of a 180 point sine and cosine plotted at over 100 Hz.

http://kim.bio.upenn.edu/~pmagwene/disipyl.html
http://www.mps.mpg.de/dislin/


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


Re: Trying to write CGI script with python...

2005-04-28 Thread Jason Mobarak
Probably going to need more information about how mplayer is not being
accessed correctly.

CGI uses the shell environment to pass web information to a program...
so maybe this is messing up mplayer. You'll need to augment or wrap
your partners program in order to give you more information about
what's failing (e.g. wrap the call to mplayer in a try/except use the
traceback module to format a traceback if your CGI server is swallowing
it).

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


Re: why "import wx" doesn't work?

2005-04-28 Thread monkey
It is the current version of wxPython(2.6). But follow you instruction it
still can't work...
But if using the default "from wxPython.wx import *", it work, don't know
what is the problem. May be this is an old example that cannot work with
"import wx". Because I get another example and it is ok.

Anyway, I hope I can catch up with you guys here in python programming soon.
Thanks a lot ( :

> Assuming you've installed a version of wxPython that is recent enough
> that "import wx" works (it's really unclear from what you've written
> above), then the problem you are facing is not using the namespace that
> you've now imported.  Do this instead:
>
> class MyApp(wx.App):
>  def OnInit(self):
>  frame = wx.Frame(NULL, -1, "
>
>
> Note that "wx." before everything from wxPython...
>
> -Peter


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


Re: New Python website

2005-04-28 Thread Maurice LING
Michael Soulier wrote:
On 28 Apr 2005 17:45:02 -0700, lpe <[EMAIL PROTECTED]> wrote:
http://www.pycode.com
I was kinda suprised when I could not find any good sites with 3rd
party modules (other than the Vaults of Parnassus, where you must host
files elsewhere), so I decided to write one myself :)
It is brand new and might still be buggy, but hopefully it will be
usefull to some people.  Feel free to join and upload any of your code.
thanks

Something wrong with PyPi?
Mike
I think it is quite clear when he says "I could not find any good sites 
with 3rd party modules (other than the Vaults of Parnassus, where you 
must host files elsewhere)", suggesting that he is looking for a site 
whereby 3rd party modules can be hosted, rather than a site telling you 
where 3rd party modules are hosted.

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


Re: How do I parse this ? regexp ? [slighly OT]

2005-04-28 Thread Jeremy Bowers
On Thu, 28 Apr 2005 20:53:14 -0400, Peter Hansen wrote:
> The re docs clearly say this is not the case:
> 
> '''
> []
>  Used to indicate a set of characters. Characters can be listed
> individually, or a range of characters can be indicated by giving two
> characters and separating them by a "-". Special characters are not active
> inside sets.
> '''
> 
> Note the last sentence in the above quotation...
> 
> -Peter

Aren't regexes /fun/?

Also from that passage, Simon, note the "-" right in front of 
[-\[\]0-9,. ], another one that's tripped me up more than once.

Wh!

"Some people, when confronted with a problem, think ``I know, I'll use
regular expressions.'' Now they have two problems." - jwz
http://www.jwz.org/hacks/marginal.html

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


Re: Setting win32 console title from Python

2005-04-28 Thread Bengt Richter
On 28 Apr 2005 12:42:34 -0700, "runes" <[EMAIL PROTECTED]> wrote:

>Hi Duncan, sorry, I was unprecise.  I'm thinking of a script, called
>t.py  that can be used in the console  like an ordinary command. Som if
>I change directory from S:\scripts to d:\projects and execute the
>script  the title changes to "projects" etc.
>
>I have that functionality today with a combination of a python script
>and a batch file. I just wondered if I could use python all the way.
>Apparently I cannot.
>
>Here are the scripts:
>
>
>-- DirInPath:\t.bat 
>@echo off
>:: reads bare directory name from file
>:: created by external Python script
>set DIR_FILE_NAME=DOS_IS_TERRIBLE.tmp
>PyBareDir.py %DIR_FILE_NAME%
>
>for /F "eol=;" %%t in (%DIR_FILE_NAME%) do (
>   title %%t
>)
>
>del /Q /F DOS_IS_TERRIBLE.tmp
>
>
>
>-- DirInPath:\PyBareDir.py 
># extracts bare directory name and  writes
># it to file with name given as argument.
>
>from os import getcwd
>from os.path import basename
>import sys
>
>try:
>   saveAsName = sys.argv[1]
>   lastDir = basename(getcwd())
>   XWwz(saveAsName, 'w+').write(lastDir + '\n;')
>except:
>   print "PyBareDir failed:", sys.exc_info()[1]
>
>---
>

I think I'd try one of the win32 api packages and see if SetConsoleTitle
would work. I.e., from some old API docs:

The SetConsoleTitle function sets the title bar string for the current console 
window. 

BOOL SetConsoleTitle(

LPTSTR  lpszTitle   // address of new title  
   );   
Parameters

lpszTitle

Points to a null-terminated string that contains the string to appear in the 
title bar of the console window. 

Return Value

If the function succeeds, the return value is TRUE.
If the function fails, the return value is FALSE. To get extended error 
information, call GetLastError. 

See Also

GetConsoleTitle 


Alternatively, you could compile your own extension for
title setting/getting called consoletitle.dll
using the above API (assuming it works) and
its companion GetConsoleTitle.

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


Re: dynamically generating temporary files through python/cgi

2005-04-28 Thread Steve Holden
poisondart wrote:
Is there a way to dynamically generate temporary files (such as an
html, xml or text file) in Python?
I'm not sure if I'm explaining myself clearly as I've no clue how to
describe this mechanism. I've seen it on certain websites that will
generate a file under certain parameters (through forms) that will
dissapear (i.e. delete itself) after a specified amount of time. These
files usually have some phony string for their filenames...like it's
been md5 hashed or something.
Is there a group of library functions that allow this? I imagine that
if i manually go and allocate a bunch of timers to monitor files, it
would be really expensive in load. Or perhaps is this a client-side
mechanism?
Thanks,
- poisondart
Typically such functionality would be provided by having the server 
periodically run a task to delete files from the temporary directory 
whose age exceeds a given value.

regards
 Steve
--
Steve Holden+1 703 861 4237  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: New Python website

2005-04-28 Thread Maurice LING
lpe wrote:
http://www.pycode.com
I was kinda suprised when I could not find any good sites with 3rd
party modules (other than the Vaults of Parnassus, where you must host
files elsewhere), so I decided to write one myself :)
It is brand new and might still be buggy, but hopefully it will be
usefull to some people.  Feel free to join and upload any of your code.
thanks
Hi,
Just yesterday, I was frustrated waiting for replies from Catelog-SIG 
about the possibilities of a package management system that works like 
Fink (fink.sf.net). Basically, the problems I see is that C extension 
modules aren't portable across major Python revisions and there is no 
easy way to maintain the installed packages in site-packages directory. 
My scenario is that a system admin has to maintain 50 different 
libraries and their dependencies...

So I've decided to write something myself... and call it 'centipyde'.
Modelled against Fink and Darwinports (darwinports.opendarwin.org) 
(obviously I'm a Mac user), information (in text file) are in a folder 
(centipyde/pkginfo/) as .info files. Each package will have a .info file 
which tells the system (centipyde) where to download the source tar (or 
zip) and how to install the package, as well as the dependecies, 
maintaining the installed packages etc etc. No difference from other 
package managers (a goal)...

It is still very rough at this moment, so please bear with me. 
Basically, the user will have to cvs checkout the system and just run it.

I've checked it into Sourceforge, under IB-DWB project (which is 
abandoned) as 'centipyde'. But for some reason, I still can't view it in 
 ViewCVS yet. Anyway, the directory layout is

../centipyde
../centipyde/centipyde.py
../centipyde/pgkinfo
../centipyde/pgkinfo/ply15.info
ply15.info contains the following text (pretty much modelled against Fink):
package=ply15
maintainer=.
dependencies=.
downloadurl=http://systems.cs.uchicago.edu/ply/ply-1.5.tar.gz
prebuildscript=tar zxvf ply-1.5.tar.gz
sourcedir=ply-1.5
buildscript=python setup.py build
installscript=sudo python setup.py install
centipyde.py is the following:
=
"""
Author: Maurice H.T. Ling <[EMAIL PROTECTED]>
Copyright (c) 2005 Maurice H.T. Ling
Date created : 28th April 2005
"""
PKGINFOPATH = 'pkginfo'
INSTALL_LOG = 'install.log'
import os
import string
import sys
def install_package(package_name):
f = open(os.getcwd() + os.sep + PKGINFOPATH + os.sep + package_name 
+ '.info', 'r')
install_info = {}
for line in f.readlines():
line = string.split(line, '=')
if line[1][-1] == os.linesep:
install_info[line[0]] = string.strip(line[1][:-1])
else: install_info[line[0]] = string.strip(line[1])
f.close()
print "Package Installation Information: " + str(install_info)

os.system('curl -O ' + str(install_info['downloadurl']))
preinstall = []
preinstall = string.split(install_info['prebuildscript'], ';')
for cmd in preinstall: os.system(cmd)
cwd = os.getcwd()
print cwd
os.chdir(os.path.join(os.getcwd(), install_info['sourcedir']))
print os.getcwd()
buildscript = []
buildscript = string.split(install_info['buildscript'], ';')
for cmd in buildscript: os.system(cmd)
installscript = []
installscript = string.split(install_info['installscript'], ';')
for cmd in installscript: os.system(cmd)
if sys.argv[1] == 'install':
install_package(sys.argv[2])
=
When I run "python centipyde.py install ply15", PLY1.5 gets downloaded 
from David Beazley's website, uncompressed and installed into the 
site-package as shown here:

znichols-maurice:~/MyProjects/ib-dwb/centipyde mauriceling$ ls -alltotal 8
drwxr-xr-x   5 mauricel  mauricel   170 28 Apr 17:37 .
drwxr-xr-x  10 mauricel  mauricel   340 28 Apr 16:21 ..
drwxr-xr-x   5 mauricel  mauricel   170 28 Apr 17:33 CVS
-rw-r--r--   1 mauricel  mauricel  1385 28 Apr 23:47 centipyde.py
drwxr-xr-x   4 mauricel  mauricel   136 28 Apr 17:36 pkginfo
znichols-maurice:~/MyProjects/ib-dwb/centipyde mauriceling$ sudo python 
centipyde.py install ply15
Package Installation Information: {'maintainer': '.', 'sourcedir': 
'ply-1.5', 'package': 'ply15', 'downloadurl': 
'http://systems.cs.uchicago.edu/ply/ply-1.5.tar.gz', 'installscript': 
'sudo python setup.py install', 'dependencies': '.', 'buildscript': 
'python setup.py build', 'prebuildscript': 'tar zxvf ply-1.5.tar.gz'}
  % Total% Received % Xferd  Average Speed  Time 
  Curr.
 Dload  Upload TotalCurrent  Left 
  Speed
100 69278  100 692780 0   7746  0  0:00:08  0:00:08  0:00:00 
31811
ply-1.5/
ply-1.5/doc/
ply-1.5/doc/ply.html
ply-1.5/CHANGES
ply-1.5/COPYING

. [snipped] .
ply-1.5/test/yacc_uprec.exp
ply-1.5/test/yacc_uprec.py
/sw/lib/python2.3/distutils/dist.py:213: UserWarning: 'licence' 
distribution option is deprecated; use 'license'

Re: New Python website

2005-04-28 Thread Michael Soulier
On 28 Apr 2005 17:45:02 -0700, lpe <[EMAIL PROTECTED]> wrote:
> http://www.pycode.com
> 
> I was kinda suprised when I could not find any good sites with 3rd
> party modules (other than the Vaults of Parnassus, where you must host
> files elsewhere), so I decided to write one myself :)
> It is brand new and might still be buggy, but hopefully it will be
> usefull to some people.  Feel free to join and upload any of your code.
> thanks

Something wrong with PyPi?

Mike

-- 
Michael P. Soulier <[EMAIL PROTECTED]>
http://www.digitaltorque.ca
http://opag.ca  python -c 'import this'
--
http://mail.python.org/mailman/listinfo/python-list


Python Client & Loggin into Secure User Database

2005-04-28 Thread flamesrock
First, my problem doesn't make much practical sense so I hope you're up
for a challenge.

What I have (in concept) is a standalone web client that connects
different 'players' to a central host and distributes game files
between them. A user claims certain files, plays them, and then
automatically uploads them to the site where they are subsequently
distributed.

What I want to do is have a secure system that lets users log in upon
connecting so that the client has ftp privileges to upload. I'd like to
avoid xmlrpc and anything that would require the server to do more than
a simple php + sql script,  preferably less. Basically, as simple as
possible without scripting the server in python too.

Whats the best way to accomplish this for a python client?
(registration will be browser based btw..)

-thanks in advance

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


Re: Working with method-wrapper objects

2005-04-28 Thread Steven Bethard
Dr. Peer Griebel wrote:
Why has [].__str__ a different type than object.__str__?
Why is object.__str__ a routine while object().__str__ not?
Well, I don't know why inspect.isroutine does what it does, but if you 
really need to detect these, can you do something like:

py> MethodWrapperType = type(object().__str__)
py> type([].__str__) == MethodWrapperType
True
This is basically all the types module does for similar types.  (Take a 
look -- it's written in Python.)

Some more investigation shows that also the module "types" is not 
universally usable. E.g. InstanceType is only usabel for instances of 
old classes. How do I test for instances of new classes?
isinstance(obj, object)
All new-style classes are subclasses of object (even type!)
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Steven Bethard
Lonnie Princehouse wrote:
Likewise, the above is basically just an inefficient way of writing:
def date_key(book):
   return book.data
def author_and_date_key(book):
   return (author_key(book), date_key(book))

It's certainly more elegant, but I wanted to talk about the mechanics
of comparison functions =)
I don't know that it's more or less efficient in execution.  That
depends on a few factors.
For most cases, key= will be more efficient than cmp=.  The key= 
argument will only be called once for each item in the list.  The cmp= 
argument will be called once for each comparison:

py> class Cmp(object):
... def __init__(self):
... self.count = 0
... def __call__(self, x, y):
... self.count += 1
... return cmp(x, y)
...
py> class Key(object):
... def __init__(self):
... self.count = 0
... def __call__(self, x):
... self.count += 1
... return x
...
py> import random
py> lst = range(1000)
py> random.shuffle(lst)
py> lst2 = list(lst)
py> c = Cmp()
py> lst.sort(cmp=c)
py> c.count
8599
py> k = Key()
py> lst.sort(key=k)
py> k.count
1000
Since in all but a few corner cases (e.g. where the list is already 
sorted) there will be way more comparisons than items, the key= argument 
will minimize the number of function calls.  Since function calls are 
one of the more expensive operations in Python, my guess is that there 
are very few cases where you would want to use the cmp= argument if you 
know you can use the key= argument.

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


Re: regex over files

2005-04-28 Thread Bengt Richter
On Thu, 28 Apr 2005 20:35:43 +, Robin Becker <[EMAIL PROTECTED]> wrote:

>Jeremy Bowers wrote:
>
> >
> > As you try to understand mmap, make sure your mental model can take into
> > account the fact that it is easy and quite common to mmap a file several
> > times larger than your physical memory, and it does not even *try* to read
> > the whole thing in at any given time. You may benefit from
> > reviewing/studying the difference between virtual memory and physical
> > memory.
>I've been using vm systems for 30 years and I suspect my mental model is a bit
>decrepit. However, as convincingly demonstrated by testing my mental model 
>seems
>able to predict low memory problems. When systems run out of memory they tend 
>to
>perform poorly. I'm not sure the horrible degradation I see with large files is
>necessary, but I know it occurs on at least two common vm implementations.

It's interesting. One could envisage an mmap that would hava a parameter for 
its own
lru working set max page count, so mmap would only displace up to that many
pages from normal system paged-in file data. Then you could induce extra
reads by referring back to abandoned mmap-lru pages, but you wouldn't be
displacing anything else, and if you were moving sequentially and staying within
your page residency count allotment, things would work like the best of both 
worlds
(assuming this idea doesn't have a delusion-busting gotcha lurking ;-) 
But this kind of partitioning of VM lru logic would take some kernel changes 
IWT.

IIRC, don't mmap VM access ideas date back to multics at least?
Anyway, what with fancy controllers as well as fancy file systems and kernels,
it's easy to get hard-to-interpret results, but your large-file examples seem
pretty conclusive.

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


Re: Best way to parse file into db-type layout?

2005-04-28 Thread John Machin
On Fri, 29 Apr 2005 01:44:30 +0100, Michael Hoffman
<[EMAIL PROTECTED]> wrote:

>for row in csv.reader(fileinput.input()):

csv.reader requires that if the first arg is a file that it be opened
in binary mode.


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


Re: anonymous function objects?

2005-04-28 Thread Peter Hansen
Uwe Mayer wrote:
Unfortunately I want to assign a handler function to an object and something
like this does not work:
class Foobar(object): pass
...
a = Foobar()
def a.handler():
  File "", line 1
def a.handler():
 ^
SyntaxError: invalid syntax
But this does work, or something close to it:
>>> class Foobar(object): pass
...
>>> def handler(self):
...   print 'in handler'
...
>>> f = Foobar()
>>> f.handler()
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: 'Foobar' object has no attribute 'handler'
>>>
>>> import new
>>> f.handler = new.instancemethod(handler, f)
>>> f.handler()
in handler
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Shutting down twisted reacotr

2005-04-28 Thread Jp Calderone
On Thu, 28 Apr 2005 12:34:33 + (UTC), Operation Latte Thunder <[EMAIL PROTECTED]> wrote:
Jason  Mobarak <[EMAIL PROTECTED]> wrote:
Why do you want to do this in a thread? What's wrong with
reactor.callLater?
import time
from twisted.internet import reactor
def shutdown():
   time.sleep(3)
   print "stopping"
   reactor.callFromThread(reactor.stop)
reactor.callInThread(shutdown)
reactor.run()
In the app I am playing with, I have a thread that reads from the console.
When it terminates, I wanted it to shut down the reactor and couldn't use
callLater.  However, callFromThread worked perfectly.   I guess I need to
look at the docs some more to understand why its necessary
 In general, you cannot call Twisted APIs from a thread other than that in 
which the reactor is executing.  There are a few exceptions, callFromThread 
being one of them, but in general doing so has unpredictable behavior and is 
not supported.
 You also may be interested in twisted.internet.stdio and, in Twisted 2.0, 
twisted.conch.insults.
 Jp
--
http://mail.python.org/mailman/listinfo/python-list


Re: How do I parse this ? regexp ? [slighly OT]

2005-04-28 Thread Peter Hansen
Simon Dahlbacka wrote:
safetyChecker = re.compile(r"^[-\[\]0-9,. ]*$")
..doesn't the dot (.) in your character class mean that you are allowing
EVERYTHING (except newline?)
The re docs clearly say this is not the case:
'''
[]
Used to indicate a set of characters. Characters can be listed 
individually, or a range of characters can be indicated by giving two 
characters and separating them by a "-". Special characters are not 
active inside sets.
'''

Note the last sentence in the above quotation...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


New Python website

2005-04-28 Thread lpe
http://www.pycode.com

I was kinda suprised when I could not find any good sites with 3rd
party modules (other than the Vaults of Parnassus, where you must host
files elsewhere), so I decided to write one myself :)
It is brand new and might still be buggy, but hopefully it will be
usefull to some people.  Feel free to join and upload any of your code.
thanks

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


Re: Best way to parse file into db-type layout?

2005-04-28 Thread Michael Hoffman
Peter A. Schott wrote:
I've got a file that seems to come across more like a dictionary from what I can
tell.  Something like the following format:
###,1,val_1,2,val_2,3,val_3,5,val_5,10,val_10
###,1,val_1,2,val_2,3,val_3,5,val_5,11,val_11,25,val_25,967,val_967
Peter, I'm not sure exactly what you want. Perhaps a dictionary for each
row in the file? Where the first row would result in:
{"letter_type": "###", 1: "val_1", 2: "val_2", 3: "val_3", 5: "val_5",
10: "val_10"}
Something like this:
import csv
import fileinput
row_dicts = []
for row in csv.reader(fileinput.input()):
row_dict = dict(letter_type=row[0])
for col_index in xrange(1, len(row), 2):
row_dict[int(row[col_index])] = row[col_index+1]
row_dicts.append(row_dict)
Someone else might come up with something more elegant.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to parse file into db-type layout?

2005-04-28 Thread John Machin
On Thu, 28 Apr 2005 23:34:31 GMT, Peter A. Schott
<[EMAIL PROTECTED]> wrote:

>I've got a file that seems to come across more like a dictionary from what I 
>can
>tell.  Something like the following format:
>
>###,1,val_1,2,val_2,3,val_3,5,val_5,10,val_10
>###,1,val_1,2,val_2,3,val_3,5,val_5,11,val_11,25,val_25,967,val_967
>
>In other words, different layouts (defined mostly by what is in val_1, val_2,
>val_3).
>
>The ,#, fields indicate what "field" from our mainframe the corresponding value
>represents.
>
>Is there a good way to parse this into a DB-type format where I only pull out
>the values corresponding to the appropriate field numbers?  Seems like
>converting to a dictionary of some sort would be best, but I don't quite know
>how I would go about that.
>
>In this case, the first field is a value unto itself - represents a "letter
>type" that would be associated with the rest of the record.  The fields are
>either present or not, no placeholder if there's no value for e.g. Field #4.

Here's a sketch, tested as you'll see, but totally devoid of the
error-checking that would be necessary for any data coming from an MF.

C:\junk>type schott.txt
pers,1,xxx,2,yyy,3,zzz,100,SMITH,101,JOHN,102,ALOYSIUS,103,1969-12-31
addr,1,qqq,2,www,3,eee,200,"""THE LODGE"", 123 MAIN ST",205,WALLA
WALLA,206,WA

C:\junk>type schott.py
import csv
for row in csv.reader(open('schott.txt', 'rb')):
rectype = row[0]
recdict = {}
for k in range(1, len(row), 2):
recdict[int(row[k])] = row[k+1]
print rectype, recdict

C:\junk>python schott.py
pers {1: 'xxx', 2: 'yyy', 3: 'zzz', 100: 'SMITH', 101: 'JOHN', 102:
'ALOYSIUS', 103: '1969-12-31'}
addr {1: 'qqq', 2: 'www', 3: 'eee', 200: '"THE LODGE", 123 MAIN ST',
205: 'WALLA WALLA', 206: 'WA'}

Hint: you'll probably go nuts if you don't implement some sort of
naming convention instead of those numbers.

One way would be like this:

mf_surname = 100
mf_given_1 = 101
...
mf_state = 206

then you can refer to recdict[mf_state] instead of recdict[206].

Going upmarket a bit:

Have a mf_map = {100: 'surname', 206: 'state', } # etc etc

then you do

class Record(object):
pass

# for each row:
   rec = Record()
   rec.rectype = row[0]
   for k in range(1, len(row), 2):
   setattr(rec, mf_map[int(row[k])], row[k+1])

Then you can refer to rec.state instead of recdict[mf_state] or
recdict[206].

Further upmarket would involve gathering basic "type" information
about the MF fields (free text, alpha code, identifier (e.g. SSN),
money, quantity, date, etc etc) so that you can do validations and
format conversions as appropriate.

HTH,
John



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


Re: logging problems

2005-04-28 Thread Michael Hoffman
Simon Dahlbacka wrote:
print sys.modules["traceback"]
import traceback
print "Hello World"
sys.stdout.flush()
just renders:  in the
console, and no "Hello World"
Works fine on Python 2.4 for Windows.
I'm running out of ideas what to try next, so suggestions/ideas appreciated!
That's a very strange failure condition. Perhaps something is wrong with 
your
Python installation. Have you edited any other system modules besides logging?
I would try a clean installation of the newest version and see if that fixes
it.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: OOP

2005-04-28 Thread Dave Cook
On 2005-04-28, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> I'm new to Python and I love it. Now I can get most of the topics
> covered with the Python tutorials I've read but the one thats just
> stumping me is Object Orientation. I can't get the grasp of it. Does
> anyone know of a good resource that could possibly put things in focus
> for me? Thanks.

I haven't seen anything specifically written for Python that gets much
beyond the mechanics.

One of the best books I've read on OOP is _Smalltalk, Objects, and Design_
by Chamond Liu.  It would be nice to have something like that for Python.

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


Re: OOP

2005-04-28 Thread Scott Robinson
On Thu, 28 Apr 2005 17:58:47 GMT, Charles Krug
<[EMAIL PROTECTED]> wrote:

>On 28 Apr 2005 10:34:44 -0700, [EMAIL PROTECTED]
><[EMAIL PROTECTED]> wrote:
>> Hey yall,
>> I'm new to Python and I love it. Now I can get most of the topics
>> covered with the Python tutorials I've read but the one thats just
>> stumping me is Object Orientation. I can't get the grasp of it. Does
>> anyone know of a good resource that could possibly put things in focus
>> for me? Thanks.
>> 
>
>"Learning Python" (Lutz/Ascher) has a good discussion of the basics.
>
>Unfortunately, most of the OOP writings I've read fall into two
>catagories:  Trivial examples where you say, "But why Bother??" and
>examples that you don't understand until you've some OO design under
>your belt and can understand what it's all good for.
>
>Objects are, at the end of the day, data and the accompanying methods.
>Once you've read the various tutorials take a stab at converting a
>problem you know well into objects.
>
>You'll get it wrong at first.  Most everyone does.  Don't sweat it.
>Eventually, you'll just "get" it.

[Note:  this is just the start of an explanation.  If you don't
understand OOP, just try programming that way (yes, I got it wrong to
see my usage of "Wally objects").  

This is something I thought of awhile ago, and wondered where I could
use it.  My background is a hardware guy who first learned spaghetti
coding in basic on 8-bits, received the wisdom of modular programming
when learning assembler, then much later tried his hand teaching
himself python.  Those from other backgrounds may be amused at my
naivete.]
 
I've been trying to figure out the "Dilbert" view of OOP.

My first objects were like C types:

class Super_object:
pass

Consider this the Wally object.

Wally=Super_object():

Things get put on his desk:

Wally.MeetingActionItems=[1,2,3]

And stay there.  At first, this seems great.  It gives you plenty of
desks to store data on.

After a while, you might paint yourself into a corner (such as wanting
to append to lists, but later wish to hard limit the number of
entries, thus needing to change from a list to an overloaded object).
This brings the Dilbert object.  You can put things on Dilbert's desk,
but unlike Wally, he can actually notice the objects, manage them, and
do some work on it.

Class Dilbert_object:
__init__(self):
ActionItems=[]
def AddItems(self,items):
self.ActionItems.append(items)

def DoAction(self):
return self.ActionItems.pop()   

Ok, I admit that this just looks like yet another getter and setter.
Maybe this is an Asok object and Dilbert would realize that the Boss
doesn't remember everything on his desk, so we change it to:

Class Dilbert_object:
__init__(self):
ActionItems=[]
def AddItems(self,items):
self.ActionItems.append(items)
if len(self.ActionItems)>10:
self.ActionItems.pop(0) 
def DoAction(self):
return self.ActionItems.pop()   

Since OOP dogmatists insist that inheritance is vital to OOP, we
include the Alice object.  Alice can do everything Dilbert can do, and
then some.  To include Dilbert's skills we simply include

Class Alice_object(Dilbert_object):

To add new things to the Alice object:

Class Alice_object(Dilbert_object):
def FistOfDeath(self):
import os
os._exit(0)


The critical thing is that you can now let Dilbert manage your data.
That's one of the main reasons for inventing computers anyway, to
manage data.  So write subprograms (objects) that do your work for
you, and work as thanklessly as Dilbert, and then try to concentrate
on debugging the big picture.

Scott

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


Re: dynamically generating temporary files through python/cgi

2005-04-28 Thread fred.dixon
import tempfile
works under windows and linux

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


Re: Python site-packages and import

2005-04-28 Thread Maurice LING
Peter Saffrey wrote:
I'm trying to write a python service, with an executable in
/usr/local/bin, but modules that are kept in a sub-directory of
/usr/lib/python/site-packages.
Using apt-proxy as my template, I've put the modules in
/usr/lib/python/site-packages/mymodules and tried to import them with
import mymodules.module1. However, this doesn't seem to be working,
even though something very similar works for apt-proxy. I thought this
might be something to do with sys.path, but I can't work out why it's
different for my modules and those used by apt-proxy.
To be fair, it is past midnight, and I'm probably just being stupid.
Would anybody care to point out where? :)
Peter
your site-packages directory must be seen in python. try
import sys
sys.path
and see if your site-packages directory is listed?
maurice
--
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous function objects?

2005-04-28 Thread gabriele renzi
Uwe Mayer ha scritto:
Friday 29 April 2005 00:06 am Paul Rubin wrote:
Closest you can come is:
  f = lambda: sys.stdout.write("hello world\n")
 
Ah. :))
Why does the "print" statement return a syntax error here?
 ^

this is the reason :)
You can't have statements into an expression
--
http://mail.python.org/mailman/listinfo/python-list


Best way to parse file into db-type layout?

2005-04-28 Thread Peter A.Schott
I've got a file that seems to come across more like a dictionary from what I can
tell.  Something like the following format:

###,1,val_1,2,val_2,3,val_3,5,val_5,10,val_10
###,1,val_1,2,val_2,3,val_3,5,val_5,11,val_11,25,val_25,967,val_967

In other words, different layouts (defined mostly by what is in val_1, val_2,
val_3).

The ,#, fields indicate what "field" from our mainframe the corresponding value
represents.

Is there a good way to parse this into a DB-type format where I only pull out
the values corresponding to the appropriate field numbers?  Seems like
converting to a dictionary of some sort would be best, but I don't quite know
how I would go about that.

In this case, the first field is a value unto itself - represents a "letter
type" that would be associated with the rest of the record.  The fields are
either present or not, no placeholder if there's no value for e.g. Field #4.

Thanks for any help or pointers you can give me.

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


Re: why "import wx" doesn't work?

2005-04-28 Thread Filip Dreger

U¿ytkownik "monkey" <[EMAIL PROTECTED]> napisa³ w wiadomo¶ci 
news:[EMAIL PROTECTED]
>> Which version of wxPython are you running? What do you mean by 
>> "does not
>> work"...does the import fail or is your code giving errors?
>
> It is the current new version 2.6. The error message said that the 
> class
> wxApp is not defined...

This is very good! wxApp is never defined if you use "import wx". You 
must use "wx.wxApp" instead.

If you import a module using "import anything", then all the names 
imported from the module must begin with "anything.". If you import wx 
using "import wx", then ALL the wx commands, classes and variables 
(all the names) MUST begin with 'wx.". Change them, and your program 
will work.

"from wx import *" is a special shortcut, allowing you to use all the 
names without "wx.". If you change "from something import *" to 
"import something", your code will always break, this is normal.

regards,
Filip Dreger 


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


Python site-packages and import

2005-04-28 Thread Peter Saffrey
I'm trying to write a python service, with an executable in
/usr/local/bin, but modules that are kept in a sub-directory of
/usr/lib/python/site-packages.

Using apt-proxy as my template, I've put the modules in
/usr/lib/python/site-packages/mymodules and tried to import them with
import mymodules.module1. However, this doesn't seem to be working,
even though something very similar works for apt-proxy. I thought this
might be something to do with sys.path, but I can't work out why it's
different for my modules and those used by apt-proxy.

To be fair, it is past midnight, and I'm probably just being stupid.
Would anybody care to point out where? :)

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


Re: anonymous function objects?

2005-04-28 Thread Uwe Mayer
Friday 29 April 2005 00:06 am Paul Rubin wrote:
> Closest you can come is:
> 
>f = lambda: sys.stdout.write("hello world\n")
 
Ah. :))
Why does the "print" statement return a syntax error here?

>>> lambda: print("hallo")
  File "", line 1
lambda: print("hallo")
^
SyntaxError: invalid syntax

> Of course if you're trying to capture the function in a named variable
> like f, just use a def statement.

Unfortunately I want to assign a handler function to an object and something
like this does not work:

>>> class Foobar(object): pass
...
>>> a = Foobar()
>>> def a.handler():
  File "", line 1
def a.handler():
 ^
SyntaxError: invalid syntax

But wrapping print into a myprint function works :)


Thanks,
Ciao
Uwe 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous function objects?

2005-04-28 Thread Paul Rubin
Uwe Mayer <[EMAIL PROTECTED]> writes:
> >>> f = {print "hello world"}
> >>> f()
> hello world

> in Pyton?  Lambda expressions don't work here.

Closest you can come is:

   f = lambda: sys.stdout.write("hello world\n")

Of course if you're trying to capture the function in a named variable
like f, just use a def statement.
-- 
http://mail.python.org/mailman/listinfo/python-list


anonymous function objects?

2005-04-28 Thread Uwe Mayer
Is it possible to specify anonymous functions, something like:

>>> f = {print "hello world"}
>>> f()
hello world


in Pyton?
Lambda expressions don't work here.

Thanks,
Uwe

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


Re: why "import wx" doesn't work?

2005-04-28 Thread Kartic
The Great 'monkey' uttered these words on 4/28/2005 5:50 PM:
Which version of wxPython are you running? What do you mean by "does not
work"...does the import fail or is your code giving errors?

It is the current new version 2.6. The error message said that the class
wxApp is not defined...
But when using the default "from wxPython.wx import *", it works.

See my previous post for examples... you are mixing the new import style 
and old style of using the classes. That will not work.

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


Re: why "import wx" doesn't work?

2005-04-28 Thread Kartic
The Great 'monkey' uttered these words on 4/28/2005 5:30 PM:
It is the current version of wxPython(2.6). But follow you instruction it
still can't work...
But if using the default "from wxPython.wx import *", it work, don't know
what is the problem. May be this is an old example that cannot work with
"import wx". Because I get another example and it is ok.

I suspect you are mixing program code for the namespace version (import 
wx) with the old method of importing (from wxPython.wx import *).

Here are two version of a very simple app... try both and see if you get 
any errors. And if so, _please_ post the exact error you get.

--- BEGIN The "new" namespace version 
import wx
class MainFrame(wx.Frame):
def __init__(self, parent, id=-1, title="Test Wx", size=(-1, -1), 
pos=(-1,-1), style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE):
wx.Frame.__init__(self, parent, id, title, size, pos, style)
self.Show(True)

app = wx.PySimpleApp()
frame = MainFrame(None, -1, "Test Wx NameSpace Style")
app.MainLoop()
--- END The "new" namespace version 
--- BEGIN The old style import 
from wxPython.wx import *
class MainFrame(wxFrame):
def __init__(self, parent, id=-1, title="Test Wx", size=(-1, -1), 
pos=(-1,-1), style=wxDEFAULT_FRAME_STYLE|wxNO_FULL_REPAINT_ON_RESIZE):
wxFrame.__init__(self, parent, id, title, size, pos, style)
self.Show(True)

app = wxPySimpleApp()
frame = MainFrame(None, -1, "Test Wx Old Style")
app.MainLoop()
--- END The old style import 
Hope that helped!
Thanks,
-Kartic
--
http://mail.python.org/mailman/listinfo/python-list


Re: Can .py be complied?

2005-04-28 Thread monkey
> python -o foo.exe foo.py
>

Is that a real command that can be use?


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


Re: why "import wx" doesn't work?

2005-04-28 Thread monkey
> Which version of wxPython are you running? What do you mean by "does not
> work"...does the import fail or is your code giving errors?

It is the current new version 2.6. The error message said that the class
wxApp is not defined...
But when using the default "from wxPython.wx import *", it works.


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


Re: unicode encoding problem

2005-04-28 Thread "Martin v. Löwis"
[EMAIL PROTECTED] wrote:
> So how do I tell what encoding my unicode string is in, and how do I
> retrieve that when I read it from a file?

In interactive mode, you best avoid non-ASCII characters in a Unicode
literal.

In theory, Python should look at sys.stdin.encoding when processing
the interactive source. In practice, various Python releases ignore
sys.stdin.encoding, and just assume it is Latin-1. What is
sys.stdin.encoding on your system?

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


Re: Can .py be complied?

2005-04-28 Thread Maurice LING
steve.leach wrote:
python -o foo.exe foo.py
at the command line, and get an executable, without any further effort.

Hence making the resulting program useless to users of most operating 
systems.
In close sourced development, which most corporates may prefer, yes, the 
resulting program is useless to users of most operating systems.

In open sourced developement, it is still a good feature to have. At 
least for distribution to end users or as trial.

To end users, they don't care, as long as they can click and run the 
program they need.

To developers, if the codes are close source, nothing can be done anyway 
even if you have the codes, licensing agreements and contracts usually 
forbids everything. If the codes are open source, you will get the codes 
 anyway and do according to the limits of the licence.

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


Re: dynamically generating temporary files through python/cgi

2005-04-28 Thread Jaime Wyant
On 27 Apr 2005 23:32:15 -0700, poisondart <[EMAIL PROTECTED]> wrote:
> Is there a way to dynamically generate temporary files (such as an
> html, xml or text file) in Python?
> 
> I'm not sure if I'm explaining myself clearly as I've no clue how to
> describe this mechanism. I've seen it on certain websites that will
> generate a file under certain parameters (through forms) that will
> dissapear (i.e. delete itself) after a specified amount of time. These
> files usually have some phony string for their filenames...like it's
> been md5 hashed or something.
> 
> Is there a group of library functions that allow this? I imagine that
> if i manually go and allocate a bunch of timers to monitor files, it
> would be really expensive in load. Or perhaps is this a client-side
> mechanism?

I think the best way to do that is have a web page that generates the
files with random filenames.  These files probably ought to reside in
their own special directory.  This web page gives the user a link to
the filename.

Next, have a cron job kick off every 5 minutes or so that deletes any
files that are older than 'X' minutes.  This seems to be the simplest
approach.

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


Re: OOP

2005-04-28 Thread Kartic
The Great '[EMAIL PROTECTED]' uttered these words on 4/28/2005 
1:34 PM:
Hey yall,
I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me? Thanks.
I thought the Object Orientation chapter (Chapter 5) of Python in a 
Nutshell by Alex Martelli, gave a good overview for Classes in Python. 
Please take a peek at it and see if it helps you any.

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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Lonnie Princehouse
> Likewise, the above is basically just an inefficient way of writing:
>
> def date_key(book):
> return book.data
>
> def author_and_date_key(book):
> return (author_key(book), date_key(book))

It's certainly more elegant, but I wanted to talk about the mechanics
of comparison functions =)

I don't know that it's more or less efficient in execution.  That
depends on a few factors.

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


Re: why "import wx" doesn't work?

2005-04-28 Thread Kartic
The Great 'monkey' uttered these words on 4/28/2005 2:09 PM:
I just learn to make a blank windows frame with python and wxpython. I found
the statment "import wx" cannot work as the original "from wxPython.wx
import *". I see in the readme file of wxpython that if I install it as the
default one, I can use "import wx" instead of the long one. What is wrong?
The code pasted below:
import wx   # the default is "from wxPython.wx import *", I change it and it
just can't work.

Which version of wxPython are you running? What do you mean by "does not 
work"...does the import fail or is your code giving errors?
--
http://mail.python.org/mailman/listinfo/python-list


unicode encoding problem

2005-04-28 Thread garykpdx

Every time I think I understand unicode, I prove I don't.

I created a variable in interactive mode like this:
s = u'ä'
where this character is the a-umlaut
that worked alright. Then I encoded it like this:
s.encode( 'latin1')

and it printed out a sigma (totally wrong)

then I typed this:
s.encode( 'utf-8')

Then it gave me two weird characters +ñ

So how do I tell what encoding my unicode string is in, and how do I
retrieve that when I read it from a file?

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


Data smoothing algorithms?

2005-04-28 Thread Anthra Norell



Hi,
 
The following are differences of solar declinations 
from one day to the next, (never mind the unit). Considering the inertia of a 
planet, any progress of (apparent) celestial motion over regular time intervals 
has to be highly regular too, meaning that a plot cannot be jagged. The data I 
googled out of Her Majesty's Nautical Almanac are merely nautical precision and 
that, I suppose, is where the jitter comes in. There's got to be algorithms out 
there to iron it out. If it were a straight line, I could do it. But this, over 
the whole year, is a wavy curve, somthing with a dominant sine component. 
Suggestions welcome.
 
Frederic
 
< snip >2008.05.29    
-2.754  XX2008.05.30    
-2.614  XXX2008.05.31    
-2.798  XX2008.06.01    
-3.048  XXX2008.06.02    
-3.092  XXX2008.06.03    
-3.092  XXX2008.06.04    
-3.527  XX2008.06.05    -3.385  
2008.06.06    -3.573  
XX2008.06.07    -3.820  
XXX2008.06.08    -3.865  
XXX2008.06.09    -3.865  
XXX2008.06.10    -3.865  
XXX2008.06.11    -3.865  
XXX2008.06.12    -3.429  
XXX2008.06.13    -4.011  
X2008.06.14    -4.109  
2008.06.15    -4.348  
XX2008.06.16    -4.155  
2008.06.17    -4.348  
XX2008.06.18    -4.155  
2008.06.19    -3.912  
XX2008.06.20    -4.302  
XX2008.06.21    -4.155  
2008.06.22    -4.349  
XX2008.06.23    -4.155  
2008.06.24    -3.913  
XX2008.06.25    -3.866  
XXX2008.06.26    -4.303  
XX2008.06.27    -4.155  
2008.06.28    -3.913  
XX2008.06.29    -3.866  
XXX< snip >
-- 
http://mail.python.org/mailman/listinfo/python-list

[ANNOUNCE] Twenty-fourth release of PythonCAD now available

2005-04-28 Thread Art Haas

I'm pleased to announce the twenty-fourth development release of PythonCAD,
a CAD package for open-source software users. As the name implies,
PythonCAD is written entirely in Python. The goal of this project is
to create a fully scriptable drafting program that will match and eventually
exceed features found in commercial CAD software. PythonCAD is released
under the GNU Public License (GPL).

PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0
based, and uses the PyGTK module for interfacing to GTK. The design of
PythonCAD is built around the idea of separating the interface
from the back end as much as possible. By doing this, it is hoped
that both GNOME and KDE interfaces can be added to PythonCAD through
usage of the appropriate Python module. Addition of other PythonCAD 
interfaces will depend on the availability of a Python module for that
particular interface and developer interest and action.

The twenty-fourth release contains numerous improvements to the code
used for constructing the user interface and the entity drawing routines.
This release utilizes the GTK Action and ActionGroup classes for building
and controlling the menubar and menus. Using these classes greatly simplifies
and enhances the ability to manipulate the menu items, and these features
are used extensively in this release. Many menu choices are now activated
when the functionality they provide can be used, and deactivated when their
use is not possible. More enhancements of this nature will be appearing in
future releases. Another significant improvement is the refactoring of the
entity drawing routines. These routines are now provided as methods for each
entity class, making their usage much clearer and simpler. Changing the
drawing routines has allowed significant simplification of the code
responsible for drawing as well as fixing several drawing bugs. Future
releases of PythonCAD will build on this change to enhance and improve the
graphical behavior of the program even further. A number of PyGTK deprecation
warnings that slipped by in the previous release have been removed, and a
good number of bug fixes and code enhancements are present in this release
as well.

A mailing list for the development and use of PythonCAD is available.
Visit the following page for information about subscribing and viewing
the mailing list archive:

http://mail.python.org/mailman/listinfo/pythoncad

Visit the PythonCAD web site for more information about what PythonCAD
does and aims to be:

http://www.pythoncad.org/

Come and join me in developing PythonCAD into a world class drafting
program!

Art Haas
-- 
Man once surrendering his reason, has no remaining guard against absurdities
the most monstrous, and like a ship without rudder, is the sport of every wind.

-Thomas Jefferson to James Smith, 1822
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding an interactive console

2005-04-28 Thread Paul Miller
Paul Miller wrote:
I note the documentation for InteractiveConsole, which is implemented in 
Python. Is there any example code for using this from within C/C++ code 
to emulate the command-line interpreter inside a GUI app?
I've gotten my text edit widget to send InteractiveConsole strings to 
run and can see the results.

But I'm not getting a >>> prompt consistently.
I'd love to see some sample code from anyone who is using this with an 
embedded interpreter.

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


logging problems

2005-04-28 Thread Simon Dahlbacka
Hi,

I'm currently using python 2.3.4 and I'm having problem with the logging module.

Occasionally when logging something with exc_info=True it just hangs, nothing is
logged, and software cannot continue executing.

By drilling down into logging package and adding rather many print statements
into  logging/__init__.py it seems like the "import traceback" in
formatException(self, ei) fails.

I.e.

print sys.modules["traceback"]
import traceback
print "Hello World"
sys.stdout.flush()

just renders:  in the
console, and no "Hello World"

I'm running out of ideas what to try next, so suggestions/ideas appreciated!

/Simon

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


Re: How do I parse this ? regexp ? [slighly OT]

2005-04-28 Thread Simon Dahlbacka

> >>> safetyChecker = re.compile(r"^[-\[\]0-9,. ]*$")

..doesn't the dot (.) in your character class mean that you are allowing
EVERYTHING (except newline?)

(you would probably want \. instead)

/Simon


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


Re: regex over files

2005-04-28 Thread Robin Becker
Skip Montanaro wrote:
.

Let me return to your original problem though, doing regex operations on
files.  I modified your two scripts slightly:
.
Skip
I'm sure my results are dependent on something other than the coding style
I suspect file/disk cache and paging operates here. Note that we now agree on 
total match length and split count. However, when the windows VM goes into 
paging mode the mmap thing falls off the world as I would expect for a thrashing 
 system.

eg small memory (relatively)
C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=3.55
C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=8.25
C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=9.77
C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=5.09
C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=6.17
C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=4.64
and large memory
C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_200mb.dat
fn=xxx_200mb.dat n=3797470 l=181012689 time=20.16
C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_200mb.dat
fn=xxx_200mb.dat n=3797470 l=181012689 time=136.42
At the end of this run I had to wait quite a long time for other things to 
become responsive (ie things were entirely paged out).

Here I've implemented slightly modified versions of the scanners that you put 
forward.

eg
#sscan0.py thanks to Bengt
import sys, time, re
fn = sys.argv[1]
rxo = re.compile('X')
def frxsplit(path, rxo, chunksize=4096):
buffer = ''
for chunk in iter((lambda f=open(path,'rb'): f.read(chunksize)),''):
buffer += chunk
pieces = rxo.split(buffer)
for piece in pieces[:-1]: yield piece
buffer = pieces[-1]
yield buffer
l=n=0
t0 = time.time()
for mat in frxsplit(fn,rxo):
n += 1
l += len(mat)
t1 = time.time()
print "fn=%s n=%d l=%d time=%.2f" % (fn, n, l, (t1-t0))
#sscan1.py thanks to Skip
import sys, time, mmap, os, re
fn = sys.argv[1]
fh=os.open(fn,os.O_BINARY|os.O_RDONLY)
s=mmap.mmap(fh,0,access=mmap.ACCESS_READ)
l=n=0
t0 = time.time()
for mat in re.split("X", s):
n += 1
l += len(mat)
t1 = time.time()
print "fn=%s n=%d l=%d time=%.2f" % (fn, n, l, (t1-t0))
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: regex over files

2005-04-28 Thread Robin Becker
Jeremy Bowers wrote:
.
As you try to understand mmap, make sure your mental model can take into
account the fact that it is easy and quite common to mmap a file several
times larger than your physical memory, and it does not even *try* to read
the whole thing in at any given time. You may benefit from
reviewing/studying the difference between virtual memory and physical
memory.
I've been using vm systems for 30 years and I suspect my mental model is a bit 
decrepit. However, as convincingly demonstrated by testing my mental model seems 
able to predict low memory problems. When systems run out of memory they tend to 
perform poorly. I'm not sure the horrible degradation I see with large files is 
necessary, but I know it occurs on at least one common vm implementation.
--
Robin Becker

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


Re: regex over files

2005-04-28 Thread Robin Becker
Robin Becker wrote:
Skip Montanaro wrote:
..
I'm not sure why the mmap() solution is so much slower for you.  
Perhaps on
some systems files opened for reading are mmap'd under the covers.  
I'm sure
it's highly platform-dependent.  (My results on MacOSX - see below - are
somewhat better.)

. as a data point with sscan0/1.py (slight mods of your code) I get this 
with a 200mb file on freeBSD 4.9

/usr/RL_HOME/users/robin/sstest:
$ python sscan0.py xxx_200mb.dat
fn=xxx_200mb.dat n=3797470 l=181012689 time=7.37
/usr/RL_HOME/users/robin/sstest:
$ python sscan1.py xxx_200mb.dat
fn=xxx_200mb.dat n=3797470 l=181012689 time=129.65
/usr/RL_HOME/users/robin/sstest:
ie the freeBSD vm seems to thrash just as nastily as xp :(
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: goto statement

2005-04-28 Thread Mikhail 'Xen' Kashkin
If you use ssh, then you must to learn 'scp'. Or buy books about
programming ;)

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


Re: Ron Grossi: God is not a man

2005-04-28 Thread Lawrence Lucier
Donald L McDaniel wrote:
3) Since Lucifer is an angel, he does not engage in sexual relations. 
(Christ tells us that angels don't engage in sexual relations by His Own 
Words.)
Maybe you should take time to stop posting this inane drivel and do some 
studying pertaining to the "Nephilim".or have you just conveniently 
decided to ignore the writtings of Genesis?
--
http://mail.python.org/mailman/listinfo/python-list


Trying to write CGI script with python...

2005-04-28 Thread ckb2102

Hi there,

I am new to this so I apologize in advance if I am not following the 
right etiquette or something...

I am working on a project for school.  My partner has written a 
short program in Python which takes 2 arguments - the name of a .mov 
file and a number which represents the number of seconds into that 
movie.  The program then passes this info to MPlayer and produces as 
output a .jpg image which is basically the frame of the movie at the 
stated time.

It's my job to make this a web-based function, and when I try to 
convert my partner's code to a working CGI script, it fails.  
Basically, MPlayer is not being accessed properly.

Does anyone have any insight or has anyone tried to do something 
similar?  I am fairly new to all this...

Thank you!





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


Re: kdialog and unicode

2005-04-28 Thread John Ridley
Matt wrote:
> Interesting - this displays correctly when I run the above code from
a
> python shell.  However, when I run it as a superkaramba theme (which
is
> a wrapper interface to some kde functions, but allegedly passes
> straight python functions direct to the python interpreter), it shows
> up as letters, with &nnn (where nnn is a number) instead of the \xc4
> etc.  I need to do some more investigating of this with the
> superkaramba developers, and my own machine to see where the problem
> lies - clearly it's not in the code I'm using - there's either
> something wrong on my machine, or wrong with the way superkaramba
> passes this code to the python interpreter.

If xml character escapes are showing up in the output, it suggests the
input is being treated as plain-text, rather than as rich-text (i.e.
markup). In order for kdialog to guess that the input is markup, it
needs to find some sort of tag before the first line-break. That is why
I used P tags to enclose the polish text in my example - you didn't
leave these off when you tried it out with superkaramba, did you? What
exactly *is* the code you are running?

BTW, if you want more details on kdialog's markup handling, try this
reference from the qt docs:

http://doc.trolltech.com/qstylesheet.html

HTH

John Ridley

Send instant messages to your online friends http://uk.messenger.yahoo.com 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: regex over files

2005-04-28 Thread Robin Becker
Jeremy Bowers wrote:

>
> As you try to understand mmap, make sure your mental model can take into
> account the fact that it is easy and quite common to mmap a file several
> times larger than your physical memory, and it does not even *try* to read
> the whole thing in at any given time. You may benefit from
> reviewing/studying the difference between virtual memory and physical
> memory.
I've been using vm systems for 30 years and I suspect my mental model is a bit
decrepit. However, as convincingly demonstrated by testing my mental model seems
able to predict low memory problems. When systems run out of memory they tend to
perform poorly. I'm not sure the horrible degradation I see with large files is
necessary, but I know it occurs on at least two common vm implementations.
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: OOP

2005-04-28 Thread Jeremy Bowers
On Thu, 28 Apr 2005 10:34:44 -0700, demon_slayer2839 wrote:

> Hey yall,
> I'm new to Python and I love it. Now I can get most of the topics
> covered with the Python tutorials I've read but the one thats just
> stumping me is Object Orientation. I can't get the grasp of it. Does
> anyone know of a good resource that could possibly put things in focus
> for me? Thanks.

The biggest problem with understanding Object Orientation is that it is
only a net gain, even when using something as nice as Python, when you
pass the trivial. 

If you're looking at provided examples of OO that fits on a screen or two
and going "And so what...?", I'd actually consider that a sign of
comprehension, not a bad thing. (No sarcasm.)

It only goes past "And so what...?" when you get into larger programs.

One example that exists in the Python library and has a lot of code
available on line is the urllib2 library. (Unfortunately, that is
something of a complicated bit of code and you're almost better off just
listening to what I'm going to say here than actually looking at the
code :-) )It uses an OO pattern called the "template" pattern, where you
bundle as much code as possible that can be used generally into a
"superclass", and inherit and specialize when you need to do something
specific.

When you want to send an HTTP request, and do something useful with the
results, you create your own request subclass. As a result of using it,
the superclass does all of it's stuff, in this case making the connection
and basic parsing of the results, so you don't have to. The superclass
then calls into the sub-class's overridden methods, based on what happened
with the request. For instance, if you are writing an RSS retriever and
the retrieval results in a 302 code, "Moved Permanently", the superclass
will call self.error_302(), and the RSS reader can then update its
personal database of RSS file locations.

OO consists structurally of the code+data combination; OO consists
*practically* of each of these little techniques, like I gave in the
previous paragraph, adding together and making things easy. None of them
are *impossible* with non-OO code, merely harder to write, but the
cumulative easing effect is quite significant.

You're probably closer to understanding the theory than you think; now you
just need to use it for a while, with an active, open mind probing for
ways to make your programming life easier. Only that will bring deeper
understanding, or maybe reading other's code if you're dedicated. You
might also look online for some of the "Design Patterns", which aren't
worth worshiping but provide a concise description of some of the other
things that OO makes easier than the alternatives.

(You may also be interested in this essay I wrote:

http://www.jerf.org/writings/bowersLaw.html

One of the problems OO faced in general, especially the late 80s and most
of the 90s, was prematurely jumping to dogma before there was adequate
community experience to formulate a *good* dogma; even today there are a
lot of "OO experts" who would take extensive exception to both this post
and that essay, even though I'm pretty sure that facts and experience are
on my side :-) . The old dogma lives on, even as many communities like
Python, Ruby, and the Testing Methodology folk are formulating better
ones. The reality of OO is that it is a rich and highly varied *family* of
techniques, which may also not be helping if you try to learn from
multiple sources; that essay tries to explore the common thread behind all
of those techniques, and explain why it is the common thread.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interactive web graphics

2005-04-28 Thread Eckhoff, Michael A
Thanks Larry and Diez. I figured that doing
'GUIs over the web' would probably not work.

Where I work, we have a bunch of numerical
weather-prediction-type models that take
several hours to run. By having a cron job
copy over the output, I think I can still
implement a type of progress bar using an
update button, and show some png images as
well. Animations would be nice, but I have
not reached that point yet.

In case anyone is interested...
The initial plan was to use a GTK+ GUI
to monitor these models and the GIMP
library to create an indexed image from
the pressure field, overlayed with vectors
depicting winds (or currents, for the ocean).
Think I'll take another look at pygtk.

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


Re: regex over files

2005-04-28 Thread Robin Becker
Skip Montanaro wrote:
...
I'm not sure why the mmap() solution is so much slower for you.  Perhaps on
some systems files opened for reading are mmap'd under the covers.  I'm sure
it's highly platform-dependent.  (My results on MacOSX - see below - are
somewhat better.)
Let me return to your original problem though, doing regex operations on
files.  I modified your two scripts slightly:
I'm sure my results are dependent on something other than the coding 
style I suspect file/disk cache and paging operates here. Note that we 
now agree on total match length and split count. However, when the 
windows VM goes into paging mode the mmap thing falls off the world as I 
would expect for a thrashing system.

eg small memory (relatively)
C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=3.55
C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=8.25
C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=9.77
C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=5.09
C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=6.17
C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_100mb.dat
fn=xxx_100mb.dat n=1898737 l=90506416 time=4.64
and large memory
C:\code\reportlab\demos\gadflypaper>\tmp\sscan0.py xxx_200mb.dat
fn=xxx_200mb.dat n=3797470 l=181012689 time=20.16
C:\code\reportlab\demos\gadflypaper>\tmp\sscan1.py xxx_200mb.dat
fn=xxx_200mb.dat n=3797470 l=181012689 time=136.42
At the end of this run I had to wait quite a long time for other things 
to become responsive (ie things were entirely paged out).

as another data point with sscan0/1.py (slight mods of your code) I get 
this with a 200mb file on freeBSD 4.9

/usr/RL_HOME/users/robin/sstest:
$ python sscan0.py xxx_200mb.dat
fn=xxx_200mb.dat n=3797470 l=181012689 time=7.37
/usr/RL_HOME/users/robin/sstest:
$ python sscan1.py xxx_200mb.dat
fn=xxx_200mb.dat n=3797470 l=181012689 time=129.65
/usr/RL_HOME/users/robin/sstest:
ie the freeBSD vm seems to thrash just as nastily as xp :(

Here I've implemented slightly modified versions of the scanners that 
you put forward.

eg
#sscan0.py thanks to Bengt
import sys, time, re
fn = sys.argv[1]
rxo = re.compile('X')
def frxsplit(path, rxo, chunksize=4096):
buffer = ''
for chunk in iter((lambda f=open(path,'rb'): f.read(chunksize)),''):
buffer += chunk
pieces = rxo.split(buffer)
for piece in pieces[:-1]: yield piece
buffer = pieces[-1]
yield buffer
l=n=0
t0 = time.time()
for mat in frxsplit(fn,rxo):
n += 1
l += len(mat)
t1 = time.time()
print "fn=%s n=%d l=%d time=%.2f" % (fn, n, l, (t1-t0))
#sscan1.py thanks to Skip
import sys, time, mmap, os, re
fn = sys.argv[1]
fh=os.open(fn,os.O_BINARY|os.O_RDONLY)
s=mmap.mmap(fh,0,access=mmap.ACCESS_READ)
l=n=0
t0 = time.time()
for mat in re.split("X", s):
n += 1
l += len(mat)
t1 = time.time()
print "fn=%s n=%d l=%d time=%.2f" % (fn, n, l, (t1
--
Robin Becker
--
http://mail.python.org/mailman/listinfo/python-list


Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Steven Bethard
Lonnie Princehouse wrote:
So far, we've been using the "key" parameter of list.sort.  If you want
sort criteria more complicated than a single attribute, you can sort
based on a custom comparison function.
Actually, the key= parameter can do anything the cmp= parameter can:
class Key(object):
def __init__(self, item)
self.item = item
def __cmp__(self, other):
# put your usual cmp code here
cmp(self.item, other)
lst.sort(key=Key)
Of course this is a pretty silly way to write a cmp function.  But the 
point is that you shouldn't think of the key= parameter as only useful 
for simple comparisons. See
http://mail.python.org/pipermail/python-list/2005-April/277448.html
for a recent example of a pretty complex key function.

I would guess that 80-90% of all uses of sort that need a custom 
comparison function can be met easily by using the key= parameter and 
will be more efficient than using the cmp= parameter.

The above "Key" example has the same inefficiency problems that the cmp= 
parameter normally does, but in most cases, you won't need to define a 
custom __cmp__ function, and you can rely on __cmp__ functions 
implemented in C, like those of strs and tuples (as I do below).

So another way to do a sort-by-author for your books would be:
  def compare_authors(book1, book2):
  return cmp(book1.author, book2.author)
   books.sort(compare_authors)
This is definitely not a case where you want to use a comparison 
function.  It will be much more efficient to write:

def author_key(book):
return book.author
books.sort(key=author_key)
A more complicated comparison function might nest two others:
  def compare_dates(book1, book2):
  # Assuming that your dates are either numerical or are strings
for which
  # alphabetical sorting is identical to chronological...
  return cmp(book1.date, book2.date)
  def compare_author_and_date(book1, book2):
   different_authors = compare_authors(book1, book2)
   if different_authors:  # different authors
   return different_authors
   else:  # same author.  sort by date.
   return compare_dates(book1, book2)
  
  books.sort(compare_author_and_date)
Likewise, the above is basically just an inefficient way of writing:
def date_key(book):
return book.data
def author_and_date_key(book):
return (author_key(book), date_key(book))
books.sort(key=author_and_date_key)
Note that the thing I take advantage of here is that tuples are 
comparable, and compare as you'd expect them to (in lexicographic order).

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


Re: regex over files

2005-04-28 Thread Skip Montanaro

Bengt> To be fairer, I think you'd want to hoist the re compilation out
Bengt> of the loop.

The re module compiles and caches regular expressions, so I doubt it would
affect the runtime of either version.

Bengt> But also to be fairer, maybe include the overhead of splitting
Bengt> correctly, at least for the simple case regex in my example -- or
Bengt> is a you-goofed post for me in the usenet forwarding queues
Bengt> somewhere still? ;-)

I was just too lazy to incorporate (something like) your change.  You will
note that I was also lazy enough to simply steal your X file. 

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


Re: Can .py be complied?

2005-04-28 Thread jfj
[EMAIL PROTECTED] wrote:
IMO the fact that so many people ask
"How can I create executables in Python on Windows"
indicates that standard "batteries included" Windows Python
distribution is missing a vital battery. There are tools such as
py2exe, but this functionality should be built-in, so that a newbie to
Python can just download it, type
python -o foo.exe foo.py
at the command line, and get an executable, without any further effort.

Since this is about windows and windows users just want everything in
".exe" form (no matter if it also contains spyware), and they don't care
about the size of it (they just want the damn exe) and since there is
zero chance that python will be included in the next windows
distribution but these people still want the exe (they do, really),
I think I have a convenient solution to give it to them.
/* small program in C in self extracting archive
 */
if (have_application ("Python")) {
  have_python:
  system ("python.exe my_application.py")
} else {
  printf ("This software requires python. Wait until all the
necessary components are being installed\n");
  download_python_from_python_org();
  system ("install_python.exe");
  goto have_python;
}
Seriously, people who want executables wouldn't notice the difference.
jfj
--
http://mail.python.org/mailman/listinfo/python-list


Re: Working with method-wrapper objects

2005-04-28 Thread Dr. Peer Griebel
Peer Dr. Griebel wrote:
I think I was a little bit unspecific in my last mail.
I would like to see some description about method-wrapper and
wrapper_descriptor objects.  I dont' understand the following behaviour:

type([].__str__)

type(object.__str__)

type(object().__str__)

import inspect
inspect.isroutine([].__str__)
False
inspect.isroutine(object.__str__)
True
inspect.isroutine(object().__str__)
False
Why has [].__str__ a different type than object.__str__?
Why is object.__str__ a routine while object().__str__ not?
And one again my question: Can I extract some more information about a
methed-wrapper object. E.g. can I somehow determine the arg spec?
Thanks
  Peer
Isn't there anybody who has something to say about the issue?
I think it's not only a problem with inspect. It is aproblem about old 
style classes vs. new style classes. It seems that the support for new 
style classes is not complete (yet).

Some more investigation shows that also the module "types" is not 
universally usable. E.g. InstanceType is only usabel for instances of 
old classes. How do I test for instances of new classes?

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


Re: Is this a bug?

2005-04-28 Thread Aahz
In article <[EMAIL PROTECTED]>,
Fredrik Lundh <[EMAIL PROTECTED]> wrote:
>
>mapping += to extend is a design mistake (I guess someone got a
>little carried away).

There were two use cases that drove augmented assignment (I know you know
this -- but other people probably do not):

reallylongvariablename = reallylongvariablename + 1
hugearray = hugearray + tinyarray

The latter was particularly coming from the Numeric types.  The docs
probably should clarify that augmented assignment is *NOT* necessarily
the same as ``foo = foo + bar`` when ``foo`` is a mutable type.  You can
argue that you disagree with mapping ``+=`` to ``extend()``, but I don't
think it's fair for you to flatly claim that it's a design mistake.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"It's 106 miles to Chicago.  We have a full tank of gas, a half-pack of
cigarettes, it's dark, and we're wearing sunglasses."  "Hit it."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: interactive web graphics

2005-04-28 Thread Lee Harr
On 2005-04-27, Eckhoff, Michael A <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I failed to locate a list for pygtk, so I thought I'd
> ask my question here. Is it possible to write CGI
> scripts that bring up a GUI (as in GTK+, QT, Tk, ...)
> or an openGL display that is windowed inside a web
> browser?
>

How about the blender web plugin?
http://www.blender.org/modules/bc2002/plugin.html

I am not sure the plugin has been updated to match
recent blender releases, but recent blenders offer
python scripting. Could be interesting anyhow.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Paul Miller
Michael Hoffman wrote:
Paul Miller wrote:
While on the subject, is there an equivalent for "methodcaller"?
ie. if I want to bind a function which calls a specific method of an 
object with a specific parameter?

def funccaller(func, *args, **kwargs):
def _return_func():
return func(*args, **kwargs)
return _return_func
...
And this time I actually tested it, and it works! ;)
Wow! Amazing. Yer right, it works!
Man, I LOVE this language.
--
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Dave Benjamin
Cameron Laird wrote:
In article <[EMAIL PROTECTED]>,
Peter Hansen  <[EMAIL PROTECTED]> wrote:
This meets your requirements as stated:
def temp():
  foo.var = 1
bind('a', temp)
def temp():
  foo.var = 2
bind('b', temp)
del temp
Ewww!  *When* is lambda going bye-bye?  I apparently
haven't been paying close enough attention.  Among other
considerations, I still instruct people to use lambda for
plenty of specific cases.
Well, IMNSHO, it's an empty threat that's been looming on the horizon 
for several years now. ;) Most recently, Guido mentioned his desire to 
remove the keyword in his post on Artima, which resulted in a huge debate:

http://www.artima.com/weblogs/viewpost.jsp?thread=98196
Note that in the OP's question, as with Peter's example above, you still 
can't do it with lambda alone, since you can't mix expressions with 
assignment. Nonetheless, lambda is nice for delaying binding, and 
combined with a helper function that sets attributes, it can produce the 
most concise solution:

bind('a', lambda: setattr(foo, 'var', 1))
bind('b', lambda: setattr(foo, 'var', 2))
The usual response is that you probably want to make a class anyway, and 
use bound methods for this type of stuff. But I find that in GUI/async 
programming, often you need a little dab of glue to connect events 
between objects, and lambda provides a nice way to avoid 
over-abstracting the problem.

We'll see how this all pans out in the next few years. I'm not too fond 
of removing features from a language for purely aesthetic reasons, but 
lambda's really stuck in a syntactic quandry due to the 
statement/expression dichotomy, so I can understand to some extent 
Guido's desire to remove it.

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


Re: dynamically generating temporary files through python/cgi

2005-04-28 Thread Tiziano Bettio
poisondart wrote:
Is there a way to dynamically generate temporary files (such as an
html, xml or text file) in Python?
I'm not sure if I'm explaining myself clearly as I've no clue how to
describe this mechanism. I've seen it on certain websites that will
generate a file under certain parameters (through forms) that will
dissapear (i.e. delete itself) after a specified amount of time. These
files usually have some phony string for their filenames...like it's
been md5 hashed or something.
Is there a group of library functions that allow this? I imagine that
if i manually go and allocate a bunch of timers to monitor files, it
would be really expensive in load. Or perhaps is this a client-side
mechanism?
Thanks,
- poisondart
 

hi there
first of you could use the tempfile
import tempfile
tempfile.mktemp('.thefileendingudlike')
i never really studied the cgi capability of python but for example in 
php there is the posibility to serve a request with a mime formated 
response such as html, gif, pdf, and so on. so if u want to generate 
content dynamically u wouldn't need to store those files but generate 
and send em on request without having to destroy them later on..

hope this is helpful
cheers
tc
--
http://mail.python.org/mailman/listinfo/python-list


Re: why "import wx" doesn't work?

2005-04-28 Thread Peter Hansen
monkey wrote:
I just learn to make a blank windows frame with python and wxpython. I found
the statment "import wx" cannot work as the original "from wxPython.wx
import *". I see in the readme file of wxpython that if I install it as the
default one, I can use "import wx" instead of the long one. What is wrong?
The code pasted below:
import wx   # the default is "from wxPython.wx import *", I change it and it
just can't work.
class MyApp(wxApp):
...
Assuming you've installed a version of wxPython that is recent enough 
that "import wx" works (it's really unclear from what you've written 
above), then the problem you are facing is not using the namespace that 
you've now imported.  Do this instead:

class MyApp(wx.App):
def OnInit(self):
frame = wx.Frame(NULL, -1, "
Note that "wx." before everything from wxPython...
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Dave Benjamin
Dave Benjamin wrote:
You could use a combination of bound methods and the "curry" function 
defined in the Python Cookbook:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
The examples in the discussion do just that.
Also, in the CVS version of Python, there's a new module called 
"functional" with a function called "partial" that does the same thing 
as far as I can tell. So, in the future, this function will probably be 
available in the standard library.

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


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Michael Hoffman
Paul Miller wrote:
While on the subject, is there an equivalent for "methodcaller"?
ie. if I want to bind a function which calls a specific method of an 
object with a specific parameter?

def funccaller(func, *args, **kwargs):
def _return_func():
return func(*args, **kwargs)
return _return_func
class Test1(object):
def __init__(self, x):
self.x = x
def method(self, a, b, c):
return self.x + a + b + c
t1 = Test1(42)
funccaller_result = funccaller(t1.method, 3, 4, c=5)
funccaller_result()
And this time I actually tested it, and it works! ;)
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: Internet Explorer, COM+, Javascript and Python

2005-04-28 Thread J Correia

"Roger Upole" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Something like this should be close:
>
> import win32com.client, pythoncom
> ie=win32com.client.Dispatch('internetexplorer.application')
> ie.Visible=1
> ie.Navigate('somepagewithjavascript.html')
> id=ie.Document.Script._oleobj_.GetIDsOfNames('somejsfunction')
> res=ie.Document.Script._oleobj_.Invoke(id, 0, pythoncom.DISPATCH_METHOD,
> True,  )
>
>hth
>Roger

Yes, that definitely works.  Only one minor correction:  it seems that to
pass multiple parameters you need to pass them sequentially seperated by
commas instead of in a tuple, i.e.
res=ie.Document.Script._oleobj_.Invoke(id, 0, pythoncom.DISPATCH_METHOD,
True, param1, param2, param3, . )

Useful test sitefor above code:
http://www.cpplab.com/Articles/JSCalls/TestPage/JSCallTestPage.htm

HTH,

>
>
> "Ishpeck" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> >I need to make IE execute javascript in a web page with COM+ and
> > Python.
> >
> > Similarly to the way they do it in this article. . .
> >
> > http://www.codeproject.com/com/jscalls.asp
> >
>
>
>
> == Posted via Newsfeeds.Com - Unlimited-Uncensored-Secure Usenet
News==
> http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+
Newsgroups
> = East and West-Coast Server Farms - Total Privacy via Encryption
=



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


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Dave Benjamin
Paul Miller wrote:
Michael Hoffman wrote:
Dave Benjamin wrote:
I think you meant to write something like this:
def attrsetter(obj, name, value):
def _return_func():
return setattr(obj, name, value)
return _return_func

Sure did. Sorry.

You guys have been very helpful!
While on the subject, is there an equivalent for "methodcaller"?
ie. if I want to bind a function which calls a specific method of an 
object with a specific parameter?
You could use a combination of bound methods and the "curry" function 
defined in the Python Cookbook:

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52549
The examples in the discussion do just that.
Dave
--
http://mail.python.org/mailman/listinfo/python-list


Can'r run BLT twice?

2005-04-28 Thread Todd Krein
I'm running PythonWin on XP. When I run my plotter program the first
time, it works fine. The second time I run it, I get the following
error. If I exit PythonWin, and restart, I can again run it once. Any
ideas?

Error: 1
TclError Exception in Tk callback
  Function: > (type: )
  Args: ()
Traceback (innermost last):
  File "C:\Python24\lib\Pmw\Pmw_1_2\lib\PmwBase.py", line 1747, in
__call__
None
  File
"C:\NBU\perforce\hardware\test\home_survey\data\home_007\raw_data\KitchenToDen\AMPLITUDE\PathEval.py",
line 89, in doOpenTrace
self.doPlotTrace()  # go plot the thing
  File
"C:\NBU\perforce\hardware\test\home_survey\data\home_007\raw_data\KitchenToDen\AMPLITUDE\PathEval.py",
line 117, in doPlotTrace
self.graph = Pmw.Blt.Graph(tkRoot)   # make a new
graph area
  File "C:\Python24\lib\Pmw\Pmw_1_2\lib\PmwBlt.py", line 260, in
__init__
None
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1861, in __init__
self.tk.call(
TclError: invalid command name "::blt::graph"

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


Can't run BLT program more than once?

2005-04-28 Thread Todd Krein
I'm running activestate Python 2.4 for windows, and the latest BLT,
under XP. I'm using pythonWin as my environment.

When I run my plotting program the first time, it works just fine. If I
exit out (normally), and then run it again from PythonWin, I get the
following error. It's as if something isn't getting properly
re-initialized. If I quit out of PythonWin, and relaunch it, I can run
the program again, once. Any ideas?



Error: 1
TclError Exception in Tk callback
  Function: > (type: )
  Args: ()
Traceback (innermost last):
  File "C:\Python24\lib\Pmw\Pmw_1_2\lib\PmwBase.py", line 1747, in
__call__
None
  File
"C:\NBU\perforce\hardware\test\home_survey\data\home_007\raw_data\KitchenToDen\AMPLITUDE\PathEval.py",
line 89, in doOpenTrace
self.doPlotTrace()  # go plot the thing
  File
"C:\NBU\perforce\hardware\test\home_survey\data\home_007\raw_data\KitchenToDen\AMPLITUDE\PathEval.py",
line 117, in doPlotTrace
self.graph = Pmw.Blt.Graph(tkRoot)   # make a new
graph area
  File "C:\Python24\lib\Pmw\Pmw_1_2\lib\PmwBlt.py", line 260, in
__init__
None
  File "C:\Python24\lib\lib-tk\Tkinter.py", line 1861, in __init__
self.tk.call(
TclError: invalid command name "::blt::graph"

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


embedding an interactive console

2005-04-28 Thread Paul Miller
I did this YEARS ago with Python 1.5, and I recall it being slightly 
painful. I have an embedded Python interpreter and I want to provide an 
interactive console (implemented in my GUI application with a Qt 
TextEdit widget). I can handle the GUI part of it, but I'm wondering 
what the latest Python method of implementing this is.

I note the documentation for InteractiveConsole, which is implemented in 
Python. Is there any example code for using this from within C/C++ code 
to emulate the command-line interpreter inside a GUI app?

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


Re: Setting win32 console title from Python

2005-04-28 Thread runes
Hi Duncan, sorry, I was unprecise.  I'm thinking of a script, called
t.py  that can be used in the console  like an ordinary command. Som if
I change directory from S:\scripts to d:\projects and execute the
script  the title changes to "projects" etc.

I have that functionality today with a combination of a python script
and a batch file. I just wondered if I could use python all the way.
Apparently I cannot.

Here are the scripts:


-- DirInPath:\t.bat 
@echo off
:: reads bare directory name from file
:: created by external Python script
set DIR_FILE_NAME=DOS_IS_TERRIBLE.tmp
PyBareDir.py %DIR_FILE_NAME%

for /F "eol=;" %%t in (%DIR_FILE_NAME%) do (
title %%t
)

del /Q /F DOS_IS_TERRIBLE.tmp



-- DirInPath:\PyBareDir.py 
# extracts bare directory name and  writes
# it to file with name given as argument.

from os import getcwd
from os.path import basename
import sys

try:
saveAsName = sys.argv[1]
lastDir = basename(getcwd())
XWwz(saveAsName, 'w+').write(lastDir + '\n;')
except:
print "PyBareDir failed:", sys.exc_info()[1]

---

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


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Paul Miller
Michael Hoffman wrote:
Dave Benjamin wrote:
I think you meant to write something like this:
def attrsetter(obj, name, value):
def _return_func():
return setattr(obj, name, value)
return _return_func

Sure did. Sorry.
You guys have been very helpful!
While on the subject, is there an equivalent for "methodcaller"?
ie. if I want to bind a function which calls a specific method of an 
object with a specific parameter?

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


Re: Getting the sender widget's name in function (Tkinter)

2005-04-28 Thread tiissa
Cameron Laird wrote:
In article <[EMAIL PROTECTED]>,
tiissa  <[EMAIL PROTECTED]> wrote:
So far, the OP is proposed the choice to either use the event/bind 
mecanism or use different callbacks for his different buttons (either 
with the method I proposed or not).
Is there general understanding that "use different
callbacks ..." can be implemented as "parametrize the same callback
with a widget-specific value"?
Tough questions thou ask! Again I can't answer about general 
understanding. ;)

However, having myself proposed such a solution in this very thread (and 
hinted about it in the above sentence), I do hope most people (at least 
those interested in this issue) will be aware of this kind of trick 
(without any restriction on the actual implementation). :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
Peter Hansen  <[EMAIL PROTECTED]> wrote:
>Paul Miller wrote:
>> For example, let's say I have a function which binds a key to a function 
>> call. I want to do something "simple" in this function call, and I have 
>> a lot of bindings, so I don't want to have a ton of tiny little 
>> functions scattered around:
>> 
>> def setVarTo1():
>> foo.var = 1
>> def setVarTo2():
>> foo.var = 2
>> 
>> bind('a', setVarTo1)
>> bind('b', setVarTo2)
>> 
>> Instead, I'd like to do something like this:
>> 
>> bind('a', foo.var = 1)
>> bind('b', foo.var = 2)
>> 
>> What's the recommended way to do something like this?
>
>This meets your requirements as stated:
>
>def temp():
>foo.var = 1
>
>bind('a', temp)
>
>def temp():
>foo.var = 2
>
>bind('b', temp)
>
>del temp
>
>
>-Peter

Ewww!  *When* is lambda going bye-bye?  I apparently
haven't been paying close enough attention.  Among other
considerations, I still instruct people to use lambda for
plenty of specific cases.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting the sender widget's name in function (Tkinter)

2005-04-28 Thread Cameron Laird
In article <[EMAIL PROTECTED]>,
tiissa  <[EMAIL PROTECTED]> wrote:
.
.
.
>So far, the OP is proposed the choice to either use the event/bind 
>mecanism or use different callbacks for his different buttons (either 
>with the method I proposed or not).

Thanks, Tissa.  Is there general understanding that "use different
callbacks ..." can be implemented as "parametrize the same callback
with a widget-specific value"?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Lonnie Princehouse
> I'd be just such a newbie; I don't understand why it would matter if
I
> left the book instance referencing itself

It's just kind of sloppy and unnecessary to have self.self

> firstly,  I am trying hard to figure out how to create a new file
with
> the list rather than print to standard out.  I haev done this:

I think you want 'a' instead of 'w+' as the file's mode.  You can also
open and close the file outside of the loop; it would be more
efficient.

> Secondly,  I am wondering how I can get a search algorithm that will
> search by multiple fields here,  so that I can (as one example) sort
> the books out by author and then date,  to present a list of the book
> grouped by authors and having each group presented in a chronological
> order,   or by author and title, grouping all the books up into
authors
> presenting each group alphabetically by title.  Or by publisher and
> date,  or by publisher and code

So far, we've been using the "key" parameter of list.sort.  If you want
sort criteria more complicated than a single attribute, you can sort
based on a custom comparison function.Comparison functions compare
two objects (let's call them A and B), and return one of three possible
values:

A is greater than B  => 1
A is less than B => -1
A and B are equal => 0

The built-in function "cmp" can be used to compare objects; behavior is
defined for built-in types:

cmp(0, 1) => -1
cmp("Zylophone", "Abstract") => 1   # alphabetical ordering for strings
cmp( [1,2,3], [1,2,3] ) => 0  # compare sequence elements from left to
right

So another way to do a sort-by-author for your books would be:

  def compare_authors(book1, book2):
  return cmp(book1.author, book2.author)

   books.sort(compare_authors)

A more complicated comparison function might nest two others:

  def compare_dates(book1, book2):
  # Assuming that your dates are either numerical or are strings
for which
  # alphabetical sorting is identical to chronological...
  return cmp(book1.date, book2.date)

  def compare_author_and_date(book1, book2):
   different_authors = compare_authors(book1, book2)
   if different_authors:  # different authors
   return different_authors
   else:  # same author.  sort by date.
   return compare_dates(book1, book2)
  
  books.sort(compare_author_and_date)

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


Re: anonymous functions/expressions without lambda?

2005-04-28 Thread Michael Hoffman
Dave Benjamin wrote:
I think you meant to write something like this:
def attrsetter(obj, name, value):
def _return_func():
return setattr(obj, name, value)
return _return_func
Sure did. Sorry.
--
Michael Hoffman
--
http://mail.python.org/mailman/listinfo/python-list


Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Steven Bethard
googleboy wrote:
firstly,  I am trying hard to figure out how to create a new file with
the list rather than print to standard out.  I haev done this:
for book in books:
print book # just to be sure it works as I expect
sort1 = open(r'D:\path to\sort1.csv', 'w+')
print >> sort1, book
sort1.close()
and this creates the file as I expect, however it creates it populated
with only the information of the final book in the sorted list.
You're reopening the file on each iteration of the loop.  I think you 
want to open it only once, before the loop, e.g.

sort1_file = open(r'D:\path to\sort1.csv', 'w+')
for book in books:
sort1_file.write('%s\n' % book) # same as "print >> sort1, book"
sort1_file.close()
Note that the opening and closing of the file is outside the loop.
Secondly,  I am wondering how I can get a search algorithm that will
search by multiple fields here,  so that I can (as one example) sort
the books out by author and then date,  to present a list of the book
grouped by authors and having each group presented in a chronological
order,   or by author and title, grouping all the books up into authors
presenting each group alphabetically by title.  Or by publisher and
date,  or by publisher and code
I have tried things like
books.sort(key = operator.attrgetter("author"), key =
operator.attrgetter("title") and
books.sort(key = operator.attrgetter("author", "title")
but they both give errors.
The problem is that operator.attrgetter only accepts a single attribute. 
 Basically, attrgetter looks something like:

def attrgetter(attr_name):
def func(obj):
return getattr(obj, attr_name)
return func
So attrgetter can't really solve your problem.  However, you can create 
a similar function that should do the job.  Something like (untested):

def get_key(*attr_names):
def key(book):
return [getattr(book, name) for name in attr_names)]
return key
Then you should be able to do something like:
books.sort(key=get_key("author", "title"))
The trick is that the inner function, 'key', looks up a sequence of 
attributes on the book object, instead of just a single attribute like 
attrgetter does.

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


Re: Getting the sender widget's name in function (Tkinter)

2005-04-28 Thread infidel
Here's a slight variation of tiissa's solution that gives the callable
a reference to the actual widget instead of just it's name:

from Tkinter import Tk, Button

class say_hello:
def __init__(self, widget):
self.widget = widget
def __call__(self):
print 'Hello,', self.widget['text']

def run():
root = Tk()
b1 = Button(root, text='Button 1')
b1.configure(command=say_hello(b1))
b1.pack()
b2 = Button(root, text='Button 2')
b2.configure(command=say_hello(b2))
b2.pack()
root.mainloop()

run()

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


why "import wx" doesn't work?

2005-04-28 Thread monkey
I just learn to make a blank windows frame with python and wxpython. I found
the statment "import wx" cannot work as the original "from wxPython.wx
import *". I see in the readme file of wxpython that if I install it as the
default one, I can use "import wx" instead of the long one. What is wrong?
The code pasted below:

import wx   # the default is "from wxPython.wx import *", I change it and it
just can't work.

class MyApp(wxApp):
def OnInit(self):
frame = wxFrame(NULL, -1, "Hello from wxPython")
frame.Show(true)
self.SetTopWindow(frame)
return true

app = MyApp(0)
app.MainLoop()


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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread Philippe C. Martin
How about using the csv module instead of splitting ?


[EMAIL PROTECTED] wrote:

> What you want I guess is to read first all lines of the file into a
> string as you did, and then let the split method split it based on
> newlines only - see example below.
> 
> Then you use split again to put all elements of one line into another
> list - split it on commas.
> 
> Now you can define sortfunctions for all columns you want to sort, e.g.
> like below - and use those to compare elements. You get a script like:
> -#!/usr/bin/env python
> -
> -def cmp_index(a, b, ndx):
> -   if a[ndx] < b[ndx]:
> -return -1
> -elif a[ndx] > b[ndx]:
> -   return 1
> -else:
> -return 0
> -
> -def cmp_0(a, b):
> -return cmp_index(a, b, 0)
> -
> -def cmp_1(a, b):
> -return cmp_index(a, b, 1)
> -
> -s = 'Kikker en Eend,Max Veldhuis\nDikkie Dik,Jet Boeke\nRuminations on
> C++,Andrew Koenig & Barbara Moo'
> -s = s.split('\n')
> -l = []
> -for i in s:
> -l.append(i.split(','))
> -
> -l.sort(cmp_0)
> -print l
> -l.sort(cmp_1)
> -print l
> 
> with output like:
> [EMAIL PROTECTED]:~ $ ./test.py
> [['Dikkie Dik', 'Jet Boeke'], ['Kikker en Eend', 'Max Veldhuis'],
> ['Ruminations on C++', 'Andrew Koenig & Barbara Moo']]
> [['Ruminations on C++', 'Andrew Koenig & Barbara Moo'], ['Dikkie Dik',
> 'Jet Boeke'], ['Kikker en Eend', 'Max Veldhuis']]
> [EMAIL PROTECTED]:~ $

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


Re: OOP

2005-04-28 Thread Charles Krug
On 28 Apr 2005 10:34:44 -0700, [EMAIL PROTECTED]
<[EMAIL PROTECTED]> wrote:
> Hey yall,
> I'm new to Python and I love it. Now I can get most of the topics
> covered with the Python tutorials I've read but the one thats just
> stumping me is Object Orientation. I can't get the grasp of it. Does
> anyone know of a good resource that could possibly put things in focus
> for me? Thanks.
> 

"Learning Python" (Lutz/Ascher) has a good discussion of the basics.

Unfortunately, most of the OOP writings I've read fall into two
catagories:  Trivial examples where you say, "But why Bother??" and
examples that you don't understand until you've some OO design under
your belt and can understand what it's all good for.

Objects are, at the end of the day, data and the accompanying methods.
Once you've read the various tutorials take a stab at converting a
problem you know well into objects.

You'll get it wrong at first.  Most everyone does.  Don't sweat it.
Eventually, you'll just "get" it.

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


Re: how can I sort a bunch of lists over multiple fields?

2005-04-28 Thread googleboy
I'd be just such a newbie; I don't understand why it would matter if I
left the book instance referencing itself

However these wonderful responses have gotten me a very long way
towards my goal.  I just have a couple of quick questions.

firstly,  I am trying hard to figure out how to create a new file with
the list rather than print to standard out.  I haev done this:

for book in books:
print book # just to be sure it works as I expect
sort1 = open(r'D:\path to\sort1.csv', 'w+')
print >> sort1, book
sort1.close()

and this creates the file as I expect, however it creates it populated
with only the information of the final book in the sorted list. I am
guessing I need to figure out how to append as part of this loop,  but
the only info I have found so far suggests this should append by
default?

Secondly,  I am wondering how I can get a search algorithm that will
search by multiple fields here,  so that I can (as one example) sort
the books out by author and then date,  to present a list of the book
grouped by authors and having each group presented in a chronological
order,   or by author and title, grouping all the books up into authors
presenting each group alphabetically by title.  Or by publisher and
date,  or by publisher and code

I have tried things like

books.sort(key = operator.attrgetter("author"), key =
operator.attrgetter("title") and
books.sort(key = operator.attrgetter("author", "title")

but they both give errors.

Is this where using cmd functions instead of keys becomes necessary?

Thanks!

googleboy

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


Re: split question

2005-04-28 Thread alexk
Yes, all of you are right. Thank you all for your answers - I'll use a
regex.

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


Re: OOP

2005-04-28 Thread beliavsky
[EMAIL PROTECTED] wrote:
> Hey yall,
> I'm new to Python and I love it. Now I can get most of the topics
> covered with the Python tutorials I've read but the one thats just
> stumping me is Object Orientation. I can't get the grasp of it. Does
> anyone know of a good resource that could possibly put things in
focus
> for me?

Maybe Part VI, "Classes and OOP", of the book "Learning Python", 2nd
edition, by Lutz and Ascher. Both the motivation for OOP and its
implementation in Python are discussed, in about 100 pages.

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


Re: Getting the sender widget's name in function (Tkinter)

2005-04-28 Thread tiissa
Cameron Laird wrote:
In article <[EMAIL PROTECTED]>,
Eric Brunel <[EMAIL PROTECTED]> wrote:
Unfortunately, making a binding to  on Button widgets does not
have the same behavior as setting their 'command' option.
Without unraveling my own confusion about who has said what to whom, does
everyone realize that Tkinter bind()ings inherently can access the widgets
which generate their events?
I don't know about everyone, but I can assume that's definitively the 
case of infidel (who precisely based the solution you quoted on this) 
and Eric Brunel.

But that may not be the topic at hand. Indeed, the main point is that, 
according to Eric, bind() and command don't behave in the exact same way.

And the OP asked about having a reference on the widget using the 
command callback (that, contrary to event-binded callbacks, don't get 
passed any argument).

So far, the OP is proposed the choice to either use the event/bind 
mecanism or use different callbacks for his different buttons (either 
with the method I proposed or not).
--
http://mail.python.org/mailman/listinfo/python-list


OOP

2005-04-28 Thread demon_slayer2839
Hey yall,
I'm new to Python and I love it. Now I can get most of the topics
covered with the Python tutorials I've read but the one thats just
stumping me is Object Orientation. I can't get the grasp of it. Does
anyone know of a good resource that could possibly put things in focus
for me? Thanks.

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


  1   2   >