Re: Sound and music libraries?

2005-02-28 Thread Alia Khouri
http://www.python.org/moin/PythonInMusic

AK

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


Re: Decimal, __radd__, and custom numeric types...

2005-02-28 Thread Kanenas
On 28 Feb 2005 12:11:33 -0800, "Blake T. Garretson"
<[EMAIL PROTECTED]> wrote:

[...]
>From the Python docs (specifically sections 3.3.7 and 3.3.8), I thought
>that the left object should try its own __add__, and if it doesn't know
>what to do, THEN try the right object's __radd__ method.  

To me it reads more like the interpreter is responsible for picking
which method to call.  Specifically, section 3.3.8 of the reference
manual states that y.__rop__() will be called if x.__op__() is not
implemented or returns NotImplemented.  The decision to call
y.__rop__() is made outside the x.__op__() method, implying that
x.__op__() doesn't handle a call to y.__rop__() in this case.  The
other rules dealing with whether x.__op__() or y.__rop__() is called
don't apply to your situation (but they could, keep reading).

>I guess
>Decimal objects don't do this?  Is there a way to change this behavior?
> If Decimal objects prematurely throw a TypeError before trying the
>__rop__, is Decimal broken, or was it designed this way?  I think I'm
>missing something...
>
You could change the behavior of Decimal.__add__ by patching it or you
could use subclassing.  If your classes are subclasses of Decimal,
their __rop__ methods will be called before Decimal.__op__ is tried.
I'm guessing your matrix and rational classes don't use decimal
representation, which makes this an OOP style-breaking kludge.

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


Re: closing tabs in wxpython

2005-02-28 Thread Raghul
I think this need some more explanation.Pls help me to understand this
by giving  an example.

Thanks in advance

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


Re: User Security (Roles & Permissions)

2005-02-28 Thread Andreas Pauley

On Mon, 28 Feb 2005, Andreas Pauley wrote:
Hi all,
I'm starting with a Point of Sale system (QT gui, MySQL db) and I'm wondering 
if there are any user management/user security modules available that can be 
reused independently of the specific system that you write.

I think something similar to the roles & permission scheme of Zope would 
work, were I can assign certain functionality/permissions to a role, and then 
assign each user a role.

I'd prefer not to fully jump into Zope just yet, because although it has just 
about all the features you can think of, it is also fairly complex (for me at 
least).
It seems that its quite possible to use the security system of Zope 3 
outside of the Zope environment in standard Python.
I just copied the relevant zope package dirs to my own source tree and I 
was able to run the supplied Python examples.

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


Importing from filesystem path a 'frozen sub-module' error

2005-02-28 Thread Calvin Spealman
I've been working on a small test runner script, to accumulate my test
scripts (all python files in the 'test' sub-directories of my source tree).
Things were going well, but I'm still having trouble loading the modules,
once I have a path to the python source file. This is the error I am
getting:

  mod_info = imp.find_module(module_name, module_path)
   ImportError: No frozen submodule named PyInvolgo.test.test_RepoBase

I know 100% sure the module exists (I can enter a python shell and import it
directly, no problem), so that isn't the problem. I don't know what a
'frozen sub-module' is, tho, and I haven't been able to find anything about
them from google searches and documentation on python.org.

At first, I thought maybe it was because the test directory had no
__init__.py (it isn't a package, so I didn't make one), but added one made
no difference.
-- 
 

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


Re: Decimal, __radd__, and custom numeric types...

2005-02-28 Thread Nick Craig-Wood
Blake T. Garretson <[EMAIL PROTECTED]> wrote:
>  I'm having some issues with decimal.Decimal objects playing nice with
>  custom data types.  I have my own matrix and rational classes which
>  implement __add__ and __radd__.  They know what to do with Decimal
>  objects and react appropriately.
> 
>  The problem is that they only work with Decimals if the custom type is
>  on the left (and therefore __add__ gets called), but NOT if the Decimal
>  is on the left.  The Decimal immediately throws the usual "TypeError:
>  You can interact Decimal only with int, long or Decimal data types."
>  without even trying my __radd__ method to see if my custom type can
>  handle Decimals.
> 
> From the Python docs (specifically sections 3.3.7 and 3.3.8), I thought
>  that the left object should try its own __add__, and if it doesn't know
>  what to do, THEN try the right object's __radd__ method.  I guess
>  Decimal objects don't do this?  Is there a way to change this behavior?
>   If Decimal objects prematurely throw a TypeError before trying the
>  __rop__, is Decimal broken, or was it designed this way?  I think I'm
>  missing something...

It looks like from reading 3.3.8 if decimal raised a NotImplemented
exception instead of a TypeError then it would work.

For objects x and y, first x.__op__(y) is tried. If this is not
implemented or returns NotImplemented, y.__rop__(x) is tried. If
this is also not implemented or returns NotImplemented, a
TypeError exception is raised. But see the following exception:

Exception to the previous item: if the left operand is an instance
of a built-in type or a new-style class, and the right operand is
an instance of a proper subclass of that type or class, the right
operand's __rop__() method is tried before the left operand's
__op__() method. This is done so that a subclass can completely
override binary operators. Otherwise, the left operand's __op__
method would always accept the right operand: when an instance of
a given class is expected, an instance of a subclass of that class
is always acceptable.

You could try this with a local copy of decimal.py since it is
written in Python.

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


Re: Explicit or general importing of namespaces?

2005-02-28 Thread Nick Craig-Wood
Paul Rubin  wrote:
>  Peter Hansen <[EMAIL PROTECTED]> writes:
> > Ultimately more important than mere "pollution" are the
> > latent problems this can cause if any of the names in
> > the original module can ever be re-bound.
> 
>  You know, this is another reason the compiler really ought to (at
>  least optionally) check for such shadowing and have a setting to
>  enforce user declarations, like perl's "use strict".

As a (mostly) ex-perl user I wouldn't like to see python go there - it
seems like a rather slippery slope (like the warnings subsystem).

This is surely a job for pychecker / pylint?

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


Re: Validating A User/Password Pair + Getting Groups On Unix

2005-02-28 Thread Kanenas
On 28 Feb 2005 20:17:58 EST, Tim Daneliuk <[EMAIL PROTECTED]>
wrote:

[...]
>Given a username and a password (plain text):
>
>   1) Validate that the password is correct for that user *without actually 
> logging in*.
>
The naive solution is to use the 'crypt' module to encrypt the alleged
password, use 'pwd.getpwuid' or 'pwd.getpwnam' to get the user's
encrypted password (assuming the python process has appropriate access
privileges) and compare the two.  This is naive in that:
* 'pwd.getpw*' may not retrieve the encrypted password even though the
current process has appropriate access privileges 
* the password may be for an encryption or authentication scheme other
than that provided by 'crypt'.  
Using the local authentication scheme shouldn't have these
shortcomings.

There may not be a Python module which handles your local
authentication scheme (there's a 'krb5' module for Kerberos
authentication), so you may need to write one.  This could be done by
an extension module in C or C++ which wraps around whatever local
authentication functions are appropriate (e.g. a 'pam' module for PAM,
an 'auth' module for BSD).  You'd only need to wrap the functions
needed for simple pass/fail authentication (e.g. 'auth_userokay'), but
the other functions could easily be added to the extension later if
needed.  

If you're not sure what authentication scheme your system uses, try
`man -s 3 authenticate` or examine "/usr/src/usr.bin/login/login.c".

Whichever approach you use, the process that calls the authentication
functions needs special access privileges so that the functions can
succesfully accept or reject the password.  The man pages for the
authentication functions should have details.  For example, 'getpwnam'
(used by 'auth_userokay' and the 'pwd' module) requires the effective
uid to be 0 (or, on some systems, the user to be in the "_shadow"
group) for it to include the encrypted password in the returned passwd
entry.

'crypt' and 'pwd' modules:
http://www.python.org/doc/2.4/lib/module-crypt.html
http://www.python.org/doc/2.4/lib/module-pwd.html

extending Python:
http://www.python.org/doc/2.4/ext/ext.html

Python/C API:
http://www.python.org/doc/2.4/api/api.html

Information on Linux-PAM
http://www.kernel.org/pub/linux/libs/pam/

You could even add support for the full authentication API to your
module and contribute the extension to the Python community.
http://www.python.org/download/Contributed.html.


>   2) If the password is valid, return a list of all the groups the user 
> belongs to.
>  Otherwise, return some error string.
>
[...]
>I can do 2) by brute force - just parse through /etc/group - but this
>misses the primary group a given user may belong to - and that requires
>also scanning /etc/passwd and then looking up the corresponding primary
>group in /etc/group.  Is there a better way?
>
Slightly better would be to use the 'grp' and 'pwd' modules.  One
advantage of this is it should support networked user databases (such
as YP).
http://www.python.org/doc/2.4/lib/module-grp.html
http://www.python.org/doc/2.4/lib/module-pwd.html

If you've grabbed the password entry for a user during authentication,
you've already got the login group but you'll still need to check for
additional groups.  You could create a dictionary which maps user
names or IDs to groups.  This would still require processing all
groups (via 'grp.getpwall()'), but is more efficient if you need to
fetch the groups of more than one user in the life of the process
(from the outline, I'm guessing this will only be the case if the
program is a server of some sort).  Just make sure you have a method
to re-process the group database into the group dictionary in case the
group file changes.

Even better would be to write an extension or add to the grp module to
wrap around local group database access functions (e.g. getgrouplist).
See the 'getgrouplist' man page for more information and examine the
source of the `groups` command (probably
"/usr/src/usr.bin/groups/groups.c") or `id` command (should be
"/usr/src/usr.bin/id/id.c") for other group DB access functions.

You could also call the `groups` command via 'os.popen(...)'.

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


Re: zlib.decompress cannot, gunzip can

2005-02-28 Thread Dima Dorfman
On 2005-03-01, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I have a string which I try to decompress:
>
>   body = zlib.decompress(body)
>
> but I get
>
>   zlib.error: Error -3 while decompressing data: incorrect header check
>
> However, I can write the string to a file and run gunzip with the
> expected results:

gzip files have a header preceding the zlib stream. Try the gzip module.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Met Problem with Distutils

2005-02-28 Thread Robert Kern
[EMAIL PROTECTED] wrote:
if i want a main executable py script installed on the /usr/local/bin,
what do i do?  i tried the data_files options in the setup.py, but
nothing happened, no the expected file appeared in the resulted tarbar.
Generally speaking, you, the author, shouldn't dictate to the user 
exactly where to install stuff to. There are reasons to break this rule, 
but installing exectuable scripts is too common to be one of them.

The way for the user to install scripts to the location of their choice 
is given here:

  http://docs.python.org/inst/alt-install-windows.html
In short, use the --install-scripts command-line option, or the 
setup.cfg/.pydistutils.cfg snippet:

  [install]
  install_scripts=...
--
Robert Kern
[EMAIL PROTECTED]
"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter
--
http://mail.python.org/mailman/listinfo/python-list


Met Problem with Distutils

2005-02-28 Thread steven
if i want a main executable py script installed on the /usr/local/bin,
what do i do?  i tried the data_files options in the setup.py, but
nothing happened, no the expected file appeared in the resulted tarbar.

below is the setup.py:

setup(name='foopkg',

  version='1.0',

  author="Steven Woody",

  author_email="[EMAIL PROTECTED]",

  url="http://a.b.c";,

  packages=['foopkg'],

  scripts=['scripts/*.py'],

  data_files=[('/usr/local/bin', ['scripts/myprj.py'])]

  )


can anyone tell me what is wrong?

thanks in advance!

-
narke

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


Google Technology

2005-02-28 Thread vijay123
I am just wondering which technologies google is using for gmail and
Google Groups???

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


[OT] Re: String Replace Problem...

2005-02-28 Thread Steven Bethard
Sean McIlroy wrote:
Alright, now it's too much. It's not enough that you're eliminating it
from the language, you have to stigmatize the lambda as well.
You misunderstand me.  I don't have a problem with lambda when it's 
appropriate, e.g. when used as an expression, where a statement is 
forbidden.  See my post examining some of the uses in the standard 
library[1].  But when you're defining a named function, you should use 
the named function construct.  That's what it's there for.  =)

And besides, it amounts to an explicit declaration that the function
in question has no side effects.
Not at all.  Some examples of lambdas with side effects:
py> a
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'a' is not defined
py> (lambda s: globals().__setitem__(s, 'side-effect'))('a')
py> a
'side-effect'
py> x = (lambda s: sys.stdout.write(s) or s.split())('side effect')
side effect
py> x
['side', 'effect']
py> s = set()
py> x = (lambda x: s.add(x) or x**2)(3)
py> s
set([3])
py> x
9
It is certainly possible to use lambda in such a way that it produces no 
side effects, but it's definitely not guaranteed by the language.

And besides, it adds flexibility to the language.
I'm not sure I'd agree with flexibility...  True, in some cases it can 
allow more concise code, and occasionally it can read more clearly than 
the other available options, but since you can use a function created 
with def anywhere you can use a function created with lambda, I wouldn't 
say that lambdas make Python any more flexible.

STeVe
[1]http://mail.python.org/pipermail/python-list/2004-December/257990.html
--
http://mail.python.org/mailman/listinfo/python-list


Re: Validating A User/Password Pair + Getting Groups On Unix

2005-02-28 Thread Kanenas
On 28 Feb 2005 20:17:58 EST, Tim Daneliuk <[EMAIL PROTECTED]>
wrote:

[...]
>Given a username and a password (plain text):
>
>   1) Validate that the password is correct for that user *without actually 
> logging in*.
>
The 'pwd' module probably won't be able (and won't try) to read the
shadow password file, so 'pwd' won't be of use.  There may not be a
Python module which handles your local authentication scheme (there's
a 'krb5' module for Kerberos authentication), so you may need to write
one.  The best approach may be to write an extension module in C or
C++ which wraps around whatever local authentication functions are
appropriate (e.g. a 'pam' module for PAM, an 'auth' module for BSD).
You'd only need to wrap the functions needed for simple pass/fail
authentication (e.g. auth_userokay), but the other functions could
easily be added to the extension later if needed.  

The process that calls the authentication functions will probably need
special access privileges so that the functions can succesfully accept
or reject the password.  The man pages for the authentication
functions should have details.  For example, auth_userokay calls
getpwnam, which requires the effective uid to be 0 (or, on some
systems, the user to be in the "_shadow" group) for it to include the
encrypted password in the passwd entry.

