Re: Help for NewBies at WikiBooks

2005-09-03 Thread Do Re Mi chel La Si Do
Hi !

I had read the article on Python's concept  "Metaclass": zero error in 
the content !

@-salutations

Michel Claveau



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


Re: python logo

2005-09-03 Thread Steve Holden
Xah Lee wrote:
> i noticed that Python uses various logos:
> 
> http://python.org/pics/pythonHi.gif
> http://python.org/pics/PyBanner038.gif
> http://python.org/pics/PyBanner037.gif
> http://python.org/pics/PythonPoweredSmall.gif
> http://wiki.python.org/pics/PyBanner057.gif
> 
>  is this some decision that python should use various different logos?
> 
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/
> 
Yes.
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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

Re: PyBool_FromLong

2005-09-03 Thread Reinhold Birkenfeld
Michael Hoffman wrote:
> Andrew MacKeith wrote:
>> In the C API Docs, the signature of PyBool from long seems to be incorrect.
>> 
>> int PyBool_FromLong(long v)
>> Returns Py_True or Py_False depending on the truth value of v. New 
>> in version 2.3.
>> 
>> The description would suggest:
>> 
>> PyObject* PyBool_FromLong(long v)
> 
> That's in the source too (dist/src/Objects/boolobject.c, 
> dist/src/Include/boolobject.h). Want to submit a documentation bug?

Not necessary. I just fixed it.

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


Re: python logo

2005-09-03 Thread Michele Petrazzo
Xah Lee ha scritto:
> i noticed that Python uses various logos:
> 


Ok, this are not a logo, but better image are this:
http://python.org/pics/PythonIndented_Back.jpg

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


Re: python logo

2005-09-03 Thread Xah Lee
what's the decision? any reference to the discussion?

i thought it is better for Python to have one single recognizable logo.
Perhaps python doesn't have a logo and the official python people
decided it shouldn't or just doesn't have one currently?

of course, a logo helps in identity and as well as advertisement.

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

Steve Holden wrote:
> Xah Lee wrote:
> > i noticed that Python uses various logos:
> >
> > http://python.org/pics/pythonHi.gif
> > http://python.org/pics/PyBanner038.gif
> > http://python.org/pics/PyBanner037.gif
> > http://python.org/pics/PythonPoweredSmall.gif
> > http://wiki.python.org/pics/PyBanner057.gif
> >
> >  is this some decision that python should use various different logos?
> >
> >  Xah
> >  [EMAIL PROTECTED]
> > ∑ http://xahlee.org/
> >
> Yes.
> --
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC http://www.holdenweb.com/

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

Re: python logo

2005-09-03 Thread Tim Churches
Xah Lee wrote:

>i noticed that Python uses various logos:
>
>http://python.org/pics/pythonHi.gif
>http://python.org/pics/PyBanner038.gif
>http://python.org/pics/PyBanner037.gif
>http://python.org/pics/PythonPoweredSmall.gif
>http://wiki.python.org/pics/PyBanner057.gif
>
> is this some decision that python should use various different logos?
>
> Xah
> [EMAIL PROTECTED]
>∑ http://xahlee.org/
>
>  
>
"A foolish consistency is the hobgoblin of little minds."
  - Ralph Waldo Emerson

Tim C

PS Yes, I know that I shouldn't feed the trolls (or hobgoblins), but I 
invoke Screwtape's Defence: other people who should know better don't 
seem to be able to resist the temptation either...

PPS Emerson's assertion might well apply not just to Python logos, but 
also, ahem, to certain aspects of the Python standard library.

TC


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

Re: Proposal: add sys to __builtins__

2005-09-03 Thread tiissa
Michael Hoffman wrote:
> To the contrary, I agree with Larry Wall that laziness is one of the 
> cardinal virtues of a programmer.

There's lazy and too lazy.
You don't want to be too lazy to even get out of bed to code in Python. 
Of course, with Perl, that's entirely another mattress^Wmatter.


> Would you argue that the language is superior because half of its 
> modules must have "import sys" at the beginning

I wouldn't dare arguing about superiority.

I was just stating your proposal didn't really solve anything. A good 
editor/template and .pythonrc already save you the typing of 'import 
sys' in scripts for the former and shell command for the latter.


> Sorry, that's incorrect

Alright, that was a bit of an overstatement.
I should have said your proposal is perceptibly useful in those shell 
one-liners. The distribution of script and modules is another matter.


As for my opinion, you've already guessed I don't perceive 'import sys' 
as an issue. Therefore, the special case of an implicit import of sys 
does not appeal to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python logo

2005-09-03 Thread Diez B. Roggisch
> "A foolish consistency is the hobgoblin of little minds."
>  - Ralph Waldo Emerson
> 
> Tim C
> 
> PS Yes, I know that I shouldn't feed the trolls (or hobgoblins), but I 
> invoke Screwtape's Defence: other people who should know better don't 
> seem to be able to resist the temptation either...
> 
> PPS Emerson's assertion might well apply not just to Python logos, but 
> also, ahem, to certain aspects of the Python standard library.

AMEN!

and +1 QOTW

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


Re: 'isa' keyword

2005-09-03 Thread Devan L
talin at acm dot org wrote:
> Thanks for all the respones :) I realized up front that this suggestion
> is unlikely to gain approval, for reasons eloquently stated above.
> However, there are still some interesting issues raised that I would
> like to discuss.
>
> Let me first respond to a few of the comments:
>
> >What's the difference between this and ``isinstance`` ?
>
> What's the difference between 'in' and 'has_key()"? 1) Its shorter and
> more readable, 2) it can be overridden to mean different things for
> different container types.

Your analogy doesn't apply to non dictionaries. In any case, nothing
stops you from writing your own has_key() method for a different
container type. Likewise, if you made an isa keyword, it would just
call a method to have the traits you described above. You could write
your own method to see if it was an instance of the class, but it would
end up being more or less similar to isinstance().

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


Re: python logo

2005-09-03 Thread Devan L

Xah Lee wrote:
> what's the decision? any reference to the discussion?
>
> i thought it is better for Python to have one single recognizable logo.
> Perhaps python doesn't have a logo and the official python people
> decided it shouldn't or just doesn't have one currently?
>
> of course, a logo helps in identity and as well as advertisement.
>
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/
>
> Steve Holden wrote:
> > Xah Lee wrote:
> > > i noticed that Python uses various logos:
> > >
> > > http://python.org/pics/pythonHi.gif
> > > http://python.org/pics/PyBanner038.gif
> > > http://python.org/pics/PyBanner037.gif
> > > http://python.org/pics/PythonPoweredSmall.gif
> > > http://wiki.python.org/pics/PyBanner057.gif
> > >
> > >  is this some decision that python should use various different logos?
> > >
> > >  Xah
> > >  [EMAIL PROTECTED]
> > > ∑ http://xahlee.org/
> > >
> > Yes.
> > --
> > Steve Holden   +44 150 684 7255  +1 800 494 3119
> > Holden Web LLC http://www.holdenweb.com/

There should only be one obvious way to do it, but there are many
creative ways to do it too.

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

How to identify which interface a broadcast packet comes in on?

2005-09-03 Thread Lincoln Yeoh
Hi,

If I have a program listening on 0.0.0.0:(someport) on all interfaces,
how do I know which network interface a broadcast packet is coming in
on - assuming Linux and _many_ interfaces. And how do I set which
interface a frame will leave on, assuming I'm sending a raw frame (no
IP address, just the ethernet address).

If I use C, it seems I'm to use the IP_PKTINFO socket options,
send/recv the ancillary messages and set/check the  ipi_ifindex value.

struct in_pktinfo {
unsigned intipi_ifindex;/* Interface index */
struct in_addr  ipi_spec_dst;   /* Local address */
struct in_addr  ipi_addr;   /* Header Destination address
*/
};

How would I achieve the same thing in Python? 

This would be useful for writing something like a DHCP server - such a
server could receive packets with source IP addresses of 0.0.0.0
destined to 255.255.255.255, and will need to know which interface the
packet is coming in from AND the source ethernet (or other link layer)
address so that it can send the replies out the right interface.

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


embedding python in C, working but with exception at the end

2005-09-03 Thread brobigi
well I manage to figure it out myself. I'm using Bloodshed Dev-cpp
Here's the code:


#include "python.h"
#include 

int main(int argc, char* argv[])
{
double answer = 0;
PyObject *modname, *mod, *mdict, *func, *stringarg, *args, *rslt;

Py_Initialize();
modname = PyString_FromString("Test");
mod = PyImport_Import(modname);
if (mod)
{
mdict = PyModule_GetDict(mod);
func = PyDict_GetItemString(mdict, "doit"); /* borrowed 
reference */
if (func)
{
if (PyCallable_Check(func))
{
stringarg = PyString_FromString("5");/*pay 
attention here*/
args = PyTuple_New(1);
PyTuple_SetItem(args, 0, stringarg);
rslt = PyObject_CallObject(func, args);
if (rslt)
{
answer = PyFloat_AsDouble(rslt);
Py_XDECREF(rslt);
}
  Py_XDECREF(stringarg);
  Py_XDECREF(args);
}
}

Py_XDECREF(mod);
}

Py_XDECREF(modname);

Py_Finalize();

printf("%g",answer);

return 0;
}

I need to add include and lib directories to the project in order to
everything works fine. Also Test.py  is copied in Dev-cpp source code's
folder.
Test file contains the following code

def doit(x1):
try:
x2 = eval(x1)
except:
print 'Error!'
return 0

else:
return x2




However there is an error. Look at the line stringarg =
PyString_FromString("5"); If I put this:
stringarg = PyString_FromString("5+2"); or even this stringarg =
PyString_FromString("5.0");
Program crashes at line Py_Finalize(). Program tries to read some
memory location and suffer run time exception.
Only suggestion is to try to send it to Microsoft.
Why is this happening?
Everything (seems to) works fine I comment line Py_Finalize(), but I
know that this is not a real solution.

Does anybode have a clue what is happening?

Thanks

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


Re: 'isa' keyword

