Re: Queue can result in nested monitor deadlock

2006-04-19 Thread Ove Svensson
"Jonathan Amsterdam" <[EMAIL PROTECTED]> writes:

> No redesign necessary. I simply make M be the Queue's mutex, via the
> LQueue class I posted. I am making the modest suggestion that this
> feature be documented and exposed in the Queue class.
> 

Even though LQueue is the correct sollution to the problem, why not fix
Queue.Queue? Fixing Queue.Queue would not break any existing code and we
don't have to pollute the namespace with yet another class. 

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


Re: Activating Batch Files from Python

2006-04-19 Thread Serge Orlov
Jeff Groves wrote:
> I'm writing a launcher that should do the following:
>
> 1. Activate a .bat file to set environmental variables.
> 2. Start 3 programs, using said environmental variables as arguments.
>
> However, I can't get the environmental variables to stick because all
> of Pythons' system start/open functions split off into their own little
> subshells, therefore the .bat file doesn't affect the main shell.

That's right. That is how enviromental variables work regardless of
programming language.

>
> How can I use the .bat file to set environmental vars from Python?

If it is your bat file, forget about it. Set the variables in your
Python program using os.environ. If it is a 3rd party bat file, the
best you can do is to copy it, add (at the end) a command to dump all
enviromental variables to a temp file like this: set >dump_file.txt,
parse the dump file to see what variables changed and set the variables
using os.environ.

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


Re: Missing interfaces in Python...

2006-04-19 Thread Kay Schluehr

[EMAIL PROTECTED] wrote:
> I'm coming from a Java background, so please don't stone me...
>
> I see that Python is missing "interfaces". The concept of an interface
> is a key to good programming design in Java, but I've read that they
> aren't really necessary in Python. I am wondering what technique I can
> use in Python to get the same benefits to a program design that I would
> get with interfaces in Java.
>
> For example, if I want to have a program with a Car object, and a Bus
> object. I want both of these objects to present a common group of
> methods that can be used by Mechanic objects, but slightly different
> methods that can be used by Driver objects.
>
> In Java I would accomplish this by defining an IFixable interface that
> would be implemented by both the Car and Bus objects. Mechanic objects
> would work with any object implementing this interface.
>
> How would I approach this problem in Python? I think I would use an
> abstract class instead of an interface for IFixable, since Python
> supports multiple inheritance, but I'm not sure this is correct.
>
> Thanks for any suggestions.
>
> Scott Huey

The answer is called "duck typing" or "structural typing". Any two
classes that implement a set of methods with pairwise equal signatures
can be considered as "presenting a group of methods". You do not have
to create a special construct and assign it to classes ( e.g. via an
"implements" directive ) in order to make it work. That's because you
are not enforced to know the type of an object at compile time. Car and
Bus classes may be selected from two completely different libraries
without any common convention but it is still possible ( though not
very likely without any adaption ) that they work together and show
sound behaviour ( you have to prove at least certain behavioural
properties using unit tests ).

"Duck typing" is also the reason why coupling of an interface with an
implementation is not harmfull in Python. You won't find many deep
class hierarchies and extensive frameworks. This has the advantage that
a classification you have done once at the beginning of your project in
the design phase is not considered to be carved in stone.
In Java/C#/C++ you can achieve many of the same effects of using
"generic" or "templates" but if you are not start coding with them from
the very beginning you loose many of their benfits. In Python this is a
non-issue.

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


Re: local greediness ???

2006-04-19 Thread John Machin
On 19/04/2006 3:09 PM, [EMAIL PROTECTED] wrote:
> hi, all. I need to process a file with the following format:
> $ cat sample
> [(some text)2.3(more text)4.5(more text here)]
> [(aa bb ccc)-1.2(kdk)12.0(xxxyyy)]
> [(xxx)11.0(bbb\))8.9(end here)]
> ...
> 
> my goal here is for each line, extract every '(.*)' (including the
> round
> brackets, put them in a list, and extract every float on the same line
> and put them in a list.. here is my code:
> 
>   p = re.compile(r'\[.*\]$')
>   num = re.compile(r'[-\d]+[.\d]*')
>   brac  = re.compile(r'\(.*?\)')
> 
>   for line in ifp:
>   if p.match(line):
>   x = num.findall(line)
>   y = brac.findall(line)
> print x, y len(x), len(y)
> 
> Now, this works for most of the lines. however, I'm having problems
> with
> lines such as line 3 above (in the sample file). here, (bbb\)) contains
> an escaped
> ')' and the re I use will match it (because of the non-greedy '?'). But
> I want this to
> be ignored since it's escaped. is there a such thing as local
> greediness??
> Can anyone suggest a way to deal with this here.. 
> thanks.
> 

For a start, your brac pattern is better rewritten to avoid the 
non-greedy ? tag: r'\([^)]*\)' -- this says the middle part is zero or 
more occurrences of a single character that is not a ')'

To handle the pesky backslash-as-escape, we need to extend that to: zero 
or more occurrences of either (a) a single character that is not a ')' 
or (b) the two-character string r"\)". This gives us something like this:

#>>> brac  = re.compile(r'\((?:\\\)|[^)])*\)')
#>>> tests = r"(xxx)123.4(bbb\))5.6(end\Zhere)7.8()9.0(\))1.2(ab\)cd)"
#>>> brac.findall(tests)
['(xxx)', '(bbb\\))', '(end\\Zhere)', '()', '(\\))', '(ab\\)cd)']
#>>>

Pretty, isn't it? Maybe better done with a hand-coded state machine.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiline comments

2006-04-19 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 Edward Elliott <[EMAIL PROTECTED]> wrote:

>ML has a 
>very elegant system for nested comments with (* and *).

Which, if you mistype an opening or closing comment symbol, can lead to 
some very mysterious syntax errors.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Activating Batch Files from Python

2006-04-19 Thread Lawrence D'Oliveiro
In article <[EMAIL PROTECTED]>,
 "Jeff Groves" <[EMAIL PROTECTED]> wrote:

>How can I use the .bat file to set environmental vars from Python?

How about sourcing it from a shell, then using that same shell instance 
to run the programs?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: indirect import of standard module

2006-04-19 Thread Fredrik Lundh
BartlebyScrivener wrote:

> >> More accurately, it *does* import it twice, into two separate
> >> namespaces;
>
> If it's in two different namespaces, how can they have the same id
> number?

they're mixing up the terminology.  each loaded module has exactly one
namespace, no matter how many times you import it.

the modules you're importing to have their own namespaces, of course.

this link may help:

http://effbot.org/zone/import-confusion.htm#what-does-python-do





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


Re: freakin out over C++ module in python

2006-04-19 Thread Serge Orlov
[EMAIL PROTECTED] wrote:
> pyconstruct looks cool. i dont know if the classes are using the plain
> berkely-ish code. i couldn't find anything in it that pointed to send()
> recv(), & such. i found other stuff like SetSocketOpt() and so on like
> this :
>
> long CClientSocket::ConnectToServer(LPCTSTR serverAddr, UINT port)
>
> {
>
> BOOL socketOption = TRUE;
>
>   const int rcvBuffsize = 64 *1024;
>
>   const int sendBuffsize = 64*1024;
>
>
>
>   if ( !Create() )
>
>   return ERR_SOCKET_CREATE;
>
>   int intvalue = sizeof(int);
>
>   if(!( SetSockOpt(SO_DONTROUTE,&socketOption,sizeof(BOOL),SOL_SOCKET)
> &&
>
>   SetSockOpt(SO_RCVBUF,&rcvBuffsize,sizeof(int),SOL_SOCKET) &&
>
>   SetSockOpt(SO_SNDBUF,&sendBuffsize,sizeof(int),SOL_SOCKET) &&
>
>   SetSockOpt(TCP_NODELAY,&socketOption,sizeof(BOOL),SOL_SOCKET) &&
>
>   SetSockOpt(SO_KEEPALIVE,&socketOption,sizeof(BOOL),SOL_SOCKET)))
>
>   return ERR_SOCKET_CREATE;
>
>
> i looked around for some of these and found most references to UDP. I
> guess its also a windows specific thing too.

Nope. It's a UNIX function:
http://www.opengroup.org/onlinepubs/007908799/xns/setsockopt.html
And corresponding Python stuff is in the socket module. The code above
can be roughly translated as

def ConnectToServer(self, serverAddr, port):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.connection = s
s.connect((serverAddr, port))
s.setsockopt(socket.SOL_SOCKET, socket.SO_DONTROUTE, 1)
s.setsockopt(socket.SOL_SOCKET, socket.TCP_NODELAY, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 64*1024)
s.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, 64*1024)

Note, you don't need to handle errors in this method like C++ code,
instead catch socket.error exception where you handle *all* fatal
exceptions during connection setup.

With regards to your first question about automatic language
translation - don't even dream about it. IMHO, C++ is one of the most
complicated high-level languages for automatic translation.

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


Re: multiline comments

2006-04-19 Thread Duncan Booth
Edward Elliott wrote:

> Ben Finney wrote:
>> Indeed. Using revision control means never needing to comment out
>> blocks of code.
> 
> Typing (* and *) on a few line will always be quicker, easier, and
> less confusing than any rcs diffs/restores.  Once you delete the code
> you can no longer see it or add pieces back in without retrieving it
> from an external store.  I'm not saying nested comments solve every
> problem, just that there exists a certain (perhaps small) class of
> problems they solve particularly well.

Would you care to name a few languages which support nested block
comments? There really aren't many: ML as you mentioned; Standard Pascal 
doesn't permit nesting of comments but *some* implementations do allow it.

Want to comment out a block of code in C++? The only (nearly) reliable way 
is to insert single-line comments down the block. You can't use a block 
comment if there are any other block comments inside the code you want to 
block out.

The danger of block comments is that if you forget to close the comment
you can accidentally comment out a large part of your code. With support
from the editor (coloured highlighting of comments) this isn't so bad,
but then if you have a decent editor you don't need the block comments
anyway as you will be able to comment/uncomment a block in your editor. 

Doc strings will usually work as an alternative, especially since you
have a choice of two flavours of triple quoted strings, so if you use
one for docstrings the other is always free for your temporary block
comments. 

> Forcing programmers to write clean code with syntax is like teaching a
> pig to sing: it wastes your time and annoys the pig. 

This pig gets much more annoyed having to maintain code which has large 
chunks of unneeded commented out code left over from some other programmer, 
or which has completely messed up indentation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scanning for numerals / letters

2006-04-19 Thread johnzenger
First, note that form["date"] is all you need.  form["date"].value is
redundant.

I would do this with sets:

import string
if set(form["date"]) & set(string.ascii_letters) != set([]): print "You
have to enter a date with numbers"

if set(form["purchases"]) & set(string.digits) != set([]): print
"Please do not use numbers"

Sets take time to construct, but they test membership faster than
strings.  Plus, the code just reads logically.  (The &, if you couldn't
figure it out, does an intersection of sets.  You could also use the
.intersection method for even better readability).

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


Re: Missing interfaces in Python...

2006-04-19 Thread Rene Pijlman
Kay Schluehr:
>You won't find many deep class hierarchies and extensive frameworks. 

Zope comes to mind.

>This has the advantage that a classification you have done once at 
>the beginning of your project in the design phase is not considered 
>to be carved in stone.

Zope 3 comes to mind.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: local greediness ???

2006-04-19 Thread johnzenger
How about using the numbers as delimiters:

>>> pat = re.compile(r"[\d\.\-]+")
>>> pat.split("[(some text)2.3(more text)4.5(more text here)]")
['[(some text)', '(more text)', '(more text here)]']
>>> pat.findall("[(some text)2.3(more text)4.5(more text here)]")
['2.3', '4.5']
>>> pat.split("[(xxx)11.0(bbb\))8.9(end here)] ")
['[(xxx)', '(bbb\\))', '(end here)] ']
>>> pat.findall("[(xxx)11.0(bbb\))8.9(end here)] ")
['11.0', '8.9']