If you're not sure what authentication scheme your system uses, try
`man -s 3 authenticate` or examine "/usr/src/usr.bin/login/login.c".

extending Python:
http://www.python.org/doc/2.4/ext/ext.html

Python/C API:
http://www.python.org/doc/2.4/api/api.html

Information on Linux-PAM
http://www.kernel.org/pub/linux/libs/pam/

You could even add support for the full authentication API to your
module and contribute the extension to the Python community.
http://www.python.org/download/Contributed.html.


>   2) If the password is valid, return a list of all the groups the user 
> belongs to.
>  Otherwise, return some error string.
>
[...]
>I can do 2) by brute force - just parse through /etc/group - but this
>misses the primary group a given user may belong to - and that requires
>also scanning /etc/passwd and then looking up the corresponding primary
>group in /etc/group.  Is there a better way?
>
Slightly better would be to use the grp and pwd modules:
http://www.python.org/doc/2.4/lib/module-grp.html
http://www.python.org/doc/2.4/lib/module-pwd.html

Even better would be to write an extension or add to the grp module to
wrap around local group database access functions (e.g. getgrouplist).
See the 'getgrouplist' man page for more information and examine the
source of the `groups` command (probably
"/usr/src/usr.bin/groups/groups.c") or `id` command (should be
"/usr/src/usr.bin/id/id.c") for other group DB access functions.

You could also call the `groups` command via 'os.popen(...)'.

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


enter key event in wxpython

2005-02-28 Thread Raghul
hi,
   I am developing a jabber client.What I need is whrn i enter text in
the text area and when I press return key. The following text should be
send.I found the way to send the message, the only thing is I want to
handle the enter key event.how to do this? so that when i press enter
key, The key id or the event to be handled. Help me pls.

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


Re: ZoDB's capabilities

2005-02-28 Thread Joe
On Mon, 28 Feb 2005 23:31:27 +0100, Almad <[EMAIL PROTECTED]> wrote:
>I'm going to write a custom CMS. I'd like to use some odbms, as code is then
>much more cleaner...

You should go ask for pratical infos on ZODB here:

http://www.zope.org/Products/StandaloneZODB

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


Weekly Python Patch/Bug Summary

2005-02-28 Thread Kurt B. Kaiser
Patch / Bug Summary
___

Patches :  303 open ( -5) /  2764 closed ( +9) /  3067 total ( +4)
Bugs:  849 open (+11) /  4837 closed ( +3) /  5686 total (+14)
RFE :  169 open ( +1) /   148 closed ( +0) /   317 total ( +1)

New / Reopened Patches
__

New fpconst module  (2005-02-24)
   http://python.org/sf/1151323  opened by  Gregory Warnes

PyXxx_Check() speed-up  (2005-02-27)
   http://python.org/sf/1153056  opened by  Armin Rigo

os.remove error on Solaris  (2005-02-28)
   http://python.org/sf/1153417  opened by  Richard Philips

Patches Closed
__

rlcompleter does not expand on [ ]  (2002-04-22)
   http://python.org/sf/547176  closed by  mwh

Non-blocking Socket Server  (2004-05-02)
   http://python.org/sf/946207  closed by  loewis

add urldecode() method to urllib  (2003-05-21)
   http://python.org/sf/740827  closed by  loewis

adding bool support to xdrlib.py  (2004-10-18)
   http://python.org/sf/1049151  closed by  loewis

PEP309 Partial implementation  (2004-04-25)
   http://python.org/sf/941881  closed by  rhettinger

sanity check for readline remove/replace  (2004-12-31)
   http://python.org/sf/1093585  closed by  loewis

PEP 309 LaTeX documentation  (2004-04-07)
   http://python.org/sf/931007  closed by  rhettinger

Build Patch #941881 (PEP 309 in C) on windows  (2004-08-10)
   http://python.org/sf/1006948  closed by  rhettinger

PEP 309 unit tests  (2004-04-07)
   http://python.org/sf/931010  closed by  rhettinger

New / Reopened Bugs
___

hotshot.runctx: builtins missing  (2005-02-23)
   http://python.org/sf/1149798  opened by  Jurjen N.E. Bos

macostools.mkdirs: not thread-safe  (2005-02-23)
   http://python.org/sf/1149804  opened by  Jurjen N.E. Bos

(XMLRPC) multitude of sockets ending up in TIME_WAIT  (2005-02-25)
   http://python.org/sf/1151968  opened by  Jonas Widén

Dict docstring error Python-2.3.5  (2005-02-26)
   http://python.org/sf/1152424  opened by  Colin J. Williams

urllib2 dont respect debuglevel in httplib  (2005-02-27)
   http://python.org/sf/1152723  opened by  abbatini

Default class args get clobbered by prior instances.  (2005-02-26)
CLOSED http://python.org/sf/1152726  opened by  Simon Drabble

curses.textpad raises error  (2005-02-27)
   http://python.org/sf/1152762  opened by  John McPherson

Setting socket timeout crashes SSL  (2005-02-27)
   http://python.org/sf/1153016  opened by  pristine777

http_error_302() crashes with 'HTTP/1.1 400 Bad Request  (2005-02-27)
   http://python.org/sf/1153027  opened by  pristine777

PyXxx_Check(x) trusts x->ob_type->tp_mro  (2005-02-27)
   http://python.org/sf/1153075  opened by  Armin Rigo

reflected operator not used when operands have the same type  (2005-02-27)
   http://python.org/sf/1153163  opened by  HughSW

reflected operator not used when operands have the same type  (2005-02-27)
CLOSED http://python.org/sf/1153171  opened by  HughSW

string interpolation breaks with %d and large float  (2005-02-28)
   http://python.org/sf/1153226  opened by  Stephen Thorne

eval does not bind variables in lambda bodies correctly  (2005-02-28)
   http://python.org/sf/1153622  opened by  Mattias Engdegård

String interpolation needs PEP 237 update  (2005-02-28)
   http://python.org/sf/1153769  opened by  Richard Brodie

Bugs Closed
___

Python24.dll crashes, EXAMPLE ATTACHED  (2005-02-12)
   http://python.org/sf/1121201  closed by  complex

Default class args get clobbered by prior instances.  (2005-02-26)
   http://python.org/sf/1152726  closed by  rhettinger

reflected operator not used when operands have the same type  (2005-02-27)
   http://python.org/sf/1153171  closed by  rhettinger

New / Reopened RFE
__

Enhance file.readlines by making line separator selectable  (2005-02-26)
   http://python.org/sf/1152248  opened by  Nick Coghlan

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


Re: python-dev Summary for 2005-01-16 through 2005-01-31

2005-02-28 Thread Michele Simionato
Brett Cannon:
>Lastly, the typical boilerplate for each Summary has now been moved to
the
>bottom.  This was at the request of a regular reader who I would like
to keep
>happy.  =)  It also seems reasonable since once you have read through
it once
>chances are you are not going to read it again so might as well move
it out of
>the way.

+1 for this idea. The summary looks much better now :)
Keep the good work going,

  Michele Simionato

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


java crashes in python thread

2005-02-28 Thread Easeway
I use os.system invoking java VM, when running in python thread, 
the java application crashes.  But it works properly when thread is
not used.

Has any body come across with this problem?

Python 2.3.3
J2SDK 1.4.2_05
SuSE Linux Enterprise Server 9

The following is source file:
#!/usr/bin/env python

import os, sys, threading

class ThreadTask(threading.Thread) :

def __init__(self, shellcmd) :
threading.Thread.__init__(self)
self.command = shellcmd

def isStopped(self) :
self.join(0.01)
return not self.isAlive()

def run(self) :
os.system(self.command)

def test() :
commands = [
"/usr/lib/java/bin/javac",
"/usr/lib/java/bin/java",
   ]
tasks = []
for a in commands :
tasks.append(ThreadTask(a))

for a in tasks :
a.start()

endcnt = 0
while endcnt < len(tasks) :
endcnt = 0
for a in tasks :
if a.isStopped() : endcnt += 1
print("DONE")

test()

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


Re: String Replace Problem...

2005-02-28 Thread Sean McIlroy
Alright, now it's too much. It's not enough that you're eliminating it
from the language, you have to stigmatize the lambda as well. You
should take some time to reflect that not everybody thinks the same
way. Those of us who are mathematically inclined like the lambda
because it fits in well with the way we already think. And besides, it
amounts to an explicit declaration that the function in question has
no side effects. And besides, it adds flexibility to the language. Go
ahead and throw it away, but you're making python less accessible for
those of us whose central concern is something other than programming.
("Single line" indeed!)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best XSLT processor?

2005-02-28 Thread uche . ogbuji
Actually, most of the compliant problems I can remember off-head with
respect to Xalan have been regarding EXSLT 1.0, not base XSLT 1.0.
Sorry for any misconstruction.

--Uche

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


Re: accessor/mutator functions

2005-02-28 Thread Dan Sommers
On Tue, 01 Mar 2005 02:27:03 GMT,
Andrew Dalke <[EMAIL PROTECTED]> wrote:

> Me:
>>> What's wrong with the use of attributes in this case and how
>>> would you write your interface?

> Dan Sommers:
>> I think I'd add a change_temperature_to method that accepts the target
>> temperature and some sort of timing information, depending on how the
>> rest of the program and/or thread is structured.

> Hmmm.  I wonder if this is mostly a question of how the process
> decomposition occurs.  I think in objects ("thingys with state")
> whereas you think in tasks ("thingys that do stuff")?  I say that
> somewhat surprisingly in that I'm not a deep OO person - functions are
> fine with me and I don't like the Java/Ruby "everything is in a class"
> world view.

I'm not an OO guy, either.  Somewhere back in the mid 90's, I was
dragged, kicking and screaming, into OO from the world of Structured
Programming.

You're right about my notion of an object:  I think that if all you have
is state information, then you just have a C struct and there's no point
in doing OO.  I still write plenty of (smallish) programs like that.

>> It might turn into two or three methods, depending on whether I can
>> afford to block while waiting, or what kind of intermediate feedback
>> and/or error handling I want (or one method with some carefully
>> chosen default arguments).

> In the case I'm hypothesizing (haven't worked with a temperature
> controller in about 15 years) it's hard to put a layer above
> everything because there could be so many different protocols
> (chemical protocols, not I/O ones) with different rates.  Eg, it could
> be an exponential decay, or step-wise approximation thereof.

Yes, it would be difficult (and silly and a maintentance nightmare,
too!) to put every protocol into the temerature controller.  I think at
that point, I'd put the protocols in a separate "layer," and I'd have to
think carefully about that layer's interface to the temperature
controller.  My application would be that much farther from even having
to know the current temperature, let alone access it directly from the
TemperatureController object (although at some point, the application
would probably end up displaying that current temperature, so it's not
like everything is completely isolated from everything else).

>> I don't know how that device driver works, but it might look something
>> like this:
>> 
>> def change_temperature_to( self, target, seconds_between_checks ):
>> print 'target temperature:', target
>> tell_the_device_to_change( )
>> while 1:
>> current = read_the_temperature_from_the_device( )
>> print 'current temperature:', current
>> if abs( current - target ) < 0.1:
>> break
>> time.sleep( seconds_between_checks )

> Your "tell_the_device_to_change" is my "self.target" and your
> "read_the_temperature_from_the_device" is "self.current_temperature".
> In some sense it comes down to style.

My point was mostly that change_temerature_to would be a method of a
TemperatureController object.  "tell_the_device_to_change" is whatever
method/function you have behind setting self.target.  As you noted, I
think of the temperature controller as being able to manage its own
temperature rather than be a (thin) wrapper around a device driver.

> BTW, had I done this for real I would have two layers, one which is
> communications oriented ("send 'get current temperature' message to
> device") and my object model which uses the messaging interface
> underneath.

That sounds about right.

> I liked being able to say:

> print atom.symbol, "with charge", atom.charge, "has", \
>   len(atom.bonds), "bonds"

> for i, bond in enumerate(bonds):
>   print "bond", i, "has type", bond.bondtype

> To me this is a very natural way of querying the data and
> traversing the data structure.

> Now underneath the covers it looks like this:

>   atom.charge fails so use __getattr__(atom, "charge")
>   __getattr__ uses a dispatch table to get the underlying C function
>   which is "dt_getcharge"
>   return dt_getcharge(self.handle)

> where "handle" is the handle used by the C library.

> I figured though that this example might be more esoteric
> than my PID controller example, though in retrospect it
> looks like it might be a better justification.

I like that kind of abstraction:  the atom object hides the fact that
the charge comes out of another layer/library/object entirely.

Regards,
Dan

-- 
Dan Sommers

Îâ à Îâ à c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] pyasm 0.1 - x86 assembler for Python

2005-02-28 Thread Grant Olson
pyasm 0.1 - x86 assembler for Python

This release is for early adopters only.  It is not properly packaged and
doesn't have very good documentation.  It is however a functional assembler
that should be of interest to some people.

Current output targets include Windows-style COFF files that can be
subsequently linked to produce executables, and more interestingly output
can target memory in an existing Python process and binding within a Python
namespace.  That's right, you can now generate dynamic inline assembly
straight from Python!  A simple hello world function implementation is
listed at the end of this message.


The files test\test_object_creation.py and test\test_winmem.py in the
distribution probably give the best examples of usage.

Future plans include targeting ELF file formats and Linux memory at runtime,
and of course real documentation.

The package is available at:
http://mysite.verizon.net/olsongt/pyasm-0.1.zip

Enjoy,

-Grant

#
# PYTHON HELLO WORLD IN ASSEMBLY
#

import pyasm.winmem
from pyasm.x86asm import assembler, CDECL
from pyasm.x86cpToMemory import CpToMemory

nonePointer = id(None)


a = assembler()
a.ADStr("hello_world", "Hello world!\n\0")
a.AP("test_print", CDECL)
a.AddLocal("self")
a.AddLocal("args")
#a.AI("INT 3")
a.AI("PUSH hello_world")
a.AI("CALL PySys_WriteStdout")
#a.AI("INT 3")
a.AI("MOV EAX,%s" % id(None))
a.AI("ADD [EAX],0x1") #refcount manipulation
a.EP()


mem = CpToMemory(a.Compile(),pyasm.winmem)
mem.MakeMemory()
mem.BindPythonFunctions(globals())

test_print() # calls the assembly function

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


python-dev Summary for 2005-01-16 through 2005-01-31