2005-09-03 Thread phil hunt
On Sat, 03 Sep 2005 00:45:19 -0500, Steve Holden <[EMAIL PROTECTED]> wrote:
>> I'm not talking about a change in *paradigm* merely a change in 
>> *syntax*; this:
>> 
>>receiver selector argument
>> 
>> would mean the same as the current Python:
>> 
>>receiver.selector(argument)
>> 
>Aah, I see. I had assumed that "selector" was always going to be an 
>operator. 3 . (+ 4) does indeed seem very "SmallTalkative". I don't 
>think that Python method (or attribute) selection bears any relationship 
>to SmallTalk message-passing, but I hope you will feel free to enlighten me.

Let's consider the Python example first.

You have two classes A and B. Each has a method called 'selector'.

When the line of code above is executed, the Python virtual machine 
decides whether (receiver) is a member of A or B, and then executed 
one of A.selector() or B.selector() depending on which it is. 
Whichever function is executed, it is passed with (reciever) as the 
"self" argument so that the correct data is operated on.

And now let's consider the Smalltalk example. How does it do it? 
Essentially it does *exactly the same thing*.

(Yes, I know there are many differneces in detail between how 
Snalltalk and Python  work, but they are only *details*; the 
fundamental idea governing how these two object-oriented languages 
work is the same).

>>>would necessarily 
>>>benefit Python at this stage. Some people are still under the 
>>>misapprehension that message-passing is a fundamental of object-oriented 
>>>programming because of Smalltalk, but they are wrong.
>> 
>> 
>> I don't see how it can reasonably said that STK has 
>> "message-passing" but other OOPLs don't. Consider these code 
>> fragments:
>> 
>> Smalltalk:
>>receiver selector: argument
>> 
>> C++ or Java:
>>receiver.selector(argument);
>> 
>> Python:
>>receiver.selector(argument)
>> 
>> PHP:
>>$receiver->selector($argument)
>> 
>> (I'm not sure if the last one is right since I've not done much OO 
>> stuff in PHP)
>> 
>> These all mean essentially the same thing so how can one be "message 
>> passing" and the others not?
> 
>Sorry, they don't all mean "essentially the same thing" at all. It seems 
>to me you are looking at SmallTalk in entirely too superficial a light. 

OK, allow me to reprase it. Imagine a language ith the semantics of 
Python but the syntax of C++ or PHP or Smalltalk (or Lisp for that 
matter). It would still basically be Python, wouldn't it?

>  In SmallTalk, control structures aren't syntactic primitives, they are 
>also examples of message-passing, so code blocks are sent as messages to 
>objects. Python eschews such obscurity and (IMHO) gains clarity by so 
>doing. But that is, of course, a matter of opinion.

I agree, that's a major point of departure between Python and 
Smalltalk.

>Also, remember that just because two expressions in different languages 
>"mean the same thing "doesn't mean they are implemented using the same 
>techniques.

Of course not. 

CPython and JPython are different implementations, but they are 
still the same language (mostly).

>I would contend (if backed into a corner) that there is a significant 
>difference between passing the arguments 3 and 4 to a "+" operator 
>(which is what Python and most other languages implementing standard 
>ideas of operator precedence do) and sending the message "+ 4" to the 
>integer 3 (which is effectively what SmallTalk does).

In both python and smalltalk you can override the operator to mean 
what you want, so I disagree that there is any fundamental 
difference. Why do you think there is?

>Of course, I realise that you can argue that the two are equivalent in 
>the sense that they perform the same computation. But SmallTalk's choice 
>led to the loss of operator precedence, which is something that is 
>pretty fundamental to mathematics. 

Surely that's a separate issue, one purely of syntax. Imagine two 
languages:

   (* (+ a b) c)

and:

   (a + b) * c

These both mean the same thing, they just say it differently.

>Also Python allows much more 
>flexibility by hard-wiring operators and allowing alternatives to be 
>considered (if the left operand doesn't have an "__add__" method then 
>try to use the right operand's "__radd__" method). SmallTalk doesn't 
>have any parallel to this that I can think of.

You're right; in Smalltalk you'd have to code that functionality in
the method for the left-hand object.

>Of course it isn't only mathematicians who are taught to us the 
>precedence rules, so I contend that SmallTalk would seem 
>counter-intuitive in a "Programming for Everyone" context as well. 

Probably. 

However consider that a language (e.g. C++) may have lots of 
operators, e.g: & && | || << >> <= >= < > ^ % etc. Is there an 
obvious natural order of precedence for all these? I suspect that 
many C++ programmers couldn't put all its operators in the correect 
order.

>I speak as one who was partly, and in a minor way, responsible for 
>implemen

Re: Find day of week from month and year

2005-09-03 Thread Paul McGuire
Donn,

You didn't look closely enough at those results.  The OP's point was
that he did not know how to set all the tuple values correctly.  Here's
a clearer example, I think:

import time
print time.asctime((2005,9,1,0,0,0,0,0,0))
print time.asctime((2005,9,1,0,0,0,1,0,0))
print time.asctime((2005,9,1,0,0,0,2,0,0))
print time.asctime((2005,9,1,0,0,0,3,0,0))

Prints:
Mon Sep 01 00:00:00 2005
Tue Sep 01 00:00:00 2005
Wed Sep 01 00:00:00 2005
Thu Sep 01 00:00:00 2005

No matter what time zone you're in, Sep 1, 2005 can't be all those days
of the week! :)

Your code works because you use mktime, which appears to ignore the
dayOfWeek element of the input tuple, as shown by the following:

print time.asctime(time.gmtime(time.mktime((2005,9,1,0,0,0,0,0,0
print time.asctime(time.gmtime(time.mktime((2005,9,1,0,0,0,1,0,0
print time.asctime(time.gmtime(time.mktime((2005,9,1,0,0,0,2,0,0
print time.asctime(time.gmtime(time.mktime((2005,9,1,0,0,0,3,0,0

Prints:
Thu Sep 01 06:00:00 2005
Thu Sep 01 06:00:00 2005
Thu Sep 01 06:00:00 2005
Thu Sep 01 06:00:00 2005

-- Paul

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


Re: python logo

2005-09-03 Thread Fredrik Lundh
Tim Churches wrote:

> PPS Emerson's assertion might well apply not just to Python logos, but
> also, ahem, to certain aspects of the Python standard library.

you've read the python style guide, I presume?

http://www.python.org/peps/pep-0008.html

 



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


Re: embedding python in C, working but with exception at the end

2005-09-03 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> Program crashes at line Py_Finalize(). Program tries to read some
>memory location and suffer run time exception.

PyTuple_SetItem "steals" a reference, so changing

Py_XDECREF(stringarg);
Py_XDECREF(args);

to just

Py_XDECREF(args);

might fix the problem.

 



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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-09-03 Thread Scott David Daniels
Bengt Richter wrote:
> On Wed, 31 Aug 2005 14:16:28 GMT, Ron Adam <[EMAIL PROTECTED]> wrote:
> [...]
> 
>>The problem with negative index's are that positive index's are zero 
>>based, but negative index's are 1 based.  Which leads to a non 
>>symmetrical situations.
Although it is _way_ too late to try something like this, once upon
a time you could have done all of this using the one's complement
operator:
 ~0  does exist and is distinct from 0.
So you could talk about a slice:
 str[4 : ~2]
and so on.

--Scott David Daniels
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: embedding python in C, working but with exception at the end

2005-09-03 Thread jepler
I see a couple of problems.  First, because I'm using Unix, where filenames are
case-sensitive, I had to '#include "Python.h"' instead of '#include
"python.h"'.

Next, it looks like the behavior that '.' is placed on sys.path isn't done
automatically when embedding.  So I had to set the environment variable
"PYTHONPATH=." since Test.py was in the current directory.

Before I did this, I got this output:
Exception exceptions.ImportError: 'No module named Test' in 'garbage
collection' ignored
Fatal Python error: unexpected exception during garbage collection
Aborted
which was a clue about the problem you were running into.  This ImportError was
being caused back at PyImport_Import but was being transmuted into a fatal
error down at Py_Finalize().  By adding 'else { PyErr_Print(); }' to the end of
'if(mod)', I got the error message printed and cleared.  Now, garbage
collection which is kicked off by Py_Finalize() doesn't find the existing error
condition and treat it as a fatal error.

In your code, 'rslt' will be a Python Integer, not a Python Float, so
PyFloat_AsDouble will fail.  You could either write something like
if (rslt)
{   
if(PyFloat_Check(rslt)) {
answer = PyFloat_AsDouble(rslt);
} else {
printf("not a float\n");
answer = 1.0;
}
Py_XDECREF(rslt);
}
instead, or use PyErr_Check() + PyErr_Print() or PyErr_Clear().
If you want to accept integer or float returns, then maybe you want
if(PyFloat_Check(rslt)) { answer = PyFloat_AsDouble(rslt); }
else if(PyInt_Check(rslt)) { answer = PyInt_AsLong(rslt); }
else probably not a numeric type

Jeff


pgpsNcJ3ylwlJ.pgp
Description: PGP signature
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Decrypting GPG/PGP email messages

2005-09-03 Thread Alessandro Bottoni
Piet van Oostrum wrote:
> What benefit is there in encrypting the messages? It would only prevent
> people intercepting the message from seeing what's inside, but it won't
> give you any additional protection on the server.

You are right. Bad guys can still try to send garbage to my system and, with
some luck, can mess everything up. After reading your message I decided to
add some more control over what the remote user can do and how he can reach
the server:
- a list of allowed users (based on e-mail identity plus OTP, see below)
- a list of allowed commands (still with root-level ones, I'm afraid)
- chroot for the most dangerous commands, when possible
It is still dangerous but, frankly, I could not do any better.

> And if somebody can intercept the messages there is a much bigger danger:
> They could save the message and replay it later. You can't protect against
> this with encryption (well, with encryption they won't know what they
> are doing). Neither with a digital signature. Only checking timestamps,
> keeping track of the messages received and/or a challenge/response system
> will help in this case.

You are right again. As a consequence, I decided to add a one-time-password
to the encrypted message, in order to be sure of the sender identity and of
the uniqueness of the message (the OTP works as a sequence item identifier,
as well).

I'm going to use my own implementation of OTP because the existing mechanism
are devoted to protect the remote login channel and cannot be easily
adapted to my weird e-mail-based mechanism. Anyway, I'm going to use a
(encrypted) very long pseudo-random alpha-numeric sequence as a OTP so it
should be quite safe.

> If you only sign, it will be sufficient, but there is a more complete one
> (including decryption) in
> http://trac.t7a.org/isconf/file/trunk/lib/python/isconf/GPG.py

Thanks for this info. I'm studying it.

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


pyNMS

2005-09-03 Thread Colin J. Williams
The pyNMS package is available for network management using Linux.

Is there anything similar for Win32?

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


Problems with Python for Windows extensions

2005-09-03 Thread KK
the code below is taken from M$ technet as an example on using vb
script to do a replace all in word:

Const wdReplaceAll  = 2

Set objWord = CreateObject("Word.Application")
objWord.Visible = True

Set objDoc =
objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc")
Set objSelection = objWord.Selection

objSelection.Find.Text = "Contoso"
objSelection.Find.Forward = True
objSelection.Find.MatchWholeWord = True

objSelection.Find.Replacement.Text = "Fabrikam"
objSelection.Find.Execute ,,wdReplaceAll




I did a rewrite and made it pythonic:

from win32com.client import *

wdReplaceAll  = 2

objWord = Dispatch("Word.Application")
objWord.Visible = True

objDoc =
objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc")
objSelection = objWord.Selection

objSelection.Find.Text = "Contoso"
objSelection.Find.Forward = True
objSelection.Find.MatchWholeWord = True

objSelection.Find.Replacement.Text = "Fabrikam"
objSelection.Find.Execute (Replace = wdReplaceAll)


However, the document juz loaded up in word but no action was taken. I
am using Word 2003. Any ideas?

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


Re: Find day of week from month and year

2005-09-03 Thread Peter Hansen
Paul Rubin wrote:
> Peter Hansen <[EMAIL PROTECTED]> writes:
> 
>>(And, if I were "optimizing", I would of course dispense with the
>>dynamic creation of the static table upon every execution of
>>expiration(), and move it outside the function.)
> 
> Replacing it with a tuple might be enough for that.

You're right, and in fact that would actually be even faster since then 
it's a LOAD_CONST instead of a LOAD_GLOBAL.

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


Re: using common lisp with python.

2005-09-03 Thread [EMAIL PROTECTED]
Thank you all for the advice, I think I'll be writing my lisp code in
python.

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


Re: How to identify which interface a broadcast packet comes in on?

2005-09-03 Thread Jorgen Grahn
On Sat, 03 Sep 2005 18:46:05 +0800, Lincoln Yeoh <[EMAIL PROTECTED]> wrote:
> Hi,
>
> If I have a program listening on 0.0.0.0:(someport) on all interfaces,
> how do I know which network interface a broadcast packet is coming in
> on - assuming Linux and _many_ interfaces. And how do I set which
> interface a frame will leave on, assuming I'm sending a raw frame (no
> IP address, just the ethernet address).
>
> If I use C, it seems I'm to use the IP_PKTINFO socket options,
> send/recv the ancillary messages and set/check the  ipi_ifindex value.
...
> How would I achieve the same thing in Python? 

Someone may want to correct me, but from what I can see, the socket module
is almost a 1:1 mapping between the socket support your C lib has, and
Python. Plus some compatibility code for Windows.

You should be able to do everything you can do in C. Your code may
become Linux-specific if you're not careful, though.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Find day of week from month and year

2005-09-03 Thread Jorgen Grahn
On Fri, 02 Sep 2005 20:53:44 -0400, Peter Hansen <[EMAIL PROTECTED]> wrote:
> Carsten Haese wrote:
>> On Fri, 2005-09-02 at 16:46, Laguna wrote:
>>>def expiration(year, month):
>>> weekday = calendar.weekday(year, month, 1)
>>> table = [19, 18, 17, 16, 15, 21, 20]
>>> return table[weekday]
...
> True, but do you find that more readable?  If I saw that in code I was 
> maintaining I would likely rewrite it, probably to look a lot like the 
> first one (though likely with a more descriptive name than "table"... 
> maybe expirationTable?).

That doesn't explain anything, IMHO. What 'table' really is is a list of
day-of-month candidates for the third Friday.

For some pieces of code, I find that it's better to document what it /does/
than to try to document /how/ it does it. And maybe add a bunch of unit
tests to /demonstrate/ that it seems to work.

The next programmer can then choose to either (a) understand the code or (b)
rip it out and replace it.

I would leave the body alone, but rename the function 'third_friday_of_month',
and do 'expiration = third_friday_of_month'.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extend Python

2005-09-03 Thread Jorgen Grahn
On Thu, 1 Sep 2005 19:09:55 +0200, Filip Dreger <[EMAIL PROTECTED]> wrote:
>> My Question:
>> Swig offers some great features but is to basic for us. Is there
>> another program that creates more readble code that can be easily
>> edited? How much work is it to write our own wrappers?
>
> Not too much, and practicaly not at all if you want to wrap procedures 
> (not objects or types):
>  - marshaslling an argument list from Python to C and from C to Python 
> takes exactly 1 line of code,
>  - handling errors takes 2 lines of code (unless you want to do 
> something fancy with them; I mean just catching an exception and 
> getting the error message).
>  - entry in the PyMethodDef is one simple line
> Bottomline: you need 5 additional lines of C code per procedure to 
> make it usable from Python.
> Unless you have hundreds of procedures, there is no point in using 
> special tools to do that. Especially if you need full control over the 
> results.

My experience too. At least if you are a C programmer.

If it gets hard, it's because the things you wrap do something funky: take
complex memory structures as arguments, have odd resource management, etc.
A tool cannot help you with that anyway.

/Jorgen

-- 
  // Jorgen GrahnR'lyeh wgah'nagl fhtagn!
-- 
http://mail.python.org/mailman/listinfo/python-list


Managing events

2005-09-03 Thread cantabile
Hi,

I have a class (a gui) with buttons and other controls. A button, for 
example, has a callback method, so that writing

b = Button(label, OnClick)

will call the global OnClick method.

Now, if I want the OnClick method to call some of my main class methods, 
I need to write:

 UI = None
 ...
 class MainClass:
 ...
 global UI = self


Then,
def OnClik(button):
UI.do_something(button.get_label())

Is this the correct way to do it in Python ? Isn't there a potential 
flaw in declaring my MainClass instance as a global variable ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread n00m
Bryan wrote:
> Do you want to be a network engineer?
lol... definetely not! It's just my curiosity.
At my work my tools are: vba, vbs, jet-sql (ms access),
t-sql (ms sql server). The pretty humble set.

> My first two guess are:
> The client is trying to make more than one connection.
> Putting accept in a loop and moving some stuff will support
> that.
BUT your *1st version* does NOT support more than ONE client's
connection! How do I know that? I just ran several (3) instances
of my.vbs (almost) simultaneously and only the first of them could
connect to SQL Server via Python!
Just in case: SQL Server itself can accept up to 32767 clients.

Then (if I'm not wrong here) what's the difference with my own
version? Maybe replacing send() with sendall() will be quite enough
to make it working over LAN? I've NOT tested this!

PS Yes! Your last version works like a champ. It easily handles up
to 5 instances of my.vbs! Except of this thing:
> AttributeError: 'module' object has no attribute 'SHUT_WR'
Seems it's a pure Unix constant.

>> But it does NOT work without IDLE!
> Odd. What happens if you run it from a command line?
In a moment - AFTER I start my.vbs - in console window new prompt
"D:\>" appears... and vbs reports "General Network Error".

Dennis;
No no no! It's NOT firewalls trick. It's NOT db permissions issue.
VBS and SQL Server work with each other ABSOLUTELY FINE - from ANY
machine at ANY time at ANY free port - BUT WITHOUT Python being a
mediator for them.

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


Re: Decrypting GPG/PGP email messages

2005-09-03 Thread Paul Rubin
Alessandro Bottoni <[EMAIL PROTECTED]> writes:
> I'm going to use my own implementation of OTP because the existing
> mechanism are devoted to protect the remote login channel and cannot
> be easily adapted to my weird e-mail-based mechanism. Anyway, I'm
> going to use a (encrypted) very long pseudo-random alpha-numeric
> sequence as a OTP so it should be quite safe.

Be very careful.  You have to really know what you're doing to have
any chance of implementing something like this securely.  See the book
"Practical Cryptography" by Schneier and Ferguson.  You're much better
off using GPG/PGP if you can.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Bug in string.find

2005-09-03 Thread Ron Adam
Terry Reedy wrote:

>>b[-1:] = ['Z']# replaces last item
>>b[-1:-0] = ['Z']  # this doesn't work
>>
>>If you are using negative index slices, you need to check for end
>>conditions because you can't address the end of the slice in a
>>sequential/numerical way.
> 
> OK, now I understand your question, the answer 'get a one's complement 
> machine', and your point that without a -0 separate from +0, there is a 
> subtle asymmetry that is easy to overlook.

Yes, I don't thinks it falls in the catagory of bugs,  probably closer 
to a minor wart.

>>>As I posted before (but perhaps it arrived after you sent this), one 
>>>number
>>>indexing rounds down, introducing a slight asymmetry.
>>
>>I didn't see that one,
> 
> Perhaps you did not see my other long post, where I drew ascii pictures?

Yes, I saw it.  I think we are expressing the same things in different ways.


> In the US (and UK?), the ground level floor of a multifloor building is the 
> first floor.  In continental Europe (all or just some?), the ground floor 
> is the ground (effectively zeroth) floor while the first floor up is the 
> first stage (resting place on the stairway).

In the VA Hospital here in Tampa, the ground floor in the front elevator 
is on the same level as the lobby, while the ground floor in the 
elevator on the other side of the building is on the floor below. ;-)


>>I don't think people would miss negative strides much if they were
>>removed. Replacing these case's with reverse() methods shouldn't be that
>>difficult.
> 
> Yes, the introduction of reversed partly obsoleted the use of negative 
> strides, at least outside of its numerical array origin.
> 
> Terry J. Reedy



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


Re: 'isa' keyword

2005-09-03 Thread Steve Holden
phil hunt wrote:
> On Sat, 03 Sep 2005 00:45:19 -0500, Steve Holden <[EMAIL PROTECTED]> wrote:
> 
>>>I'm not talking about a change in *paradigm* merely a change in 
>>>*syntax*; this:
>>>
>>>   receiver selector argument
>>>
>>>would mean the same as the current Python:
>>>
>>>   receiver.selector(argument)
>>>
>>
>>Aah, I see. I had assumed that "selector" was always going to be an 
>>operator. 3 . (+ 4) does indeed seem very "SmallTalkative". I don't 
>>think that Python method (or attribute) selection bears any relationship 
>>to SmallTalk message-passing, but I hope you will feel free to enlighten me.
> 
> 
> Let's consider the Python example first.
> 
> You have two classes A and B. Each has a method called 'selector'.
> 
> When the line of code above is executed, the Python virtual machine 
> decides whether (receiver) is a member of A or B, and then executed 
> one of A.selector() or B.selector() depending on which it is. 
> Whichever function is executed, it is passed with (reciever) as the 
> "self" argument so that the correct data is operated on.
> 
> And now let's consider the Smalltalk example. How does it do it? 
> Essentially it does *exactly the same thing*.
> 
> (Yes, I know there are many differneces in detail between how 
> Snalltalk and Python  work, but they are only *details*; the 
> fundamental idea governing how these two object-oriented languages 
> work is the same).
> 
It's the differences we are talking about. All you have said above is 
that Python and SmallTalk both use late-binding to resolve names, 
allowing them to implement polymorphic behavior.

> 
would necessarily 
benefit Python at this stage. Some people are still under the 
misapprehension that message-passing is a fundamental of object-oriented 
programming because of Smalltalk, but they are wrong.
>>>
>>>
>>>I don't see how it can reasonably said that STK has 
>>>"message-passing" but other OOPLs don't. Consider these code 
>>>fragments:
>>>
>>>Smalltalk:
>>>   receiver selector: argument
>>>
>>>C++ or Java:
>>>   receiver.selector(argument);
>>>
>>>Python:
>>>   receiver.selector(argument)
>>>
>>>PHP:
>>>   $receiver->selector($argument)
>>>
>>>(I'm not sure if the last one is right since I've not done much OO 
>>>stuff in PHP)
>>>
>>>These all mean essentially the same thing so how can one be "message 
>>>passing" and the others not?
>>
>>Sorry, they don't all mean "essentially the same thing" at all. It seems 
>>to me you are looking at SmallTalk in entirely too superficial a light. 
> 
> 
> OK, allow me to reprase it. Imagine a language ith the semantics of 
> Python but the syntax of C++ or PHP or Smalltalk (or Lisp for that 
> matter). It would still basically be Python, wouldn't it?
> 
I'm not sure I understand this. You appear to be saying, in essence, 
"they are all programming languages, so despite the fact that they work 
slightly differently the similarity is we can write programs in them all".

> 
>> In SmallTalk, control structures aren't syntactic primitives, they are 
>>also examples of message-passing, so code blocks are sent as messages to 
>>objects. Python eschews such obscurity and (IMHO) gains clarity by so 
>>doing. But that is, of course, a matter of opinion.
> 
> 
> I agree, that's a major point of departure between Python and 
> Smalltalk.
> 
Right, but it's precisely SmallTalk's message-passing techniques that 
allow this to work. Of course Python can create code blocks with 
compiler.compile(), but this is not mainstream, and Python has so many 
more-useful mechanisms to implement program control that using code 
objects as data is correctly regarded as being ion the boundaries of 
language voodoo.

> 
>>Also, remember that just because two expressions in different languages 
>>"mean the same thing "doesn't mean they are implemented using the same 
>>techniques.
> 
> 
> Of course not. 
> 
> CPython and JPython are different implementations, but they are 
> still the same language (mostly).
> 
That we can agree on. But both differ substantially from SmallTalk.
> 
>>I would contend (if backed into a corner) that there is a significant 
>>difference between passing the arguments 3 and 4 to a "+" operator 
>>(which is what Python and most other languages implementing standard 
>>ideas of operator precedence do) and sending the message "+ 4" to the 
>>integer 3 (which is effectively what SmallTalk does).
> 
> 
> In both python and smalltalk you can override the operator to mean 
> what you want, so I disagree that there is any fundamental 
> difference. Why do you think there is?
> 
Because in Python the interpreter has hard-wired code associated with 
each operator. This code examines the left- and right-hand operands, 
calling various methods on them if they exist.

In SmallTalk the operator is the first element of a message sent to the 
left-hand operand, and if the object (or one of its superclasses) has no 
method corresponding with the operator then a "don't understand 

Re: pickling the objects returned by array.array()

2005-09-03 Thread Reinhold Birkenfeld
Raymond Hettinger wrote:
> John Machin wrote:
>> Looks like arrays are NOW (2.4.1) pickleable but not unpickleable
> 
> Please file a bug report and assign to me.

Done. http://python.org/sf/1281383

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


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread Bryan Olson
n00m wrote:
 > Your last version works like a champ. It easily handles up
 > to 5 instances of my.vbs! Except of this thing:
 >
 >>AttributeError: 'module' object has no attribute 'SHUT_WR'
 >
 > Seems it's a pure Unix constant.

No, my guess is that you're running an old version of Python.
The constant was added in the source on 27 Nov 2003; I'm not
sure what version that would first appear in. You can fix it
either by upgrading your Python distribution (a good idea
anyway), or replacing:

 sock.shutdown(socket.SHUT_WR)

with:

 sock.shutdown(1)


 >>>But it does NOT work without IDLE!
 >>
 >>Odd. What happens if you run it from a command line?
 >
 > In a moment - AFTER I start my.vbs - in console window new prompt
 > "D:\>" appears... and vbs reports "General Network Error".

Hmmm... not much to go on there. I tested it on Win-XP, running
it from a command line. I set the server to ('www.googl.com',
80), and I was able to web-search through it.

Are you running XP's local firewall?


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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,was Re: Bug in slice type

2005-09-03 Thread Ron Adam
Bengt Richter wrote:

> IMO the problem is that the index sign is doing two jobs, which for zero-based
> reverse indexing have to be separate: i.e., to show direction _and_ a _signed_
> offset which needs to be realtive to the direction and base position.

Yes, that's definitely part of it.


> A list-like class, and an option to use a zero-based reverse index will 
> illustrate:
> 
class Zbrx(object):
> 
>  ... def __init__(self, value=0):
>  ... self.value = value
>  ... def __repr__(self): return 'Zbrx(%r)'%self.value
>  ... def __sub__(self, other): return Zbrx(self.value - other)
>  ... def __add__(self, other): return Zbrx(self.value + other)
>  ...
>  >>> class Zbrxlist(object):
>  ... def normslc(self, slc):
>  ... sss = [slc.start, slc.stop, slc.step]
>  ... for i,s in enumerate(sss):
>  ... if isinstance(s, Zbrx): sss[i] = len(self.value)-1-s.value
>  ... return tuple(sss), slice(*sss)
>  ... def __init__(self, value):
>  ... self.value = value
>  ... def __getitem__(self, i):
>  ... if isinstance(i, int):
>  ... return '[%r]: %r'%(i, self.value[i])
>  ... elif isinstance(i, Zbrx):
>  ... return '[%r]: %r'%(i, self.value[len(self.value)-1-i.value])
>  ... elif isinstance(i, slice):
>  ... sss, slc = self.normslc(i)
>  ... return '[%r:%r:%r]: %r'%(sss+ (list.__getitem__(self.value, 
> slc),))
>  ... def __setitem__(self, i, v):
>  ... if isinstance(i, int):
>  ... list.__setitem__(self, i, v)
>  ... elif isinstance(i, slice):
>  ... sss, slc = self.normslc(i)
>  ... list.__setitem__(self.value, slc, v)
>  ... def __repr__(self): return 'Zbrxlist(%r)'%self.value
>  ...
>  >>> zlast = Zbrx(0)
>  >>> zbr10 = Zbrxlist(range(10))
>  >>> zbr10[zlast]
>  '[Zbrx(0)]: 9'
>  >>> zbr10[zlast:]
>  '[9:None:None]: [9]'
>  >>> zbr10[zlast:zlast] = ['end']
>  >>> zbr10
>  Zbrxlist([0, 1, 2, 3, 4, 5, 6, 7, 8, 'end', 9])
>  >>> ztop = Zbrx(-1)
>  >>> zbr10[ztop:ztop] = ['final']
>  >>> zbr10
>  Zbrxlist([0, 1, 2, 3, 4, 5, 6, 7, 8, 'end', 9, 'final'])
>  >>> zbr10[zlast:]
>  "[11:None:None]: ['final']"
>  >>> zbr10[zlast]
>  "[Zbrx(0)]: 'final'"
>  >>> zbr10[zlast+1]
>  '[Zbrx(1)]: 9'
>  >>> zbr10[zlast+2]
>  "[Zbrx(2)]: 'end'"
> 
>  >>> a = Zbrxlist(list('abcde'))
>  >>> a
>  Zbrxlist(['a', 'b', 'c', 'd', 'e'])
> 
> Forgot to provide a __len__ method ;-)
>  >>> a[len(a.value):len(a.value)] = ['end']
>  >>> a
>  Zbrxlist(['a', 'b', 'c', 'd', 'e', 'end'])
> 
> lastx refers to the last items by zero-based reverse indexing
>  >>> a[lastx]
>  "[Zbrx(0)]: 'end'"
>  >>> a[lastx:lastx] = ['last']
>  >>> a
>  Zbrxlist(['a', 'b', 'c', 'd', 'e', 'last', 'end'])
> 
> As expected, or do you want to define different semantics?
> You still need to spell len(a) in the slice somehow to indicate
> beond the top. E.g.,
> 
>  >>> a[lastx-1:lastx-1] = ['final']
>  >>> a
>  Zbrxlist(['a', 'b', 'c', 'd', 'e', 'last', 'end', 'final'])
> 
> Perhaps you can take the above toy and make something that works
> they way you had in mind? Nothing like implementation to give
> your ideas reality ;-)

Thanks, I'll play around with it.  ;-)

As you stated before the index is doing two jobs, so limiting it in some 
way may be what is needed.  Here's a few possible (or impossible) options.

(Some of these aren't pretty.)


* Disallow *all* negative values, use values of start/stop to determine 
direction. Indexing from far end needs to be explicit (len(n)-x).

a[len(a):0]reverse order
a[len(a):0:2]  reveres order, even items

(I was wondering why list's couldn't have len,min, and max attribute 
that are updated when ever the list is modified in place of using 
len,min, and max functions? Would the overhead be that much?)

   a[len.a:0]


* Disallow negative index's,  use negative steps to determine indexing 
direction. Order of index's to determine output order.

a[len(a):0:-1] forward order, zero based indexing from end.
a[0:len(a):-1] reverse order, zero based from end.
a[0:1:-1]  last item

I works, but single a[-1] is used extremely often.  I don't think having 
to do a[0:1:-1] would be very popular.


* A reverse index symbol/operator could be used ...

a[~0]  ->   last item,  This works BTW. :-)  ~0 == -1
a[~1]  ->   next to last item

(Could this be related to the original intended use?)


a[~0:~0]   slice after end ?.  Doesn't work correctly.

What is needed here is to index from the left instead of the right.

a[~0] -> item to left of end gap.

*IF* this could be done; I'm sure there's some reason why this won't 
work. ;-), then all indexing operations with '~' could be symmetric with 
all positive indexing operations. Then in Python 3k true negative 
index's could cause an exception... less bugs I bet.  And then negative 
steps could reverse lists with a lot less co

Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread Peter Hansen
n00m wrote:
> Bryan wrote:
> PS Yes! Your last version works like a champ. It easily handles up
> to 5 instances of my.vbs! Except of this thing:
> 
>>AttributeError: 'module' object has no attribute 'SHUT_WR'
> 
> Seems it's a pure Unix constant.

Definitely not.  Are you sure you've got a proper Python install?

c:\>python
Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on 
win32
 >>> import socket
 >>> dir(socket)
['AF_APPLETALK', 'AF_DECnet', ... 'SHUT_RD', 'SHUT_RDWR', 'SHUT_WR',
'SOCK_DGRAM', ... 'sys', 'timeout']

 >>> socket.SHUT_WR
1

If you're really getting this error it would seem something is very 
wrong on your machine.

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


Re: plotting with gnuplot.py

2005-09-03 Thread [EMAIL PROTECTED]
Thanks for the response Varun,

I guess I still not sure the distingtion betweein gnuplot.py and its
implentation in scipy.

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


Re: Bug in string.find; was: Re: Proposed PEP: New style indexing,wasRe: Bug in slice type

2005-09-03 Thread Terry Reedy

"Ron Adam" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> (I was wondering why list's couldn't have len,min, and max attribute
> that are updated when ever the list is modified in place of using
> len,min, and max functions?

Python's list and, I believe, other builtin roster objects do have a 
C-level length attribute.  For mutables, it is updated.  __len__ is just a 
get of int value the and conversion to int object.  Min and max are defined 
and sensible for only a subset of lists, and when they are, are very seldom 
need repeated updates.

> Would the overhead be that much?)

For the fraction of times used, yes.

Terry J. Reedy



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


Re: Managing events

2005-09-03 Thread Steve Holden
cantabile wrote:
> Hi,
> 
> I have a class (a gui) with buttons and other controls. A button, for 
> example, has a callback method, so that writing
> 
> b = Button(label, OnClick)
> 
> will call the global OnClick method.
> 
> Now, if I want the OnClick method to call some of my main class methods, 
> I need to write:
> 
>  UI = None
>  ...
>  class MainClass:
>  ...
>  global UI = self
> 
> 
> Then,
> def OnClik(button):
> UI.do_something(button.get_label())
> 
> Is this the correct way to do it in Python ? Isn't there a potential 
> flaw in declaring my MainClass instance as a global variable ?

Yes. Normally graphical widgets are declared as object classes (in both 
wxPython and Tkinter, at least) for precisely this reason.

Then the onClick() can be a method of the class, and the callback is a 
bound method of the class (in other words a method that's already 
identified with a specific instance).

Here's a simple-ish piece of wxPython code to demonstrate. Notice that 
each paramDialog closes its own dialog box, because the callback 
provided in the event binding is already bound to the instance.

import wx

class paramDialog(wx.Dialog):
 count = 0  # Class variable counts # of instances
 def __init__(self, parent):
 wx.Dialog.__init__(self, parent, id=-1, title="This is a 
Dialog", size=(300, 250))
 btn = wx.Button(self, -1, "Close Me", (100, 75))
 # THIS LINE ASSOCIATES A BOUND METHOD OF THE CURRENT
 # INSTANCE WITH A CLICK ON THE "Close Me" BUTTON OF
 # THIS PARTICULAR DIALOG INSTANCE
 btn.Bind(wx.EVT_BUTTON, self.shutdown)
 self.Bind(wx.EVT_CLOSE, self.shutdown)
 self.SetAutoLayout(True)
 paramDialog.count += 1

 def shutdown(self, evt):
 paramDialog.count -= 1
 self.Destroy()
 if paramDialog.count == 0:
 app.Destroy()
 import sys
 sys.exit("Done")


class MyApp(wx.App):
 # wxWidgets calls this method to initialize the application
 def OnInit(self):
 frame = wx.Frame(None, -1, "This is the main frame")
 self.SetTopWindow(frame)
 d1 = paramDialog(frame)
 d2 = paramDialog(frame)
 d3 = paramDialog(frame)
 d1.Show()
 d2.Show()
 d3.Show()
 return True

if __name__ == '__main__':
 app = MyApp(0)
 app.MainLoop()



regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: Managing events

2005-09-03 Thread Rob Williscroft
cantabile wrote in news:[EMAIL PROTECTED] in 
comp.lang.python:

> Hi,
> 
> I have a class (a gui) with buttons and other controls. A button, for 
> example, has a callback method, so that writing
> 
> b = Button(label, OnClick)
> 
> will call the global OnClick method.
> 
> Now, if I want the OnClick method to call some of my main class 
> methods, 
> I need to write:
> 
>  UI = None
>  ...
>  class MainClass:
>  ...
>  global UI = self
> 
> 
> Then,
> def OnClik(button):
> UI.do_something(button.get_label())
> 
> Is this the correct way to do it in Python ? 

Try:

class MainClass:
  def do_something( self, label ):
pass

  def OnClick( self, button ):
self.do_something( button.get_label() )

  def some_method( self ):
b = Button( label, self.OnClick )


With the above you could also do:

main = MainClass()
b = Button( "A Label", main.OnClick )

Rob.
-- 
http://www.victim-prime.dsl.pipex.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Submitting doc bug reports without SF registration

2005-09-03 Thread Terry Reedy
In response to posts about the overhead of registering as SourceForge to 
submit quick doc typo/bug reports, I sent an email to docs AT python.org 
(== Fred Drake) about submitting via that address instead.

He responded that he really does not want specific action items sent there 
because such email only goes to him and can get lost or not read for 
awhile.  Tracker reports, on the other hand, give immediate feedback of 
reception and are immediately readable and possibly acted on by anyone who 
reviews tracker items.  Indeed, fixes sometimes happen within a day or two.

On the other hand, he can see that registration could be just enough 
barrier to stop someone and does not want that either.  He knows that the 
docs 'need more attention and fresh eyes!'  So he suggested two 
possibilities:

1. A DocImprovement wiki.  People could optionally sign up for update 
reports on specific wiki pages.

2. A new SF tracker, only for doc bugs, that would accept anonymous 
submissions.  The other trackers require login because most items need 
additional feedback from requestors.  But reports like "On page x.y.x, 
'seperate' should be 'separate'" do not require feedback unless the 
requestor wants the 'fixed, thank you' comment emailed.

As an item reviewer, I prefer the second, but we are both curious as to the 
preference of potential no-login reporters.

Terry J. Reedy



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


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread n00m
1.
Python 2.3.4

2.
Win98 and Win2k Professional

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


ANN: PyInstaller 1.0 in the works: package your Python app into a single-file executable

2005-09-03 Thread Giovanni Bajo
Hello,

http://pyinstaller.hpcf.upr.edu/

PyInstaller is a program that packages Python programs into stand-alone
executables, under both Windows and Linux. This is similar to the famous
py2exe, but PyInstaller is also able to build fully-contained (single file)
executables, while py2exe can only build directories containing an executable
with multiple dynamic libraries.
PyInstaller is an effort to rescue, maintain and further develop Gordon
McMillan's Python Installer (now PyInstaller). Their official website is not
longer available and the original package is not longer maintained. Believing
that it is still far superior to py2exe we have setup this page to continue its
further development.

We have just begun development on PyInstaller. Feel free to join us in the
effort! Please consult our Roadmap
(http://pyinstaller.hpcf.upr.edu/pyinstaller/roadmap) to check our plans.

-- 
Giovanni Bajo



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


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread Bryan Olson
Dennis Lee Bieber wrote:
> Bryan Olson declaimed the following in comp.lang.python:
> 
>>No, my guess is that you're running an old version of Python.
>>The constant was added in the source on 27 Nov 2003; I'm not
> 
> 
>   Are you sure of that 2003?

Yes, but that's when it went into the source, in the sense of
first being edited into a file. It was Revision 1.279 of
socketmodule.c.

http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/socketmodule.c?rev=1.312&view=log


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


descriptors for container items

2005-09-03 Thread Brock Filer
> I personally would first try to dump the quotes and use standard
> attributes --  countries.us.Colorado... -- and the  __get/set/delattr__
> methods.

If I do that, the attributes (that was a stupid name for me to choose) 
and children would have to not share any names with each other, with 
the object's regular attrs, or python keywords.

I toyed with the idea of having __div__ create a descriptor, assign it 
to a temporary attr, and access that. But then I realized that the 
children should never be directly assigned to anyways. I can live with 
one set of brackets at the end of the expression.

__methods__ are delightfully evil :-)

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


Re: PyChecker lives, version 0.8.15 released

2005-09-03 Thread Al Christians
Neal Norwitz wrote:
> Special thanks to Ken Pronovici.  He did a lot of work for this
> release and helped ensure it occurred.
> 
> Version 0.8.15 of PyChecker is available.  It's been over a year since
> the last release.  Wow, time really does fly.  Since it's been so long
> I'm sure I screwed something up, treat it delicately.  It may have bugs
> and erase your hard drive.  If that happens, look on the bright side, 
> you won't have any more bugs. :-)
> 
> PyChecker is a tool for finding bugs in Python source code.
> It finds problems that are typically caught by a compiler for less
> dynamic languages, like C and C++.  It is similar to lint.
> 
> Comments, criticisms, new ideas, and other feedback is welcome.
> 
> Since I expect there may be a bit more bugs than normal, I will try to
> put out another release in a few weeks.  Please file bug reports
> including problems with installation, false positives, &c on Source Forge.
> You are welcome to use the mailling list to discuss anything pychecker 
> related, including ideas for new checks.
> 
> Changes from 0.8.14 to 0.8.15:
> 
>   * Fix spurious warning about catching string exceptions
>   * Don't barf if there is # -*- encoding: ... -*- lines and unicode strings
>   * setup.py was rewritten to honor --root, --home, etc options
>   * Fix internal error on processing nested scopes
>   * Fix constant tuples in Python 2.4
>   * Don't warn about implicit/explicit returns in Python 2.4, we can't tell
>   * Fix crash when __slots__ was an instance w/o __len__
>   * Fix bug that declared {}.pop to only take one argument, it takes 1 or 2
>   * Fix spurious warning when using tuples for exceptions
>   * Fix spurious warning  /  
>   * Fix spurious warnings for sets module about __cmp__, __hash__
>   * Changed abstract check to require raising NotImplementedError
> rather than raising any error
>   * Fix spurious warnings in Python 2.4 for Using is (not) None warnings
>   * Fix spurious warnings for some instances of No class attribute found
>   * Fix spurious warnings for implicit returns when using nested functions
> 
> PyChecker is available on Source Forge:
> Web page:   http://pychecker.sourceforge.net/
> Project page:   http://sourceforge.net/projects/pychecker/
> Mailing List:   [EMAIL PROTECTED]
> 
> Neal
> --
> [EMAIL PROTECTED]

Not to complain, as this is a very useful one-of-a-kind tool, but it 
does appear to use more memory than I can imagine how when you run it on 
a substantial program.  Like a few kilobytes per line of code, maybe. 
It's slow, too, but that's ok for the usefulness of it, but trying to 
let it run and do something else with someone else's code bloat (like MS 
Word or something) in another window leads to something 
indistinguishable from system meltdown.  Any reason for hope of future 
improvements in this regard?


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


Digest MD5 authentication over using ZSI

2005-09-03 Thread trapeze . jsg
Hi.

I am trying to get through to Microsoft MapPoint Services using ZSI for
soap handling. I can generate the service classes and also the
soap-requests generated by the service classes seem to be OK. The
problem I am facing is that I can't seem to authenticate myself. I have
made a small change to ZSI.client so that when I get a "401
Unauthorized" response from the remote server I build up a nice
authorization request:

POST /Find-30/FindService.asmx HTTP/1.1
Host: findv3.staging.mappoint.net
Accept-Encoding: identity
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client
Protocol 1.1.4322.573)
SOAPAction: "http://s.mappoint.net/mappoint-30/FindAddress";
Authorization: Digest username="106288", realm="MapPoint",
nonce="91168da8e3a097f41264875211009a194b99a94ffe5bc619415820880a5b",
uri="/Find-30/FindService.asmx",
response="26aa9e36f9ff2a8308030810ab83dad1", qop=auth, nc=0001,
cnonce="623c12f33f0eb883"
Content-length: 0
Expect: 100-continue


The problem is that the server won't authorize me. I have a C# .net
program that does exactly the same I'm trying in python, and it is
authorized nicely:

POST /Find-30/FindService.asmx HTTP/1.1
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; MS Web Services Client
Protocol 1.1.4322.573)
Content-Type: text/xml; charset=utf-8
SOAPAction: "http://s.mappoint.net/mappoint-30/FindAddress";
Authorization: Digest
username="106288",realm="MapPoint",nonce="487911f02ed2ef706326675211008a8ec39cfa4fb09304757c8dde417354",uri="/Find-30/FindService.asmx",cnonce="e1ed9880c5e3777a4ba280cec1c9e362",nc=0001,qop="auth",response="b4119a4db73814fd09ae5fec11fc9730"
Content-Length: 523
Expect: 100-continue
Host: findv3.staging.mappoint.net

So I guess the problem is in the Digest calculation. Unfortunately I
don't know much about the issue but I have managed to "steel" this from
urllib2 and changed it a bit to fit my usage (see below).

1. Can I do this another way?
2. Has anybody made a digest MD5 authenticator for ZSI?
3. Whats wrong with my calculation or is it the header??
4. Can I use urllib2 to test the authentication part of a Soap Service.

- My authentication calculator >

import md5
import sha
import re
import time
import random
import os.path


def randombytes(n):
"""Return n random bytes."""
# Use /dev/urandom if it is available.  Fall back to random module
# if not.  It might be worthwhile to extend this function to use
# other platform-specific mechanisms for getting random bytes.
if os.path.exists("/dev/urandom"):
f = open("/dev/urandom")
s = f.read(n)
f.close()
return s
else:
L = [chr(random.randrange(0, 256)) for i in range(n)]
return "".join(L)


class Challenge:
  def __init__(self,challenge):
self.params = {}
self.no_chal=0
if challenge.upper().find('WWW-Authenticate:'.upper())==-1:
  self.no_chal=1
rx =
re.compile('WWW-Authenticate:.*qop="(\w+)"',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['qop'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*realm="(\w+)"',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['realm'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*algorithm="(\w+)"',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['algorithm'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*nonce="(\w+)"',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['nonce'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*opaque="(\w+)"',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['opaque'] = m.group(1)

rx =
re.compile('WWW-Authenticate:.*Digest.*"',re.IGNORECASE|re.MULTILINE)
m = rx.search(challenge)
if m:
  self.params['Digest'] = 1


  def get(self,keyword,default=None):
if self.params.has_key(keyword):
  return self.params[keyword]
else:
  return default

  def no_challenge(self):
return self.no_chal


class AbstractDigestAuthHandler:
# Digest authentication is specified in RFC 2617.

# XXX The client does not inspect the Authentication-Info header
# in a successful response.

# XXX It should be possible to test this implementation against
# a mock server that just generates a static set of challenges.

# XXX qop="auth-int" supports is shaky

def __init__(self, user, passwd):
self.user = user
self.passwd = passwd
self.retried = 0
self.nonce_count = 0

def reset_retry_count(self):
self.retried = 0

def retry_http_digest_auth(self, req, auth):
token, challenge = auth.split(' ', 1)
chal = parse_keqv_list(parse_http_list(challenge))
auth = self.get_authorization(req, chal)
if auth:
auth_val = 'Digest %s' % auth
if req.headers.get(self.auth_header, None) == auth_val:
   

Re: python logo

2005-09-03 Thread Tim Churches
Fredrik Lundh wrote:
> Tim Churches wrote:
> 
> 
>>PPS Emerson's assertion might well apply not just to Python logos, but
>>also, ahem, to certain aspects of the Python standard library.
> 
> 
> you've read the python style guide, I presume?
> 
> http://www.python.org/peps/pep-0008.html

A Foolish Consistency is the Hobgoblin of Little Minds.
 --often ascribed to Ralph Waldo Emerson but
   in fact due to[1] G. van Rossum and B Warsaw.

[1] The convention that quotes are ascribed to those who first used them
is, of course, a foolish consistency.

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


Language Work Benches in Py

2005-09-03 Thread yoda
Hi,
I recently read Martin Fowler's article on language workbenches and
domain specific
languages(http://www.martinfowler.com/articles/languageWorkbench.html).
I then had the pleasure of reading Rainer Jowsig's implementation of
the sample in Lisp(http://lispm.dyndns.org/news?ID=NEWS-2005-07-08-1).

The lisp code was so sexy that I was inspired to write a sample in
Python. I'm relatively new to coding in Python so I'd love any barbs,
comments or criticisms about the code. You can find my article here :
(http://billionairebusinessman.blogspot.com/2005/09/drop-that-schema-and-put-your-hands-in.html).

I also made a screen cast of the same
(http://openenterpriseafrica.com/neo/blogs/010905/dsl-in-python.wmv.bz2).
Unfortunately, I had to make it using a windows machine so it's encoded
as wmv. (If anyone finds it useful and is inspired to encode it in a
more palatable format e.g. mov, I'd be honoured to create a torrent and
host it)

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


Re: Sockets: code works locally but fails over LAN

2005-09-03 Thread n00m
Bryan;
Look at how I corrected your the very first version
(see added arguments in both functions). And now it
really can handle multiple connections!


import socket, thread

sqls_host, sqls_port = '127.0.0.1', 1433
proxy_host, proxy_port = '127.0.0.1', 1434

# How I tested it:
# sqls_host, sqls_port = 'www.google.com', 80

def VB_SCRIPT(s2, cn):
 while 1:
 data = cn.recv(4096)
 if not data: return
 s2.sendall(data)
 print 'VB_SCRIPT:' + data + '\n'

def SQL_SERVER(s2, cn):
 while 1:
 data = s2.recv(4096)
 if not data: return
 cn.sendall(data)
 print 'SQL_SERVER:' + data + '\n'

s1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s1.bind((proxy_host, proxy_port))
s1.listen(5)

while 1:
 cn, addr = s1.accept()
 s2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
 s2.connect((sqls_host, sqls_port))
 thread.start_new_thread(VB_SCRIPT,(s2, cn))
 thread.start_new_thread(SQL_SERVER,(s2, cn))


Without these corrections I got these error messages
when I launched SIMULTANEOUSLY 3 instances of my.vbs:


Unhandled exception in thread started by
Unhandled exception in thread started by
Traceback (most recent call last):
Traceback (most recent call last):
  File "D:\Python23\00\socket_Br10.py", line 18, in SQL_SERVER
  File "D:\Python23\00\socket_Br10.py", line 13, in VB_SCRIPT
data = s2.recv(4096)
s2.sendall(data)
socket  File "", line 1, in sendall
.socketerror.: error: (10054, 'Connection reset by peer')
(10054, 'Connection reset by peer')

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


Re: descriptors for container items

2005-09-03 Thread Terry Reedy

"Brock Filer" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
>> I personally would first try to dump the quotes and use standard
>> attributes --  countries.us.Colorado... -- and the  __get/set/delattr__
>> methods.
>
> If I do that, the attributes (that was a stupid name for me to choose)
> and children would have to not share any names with each other,

Since multiple objects can indeed have duplicate attribute names, and such 
duplication is rampant in Python, I am not sure what you mean.

Terry J. Reedy 



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


Re: plotting with gnuplot.py

2005-09-03 Thread [EMAIL PROTECTED]
Still having some issues plotting:

In attempting as explained above:

import Gnuplot,Numeric
filename = ('Default.PL1')
data = scipy.io.array_import.read_array(filename)

y = data[:,1]
x = data[:,0]
z = data[:,2]

//I think u need to take the transpose of this column before
plotting..

x=Numeric.transpose(x)
y=Numeric.transpose(y)

g=Gnuplot.Gnuplot(debug=1)
d=Gnuplot.Data(x,y)
g('set logscale xy')
g.plot(d)

The file executes without generating any plot being displayed however
the debug option generates this output:

gnuplot> set terminal windows
.
.
gnuplot> plot 'c:\documen~1\leon\loca`l\temp\tmpuskt1' notitle

When I open this file in wordpad it contains the contents of the d
array.

Any ideas why gnuplot is not outputing to the screen??

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


os.system(r"ls") prints to screen??

2005-09-03 Thread Xah Lee
does anyone know why the folllowing prints to the screen?

# python
import os
os.system(r"ls")

 Xah
 [EMAIL PROTECTED]
∑ http://xahlee.org/

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

Re: Add lists to class?

2005-09-03 Thread Mike Meyer
"BBands" <[EMAIL PROTECTED]> writes:

>> Why don't you use a real list instead?
>
> I am using lists... I just showed the naming schema. Here is how they
> are implemented.
>
> for var in range(len(self.symbols)):
> setattr(self, "_" + str(var), [])

That's not the list he's talking about. And I agree with him.

Why are you setting the attreibutes "_" + str(var)? Why not just store
them in a dictionary?

>> I don't understand what
>> self.__dict__["_" + str(var)] gets you.
> It let's me access lists that aren't known at write time.

Yes, but it's ugly, makes one address space server for two different
sets of variables, and has potential for some nasty bugs. Why not just
do:

self.lists[var] = []

Or, if you're really tied to "_", do:

self._[var] = []

Or, given that your example used increasing numeric names, just use a
list here:

 self._.append([])

which you would then reference as self._[0], self._[1], etc.

  http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Add lists to class?

2005-09-03 Thread Mike Meyer
Paolino <[EMAIL PROTECTED]> writes:
> Mike Meyer wrote:
>> "BBands" <[EMAIL PROTECTED]> writes:
>>>I have a list with some strings in in it, 'one', 'two' 'three' and so
>>>on. I would like to add lists to a class with those names. I have no
>>>way of knowing what will be in the list or how long the list will be in
>>>advance.
>> Others have told you how to do it. Now I'm going to tell you why you
>> shouldn't.
>> First, since you don't know the names of the attributes you added,
>> you
>> can't possibly write code that references them in the normal way. So
>> is there really much point in making them an attribute at all?
>> Second, since you don't know the names of the attributes you added,
>> you don't know if one of more of them is going to clobber a feafure of
>> the class that you want to use for something else. I.e., consider:
>>
>class C:
>> ...  pass
>> ...
>c = C()
>print c
>> <__main__.C instance at 0x8270b4c>
>>
>c.__str__ = 'foo'
>print c
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> TypeError: 'str' object is not callable
>> I.e. - if someone adds a __str__ attribute to your class, you won't
>> be
>> able to print it any more. Not a good thing.
>> In general, you probably want a dictionary instead of attributes:
>>
>class C(dict):
>> ...  def __init__(self, l):
>> ...   for i in l:
>> ...self[i] = []
>> ...
>c = C(['a', 'b', 'c'])
>c['a']
>> []
>>
> and 2c more to use attributes but prevent overriding of real attributes
>
> def __getattr__(self,name):
>   if name in self:
> return self[name]
>   raise AttributeError

Good point. The problem with this is that your real attributes will
now hide things stored in the dictionary. The bugs I listed above are
all caused by trying to conflate two different name spaces: the
attributes of the object and the variables stored in it as
data. Separating them out and then layering one back on top of the
other just gives you those bugs back.

http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: os.system(r"ls") prints to screen??

2005-09-03 Thread Robert Kern
Xah Lee wrote:
> does anyone know why the folllowing prints to the screen?
> 
> # python
> import os
> os.system(r"ls")

os.system() starts a shell and has the shell execute the program as a
separate process. If you want to get the output of the given program,
then use the subprocess module.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Command config, quitting, binary, Timer

2005-09-03 Thread bearophileHUGS
Hello, I have four things to ask or to suggest, sorry if they seem
basic or already discussed.

---

I am still ignorant about Tkinter. This little program, after pressing
the "Go" eats more and more RAM, is it normal? Can it be avoided? (In
normal programs this is isn't a real problem).

! import Tkinter
! def dogo():
! while 1:
! b.config(command=lambda:None)
! root = Tkinter.Tk()
! b = Tkinter.Button(root, text="Go", command=dogo)
! b.pack()
! root.mainloop()

Note: I have found this problem because in a small program I have a
Start button that becomes a Stop, so the bound command must change each
time. (Maybe there is some other solution, like hiding/unhiding the
buttons, I don't know.)

---

When I quit a Tkinter program (clicking the [X] button of the window)
while it's running, it stops with something like this:

TclError: invalid command name ".9970192"

There is a way to avoid it, or to intercept that quitting command to
stop the program more gracefully?

---

When I have to convert numbers to binary I use something like this (the
management of negative numbers is removed). It's my faster Python
version (derived by a Hettinger's version):

! from collections import deque
! def binary_conv(n):
! if n == 0:
! return 0
! else:
! absn = abs(n)
! conv = ["0", "1"]
! result = deque()
! _app = result.appendleft
! while absn:
! _app( conv[absn & 1] )
! absn >>= 1
! return int("".join(result))

But converting to binary is a quite common operation, so I think it can
be added as a binary function to Python, for example adding "b" to the
the conversion types of the % formatting.

---

Sometimes I need something like the Timer of Java, it generates "ticks"
and calls a function for each tick. The tick frequency can be set, or
they can be stopped.

In another Newsgroup someone has suggested me that the callLater of
Twisted can solve my problem, but I think it's a quite common thing, so
I think that maybe it can be added to the threading standard module.

This is a rough Python version of mine (without comments), it's not a
true Metronome because it counts the delay time after the end of the
last function call. This class also seems fragile, sometimes it gives
me problems, and I cannot use too much concurrent metronomes, etc. It's
quite

Maybe someone can suggest me how to improve it.


! from threading import Timer
!
! class Metronome(object):
! def __init__(self, interval, fun, *args, **kwargs):
! self.interval = interval # seconds.
! self.fun = fun
! self.args = args
! self.kwargs = kwargs
! self._running = False
! def _go(self):
! # Call the function with the stored values
! self.fun(*self.args, **self.kwargs)
! if self._running:
! self._call = Timer(self.interval, self._go)
! self._call.start()
! def start(self):
! if not self._running:
! self._running = True
! self._go()
! def stop(self):
! if self._running:
! self._call.cancel()
! self._running = False

Thank you,
bearophile

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


Re: global interpreter lock

2005-09-03 Thread Mike Meyer
Dennis Lee Bieber <[EMAIL PROTECTED]> writes:
> On Wed, 31 Aug 2005 22:44:06 -0400, Mike Meyer <[EMAIL PROTECTED]> declaimed
> the following in comp.lang.python:
>> I don't know what Ada offers. Java gives you pseudo-monitors. I'm
>
>   From the days of mil-std 1815, Ada has supported "tasks" which
> communicate via "rendezvous"... The receiving task waits on an "accept"
> statement (simplified -- there is a means to wait on multiple different
> accepts, and/or time-out). The "sending" task calls the "entry" (looks
> like a regular procedure call with in and/or out parameters -- matches
> the signature of the waiting "accept"). As with "accept", there are
> selective entry calls, wherein which ever task is waiting on the
> matching accept will be invoked. During the rendezvous, the "sending"
> task blocks until the "receiving" task exits the "accept" block -- at
> which point both tasks may proceed concurrently.

Thank you for providing the description. That was sufficient context
that Google found the GNAT documentation, which was very detailed.

Based on that, it seems that entry/accept are just a synchronization
construct - with some RPC semantics thrown in.

>   As you might notice -- data can go both ways: in at the top of the
> rendezvous, and out at the end.
>
>   Tasks are created by declaring them (there are also task types, so
> one can easily create a slew of identical tasks). 
>
> procedure xyz is
>
>   a : task;   -- not real Ada, again, simplified
>   b : task;
>
> begin -- the tasks begin execution here
>   -- do stuff in the procedure itself, maybe call task entries
> end;

The problem is that this doesn't really provide any extra protection
for the programmer. You get language facilities that will provide the
protection, but the programmer has to remember to use them in every
case. If you forget to declare a method as protected, then nothing
stops two tasks from entering it and screwing up the objects data with
unsynchronized access. This should be compared to SCOOP, where trying
to do something like that is impossible.

   Thanks again,
 http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Command config, quitting, binary, Timer

2005-09-03 Thread Peter Hansen
[EMAIL PROTECTED] wrote:
> I am still ignorant about Tkinter. This little program, after pressing
> the "Go" eats more and more RAM, is it normal? Can it be avoided? (In
> normal programs this is isn't a real problem).
> 
> ! import Tkinter
> ! def dogo():
> ! while 1:
> ! b.config(command=lambda:None)
> ! root = Tkinter.Tk()
> ! b = Tkinter.Button(root, text="Go", command=dogo)
> ! b.pack()
> ! root.mainloop()

What did you expect to happen with the infinite loop inside dogo()? 
Wouldn't it call b.config() over and over again, never returning?  Is 
that really what you wanted?

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


Re: os.system(r"ls") prints to screen??

2005-09-03 Thread Steve Holden
Xah Lee wrote:
> does anyone know why the folllowing prints to the screen?
> 
> # python
> import os
> os.system(r"ls")
> 
>  Xah
>  [EMAIL PROTECTED]
> ∑ http://xahlee.org/
> 
It only prints to the screen when standard output of the invoking 
process is the screen. The sub-process forked by os.system inherits 
stdin stdout and stderr from the invoking process.

This is all pretty basic stuff. Perhaps you should stop your verbal 
assault on the computer science community and start to learn the 
principles of what you are doing.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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

Re: Submitting doc bug reports without SF registration

2005-09-03 Thread Paul Rubin
"Terry Reedy" <[EMAIL PROTECTED]> writes:
> 1. A DocImprovement wiki.  People could optionally sign up for update 
> reports on specific wiki pages.
> 
> 2. A new SF tracker, only for doc bugs, that would accept anonymous 
> submissions.  The other trackers require login because most items need 
> additional feedback from requestors.  But reports like "On page x.y.x, 
> 'seperate' should be 'separate'" do not require feedback unless the 
> requestor wants the 'fixed, thank you' comment emailed.
> 
> As an item reviewer, I prefer the second, but we are both curious as
> to the preference of potential no-login reporters.

I think php.net's system works quite well and Python should do
something similar if it's feasible.
-- 
http://mail.python.org/mailman/listinfo/python-list


descriptors for container items

2005-09-03 Thread Brock Filer

> > If I do that, the attributes (that was a stupid name for me to 
> choose)
> > and children would have to not share any names with each other,
>
> Since multiple objects can indeed have duplicate attribute names, and 
> such
> duplication is rampant in Python, I am not sure what you mean.

felons['@class'] = 'capital'
felons['class'].do_something()
felons.class -> SyntaxError

I thought I had my previous example down to:

countries/'us'/'Colorado'/'Denver'['@population']

, but of course that tries to subscript a string with a string; which 
might be an interesting idiom for substring searching, as long as it 
never returned -1.

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


how to do this?

2005-09-03 Thread Justin Straube
Greetings Pythonistas.
Im looking for a way to write this but not sure where or how to begin.
As the user enters or removes characters into/from sEnt I would like
for set_info() to set infVar with the correct value. The same as how
IDLE shows the line and column in the lower right corner.

 Code Example 
from time import localtime
from Tkinter import *

def set_info():
 x = len(strVar.get())
 infVar.set('Length: %i' % (x))

ROOT = Tk()
strVar = StringVar()
infVar = StringVar()

sLab = Label(ROOT, text='String')
sLab.grid(row=0, column=0)
sEnt = Entry(ROOT, textvariable=strVar, width=15)
sEnt.grid(row=0, column=1, columnspan=2)
qBut = Button(ROOT, text='Quit', command=ROOT.quit)
qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E)
iLab = Label(ROOT, textvariable=infVar, width=21,
  relief=SUNKEN, anchor=W)
iLab.grid(row=2, column=0, columnspan=3)

set_info() # example to show what will be displayed.
ROOT.mainloop()
 End Example 

Can anyone point me in the right direction for how to do this?

Regards,

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


gmail access

2005-09-03 Thread gerald gillespie
how do I access my new Gmail account [EMAIL PROTECTED]

_
Express yourself instantly with MSN Messenger! Download today - it's FREE! 
http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/

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


Re: how to do this?

2005-09-03 Thread Steve Holden
Justin Straube wrote:
> Greetings Pythonistas.
> Im looking for a way to write this but not sure where or how to begin.
> As the user enters or removes characters into/from sEnt I would like
> for set_info() to set infVar with the correct value. The same as how
> IDLE shows the line and column in the lower right corner.
> 
First of all, it might have been better to provide a more meaningful 
title like "Update display as text entry changes", but not to worry - 
this is a matter of experience.

>  Code Example 
> from time import localtime
> from Tkinter import *
> 
> def set_info():
>  x = len(strVar.get())
>  infVar.set('Length: %i' % (x))
> 
> ROOT = Tk()
> strVar = StringVar()
> infVar = StringVar()
> 
> sLab = Label(ROOT, text='String')
> sLab.grid(row=0, column=0)
> sEnt = Entry(ROOT, textvariable=strVar, width=15)
> sEnt.grid(row=0, column=1, columnspan=2)
> qBut = Button(ROOT, text='Quit', command=ROOT.quit)
> qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E)
> iLab = Label(ROOT, textvariable=infVar, width=21,
>   relief=SUNKEN, anchor=W)
> iLab.grid(row=2, column=0, columnspan=3)
> 
> set_info() # example to show what will be displayed.
> ROOT.mainloop()
>  End Example 
> 
> Can anyone point me in the right direction for how to do this?
> 
The key here is to bind keystroke events to the routine to change the 
display. The following program uses your set_info() function to update 
the display every time a key is released (I chose this event because by 
the time it is raised the keystroke has been processed by the Entry widget.

I don;t guarantee this code will work across several Entry widgets 
without your keeping track of which one has focus when the event is 
raised (it's late, and I'm about to turn in for the night), but at least 
it will give you something to play with.

You'll note that set_info() has acquired an argument - Tkinter provides 
an event as an argument when a callback is called. So the manual call 
gets a bogus event of "None" just to avoid exceptions. Hope this gets 
you started.

 Code Example 
from time import localtime
from Tkinter import *

def set_info(event):
  x = len(strVar.get())
  infVar.set('Length: %i' % (x))

ROOT = Tk()
strVar = StringVar()
infVar = StringVar()

sLab = Label(ROOT, text='String')
sLab.grid(row=0, column=0)
sEnt = Entry(ROOT, textvariable=strVar, width=15)
sEnt.grid(row=0, column=1, columnspan=2)
sEnt.bind("", set_info)
qBut = Button(ROOT, text='Quit', command=ROOT.quit)
qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E)
iLab = Label(ROOT, textvariable=infVar, width=21,
   relief=SUNKEN, anchor=W)
iLab.grid(row=2, column=0, columnspan=3)

set_info(None) # example to show what will be displayed.
ROOT.mainloop()
 End Example 

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/

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


Re: how to do this?

2005-09-03 Thread Peter Otten
Justin Straube wrote:

> As the user enters or removes characters into/from sEnt I would like
> for set_info() to set infVar with the correct value. The same as how
> IDLE shows the line and column in the lower right corner.
> 
>  Code Example 
> from time import localtime
> from Tkinter import *

  # ignore arguments we don't care for in our application
  def set_info(*args):
>  x = len(strVar.get())
>  infVar.set('Length: %i' % (x))
> 
> ROOT = Tk()
> strVar = StringVar()
> infVar = StringVar()

  # register set_info() to listen for changes written to strVar
  strVar.trace_variable("w", set_info)

> sLab = Label(ROOT, text='String')
> sLab.grid(row=0, column=0)
> sEnt = Entry(ROOT, textvariable=strVar, width=15)
> sEnt.grid(row=0, column=1, columnspan=2)
> qBut = Button(ROOT, text='Quit', command=ROOT.quit)
> qBut.grid(row=1, column=2, pady=2, padx=2, sticky=E)
> iLab = Label(ROOT, textvariable=infVar, width=21,
>   relief=SUNKEN, anchor=W)
> iLab.grid(row=2, column=0, columnspan=3)
> 
> set_info() # example to show what will be displayed.
> ROOT.mainloop()
>  End Example 
> 
> Can anyone point me in the right direction for how to do this?

Yes, see above.

Peter

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


Re: Problems with Python for Windows extensions

2005-09-03 Thread vincent wehren
"KK" <[EMAIL PROTECTED]> schrieb im Newsbeitrag 
news:[EMAIL PROTECTED]
| the code below is taken from M$ technet as an example on using vb
| script to do a replace all in word:
|
| Const wdReplaceAll  = 2
|
| Set objWord = CreateObject("Word.Application")
| objWord.Visible = True
|
| Set objDoc =
| objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc")
| Set objSelection = objWord.Selection
|
| objSelection.Find.Text = "Contoso"
| objSelection.Find.Forward = True
| objSelection.Find.MatchWholeWord = True
|
| objSelection.Find.Replacement.Text = "Fabrikam"
| objSelection.Find.Execute ,,wdReplaceAll
|
|
|
|
| I did a rewrite and made it pythonic:
|
| from win32com.client import *
|
| wdReplaceAll  = 2
|
| objWord = Dispatch("Word.Application")
| objWord.Visible = True
|
| objDoc =
| objWord.Documents.Open("K:\Development\Fabricbase\prod\Test.doc")
| objSelection = objWord.Selection
|
| objSelection.Find.Text = "Contoso"
| objSelection.Find.Forward = True
| objSelection.Find.MatchWholeWord = True
|
| objSelection.Find.Replacement.Text = "Fabrikam"
| objSelection.Find.Execute (Replace = wdReplaceAll)
|
|
| However, the document juz loaded up in word but no action was taken. I
| am using Word 2003. Any ideas?

KK,

Your example seemed to work fine for me (Python2.4, Pythonwin build 204, 
Word 2003)

One thing: since you say your document loads up fine I don't know if it is 
just a typo, but make sure you follow the rules of backslash literals in 
path names. In other words:
"K:\Development\Fabricbase\prod\Test.doc" should read either

r"K:\Development\Fabricbase\prod\Test.doc" (note the leading r for raw 
string
or

"K:\\Development\\Fabricbase\\prod\\Test.doc"
or

"K:/Development/Fabricbase/prod/Test.doc"

--

Vincent Wehren





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