[EMAIL PROTECTED] wrote:
> hi, all. I need to process a file with the following format:
> $ cat sample
> [(some text)2.3(more text)4.5(more text here)]
> [(aa bb ccc)-1.2(kdk)12.0(xxxyyy)]
> [(xxx)11.0(bbb\))8.9(end here)]
> ...
>
> my goal here is for each line, extract every '(.*)' (including the
> round
> brackets, put them in a list, and extract every float on the same line
> and put them in a list.. here is my code:
>
>   p = re.compile(r'\[.*\]$')
>   num = re.compile(r'[-\d]+[.\d]*')
>   brac  = re.compile(r'\(.*?\)')
>
>   for line in ifp:
>   if p.match(line):
>   x = num.findall(line)
>   y = brac.findall(line)
> print x, y len(x), len(y)
>
> Now, this works for most of the lines. however, I'm having problems
> with
> lines such as line 3 above (in the sample file). here, (bbb\)) contains
> an escaped
> ')' and the re I use will match it (because of the non-greedy '?'). But
> I want this to
> be ignored since it's escaped. is there a such thing as local
> greediness??
> Can anyone suggest a way to deal with this here.. 
> thanks.

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


Re: Missing interfaces in Python...

2006-04-19 Thread bruno at modulix
[EMAIL PROTECTED] wrote:
(snip)

> Everyone is getting off track here.

Not that much...

> Java has interfaces because it doesn't support multiple inheritance.

Java as interfaces because it relies on type declaration for subtyping
*and* doesn't support MI.

> Python supports MI, so you don't need to use the seperate concept of an
> interface.  

s/supports MI/doesn't rely on type declaration for subtyping/

Would we need interfaces in Python if Python did not support MI ? Of
course not, duck typing would still work.

(snip)


> The general wisdom is that Abstract Base Classes aren't pythonic
> though.  

*Pure* abstract base classes (ie: abc without any implementation) are
not Pythonic. I often use abc's that provides the 'guts' for common
stuff, but are meant to be specialized for use (this is pretty common in
frameworks).

(snip the rest - mostly agree)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing interfaces in Python...

2006-04-19 Thread bruno at modulix
Rene Pijlman wrote:
> Kay Schluehr:
> 
>>You won't find many deep class hierarchies and extensive frameworks. 
> 
> 
> Zope comes to mind.
> 
> 
>>This has the advantage that a classification you have done once at 
>>the beginning of your project in the design phase is not considered 
>>to be carved in stone.
> 
> 
> Zope 3 comes to mind.

Yeps. Now Zope is a world in itself, and is not really pythonic IMHO.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Updated PEP 359: The make statement

2006-04-19 Thread bruno at modulix
Steven Bethard wrote:
(snip)

> Guido has pronounced on this PEP:
>http://mail.python.org/pipermail/python-3000/2006-April/000936.html
> Consider it dead. =)

:(


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.5 excitement (was Re: Java Developer Exploring Python)

2006-04-19 Thread Jon Ribbens
In article <[EMAIL PROTECTED]>, Chris Lambacher wrote:
> At least on windows.  PySqlite is statically linked with the sqlite library.
> This can be done because it is quite small.

OK, well that makes sense, but why not on any other platform?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: removing cgi fieldstorage keys

2006-04-19 Thread Diez B. Roggisch
Tim Roberts wrote:

> Kun <[EMAIL PROTECTED]> wrote:
>>
>>i don't know what happened but all of a sudden, my cgi.fieldstorage has
>>two extra keys, 'x' and 'y', does anyone know how i can remove them in
>>python?
> 
> If this is coming from a web site that you created, then you darned well
> better figure out where they're coming from!  Did you add any  hidden> fields?  Did you add an image map?

AFAIK these come in case of image-submit-buttons, too.

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


Re: Missing interfaces in Python...

2006-04-19 Thread Ben

bruno at modulix wrote:
> Rene Pijlman wrote:
> > Kay Schluehr:
> >
> >>You won't find many deep class hierarchies and extensive frameworks.
> >
> >
> > Zope comes to mind.
> >
> >
> >>This has the advantage that a classification you have done once at
> >>the beginning of your project in the design phase is not considered
> >>to be carved in stone.
> >
> >
> > Zope 3 comes to mind.
>
> Yeps. Now Zope is a world in itself, and is not really pythonic IMHO.
>

It seems to me that a lot of python projects reimplement interfaces or
adaption of some kind once they reach a certain size (Zope, PEAK, eggs,
TurboGears, etc), which implies that they really do have some benefits,
particularly in documentation.

Cheers,
Ben

> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"

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


Re: multiline comments

2006-04-19 Thread Roel Schroeven
Duncan Booth schreef:
> Would you care to name a few languages which support nested block
> comments? There really aren't many: ML as you mentioned; Standard Pascal 
> doesn't permit nesting of comments but *some* implementations do allow it.
> 
> Want to comment out a block of code in C++? The only (nearly) reliable way 
> is to insert single-line comments down the block. You can't use a block 
> comment if there are any other block comments inside the code you want to 
> block out.

Depends, some compilers support that. But the preferred way, which works 
very well, is to use preprocessor directives:

#if 0
 ...
#endif

Works in both C and C++.

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

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


namespace question

2006-04-19 Thread Nugent, Pete (P.)
Title: namespace question






Hi all,


I'm confused by namespaces in python, specifically using the global keyword.  I'm able to access and modify a global variable from a function if the function is defined in the same module but not if the function is defined in a different module:

//File t2.py

def sn():

    global test_var 

    test_var = 2


//File t1.py

test_var = 1

print test_var

from t2 import sn

sn()

print test_var

def so():

    global test_var 

    test_var = 3

so()

print test_var



The output from running t1 is:

1

1

3


Can anyone tell me how I can modify the test_var variable form another module?


Pete



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

Re: 2.5 excitement (was Re: Java Developer Exploring Python)

2006-04-19 Thread Jon Ribbens
In article <[EMAIL PROTECTED]>, Fredrik Lundh wrote:
>> Apologies if I'm being obtuse, but how does including the pysqlite
>> wrapper module change anything? You still need to download and install
>> SQLite
> 
> I'm pretty sure the distributors will do this for you, just as
> they've included zlib, dbm, tcl/tk, openssl, and many other standard
> libraries over the years.

"The distributors"? Que?

I guess I just don't get why the inclusion of the pysqlite wrapper
is so exciting if all it's doing is changing the situation from
"Python does not come with a DB, but you can install extra software
to provide one" to "Python does not come with a DB, but you can
install extra software to provide one".
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: namespace question

2006-04-19 Thread Fredrik Lundh
"Nugent, Pete (P.)" wrote:

> I'm confused by namespaces in python, specifically
> using the global keyword.  I'm able to access and
> modify a global variable from a function if the function
> is defined in the same module but not if the function
> s defined in a different module:

"global" means "not local", not "application-wide global".

> Can anyone tell me how I can modify the test_var variable
> form another module?

import t2
t2.test_variable = some value

also see:

http://pyfaq.infogami.com/how-do-i-share-global-variables-across-modules

http://pyfaq.infogami.com/what-are-the-rules-for-local-and-global-variables-in-python





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


Egg with option to install extra packages

2006-04-19 Thread Sebastjan Trepca
Hi,

I'm trying to distribute my application which also support some extra
libraries but does not require them to run. I set the "extra" option
but I don't know how could I specify that I want to install my
application with any of that extra packages.

So now I have in my setup.py like this:

  extras_require={
'postgresql': ['psycopg2'],
'mysql': ['MySQLdb'],
'odbc': ['pyodbc'],
'mssql': ['pymssql'],
},

Could I now specify an extra package when installing?

ie. easy_install my_egg.egg --extra=postgresql,mysql,odbc


Thanks!

--
Sebastjan
http://www.trepca.si/blog
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiline comments

2006-04-19 Thread Edward Elliott
Duncan Booth wrote:
> Want to comment out a block of code in C++? The only (nearly) reliable way 
> is to insert single-line comments down the block. You can't use a block 
> comment if there are any other block comments inside the code you want to 
> block out.

As Roel said, #if 0 is the standard way.  It abuses the preprocessor and 
doesn't show up in syntax highlighting, but other than that works very 
well.  Honestly though, /* and */ should have nested properly since day 1. 
  Adding it wouldn't even break existing code.

> The danger of block comments is that if you forget to close the comment
> you can accidentally comment out a large part of your code. 

No, unclosed comments should raise a syntax error.  Would you accept an 
unclosed string literal?

> Doc strings will usually work as an alternative, especially since you
> have a choice of two flavours of triple quoted strings, so if you use
> one for docstrings the other is always free for your temporary block
> comments.

That's a fair point, if a bit of a kludge.  90% there is good enough in 
practice.

> This pig gets much more annoyed having to maintain code which has large 
> chunks of unneeded commented out code left over from some other programmer, 
> or which has completely messed up indentation.

Sure they can be abused.  So can a thousand other language features.  My 
point is you can't teach good coding through syntax, and trying to causes 
more problems than it solves.

I would argue the current system is in fact slightly worse, because people 
will comment out code chunks anyway (either lots of #s or triple-quotes) 
and are less likely to remove them when it's more work.  But either way, 
social pressure is infinitely more effective at cleaning up code than 
comment syntax.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiline comments

2006-04-19 Thread Gregor Horvath
Edward Elliott schrieb:

> On top of that, the expressive power of nested comments seems greater
> than an endless string of ^#s.  Sometimes it's just easier to see what's
> going on.

not if you are using grep

-- 
Gregor
http://www.gregor-horvath.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiline comments

2006-04-19 Thread Peter Tillotson
Ben Finney wrote:
> "Atanas Banov" <[EMAIL PROTECTED]> writes:
> 
>> Edward Elliott wrote:
>>> Saying coders shouldn't use multiline comments to disable code
>>> misses the point.  Coders will comment out code regardless of the
>>> existence of multiline comemnts.  There has to be a better
>>> argument for leaving them out.
>> i beg to differ: you'd be surprised how much effect can little
>> inconveniences have.
>>
>> want to comment block of code? use tripple-quotes. does not nest?
>> ahhh, maybe it's time to get rid of that block you commented out a
>> month ago "just in case the new code doesnt work".
> 
> Indeed. Using revision control means never needing to comment out
> blocks of code.
> 
> If your revision control system is so inconvenient to use that you'd
> rather have large blocks of commented-out code, it's time to start
> using a better RCS -- perhaps a distributed one, so you can commit to
> your own local repository with abandon while trying out changes.
> 

I'm not sure I agree, revision control is great but not the only answer.
In multi-developer teams working on the trunk, it its kind of
inconvenient if someone checks in broken code. It also blocks critical
path development if the person responsible for the code you conflict
with happens to be out on holiday. Block commenting is a clear flag to
that developer that something has changed - ideally he'd notice, see
sensible revision control comments, see the flag on the wiki or you
would remember to tell him. But if all of that fails, if it is commented
in the code it should get picked up at a code review.

Personally, I prefer clear code, minimally commented with good high
level descriptions of particularly complex section / algorithms. The
later doesn't always fit neatly on one line. There is an argument that
these should go into their own functions and be commented at the
function level. Again I'm not sure I agree entirely - function comments
that are auto extracted to create api docs (sorry Java background :-))
need only outline What a function does. There is a place for multiline
comments to describe How that is achieved.

Having said all that, I generally don't like comments, they are often
maintained poorly, too numerous, too verbose (red rag :-)) - so i'm
undecided whether they should be made easier for developers or
discouraged except where vital. Perhaps we should make them really hard
and elegant - mandate latex/mathml markup so good editors can display
the equations we are implementing :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: scanning for numerals / letters

2006-04-19 Thread Gerard Flanagan
Kun wrote:
> I have the following if statement that checks if a form is empty:
>
>  if form.has_key("date") and form["date"].value != "":
>  date=form['date'].value
>
>  else:
>  print "ERROR: No date entered!"
>  raise Exception
>
> I would also like to add another if statement checking if 'date' has any
> letters (a-z) in it, and if so, would like to say that "you have to
> enter a date with numbers".  I am not sure how to alter my current if
> statement to do that check so any assistance would be appreciated.
>

Having just attempted a 'string_to_date' function I can see the wisdom
of having separate 'day', 'month' and 'year' input fields on the
client.  If you can't or won't provide separate fields then I suppose
you have to inform users as to what you accept as valid input, eg.
'ddmmyy', or 'month/day/year'.  Here's some code which assumes that you
are providing appropriate formatting hints:

import time
import datetime

DDMMYY = ['%d %m %Y', '%d %m %y', '%d/%m/%Y', '%d/%m/%y', '%d-%m-%Y',
'%d-%m-%y' ]

def yearmonthday(datestring, fmts=DDMMYY):
ymd = tuple()
for f in fmts:
try:
ymd = time.strptime( datestring, f )
break
except ValueError:
continue
if not ymd:
raise ValueError
return ymd[0], ymd[1], ymd[2]