2005-02-28 Thread Brett C
=
Summary Announcements
=
-
School sure likes to destroy my free time
-
A month late, that much closer to having this hectic quarter being over.  Sorry 
for being so delinquent with this summary but school has kept me busy and 
obviously the Real World has to take precedence over volunteer work.  Now if I 
could only get paid for doing this... =)

And if you hate the summaries being late, you could do it yourself.  This is 
not meant to be a flippant comment!  I am always willing to hand over 
development of the summaries to anyone who is willing to do a comparable job. 
If you are interested feel free to email me.  I have now made this a permanent 
offer in the header in case someone comes along later and decides they want to 
do this.

--
RSS feed now available
--
Thanks entirely to one of my predecessors, A.M. Kuchling, the python-dev 
Summaries are available as an `RSS feed`_.  The feed contains the titles of 
every summary and so will be updated with the newest summaries as soon as they 
are posted online.  A full text feed will eventually be available.

--
New format
--
I have done a thorough restructuring of the boilerplate and the Summary 
Announcements section for the Summaries.  The purpose of this is to make 
finding information in the boilerplate much easier.  It also keeps consistency 
by sectioning off everything as in the Summary section.

The other reason is for the ``contents`` directive in reST_.  This will provide 
a more thorough table of contents for the web version of the summary at the 
very top of the summaries.  This will allow people to jump directly to the 
section of the Summary they care about the most.  Obviously this perk only 
exists in the HTML version.

Lastly, the typical boilerplate for each Summary has now been moved to the 
bottom.  This was at the request of a regular reader who I would like to keep 
happy.  =)  It also seems reasonable since once you have read through it once 
chances are you are not going to read it again so might as well move it out of 
the way.

Then again I could be totally wrong about all of this and manage to alienate 
every person who reads the summaries regularly.  =)


===
Summary
===
-
Python 2.3.5 released
-
Consider how late this summary is I bet you already knew Python 2.3.5 was 
already out the door.  =)

With Python 2.4 out in the world this means there is a very high probability 
2.3.6 will never exist and this marks the end of the 2.3 branch.

Contributing threads:
  - `2.3.5 delayed til next week 
`__
  - `2.3 BRANCH FREEZE imminent! 
`__
  - `RELEASED Python 2.3.5, release candidate 1 
`__

--
Making magic type conversion methods act like __str__
--
Walter DÃrwald discovered that when you subclass 'unicode' and call unicode() 
on an instance of the subclass it will not call the implementation of 
__unicode__ of the subclass but instead will call unicode.__unicode__ .  When 
in the same scenario with strings, though, str() calls the subclass' __str__ 
method.  Turns out 'int' and 'float' act like 'unicode' while 'complex' acts 
like 'str'.

So who is right?  Docs say 'str' is wrong, but this is mainly an artifact of 
pre-2.2 inability to subclass types.  Turns out 'str' is acting properly. 
`Patch #1109424`_ implements the proper semantics and will eventually go in for 
2.5 (won't touch 2.4 since it is a semantic change).

.. _Patch #1109424: http://www.python.org/sf/1109424
Contributing threads:
  - `__str__ vs. __unicode__ 
`__

-
Speeding up function calls to C API functions
-
Neal Norwitz posted the patch found at http://www.python.org/sf/1107887 to help 
with function calls to C code.  The idea is to expand the family of values used 
in PyMethodDef.ml_flags for argument types to include specifying the number of 
minimum and maximum number of arguments.  This can provide a speedup by 
allowing the eval loop to unpack everything in the C stack and skip packing 
arguments in a tuple.

But not everyone was sure it was worth the extra need to specify all of this 
for functions.  Regardless of that and any other objections this would be more 
of a Python 3000 thing.

Which also led to a quick shift in topic to how Python 3.0 will be developed. 
Guido said it would be piece-meal.  Read 
http://joelonsoftware.com/articles/fog69.html for why.

Co

Re: best XSLT processor?

2005-02-28 Thread uche . ogbuji
This is a good way to kick off a tussle among interested parties, but
hinestly, at this point, most packages work fine.  In my opinion your
rade-off right now is raw speed (e.g. libxslt) versus flexibility (e.g.
4Suite).  All are bug-free enough that you'd have to be doing somethign
*very* exotic to run into trouble.

Just pick one or two and try them.

http://uche.ogbuji.net/tech/akara/nodes/2003-01-01/python-xslt

--Uche

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


Re: best XSLT processor?

2005-02-28 Thread uche . ogbuji
Xalan is certainly faster, but it is almost certainly not more
compliant than 4Suite.  Xalan actually has a bit of a reputation among
XSLT processors in its carelessness with compliance.  But I suppoose in
order to settle these counter-claims, one of us will have to come up
with specific compliance examples.  You fired the first shot.  Can you
back it up?

--Uche

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


Re: best XSLT processor?

2005-02-28 Thread uche . ogbuji
Who says 4Suite is buggy?  Do they have any evidence to back that up?
We have a huge test suite, and though 4Suite is by no means the fastest
option, it's quite reliable for XSLT.

The XSLT processor in PyXML is just a very old version of 4XSLT.

--Uche

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


Re: accessor/mutator functions

2005-02-28 Thread Andrew Dalke
Me:
>> What's wrong with the use of attributes in this case and how
>> would you write your interface?

Dan Sommers:
> I think I'd add a change_temperature_to method that accepts the target
> temperature and some sort of timing information, depending on how the
> rest of the program and/or thread is structured.

Hmmm.  I wonder if this is mostly a question of how the
process decomposition occurs.  I think in objects ("thingys
with state") whereas you think in tasks ("thingys that do stuff")?
I say that somewhat surprisingly in that I'm not a deep OO
person - functions are fine with me and I don't like the
Java/Ruby "everything is in a class" world view.

> It might turn into two
> or three methods, depending on whether I can afford to block while
> waiting, or what kind of intermediate feedback and/or error handling I
> want (or one method with some carefully chosen default arguments).

In the case I'm hypothesizing (haven't worked with a temperature
controller in about 15 years) it's hard to put a layer above
everything because there could be so many different protocols
(chemical protocols, not I/O ones) with different rates.  Eg,
it could be an exponential decay, or step-wise approximation
thereof.

The note about errors is interesting.  For example, if the
cable to the controller was disconnected then someone, especially
someone used to memory lookups for attributes, might not expect

  temp_controller.current

to possibly raise an I/O error exception.  On the other hand,
at the C level that could be memory mapped I/O, so that

  int x = temp_controller.current;

could also have all sorts of side effects.  That case
is dangerous in C because of its poor exception mechanism.
I think in Python it's much less of a problem.


> I don't know how that device driver works, but it might look something
> like this:
> 
> def change_temperature_to( self, target, seconds_between_checks ):
> print 'target temperature:', target
> tell_the_device_to_change( )
> while 1:
> current = read_the_temperature_from_the_device( )
> print 'current temperature:', current
> if abs( current - target ) < 0.1:
> break
> time.sleep( seconds_between_checks )

Your "tell_the_device_to_change" is my "self.target" and your
"read_the_temperature_from_the_device" is "self.current_temperature".
In some sense it comes down to style.

BTW, had I done this for real I would have two layers, one
which is communications oriented ("send 'get current temperature'
message to device") and my object model which uses the messaging
interface underneath.

>  I think part of my thinking
> comes from my old Pascal days, when it made me cringe to think that
> "x:=b;" might actually execute a subroutine rather than just copy some
> memory around.

To give a more recent example for me, which I covered here some
years back, I wrote an OO interface to an "OO-ish" C library
for doing chemistry.  In the data model, atoms have an atomic
symbol, a charge and a list of bonds (and many other things).
Bonds have a bond type and the two atoms at the ends of the bonds
(and many other things).

I liked being able to say:

print atom.symbol, "with charge", atom.charge, "has", \
  len(atom.bonds), "bonds"

for i, bond in enumerate(bonds):
  print "bond", i, "has type", bond.bondtype

To me this is a very natural way of querying the data and
traversing the data structure.

Now underneath the covers it looks like this:

  atom.charge fails so use __getattr__(atom, "charge")
  __getattr__ uses a dispatch table to get the underlying C function
  which is "dt_getcharge"
  return dt_getcharge(self.handle)

where "handle" is the handle used by the C library.

I figured though that this example might be more esoteric
than my PID controller example, though in retrospect it
looks like it might be a better justification.

Andrew
[EMAIL PROTECTED]

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


Re: Scoping issue with import

2005-02-28 Thread Calvin Spealman
Each module is only 'aware' of the built-ins and the modules it itself
imports. So, all you need to do is add this line to my_imported_mod:

from my_main_mod import myfun

This is a fully intentional feature. Modules stand on their own.

James Stroud wrote:

> Say I have a module, we'll call it "my_imported_mod". It contains a
> function in it that calls another function, "myfun". The "myfun" function
> is in the module "my_main_mod", that imports "my_imported_mod".
> 
> The code of "my_main_mod" might look like this:
> ==
> from my_imported_mod import *
> 
> def myfun():
>   print "stuff"
> ==
> 
> the code of "my_imported_mod" might look like this:
> ==
> def somefun():
>   myfun()
> ==
> 
> When trying to execute the function somefun(), I get a
> NameError: global name 'myfun' is not defined
> 
> How to rectify this with minimal code change? How to let imported modules
> know about the namespace they are getting imported into? I do not want to
> restructure my code right now.
> 
> Thanks in advance for help.
> 
> James

-- 
 

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


Sound and music libraries?

2005-02-28 Thread Ben Sizer
Are there any decent sound and music libraries for Python that are
suitable for game use? Pygame is too closely tied to SDL, PyFMOD seems
to no longer be maintained, and ALPY 1.0 has disappeared and is GPL
anyway (not suitable for my purposes). I'd settle for DirectSound
bindings but DirectX use in Python doesn't seem to be done for some
reason.

-- 
Ben Sizer.

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


Re: Canonical way of dealing with null-separated lines?

2005-02-28 Thread John Machin

Douglas Alan wrote:
> I wrote:
>
> > Oops, I just realized that my previously definitive version did not
> > handle multi-character newlines.  So here is a new definitive
> > version.  Oog, now my brain hurts:
>
> I dunno what I was thinking.  That version sucked!  Here's a version
> that's actually comprehensible, a fraction of the size, and works in
> all cases.  (I think.)
>
> def fileLineIter(inputFile, newline='\n', leaveNewline=False,
readSize=8192):
>"""Like the normal file iter but you can set what string indicates
newline.
>
>The newline string can be arbitrarily long; it need not be
restricted to a
>single character. You can also set the read size and control
whether or not
>the newline string is left on the end of the iterated lines.
Setting
>newline to '\0' is particularly good for use with an input file
created with
>something like "os.popen('find -print0')".
>"""
>outputLineEnd = ("", newline)[leaveNewline]
>partialLine = ''
>while True:
>charsJustRead = inputFile.read(readSize)
>if not charsJustRead: break
>lines = (partialLine + charsJustRead).split(newline)

The above line is prepending a short string to what will typically be a
whole buffer full. There's gotta be a better way to do it. Perhaps you
might like to refer back to CdV's solution which was prepending the
residue to the first element of the split() result.

>partialLine = lines.pop()
>for line in lines: yield line + outputLineEnd

In the case of leaveNewline being false, you are concatenating an empty
string. IMHO, to quote Jon Bentley, one should "do nothing gracefully".


>if partialLine: yield partialLine
> 
> |>oug

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


Re: accessor/mutator functions

2005-02-28 Thread Dan Sommers
On Tue, 01 Mar 2005 01:39:13 +0100,
Thomas Lotze <[EMAIL PROTECTED]> wrote:

> Dan Sommers wrote:

>> I think I'd add a change_temperature_to method that accepts the
>> target temperature and some sort of timing information, depending on
>> how the rest of the program and/or thread is structured.

> But then you put application logic into a library function. Doing this
> consistently leads to a monster of a library that tries to account for
> all possible applications. Where does this leave the KISS principle?

Maybe I'm "old school," but I usually end up with lots of layers in
between library functions and application logic.  If I think my
"library" layer is too big, yes, I will add another layer of abstraction
around it.  Nothing says that my application has to talk directly to
every low-level library function.

>> In the case of simply reading the current temperature, and not
>> knowing what's inside that device driver, I'd still lean away from
>> exposing a current temperature attribute directly.  I think part of
>> my thinking comes from my old Pascal days, when it made me cringe to
>> think that "x:=b;" might actually execute a subroutine rather than
>> just copy some memory around.

> Then you also avoid lists, dicts and, ironically, methods. Accessing
> methods means to access a callable attribute, after all, with all the
> stuff going on behind the scenes on attribute access.

By that logic, I'd also avoid Python, which, obviously, I'm don't.

When I see a simple construct like "a = b," or "a = b[ 2 ]," or even
"a.b.c = d.e.f," I would like to think that nothing "magic" (for some
suitable definition of "magic") is happening.  Yes, in a language like
Python, a lot more is happening (and a whole lot more *could* happen)
under the hood than in the extremely roughly equivalent "move.l d1,d2"
in assembly language.

I guess we all have our own personal tolerances for "Explicit is better
than implicit."

Regards,
Dan

-- 
Dan Sommers

Îâ à Îâ à c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: yield_all needed in Python

2005-02-28 Thread Terry Reedy

"Douglas Alan" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> We can shorten the code--and make it run in O(N) time--by adding a 
> new
> keyword to replace the "for v in ...: yield v" pattern:

Maybe.  Until you define the semantics of yield_all and at least outline an 
implementation, I am not convinced of 'run in o(n) time'.  There was once a 
several-post discussion of a related idea of having yield somehow, 
magically, skip intermediate generators that only yielded value on up, 
without tranformation.  But it was never clear how to do this practically 
without negatively impacting all generators.  Cetainly, if  == , I don't see how anything is 
gained except for a few keystrokes.  If  ==  then the replacement is a semantic change.

>   def in_order(self):
>   if self.left is not None:
>   yield_all self.left.in_order():
>   yield self.value
>   if self.right is not None:
>   yield_all self.right.in_order():

If and when I write a text-based double-recursion to iteration transformer, 
a pseudokeyword might be be an idea for indicating that stacked yields are 
identify functions and therefore bypassable.

Terry J. Reedy



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


Validating A User/Password Pair + Getting Groups On Unix

2005-02-28 Thread Tim Daneliuk
OK, I've Googled for this and cannot seem to quite find what I need.
So, I turn to the Gentle Geniuses here for help.  Here is what I
need to do from within a script:
Given a username and a password (plain text):
  1) Validate that the password is correct for that user *without actually 
logging in*.
  2) If the password is valid, return a list of all the groups the user belongs 
to.
 Otherwise, return some error string.
I seem to not be able to crack how to do 1.
I can do 2) by brute force - just parse through /etc/group - but this
misses the primary group a given user may belong to - and that requires
also scanning /etc/passwd and then looking up the corresponding primary
group in /etc/group.  Is there a better way?
TIA,
--

Tim Daneliuk [EMAIL PROTECTED]
PGP Key: http://www.tundraware.com/PGP/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Canonical way of dealing with null-separated lines?

2005-02-28 Thread Douglas Alan
I wrote:

> Oops, I just realized that my previously definitive version did not
> handle multi-character newlines.  So here is a new definitive
> version.  Oog, now my brain hurts:

I dunno what I was thinking.  That version sucked!  Here's a version
that's actually comprehensible, a fraction of the size, and works in
all cases.  (I think.)

def fileLineIter(inputFile, newline='\n', leaveNewline=False, readSize=8192):
   """Like the normal file iter but you can set what string indicates newline.
   
   The newline string can be arbitrarily long; it need not be restricted to a
   single character. You can also set the read size and control whether or not
   the newline string is left on the end of the iterated lines.  Setting
   newline to '\0' is particularly good for use with an input file created with
   something like "os.popen('find -print0')".
   """
   outputLineEnd = ("", newline)[leaveNewline]
   partialLine = ''
   while True:
   charsJustRead = inputFile.read(readSize)
   if not charsJustRead: break
   lines = (partialLine + charsJustRead).split(newline)
   partialLine = lines.pop()
   for line in lines: yield line + outputLineEnd
   if partialLine: yield partialLine

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


Re: TKinter

2005-02-28 Thread anthonyberet
Steve Holden wrote:
anthonyberet wrote:
So, is it pronounced 'Tee-Kinter', or 'Tee-Kay-Inter'?
I don't want to appear as a dork down the pub.

If anyone down your pub knows enough about Python to understand what 
TKinter is I very much doubt they'll be rude enough to call you a dork 
for displaying your ignorance.

that's-my-kind-of-pub-ly y'rs  - steve
I have never recovered from the time I said 'Lye-Nux' and 'Ess-Kyoo-Ell' 
in the same evening ;|)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Share your SciTEGlobal.properties pls~~~~

2005-02-28 Thread Neil Hodgson
DENG:

> im new to Python, i chose SciTE as my Python editor. but the problem is
> SciTE needs to be config carefully, are there anyone use SciTE too? can
> you share your SciTEGlobal.properties file? black background solution
> is prefered:)

http://scintilla.sourceforge.net/SciTEFAQ.html#BlackBackground

   Adding changes to your user options file rather the global options file
means that they will survive if you upgrade to a new version of SciTE.

   There is a SciTE mailing list at
http://mailman.lyra.org/mailman/listinfo/scite-interest

   Neil


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


Re: Pythonwin: Red squiggley underline and syntax error

2005-02-28 Thread Neil Hodgson
Steven Bethard:

> You've probably mixed tabs with spaces in your indentation somewhere.
> Either replace all tabs with spaces or replace all spaces with tabs.

   You can see what characters are being used with the View | Whitespace
command which shows tabs as arrows and spaces as centred dots.

   Neil


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


zlib.decompress cannot, gunzip can

2005-02-28 Thread enrio
I have a string which I try to decompress:

  body = zlib.decompress(body)

but I get

  zlib.error: Error -3 while decompressing data: incorrect header check

However, I can write the string to a file and run gunzip with the
expected results:

  f = open('/tmp/bd.gz', 'w')
  f.write(body)
  f.close
...
  $ gunzip bd.gz
  $ less bd

What should I do to decompress it in Python?

Regards, Enrique

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


Re: Hey, How Do I Distribute my New Completed Python Project?

2005-02-28 Thread steven
Thank You All

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


Re: ZoDB's capabilities

2005-02-28 Thread Larry Bates
There is a VERY large website that uses Zope/ZODB that takes up to
9000 hits per second when it gets busy.  ZODB is very fast and
holds up well under load.

You should probably look at Plone.  It is CMS already built on
top of Zope.  Might safe you a LOT of work.

Larry Bates


Almad wrote:
> Hello, 
> 
> I'm going to write a custom CMS. I'd like to use some odbms, as code is then
> much more cleaner...however, i'm a little bit scared about capabilities of
> ZoDB, when compared with f. e. Firebird. 
> How much instances is Zodb able to handle? Under "handle" I mean "in real
> time", not "theoretically". I'd like to use it for dynamic portal with
> about 2000 - 3000 UIP / day. 
> 
> And, how is it with stability and crash recovery? I can't find some more
> sources about zodb, when there are some other sources then those on Zope,
> please tell me. Or, please tell me if you knew some better odbms engine ^_^
> 
> Thanks, 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem When Unit Testing with PMock

2005-02-28 Thread steven
Peter,

I'm so sorry, the letter was originally wrote to Terry, not to you!
I guess Terry not very familar to unit testing because he said:

-- cut --
I am not familiar with pmock, but my impression is that mock objects
are
for objects that you may not have available, such as a connection to a
database or file or instance of an umimplemented class ;-).  For such
objects, the mock-ness consists in returning canned rather than actual
fetched or calculated answers.  Iterators, on the other hand, are
almost as
-- end --

and i just want to say, mocking object is a useful testing method , not
was telling a tutorial.  :-)


What you said about the overuse of the generic mock object is very
interesting. I did not think that before.  I believe that use generic
or customized mocks is a problem of balance, so we may call it Art :-)

Below is my code, you may look it to understand my original question
(sorry for the coding for i am totally a python newbie):

---
import unittest

from pmock import *

from mainctr import MainCtr



class MainCtrTest(unittest.TestCase):

def testProcess(self):

filePicker = MockFilePicker()

filePicker.expectedNextCalls = len(MockFilePicker.fns) + 1



rpt0 = "foo"

rpt1 = "bar"

(router0, router1) = (Mock(), Mock())

router0.expects(once()).feedIn(eq(MockFilePicker.fns))

router1.expects(once()).feedIn(eq(MockFilePicker.fns))

router0.expects(once()).deliver()

router1.expects(once()).deliver()


router0.expects(once()).getDeliveredSrcList().will(return_value(["fn0",
"fn2"]))

router1.expects(once()).getDeliveredSrcList().will(return_value([]))


router0.expects(once()).getDeliveryRpt().will(return_value(rpt0))


router1.expects(once()).getDeliveryRpt().will(return_value(rpt1))


routes = [router0, router1]

ctr = MainCtr(filePicker, routes)

ctr.process()

self.assertEquals(ctr.getProcessRpt(), [rpt0, rpt1])

filePicker.verify()

router0.verify()

router1.verify()



class MockFilePicker:

fns = ["f0", "f1", "f2"]

idx = 0

nextCalls = 0

resetCalls = 0

expectedResetCalls = 1

expectedNextCalls = 0

processedSet = set()

expectedProcessedSet = set(["fn0", "fn2"])

rememberProcessedCalls = 0

expectedRememberProcessedCalls = 1



def __iter__(self):

return self



def reset(self):

self.resetCalls += 1


def next(self):

self.nextCalls += 1

if self.idx < len(self.fns):

self.idx += 1

return self.fns[self.idx - 1]

else:

raise StopIteration



def processed(self, fn):

self.processedSet.add(fn)



def rememberProcessed(self):

self.rememberProcessedCalls += 1




def verify(self):

if self.nextCalls != self.expectedNextCalls:

raise Exception("nextCalls: " + str(self.nextCalls))

if self.resetCalls != self.expectedResetCalls:

raise Exception("resetCalls: " + str(self.resetCalls))

if self.processedSet != self.expectedProcessedSet:

 raise Exception("processedSet: " + str(self.processedSet))

if self.rememberProcessedCalls !=
self.expectedRememberProcessedCalls:
raise Exception("rememberProcessedCalls: " +
str(self.rememberProcessedCalls))


if __name__ == "__main__":

unittest.main()

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


Re: accessor/mutator functions

2005-02-28 Thread Thomas Lotze
Dan Sommers wrote:

> I think I'd add a change_temperature_to method that accepts the target
> temperature and some sort of timing information, depending on how the rest
> of the program and/or thread is structured.

But then you put application logic into a library function. Doing this
consistently leads to a monster of a library that tries to account for all
possible applications. Where does this leave the KISS principle?

> In the case of simply reading the current temperature, and not knowing
> what's inside that device driver, I'd still lean away from exposing a
> current temperature attribute directly.  I think part of my thinking comes
> from my old Pascal days, when it made me cringe to think that "x:=b;"
> might actually execute a subroutine rather than just copy some memory
> around.

Then you also avoid lists, dicts and, ironically, methods. Accessing
methods means to access a callable attribute, after all, with all the
stuff going on behind the scenes on attribute access.

-- 
Thomas


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


Re: Scoping issue with import

2005-02-28 Thread Carl Banks

James Stroud wrote:
> Say I have a module, we'll call it "my_imported_mod". It contains a
function
> in it that calls another function, "myfun". The "myfun" function is
in the
> module "my_main_mod", that imports "my_imported_mod".

[snip]

> How to rectify this with minimal code change? How to let imported
modules know
> about the namespace they are getting imported into? I do not want to
> restructure my code right now.
>
> Thanks in advance for help.


Change it so that my_imported_mod imports my_main_mod.  If A depends on
B, then A should import B, not the other way around.

If there's some good reason why B imports A despite this (and there
could be--say if myfun is some kind of a callback), then you should
probably pass myfun to the function in the imported module as an
argument.  If that's not practical, put myfun into a third module, and
have my_imported_mod import that.

If you want to live dangerously, you could do something like this from
my_main_mod:

   import my_imported_mod
   my_imported_mod.myfun = myfun

I don't recommend it, though, because my_imported_mod is no longer
self-contained (i.e., it's a module not modular).


-- 
CARL BANKS

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


Re: yield_all needed in Python

2005-02-28 Thread Andrew Dalke
On Mon, 28 Feb 2005 18:25:51 -0500, Douglas Alan wrote:
> While writing a generator, I was just thinking how Python needs a
> "yield_all" statement.  With the help of Google, I found a pre-existing
> discussion on this from a while back in the Lightweight Languages
> mailing list.  I'll repost it here in order to improve the chances of
> this enhancement actually happening someday.

You should also have looked for the responses to that. Tim Peter's
response is available from
  http://aspn.activestate.com/ASPN/Mail/Message/624273
as linked from
  http://aspn.activestate.com/ASPN/Mail/Message/python-dev/758572
Here is the most relevant parts.

   I'm not bothered -- this comes with the territory.  If/when
   full-fledged coroutines make it in too, people worried about that can
   use them instead.  Curious fact:  I *was* worried about the worst-case
   time aspects of "simple generators" in Icon years ago, but in practice
   never ever got burned by it. And rewriting stuff to use Icon
   co-expressions instead invariably resulted in messier code that ran
   significantly slower in virtually all cases, except for the ones I
   *contrived* to prove the O() difference.

   BTW, Python almost never worries about worst-case behavior, and people
   using Python dicts instead of, e.g., balanced trees, get to carry their
   shame home with them hours earlier each day  .

Andrew
[EMAIL PROTECTED]

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


Re: Why do descriptors (and thus properties) only work on attributes.

2005-02-28 Thread Steven Bethard
Antoon Pardon wrote:
Can anyone explain why descriptors only work when they are an attribute
to an object or class.  I think a lot of interesting things one can
do with descriptors would be just as interesting if the object stood
on itself instead of being an attribute to an other object.
Not sure what "stood on itself" really means, but if you just want to be 
able to have module-level properties, you can do something like:

py> class Module(object):
... oldimporter = __builtins__.__import__
... def __init__(self, *args):
... mod = self.oldimporter(*args)
... self.__dict__ = mod.__dict__
... p = property(lambda self: 42)
...
py> __builtins__.__import__ = Module
py> import __main__
py> __main__.p
42
py> __main__.p = 3
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: can't set attribute
where you replace module objects with a different object.  Note that 
this is also nasty since properties reside in the class, so all modules 
now share the same properties:

py> import sys
py> sys.p
42
py> sys.p = 13
Traceback (most recent call last):
  File "", line 1, in ?
AttributeError: can't set attribute
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Scoping issue with import

2005-02-28 Thread James Stroud
Say I have a module, we'll call it "my_imported_mod". It contains a function 
in it that calls another function, "myfun". The "myfun" function is in the 
module "my_main_mod", that imports "my_imported_mod".

The code of "my_main_mod" might look like this:
==
from my_imported_mod import *

def myfun():
  print "stuff"
==

the code of "my_imported_mod" might look like this:
==
def somefun():
  myfun()
==

When trying to execute the function somefun(), I get a
NameError: global name 'myfun' is not defined

How to rectify this with minimal code change? How to let imported modules know 
about the namespace they are getting imported into? I do not want to 
restructure my code right now.

Thanks in advance for help.

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


Re: accessor/mutator functions

2005-02-28 Thread Dan Sommers
On Mon, 28 Feb 2005 23:08:04 GMT,
Andrew Dalke <[EMAIL PROTECTED]> wrote:

> On Mon, 28 Feb 2005 15:50:22 -0500, Dan Sommers wrote:
>> The reason their code is so inflexible is that they've filled their
>> classes with boiler plate get/set methods.
>> 
>> Why do users of classes need such access anyway?  If my class performs
>> useful functions and returns useful results, no user of my class should
>> care about its attributes.  If I "have to" allow access to my attributes
>> in order that my users be happy, then I did something else wrong when I
>> designed the class and its public interface in the first place.

> Consider an interface to a temperature controller.  It will
> have several properties:

>   - current temperature (read only)
>   - target temperature (read/write)
>   - various tuning parameters that affect the rate of change,
>  stability, etc.; eg, lookup details on a PID controller

> These are properties of the temperature controller object.
> In Python these properties are traditionally mapped to attributes.
> Under languages that don't have a __getattr__/"property" mechanism
> for separating interface from implementation these are implemented
> via get/set accessor methods.

> It is very often useful to change the temperature setting of
> a controller over time.  Eg, a chemical protocol might say
> "warm from 50 to 80 over a period of 30 minutes, 1 degree
> per minute".

> In Python that might be written as:

>   temp_controller = TemperatureController("/dev/com3")
>   temp_controller.target = 50
>   print "Bringing reactor to", temp_controller.target
>   while 1:
> print "Current temperature is", temp_controller.current
> if abs(temp_controller.current - temp_controller.target) < 0.1:
>   break
> time.sleep(30)

>   raw_input("Insert sample and press the  key: ")

>   for temp in range(51, 81):
> print "Raising reactor temperature to", temp
> temp_controller.target = temp
> time.sleep(60)
> if abs(temp_controller.current - temp) > 0.1:
>   print "Variance too high!", temp_controller.current

>   print "DONE!"


> What's wrong with the use of attributes in this case and how
> would you write your interface?

I think I'd add a change_temperature_to method that accepts the target
temperature and some sort of timing information, depending on how the
rest of the program and/or thread is structured.  It might turn into two
or three methods, depending on whether I can afford to block while
waiting, or what kind of intermediate feedback and/or error handling I
want (or one method with some carefully chosen default arguments).  I
don't know how that device driver works, but it might look something
like this:

def change_temperature_to( self, target, seconds_between_checks ):
print 'target temperature:', target
tell_the_device_to_change( )
while 1:
current = read_the_temperature_from_the_device( )
print 'current temperature:', current
if abs( current - target ) < 0.1:
break
time.sleep( seconds_between_checks )

Obviously, that code is untested!  ;-)