def is_valid_date(datestring, fmts=DDMMYY):
try:
yearmonthday(datestring, fmts)
return True
except ValueError:
return False

def string_to_date(datestring, fmts=DDMMYY):
return datetime.date( *yearmonthday(datestring, fmts) )

assert string_to_date( '1/2/01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '1 2 01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '01/02/01', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '1/02/2001', DDMMYY) == datetime.date(2001,2,1)
assert string_to_date( '29/02/2008', DDMMYY) ==
datetime.date(2008,2,29)
assert string_to_date( '01/2/99', DDMMYY) == datetime.date(1999,2,1)

for d in [ '', '32/1/01', '01/13/01', '29/2/07', '1/2', 'abcdef' ]:
assert not is_valid_date(d, DDMMYY)


Gerard

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


Re: multiline comments

2006-04-19 Thread Jorge Godoy
Edward Elliott wrote:

> Typing (* and *) on a few line will always be quicker, easier, and less
> confusing than any rcs diffs/restores.  Once you delete the code you can
> no longer see it or add pieces back in without retrieving it from an
> external store.

Try using Subversion.  You can work and make diffs disconnected from the
network.  You can't, of course, commit / update but you can work with it
and have what you need to compare original code (i.e. the one from the last
commit) to new code and go back to original code if needed.

> I'm not saying nested comments solve every problem, just that 
> there exists a certain (perhaps small) class of problems they solve
> particularly well.

I don't miss them.  :-)

> Personally, I rarely leave code commented out beyond a single coding
> session.  But my particular coding habits aren't relevant here.

Well, I believe they are since it looks like a habit of yours to use
multiline comments.  It is common for people coming from other programming
languages that support them.

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiline comments

2006-04-19 Thread Jorge Godoy
Edward Elliott wrote:

> Sure they can be abused.  So can a thousand other language features.  My
> point is you can't teach good coding through syntax, and trying to causes
> more problems than it solves.

I like the phrase: there are some languages that incentivates bad practices
in programming; there is Python that doesn't.

Some rigid syntax indeed makes you think one way -- and that's one of
Python's motto, isn't it?  "There's one right way to do it" -- but that
will make your code more understandable and readable in the future.

> I would argue the current system is in fact slightly worse, because people
> will comment out code chunks anyway (either lots of #s or triple-quotes)
> and are less likely to remove them when it's more work.  But either way,
> social pressure is infinitely more effective at cleaning up code than
> comment syntax.

Is it harder to remove "n" lines of code commented out with "#" than "n"
lines of multiline commented code?  How?  The same question goes for triple
quoted code.

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: win32com Excel bug?

2006-04-19 Thread Roger Upole
<[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED]
> I'm driving Excel from python, largely successfully. Now I'm trying to
> add errorbars to XY scatter plots. Keep getting a com_error. Can't
> track down the problem.
>
> I modified a simple example to duplicate the problem. Thanks to Mathieu
> Fenniak http://www.stompstompstomp.com/weblog/entries/67/ for the code.
>
> The traceback is shown below. You can see that the Excel chart series
> has a method called ErrorBar. But when I try to use it with any or all
> of its allowed arguments, it fails. The traceback goes into the guts of
> win32com but I don't really have a clue at that point. (Happy to learn
> something new though).
>
> The relevant Excel VBA language doc is here.
> http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vbaxl11/html/xlmthErrorBar1_HV03076818.asp
>
> Hope someone can help. Losing hair  fast!
>
>
>
> In [16]: %run test.py
> --Return--
>> c:\python23\lib\pdb.py(992)set_trace()->None
> -> Pdb().set_trace()
> (Pdb) c
> There's a method waiting
> ---
> pywintypes.com_error Traceback (most
> recent call
> last)
>
> c:\temp\mpival\test.py
> 79
> 80 # A simple example:
> ---> 81 plot( (1,2,3,4,5), (6,7,8,9,10) )
> 82
> 83 # Some more data:
>
> c:\temp\mpival\test.py in plot(x, y, xAxisLog, yAxisLog)
> 35 if series.ErrorBar:
> 36 print "There's a method waiting"
> ---> 37 series.ErrorBar(Direction = constants.xlY)


According to the docs, the Include and Type arguments are
required, and they're not being passed to the method.

  hth
   Roger



== Posted via Newsfeeds.Com - Unlimited-Unrestricted-Secure Usenet 
News==
http://www.newsfeeds.com The #1 Newsgroup Service in the World! 120,000+ 
Newsgroups
= East and West-Coast Server Farms - Total Privacy via Encryption =
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiline comments

2006-04-19 Thread Jorge Godoy
Peter Tillotson wrote:

> I'm not sure I agree, revision control is great but not the only answer.
> In multi-developer teams working on the trunk, it its kind of
> inconvenient if someone checks in broken code. It also blocks critical

This is something that should be a policy: no untested and working code
should be commited to the trunk; if you need to commit it for any reason
create a branch and do it there.

> path development if the person responsible for the code you conflict
> with happens to be out on holiday. Block commenting is a clear flag to

Here I believe that no code revision system is a substitute for project.  If
you have two conflicting changes on the same line of code, then you surely
are missing some discussion on the code and more documentation on what is
being done / has been done.  Revision management is no substitute for
meetings and projects.

> that developer that something has changed - ideally he'd notice, see
> sensible revision control comments, see the flag on the wiki or you
> would remember to tell him. But if all of that fails, if it is commented
> in the code it should get picked up at a code review.

I believe that it is easier to see multiple commented out lines than just
the beginning and ending of a multiline comment.  Specially when you're
screening the code instead of reading it line by line.

> Personally, I prefer clear code, minimally commented with good high
> level descriptions of particularly complex section / algorithms. The

We have the same taste, except that I prefer documenting more things than
just complex algorithms so I have a lot of comments and docstrings in my
code.

> later doesn't always fit neatly on one line. There is an argument that
> these should go into their own functions and be commented at the
> function level. Again I'm not sure I agree entirely - function comments
> that are auto extracted to create api docs (sorry Java background :-))
> need only outline What a function does. There is a place for multiline
> comments to describe How that is achieved.

I still believe that you're working with an inappropriate environment if
your editor can't use some extension for the language you choose (coming
from a Java background you might like PyDev on Eclipse, even though its
indentation features aren't as nice as Emacs' features...) or being able to
repeat the comment symbol from one line to the next when it wraps (keeping
indentation, of course!)

> Having said all that, I generally don't like comments, they are often
> maintained poorly, too numerous, too verbose (red rag :-)) - so i'm
> undecided whether they should be made easier for developers or
> discouraged except where vital. Perhaps we should make them really hard
> and elegant - mandate latex/mathml markup so good editors can display
> the equations we are implementing :-)

:-)  There's an approach that allows using those...  I don't remember which
docsystem allows for MathML markup.  But then, I'd go with DocBook + MathML
+ SVG ;-)  (Hey!  You started!  And you even said that you didn't like
verbose comments... ;-))

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.5 excitement

2006-04-19 Thread Jay Parlar

On Apr 18, 2006, at 9:06 PM, Alex Martelli wrote:
>
> Funny timing coincidence: your 1st draft of Python for Dummies going in
> now, my 2nd edition of Python in a Nutshell just went to production, 
> AND
> Wesley Chun's 2nd ed is also being finished this week.  Three 
> Baypiggies
> (or whatever we'll have to call ourselves) all finishing Python books
> (be they new, or 2nd eds) all within one week of Easter -- what's the
> chances of THAT?-)
>
>

Wesley Chun is doing a second edition of Core Python? Oh wow! That's 
the book I learned Python with oh so long ago(between 1.5.2 and the 
mysterious 1.6). I told people for a long time that Core was the best 
book with which to learn Python, but I stopped doing that as it's too 
out of date now.

Glad to see Ruby isn't the only language getting a bunch of new good 
books.

Jay P.

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


Re: multiline comments

2006-04-19 Thread Jorge Godoy
Edward Elliott wrote:

> And when the section I want to comment out contains a legit doc string in
> the middle, triple-quotes won't work.  There are valid reasons to nest