In the case of simply reading the current temperature, and not knowing
what's inside that device driver, I'd still lean away from exposing a
current temperature attribute directly.  I think part of my thinking
comes from my old Pascal days, when it made me cringe to think that
"x:=b;" might actually execute a subroutine rather than just copy some
memory around.

I'm not saying that my applications *never* access my objects'
attributes directly, just that it's one of those things that raises at
least a yellow flag in my mind.

Regards,
Dan

-- 
Dan Sommers

Îâ à Îâ à c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


yield_all needed in Python

2005-02-28 Thread Douglas Alan
While writing a generator, I was just thinking how Python needs a
"yield_all" statement.  With the help of Google, I found a
pre-existing discussion on this from a while back in the Lightweight
Languages mailing list.  I'll repost it here in order to improve the
chances of this enhancement actually happening someday.  The original
poster from the LL mailing list seems mostly concerned with
algorithmic efficiency, while I'm concerned more about making my
programs shorter and easier to read.  The ensuing discussion on the LL
list talks about how yield_all would be somewhat difficult to
implement if you want to get the efficiency gain desired, but I don't
think it would be very difficult to implement if that goal weren't
required, and the goal were limited to just the expressive elegance:

 A Problem with Python's 'yield'

 * To: LL1 Mailing List <[EMAIL PROTECTED]>
 * Subject: A Problem with Python's 'yield'
 * From: Eric Kidd <[EMAIL PROTECTED]>
 * Date: 27 May 2003 11:15:20 -0400
 * Organization:
 * Sender: [EMAIL PROTECTED]

 I'm going to pick on Python here, but only because the example code will
 be short and sweet. :-) I believe several other implementations of
 generators have the same problem.

 Python's generator system, used naively, turns an O(N) tree traversal
 into an O(N log N) tree traversal:

   class Tree:
   def __init__(self, value, left=None, right=None):
   self.value = value
   self.left = left
   self.right = right

   def in_order(self):
   if self.left is not None:
   for v in self.left.in_order():
   yield v
   yield self.value
   if self.right is not None:
   for v in self.right.in_order():
   yield v

   t=Tree(2, Tree(1), Tree(3))
   for v in yield_bug.t.in_order():
   print v

 This prints:
   1
   2
   3

 Unfortunately, this snippet calls 'yield' 5 times, because the leaf
 values must be yielded twice on their way back up the tree.

 We can shorten the code--and make it run in O(N) time--by adding a new
 keyword to replace the "for v in ...: yield v" pattern:

   def in_order(self):
   if self.left is not None:
   yield_all self.left.in_order():
   yield self.value
   if self.right is not None:
   yield_all self.right.in_order():

 Interestingly enough, this allows you define notions such as
 "tail-recursive generation", and apply the usual bag of
 recursion-optimization techniques.

 Cheers,
 Eric

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


Re: accessor/mutator functions

2005-02-28 Thread Andrew Dalke
On Mon, 28 Feb 2005 15:50:22 -0500, Dan Sommers wrote:
> The reason their code is so inflexible is that they've filled their
> classes with boiler plate get/set methods.
> 
> Why do users of classes need such access anyway?  If my class performs
> useful functions and returns useful results, no user of my class should
> care about its attributes.  If I "have to" allow access to my attributes
> in order that my users be happy, then I did something else wrong when I
> designed the class and its public interface in the first place.

Consider an interface to a temperature controller.  It will
have several properties:

  - current temperature (read only)
  - target temperature (read/write)
  - various tuning parameters that affect the rate of change,
 stability, etc.; eg, lookup details on a PID controller

These are properties of the temperature controller object.
In Python these properties are traditionally mapped to attributes.
Under languages that don't have a __getattr__/"property" mechanism
for separating interface from implementation these are implemented
via get/set accessor methods.

It is very often useful to change the temperature setting of
a controller over time.  Eg, a chemical protocol might say
"warm from 50 to 80 over a period of 30 minutes, 1 degree
per minute".

In Python that might be written as:

  temp_controller = TemperatureController("/dev/com3")
  temp_controller.target = 50
  print "Bringing reactor to", temp_controller.target
  while 1:
print "Current temperature is", temp_controller.current
if abs(temp_controller.current - temp_controller.target) < 0.1:
  break
time.sleep(30)

  raw_input("Insert sample and press the  key: ")

  for temp in range(51, 81):
print "Raising reactor temperature to", temp
temp_controller.target = temp
time.sleep(60)
if abs(temp_controller.current - temp) > 0.1:
  print "Variance too high!", temp_controller.current

  print "DONE!"


What's wrong with the use of attributes in this case and how
would you write your interface?

Andrew
[EMAIL PROTECTED]

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


Re: ZoDB's capabilities

2005-02-28 Thread Calvin Spealman
I don't think you have anything to worry about. Consider that this is
exactly what ZODB was designed for. It is, after all, the database back-end
for Zope itself, which is just another (very good, some say) CMS.

Almad wrote:

> Hello,
> 
> I'm going to write a custom CMS. I'd like to use some odbms, as code is
> then much more cleaner...however, i'm a little bit scared about
> capabilities of ZoDB, when compared with f. e. Firebird.
> How much instances is Zodb able to handle? Under "handle" I mean "in real
> time", not "theoretically". I'd like to use it for dynamic portal with
> about 2000 - 3000 UIP / day.
> 
> And, how is it with stability and crash recovery? I can't find some more
> sources about zodb, when there are some other sources then those on Zope,
> please tell me. Or, please tell me if you knew some better odbms engine
> ^_^
> 
> Thanks,

-- 
 

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


Re: My C module crashes

2005-02-28 Thread Dima Dorfman
On 2005-02-28, Egil Moeller <[EMAIL PROTECTED]> wrote:
> I've written a C-module for Python, and it works as intended, but
> obviously does something wrong with its memmory management (refference
> counting), as it causes Python to segfault now and then (randomly,
> whey :S)

Have you tried compiling Python and your module with debugging
enabled? It might make the crash less random--or it might not help at
all, but it's probably worth a try. Running Python with debugging
enabled is a good idea anyway when developing extension modules.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to define a window's position (Tkinter)

2005-02-28 Thread Russell E. Owen
In article <[EMAIL PROTECTED]>,
 "Harlin Seritt" <[EMAIL PROTECTED]> wrote:

>I am trying to use the geometry() method with the toplevel window
>called root. I know that one can do the following:
>
>root.geometry('400x400+200+200')
>
>This will put the window in 200, 200 position with a size of 400x400.
>Now, I don't really want to set the size. I simply want to set the
>position of the window. I've tried this:
>
>root.geometry('200+200')
>
>However, this doesn't seem to work. What can I do to set the position
>of the window without actually setting the size?

You were almost there, but you need an initial "+":
root.geometry("+200+200").

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


Re: accessor/mutator functions

2005-02-28 Thread Carl Banks

[EMAIL PROTECTED] wrote:
> When I look at how classes are set up in other languages (e.g. C++),
I
> often observe the following patterns:
> 1) for each data member, the class will have an accessor member
> function (a Get function)
> 2) for each data member, the class will have a mutator member
function
> (a Set function)
> 3) data members are never referenced directly; they are always
> referenced with the accessor and mutator functions
>
> My questions are:
> a) Are the three things above considered pythonic?

No.  It's not good programming practice in C++, either.

If you have a class that's nothing but a big data structure, you ought
to use it as a data structure.  Writing accessor and mutator methods
for its fields is just doing a lot of work to accomplish nothing.

If you want to provide access to a certain occasional field, but you're
concerned about keeping the interface backwards-compatible, go ahead
and use them.  But try to observe the following rules of thumb:

1. Don't provide accessor or mutator function to every single member of
every single class you write.  Only provide accessor/mutator functions
if the accessor/mutator methods are a sensible and useful part of the
class's interface.

2. Don't think of these methods as accessors or mutators.  Instead,
think
of them as methods that access or mutate a certain abstract property of
the object that happens to be represented by a single member.

And, keep in mind that, since Python doesn't really have private data,
you don't have to worry about adding these functions to make debugging
easier.


> b) What are the tradeoffs of using getattr() and setattr() rather
than
> creating accessor and mutator functions for each data member?

Don't use getattr and setattr unless you have to construct the name of
the attribute at run time.  That's what they're for.


-- 
CARL BANKS

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


ZoDB's capabilities

2005-02-28 Thread Almad
Hello, 

I'm going to write a custom CMS. I'd like to use some odbms, as code is then
much more cleaner...however, i'm a little bit scared about capabilities of
ZoDB, when compared with f. e. Firebird. 
How much instances is Zodb able to handle? Under "handle" I mean "in real
time", not "theoretically". I'd like to use it for dynamic portal with
about 2000 - 3000 UIP / day. 

And, how is it with stability and crash recovery? I can't find some more
sources about zodb, when there are some other sources then those on Zope,
please tell me. Or, please tell me if you knew some better odbms engine ^_^

Thanks, 
-- 
Lukas "Almad" Linhart