You can use either """ or '''.  I don't keep changing them in my code, so I
can always use the other type (usually I use " so for commenting things out
I'd use ') to do that. 

> comments which have nothing to do with laziness or sloppy code.
> 
> Forcing programmers to write clean code with syntax is like teaching a pig
> to sing: it wastes your time and annoys the pig.  Good coding is a state
> of mind, not a parser option.

If the latter can help, why not?

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Writing backwards compatible code - when?

2006-04-19 Thread Kent Johnson
> Bob Greschke wrote:
>> Is there a list of all of the Python commands and modules that tell when 
>> (what version) they were added to Python?  I was hoping the new Essential 
>> Reference would have it, but it doesn't.

The Library Reference page for a module or built-in often documents the 
version when any change was made. You can also read through the What's 
New documents for each release to see what changed in that release.

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


Re: Shell like syntax for subprocess.Popen # overloading >, <, |

2006-04-19 Thread Christos Georgiou
On 18 Apr 2006 05:00:55 -0700, rumours say that "jelle"
<[EMAIL PROTECTED]> might have written:

>Hi Christos,
>
>Thanks for your pointers there, impressive to see
>-that a 12 year old thread still can make an interesting read
>-you being able to remember & trace it... impressive...
>
>Thanks for your pointers.
>I think the
>input > process > output
>Syntax is more powerful , since it would let you build chaining
>commmands in a more readable fashion.
>
>The goal of this class would be to construct command chains such as:
>
>input > processA | processB > ouput
>
>Something which wouldn't be possible if only one operator is
>overloaded.
>I'm curious to see if its doable via overloading, since no __rgt__
>methods exists...

The problem with the operators chaining is that ">" is treated differently
than "|".  Check the following disassembly:

>>> import dis
>>> dis.dis(compile("a>   24 ROT_TWO 
 25 POP_TOP 
>>   26 RETURN_VALUE
>>> dis.dis(compile("a|b|c", "", "eval"))
  0   0 LOAD_NAME0 (a)
  3 LOAD_NAME1 (b)
  6 BINARY_OR   
  7 LOAD_NAME2 (c)
 10 BINARY_OR   
 11 RETURN_VALUE


The comparison operators include some logic in order to "do what I mean" (so
that 4" operator, just don't chain it, in order to
avoid such unexpected behaviour.
-- 
TZOTZIOY, I speak England very best.
"Dear Paul,
please stop spamming us."
The Corinthians
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing interfaces in Python...

2006-04-19 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] (Alex Martelli) wrote:

> Roy Smith <[EMAIL PROTECTED]> wrote:
> 
> > Peter Maas  <[EMAIL PROTECTED]> wrote:
> > > He probably means that with interfaces one could test compliance
> > > with the interface as a whole instead of testing each member and
> > > each signature as a single piece.
> > 
> > All interfaces (as implemented by Java) prove is that your class has a
> > bunch of methods with the right names and signatures.  It doesn't
> > prove that those methods do the right things.  It's like having a
> 
> There's a _tiny_ bit more -- accidental clashes of methodnames are more
> likely to be avoided.  I.e.,
> 
> interface ILottery {
> void draw();
> };
> 
> interface IGunslinger {
> void draw();
> };
> 
> interface IPainter {
> void draw();
> };
> 
> A class asserting, e.g., "implements IPainter", doesn't thereby risk
> being accidentally misused where an IGunslinger is required (OTOH,
> implementing >1 of these IS a bother, but that's sort of inevitable).

I suppose, but all you've really done is move the problem to a different 
namespace.  Which IPainter did you have in mind?  The one that has to do 
with people who apply oils to canvas, or the one that has to do with ropes 
that are used to tie up rowboats?
-- 
http://mail.python.org/mailman/listinfo/python-list


Pyrex installation on windows XP: step-by-step guide

2006-04-19 Thread Julien Fiore
Do you wand to install Pyrex on Windows ?

Here is a step-by-step guide explaining:

A) how to install Pyrex on Windows XP.
B) how to compile a Pyrex module.

Julien Fiore,
U. of Geneva

---

### A) Pyrex installation on Windows XP ###


# step A.1 #
Install Python (we used version 2.4.2)


# step A.2 #
Run the windows installer for Pyrex (e.g. Pyrex-0.9.3.1.win32.exe),
available on the Pyrex homepage
(http://www.cosc.canterbury.ac.nz/~greg/python/Pyrex/)


# step A.3 #
Install Mingw, the gcc compiler for Windows, available at
http://www.mingw.org/download.shtml. (we downloaded the file
MinGW-5.0.2.exe and installed only the "base tool" (this includes
mingw-runtime 3.9, w32api-3.6, binutils 2.15.91 and gcc-core 3.4.2).
Add Mingw path ("C:\MinGW\bin") to the Windows "Path" environment
variable. If you already have cygwin installed, add C:\MinGW\bin before
the Cygwin path.


# step A.4 #
Create or edit the file "c:/Python2x/Lib/distutils/distutils.cfg" and
put the following into it:
[build]
compiler = mingw32

---


### B) Create a Pyrex module ###


# step B.1 #
Create a working directory (e.g. D:\pyrex_module\). Write a pyrex
module and save it with a "pyx" extension (e.g. "primes.pyx", code
available on the Pyrex homepage)


# step B.2 #
Write the following python script and save it as "setup.py" in your
working directory.

from distutils.core import setup
from distutils.extension import Extension
from Pyrex.Distutils import build_ext
setup(
  name = "PyrexGuide",
  ext_modules=[
Extension("primes", ["primes.pyx"])
],
  cmdclass = {'build_ext': build_ext}
)

If you want to compile several modules, duplicate the line starting
with "Extension" and replace "primes" by your module names.


# step B.3 #
In your working directory, create a batch file called
"build_and_install.bat" containing the following lines, where
"PythonXX" should be replaces by your Python version (e.g. "Python24").

C:\Python24\python.exe setup.py build_ext install
pause

To run the batch, double-click the file. You will see many "Warning"
messages during the building process: do not worry, it is normal.


# step B.4 #
Mission completed. The file "primes.pyd" (a "pyd" is a Python Extension
DLL, equivalent of .so in Unix) is now located in
"C:\Python24\Lib\site-packages" and the "primes" module is available in
Python. In your working directory, you can delete the file "primes.c"
and the "build" folder created by the building process.

Test your new module at the python shell:

>>> import primes
>>> primes.primes(10)
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]



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


Re: http request with cookie sending

2006-04-19 Thread Kent Johnson
itay_k wrote:
> Hi,
> 
> I want to send a cookie on some http request (with urllib2),
> so I created a Cookie but I cant associate it with CookieJar object.

You have to use a cookielib.Cookie, not Cookie.SimpleCookie():

import cookielib, urllib2

cj = cookielib.CookieJar()
cookie = cookielib.Cookie(...your cookie data here...)
cj.set_cookie(cookie)

opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
urllib2.install_opener(opener)

data = urllib2.urlopen(...).read()

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


Re: extracting a substring

2006-04-19 Thread Kent Johnson
[EMAIL PROTECTED] wrote:
> Hi,
> I have a bunch of strings like
> a53bc_531.txt
> a53bc_2285.txt
> ...
> a53bc_359.txt
> 
> and I want to extract the numbers 531, 2285, ...,359.
> 
> One thing for sure is that these numbers are the ONLY part that is
> changing; all the other characters are always fixed.

In that case a fixed slice will do what you want:

In [1]: s='a53bc_531.txt'

In [2]: s[6:-4]
Out[2]: '531'

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


Re: How protect proprietary Python code? (bytecode obfuscation?, what better?)

2006-04-19 Thread Ben Sizer
bruno at modulix wrote:
> [EMAIL PROTECTED] wrote:
> > I suppose another idea is to rewrite entire Python app in C if compiled
> > C code
> > is harder to decompile.
>
> Do you really think "native" code is harder to reverse-engineer than
> Python's byte-code ?

Yes, until there's a native code equivalent of "import dis" that
telepathically contacts the original programmer to obtain variable
names that aren't in the executable.

-- 
Ben Sizer

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


Re: multiline comments

2006-04-19 Thread Peter Tillotson
nice one Jorge :-)

Jorge Godoy wrote:
> Peter Tillotson wrote:
> 
>> I'm not sure I agree, revision control is great but not the only answer.
>> In multi-developer teams working on the trunk, it its kind of
>> inconvenient if someone checks in broken code. It also blocks critical
> 
> This is something that should be a policy: no untested and working code
> should be commited to the trunk; if you need to commit it for any reason
> create a branch and do it there.
typo

committing broken code to trunk should punishable by stocks at least --
perhaps a public flogging.

Though on a serious note, you need a good reason for creating arbitrary
branches and a clearly defined naming policy. You also need to remember
to get off the branch asap before you inadvertently start a major fork.

>> path development if the person responsible for the code you conflict
>> with happens to be out on holiday. Block commenting is a clear flag to
> 
> Here I believe that no code revision system is a substitute for project.  If
> you have two conflicting changes on the same line of code, then you surely
> are missing some discussion on the code and more documentation on what is
> being done / has been done.  Revision management is no substitute for
> meetings and projects.
> 
>> that developer that something has changed - ideally he'd notice, see
>> sensible revision control comments, see the flag on the wiki or you
>> would remember to tell him. But if all of that fails, if it is commented
>> in the code it should get picked up at a code review.
> 
> I believe that it is easier to see multiple commented out lines than just
> the beginning and ending of a multiline comment.  Specially when you're
> screening the code instead of reading it line by line.
> 
>> Personally, I prefer clear code, minimally commented with good high
>> level descriptions of particularly complex section / algorithms. The
> 
> We have the same taste, except that I prefer documenting more things than
> just complex algorithms so I have a lot of comments and docstrings in my
> code.
>> later doesn't always fit neatly on one line. There is an argument that
>> these should go into their own functions and be commented at the
>> function level. Again I'm not sure I agree entirely - function comments
>> that are auto extracted to create api docs (sorry Java background :-))
>> need only outline What a function does. There is a place for multiline
>> comments to describe How that is achieved.
> 
> I still believe that you're working with an inappropriate environment if
> your editor can't use some extension for the language you choose (coming
> from a Java background you might like PyDev on Eclipse, even though its
> indentation features aren't as nice as Emacs' features...) or being able to
> repeat the comment symbol from one line to the next when it wraps (keeping
> indentation, of course!)
Sadly i don't get to code at the coalface much recently. I've tinkered
in python with pydev and vi over the last couple of years - i just
really dislike coding on a white background. I'm sure eclipse can do it
- i'm just not sure i've got the perseverance to work out how.

>> Having said all that, I generally don't like comments, they are often
>> maintained poorly, too numerous, too verbose (red rag :-)) - so i'm
>> undecided whether they should be made easier for developers or
>> discouraged except where vital. Perhaps we should make them really hard
>> and elegant - mandate latex/mathml markup so good editors can display
>> the equations we are implementing :-)
> 
> :-)  There's an approach that allows using those...  I don't remember which
> docsystem allows for MathML markup.  But then, I'd go with DocBook + MathML
> + SVG ;-)  (Hey!  You started!  And you even said that you didn't like
> verbose comments... ;-))
> 
oooh - but surely a picture is worth a thousand words and with SVG no
truer word was spoken :-)

I was only half kidding about latex. I can just about read pure latex
but that human readable xml stuff always defeats me
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: mod_python web-dav management system

2006-04-19 Thread Kyler Laird
Damjan <[EMAIL PROTECTED]> writes:

>Now I've been thinking that it might be pretty easy to implement a
>authorization layer with mod_python (but living handling of the web-dav
>protocol to apache)... So, has anyone already done something similar?

Yup.  I'm in the process.  I'm using mod_python to do LDAP
authentication of WebDAV requests.

Now I just need to get a FUSE filesystem working and I should
be able to cobble together a "simple" DAV server...

It would be *so* much cleaner to have a total Python-based
solution (that could run as root) so I periodically check on
progress in this area.  I have high hopes for Twisted's DAV
server but I'm told it's not ready for use yet.  In another
thread I just learned about PanDAV
http://ivoras.sharanet.org/projects/pandav.html
but I haven't installed it yet.

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


Re: mod_python web-dav management system

2006-04-19 Thread Kyler Laird
Damjan <[EMAIL PROTECTED]> writes:

>I wouldn't use Zope as file storage. The ZODB is inefficient for storing big
>files.

It sounds like you're describing Zope FileStorage.  There are
certainly other options for Zope storage.  I still use
DirectoryStorage sometimes but Zope Local File System
http://sourceforge.net/projects/localfs
or ZFSPath
http://www.zope.org/Members/asterisk/ZFSPath/
might be more appropriate for this.

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


Re: Telnet Server Lib

2006-04-19 Thread [EMAIL PROTECTED]
Does anybody have any ideas?

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


Re: Shell like syntax for subprocess.Popen # overloading >, <, |

2006-04-19 Thread Serge Orlov
jelle wrote:
> Hi,
>
> I use python quite a bit to couple different programs together.
> Doing so has been a _lot_ easier since subprocess came around, but
> would really like to be able to use the succinct shell syntax; >, <, |
>
> That really shouldn't be too hard to wrap in a class, but so far I
> didn't succeed to do so this well, since I'm facing some trouble with
> operator precedence that I do not know how to overcome.
>
> Consider the following:
>
> A = 'inputString'
> B = Process('process.exe')
> C = cStringIO.StringIO() # output bucket
>
> A > B > C
>
> A is being piped to B and processed, but the output of B is not being
> piped to C
> executing A > B; B > C works as expected however.
> Which is disappointing, since what I'm trying to achieve is a sugar
> syntax for Popen processes, where directly sees the chain of
> commands...
>
> Any suggestions to overcome this issue are greatly appreciated!

How about good old function call?

A = Lines('inputString')
B = Process('process.exe')
C = Process('proc2.exe')
result = pipeline(A, B, C, Lines()) # Text result
result = pipeline(A, B, C, Bytes()) # Binary result
pipeline(A, B, C, file("somefile","wb")) # dump to binary file

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


Re: Telnet Server Lib

2006-04-19 Thread Diez B. Roggisch
[EMAIL PROTECTED] wrote:

> I have been working on a project for some time now, that has various
> types of admistrating including a CGI web interface, In a previous
> version I implemented a Psuedo-Telnet Server if you will, bassicly all
> it did was print text to the client, and expect back data, it did not
> work with any of the protocol needless to say it was a mess, instead of
> programming my own library for the project (Which is a whole nother
> project.) Knowing that writing your own telent server is serious
> buisness, I have tried googling this and found nothing of relevancy. Do
> any of you know of or used any library for telnet servers?

Look at twisted. Might do what you want.

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


[OT] jEdit [was: Re: Why new Python 2.5 feature "class C()" return old-style class ?]

2006-04-19 Thread Wildemar Wildenburger
Ant wrote:
> (OT) I don't have the same issue with Syntax highlighting, and I use
> jEdit as my main Python editor (Though some of the dedicated Python
> IDE's have some nice refactoring/code completion stuff, none has the
> raw editing power of jEdit).
>   
Could be I got a customized python.xml file when I started ... maybe 
I'll have a look.

> I'm using jEdit 4.3 pre3 - though I don't recall any problems with 4.2
> (and it was only a week ago I changed).
I'm cautious on the pre's ... how much of an improvement is it (feature- 
and otherwise)?

> The Jython plugin enables
> Structure browsing if you haven't already got it installed
Really? I got it with the JPyDebug ... but perhaps that includes Jython.
I'll be looking into Jython soon, as I could use a plugin (for AGAST) 
and I'm not learning Java just for that!

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


help wanted regarding displaying Japanese characters in a GUI using QT and python

2006-04-19 Thread prats
I want to write a GUI application in PYTHON using QT. This application
is supposed to take in Japanese characters. I am using PyQt as the
wrapper for using QT from python. I am able to take input in japanese.
But I am unable to display them back to GUI. It displays some junk
characters Can anyone suggest me some way how to debug the issue.

The code used for tranferring data from view to document is:

"
codec = QTextCodec.codecForName('ISO-2022-JP')
encoded_string = codec.fromUnicode( string )
return str(encoded_string)
"

here string is QString object containing the data from the view.
I think the encoded_string is a QCString object and contains the
unicode coded characters of the japanese string given in the GUI?

how am I going to display the data back to the view from document.

I would be really grateful if somebody helps me in this regard.

Regards,
Pratik

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


Re: Ironpython book?

2006-04-19 Thread John Salerno
[EMAIL PROTECTED] wrote:
> Anyone know if there is a book for Ironpython in the works? A good
> knowledge of .NET and Python is enough to get started but just poking
> around Ironpython homepage it seems like there are some new language
> features added to handle some quirks with working within the CLR.
> Although I could be wrong. 
> 
> Thanks
> 
> -Jake
> 

Just out of curiosity, is Python.NET a dead project?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: local greediness ???

2006-04-19 Thread Paul McGuire
<[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> hi, all. I need to process a file with the following format:
> $ cat sample
> [(some text)2.3(more text)4.5(more text here)]
> [(aa bb ccc)-1.2(kdk)12.0(xxxyyy)]
> [(xxx)11.0(bbb\))8.9(end here)]
> ...
>
> my goal here is for each line, extract every '(.*)' (including the
> round
> brackets, put them in a list, and extract every float on the same line
> and put them in a list..

Are you wedded to re's?  Here's a pyparsing approach for your perusal.  It
uses the new QuotedString class, treating your ()-enclosed elements as
custom quoted strings (including backslash escape support).

Some other things the parser does for you during parsing:
- converts the numeric strings to floats
- processes the \) escaped paren, returning just the )
Why not? While parsing, the parser "knows" it has just parsed a floating
point number (or an escaped character), go ahead and do the conversion too.

-- Paul
(Download pyparsing at http://pyparsing.sourceforge.net.)


test = r"""
[(some text)2.3(more text)4.5(more text here)]
[(aa bb ccc)-1.2(kdk)12.0(xxxyyy)]
[(xxx)11.0(bbb\))8.9(end here)]
"""
from pyparsing import oneOf,Combine,Optional,Word,nums,QuotedString,Suppress

# define a floating point number
sign = oneOf("+ -")
floatNum = Combine( Optional(sign) + Word(nums) + "." + Word(nums) )

# have parser convert to actual floats while parsing
floatNum.setParseAction(lambda s,l,t: float(t[0]))

# define a "quoted string" where ()'s are the opening and closing quotes
parenString = QuotedString("(",endQuoteChar=")",escChar="\\")

# define the overall entry structure
entry = Suppress("[") + parenString + floatNum + parenString + floatNum +
parenString + Suppress("]")

# scan for floats
for toks,start,end in floatNum.scanString(test):
print toks[0]
print

# scan for paren strings
for toks,start,end in parenString.scanString(test):
print toks[0]
print

# scan for entries
for toks,start,end in entry.scanString(test):
print toks
print

Gives:
2.3
4.5
-1.2
12.0
11.0
8.9

some text
more text
more text here
aa bb ccc
kdk
xxxyyy
xxx
bbb)
end here

['some text', 2.2998, 'more text', 4.5, 'more text here']
['aa bb ccc', -1.2, 'kdk', 12.0, 'xxxyyy']
['xxx', 11.0, 'bbb)', 8.9004, 'end here']



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


problems installling scipy.weave on windows

2006-04-19 Thread Julien Fiore
Hi,

I have problems trying to install the scipy.weave package. I run Python
2.4 on windows XP and my C compiler is MinGW.
Below is the output of scipy.weave.test(). I read that the tests should
last several minutes, but in my case it only lasts a few seconds.

Thanks in advance for any help.

Julien Fiore


>>> import scipy.weave
>>> scipy.weave.test()
  Found 16 tests for scipy.weave.slice_handler
  Found 0 tests for scipy.weave.c_spec
  Found 2 tests for scipy.weave.blitz_tools
building extensions here:
c:\docume~1\julien~1\locals~1\temp\Julien\python24_compiled\m10
  Found 1 tests for scipy.weave.ext_tools
  Found 74 tests for scipy.weave.size_check
  Found 9 tests for scipy.weave.build_tools
  Found 0 tests for scipy.weave.inline_tools
  Found 1 tests for scipy.weave.ast_tools
  Found 0 tests for scipy.weave.wx_spec
  Found 3 tests for scipy.weave.standard_array_spec
  Found 26 tests for scipy.weave.catalog
  Found 0 tests for __main__
...EE..E..EEEE...warning:
specified build_dir '_bad_path_' does not exist or is not writable.
Trying default locations
.warning: specified build_dir '_bad_path_' does not exist or is not
writable. Trying default locations
removing
'c:\docume~1\julien~1\locals~1\temp\tmpsavufxcat_test' (and everything
under it)
error removing c:\docume~1\julien~1\locals~1\temp\tmpsavufxcat_test:
c:\docume~1\julien~1\locals~1\temp\tmpsavufxcat_test\win3224compiled_catalog:
Permission denied
error removing c:\docume~1\julien~1\locals~1\temp\tmpsavufxcat_test:
c:\docume~1\julien~1\locals~1\temp\tmpsavufxcat_test: Directory not
empty
.removing 'c:\docume~1\julien~1\locals~1\temp\tmpt-_vddcat_test' (and
everything under it)
.
==
ERROR: check_error1
(scipy.weave.size_check.test_size_check.test_dummy_array)
--
Traceback (most recent call last):
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 99, in check_error1
self.generic_error_test(x,y)
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 134, in generic_error_test
self.generic_test('',x,y)
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 131, in generic_test
self.assert_array_equal('',actual,desired)
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 110, in assert_array_equal
assert(actual == desired)
  File "C:\Python24\lib\site-packages\scipy\weave\size_check.py", line
122, in __cmp__
if len(self.shape) == len(other.shape) == 0:
AttributeError: 'tuple' object has no attribute 'shape'

==
ERROR: check_error2
(scipy.weave.size_check.test_size_check.test_dummy_array)
--
Traceback (most recent call last):
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 102, in check_error2
self.generic_error_test(x,y)
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 134, in generic_error_test
self.generic_test('',x,y)
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 131, in generic_test
self.assert_array_equal('',actual,desired)
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 110, in assert_array_equal
assert(actual == desired)
  File "C:\Python24\lib\site-packages\scipy\weave\size_check.py", line
122, in __cmp__
if len(self.shape) == len(other.shape) == 0:
AttributeError: 'tuple' object has no attribute 'shape'

==
ERROR: check_1d_3
(scipy.weave.size_check.test_size_check.test_dummy_array_indexing)
--
Traceback (most recent call last):
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 207, in check_1d_3
if nx.which[0] != "numarray":
AttributeError: 'module' object has no attribute 'which'

==
ERROR: check_1d_6
(scipy.weave.size_check.test_size_check.test_dummy_array_indexing)
--
Traceback (most recent call last):
  File
"C:\Python24\lib\site-packages\scipy\weave\tests\test_size_check.py",
line 214, in check_1d_6
if nx.which[0] != "numarray":
AttributeError: 'module' object has no attribute 'which'

==
ERROR: through a bunch of different indexes at it for good measure.
--
Traceback (most recent call last):
  File
"C:\Python24\lib\site-packages\sci

Re: semi-[OT]: adding a reply-to line to these mails?

2006-04-19 Thread Wildemar Wildenburger
Ben Finney wrote:
> Wildemar Wildenburger <[EMAIL PROTECTED]> writes:
>
>   
>> I've noticed that I replied to individual posters' private addresses 
>> several times now ...
>> 
>
> That's a much preferable, and much more easily corrected, error than
> the alternative: replying to the entire group what was intended only
> for the individual in private.
>
>   
>> So a quick note to the admin(s): see topic ;)
>> 
>
> The Reply-To header field is to be set by an individual on their own
> messages, to indicate where a *private* reply should go.
>
>   

I guess that means no, huh?

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


items in an array

2006-04-19 Thread [EMAIL PROTECTED]
Hi All -

I am working on a project in which I generate an array of values
(list_array).  I need to use the values in this array to create list
similar to the one below:

  list_array = []
  list = item1,item2,itemN...

I am having difficulty in getting the values out of the original array.
 I have tried enumerating over the array, but the results are not what
I need.  When I attempt to simply print list, I get the following
output:

  print list
  ['item1',  'item2', ..., 'itemN']

I can get list to be how I want it if I use the index value as follows:

  list = ("%s" + "," + "%s", ...) % (list_array[0], list_array[1], ...

However, the list_array will never contain a constant number of items.
So my dilema is how to loop/iterate through list_array to create list
in the format I want.

Any suggestions are greatly appreciated.

-Shawn

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


Re: Missing interfaces in Python...

2006-04-19 Thread Neal Becker
[EMAIL PROTECTED] wrote:

> I'm coming from a Java background, so please don't stone me...
> 
> I see that Python is missing "interfaces". The concept of an interface
> is a key to good programming design in Java, but I've read that they
> aren't really necessary in Python. I am wondering what technique I can
> use in Python to get the same benefits to a program design that I would
> get with interfaces in Java.
> 
> For example, if I want to have a program with a Car object, and a Bus
> object. I want both of these objects to present a common group of
> methods that can be used by Mechanic objects, but slightly different
> methods that can be used by Driver objects.
> 
> In Java I would accomplish this by defining an IFixable interface that
> would be implemented by both the Car and Bus objects. Mechanic objects
> would work with any object implementing this interface.
> 
> How would I approach this problem in Python? I think I would use an
> abstract class instead of an interface for IFixable, since Python
> supports multiple inheritance, but I'm not sure this is correct.
> 
> Thanks for any suggestions.
> 

I see various answers that Python doesn't need interfaces.  OTOH, there are
responses that some large Python apps have implemented them (e.g., zope). 
Does anyone have an explanation of why these large systems felt they needed
to implement interfaces?

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


Re: items in an array

2006-04-19 Thread Tim Chase
>   list_array = []
>   list = item1,item2,itemN...

My first recommendation would be that you not use "list" as 
an identifier, as it's a builtin function.  Odd bugs might 
start happening if you redefine it.

> I can get list to be how I want it if I use the index value as follows:
> 
>   list = ("%s" + "," + "%s", ...) % (list_array[0], list_array[1], ...

If I understand correctly what you want, you're looking to 
create a string that consists of commas separating each 
element of your array.  In such case, what you want is

result = ",".join(list_array)

or if you want spaces after your commas, the boringly 
trivial modification:

result = ", ".join(list_array)

If instead you want the result as a tuple, you can just use 
the tuple() function:

tuple_result = tuple(list_array)

If you want a tuple containing just the one string (which it 
strangely seems like your example is doing), you can do

one_string_tuple = (",".join(list_array),)

(note the peculiar "trailing comma in parens creates a 
one-element tuple" syntax...it often catches new Python 
programmers off-guard)

HTH,

-tim





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


Re: Missing interfaces in Python...

2006-04-19 Thread Alex Martelli
Roy Smith <[EMAIL PROTECTED]> wrote:
   ...
> > A class asserting, e.g., "implements IPainter", doesn't thereby risk
> > being accidentally misused where an IGunslinger is required (OTOH,
> > implementing >1 of these IS a bother, but that's sort of inevitable).
> 
> I suppose, but all you've really done is move the problem to a different
> namespace.  Which IPainter did you have in mind?  The one that has to do
> with people who apply oils to canvas, or the one that has to do with ropes
> that are used to tie up rowboats?

In Java's excellent naming convention for modules, there's no ambiguity:
I specifically requested it.aleax.artists.IPainter, or else specifically
requested com.panix.roy.boating.IPainter -- nothing stops any language
with a structured namespace for modules from using that convention.


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


Re: items in an array

2006-04-19 Thread Ant
If you just want the items concatenated with a comma separator, the
following is what you need:

>>> list_arr = ["one", "two", "three"]
>>> list = ",".join(list_arr)
>>> print(list)
one,two,three

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


Re: items in an array

2006-04-19 Thread Renato
>>> list_array = ['aaa','bbb','ccc']
>>> for item in list_array:
... print item + ',',
...
aaa, bbb, ccc,


(notice the comma at the end of the print statement: this causes the
suppression of the automatic newline)

Is this what you need?

-- 
Renato Ramonda

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


Re: items in an array

2006-04-19 Thread Daniel Nogradi
> I am working on a project in which I generate an array of values
> (list_array).  I need to use the values in this array to create list
> similar to the one below:
>
>   list_array = []
>   list = item1,item2,itemN...
>
> I am having difficulty in getting the values out of the original array.
>  I have tried enumerating over the array, but the results are not what
> I need.  When I attempt to simply print list, I get the following
> output:
>
>   print list
>   ['item1',  'item2', ..., 'itemN']
>
> I can get list to be how I want it if I use the index value as follows:
>
>   list = ("%s" + "," + "%s", ...) % (list_array[0], list_array[1], ...
>
> However, the list_array will never contain a constant number of items.
> So my dilema is how to loop/iterate through list_array to create list
> in the format I want.
>
> Any suggestions are greatly appreciated.

I'm not sure if I understand exactly what you want, but if all you
need is turning a list into a tuple then just use the function tuple:

>>> mylist = [ 1, 2, 3 ]
>>> mytuple = tuple( mylist )
>>> print mylist
[1, 2, 3]
>>> print mytuple
(1, 2, 3)
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing interfaces in Python...

2006-04-19 Thread Roy Smith
Alex Martelli <[EMAIL PROTECTED]> wrote:
>Roy Smith <[EMAIL PROTECTED]> wrote:
>   ...
>> > A class asserting, e.g., "implements IPainter", doesn't thereby risk
>> > being accidentally misused where an IGunslinger is required (OTOH,
>> > implementing >1 of these IS a bother, but that's sort of inevitable).
>> 
>> I suppose, but all you've really done is move the problem to a different
>> namespace.  Which IPainter did you have in mind?  The one that has to do
>> with people who apply oils to canvas, or the one that has to do with ropes
>> that are used to tie up rowboats?
>
>In Java's excellent naming convention for modules, there's no ambiguity:
>I specifically requested it.aleax.artists.IPainter, or else specifically
>requested com.panix.roy.boating.IPainter -- nothing stops any language
>with a structured namespace for modules from using that convention.

This is true.  This is one of the things Java does well.


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


Re: items in an array

2006-04-19 Thread Shawn Kelley
Hi All -

Thanks to everyone for their input.  The repsonses provided are exactly
what I was looking for!

Regards -
Shawn

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


Re: Missing interfaces in Python...

2006-04-19 Thread Alex Martelli
Ben <[EMAIL PROTECTED]> wrote:
   ...
> It seems to me that a lot of python projects reimplement interfaces or
> adaption of some kind once they reach a certain size (Zope, PEAK, eggs,
> TurboGears, etc), which implies that they really do have some benefits,
> particularly in documentation.

PEAK is an interesting counterexample, particularly since Philip Eby
tends to be "ahead of the curve": it appears that he's determined that
``generic functions'' (with ``multimethods'') are a superior approach,
and seems to have convinced Guido to the point that GFs are the
alternative being actively explored for Py3k.  I will admit that, while
still undecided, I'm halfway-convinced enough not to mourn for PEP 246.

((It's possible to implement protocols, a la PyProtocols and as
advocated in PEP 246, in terms of GFs, or viceversa; in PEAK, it's
GFs-in-terms-of-protocols for strictly historical reasons, but the
advantage along various axes seems to be to the
protocols-in-terms-of-GFs camp; since protocols are a strict superset of
interfaces...))

BTW, this _could_ be seen as yet another case of "reimplementing LISP",
since Lisp/CLOS was always based on GFs/multimethods...;-).


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


Re: datetime question

2006-04-19 Thread Philippe Martin
:-)

Thanks.

Philippe


Scott David Daniels wrote:

> Jorge Godoy wrote:
>> Philippe Martin wrote:
>> 
>>> I need to get the date and time under Windows and Linux but need the
>>> information visible to the user (cannot find my words) not the sytem
>>> information (ex: a PC setup on greenwich but the date/time displayed are
>>> relative to some other place.
>> 
>> Something like this?
>> 
> import datetime
> datetime.datetime.now()
>> ...
> 
> Just so you (Phillipe) know, you are talking about "local time" vs. UTC.
>  >>> import datetime
>  >>> print datetime.datetime.now() # local
>  2006-04-18 15:25:03.14
>  >>> print datetime.datetime.utcnow() # zulu / utc / gmt
>  2006-04-18 22:25:13.625000
> 
> --Scott David Daniels
> [EMAIL PROTECTED]

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


Re: Ironpython book?

2006-04-19 Thread Alex Martelli
John Salerno <[EMAIL PROTECTED]> wrote:
   ...
> Just out of curiosity, is Python.NET a dead project?

AFAIK, it's a long-completed research project. I do not know of anybody
planning to fork it to a new project, though that of course does not
rule out that somebody might be planning to do so.


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


Re: items in an array

2006-04-19 Thread Sion Arrowsmith
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>I can get list to be how I want it if I use the index value as follows:
>
>  list = ("%s" + "," + "%s", ...) % (list_array[0], list_array[1], ...
>
>However, the list_array will never contain a constant number of items.
>So my dilema is how to loop/iterate through list_array to create list
>in the format I want.

I think what you want is:

list_string = ",".join(list_array)

(Don't use the name "list" as it shadows the builtin "list".)

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: multiline comments

2006-04-19 Thread Sion Arrowsmith
Edward Elliott  <[EMAIL PROTECTED]> wrote:
>On top of that, the expressive power of nested comments seems greater than 
>an endless string of ^#s.  Sometimes it's just easier to see what's going on.

Really? Under what circumstances is it easier to see what's going on
with start/end comments than with comment-to-end-of-line?

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: 2.5 excitement (was Re: Java Developer Exploring Python)

2006-04-19 Thread Fredrik Lundh
Jon Ribbens wrote:

> "The distributors"? Que?

all the downstream people who work their asses off to provide pre-
built, pre-tested distributions for various platforms.  this includes the
PSF volunteers, commercial actors, and a large crowd of linux/bsd
volunteers.

these days, most end users get their Python either with their OS,
or by downloading a prebuilt installer.

> I guess I just don't get why the inclusion of the pysqlite wrapper
> is so exciting if all it's doing is changing the situation from
> "Python does not come with a DB, but you can install extra software
> to provide one" to "Python does not come with a DB, but you can
> install extra software to provide one".

I assume you stopped reading at "just as they've included zlib, dbm,
tcl/tk, openssl, and many other standard libraries over the years."

sqlite is not exactly Python's first external depency (check the depency
lists for a typical linux distribution if you don't believe me)





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


Re: multiline comments

2006-04-19 Thread Sion Arrowsmith
Jorge Godoy  <[EMAIL PROTECTED]> wrote:
>Is it harder to remove "n" lines of code commented out with "#" than "n"
>lines of multiline commented code?  How?

I'd say it's harder to remove the latter, due to having to search for
the end of comment sequence, rather than simply looking for where the
block comment stops. And you've extra problems if you allow nested
comments, because then you'll have to count how deep you've gone. Of
course, if you can completely trust your editor's syntax highlighter
you might be OK, but wasn't part of the point of this argument about
not *requiring* smart editors to be productive?

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
  ___  |  "Frankly I have no feelings towards penguins one way or the other"
  \X/  |-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

accessing a classes code

2006-04-19 Thread Ryan Krauss
I have a set of Python classes that represent elements in a structural
model for vibration modeling (sort of like FEA).  Some of the
parameters of the model are initially unknown and I do some system
identification to determine the parameters.  After I determine these
unknown parameters, I would like to substitute them back into the
model and save the model as a new python class.  To do this, I think
each element needs to be able to read in the code for its __init__
method, make the substitutions and then write the new __init__ method
to a file defining a new class with the now known parameters.

Is there a way for a Python instance to access its own code
(especially the __init__ method)?  And if there is, is there a clean
way to write the modified code back to a file?   I assume that if I
can get the code as a list of strings, I can output it to a file
easily enough.

I am tempted to just read in the code and write a little Python script
to parse it to get me the __init__ methods, but that seems like
reinventing the wheel.

Thanks,

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


Re: Ironpython book?

2006-04-19 Thread John Salerno
Alex Martelli wrote:
> John Salerno <[EMAIL PROTECTED]> wrote:
>...
>> Just out of curiosity, is Python.NET a dead project?
> 
> AFAIK, it's a long-completed research project. I do not know of anybody
> planning to fork it to a new project, though that of course does not
> rule out that somebody might be planning to do so.

But is IronPython sort of the 'official' .NET implementation of Python 
though? I know there is a difference between the two, but I haven't 
heard about Python.NET in so long that I thought maybe it wasn't being 
developed/used anymore. IronPython seems to be the equivalent of Jython 
for .NET.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiline comments

2006-04-19 Thread Jorge Godoy
Sion Arrowsmith wrote:

> I'd say it's harder to remove the latter, due to having to search for
> the end of comment sequence, rather than simply looking for where the
> block comment stops. And you've extra problems if you allow nested
> comments, because then you'll have to count how deep you've gone. Of
> course, if you can completely trust your editor's syntax highlighter
> you might be OK, but wasn't part of the point of this argument about
> not *requiring* smart editors to be productive?

Also, if you remove the start of the block first, then your editor might not
be highlighting anymore...  With nested comments things get even worse
because you might miss the end of the outer block or something like that.

-- 
Jorge Godoy  <[EMAIL PROTECTED]>

"Quidquid latine dictum sit, altum sonatur."
- Qualquer coisa dita em latim soa profundo.
- Anything said in Latin sounds smart.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ironpython book?

2006-04-19 Thread Fredrik Lundh
Alex Martelli wrote:

> > Just out of curiosity, is Python.NET a dead project?
>
> AFAIK, it's a long-completed research project. I do not know of anybody
> planning to fork it to a new project, though that of course does not
> rule out that somebody might be planning to do so.

brian's latest development blog entry is from april 13th, this year.

http://brianlloyd.blogspot.com/

"I'm happy to say its been a pretty busy month in Python
for .NET-land"





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


Re: Ironpython book?

2006-04-19 Thread Alex Martelli
John Salerno <[EMAIL PROTECTED]> wrote:

> Alex Martelli wrote:
> > John Salerno <[EMAIL PROTECTED]> wrote:
> >...
> >> Just out of curiosity, is Python.NET a dead project?
> > 
> > AFAIK, it's a long-completed research project. I do not know of anybody
> > planning to fork it to a new project, though that of course does not
> > rule out that somebody might be planning to do so.
> 
> But is IronPython sort of the 'official' .NET implementation of Python
> though? I know there is a difference between the two, but I haven't 
> heard about Python.NET in so long that I thought maybe it wasn't being
> developed/used anymore. IronPython seems to be the equivalent of Jython
> for .NET.

Sure, particularly since both Jython and IronPython are brainchildren of
Jim Hugunin.  But, apparently, we're having communication problems.
Since I say that Python.NET is "a long-completed research project", what
contradition do you find between that and your opinion that "it [isn't]
being developed/used anymore"?  Why should a research project, that was
finished years ago and to which (to the best of my knowledge) no
followup is planned, be "developed" any further?

IOW, although I believe it's absurd to call a research project "dead"
when it's completed, I know of no current nor planned development for
Python.NET.


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


Re: 2.5 excitement (was Re: Java Developer Exploring Python)

2006-04-19 Thread Aahz
In article <[EMAIL PROTECTED]>,
Jon Ribbens  <[EMAIL PROTECTED]> wrote:
>
>I guess I just don't get why the inclusion of the pysqlite wrapper
>is so exciting if all it's doing is changing the situation from
>"Python does not come with a DB, but you can install extra software
>to provide one" to "Python does not come with a DB, but you can
>install extra software to provide one".

There's a difference between "needing to install extra software" and
"compiling Python allows you to use your installed software".
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"LL YR VWL R BLNG T S"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: freakin out over C++ module in python

2006-04-19 Thread nephish
wow , thanks for the tips and the link.. i can at least see whats going
on here.
this project is beginning to look believable to me.

i have another question.. later , in this same class, after it goes
thru some error handling, it returns like this
return COM_SUCCESS;
but i cannot find where COM_SUCCESS is defined.
can something in C++ just represent itself?

thanks again for all your help.

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


Re: help wanted regarding displaying Japanese characters in a GUI using QT and python

2006-04-19 Thread David Boddie
[Posting via Google's web interface again and hoping that double
newlines will prevent insane concatenation of lines...]


prats wrote:


> I want to write a GUI application in PYTHON using QT. This application
> is supposed to take in Japanese characters. I am using PyQt as the
> wrapper for using QT from python. I am able to take input in japanese.
> But I am unable to display them back to GUI. It displays some junk
> characters Can anyone suggest me some way how to debug the issue.


> The code used for tranferring data from view to document is:


> "
> codec = QTextCodec.codecForName('ISO-2022-JP')
> encoded_string = codec.fromUnicode( string )
> return str(encoded_string)
> "


> here string is QString object containing the data from the view.
> I think the encoded_string is a QCString object and contains the
> unicode coded characters of the japanese string given in the GUI?


Actually, it contains the original text in the ISO-2022-JP encoding and
not a unicode representation. You're just storing an anonymous sequence
of characters in your encoded_string variable which you then return.
Any
user interface element that receives these later on has to guess which
encoding is used to represent the text, and it sounds like it can't do
that.


> how am I going to display the data back to the view from document.


If you're using the text in the GUI, you shouldn't need to pass it
through the codec at all. It should be possible to display the original
string in any widget that can display text. Keep the text in a QString
and
it should just work.


David

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


Re: Missing interfaces in Python...

2006-04-19 Thread Rene Pijlman
Alex Martelli:
>PEAK is an interesting counterexample, particularly since Philip Eby
>tends to be "ahead of the curve":

I never noticed PEAK before. Is it well worth studying?
-- 
http://mail.python.org/mailman/listinfo/python-list


SQLite (with APSW) and transaction separate

2006-04-19 Thread Christian Stooker
Part one:
==

Hi !

I want to use SQLite database like the FireBird database: with big
isolation level.
What's that meaning ?

I have an application that periodically check some input directory,
process the elements in it, and copy them into a global database.
It is like a daemon, working in the background.

The end-user uses an another GUI application, that can create reports
from this database.

Ok. In FireBird I can do it fine that the user's app use another
transaction with READ REPEATABLE style, and the daemon use another
transaction too, with same style.

This style is correctly separate two transactions, the user see full
consistent state in database.
If daemon has been finished the work, commit and close it's transaction
- but that is not confused the user's reporter program.

Example:
I open the database for create reports from a master-detail table.
Example bills.
The code get every bills.
If daemon see a new data, it is get it, and put to the database.
Now it is see a new data. It is make insert/update sqls.

The reporter tool read the bill 002 head.
The daemon write this head, and append a new subitem to bill's subitems
table. Commit.
If ISOLATION LEVEL is low, the report can see the new subitems of the
bill, but the bill's head is not same - inconsistency we get.
Example: Bills head have 3 items, the total charge is 600$. In low Isol.
level when the daemon is add new records to this bill, the head total is
remaining 600$, but calculated subtotals are bigger than this.

In the big isolation level (repeatable read) the reporter not see the
any changes in the database only what it makes.

I can do same effect if I create "transaction aliasing code". I need to
extend my tables with recversion field that containing a timestamp value.
And every SQL I need to extend with where timestamp is...
But it is very ugly solution...

Please help me: have the SQLite same tr. isol. mechanism like FireBird ?
http://www.dotnetfirebird.org/transaction-isolation-levels
http://www.ibphoenix.com/main.nfs?a=ibphoenix&l=;KNOWLEDGEBASE;ID='377'
http://www.ibphoenix.com/main.nfs?a=ibphoenix&l=;KNOWLEDGEBASE;ID='128'
http://www.ibphoenix.com/main.nfs?a=ibphoenix&l=;KNOWLEDGEBASE;ID='129'

Thanx for your help:
dd


Part two:
=

[EMAIL PROTECTED] írta:
> DurumDara <[EMAIL PROTECTED]> wrote:
>   
>> I want to use SQLite database like the FireBird database: with big
>> isolation level.
>> 
>
> SQLite transactions are SERIALIZABLE.
>
> It is possible to force SQLite transactions to be
> READ UNCOMMITTED under some special circumstances, but
> you have to work very hard to make this happen.  By
> default, transactions are always SERIALIZABLE.
>
> SERIALIZABLE gives you everything that REPEATABLE READ
> gives you in terms of isolation.
>
> --
> D. Richard Hipp   <[EMAIL PROTECTED]>
>
>   
Hi !

I see you don't understand what I saw about.
In FireBird every transactions have a tr. number, an integer.
If isolation level is high, the transaction with lesser number does not 
see the modifications of the later opened transaction, because this 
transaction have greater number (ID), and every transaction see only 
modifications created by transactions are have lesser or equal ID.
So:
2. transaction is see 1. and 2., but does not see the 3., 4. etc, 
because every records are versioned ("stamped" with it's creator's number).
Why it is good ?
When you are a reader, and some other people are writer, you don't see 
any changes in database, because you see only your version of the database.
That's caused consistency. The later opened transactions can write 
anything to the database, if you don't reopen your transaction, you 
don't see any changes in it.
That is what I wroted about: the bill and it's items are reserved - if 
anyone change the subtotals, your total and subtotals are not changed.

Only this way makes good result in the reporter applications, because if 
anyone commit changes in databases, you don't see it, it is not confused 
the database, and reports. If you have 6. items in a bill, and anyone 
delete one of them, you don't see it. I you can see it, your bill's 
total is not equal with sum of subelements !

I maked a try with Python APSW and SQLite. This is a double threaded 
app, because it need to simulate the isolation between reader and writer.

It is use queue to send signals, and for control main/subthread.


import threading,apsw,Queue

class TestThr(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
self.IQ=Queue.Queue()
self.OQ=Queue.Queue()
   
def run(self):
try:
print "*THREAD: Thread started"
while self.IQ.empty(): pass
self.IQ.get()
print "*THREAD: <<< Prepare database"
con=apsw.Connection('test.db')
c=con.cursor()
try:
c.execute('create table a(a integer)')
c.execute('end')
e

unrecognized command line option "-Wno-long-double"

2006-04-19 Thread Dean N. Williams
Dear Python and Mac Community,

I have just successfully built gcc version 4.1.0 for my Mac OS X 10.4.6.

gcc -v
Using built-in specs.
Target: powerpc-apple-darwin8.6.0
Configured with: /usr/local/src/gcc-4.1.0/configure
Thread model: posix
gcc version 4.1.0

When I try to build Python 2.4.3, I get the following error below:

gcc -c -fno-strict-aliasing -no-cpp-precomp -mno-fused-madd 
-fno-strict-aliasing -Wno-long-double -no-cpp-precomp -mno-fused-madd 
-DNDEBUG -g -O3 -Wall -Wstrict-prototypes -I. -I./Include  
-DPy_BUILD_CORE -o Modules/python.o Modules/python.c
gcc: unrecognized option '-no-cpp-precomp'
gcc: unrecognized option '-no-cpp-precomp'
cc1: error: unrecognized command line option "-Wno-long-double"
make: *** [Modules/python.o] Error 1
Python make failed.


   What is the best solution for this unrecognized command line option?

Thanks for your help in advance,
Dean
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ironpython book?

2006-04-19 Thread John Salerno
Alex Martelli wrote:

> Jim Hugunin.  But, apparently, we're having communication problems.
> Since I say that Python.NET is "a long-completed research project", what
> contradition do you find between that and your opinion that "it [isn't]
> being developed/used anymore"?  Why should a research project, that was
> finished years ago and to which (to the best of my knowledge) no
> followup is planned, be "developed" any further?

I was just saying what my thoughts were before you told me that it was a 
completed project. What I had thought was that work on it had stopped 
and it wasn't being used anymore, perhaps because IronPython was 
becoming the main .NET implementation to use.

But it sounds like, from Fred's post, that work is still being done on 
it. My main point in asking was just that I hadn't heard as much about 
it as IronPython lately, and I was just curious what the community would 
think about two competing .NET implementations, since a big part of 
Python is having one main way to do everything (I think).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Ironpython book?

2006-04-19 Thread John Salerno
John Salerno wrote:

> But it sounds like, from Fred's post

"Fredrik". Have no idea why Fred slipped out. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Missing interfaces in Python...

2006-04-19 Thread Rene Pijlman
Neal Becker:
>I see various answers that Python doesn't need interfaces.  OTOH, there are
>responses that some large Python apps have implemented them (e.g., zope). 
>Does anyone have an explanation of why these large systems felt they needed
>to implement interfaces?

A programming language doesn't need interfaces, unless it insists on
compile time checking of just about everything.

The idea of interfaces arises from the construction and maintenance of
large and complex software systems. It provides a level of abstraction
that makes it easier to talk about a component and document what it
requires from and offers to it's environment.

Also, interfaces can make this documentation first-class objects, so test
tools, IDE's and software design tools can take advantage of it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing a classes code

2006-04-19 Thread Paul McGuire
"Ryan Krauss" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
==
I have a set of Python classes that represent elements in a structural
model for vibration modeling (sort of like FEA).  Some of the
parameters of the model are initially unknown and I do some system
identification to determine the parameters.  After I determine these
unknown parameters, I would like to substitute them back into the
model and save the model as a new python class.  To do this, I think
each element needs to be able to read in the code for its __init__
method, make the substitutions and then write the new __init__ method
to a file defining a new class with the now known parameters.

Is there a way for a Python instance to access its own code
(especially the __init__ method)?  And if there is, is there a clean
way to write the modified code back to a file?   I assume that if I
can get the code as a list of strings, I can output it to a file
easily enough.
==

Any chance you could come up with a less hacky design, such as creating a
sub-class of one of your base classes?  As in:

class BaseClass(object):
def __init__(self):
# do common base class stuff here
print "doing common base functionality"

class SpecialCoolClass(BaseClass):
def __init__(self,specialArg1, coolArg2):
# invoke common initialization stuff
# (much simpler than extracting lines of source code and
# mucking with them)
super(SpecialCoolClass,self).__init__()

# now do special/cool stuff with additional init args
print "but this is really special/cool!"
print specialArg1
print coolArg2

bc = BaseClass()
scc = SpecialCoolClass("Grabthar's Hammer", 6.02e23)

Prints:
--
doing common base functionality
doing common base functionality
but this is really special/cool!
Grabthar's Hammer
6.02e+023

If you're still stuck on generating code, at least now you can just focus
your attention on how to generate your special-cool classes, and not so much
on extracting source code from running classes.

-- Paul




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


Re: 2.5 excitement (was Re: Java Developer Exploring Python)

2006-04-19 Thread Jon Ribbens
In article <[EMAIL PROTECTED]>, Fredrik Lundh wrote:
> these days, most end users get their Python either with their OS,
> or by downloading a prebuilt installer.

Oh, ok. I've just never heard such people referred to as "the
distributors" before. It sounds like some sort of TV series! ;-)

>> I guess I just don't get why the inclusion of the pysqlite wrapper
>> is so exciting if all it's doing is changing the situation from
>> "Python does not come with a DB, but you can install extra software
>> to provide one" to "Python does not come with a DB, but you can
>> install extra software to provide one".
> 
> I assume you stopped reading at "just as they've included zlib, dbm,
> tcl/tk, openssl, and many other standard libraries over the years."

I'll assume you didn't read my post properly then, since I did no such
thing.

Never mind, it was just meant to be an innocuous question, and
I'm certainly not disagreeing with the decision to include pysqlite.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Java Developer Exploring Python

2006-04-19 Thread SPE - Stani's Python Editor
> Can anyone recommend an open source IDE for Python that runs on Linux?

A lot of SPE (http://pythonide.stani.be) users are on all kinds of
Linux flavours (but also Mac OSX and windows). I've started to use SPE
on Ubuntu. There could be some improvements. As soon as I have time
I'll implement them. If you want to try SPE, use for sure the latest
version 0.8.2.a

> Perhaps I will have to write a simple IDE for Python that integrates Glade 
> and supports pyGTK when I have some more programming experience...

Have a look at PIDA then or feel free to join the pyxides project at
that time: http://pyxides.stani.be

Stani

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


Re: accessing a classes code

2006-04-19 Thread Diez B. Roggisch
Ryan Krauss wrote:

> I have a set of Python classes that represent elements in a structural
> model for vibration modeling (sort of like FEA).  Some of the
> parameters of the model are initially unknown and I do some system
> identification to determine the parameters.  After I determine these
> unknown parameters, I would like to substitute them back into the
> model and save the model as a new python class.  To do this, I think
> each element needs to be able to read in the code for its __init__
> method, make the substitutions and then write the new __init__ method
> to a file defining a new class with the now known parameters.
> 
> Is there a way for a Python instance to access its own code
> (especially the __init__ method)?  And if there is, is there a clean
> way to write the modified code back to a file?   I assume that if I
> can get the code as a list of strings, I can output it to a file
> easily enough.
> 
> I am tempted to just read in the code and write a little Python script
> to parse it to get me the __init__ methods, but that seems like
> reinventing the wheel.

Use dictionaries for those parameters, and set them on your instances.

class Foo(object):

   def __init__(self, **unknown_params):
   for key, value in unknown_params:
   setattr(self, key, value)


HTH,

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


Re: semi-[OT]: adding a reply-to line to these mails?

2006-04-19 Thread Kelvie Wong
Is there not a "Reply to all" function in Thunderbird?  (and I'd go
shopping for plugins for TB, if not)
(Sorry, Wildemar, looks like I didn't click Reply to all :d)

On 4/19/06, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:
> Ben Finney wrote:
> > Wildemar Wildenburger <[EMAIL PROTECTED]> writes:
> >
> >
> >> I've noticed that I replied to individual posters' private addresses
> >> several times now ...
> >>
> >
> > That's a much preferable, and much more easily corrected, error than
> > the alternative: replying to the entire group what was intended only
> > for the individual in private.
> >
> >
> >> So a quick note to the admin(s): see topic ;)
> >>
> >
> > The Reply-To header field is to be set by an individual on their own
> > messages, to indicate where a *private* reply should go.
> >
> >
>
> I guess that means no, huh?
>
> :)
> --
> http://mail.python.org/mailman/listinfo/python-list
>


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


Re: accessing a classes code

2006-04-19 Thread Ryan Krauss
I think this is a lot like I am planning to do, except that the new
classes will be dynamically generated and will have new default values
that I want to specify before I write them to a file.  But how do I do
that?

Ryan

On 4/19/06, Paul McGuire <[EMAIL PROTECTED]> wrote:
> "Ryan Krauss" <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
> ==
> I have a set of Python classes that represent elements in a structural
> model for vibration modeling (sort of like FEA).  Some of the
> parameters of the model are initially unknown and I do some system
> identification to determine the parameters.  After I determine these
> unknown parameters, I would like to substitute them back into the
> model and save the model as a new python class.  To do this, I think
> each element needs to be able to read in the code for its __init__
> method, make the substitutions and then write the new __init__ method
> to a file defining a new class with the now known parameters.
>
> Is there a way for a Python instance to access its own code
> (especially the __init__ method)?  And if there is, is there a clean
> way to write the modified code back to a file?   I assume that if I
> can get the code as a list of strings, I can output it to a file
> easily enough.
> ==
>
> Any chance you could come up with a less hacky design, such as creating a
> sub-class of one of your base classes?  As in:
>
> class BaseClass(object):
> def __init__(self):
> # do common base class stuff here
> print "doing common base functionality"
>
> class SpecialCoolClass(BaseClass):
> def __init__(self,specialArg1, coolArg2):
> # invoke common initialization stuff
> # (much simpler than extracting lines of source code and
> # mucking with them)
> super(SpecialCoolClass,self).__init__()
>
> # now do special/cool stuff with additional init args
> print "but this is really special/cool!"
> print specialArg1
> print coolArg2
>
> bc = BaseClass()
> scc = SpecialCoolClass("Grabthar's Hammer", 6.02e23)
>
> Prints:
> --
> doing common base functionality
> doing common base functionality
> but this is really special/cool!
> Grabthar's Hammer
> 6.02e+023
>
> If you're still stuck on generating code, at least now you can just focus
> your attention on how to generate your special-cool classes, and not so much
> on extracting source code from running classes.
>
> -- Paul
>
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing a classes code

2006-04-19 Thread bruno at modulix
Ryan Krauss wrote:
> I have a set of Python classes that represent elements in a structural
> model for vibration modeling (sort of like FEA).  Some of the
> parameters of the model are initially unknown and I do some system
> identification to determine the parameters.  After I determine these
> unknown parameters, I would like to substitute them back into the
> model and save the model as a new python class. 

Why ? Python is dynamic enough to let you modify classes at runtime...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: extracting a substring

2006-04-19 Thread rx

> and I want to extract the numbers 531, 2285, ...,359.
>
> One thing for sure is that these numbers are the ONLY part that is
> changing; all the other characters are always fixed.
>

I'm not sure about what you mean by "always fixed" but I guess it means that 
you have n files with a fixed start and a changing ending, and m files with 
a fixed start and a changing ending, 

import re
filenames=['ac99_124.txt', 'ac99_344.txt', 'ac99_445.txt']
numbers=[]
for i in filenames:

numbers.append(int(re.compile('[^_]*_(?P[^.]*).txt').match(i).group('number')))



this sets numbers to: [124, 344, 445] 


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


Re: accessing a classes code

2006-04-19 Thread Ryan Krauss
Because I want to store the results in one place so that in order to
use the code later, all I have to do is import the classes that
include the parameters that were previously unknown.  I want to make
using the results as easy and clean as possible for other users.

Ryan

On 4/19/06, bruno at modulix <[EMAIL PROTECTED]> wrote:
> Ryan Krauss wrote:
> > I have a set of Python classes that represent elements in a structural
> > model for vibration modeling (sort of like FEA).  Some of the
> > parameters of the model are initially unknown and I do some system
> > identification to determine the parameters.  After I determine these
> > unknown parameters, I would like to substitute them back into the
> > model and save the model as a new python class.
>
> Why ? Python is dynamic enough to let you modify classes at runtime...
>
> --
> bruno desthuilliers
> python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
> p in '[EMAIL PROTECTED]'.split('@')])"
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


C API - Conversions from PyInt or PyFloat to a char *

2006-04-19 Thread [EMAIL PROTECTED]
Hi,

I'm looking at the C API and wanting to know a good way to convert
Python numeric types to native c types.  For strings I've been using
PyString_AsString(v) and thats great, but I would like to do the same
for ints and floats.  I have found PyFloat_AsString in the  source but
it seems to be undocumented and some of the comments make me think that
I shouldn't use it but I've given it a go anyhow.  It is defined in
floatobject.h as:

PyAPI_FUNC(void) PyFloat_AsString(char*, PyFloatObject *v);

and also:

PyAPI_FUNC(void) PyFloat_AsReprString(char*, PyFloatObject *v);

And I have a few questions:

Should I use these calls?  And the comment that I am concerned about
from floatobject.c is:

315 /* XXX PyFloat_AsString and PyFloat_AsReprString should be
deprecated:
316XXX they pass a char buffer without passing a length.
317 */

OK so what the caller can manage the buf len, but is there something
else I should be concerned about?

If these types of calls are the way to go, is there a call for int?
And how should I convert a PyObject to a PyFloatObject?

If this isn't a good approach, what is?

thanks,

~jason

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


RE: Help needed on COM issue

2006-04-19 Thread Stefan Schukat
Hi, 

the feature you expierenced are parameterized properties. This is only
supported 
by VB and could only be emulated in python. If you use makepy/gencache
to generate a wrapper 
the appropriate Set methods are created:

oR.SetItem(1,2, "4")

Stefan

> -Original Message-
> From: [EMAIL PROTECTED] 
> [mailto:[EMAIL PROTECTED] On 
> Behalf Of Mike Howard
> Sent: Wednesday, April 12, 2006 1:12 AM
> To: python-list@python.org
> Subject: Help needed on COM issue
> 
> I'm doing some conversion of vb code to python code and I 
> have a problem with a COM object
> 
> Specifically in VB I can do
> Set oR = oA.Action
> debug.print oR.Item(1,2)
>  [returns say "1"]
> oR.Item(1,2)="4"
> debug.print oR
>  [returns "4"]
> 
> In Python I need to do ..
> 
> oR=oA.Action()
> print oR.Item(1,2)[0]
>  [returns say "1"]
> oR.Update
>  [saves the record with the new item]
> 
> But when I ty to update the value
> 
> oR.Item(1,2)[0]="4"
> 
> I get a TypeError : object doesn't support item assignment.
> 
> I presume this is because Python is returning oR as a tupe - 
> hence the need to refer to Item(1,2)[0] - but I can't figure 
> out the equivalent method to update the value I need.
> 
> Any help appreciated.
> 
> --
> http://mail.python.org/mailman/listinfo/python-list
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: C API - Conversions from PyInt or PyFloat to a char *

2006-04-19 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I'm looking at the C API and wanting to know a good way to convert
> Python numeric types to native c types.  For strings I've been using
> PyString_AsString(v) and thats great, but I would like to do the same
> for ints and floats.

double d = PyFloat_AsDouble(v);
long i = PyInt_AsLong(v);

double real = PyComplex_RealAsDouble(v);
double imag = PyComplex_ImagAsDouble(v);
Py_complex c = PyComplex_AsCComplex(v);

long i = PyLong_AsLong(v);
unsigned long y = PyLong_AsUnsignedLong(v);
double d = PyLong_AsDouble(v);
PY_LONG_LONG l = PyLong_AsLongLong(v);
// and others; see include/longobject.h for details

the float and int versions also available as "unsafe" macro versions

double d = PyFloat_AS_DOUBLE(v);
int i = PyInt_AS_LONG(op);

(the macro versions assume that that v points to a python object of the
right type; it's up to you to do the type check)





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


Re: Missing interfaces in Python...

2006-04-19 Thread bruno at modulix
Neal Becker wrote:
(snip)
> I see various answers that Python doesn't need interfaces.  OTOH, there are
> responses that some large Python apps have implemented them (e.g., zope). 
> Does anyone have an explanation of why these large systems felt they needed
> to implement interfaces?

These "interface" ("protocol" would be a better name IMHO) systems are
not exactly the same as Java's interfaces. They are mainly used a a way
to describe components and allow for component adaptation and
substitutability. Think of it as a highly decoupled pluggable component
system, not as a language-level subtyping mechanism. BTW, you'll notice
that these projects (Zope, Twisted, PEAK, ...) are mostly large frameworks.

My 2 cents...
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: accessing a classes code

2006-04-19 Thread rx

"Ryan Krauss" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

Is there a way for a Python instance to access its own code
(especially the __init__ method)?  And if there is, is there a clean
way to write the modified code back to a file?   I assume that if I
can get the code as a list of strings, I can output it to a file
easily enough.



You are talking about writing code from and to a file. I think I had a 
similar problem, because I wanted a python class to contains some persistent 
runtime variables (fx the date of last backup) I didn't found a solution in 
the python library so I wrote a little class myself:

import cPickle
class Persistent:
def __init__(self,filename):
self.filename=filename
def save(self):
f=file(self.filename, 'wb')
try:
for i in vars(self):
val=vars(self)[i]
if not i[0:2]=='__':
cPickle.dump(i,f)
cPickle.dump(val,f)
finally:
f.close()
def load(self):
f=file(self.filename)
try:
while True:
name=cPickle.load(f)
value=cPickle.load(f)
setattr(self,name,value)
except EOFError:
f.close()
f.close()


You just use it like (the file has to exist - easy to change):

p=Persistent('file.obj')
p.load()
p.a=0.12345
p.b=0.21459
p.save()


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


Re: How protect proprietary Python code? (bytecode obfuscation?, what better?)

2006-04-19 Thread bruno at modulix
Ben Sizer wrote:
> bruno at modulix wrote:
> 
>>[EMAIL PROTECTED] wrote:
>>
>>>I suppose another idea is to rewrite entire Python app in C if compiled
>>>C code
>>>is harder to decompile.
>>
>>Do you really think "native" code is harder to reverse-engineer than
>>Python's byte-code ?
> 
> 
> Yes, until there's a native code equivalent of "import dis" that
> telepathically contacts the original programmer to obtain variable
> names that aren't in the executable.

Lol !-)

Ok, granted. Let's rephrase it:
"do you really think that native code is harder *enough* to
reverse-engineer ?"

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


+= append class operator

2006-04-19 Thread schwehr
Hi All,

This is probably a FAQ, but is there an operator mapping for += for
classes?  Or does a += b get converted to a = a + b?  I would like to
make this operator faster for the BitVector class, but I don't see +=
in http://docs.python.org/lib/operator-map.html

I could always create an append method, but += is nice and concise.

Thanks,
-kurt

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


What interface Can I use for Python?

2006-04-19 Thread Tomás Rodriguez Orta



Hello.
I am looking a good interface for doing app similar 
to Visaul C++, but for python over windows.
 
some can Help me.
Thanks very mouch.
 
TOMAS-
Este correo fue escaneado en busca de virus con el MDaemon Antivirus 2.27
en el dominio de correo angerona.cult.cu  y no se encontro ninguna coincidencia.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: += append class operator

2006-04-19 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> This is probably a FAQ, but is there an operator mapping for += for
> classes?

 obj.__iadd__(other)

> Or does a += b get converted to a = a + b?

only if __iadd__ is not defined.

> I would like to make this operator faster for the BitVector class, but
> I don't see += in http://docs.python.org/lib/operator-map.html

that's documentation for the operator module.

special method names are described in the language reference:

http://docs.python.org/ref/specialnames.html
http://docs.python.org/ref/numeric-types.html





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


  1   2   >