[:: http://www.almad.net/ ::]
[:: Humans are too complicated to be described with words. ::]
[:: PGP/GNUPg key: http://www.almad.net/download/pubkey.asc ::]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Building Python with Tcl/Tk on Cygwin_NT-5.1

2005-02-28 Thread Jason Tishler
Dean,

On Mon, Feb 28, 2005 at 10:34:20AM -0800, Dean N. Williams wrote:
> I have a other Cygwin port question. It turns out that the auto-import
> for XtStrings an widgetClass didn't get resolved. This a similar
> auto-import resolving error that I got when trying to build Tcl/Tk. I
> ended up using the shared Tcl/Tk that came with Cygwin. But in this
> case I must be able to build my software. Can you tell me how to get
> around this problem? Or can you tell me which cygwin mail list to send
> my plea for help?

I recommend trying the main Cygwin list:

cygwin at cygwin dot com

> gcc -shared -Wl,--enable-auto-image-base  -o gplot gplot.o cgm.o ccgm.o 
> utils.o io.o carray.o devices.o hload.o emul.o tty.o ps.o cgmc.o 
> xws_cla.o xws_color.o xws_delim.o xws_marker.o xws_polygon.o 
> xws_polyline.o xws_setup.o xws_text.o drvcla.o-L/usr/X11R6/lib -lXp 
> -lXpm -lXaw -lXmu -lXext -lXt -lX11 /usr/lib/libm.a -lc
> Info: resolving _XtStrings by linking to __imp__XtStrings (auto-import)
> Info: resolving _widgetClass by linking to __imp__widgetClass (auto-import)

However, I also recommend providing more information than the above.

Jason

-- 
PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers
Fingerprint: 7A73 1405 7F2B E669 C19D  8784 1AFD E4CC ECF4 8EF6
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling external text-files (newb)

2005-02-28 Thread Peter Hansen
Andreas Winkler wrote:
I tried to have python call an external 'Word'-file,
and the read the whole text into a single string with
the following code:
[CODE]
source = raw_input('file path')
File = open('source', 'r')
S = input.read()
print S
[/CODE]
Anything inside quotation marks is just a string of
characters, not a reference to a variable.  You are
asking it to open a file named "source", not to open
the file whose name is in the variable called source.
In addition, you are assigning the return value from
open() to a variable named "File", but then you are
not using that variable but are trying to read from
a non-existent object called "input" instead.  You'll
see an error for that if you fix only the first
problem and try rerunning the code, before you fix
the second (which you should do, to learn more).
Use this instead:
  f = open(source, 'r')
  s = f.read()
  print s
-Peter
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling external text-files (newb)

2005-02-28 Thread Michael Hartl
There are two problems: (1) by quoting 'source', you refer to a string
literal, not the variable you defined via raw_input; (2) you have not
defined the variable 'input', so there's no way to call the 'read'
method on it.

Try this instead:

source_path = raw_input('file path: ')
s = open(source_path).read()
print s

The default behavior of 'open' includes 'r' implicitly.

You can also use the function 'file', which is a synonym for 'open':

s = file(source).read()

Be warned that using the same syntax when writing files is dangerous;
in that case you should create a file object and explicitly close it.

f = file('a_copy', 'w')
f.write(s)
f.close()

HTH,

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: Calling external text-files (newb)

2005-02-28 Thread Michael Hartl
There are two problems: (1) by quoting 'source', you refer to a string
literal, not the variable you defined via raw_input; (2) you have not
defined the variable 'input', so there's no way to call the 'read'
method on it.

Try this instead:

source_path = raw_input('file path: ')
s = open(source_path).read()
print s

The default behavior of 'open' includes 'r' implicitly.

You can also use the function 'file', which is a synonym for 'open':

s = file(source).read()

Be warned that using the same syntax when writing files is dangerous;
in that case you should create a file object and explicitly close it.

f = file('a_copy', 'w')
f.write(s)
f.close()

HTH,

Michael

--
Michael D. Hartl, Ph.D.
CTO, Quark Sports LLC
http://quarksports.com/

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


Re: Pythonwin: Red squiggley underline and syntax error

2005-02-28 Thread Colin J. Williams
Steven Bethard wrote:
Brent W. Hughes wrote:
I copied and pasted some text into my Python code and then Pythowin 
put a red squiggley underline under the two tabs at the beginning of 
the line. What does that mean?  I've tried various things including 
deleting the white space in front of the line and reinserting the 
tabs.  I've also tried retyping the entire line.  Sometimes, I can get 
the red line to go away but when I try to run the program, it gives me 
a syntax error on the line that had the red underline.  Help!

You've probably mixed tabs with spaces in your indentation somewhere. 
Either replace all tabs with spaces or replace all spaces with tabs.

STeVe
The former is generally recommended.
Colin W.
--
http://mail.python.org/mailman/listinfo/python-list


Calling external text-files (newb)

2005-02-28 Thread Andreas Winkler
Hi
I tried to have python call an external 'Word'-file,
and the read the whole text into a single string with
the following code:
[CODE]
source = raw_input('file path')

File = open('source', 'r')
S = input.read()

print S
[/CODE]

But when I try to run it, it raises the following
error:

File = open('sorce', 'r')
IOError: [Errno 2] No such file or directory: 'sorce'

Is it something I am mimssing, or does python require
a special form of path?

Thanks in advance
Fred\\






___ 
Gesendet von Yahoo! Mail - Jetzt mit 250MB Speicher kostenlos - Hier anmelden: 
http://mail.yahoo.de
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question

2005-02-28 Thread Alan Gauld
On Mon, 28 Feb 2005 16:17:03 +0200, "Ryan White"
<[EMAIL PROTECTED]> wrote:

> How do I display an image in Python? - I've run over Tkinter, but obviously
> in all the wrong places.

Someone else suggested PIL.

But in Tkinter you create a PhotoImage object then insert it into
either a Canvas or a Text widget.

> Any help or sample code would be much appreciated.

If you find the file hmgui.zip on Useless Python you will find
the code for my games framework with an example Hangman game in
Tkinter. It includes the display of a set of images(the hanged
man)

HTH,

Alan G.
Author of the Learn to Program website
http://www.freenetpages.co.uk/hp/alan.gauld
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string methods (warning, newbie)

2005-02-28 Thread TZOTZIOY
On Sun, 27 Feb 2005 18:12:17 -0700, rumours say that Steven Bethard
<[EMAIL PROTECTED]> might have written:

[snip Nick Coghlan's list comprehension]

[STeVe]
>On the other hand, filter doesn't do the same thing:
>
>py> s = u'The Beatles - help - 03 - Ticket to ride'
>py> filter(str.isalpha, s)
>Traceback (most recent call last):
>   File "", line 1, in ?
>TypeError: descriptor 'isalpha' requires a 'str' object but received a 
>'unicode'
>py> ''.join(c for c in s if c.isalpha())
>u'TheBeatleshelpTickettoride'

This works though:

.>> filter(type(s).isalpha, s)

-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: string methods (warning, newbie)

2005-02-28 Thread TZOTZIOY
On Sun, 27 Feb 2005 18:12:17 -0700, rumours say that Steven Bethard
<[EMAIL PROTECTED]> might have written:

[snip Nick Coghlan's list comprehension]

[STeVe]
>On the other hand, filter doesn't do the same thing:
>
>py> s = u'The Beatles - help - 03 - Ticket to ride'
>py> filter(str.isalpha, s)
>Traceback (most recent call last):
>   File "", line 1, in ?
>TypeError: descriptor 'isalpha' requires a 'str' object but received a 
>'unicode'
>py> ''.join(c for c in s if c.isalpha())
>u'TheBeatleshelpTickettoride'

This works though:

.>> filter(type(s).isalpha, s)

As a function just for clarity.
-- 
TZOTZIOY, I speak England very best.
"Be strict when sending and tolerant when receiving." (from RFC1958)
I really should keep that in mind when talking with people, actually...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why do descriptors (and thus properties) only work on attributes.

2005-02-28 Thread Dima Dorfman
On 2005-02-28, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> Op 2005-02-28, Diez B. Roggisch schreef <[EMAIL PROTECTED]>:
>> I still don't see how that is supposed to work for "a lot of interesting
>> things". Can you provide examples for one of these interesting things?
>
> Lazy evaluation where the value of something is calculated the first
> time it is needed but accessed from some storage if it is needed again.

I do this all the time. It's not very hard and doesn't require any
extra language support, but I would like for there to be an
authoritative list of type slots (autopromise_ops).

import operator

def promise(thunk):
x = []
def promised():
if not x:
x.append(thunk())
return x[0]
return promised

autopromise_ops = [x for x in dir(operator) if x.startswith('__')]
autopromise_ops += ['__getattribute__', '__call__', '__str__', '__repr__']
autopromise_ops += ['__getattr__', '__setattr__', '__delattr__']

def autopromise(thunk):
p = promise(thunk)
d = {}
for op in autopromise_ops:
def bindhack(op=op):
return lambda self, *a, **kw: getattr(p(), op)(*a, **kw)
d[op] = bindhack()
return type('autopromise', (), d)()

def test():

lis = []

def thunk():
lis.append('ran thunk')
return 'value'

s = autopromise(thunk)
p = s * 30
assert p == 'value' * 30
p = s * 10
assert p == 'value' * 10
assert lis == ['ran thunk']  # Just once

print 'autopromise sanity test passed'

An autopromise object is good almost everywhere the real one would be,
and usually the only way to tell the difference is to call id or type
on it. The main exception is when the thunk returns a builtin type
(like a string or int) and you want to pass it to a builtin function
that expects a particular type (this would also apply to Python
functions that break duck typing on purpose, but those would just be
getting the breakage they deserve).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cannot open file in write mode, no such file or directory

2005-02-28 Thread John Machin

[EMAIL PROTECTED] wrote:
> Kartic wrote:
> > > I'm having a problem where when trying to open a file in write
> mode,
> > I
> > > get an IOError stating no such file or directory.  I'm calling an
> > > external program which takes an input file and produces an output
> > file
> > > repeatedly, simulating the input file separately for each
> replicate.
> > > The error occurs when trying to open the input file to write out
> the
> > > new data.  The problem is difficult to reproduce since it only
> shows
> > up
> > > once every few thousand replicates.  I've tried using both
> os.system
> >
> > I am afraid you need to give more information that just IOError,
> > calling an external program.
> >
> > Please post the exact message including the input filename at the
> time
> > the program went down. If you don't print the filename, please
modify
> > your program to do so.
> >
> > A shot in the dark solution to your problem might be that you are
> > dynamically  generating a filename and that filename probably
> contains
> > characters not allowed by the local file system OR you generate a
> path
> > that does not exist. For open() to work with the 'w' flag, the path
> > where the file you say should be created should exist.
> >
> > Thanks,
> > -Kartic
>
> Sorry, here is the exact error:
>
> Traceback (most recent call last):
>  File "hapSim.py", line 415, in ?
>run(REPLICATES, dsSelection, permuteStatus, sigThreshold
>  File "hapSim.py", line 354, in run
>createInput(dt)
>  File "hapSim.py", line 178, in createInput
>inF = open(IN_FNAME, "w")
> IOError: [Errno 2] No such file or directory: 'prog.input'
>
> I am using the same file name repeatedly, it works fine the first few
> thousand times, but eventually gives this error.

1. Exactly how many is "few thousand"? Is it the same number each time?
Does the problem still happen if you don't run the external program,
but just create the input file a few thousand times?

2. Which version of Windows are you using, and what type of filesystem?
When it dies, how many files exist in the directory where you are
trying to create "prog.input"? Reason for asking: I vaguely recall
problems with FAT-type filesystems where there was a rather low limit
on the number of files that could be recorded in a directory, PLUS a
rather misleading "errno" being returned when one hit the limit.

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


Re: naming convention for scalars, lists, dictionaries ...

2005-02-28 Thread Jack Diederich
On Mon, Feb 28, 2005 at 09:41:37PM +0100, Just wrote:
> In article <[EMAIL PROTECTED]>,
>  Jack Diederich <[EMAIL PROTECTED]> wrote:
> 
> > On Mon, Feb 28, 2005 at 04:02:37PM -0500, Benji York wrote:
> > > Jack Diederich wrote:
> > > >Ditto for me, plural implies list and singular implies instance, 
> > > >for (contact) in contacts:
> > > >   # do something with contact
> > > 
> > > May I ask why you place the parenthesis in the for statement?
> > 
> > I like the tuple-ness feel of it and frequently unpack multiple
> > values in for loops.  I also like the visual feel, it makes it
> > easy to see what is being unpacked and what is the source.
> > 
> > "for (one, two, three) in somelist:"
> > versus
> > "for one, two, three in sometlist:"
> > 
> > Even with a colorizing editor (emacs) I find the first version
> > easier to read.  YMMV.
> 
> But you're using it for _single_ values. That's like writing
> 
>   (val) = someFunction(...)

Your Milage May^H^H^HDoes Vary *wink*
A quick grep of my source shows zero unparenthesized for loops,
266 with multiple unpacks and 492 iterating over single values.
Actually a bit closer to even, 96 are 'for (i) in range(len(l)):'
that were written before enumerate() came about.

I just always use parenthesis in for loops and when creating/upacking
tuples.  I find it easier to read, except in the '(var) = func()' case.
Other people never use them. *shrug* I find this impossible to get
worked up about.  What other people do in the privacy of their own
codebase doesn't bother me one bit.

My $0.01 bits,

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


Re: String Replace Problem...

2005-02-28 Thread Steven Bethard
Sean McIlroy wrote:
f = lambda x: (x[0]=='@' and x[6:] + '.0') or (x=='/' and x + '\n') or
x
See "Inappropriate use of Lambda" in 
http://www.python.org/moin/DubiousPython.

You're creating a named function, so there's no reason to use the 
anonymous function syntax.  Try:

def f(x):
return (x[0]=='@' and x[6:] + '.0') or (x=='/' and x + '\n') or x
or if it must be on one line:
def f(x): return (x[0]=='@' and x[6:] + '.0') or (x=='/' and x + '\n') or x
Personally, I would probably write this as IMHO more readable:
infile, outfile = open("Errors.txt"), open("Errors_2.txt")
for i, line in enumerate(infile):
permx, atpermx, rest = line.split(None, 2)
outfile.write('  '.join([permx, str(parameter_values[i]), rest]))
In action:
py> s = """\
...   'PERMX'  @PERMX1  1 34  1  20  1 6
...   'PERMX'  @PERMX2  1 34  21 41  1 6
...   'PERMX'  @PERMX3  1 34  1  20  7 14
...   'PERMX'  @PERMX4  1 34  21 41  7 14
...   'PERMX'  @PERMX5  1 34  1  20 15 26
...   'PERMX'  @PERMX6  1 34  21 41 15 26
...   'PERMX'  @PERMX7  1 34  1  20 27 28
...   'PERMX'  @PERMX8  1 34  21 41 27 28
...   'PERMX'  @PERMX9  1 34  1  20 29 34
...   'PERMX'  @PERMX10  1 34  21 41 29 34
...   'PERMX'  @PERMX11  1 34  1  20 35 42
...   'PERMX'  @PERMX12  1 34  21 41 35 42
...   'PERMX'  @PERMX13  1 34  1  20 43 53
...   'PERMX'  @PERMX14  1 34  21 41 43 53
...   'PERMX'  @PERMX15  1 34  1  20 54 61
...   'PERMX'  @PERMX16  1 34  21 41 54 61
... """
py> parameter_values = range(1, 17)
py> for i, line in enumerate(s.splitlines()):
... permx, atpermx, rest = line.split(None, 2)
... print '  '.join([permx, str(parameter_values[i]), rest])
...
'PERMX'  1  1 34  1  20  1 6
'PERMX'  2  1 34  21 41  1 6
'PERMX'  3  1 34  1  20  7 14
'PERMX'  4  1 34  21 41  7 14
'PERMX'  5  1 34  1  20 15 26
'PERMX'  6  1 34  21 41 15 26
'PERMX'  7  1 34  1  20 27 28
'PERMX'  8  1 34  21 41 27 28
'PERMX'  9  1 34  1  20 29 34
'PERMX'  10  1 34  21 41 29 34
'PERMX'  11  1 34  1  20 35 42
'PERMX'  12  1 34  21 41 35 42
'PERMX'  13  1 34  1  20 43 53
'PERMX'  14  1 34  21 41 43 53
'PERMX'  15  1 34  1  20 54 61
'PERMX'  16  1 34  21 41 54 61
STeVe
--
http://mail.python.org/mailman/listinfo/python-list


Re: accessor/mutator functions

2005-02-28 Thread Dan Sommers
On 28 Feb 2005 10:30:03 GMT,
Nick Craig-Wood <[EMAIL PROTECTED]> wrote:

> Actually I would say just access the attribute directly for both get
> and set, until it needs to do something special in which case use
> property().

> The reason why people fill their code up with boiler plate get/set
> methods is to give them the flexibility to change the implementation
> without having to change any of the users.  In python you just swap
> from direct attribute access to using property().

The reason their code is so inflexible is that they've filled their
classes with boiler plate get/set methods.

Why do users of classes need such access anyway?  If my class performs
useful functions and returns useful results, no user of my class should
care about its attributes.  If I "have to" allow access to my attributes
in order that my users be happy, then I did something else wrong when I
designed the class and its public interface in the first place.

I usually aim for this:  if users of the public interface of my class
can figure out that I changed the implementation, then I've exposed too
much.  Sure there are exceptions, but that's my basic thought process.

Sorry about the rant.

Regards,
Dan

-- 
Dan Sommers

Îâ à Îâ à c = 1
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: naming convention for scalars, lists, dictionaries ...

2005-02-28 Thread Just
In article <[EMAIL PROTECTED]>,
 Jack Diederich <[EMAIL PROTECTED]> wrote:

> On Mon, Feb 28, 2005 at 04:02:37PM -0500, Benji York wrote:
> > Jack Diederich wrote:
> > >Ditto for me, plural implies list and singular implies instance, 
> > >for (contact) in contacts:
> > >   # do something with contact
> > 
> > May I ask why you place the parenthesis in the for statement?
> 
> I like the tuple-ness feel of it and frequently unpack multiple
> values in for loops.  I also like the visual feel, it makes it
> easy to see what is being unpacked and what is the source.
> 
> "for (one, two, three) in somelist:"
> versus
> "for one, two, three in sometlist:"
> 
> Even with a colorizing editor (emacs) I find the first version
> easier to read.  YMMV.

But you're using it for _single_ values. That's like writing

  (val) = someFunction(...)

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


Re: Working with dbase files

2005-02-28 Thread Larry Bates
On MS Windows use built in ODBC support to xBase files
which supports read and write access.

Larry Bates

Stan Cook wrote:
> Does anyone know how I can access and read data from a dbase (.dbf) file?
> 
> Regards,
> 
> Stan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cannot open file in write mode, no such file or directory

2005-02-28 Thread Kartic
Could you please post your entire program, if possible?

Thanks!

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


Re: My C module crashes

2005-02-28 Thread John Machin

Egil Moeller wrote:
> Hi!
>
> I've written a C-module for Python, and it works as intended, but
> obviously does something wrong with its memmory management
(refference
> counting), as it causes Python to segfault now and then (randomly,
> whey :S)
>
> The module source code is available at
> http://grimoire.takeit.se/files/CReader.c
>
> The code isn't _that_ long, so someone experienced with writing
Python C
> modules should probably not have that hard a time finding what I do
> wrong :)

What you are doing wrong:

1. Unless getting the source to/from a web page has stuffed up the
indentation [which you should have checked before posting your
message], it appears to be indented only ONE space per level. Are you
using tabs? Don't. They are intrinsically evil.

2. Your code's over 1200 lines long, and even after allowing for the
indentation problem it certainly doesn't read like the poetry of your
namesake, Skalla-Grim's son.

3. Expecting people to debug your code remotely when it exhibits
problems (1) and (2)

4. Not stating what (if anything) you have tried yourself before
posting.

5. Using system free() and realloc() instead the Python-supplied memory
API functions.

6. Using *ANY* free() or realloc() function on memory that has *NOT*
been allocated with the allocator function from the same family.

7. Not checking whether a buffer has even been allocated before trying
to deallocate it.

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


Re: naming convention for scalars, lists, dictionaries ...

2005-02-28 Thread Jack Diederich
On Mon, Feb 28, 2005 at 04:02:37PM -0500, Benji York wrote:
> Jack Diederich wrote:
> >Ditto for me, plural implies list and singular implies instance, 
> >for (contact) in contacts:
> >   # do something with contact
> 
> May I ask why you place the parenthesis in the for statement?

I like the tuple-ness feel of it and frequently unpack multiple
values in for loops.  I also like the visual feel, it makes it
easy to see what is being unpacked and what is the source.

"for (one, two, three) in somelist:"
versus
"for one, two, three in sometlist:"

Even with a colorizing editor (emacs) I find the first version
easier to read.  YMMV.

-Jack

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


Decimal, __radd__, and custom numeric types...

2005-02-28 Thread Blake T. Garretson
I'm having some issues with decimal.Decimal objects playing nice with
custom data types.  I have my own matrix and rational classes which
implement __add__ and __radd__.  They know what to do with Decimal
objects and react appropriately.

The problem is that they only work with Decimals if the custom type is
on the left (and therefore __add__ gets called), but NOT if the Decimal
is on the left.  The Decimal immediately throws the usual "TypeError:
You can interact Decimal only with int, long or Decimal data types."
without even trying my __radd__ method to see if my custom type can
handle Decimals.

>From the Python docs (specifically sections 3.3.7 and 3.3.8), I thought
that the left object should try its own __add__, and if it doesn't know
what to do, THEN try the right object's __radd__ method.  I guess
Decimal objects don't do this?  Is there a way to change this behavior?
 If Decimal objects prematurely throw a TypeError before trying the
__rop__, is Decimal broken, or was it designed this way?  I think I'm
missing something...

Thanks,
Blake

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


Re: Controlling Pc From Server?

2005-02-28 Thread Larry Bates
What you are asking IS much more difficult that just "timing".
The Internet is a disconnected stateless medium.  I can open
a browser to a site and just leave my browser open.  Am I viewing
that site or not?  There's no way to know.  I might have minimized
the browser window and am back doing productive work (assuming
my access to the web was non-productive).

The best way I've found to do what you want is to force all
HTTP traffic through a proxy (I like Squid, but others
work as well).  The proxy cache logs can provide you with
lost of information about where people are going and how much
information they download from the site.  They cannot however
tell you how long someone was there because of what I mentioned
above.  You can see if someone is going to www.nascar.com or
www.espn.com or to some other site.  You can also block sites
quite easily if there is no legitimate reason for people to
be at that site.

Hope info helps.
Larry Bates

[EMAIL PROTECTED] wrote:
> Hello Kartic & NG,
> 
>  Thank you for your prompt answer. In effect, I'm trying to work on
> a NT network of 6 PC (plus the server). Sorry to not have been clearer.
> Ideally, I'm trying to monitor the Internet activity of each client (PC)
> on this network (but I'm not a boss trying to control my emplyees, I'm just
> curious on it). I would like to know which PC is connected to Internet (by
> starting something like a "timer" for every PC, and then periodically check
> if a particular PC is connected or not). This should be done from the main
> server. 
> Did I make myself clear? Do you think it would be a huge task?
> 
> Sorry, it may be a very basic question, but thank you for your help.
> 
> Andrea.
> 
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


canvassing for assistance

2005-02-28 Thread Sean McIlroy
Hi all!

I've written a utility for making diagrams. It could also be a good
environment for experimenting with a Tk canvas, so I'm including the
code here (see below). The problem is that, when I save a canvas and
include the resulting postscript file in a LaTeX document, I often
find that the right edge of the canvas has been cut off and/or that
there's a bunch of extra space at the bottom that forces the picture
to take up a whole page just by itself. The Introduction to Tkinter
lists a bunch of options for the Canvas postscript method, but it
doesn't say anything about the semantics of any of them, and there are
several that sound like they could be what I need. So, if anybody
knows how to exercise finer control over the Canvas postscript method,
I'd be grateful to hear about it.

Peace,
STM


###
## FRESH SHELL: import canvasser
## (so that text can be copied from the shell)
###

pencil = 1
eraser = 10
color = 'black'

def save():
from tkSimpleDialog import askstring
filename = askstring('save diagram','enter name of diagram: ') +
'.eps'

canvas.postscript(file=filename,width=100,height=100,pagewidth=100,pageheight=100)

def circle(x,y,radius=25,color=None): 
r = radius
return canvas.create_oval(x-r,y-r,x+r,y+r,fill=color)

#

__P__ = None
__I__ = None

def draw(event):   
global __P__
Q = [event.x,event.y]
canvas.create_line(__P__[0],__P__[1],Q[0],Q[1],width=pencil,fill=color)
__P__ = Q
   
def erase(event):
r = eraser
x,y = event.x,event.y
for x in canvas.find_overlapping(x-r,y-r,x+r,y+r):
canvas.delete(x)

def carry(event):
if __I__==None: return
C = canvas.coords(__I__)
x,y = event.x,event.y
if len(C)==2: canvas.coords(__I__,x,y)
else:
a,b = C[:2]
f = lambda i: ( i%2 and [y-b] or [x-a] ) [0]
D = [x,y] + [C[i] + f(i) for i in range(2,len(C))]
canvas.coords(__I__,*D)

def scale(event):
C = canvas.coords(__I__)
if len(C)<>4: return
canvas.coords(__I__,C[0],C[1],event.x,event.y)

def point(event):
codeArea.insert(INSERT,str(event.x) + ',' + str(event.y))

def item(event):
codeArea.insert(INSERT,str(canvas.find_closest(event.x,event.y)[0]))
  
def mouseDown(event):
global __P__,__I__
m = mode.get()
if   m==0: __P__ = [event.x,event.y]
elif m==2: point(event)
elif m==3: item(event)
elif m>=4: __I__ = canvas.find_closest(event.x,event.y)

def mouseDrag(event):
m = mode.get()
if   m==0: draw(event)
elif m==1: erase(event)
elif m==4: carry(event)
elif m==5: scale(event)

def mouseUp(event): 
global __P__,__I__
__P__ = None
__I__ = None

def runCode(dummy):
x = codeArea.get()
y = [i for i in range(len(x)) if x[i]=='=' and
x[:i].count('(')==0]
z = y and x[:y[0]] + '=' + x[y[0]+1:] or x
print '>>> ' + z
try: exec z in globals() 
except: print 'ERROR'
codeArea.delete(0,END)

from Tkinter import *
print '*'*80
print 'REMINDER: canvas; pencil,eraser,color; save,circle'
print '*'*80 
root = Tk()
canvas = Canvas(root,background='white')
canvas.bind('',mouseDown)
canvas.bind('',mouseDrag)
canvas.bind('',mouseUp)
canvas.pack(side=TOP,expand=1,fill=BOTH)
codeArea = Entry(root,font=6)
codeArea.pack(side=TOP,expand=1,fill=X)
codeArea.bind('',runCode)
ctrl = Frame(root)
mode = IntVar()
Radiobutton(ctrl,indicatoron=0,variable=mode,value=0,text='draw').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=1,text='erase').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=2,text='point').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=3,text='item').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=4,text='carry').pack(side=LEFT)
Radiobutton(ctrl,indicatoron=0,variable=mode,value=5,text='scale').pack(side=LEFT)
ctrl.pack(side=TOP,pady=10)
root.title('canvasser')
root.mainloop()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cannot open file in write mode, no such file or directory

2005-02-28 Thread haynesc
Kartic wrote:
> > I'm having a problem where when trying to open a file in write
mode,
> I
> > get an IOError stating no such file or directory.  I'm calling an
> > external program which takes an input file and produces an output
> file
> > repeatedly, simulating the input file separately for each
replicate.
> > The error occurs when trying to open the input file to write out
the
> > new data.  The problem is difficult to reproduce since it only
shows
> up
> > once every few thousand replicates.  I've tried using both
os.system
>
> I am afraid you need to give more information that just IOError,
> calling an external program.
>
> Please post the exact message including the input filename at the
time
> the program went down. If you don't print the filename, please modify
> your program to do so.
>
> A shot in the dark solution to your problem might be that you are
> dynamically  generating a filename and that filename probably
contains
> characters not allowed by the local file system OR you generate a
path
> that does not exist. For open() to work with the 'w' flag, the path
> where the file you say should be created should exist.
>
> Thanks,
> -Kartic

Sorry, here is the exact error:

Traceback (most recent call last):
 File "hapSim.py", line 415, in ?
   run(REPLICATES, dsSelection, permuteStatus, sigThreshold
 File "hapSim.py", line 354, in run
   createInput(dt)
 File "hapSim.py", line 178, in createInput
   inF = open(IN_FNAME, "w")
IOError: [Errno 2] No such file or directory: 'prog.input'

I am using the same file name repeatedly, it works fine the first few
thousand times, but eventually gives this error.

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


Re: naming convention for scalars, lists, dictionaries ...

2005-02-28 Thread Benji York
Jack Diederich wrote:
Ditto for me, plural implies list and singular implies instance, 
for (contact) in contacts:
   # do something with contact
May I ask why you place the parenthesis in the for statement?
--
Benji
--
http://mail.python.org/mailman/listinfo/python-list


Re: cannot open file in write mode, no such file or directory

2005-02-28 Thread Steve Holden
Kartic wrote:
I'm having a problem where when trying to open a file in write mode,
I
get an IOError stating no such file or directory.  I'm calling an
external program which takes an input file and produces an output
file
repeatedly, simulating the input file separately for each replicate.
The error occurs when trying to open the input file to write out the
new data.  The problem is difficult to reproduce since it only shows
up
once every few thousand replicates.  I've tried using both os.system

I am afraid you need to give more information that just IOError,
calling an external program.
Please post the exact message including the input filename at the time
the program went down. If you don't print the filename, please modify
your program to do so.
A shot in the dark solution to your problem might be that you are
dynamically  generating a filename and that filename probably contains
characters not allowed by the local file system OR you generate a path
that does not exist. For open() to work with the 'w' flag, the path
where the file you say should be created should exist.
Another low-probability cause is that you are trying to create files in 
a non-existent directory.

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


Re: cannot open file in write mode, no such file or directory

2005-02-28 Thread Kartic
> I'm having a problem where when trying to open a file in write mode,
I
> get an IOError stating no such file or directory.  I'm calling an
> external program which takes an input file and produces an output
file
> repeatedly, simulating the input file separately for each replicate.
> The error occurs when trying to open the input file to write out the
> new data.  The problem is difficult to reproduce since it only shows
up
> once every few thousand replicates.  I've tried using both os.system

I am afraid you need to give more information that just IOError,
calling an external program.

Please post the exact message including the input filename at the time
the program went down. If you don't print the filename, please modify
your program to do so.

A shot in the dark solution to your problem might be that you are
dynamically  generating a filename and that filename probably contains
characters not allowed by the local file system OR you generate a path
that does not exist. For open() to work with the 'w' flag, the path
where the file you say should be created should exist.

Thanks,
-Kartic

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


Re: String Replace Problem...

2005-02-28 Thread Sean McIlroy
I can't claim to have studied your problem in detail, but I get
reasonable results from the following:

filename = 'Errors.txt'
S = open(filename,'r').read().split()
f = lambda x: (x[0]=='@' and x[6:] + '.0') or (x=='/' and x + '\n') or
x
open(filename,'w').write(' '.join(map(f,S)))

HTH

-


[EMAIL PROTECTED] wrote in message news:<[EMAIL PROTECTED]>...
> Hello NG,
> 
>   probably this is a basic question, but I'm going crazy... I am unable
> to find an answer. Suppose that I have a file (that I called "Errors.txt")
> which contains these lines:
> 
> MULTIPLY
>   'PERMX'  @PERMX1  1 34  1  20  1 6 /
>   'PERMX'  @PERMX2  1 34  21 41  1 6 /
>   'PERMX'  @PERMX3  1 34  1  20  7 14/
>   'PERMX'  @PERMX4  1 34  21 41  7 14/
>   'PERMX'  @PERMX5  1 34  1  20 15 26/
>   'PERMX'  @PERMX6  1 34  21 41 15 26/
>   'PERMX'  @PERMX7  1 34  1  20 27 28/
>   'PERMX'  @PERMX8  1 34  21 41 27 28/
>   'PERMX'  @PERMX9  1 34  1  20 29 34/
>   'PERMX'  @PERMX10  1 34  21 41 29 34/
>   'PERMX'  @PERMX11  1 34  1  20 35 42/
>   'PERMX'  @PERMX12  1 34  21 41 35 42/
>   'PERMX'  @PERMX13  1 34  1  20 43 53/
>   'PERMX'  @PERMX14  1 34  21 41 43 53/
>   'PERMX'  @PERMX15  1 34  1  20 54 61/
>   'PERMX'  @PERMX16  1 34  21 41 54 61/
> /
> 
> I would like to replace all the occurrencies of the "keywords" (beginning
> with the @ (AT) symbol) with some floating point value. As an example, this
> is what I do:
> 
> #  --- CODE BEGIN
> 
> import re
> import string
> 
> # Set Some Dummy Parameter Values
> parametervalues = range(1, 17)
> 
> # Open And Read The File With Keywords
> fid = open("Errors.txt","rt")
> onread = fid.read()
> fid.close()
> 
> # Find All Keywords Starting with @ (AT)
> regex = re.compile("[EMAIL PROTECTED]", re.IGNORECASE)
> keywords = regex.findall(onread)
> 
> counter = 0
> 
> # Try To Replace The With Floats
> for keys in keywords:
> pars = parametervalues[counter]
> onread = string.replace(onread, keys, str(float(pars)))
> counter = counter + 1
> 
> # Write A New File With Replaced Values
> fid = open("Errors_2.txt","wt")
> fid.write(onread)
> fid.close()
> 
> #  --- CODE END
> 
> 
> Now, I you try to run this little script, you will see that for keywords
> starting from "@PERMX10", the replaced values are WRONG. I don't know why,
> Python replace only the "@PERMX1" leaving out the last char of the keyword
> (that are 0, 1, 2, 3, 4, 5, 6 ). These values are left in the file and I
> don't get the expected result.
> 
> Does anyone have an explanation? What am I doing wrong?
> 
> Thanks to you all for your help.
> 
> Andrea.
> 
> --
>  Message for the recipient only, if received in error, please notify the
> sender and read http://www.eni.it/disclaimer/
-- 
http://mail.python.org/mailman/listinfo/python-list


cannot open file in write mode, no such file or directory

2005-02-28 Thread haynesc
Hi,

I'm having a problem where when trying to open a file in write mode, I
get an IOError stating no such file or directory.  I'm calling an
external program which takes an input file and produces an output file
repeatedly, simulating the input file separately for each replicate.
The error occurs when trying to open the input file to write out the
new data.  The problem is difficult to reproduce since it only shows up
once every few thousand replicates.  I've tried using both os.system
and os.popen to invoke the external program.  Originally I was running
this on cygwin, but also tried under windows.

I'm confused as to why the error would state no such file when opening
in write mode, it should just create the file if it can't find it.  I
imagine it has something to do with the external program (its mostly
likely not written very well), but I'm hoping theres a solution to this
that doesn't involve modifying that program.  Is it possible that the
file isn't being closed properly?  If so, how can I ensure it is
available?

Thanks

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


Re: Pythonwin: Red squiggley underline and syntax error

2005-02-28 Thread Steven Bethard
Brent W. Hughes wrote:
I copied and pasted some text into my Python code and then Pythowin put a 
red squiggley underline under the two tabs at the beginning of the line. 
What does that mean?  I've tried various things including deleting the white 
space in front of the line and reinserting the tabs.  I've also tried 
retyping the entire line.  Sometimes, I can get the red line to go away but 
when I try to run the program, it gives me a syntax error on the line that 
had the red underline.  Help!
You've probably mixed tabs with spaces in your indentation somewhere. 
Either replace all tabs with spaces or replace all spaces with tabs.

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


Re: naming convention for scalars, lists, dictionaries ...

2005-02-28 Thread Jack Diederich
On Mon, Feb 28, 2005 at 11:32:22AM -0700, Steven Bethard wrote:
> [EMAIL PROTECTED] wrote:
> >Since Python does not have declarations, I wonder if people think it is
> >good to name function arguments according to the type of data structure
> >expected, with names like "xlist" or "xdict".
> 
> In general, I find that naming collections for their contents is much 
> more useful than some abbreviated type prefix.  However, while I don't 
> name objects by their type, I do tend to name iterables with plurals 
> (e.g. "words", "feature_indices", "events", etc.) and I typically suffix 
> mapping types with "map" (e.g. "word_index_map", "event_relation_map", 
> "prime_factor_map", etc.)
> 
Ditto for me, plural implies list and singular implies instance, 
for (contact) in contacts:
   # do something with contact

But I tend to name dictionaries as "key_to_value" as in 
"email_to_contact" or "ip_to_hostname."  

for (email) in emails:
  contact = email_to_contact[email]
  # do something with contact

It may seem verbose but I can type much faster than I can think and 
it makes reading even forgotten code a breeze.

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


Re: Explicit or general importing of namespaces?

2005-02-28 Thread Paul Rubin
Peter Hansen <[EMAIL PROTECTED]> writes:
> Ultimately more important than mere "pollution" are the
> latent problems this can cause if any of the names in
> the original module can ever be re-bound.

You know, this is another reason the compiler really ought to (at
least optionally) check for such shadowing and have a setting to
enforce user declarations, like perl's "use strict".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question

2005-02-28 Thread Terry Reedy

For future reference, an informative subject line like

> How do I display an image in Python?

is more likely to grab the attention of someone with the information 
sought.

tjr



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


Pythonwin: Red squiggley underline and syntax error

2005-02-28 Thread Brent W. Hughes
I copied and pasted some text into my Python code and then Pythowin put a 
red squiggley underline under the two tabs at the beginning of the line. 
What does that mean?  I've tried various things including deleting the white 
space in front of the line and reinserting the tabs.  I've also tried 
retyping the entire line.  Sometimes, I can get the red line to go away but 
when I try to run the program, it gives me a syntax error on the line that 
had the red underline.  Help!

Brent


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


module/import question

2005-02-28 Thread subopt
I'm trying to import Logilab's constraint module like this:

from logilab.constraint import *

from within a Python interactive session. The module is not installed
correctly on our system, and it won't be, so i adjusted my PYTHONPATH,
added an empty __init__.py file, then started up an interactive
session.
When i do the above import i get:

Traceback (most recent call last):
  File "", line 1, in ?
  File "/afs/big/long/freakin/path/to/dl/__init__.py",line 23,in ?

ImportError: No module named constraint.propagation

the first time i do it, then the 2nd time it succeeds w/o a complaint.
The adjustment to my PYTHONPATH var was to append :

afs/big/long/freakin/path/to/dl

to the previous value. Any idea what i'm doing wrong?

thanks in advance,
E

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


Re: best XSLT processor?

2005-02-28 Thread Paul Boddie
fanbanlo <[EMAIL PROTECTED]> wrote in message news:<[EMAIL PROTECTED]>...
> Which XSLT processor is the most reliable?
> 
> requirement:
> + must support Python 2.4
> + must run w/ Windows (and Linux)
> + not super slow

I've had success with libxslt [1] (and libxml2 [2]) on Linux with
Python 2.3.x and earlier, and I imagine that it's portable enough to
work successfully on Windows and has already been tested with Python
2.4. Moreover, I don't think many people complain about the
performance of libxslt/libxml2. ;-)

If you find the supplied Python bindings for libxml2 either
"un-Pythonic" or insufficiently DOM-like, you might want to try lxml
[3] or libxml2dom [4].

Paul

[1] http://xmlsoft.org/XSLT/
[2] http://www.xmlsoft.org/
[3] http://www.xml.com/cs/user/view/cs_msg/2280
[4] http://www.python.org/pypi?:action=display&name=libxml2dom
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python - what is the fastest database ?

2005-02-28 Thread Terry Reedy

<[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> How is it possible that google (super big database) is super fast?
> What type database do they use / software ?

On the hardware side, Google's secret is massively parallel cluster 
computing, coupled with proprietary software for splitting tasks and 
joining results.  They have perhaps 200,000 CPUs.  A query might be given 
to hundreds of them for a fraction of a second.

Terry J. Reedy



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


Re: naming convention for scalars, lists, dictionaries ...

2005-02-28 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
Since Python does not have declarations, I wonder if people think it is
good to name function arguments according to the type of data structure
expected, with names like "xlist" or "xdict".
In general, I find that naming collections for their contents is much 
more useful than some abbreviated type prefix.  However, while I don't 
name objects by their type, I do tend to name iterables with plurals 
(e.g. "words", "feature_indices", "events", etc.) and I typically suffix 
mapping types with "map" (e.g. "word_index_map", "event_relation_map", 
"prime_factor_map", etc.)

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


Re: Building Python with Tcl/Tk on Cygwin_NT-5.1

2005-02-28 Thread Dean N. Williams

Hi Jason,
   I have a other Cygwin port question. It turns out that the 
auto-import for XtStrings an widgetClass didn't get resolved. This a 
similar auto-import resolving error that I got when trying to build 
Tcl/Tk. I ended up using the shared Tcl/Tk that came with Cygwin. But in 
this case I must be able to build my software. Can you tell me how to 
get around this problem? Or can you tell me which cygwin mail list to 
send my plea for help?

Thanks and best regards,
   Dean
gcc -shared -Wl,--enable-auto-image-base  -o gplot gplot.o cgm.o ccgm.o 
utils.o io.o carray.o devices.o hload.o emul.o tty.o ps.o cgmc.o 
xws_cla.o xws_color.o xws_delim.o xws_marker.o xws_polygon.o 
xws_polyline.o xws_setup.o xws_text.o drvcla.o-L/usr/X11R6/lib -lXp 
-lXpm -lXaw -lXmu -lXext -lXt -lX11 /usr/lib/libm.a -lc
Info: resolving _XtStrings by linking to __imp__XtStrings (auto-import)
Info: resolving _widgetClass by linking to __imp__widgetClass (auto-import)
>

P.S. "Platform Windows XP/Cygwin 1.5.1."
--
http://mail.python.org/mailman/listinfo/python-list


Re: naming convention for scalars, lists, dictionaries ...

2005-02-28 Thread Skip Montanaro

beliavsky> Since Python does not have declarations, I wonder if people
beliavsky> think it is good to name function arguments according to the
beliavsky> type of data structure expected, with names like "xlist" or
beliavsky> "xdict".

In general, no.  I think variable names should reflect what they are naming,
not their types.

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


naming convention for scalars, lists, dictionaries ...

2005-02-28 Thread beliavsky
Since Python does not have declarations, I wonder if people think it is
good to name function arguments according to the type of data structure
expected, with names like "xlist" or "xdict".

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


Re: bsddb for k, v in db.items(): do order the numbers ?

2005-02-28 Thread Steve Holden
Christopher De Vries wrote:
On Mon, Feb 28, 2005 at 08:30:59AM -0800, [EMAIL PROTECTED] wrote:
WHen I use the code below and printing all the results i get this:
--
0 1 10
11 2 3
4 5 6
7 8 9
--
But I want
--
0 1 2
3 4 5
6 7 8
9 10 11
--

If you want your key, value pairs in a certain order you have to sort them
yourself. Dictionaries and bsddb keys are unsorted.
Remember, also, that the keys are strings, so you'll need to convert 
them to numbers if you want them to sort numerically - otherwise "11" 
will come before "2".

regards
 Steve
--
Meet the Python developers and your c.l.py favorites March 23-25
Come to PyCon DC 2005  http://www.pycon.org/
Steve Holden   http://www.holdenweb.com/
--
http://mail.python.org/mailman/listinfo/python-list


Newbie question: Uninstalling Python Package Manager packages

2005-02-28 Thread Jeffrey A. Zelt
I am new to python, but am very enthusiastic about the language and 
hope to start using it for serious work soon (after I am more 
comfortable with all the details).

I have installed a package via the Python Package Manager program on 
Mac OS X 10.3 (http://www.python.org/packman/).

My question is:
How do I UNinstall the package?  Is there somewhere I can find what has 
been installed and where it was installed so I can delete the file(s) 
manually?  Or is there a simpler procedure to uninstall, similar to how 
the package manager performs the install?

Nothing horrible has occurred yet, but I feel uncomfortable installing 
something when I don't know where the files will end up, nor how to 
uninstall it.

Any help would be appreciated.  Thanks in advance.
Jeff
=
 Jeffrey A. Zelt
 [EMAIL PROTECTED]
 http://www.jeff.wave.no/
=
--
http://mail.python.org/mailman/listinfo/python-list


[ANN] PyAC 0.1.0

2005-02-28 Thread Premshree Pillai
PyAC 0.1.0 (http://sourceforge.net/projects/pyac/)

* ignores non-image files 
* optional arg is_ppt for ordering presentation images (eg.,
Powerpoint files exported as images)
* misc fixes

Package here: 
http://sourceforge.net/project/showfiles.php?group_id=106998&package_id=115396&release_id=309010

-- 
Premshree Pillai
http://www.livejournal.com/users/premshree/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie question -- fiddling with pictures.

2005-02-28 Thread Scott David Daniels
Ryan White wrote:
> Subject: Newbie question
Not a very good subject -- many people will not even look at it unless
you describe what your question is about.
I'm wanting to use python to display some jpeg images, maybe present them at
a percentage of their actual size etc.
How do I display an image in Python? - I've run over Tkinter, but obviously
in all the wrong places.
You probably want Fredrik Lundh's PIL (Python Imaging Library) package
to read and manipulate the images, and then use TKinter to display the
images.
--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Minor, but annoying legend problem in matplotlib

2005-02-28 Thread John Hunter
> "Jorl" == Jorl Shefner <[EMAIL PROTECTED]> writes:

Jorl>The obvious solution is to plot the lines and symbols in
Jorl> two different commands: ___


You want to explicitly pass the lines you want to legend into the
legend command, as in 

Symb= ['wo','ws','w^']
LineType= ['k-','k--','k-.']

leglines = []
for index,d in enumerate(DataSets):

plot(x,DataSets[index],LineType[index])
lines = plot(x,DataSets[index],Symb[index])
leglines.extend(lines)



legend(leglines, ["a","b","c"])

Jorl> to have it available for the second loop.  I've gotten
Jorl> around this before for somewhat similar cases using
Jorl> suggestions from this group of explicitly defining the
Jorl> values the legend will use:

Jorl> L1= plot(x,y,...

Jorl>  but I can't figure how to do this here because of the
Jorl> looping over the data sets.

Hope the above example helps here.

Jorl>On a related note, is there any way to increase the size
Jorl> of the markers within the legend?

You can access the lines of the legend instance

leg = legend(lines, labels)
lines = leg.get_lines()
set(lines, markersize=10, markeredgewidth=2)  # etc

See http://matplotlib.sourceforge.net/examples/legend_demo.py

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


  1   2   >