Re: socket: connection reset by server before client gets response

2007-07-08 Thread Frank Swarbrick
ahlongxp wrote:
>> Post the code.
> ok.
> here is the code:
> 
> # Echo server program
> import socket
> 
> HOST = '' # Symbolic name meaning the local host
> PORT = 50007  # Arbitrary non-privileged port
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
> s.bind((HOST, PORT))
> s.listen(1)
> conn, addr = s.accept()
> print 'Connected by', addr
> conn.settimeout(1)
> toread = 99
> retrytime = 0
> reads = 0
> while reads < toread and retrytime < 10:
> try:
> data = conn.recv(min(32,toread-reads))
> if not data: continue
> print data
> reads += len(data)
> except:
> retrytime += 1
> print "timeout %d" % retrytime
> continue
> if reads == toread:
> conn.send("OK")
> else:
> conn.send("NOT OK")
> conn.close()
> 
> I'm the separate
> line*
> 
> # Echo client program
> import socket
> 
> HOST = 'localhost'# The remote host
> PORT = 50007  # The same port as used by the server
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.connect((HOST, PORT))
> for i in range(12):
> print "time %d" % i
> s.send('0123456789')
> #data = s.recv(1024)
> #print "data %d" %i, data
> #s.shutdown(socket.SHUT_WR)#no more write
> data=s.recv(1024)
> s.close()
> print 'Received', repr(data)
> 
> client is supposed to get the response, either "OK" or "NOT OK".
> but the fact is, client gets "Connection reset by peer" (as shown
> below) about one in fifth.
> --
> Traceback (most recent call last):
>   File "c.py", line 10, in 
> s.send('0123456789')
> socket.error: (104, 'Connection reset by peer')
> --
> 
> anyway, server is doing well all the time.
> 
> any comments on the design or implementation will be greatly
> appreciated.

So, umm, what exactly are you trying to accomplish?
Here are the results I'm getting:

Server:
Connected by ('127.0.0.1', 53536)
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
0123456789
012345678

Client:
time 0
time 1
time 2
time 3
time 4
time 5
time 6
time 7
time 8
time 9
time 10
time 11
Traceback (most recent call last):
   File "echo_c.py", line 10, in 
 s.send('0123456789')
socket.error: (32, 'Broken pipe')

It looks like what is happening is the server only accepts 99 bytes.  It 
then does the send and the close.

The client wants to send 120 bytes, 10 bytes at a time.  By the time is 
does the 12th send the server has already finished, closing its socket 
and exiting.  So when the client attempts send #12 the socket is already 
closed.  Thus the error.

I'm not sure why you are getting the 'connection reset' instead of 
'broken pipe'.  Probably different OS.  (I'm using Mac OS X 10.4.10.)

Anyway, I changed your code slightly, wrapping the send in a try/except 
block like this:
 try:
 s.send('0123456789')
 except socket.error ,e:
 print "Socket Error:", e
 break

Now here are my results for the client:
time 0
time 1
time 2
time 3
time 4
time 5
time 6
time 7
time 8
time 9
time 10
time 11
error: (32, 'Broken pipe')
Received 'OK'

The way you had it the program crashed before it could do the receive.

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


Re: httplib module

2007-07-08 Thread Boris Ozegovic
Steve Holden wrote:

>>> Why do I get double new lines when geting data from server?  Example:
> How? It's customary to include details when you've solved your own 
> problem in case someone else gets the same issue.

Ok.  In do_GET I had this two lines:

for line in file:
print line 

As you can see, print inserted another \n.  :-)

Correct code is:

for line in file:
print line, 

-- 
Ne dajte da nas lažljivac Bandić truje:
http://cnn.blog.hr/arhiva-2007-06.html#1622776372
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unicode problem

2007-07-08 Thread [EMAIL PROTECTED]
> 
> What software did you use to make that so? The Python codec certainly
> never would do such a thing.
> 
> Are you sure it was latin-1 and \x27, and not windows-1252 and \x92?
> 
> Regards,
> Martin

you're right...the source of text are html pages and obviously webmasters
have poor knowledge of encodings, so the meta declared the encoding as
ISO-8859-1 but the real encoding is Windows-1252 and yes it uses \x92 as
apostrophe, so the problem isn't Python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket: connection reset by server before client gets response

2007-07-08 Thread ahlongxp

> So, umm, what exactly are you trying to accomplish?

> It looks like what is happening is the server only accepts 99 bytes.  It
> then does the send and the close.
yes.  What I want is that, server sends response to client and closes
connection when it feels recieving enough information, and make sure
at the same time ,client will definitely get the response from server.

> The client wants to send 120 bytes, 10 bytes at a time.  By the time is
> does the 12th send the server has already finished, closing its socket
> and exiting.  So when the client attempts send #12 the socket is already
> closed.  Thus the error.
>

> I'm not sure why you are getting the 'connection reset' instead of
> 'broken pipe'.  Probably different OS.  (I'm using Mac OS X 10.4.10.)
>
as I saied before,  running results will varies. And most of the time
they are working quite well. But that's not enough.
> Anyway, I changed your code slightly, wrapping the send in a try/except
> block like this:
>  try:
>  s.send('0123456789')
>  except socket.error ,e:
>  print "Socket Error:", e
>  break
>
> Now here are my results for the client:
> time 0
> time 1
> time 2
> time 3
> time 4
> time 5
> time 6
> time 7
> time 8
> time 9
> time 10
> time 11
> error: (32, 'Broken pipe')
> Received 'OK'

This really helped.
Now I know the client will still get the response even under
'Connection reset by peer' or 'Broken pipe'.


> The way you had it the program crashed before it could do the receive.
>
> Frank
Frank, thanks a lot.

--
ahlongxp

Software College,Northeastern University,China
[EMAIL PROTECTED]
http://www.herofit.cn

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


Re: __unicode__ method for exception object

2007-07-08 Thread Lawrence Oluyede
Ben Finney <[EMAIL PROTECTED]> wrote:
> Your terminal has been detected as using the 'ascii' encoding, so
> while that's true no attempt to output non-ASCII characters will work.
> 
> You'll need to change whatever settings are on your terminal emulator
> so that it is using an encoding (such as 'utf-8') which can display
> the characters you want.

AFAIK that's not a terminal problem. I have a UTF-8 terminal and the
problem is still there. 

-- 
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand 
something when his salary depends on not
understanding it" - Upton Sinclair
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what is wrong with that r"\"

2007-07-08 Thread jimxu
Yeah, that's a good point...


On Jul 8, 2007, at 1:48 AM, Tim Roberts wrote:

> i3dmaster <[EMAIL PROTECTED]> wrote:
>>
>> Then you can use other chars as the delimiter, [EMAIL PROTECTED]@b@ or 
>> r!a!b!,
>> etc... The import thing is so long as the interpreter doesn't get
>> confused on the data and the delimiter.
>
> That limits the number of valid delimiters to a relatively small  
> set.  You
> couldn't use any valid operator:
>
>x = r*a*b
>
> Is that a one character raw string appended to a string called "b",  
> or is
> that to multiplications?
>
>> sed also allows for
>> arbitrary delimiters too as long as you maintain the integrity of the
>> original meaning...
>
> sed can do that because its commands are one character long.  Whatever
> follows an "s" must a delimiter because it can't be anything else.
> -- 
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Timing a python program run

2007-07-08 Thread i3dmaster
simplest way is just put a timer on start and another on the end,  
then calc the elapse. You can also take a look timeit module too  
which provides similar but more powerful functions...

-Jim

On Jul 7, 2007, at 12:21 PM, David wrote:

> Hi,
>
> In matlab, I'd calculate the time for a script named test.m to run
> with:
>
>>> tic, run, toc
>
> Is there some way to do this in python on a mac os x from the terminal
> window? Or whatever?
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-08 Thread Adriano Varoli Piazza
Twisted wrote:
[...]
BASTA. Basta, cazzo (unprintable, Italian). Stop it. It wasn't funny
10 messages into your subthread, and it's even less fun now. It's
obvious you're trolling, but nevertheless, in the undescribably
improbable case you _are_ being serious:

a) Notepad is over there: --->*
b) If you do want to keep an antediluvian copy of emacs -probably
versioned in the negative numbers, for all you've said- please do. Do
be so kind as to send a copy, since it might be quite valuable as an
antique.
c) Powerful programming editors assume some willingness to learn their
interface. Deal.
d) Your capacity of denial is remarkable. Please do send us your
contact info, so that we may avoid dealing with you on a professional
basis.
--
killfile-ly yours,
Adriano

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-08 Thread Hendrik van Rooyen
 "John Machin" <[EMAIL PROTECTED]> wrote:

8< nice explanation of quoting problems -

> (2) A field containing an odd number of " characters (or more
> generally, not meeting whatever quoting convention might be expected
> in the underlying data) should be treated with suspicion.

How does one program to treat something with suspicion?

My stuff tends to either accept or reject...

This reminds me (for no discernible reason) of the word 
"eschew", and of an illustration in a Goon author's book
of someone eschewing an architectural example with a 
pocket sized eschewing instrument - a "pocket eschewer".
(He is shown peering at it through the eyepiece)

Maybe such fields should be eschewed instead.

- Hendrik

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


Re: socket: connection reset by server before client gets response

2007-07-08 Thread Hendrik van Rooyen
 "ahlongxp" <[EMAIL PROTECTED]> wrote:

> me again.
> 
> "Connection reset by peer"  happens about one in fifth.
> I'm using python 2.5.1  and ubuntu 7.04.
> 

Try to wait a while in the server thread, after sending the
message before closing the connection, to give the message 
time to get transmitted.

time.sleep(0.5) should do it...

- Hendrik

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


optparse commandline

2007-07-08 Thread vvikram

I want to call some function from my program and just pass it a
commandline. It should parse the commandline and return back a list of
parsed arguments (just like the sys.argv list)

Example:
foo.parse_cmdline("/usr/bin/foorun -v -d -h")
==> ['/usr/bin/foorun', '-v', '-d','-h']

Any suggestions on how to do this are appreciated.

Regards
Vikram

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


Re: Expandable 2D Dictionaries?

2007-07-08 Thread genro
On Jul 6, 5:43 pm, Robert Dailey <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I am interested in creating an expandable (dynamic) 2D dictionary. For
> example:
>
> myvar["cat"]["paw"] = "Some String"
>
> The above example assumes "myvar" is declared. In order for this to
> work, I have to know ahead of time the contents of the dictionary. For
> the above to work, my declaration must look like:
>
> myvar = {"cat": {"paw":""} }
>
> I would like to not have to declare my dictionary like this, as it
> does not allow it to be expandable. I'm very new to Python (I'm a
> professional C++ programmer. Any comparisons to C++ would help me
> understand concepts).
>
> Is there a way that when I index into my dictionary using an "unknown"
> index (string), that python will dynamically add that key/value pair?
>
> Thanks.

Hi Robert
take a look to our Bag module ( http://trac.genropy.org/wiki/BagManual).
Bag is a hierarchical container that can be used as nested dictionary.
If you are interested I'll send you the module.
There is not yet a public DL link as documentation has still to be
tuned...

HTH

Giovanni

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


Re: optparse commandline

2007-07-08 Thread Steven D'Aprano
On Sun, 08 Jul 2007 09:59:29 +, vvikram wrote:

> 
> I want to call some function from my program and just pass it a
> commandline. It should parse the commandline and return back a list of
> parsed arguments (just like the sys.argv list)
> 
> Example:
> foo.parse_cmdline("/usr/bin/foorun -v -d -h")
> ==> ['/usr/bin/foorun', '-v', '-d','-h']
> 
> Any suggestions on how to do this are appreciated.

def parse_cmdline(s):
"""Split a command line string s into words."""
import shlex
return shlex.split(s)




-- 
Steven.

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


socket.makefile() buggy?

2007-07-08 Thread ahlongxp
socket.makefile() may lose data when "connection reset by peer".
and socket.recv() will never lose the data.

change the "1" to "0" in the client code to see the difference.

confirmed on both windows and linux.

so I guess there is a problem with makefile().

# Echo server program
import socket

HOST = '' # Symbolic name meaning the local host
PORT = 50007  # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
while(1):
conn, addr = s.accept()
print 'Connected by', addr
conn.settimeout(1)
toread = 99
retrytime = 0
reads = 0
while reads < toread and retrytime < 10:
try:
data = conn.recv(min(32,toread-reads))
if not data: continue
print data
reads += len(data)
except:
retrytime += 1
print "timeout %d" % retrytime
continue
#conn.shutdown(socket.SHUT_RD)#no more read
if reads == toread:
conn.send("OK")
else:
conn.send("NOT OK")
conn.close()

# Echo client program
import socket

HOST = 'localhost'# The remote host
PORT = 50007  # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
for i in range(12):
print "time %d" % i
try:
s.send('0123456789')
except socket.error, e:
print "socket error:", e
break
#data = s.recv(1024)
#print "data %d" %i, data
#s.shutdown(socket.SHUT_WR)#no more write

'''
try changing 1 to 0.
'''
if 1:
data=s.recv(1024)
else:
rf = s.makefile("rb")
data = rf.read()
rf.close()
s.close()
print 'Received', repr(data)

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

Re: what is wrong with that r"\"

2007-07-08 Thread samwyse
On Jul 4, 7:15 am, Matthieu TC <[EMAIL PROTECTED]> wrote:
> May I suggest giving the possibility to use any delimiter for a raw string?  
> just like in Vi or ruby.
>
> Vi:
>  %s_a_b_g  is valid and so is  %s/a/b/g
>
> Ruby:
>  %q{dj'\ks'a\'"}   or %q-dj'\ks'a\'"-
>
> So as long as your regex does not use all the valid characters, readability 
> is maintained.

first, you'll need a way to flag that something is an arbitrarily
quoted string; 'r' is taken, so let's use 'q'.  next, you need to
distinguish strings from variables, perhaps by adding a flag to all
variables; $ should do nicely and has some historical precident.  once
you've done all that, you can write something like this:
  $q = q|this so-called "string" doesn't use conventional quotes|

congratulations!  you've just invented perl!

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread Steve Holden
Paul Rubin wrote:
> Steve Holden <[EMAIL PROTECTED]> writes:
>>> Python even leaks the index variable of list comprehensions (I've
>>> mostly stopped using them because of this), though that's a
>>> recognized wart and is due to be fixed.
>>>
>> Wow, you really take non-pollution of the namespace seriously. I agree
>> it's a wart, but it's one I have happily worked around since day one.
> 
> Well, the obvious workaround is just say "list()"
> instead of [] so that's what I do.

I think I'll start calling you Captain Sensible. But you are right, it 
does avoid that extra little potential for errors.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-08 Thread Lew
Twisted wrote:
> On Jul 7, 6:12 pm, Lew <[EMAIL PROTECTED]> wrote:
>> Twisted wrote:
>> Edward Dodge wrote:
 So -- what magical computer app illuminates the entire room and shows
 you how to use everything at the flip of a switch?  This brilliant
 discovery would put Sam's, O'Reilly, the for-Dummies series, and
 virtually every other computer book publisher out of business in weeks.
 Naturally, this would include the publishers of books on "easy-to-use"
 Microsoft products.
>>> I don't know, but it sure as hell isn't emacs.
>> The reason you don't know, and Edward Dodge's point, is that there is no such
>> app, whether emacs or not.
> 
> Translation: since perfection is unattainable, we shouldn't even try,
> and just foist upon our poor users whatever awkward and hard-to-learn
> interface pops into our heads first?

Nice rhetoric but completely twisted the point.  Blt!

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


Re: httplib module

2007-07-08 Thread Steve Holden
Boris Ozegovic wrote:
> Steve Holden wrote:
> 
 Why do I get double new lines when geting data from server?  Example:
>> How? It's customary to include details when you've solved your own 
>> problem in case someone else gets the same issue.
> 
> Ok.  In do_GET I had this two lines:
> 
> for line in file:
> print line 
> 
> As you can see, print inserted another \n.  :-)
> 
> Correct code is:
> 
> for line in file:
> print line, 
> 
Thanks. Glad you got it sorted out.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: allow scripts to use .pth files?

2007-07-08 Thread samwyse
On Jul 3, 9:35 am, Alan Isaac <[EMAIL PROTECTED]> wrote:
> Suppose I have a directory `scripts`.
> I'd like the scripts to have access to a package
> that is not "installed", i.e., it is not on sys.path.
> On this list, various people have described a variety
> of tricks they use, but nobody has proposed a
> pretty way to allow this.
> I am therefore assuming there is not one. (?)
>
> How about allowing a `scripts.pth` file in such a `scripts`
> directory, to work like a path configuration file?
> (But to be used only when __name__=="__main__".)
> Drawbacks?
>
> Alan Isaac

before i can adequately shoot down your proposal, i need more
information.

first, how does the interpreter know to look in 'scripts' for your
'scripts.pyh' file and not in '.' or '~' or sys.argv[0] or someplace
else?  and you do know, don't you, that if you run 'scripts/
myscript.py' then 'scripts' is automagically prepended to the search
path for modules?

second, what's for format of this proposed file?  does it contain the
name of a single directory?  is it one directory name per line?  is it
intended to be os-specific or will the same file work on windows,
unix, vms and macos?

third, is there anything special about the name?  should i put a
myscripts.pyh file in the myscripts directory?  what if i have
multiple .pyh files?

if i may make some assumptions about the answers to the above, then
this incantation might do somewhat more than what you've asked for
(but what you actually want may be different):

if __name__ == '__main__':
import sys
from os.path import split, join, expanduser
for d in '.', split(sys.argv[0])[0], expanduser('~'):
scripts_pyh = join(d, 'scripts.pyh')
try:
for each_line in open(scripts_pyh).readlines():
sys.path.append(each_line)
except:
pass


personally, though, i would be more likely to use this and skip all of
that 'scripts.pyh' nonsense:

if __name__ == '__main__':
import sys, os.path
for d in '.', os.path.expanduser('~'):
if os.path.isdir(d): sys.path.append(d)

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


Re: socket: connection reset by server before client gets response

2007-07-08 Thread ahlongxp

> Try to wait a while in the server thread, after sending the
> message before closing the connection, to give the message
> time to get transmitted.
>
> time.sleep(0.5) should do it...
>
> - Hendrik

OMG, it works.
I can't believe the problem can be solved so easily.

Thanks very much.

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


Re: Where is the syntax for the dict() constructor ?!

2007-07-08 Thread Steve Holden
Hendrik van Rooyen wrote:
>  "John Machin" <[EMAIL PROTECTED]> wrote:
> 
> 8< nice explanation of quoting problems -
> 
>> (2) A field containing an odd number of " characters (or more
>> generally, not meeting whatever quoting convention might be expected
>> in the underlying data) should be treated with suspicion.
> 
> How does one program to treat something with suspicion?
> 
> My stuff tends to either accept or reject...
> 
> This reminds me (for no discernible reason) of the word 
> "eschew", and of an illustration in a Goon author's book
> of someone eschewing an architectural example with a 
> pocket sized eschewing instrument - a "pocket eschewer".
> (He is shown peering at it through the eyepiece)
> 
> Maybe such fields should be eschewed instead.
> 
Would we do that with esteeth?

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: socket.makefile() buggy?

2007-07-08 Thread Steve Holden
That's a pretty pejorative subject line for someone who's been
programming Python [guessing by the date of your first post] for about a
month.

Perhaps "Incomprehensible behavior from socket.makefile()", or "I have
written a buggy network application"? That would at least show that you
are considering the possibility you yourself are the cause of the
problem ;-)

Python has been around for a long time, so you should ask yourself how
likely it is that you would be the first to discover such a fundamental
flaw? I'd be very surprised if someone doesn't point you at an article
on "how to ask smart questions", but I will content myself with that
oblique reference.

ahlongxp wrote:
> socket.makefile() may lose data when "connection reset by peer".
> and socket.recv() will never lose the data.
> 
> change the "1" to "0" in the client code to see the difference.
> 
> confirmed on both windows and linux.
> 
> so I guess there is a problem with makefile().
> 
> # Echo server program
> import socket
> 
> HOST = '' # Symbolic name meaning the local host
> PORT = 50007  # Arbitrary non-privileged port
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
> s.bind((HOST, PORT))
> s.listen(1)
> while(1):
> conn, addr = s.accept()
> print 'Connected by', addr
> conn.settimeout(1)
> toread = 99
> retrytime = 0
> reads = 0
> while reads < toread and retrytime < 10:
> try:
> data = conn.recv(min(32,toread-reads))
> if not data: continue
> print data
> reads += len(data)
> except:
> retrytime += 1
> print "timeout %d" % retrytime
> continue
> #conn.shutdown(socket.SHUT_RD)#no more read
> if reads == toread:
> conn.send("OK")
> else:
> conn.send("NOT OK")
> conn.close()
> 
> # Echo client program
> import socket
> 
> HOST = 'localhost'# The remote host
> PORT = 50007  # The same port as used by the server
> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> s.connect((HOST, PORT))
> for i in range(12):
> print "time %d" % i
> try:
> s.send('0123456789')
> except socket.error, e:
> print "socket error:", e
> break
> #data = s.recv(1024)
> #print "data %d" %i, data
> #s.shutdown(socket.SHUT_WR)#no more write
> 
> '''
> try changing 1 to 0.
> '''
> if 1:
> data=s.recv(1024)
> else:
> rf = s.makefile("rb")
> data = rf.read()
> rf.close()
> s.close()
> print 'Received', repr(data)
> 
> 
The big problem here seems to be that your server is closing the socket
after reading 99 bytes, but the client is actually sending 120. If you
change the "99" in the server to "120" you will see that the client
works when it uses the makefile().read(). I can't be bothered to debug
the exact reason why the 21 bytes of buffered data doesn't cause a
problem with the recv() version, but I wouldn't regard the error you are
getting as a bug in Python, rather as a bug in your application.

The underlying cause of all this appears to be your failure to
understand that network protocols should ideally allow the endpoints to
determine when a complete message has been transmitted, and to consume
all transmitted data.

You can't just ignore some or all of a client request and expect it not
to cause problems. If you look at some of the better-known TCP-based
application protocols you will see they take pains to ensure that
clients and servers can deterministically parse each others' messages.

In summary, a better protocol design will cause you rather less grief
and a little more humility will result in less acidity from crabby old
geeks like me.

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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

Re: Re-raising exceptions with modified message

2007-07-08 Thread Christoph Zwerschke
Did you run this?
With Py < 2.5 I get a syntax error, and with Py 2.5 I get:

 new.__class__ = old.__class__
TypeError: __class__ must be set to a class

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


Re: Re-raising exceptions with modified message

2007-07-08 Thread Christoph Zwerschke
samwyse wrote:
> def test(code):
>   try:
> code()
>   except Exception, e:
> try:
>   raise e.__class__, str(e) + ", sorry!"
> except TypeError:
>   raise SorryFactory(e)()

Ok, you're suggestig the naive approach if it works and the factory 
approach I came up with last as a fallback. Maybe a suitable compromize.

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


Re: Pretty Printing Like Tidy for HTML

2007-07-08 Thread John J. Lee
David <[EMAIL PROTECTED]> writes:

> Is there a pretty printing utility for Python, something like Tidy for
> HTML?
>
> That will change:
>
> xp=self.uleft[0]+percentx*(self.xwidth)
>
> To:
>
> xp = self.uleft[0] + percentx * (self.xwidth)
>
> And other formatting issues.

Googled and found these; no idea if they're any good (latter is
commercial):

http://cheeseshop.python.org/pypi/PythonTidy/1.11

http://python.softalizer.com/


See also:

http://svn.python.org/view/python/trunk/Tools/scripts/reindent.py?view=log


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


Validating XML in Windows

2007-07-08 Thread Omari Norman
My app needs to validate XML. That's easy enough in Unix. What is the
best way to do it in Windows?

The most obvious choice would of course be PyXML. However, apparently it
is no longer maintained:

http://sourceforge.net/project/showfiles.php?group_id=6473

so there are no Windows binaries that work with Python 2.5. Getting
other XML libraries like libxml2 also seems to be quite difficult on
Windows.

Has anyone else dealt with this problem and found a solution? It would
even be fine if I could find a free command-line validator that I could
invoke with subprocess, but I haven't even had luck with that.

Thanks,
Omari

-- 
Pay a little now, or pay a lot later.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-08 Thread Bjorn Borud
[Twisted <[EMAIL PROTECTED]>]
| 
| Translation: since perfection is unattainable, we shouldn't even try,
| and just foist upon our poor users whatever awkward and hard-to-learn
| interface pops into our heads first?

uh, I think the point here is that some think it might be an idea to
force *their* idea of the ideal interface upon others, refusing to
understand that people might have their own preferences.

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


Re: Validating XML in Windows

2007-07-08 Thread Stefan Behnel
Omari Norman wrote:
> My app needs to validate XML. That's easy enough in Unix. What is the
> best way to do it in Windows?
> 
> The most obvious choice would of course be PyXML. However, apparently it
> is no longer maintained:
> 
> http://sourceforge.net/project/showfiles.php?group_id=6473
> 
> so there are no Windows binaries that work with Python 2.5. Getting
> other XML libraries like libxml2 also seems to be quite difficult on
> Windows.
> 
> Has anyone else dealt with this problem and found a solution? It would
> even be fine if I could find a free command-line validator that I could
> invoke with subprocess, but I haven't even had luck with that.

lxml has statically built  Windows binaries available for version 1.2.1, those
for 1.3.2 should become available soon. It supports RelaxNG, XMLSchema, DTDs
and (with a little patching) Schematron.

http://codespeak.net/lxml/

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


Re: xmlrpclib hangs execution

2007-07-08 Thread Arno Stienen
Arno Stienen wrote:
> I'll now try this to fool the client into thinking the server 'should' 
> keep the connection open:
> 
> http://www.velocityreviews.com/forums/t329401-re-xmlrpc-httplib-and-ssl-http-11-xmlrpc-client.html
>  

Just to conclude. Above actually worked and solved my problems with 
xmlrpclib hanging.

Here you can find the above link with correct indentation:
http://mail.python.org/pipermail/python-list/2004-April/256360.html

Thanks for all the advice, especially from Tijs!

Bye,
Arno.
-- 
http://mail.python.org/mailman/listinfo/python-list


Learning Basics

2007-07-08 Thread Brad
So I've been studying python for a few months (it is my first foray
into computer programming) and decided to write my own little simple
journaling program. It's all pretty basic stuff but I decided that I'd
learn more from it if more experienced programmers could offer some
thoughts on how I could do things better.

#simple little journal

from time import asctime
myjournal=file('journal.txt','a+')

formatter="*"*80+"\n"
todaysdate=asctime()
myjournal.write(formatter)
myjournal.write(todaysdate + "\n\n")

loop="set"

while loop!=':a':
loop=raw_input(':')
if loop!=':a':
myjournal.write(loop+"\n")
if loopz==':a':
myjournal.close()

#end of stuff

So I'd appreciate some good feedback or ideas.

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


Re: Validating XML in Windows

2007-07-08 Thread bsneddon
On Jul 8, 12:22 pm, Stefan Behnel <[EMAIL PROTECTED]> wrote:
> Omari Norman wrote:
> > My app needs to validate XML. That's easy enough in Unix. What is the
> > best way to do it in Windows?
>
> > The most obvious choice would of course be PyXML. However, apparently it
> > is no longer maintained:
>
> >http://sourceforge.net/project/showfiles.php?group_id=6473
>
> > so there are no Windows binaries that work with Python 2.5. Getting
> > other XML libraries like libxml2 also seems to be quite difficult on
> > Windows.
>
> > Has anyone else dealt with this problem and found a solution? It would
> > even be fine if I could find a free command-line validator that I could
> > invoke with subprocess, but I haven't even had luck with that.
>
> lxml has statically built  Windows binaries available for version 1.2.1, those
> for 1.3.2 should become available soon. It supports RelaxNG, XMLSchema, DTDs
> and (with a little patching) Schematron.
>
> http://codespeak.net/lxml/
>
> Stefan

You might try something like this.  I am sure you can find help on
MSDN.
I know DOM may not be most efficient but could be a way to solve the
problem
on windows.
>>> import win32com.client
>>>
>>> import win32com.client
>>> objXML = win32com.client.Dispatch("MSXML2.DOMDocument.3.0")
>>> objXML.load(r'C:\data\pyexamples\xml\acro.xml')
True
# not sure how to load schema but there must be away
>>> objXML.validate()

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


python extra

2007-07-08 Thread Neal Becker
Just a little python humor:

http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJAK/ref=sr_1_14/103-7715091-4822251?ie=UTF8&s=hpc&qid=1183917462&sr=1-14

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


Re: Learning Basics

2007-07-08 Thread Dan Bishop
On Jul 8, 12:10 pm, Brad <[EMAIL PROTECTED]> wrote:
> So I've been studying python for a few months (it is my first foray
> into computer programming) and decided to write my own little simple
> journaling program. It's all pretty basic stuff but I decided that I'd
> learn more from it if more experienced programmers could offer some
> thoughts on how I could do things better.
>
> #simple little journal
>
> from time import asctime
> myjournal=file('journal.txt','a+')
>
> formatter="*"*80+"\n"
> todaysdate=asctime()
> myjournal.write(formatter)
> myjournal.write(todaysdate + "\n\n")
>
> loop="set"
>
> while loop!=':a':
> loop=raw_input(':')
> if loop!=':a':
> myjournal.write(loop+"\n")
> if loopz==':a':
> myjournal.close()
>
> #end of stuff
>
> So I'd appreciate some good feedback or ideas.

#!/usr/bin/env python

"""simple little journal"""

import sys
import time

EXIT_COMMAND = ':a'
HEADER = "*" * 80

def add_journal_entry(filename='journal.txt'):
"""
Prompt the user to enter text, and write it into the journal file.
"""
print "Enter your journal entry."
print "When done, type %r." % EXIT_COMMAND
journal_file = file(filename, 'a+')
journal_file.write(HEADER + "\n")
journal_file.write(time.asctime() + "\n\n")
while True:
line = raw_input(':')
if line == EXIT_COMMAND:
break
journal_file.write(line + "\n")
journal_file.close()

def _main(argv=None):
"""Executed when file is run as a script."""
if argv is None:
argv = sys.argv
if len(argv) == 1: # No filename specified; use the default
add_journal_entry()
else:
add_journal_entry(argv[1])

if __name__ == '__main__':
_main()

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


Re: Pretty Printing Like Tidy for HTML

2007-07-08 Thread bsneddon
On Jul 8, 10:59 am, [EMAIL PROTECTED] (John J. Lee) wrote:
> David <[EMAIL PROTECTED]> writes:
> > Is there a pretty printing utility for Python, something like Tidy for
> > HTML?
>
> > That will change:
>
> > xp=self.uleft[0]+percentx*(self.xwidth)
>
> > To:
>
> > xp = self.uleft[0] + percentx * (self.xwidth)
>
> > And other formatting issues.
>
> Googled and found these; no idea if they're any good (latter is
> commercial):
>
> http://cheeseshop.python.org/pypi/PythonTidy/1.11
>
> http://python.softalizer.com/
>
> See also:
>
> http://svn.python.org/view/python/trunk/Tools/scripts/reindent.py?vie...
>
> John

I did this useing the BeautifulSoup module.
Used it on XML created by msWord which had no formating was
all on one line.

>>> import BeautifulSoup
>>> soupStr = open('c:/data/quotes.xml').read()
>>> soup = BeautifulSoup.BeautifulSoup(soupStr)
>>> pSoup = soup.prettify()
>>> outFile = open('c:/data/quotesTidy.xml','w')
>>> outFile.write(pSoup)
>>> outFile.close()

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


Is there anyone familiar with pybloom (bloom filter in python)?

2007-07-08 Thread Xell Zhang

Hello,

I found pybloom module from http://www.imperialviolet.org/pybloom.html and
tried to use it for my crawler:)
I want to use it to store the URLs which have been crawled. But when I
insert a URL string I always get a warning and wrong result...

My testing code is quite simple:
from pybloom import CountedBloom
cb = CountedBloom(80, 4)
cb.insert("AAA")
print cb.__contains__("BBB")

Warning:
E:\EclipseWorkspace\demo\src\pybloom.py:74: DeprecationWarning: 'I' format
requires 0 <= number <= 4294967295
 b = [ord(x) for x in struct.pack ('I', val)]

I will get warning when running the code above.
The output is "1" which means "BBB" is in the set. But actually it is not...
When I use integer for testing it seems right.

I am not familiar with arithmetic and I don't know if I wrote something
wrong.
Can anyone help me? Thanks!



--
Zhang Xiao

Junior engineer, Web development

Ethos Tech.
http://www.ethos.com.cn
-- 
http://mail.python.org/mailman/listinfo/python-list

accessing an object instance by only having one of its attribute values

2007-07-08 Thread feli . hp
Hello all,

Imaybe someone can help me with this question.
Is there a direct way of accessing an object instance, if all I know
is the value of one of its attributes?
The object is part of a list of objects, and I would like to pick the
object directly by using this attribute value, instead of going
through the list and checking if each objects attribute value is the
one I am looking for.

Thank you in advance

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


In search of python idiom for accessing arbitrary fields at run time

2007-07-08 Thread mshiltonj
I'm trying to find the preferred python idiom for access arbitrary
fields of objects at run time.


For example, say I have an object the business code will do
*something* with three arbitrary fields at a given time, but I don't
know what the three fields are at run time. In perl, I'd do something
like this:

 sub three_fields{
  my $self = shift;
  my @fields = @_;

  foreach my $field (@fields)
  {
my $value = $self->$field; # this is the one I'm
interested in
[...]
  }
 }

In python, I'm doing something like this:

 def three_fields(self, field1, field2, field3):
  for field in (field1, field2, field3):
value = eval('self.' + field) # this is the one I'm
interested in
[...]

This seems to do what I expect it to do. I'm wondering if that's the
preferred or standard way to do this in python. I wasn't sure how to
tease the answer to this question out of Google.

Thanks.

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


Re: python extra

2007-07-08 Thread [EMAIL PROTECTED]
On Jul 8, 12:59?pm, Neal Becker <[EMAIL PROTECTED]> wrote:
> Just a little python humor:
>
> http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJ...

Aren't there any female Python programmers?

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


Re: In search of python idiom for accessing arbitrary fields at run time

2007-07-08 Thread Jean-Paul Calderone
On Sun, 08 Jul 2007 18:21:41 -, mshiltonj <[EMAIL PROTECTED]> wrote:
>I'm trying to find the preferred python idiom for access arbitrary
>fields of objects at run time.
>

It's not an idiom, it's a built-in function: getattr.

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


Re: In search of python idiom for accessing arbitrary fields at run time

2007-07-08 Thread OKB (not okblacke)
mshiltonj wrote:
> In python, I'm doing something like this:
> 
>  def three_fields(self, field1, field2, field3):
>   for field in (field1, field2, field3):
> value = eval('self.' + field) # this is the one I'm
> interested in
> [...]
> 
> This seems to do what I expect it to do. I'm wondering if that's the
> preferred or standard way to do this in python. I wasn't sure how to
> tease the answer to this question out of Google.

I believe you are looking for the getattr function.

-- 
--OKB (not okblacke)
Brendan Barnwell
"Do not follow where the path may lead.  Go, instead, where there is
no path, and leave a trail."
--author unknown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: In search of python idiom for accessing arbitrary fields at run time

2007-07-08 Thread mshiltonj
On Jul 8, 2:31 pm, "OKB (not okblacke)"
<[EMAIL PROTECTED]> wrote:
> mshiltonj wrote:
> > In python, I'm doing something like this:
>
> >  def three_fields(self, field1, field2, field3):
> >   for field in (field1, field2, field3):
> > value = eval('self.' + field) # this is the one I'm
> > interested in
> > [...]
>
> > This seems to do what I expect it to do. I'm wondering if that's the
> > preferred or standard way to do this in python. I wasn't sure how to
> > tease the answer to this question out of Google.
>
> I believe you are looking for the getattr function.
>
> --
> --OKB (not okblacke)
> Brendan Barnwell
> "Do not follow where the path may lead.  Go, instead, where there is
> no path, and leave a trail."
> --author unknown


Doh. I figured it'd by FAQish. :-/  Thanks.

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


Re: Pretty Printing Like Tidy for HTML

2007-07-08 Thread bsneddon
On Jul 8, 1:53 pm, bsneddon <[EMAIL PROTECTED]> wrote:
> On Jul 8, 10:59 am, [EMAIL PROTECTED] (John J. Lee) wrote:
>
>
>
> > David <[EMAIL PROTECTED]> writes:
> > > Is there a pretty printing utility for Python, something like Tidy for
> > > HTML?
>
> > > That will change:
>
> > > xp=self.uleft[0]+percentx*(self.xwidth)
>
> > > To:
>
> > > xp = self.uleft[0] + percentx * (self.xwidth)
>
> > > And other formatting issues.
>
> > Googled and found these; no idea if they're any good (latter is
> > commercial):
>
> >http://cheeseshop.python.org/pypi/PythonTidy/1.11
>
> >http://python.softalizer.com/
>
> > See also:
>
> >http://svn.python.org/view/python/trunk/Tools/scripts/reindent.py?vie...
>
> > John
>
> I did this useing the BeautifulSoup module.
> Used it on XML created by msWord which had no formating was
> all on one line.
>
> >>> import BeautifulSoup
> >>> soupStr = open('c:/data/quotes.xml').read()
> >>> soup = BeautifulSoup.BeautifulSoup(soupStr)
> >>> pSoup = soup.prettify()
> >>> outFile = open('c:/data/quotesTidy.xml','w')
> >>> outFile.write(pSoup)
> >>> outFile.close()

Sorry, I answered the wrong question.
You wanted to format code not HTML.

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


Re: accessing an object instance by only having one of its attribute values

2007-07-08 Thread Stargaming
[EMAIL PROTECTED] wrote:
> Hello all,
> 
> Imaybe someone can help me with this question.
> Is there a direct way of accessing an object instance, if all I know
> is the value of one of its attributes?
> The object is part of a list of objects, and I would like to pick the
> object directly by using this attribute value, instead of going
> through the list and checking if each objects attribute value is the
> one I am looking for.
> 
> Thank you in advance
> 

Okay, imagine you got a bunch of small packets (presents or something 
similiar). You want to get rid of the lightest one. You cannot see 
weights, so, what you're doing is basically measuring the weight of 
*every single packet*, compare and pick. No way around.

There might be some ways not having to touch *each* object, if you 
precompute some results. So, in the example above, you could divide the 
packets into two categories, "more than 50 lbs" and "less than 50 lbs", 
for example. I think binary trees might be interesting here but touching 
every object would be way easier.

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


Re: accessing an object instance by only having one of its attribute values

2007-07-08 Thread mshiltonj
On Jul 8, 2:18 pm, [EMAIL PROTECTED] wrote:
> Hello all,
>
> Imaybe someone can help me with this question.
> Is there a direct way of accessing an object instance, if all I know
> is the value of one of its attributes?
> The object is part of a list of objects, and I would like to pick the
> object directly by using this attribute value, instead of going
> through the list and checking if each objects attribute value is the
> one I am looking for.
>
> Thank you in advance


I'd set up a dict as a lookup table, assuming the attribute values are
unique per object.


list_of_objects = (obj1, obj2, obj3, obj4);

obj_lookup_by_attr = {};

for obj in list_of_objects:
   obj_lookup_by_attr.set(obj.attr, obj)

[...]

obj = obj_lookup_by_attr.get(attr_val, None);

if (obj):
   [...]



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


Changing the user-agent in urllib

2007-07-08 Thread James Matthews

Is there anyway of changing the user-agent in urllib without sub classing
it?

--
http://www.goldwatches.com/watches.asp?Brand=14
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Validating XML in Windows

2007-07-08 Thread numeralblue
On Jul 8, 10:01 am, Omari Norman <[EMAIL PROTECTED]> wrote:
> My app needs to validate XML. That's easy enough in Unix. What is the
> best way to do it in Windows?
>
> The most obvious choice would of course be PyXML. However, apparently it
> is no longer maintained:
>
> http://sourceforge.net/project/showfiles.php?group_id=6473

I use the xmlproc parser that is included in PyXML. It is pure Python
so
as a temporary solution it is easy to include it with my source. I
haven't
had problems with it yet even though it is dated as you mentioned.

--Miguel

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-08 Thread Twisted
On Jul 8, 4:28 am, Adriano Varoli Piazza <[EMAIL PROTECTED]> wrote:
> b) If you do want to keep an antediluvian copy of emacs -probably
> versioned in the negative numbers, for all you've said- please do. Do
> be so kind as to send a copy, since it might be quite valuable as an
> antique.

Judging by the existence of the newsgroup comp.emacs, emacs is indeed
considered by some to be a quite valuable antique. Otherwise why on
earth would it have an apparently fairly active newsgroup a full seven
years into the 21st century?

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-08 Thread Twisted
On Jul 8, 12:18 pm, Bjorn Borud <[EMAIL PROTECTED]> wrote:
> uh, I think the point here is that some think it might be an idea to
> force *their* idea of the ideal interface upon others, refusing to
> understand that people might have their own preferences.

I, for one, have a strong preference for interfaces that let me see
what the hell I'm doing and make it easy to find commands, navigate
the interface, navigate the help, and so forth, while making me resort
to reaching for that help as infrequently as reasonably achievable.

But that's just me.

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-08 Thread Matthias Buelow
Twisted wrote:

> I, for one, have a strong preference for interfaces that let me see
> what the hell I'm doing and make it easy to find commands, navigate
> the interface, navigate the help, and so forth, while making me resort
> to reaching for that help as infrequently as reasonably achievable.

These are, of course, not unreasonable wishes. I assume you're
programming that software already, given that you're crossposting to
various programming-language newsgroups. Very well. We'll eagerly judge
you by what you'll come up with.


F'up-to: comp.emacs.
-- 
http://mail.python.org/mailman/listinfo/python-list


"Empty" text

2007-07-08 Thread Jan Danielsson
Hello all,

   I'm using mod_python+ElementTree to build XHTML pages. But I stumbled
across this problem:


def foo(req, desc = None):

   ...

   tr = ET.SubElement(tbl, "tr")
   th = ET.SubElement(tr, "th")
   th.text = "Description"
   td = ET.SubElement(tr, "td")
   ta = ET.SubElement(td, "textarea", name="desc", rows="8",
cols="64")
   if desc is None:
  desc = ''
   ta.text = desc


   The problem is that this generates the following code:

  
Description

  

  

   Firefox is very unhappy about the textarea not having separate
opening and a closing tags. i.e. I need this:

  

   I understand the opitmization ElementTree is performing; but it seems
there are cases when it is not the proper thing to do. Is it possible to
 force ElementTree to output the XHTML code I need it to?

-- 
Kind regards,
Jan Danielsson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Changing the user-agent in urllib

2007-07-08 Thread Inigo Serna
On Sun, Jul 08, 2007 at 12:21:38PM -0700, James Matthews wrote:
> Is there anyway of changing the user-agent in urllib without sub classing
> it?

Yes,

>>> import urllib
>>> urllib.URLopener.version = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 
>>> 5.0; T312461)'

Regards,
I�igo Serna
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-08 Thread David Kastrup
Twisted <[EMAIL PROTECTED]> writes:

> On Jul 8, 4:28 am, Adriano Varoli Piazza <[EMAIL PROTECTED]> wrote:
>> b) If you do want to keep an antediluvian copy of emacs -probably
>> versioned in the negative numbers, for all you've said- please do. Do
>> be so kind as to send a copy, since it might be quite valuable as an
>> antique.
>
> Judging by the existence of the newsgroup comp.emacs, emacs is
> indeed considered by some to be a quite valuable antique. Otherwise
> why on earth would it have an apparently fairly active newsgroup a
> full seven years into the 21st century?

As opposed to your brain, Emacs has not undergone fossilization 10
years ago.  While a newsgroup discussing your dim recollections of
Emacs would indeed be boring (apart from the amusement value of your
pomposity), a newsgroup discussing current (and evolving) versions and
use of Emacs has its place.  And anyway, the language C has changed
much less in the last 10 years than Emacs has, and you'll still find
active discussion groups for that, too: it is still very much in use,
like Emacs.

As a note aside, you'd be hard put to find an editor that manages a
similar multitude of encodings as well as Emacs does.  While it is to
be expected that in the long term utf-8-encoded Unicode is the way of
the future (and Emacs is going to focus more on that in future
versions, too), at the moment there are few editors which keep up with
the existing multitude of multibyte encodings as well as Emacs does.

Emacs also makes it fairly easy to input stuff without much hassle, so
you can easily write things like ἐν ἀρχῇ ἦν ὁ λόγος or каша гречневая.

So even if you don't like the user interface of Emacs from 10 years
ago and delight in assuming that it did not change in all that time,
there would be valid reasons for using it nevertheless.

-- 
David Kastrup, Kriemhildstr. 15, 44793 Bochum
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread sturlamolden
On Jun 20, 8:53 pm, Stephen R Laniel <[EMAIL PROTECTED]> wrote:

> Reading [1], I wonder: why isn't the compiler making better
> use of (purely optional) type labeling? Why not make a compiler
> directive so that
>
> a) it will check the types of all my arguments and return
>values,

If that is what you want, you can get typechecking using a simple
function decorator:

def typechecked(func):
types = func.func_defaults
def decorator(*args):
if len(args) != len(types):
raise TypeError, 'Wrong number or arguments, expected %d
got %d' % (len(types),len(args))
for a,t in zip(args,types):
if type(t) == type:
if type(a) is not t:
raise TypeError, 'Expected ' + str(t) + ' got ' +
str(type(a))
else:
if type(a) is not type(t):
raise TypeError, 'Expected ' + str(type(t)) + '
got ' + str(type(a))
return func(*args)
return decorator


Now code like this:

@typechecked
def foobar(a = int, b = float, c = tuple):
   return None

or

@typechecked
def foobar(a = int, b = float, c = 1.0):
   return None

Your calls to foobar will be typechecked (at runtime, not statically),
and a TypeError exception thrown if your calling types were
incorrect.


Regards,

Sturla Molden

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


Re: The Modernization of Emacs: terminology buffer and keybinding

2007-07-08 Thread Wildemar Wildenburger
David Kastrup wrote:
> Twisted <[EMAIL PROTECTED]> writes:
>   
>> Judging by the existence of the newsgroup comp.emacs, emacs is
>> indeed considered by some to be a quite valuable antique. Otherwise
>> why on earth would it have an apparently fairly active newsgroup a
>> full seven years into the 21st century?
>> 
>
> As opposed to your brain, Emacs has not undergone fossilization 10
> years ago.
Will you people let it go already? Didn't we agree that guy was 
trolling. Just let the man rant. What harm does he do? At least he's not 
bombing busses in Jerusalem or Bagdad, not spreading AIDS in Africa, not 
selling kids lives to companies. He just pookes fun at everyone. Why do 
you people care? Its a text editor, dammit. Let go.

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


Re: allow scripts to use .pth files?

2007-07-08 Thread John Machin
On Jul 8, 10:53 pm, samwyse <[EMAIL PROTECTED]> wrote:
> On Jul 3, 9:35 am, Alan Isaac <[EMAIL PROTECTED]> wrote:
>
> > Suppose I have a directory `scripts`.
> > I'd like the scripts to have access to a package
> > that is not "installed", i.e., it is not on sys.path.
> > On this list, various people have described a variety
> > of tricks they use, but nobody has proposed a
> > pretty way to allow this.
> > I am therefore assuming there is not one. (?)
>
> > How about allowing a `scripts.pth` file in such a `scripts`
> > directory, to work like a path configuration file?
> > (But to be used only when __name__=="__main__".)
> > Drawbacks?
>
> > Alan Isaac
>
> before i can adequately shoot down your proposal, i need more
> information.
>
> first, how does the interpreter know to look in 'scripts' for your
> 'scripts.pyh' file and not in '.' or '~' or sys.argv[0] or someplace
> else?

I got the impression that the OP was suggesting that the interpreter
look in the directory in which it found the script.

> and you do know, don't you, that if you run 'scripts/
> myscript.py' then 'scripts' is automagically prepended to the search
> path for modules?

I got the impression that the problem was that the package was not
only not on sys.path but also not in the same directory as the script
that wanted to import it. Otherwise the OP's script.p?h file need only
contain ".\n" (or the path to the  directory in which it resided!!),
and I doubt that he was proposing something so silly.

I'm curious whether you think that the OP's use of ".pth" was a typo,
and whether you have read this:
http://docs.python.org/lib/module-site.html

Cheers,
John

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


Re: "Empty" text

2007-07-08 Thread Marc 'BlackJack' Rintsch
On Sun, 08 Jul 2007 22:23:20 +0200, Jan Danielsson wrote:

>The problem is that this generates the following code:
> 
>   
> Description
> 
>   
> 
>   
> 
>Firefox is very unhappy about the textarea not having separate
> opening and a closing tags. i.e. I need this:
> 
>   
> 
>I understand the opitmization ElementTree is performing; but it seems
> there are cases when it is not the proper thing to do. Is it possible to
>  force ElementTree to output the XHTML code I need it to?
>

Then either Firefox is broken or you don't declare your XHTML properly and
Firefox thinks it's HTML.

Ciao,
Marc 'BlackJack' Rintsch
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __unicode__ method for exception object

2007-07-08 Thread Manlio Perillo
Il Sun, 08 Jul 2007 10:02:01 +1000, Ben Finney ha scritto:

> Manlio Perillo <[EMAIL PROTECTED]> writes:
> 
>> I have just noticed that exception objects does not handle well Unicode
>> arguments.
> 
> This error is unrelated to the fact that you created an exception
> object.
> 

No, it is related.

>> >>> e = RuntimeError(u'àèìòù')
>> >>> str(e)
>> Traceback (most recent call last):
>>   File "", line 1, in ?
>> UnicodeEncodeError: 'ascii' codec can't encode characters in position
> 
> Your terminal has been detected as using the 'ascii' encoding, so while
> that's true no attempt to output non-ASCII characters will work.
> 
> You'll need to change whatever settings are on your terminal emulator so
> that it is using an encoding (such as 'utf-8') which can display the
> characters you want.


This is not a problem with the terminal.
And the problem is not with str(e) but with unicode(e).

unicode(e) converts the exception argument to an Unicode object, but 
since no __unicode__ object is defined, it firsts calls the __str__ 
method (and this, of course, fails, since the default encoding in CPython 
is us-ascii) and then converts the result to an Unicode object using, 
again, the default encoding.



Regards  Manlio Perillo
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread Steven D'Aprano
On Sun, 08 Jul 2007 08:49:26 -0400, Steve Holden wrote:

> Paul Rubin wrote:
>> Steve Holden <[EMAIL PROTECTED]> writes:
 Python even leaks the index variable of list comprehensions (I've
 mostly stopped using them because of this), though that's a
 recognized wart and is due to be fixed.

>>> Wow, you really take non-pollution of the namespace seriously. I agree
>>> it's a wart, but it's one I have happily worked around since day one.
>> 
>> Well, the obvious workaround is just say "list()"
>> instead of [] so that's what I do.
> 
> I think I'll start calling you Captain Sensible. But you are right, it 
> does avoid that extra little potential for errors.

I'd be thinking it should be Captain Paranoid. Why is list comp leakage
a worse problem than, well, having local variables in the first place?

def foo(x):
y = something_or_other(x+1)
z = do_something_else(y) + another_thing(y)
# Oh noes!!! y still exists!!1!11!! What to do
return ("foo", y)  # OMG I meant to say z!!!


If your function has got so many lines of code, and so many variables that
this becomes a source of errors, your function should be refactored into
smaller functions.

As far as I can see, the only difference is that the list comp variable
isn't explicitly created with a statement of the form "name = value". Why
is that a problem?


-- 
Steven.

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


Re: python extra

2007-07-08 Thread Danyelle Gragsone
Nope.. not a one..


On 7/8/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> On Jul 8, 12:59?pm, Neal Becker <[EMAIL PROTECTED]> wrote:
> > Just a little python humor:
> >
> > http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJ...
>
> Aren't there any female Python programmers?
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread Paul Rubin
Steven D'Aprano <[EMAIL PROTECTED]> writes:
> As far as I can see, the only difference is that the list comp variable
> isn't explicitly created with a statement of the form "name = value". Why
> is that a problem?

I don't know that listcomp vars are worse problem than other vars;
however there is an easy workaround for the listcomp vars so I use it.
If there was a way to restrict the scope of other local vars (I gave
examples from other languages of how this can be done), I'd use that too.
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: gozerbot 0.7 released

2007-07-08 Thread bthate
it time for a new gozerbot release ! we made a 0.7 release of
gozerbot.

new in gozerbot 0.7:

* we have a new developer on the team .. Wijnand 'tehmaze'
Modderman he contributed most of the new work in this release.
copyright on tehmaze's work is BSD
* new plugins: rest, lag, nickserv, snarf, tinyurl, umode, popcon,
job
* udp messaging can now be encrypted
* remote installable plugins are now signed .. this means gnupg is
required to install these plugins
* new plugin site: http://plugins.gozerbot.org
* gozerbot now has it own popularity contest webpage .. see
http://plugins.gozerbot.org/popcon
* new periodical class for easy scheduling of jobs
* new bugtracker site: http://dev.gozerbot.org

the new release can be downloaded from the following resources:

* http://gozerbot.org/
* http://code.google.com/p/gozerbot
* debian users can install the bot from sid/unstable

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


What is the most efficient way to test for False in a list?

2007-07-08 Thread lex
Of course there is the always the iteration method:

list = [1, True, True, False, False, True]
status = True
for each in list:
status = status and each

but what is your best way to test for for False in a list?

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


Re: What is the most efficient way to test for False in a list?

2007-07-08 Thread Paul Rubin
lex <[EMAIL PROTECTED]> writes:
> list = [1, True, True, False, False, True]
> status = True
> for each in list:
> status = status and each
> 
> but what is your best way to test for for False in a list?

status = all(list)
-- 
http://mail.python.org/mailman/listinfo/python-list


Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread socialanxiety
i hope someone here can help me.

basically, me and my friend have a summer project.

in this project, we need something that would basically function as a
blender. we know we'll need to buy a motor that spins, but what we're
having trouble with is figuring out how to program it. we want to be
able to control the speed of the motor. how would we accomplish this?

i'm new to all of this, so i'm having a hard time wrapping my mind
around how it'd be possible to program one of those things :\

ex: what if i want the motor to turn for 10 seconds. stop for 5. then
turn the other direction.

would you program it the same way you would on a personal computer
(via c, python, etc)?

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


Re: python extra

2007-07-08 Thread Neal Becker
Danyelle Gragsone wrote:

> Nope.. not a one..
> 
> 
> On 7/8/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>> On Jul 8, 12:59?pm, Neal Becker <[EMAIL PROTECTED]> wrote:
>> > Just a little python humor:
>> >
>> > http://www.amazon.com/Vitamin-Shoppe-Python-Extra-tablets/dp/B00012NJ...
>>
>> Aren't there any female Python programmers?
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
I really think we should take up a collection to send this to Guido.

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


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread John Nagle
[EMAIL PROTECTED] wrote:
> i hope someone here can help me.
> 
> basically, me and my friend have a summer project.
> 
> in this project, we need something that would basically function as a
> blender. we know we'll need to buy a motor that spins, but what we're
> having trouble with is figuring out how to program it. we want to be
> able to control the speed of the motor. how would we accomplish this?
> 
> i'm new to all of this, so i'm having a hard time wrapping my mind
> around how it'd be possible to program one of those things :\
> 
> ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> turn the other direction.
> 
> would you program it the same way you would on a personal computer
> (via c, python, etc)?

Try "comp.robotics.misc" for the basics of robot motor control.

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


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread socialanxiety
On Jul 8, 5:14 pm, John Nagle <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > i hope someone here can help me.
>
> > basically, me and my friend have a summer project.
>
> > in this project, we need something that would basically function as a
> > blender. we know we'll need to buy a motor that spins, but what we're
> > having trouble with is figuring out how to program it. we want to be
> > able to control the speed of the motor. how would we accomplish this?
>
> > i'm new to all of this, so i'm having a hard time wrapping my mind
> > around how it'd be possible to program one of those things :\
>
> > ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> > turn the other direction.
>
> > would you program it the same way you would on a personal computer
> > (via c, python, etc)?
>
> Try "comp.robotics.misc" for the basics of robot motor control.
>
> John Nagle

thank you.

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


Re: accessing an object instance by only having one of its attribute values

2007-07-08 Thread Paul McGuire
On Jul 8, 2:11 pm, mshiltonj <[EMAIL PROTECTED]> wrote:
> On Jul 8, 2:18 pm, [EMAIL PROTECTED] wrote:
>
> > Hello all,
>
> > Imaybe someone can help me with this question.
> > Is there a direct way of accessing an object instance, if all I know
> > is the value of one of its attributes?
> > The object is part of a list of objects, and I would like to pick the
> > object directly by using this attribute value, instead of going
> > through the list and checking if each objects attribute value is the
> > one I am looking for.
>
> > Thank you in advance
>
> I'd set up a dict as a lookup table, assuming the attribute values are
> unique per object.
>
> list_of_objects = (obj1, obj2, obj3, obj4);
>
> obj_lookup_by_attr = {};
>
> for obj in list_of_objects:
>obj_lookup_by_attr.set(obj.attr, obj)
>
> [...]
>
> obj = obj_lookup_by_attr.get(attr_val, None);
>
> if (obj):
>[...]

I have some comments on the Pythonicity of your suggestions.  Same
assumption, object attr is a unique key of some sort.  How to create
the dict of objects, and how to retrieve an object by key.

-- Paul


list_of_objects = (obj1, obj2, obj3, obj4);

# creating a dict by initializing to empty, and then looping
# through input list and adding items one at a time
obj_lookup_by_attr = {};
for obj in list_of_objects:
#obj_lookup_by_attr.set(obj.attr, obj)
# why use set for this?  why not just this:
obj_lookup_by_attr[obj.attr] = obj

# or even better might be to use a generator expression to create a
# sequence of tuples, and call the dict constructor - a good idiom to
# learn
obj_lookup_by_attr = dict( (obj.attr,obj) for obj in list_of_objects )

[...]

obj = obj_lookup_by_attr.get(attr_val, None);

# oh woe if obj is an instance of a class that defines special
# true/falseness - obj might be a real object, but evaluates to false
#
#if (obj):
#
# much better to test this way
# (and NEVER test using "if obj != None:" - this is wasteful
# nonsense, since None is a singleton)
if obj is not None:
   [...]

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread Steve Holden
Paul Rubin wrote:
> Steven D'Aprano <[EMAIL PROTECTED]> writes:
>> As far as I can see, the only difference is that the list comp variable
>> isn't explicitly created with a statement of the form "name = value". Why
>> is that a problem?
> 
> I don't know that listcomp vars are worse problem than other vars;
> however there is an easy workaround for the listcomp vars so I use it.
> If there was a way to restrict the scope of other local vars (I gave
> examples from other languages of how this can be done), I'd use that too.

Maybe we just have different styles, and I naturally tend to write in 
smaller scopes than you do.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread Carsten Haese
On Sun, 2007-07-08 at 17:06 -0700, [EMAIL PROTECTED] wrote:
> i hope someone here can help me.
> 
> basically, me and my friend have a summer project.
> 
> in this project, we need something that would basically function as a
> blender. we know we'll need to buy a motor that spins, but what we're
> having trouble with is figuring out how to program it. we want to be
> able to control the speed of the motor. how would we accomplish this?
> 
> i'm new to all of this, so i'm having a hard time wrapping my mind
> around how it'd be possible to program one of those things :\
> 
> ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> turn the other direction.
> 
> would you program it the same way you would on a personal computer
> (via c, python, etc)?

The answers to your questions depend very much on what you're working
with and how the motor is controlled. Is this supposed to be a
self-contained machine, or is it supposed to be connected to a personal
computer as a peripheral device?

The easier way is the peripheral device. In that case, you need some way
of sending signals e.g. from your computer's parallel or serial port to
a relay switch or voltage controller that controls your motor. In that
case, apart from the nitty gritty hardware to make the physical
connections, it's a matter of controlling the parallel or serial port
that the "robot" is attached to, which can definitely be done in Python.

I won't go into details because you're not saying enough about your
project constraints, and as fascinating as your question is, it is
somewhat off-topic on this list (as if that's a deterrent to discussing
something on this list ;-). As John said, you're more likely to receive
useful advice on comp.robotics.misc.

Good luck,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: socket.makefile() buggy?

2007-07-08 Thread Paul McGuire
On Jul 8, 8:54 am, Steve Holden <[EMAIL PROTECTED]> wrote:
> That's a pretty pejorative subject line for someone who's been
> programming Python [guessing by the date of your first post] for about a
> month.
>
> Perhaps "Incomprehensible behavior from socket.makefile()", or "I have
> written a buggy network application"? That would at least show that you
> are considering the possibility you yourself are the cause of the
> problem ;-)
>
> Python has been around for a long time, so you should ask yourself how
> likely it is that you would be the first to discover such a fundamental
> flaw? I'd be very surprised if someone doesn't point you at an article
> on "how to ask smart questions", but I will content myself with that
> oblique reference.
>
>
>
>
>
> ahlongxp wrote:
> > socket.makefile() may lose data when "connection reset by peer".
> > and socket.recv() will never lose the data.
>
> > change the "1" to "0" in the client code to see the difference.
>
> > confirmed on both windows and linux.
>
> > so I guess there is a problem with makefile().
>
> > # Echo server program
> > import socket
>
> > HOST = '' # Symbolic name meaning the local host
> > PORT = 50007  # Arbitrary non-privileged port
> > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
> > s.bind((HOST, PORT))
> > s.listen(1)
> > while(1):
> > conn, addr = s.accept()
> > print 'Connected by', addr
> > conn.settimeout(1)
> > toread = 99
> > retrytime = 0
> > reads = 0
> > while reads < toread and retrytime < 10:
> > try:
> > data = conn.recv(min(32,toread-reads))
> > if not data: continue
> > print data
> > reads += len(data)
> > except:
> > retrytime += 1
> > print "timeout %d" % retrytime
> > continue
> > #conn.shutdown(socket.SHUT_RD)#no more read
> > if reads == toread:
> > conn.send("OK")
> > else:
> > conn.send("NOT OK")
> > conn.close()
>
> > # Echo client program
> > import socket
>
> > HOST = 'localhost'# The remote host
> > PORT = 50007  # The same port as used by the server
> > s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
> > s.connect((HOST, PORT))
> > for i in range(12):
> > print "time %d" % i
> > try:
> > s.send('0123456789')
> > except socket.error, e:
> > print "socket error:", e
> > break
> > #data = s.recv(1024)
> > #print "data %d" %i, data
> > #s.shutdown(socket.SHUT_WR)#no more write
>
> > '''
> > try changing 1 to 0.
> > '''
> > if 1:
> > data=s.recv(1024)
> > else:
> > rf = s.makefile("rb")
> > data = rf.read()
> > rf.close()
> > s.close()
> > print 'Received', repr(data)
>
> The big problem here seems to be that your server is closing the socket
> after reading 99 bytes, but the client is actually sending 120. If you
> change the "99" in the server to "120" you will see that the client
> works when it uses the makefile().read(). I can't be bothered to debug
> the exact reason why the 21 bytes of buffered data doesn't cause a
> problem with the recv() version, but I wouldn't regard the error you are
> getting as a bug in Python, rather as a bug in your application.
>
> The underlying cause of all this appears to be your failure to
> understand that network protocols should ideally allow the endpoints to
> determine when a complete message has been transmitted, and to consume
> all transmitted data.
>
> You can't just ignore some or all of a client request and expect it not
> to cause problems. If you look at some of the better-known TCP-based
> application protocols you will see they take pains to ensure that
> clients and servers can deterministically parse each others' messages.
>
> In summary, a better protocol design will cause you rather less grief
> and a little more humility will result in less acidity from crabby old
> geeks like me.
>
> regards
>  Steve
> --
> Steve Holden+1 571 484 6266   +1 800 494 3119
> Holden Web LLC/Ltd  http://www.holdenweb.com
> Skype: holdenweb  http://del.icio.us/steve.holden
> --- Asciimercial --
> Get on the web: Blog, lens and tag the Internet
> Many services currently offer free registration
> --- Thank You for Reading -- Hide quoted text -
>
> - Show quoted text -

I don't think you're crabby, Steve.

-- Paul

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread Paul Rubin
Steve Holden <[EMAIL PROTECTED]> writes:
> Maybe we just have different styles, and I naturally tend to write in
> smaller scopes than you do.

It's easy to make errors even in very small scopes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread half . italian
On Jul 8, 5:06 pm, [EMAIL PROTECTED] wrote:
> i hope someone here can help me.
>
> basically, me and my friend have a summer project.
>
> in this project, we need something that would basically function as a
> blender. we know we'll need to buy a motor that spins, but what we're
> having trouble with is figuring out how to program it. we want to be
> able to control the speed of the motor. how would we accomplish this?
>
> i'm new to all of this, so i'm having a hard time wrapping my mind
> around how it'd be possible to program one of those things :\
>
> ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> turn the other direction.
>
> would you program it the same way you would on a personal computer
> (via c, python, etc)?

This might be interesting to you.

http://www.makingthings.com/

~Sean

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


Re: accessing an object instance by only having one of its attribute values

2007-07-08 Thread mshiltonj
On Jul 8, 8:29 pm, Paul McGuire <[EMAIL PROTECTED]> wrote:
> On Jul 8, 2:11 pm, mshiltonj <[EMAIL PROTECTED]> wrote:

> I have some comments on the Pythonicity of your suggestions.  Same
> assumption, object attr is a unique key of some sort.  How to create
> the dict of objects, and how to retrieve an object by key.
>
> -- Paul

I was probably being overly helpful, in a bad way. I'm new to python,
I'm not very pythonic yet, and still learning the python idioms.

Not sure why I slipped into the habit of testing for None, though. :-(

Probably a perl thing, where I'm regularly testing for defined-ness.
"if ($foo)" is different than "if (defined $foo)"

Still, I'm really like python so far.

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


Re: What is the most efficient way to test for False in a list?

2007-07-08 Thread Evan Klitzke
On 7/8/07, lex <[EMAIL PROTECTED]> wrote:
> Of course there is the always the iteration method:
>
> list = [1, True, True, False, False, True]
> status = True
> for each in list:
> status = status and each
>
> but what is your best way to test for for False in a list?

In general, you can just do:

if something in list:
do_something()

-- 
Evan Klitzke <[EMAIL PROTECTED]>
-- 
http://mail.python.org/mailman/listinfo/python-list


Tool for finding external dependencies

2007-07-08 Thread Rob Cakebread
Hi,

I need to find external dependencies for modules (not Python standard
library imports).

Currently I use pylint and manually scan the output, which is very
nice, or use pylint's --ext-import-graph option to create a .dot file
and extract the info from it, but either way can take a very long
time.

I'm aware of Python's modulefinder.py, but it doesn't find external
dependencies (or at least I don't know how to make it do them).

Thanks,
Rob

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


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread [EMAIL PROTECTED]
First you'll need a computer interface to your robot. Lego Mindstorm,
for example, comes with ways to program the onboard CPU. Other
standard robotic toolkits will also come with some kind of interface,
which may or may not have Python bindings.

Cheers,
-T

On Jul 9, 10:06 am, [EMAIL PROTECTED] wrote:
> i hope someone here can help me.
>
> basically, me and my friend have a summer project.
>
> in this project, we need something that would basically function as a
> blender. we know we'll need to buy a motor that spins, but what we're
> having trouble with is figuring out how to program it. we want to be
> able to control the speed of the motor. how would we accomplish this?
>
> i'm new to all of this, so i'm having a hard time wrapping my mind
> around how it'd be possible to program one of those things :\
>
> ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> turn the other direction.
>
> would you program it the same way you would on a personal computer
> (via c, python, etc)?


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


How to Machine A python script execute Machine B python script?

2007-07-08 Thread johnny
Anyone know how I can make Machine A python script execute a python
script on Machine B ?

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


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread socialanxiety
On Jul 8, 5:37 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Sun, 2007-07-08 at 17:06 -0700, [EMAIL PROTECTED] wrote:
> > i hope someone here can help me.
>
> > basically, me and my friend have a summer project.
>
> > in this project, we need something that would basically function as a
> > blender. we know we'll need to buy a motor that spins, but what we're
> > having trouble with is figuring out how to program it. we want to be
> > able to control the speed of the motor. how would we accomplish this?
>
> > i'm new to all of this, so i'm having a hard time wrapping my mind
> > around how it'd be possible to program one of those things :\
>
> > ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> > turn the other direction.
>
> > would you program it the same way you would on a personal computer
> > (via c, python, etc)?
>
> The answers to your questions depend very much on what you're working
> with and how the motor is controlled. Is this supposed to be a
> self-contained machine, or is it supposed to be connected to a personal
> computer as a peripheral device?
>
> The easier way is the peripheral device. In that case, you need some way
> of sending signals e.g. from your computer's parallel or serial port to
> a relay switch or voltage controller that controls your motor. In that
> case, apart from the nitty gritty hardware to make the physical
> connections, it's a matter of controlling the parallel or serial port
> that the "robot" is attached to, which can definitely be done in Python.
>
> I won't go into details because you're not saying enough about your
> project constraints, and as fascinating as your question is, it is
> somewhat off-topic on this list (as if that's a deterrent to discussing
> something on this list ;-). As John said, you're more likely to receive
> useful advice on comp.robotics.misc.
>
> Good luck,
>
> --
> Carsten Haesehttp://informixdb.sourceforge.net

I would like the robot to be self contained. basically, I'd like to be
able to program functions in python, ex:

while True:
motor.rotate(1)

and have it repeat the same piece of code every time it's turned on.

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


Re: How to Machine A python script execute Machine B python script?

2007-07-08 Thread Jay Loden
If you're running on a UNIX platform, one option would be to use SSH to execute 
the command remotely. Otherwise, you could also use a client/server setup to 
have the two scripts communicate across the network and trigger actions etc. It 
may also be possible to remotely execute an application on Windows using the 
win32api extensions, but I haven't any idea how you'd go about that. Perhaps 
others can chime in with detailed information if you let us know what kind of 
platform you're on and what you're trying to accomplish. 

-Jay

johnny wrote:
> Anyone know how I can make Machine A python script execute a python
> script on Machine B ?
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the most efficient way to test for False in a list?

2007-07-08 Thread Carsten Haese
On Sun, 2007-07-08 at 18:32 -0700, Evan Klitzke wrote:
> On 7/8/07, lex <[EMAIL PROTECTED]> wrote:
> > Of course there is the always the iteration method:
> >
> > list = [1, True, True, False, False, True]
> > status = True
> > for each in list:
> > status = status and each
> >
> > but what is your best way to test for for False in a list?
> 
> In general, you can just do:
> 
> if something in list:
> do_something()

Caution! This tests whether at least one entry in 'list' is *equal* to
'something'. It is very unusual to want to test whether an object is
equal to True (or False). Usually one simply wants to know whether the
bool() value of that object is True (or False).

While it makes no difference with the contrived example above, in
general your suggestion may give unexpected results. The following
variant, making use of a generator expression to take the bool() of each
entry, will always work correctly:

if False in (bool(x) for x in list):
  do_something()

But then again, in Python 2.5 you can use all() as suggested by Paul
Rubin:

if not all(list):
  do_something()

I'd also like to point out, since nobody has so far, that 'list' is a
terrible name for a list because it shadows the name for the list type.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: How to Machine A python script execute Machine B python script?

2007-07-08 Thread half . italian
On Jul 8, 6:45 pm, johnny <[EMAIL PROTECTED]> wrote:
> Anyone know how I can make Machine A python script execute a python
> script on Machine B ?

xmlrpc will work.

~Sean

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


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread Carsten Haese
On Sun, 2007-07-08 at 19:18 -0700, [EMAIL PROTECTED] wrote:
> On Jul 8, 5:37 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> > On Sun, 2007-07-08 at 17:06 -0700, [EMAIL PROTECTED] wrote:
> > > i hope someone here can help me.
> >
> > > basically, me and my friend have a summer project.
> >
> > > in this project, we need something that would basically function as a
> > > blender. we know we'll need to buy a motor that spins, but what we're
> > > having trouble with is figuring out how to program it. we want to be
> > > able to control the speed of the motor. how would we accomplish this?
> >
> > > i'm new to all of this, so i'm having a hard time wrapping my mind
> > > around how it'd be possible to program one of those things :\
> >
> > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> > > turn the other direction.
> >
> > > would you program it the same way you would on a personal computer
> > > (via c, python, etc)?
> >
> > The answers to your questions depend very much on what you're working
> > with and how the motor is controlled. Is this supposed to be a
> > self-contained machine, or is it supposed to be connected to a personal
> > computer as a peripheral device?
> > [...]
> I would like the robot to be self contained. basically, I'd like to be
> able to program functions in python, ex:
> 
> while True:
> motor.rotate(1)

Good luck with that. Your best bet IMHO is to find a single-board
computer (commonly referred to as SBC) that is small enough to fit your
form-factor, capable of running Linux, and equipped with a suitable I/O
interface (e.g. serial or parallel port). In theory, this should allow
you to put Linux and Python on it and control your motor in Python as if
it were a peripheral device connected to a personal computer. In
practice, I've never done anything like this, and the devil is in the
details that you'll need to work out for yourself.

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread Paul Rubin
"Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> > Which implies that even in ADA, runtime type errors are in fact
> > expected - else there would be no handler for such a case.
> 
> Well, yes, runtime errors occur - in statically typed languages as
> well. That's essentially the halting-problem.

Well, no, it's quite possible for a language to reject every program
that has any possibility of throwing a runtime type error.  The
halting problem implies that no algorithm can tell EXACTLY which
programs throw errors and which do not.  So the language cannot accept
all programs that are free of runtime type errors and reject all
programs that definitely have runtime type errors, with no uncertain
cases.  But it's fine for a language to reject uncertain cases and
accept only those which it can rigorously demonstrate have no type
errors.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: What is the most efficient way to test for False in a list?

2007-07-08 Thread Simon Forman
On Jul 8, 7:43 pm, lex <[EMAIL PROTECTED]> wrote:
> Of course there is the always the iteration method:
>
> list = [1, True, True, False, False, True]
> status = True
> for each in list:
> status = status and each
>
> but what is your best way to test for for False in a list?


False in list





i.e. for a list N

if False in N:
# do something with N..

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


How to override PyGridTableBase.SetColLabelValue()?

2007-07-08 Thread fckuen
Dear all,

the doc is missing, and
i failed to find the solution on google search.
anyone know how to override
the function SetColLabel() inside the class PyGridTableBase or the
class GridTableBase?

my code,
#===
class MegaTable(wx.grid.PyGridTableBase):
def __init__(...)
.
wx.grid.PyGridTableBase.__init__(self)

def SetColLabelValue(self, col, value):
value = self.coltags[col]
-->how to ???

class MegaGrid(wx.grid.Grid):
def __init__(...)
.
wx.grid.Grid.__init__(self, parent, id)
self._table = MegaTable(self, .)
self.SetTable(self._table)
.
#===


thanks!

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

Re: What is the most efficient way to test for False in a list?

2007-07-08 Thread Daniel
On Mon, 09 Jul 2007 06:21:31 +0300, Simon Forman <[EMAIL PROTECTED]>  
wrote:

>
> On Jul 8, 7:43 pm, lex <[EMAIL PROTECTED]> wrote:
>> Of course there is the always the iteration method:
>>
>> list = [1, True, True, False, False, True]
>> status = True
>> for each in list:
>> status = status and each
>>
>> but what is your best way to test for for False in a list?
>
>
> False in list
>
>

all() is slightly faster


-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread Carlos Guerrero
One "generic" way is using your parallel port for outputting voltages
that would control Relays [2] that would be conected to the motor.

Parapin [1] is the easiest way i know to work with parallel ports but
its for C++, the python binding is still being developed [2].


[1] http://parapin.sourceforge.net/
[2] http://en.wikipedia.org/wiki/Relay
 http://es.wikipedia.org/wiki/Rel%C3%A9 <- these graphics are kinda better
[3] http://pyserial.sourceforge.net/pyparallel.html

On 7/9/07, Carsten Haese <[EMAIL PROTECTED]> wrote:
> On Sun, 2007-07-08 at 19:18 -0700, [EMAIL PROTECTED] wrote:
> > On Jul 8, 5:37 pm, Carsten Haese <[EMAIL PROTECTED]> wrote:
> > > On Sun, 2007-07-08 at 17:06 -0700, [EMAIL PROTECTED] wrote:
> > > > i hope someone here can help me.
> > >
> > > > basically, me and my friend have a summer project.
> > >
> > > > in this project, we need something that would basically function as a
> > > > blender. we know we'll need to buy a motor that spins, but what we're
> > > > having trouble with is figuring out how to program it. we want to be
> > > > able to control the speed of the motor. how would we accomplish this?
> > >
> > > > i'm new to all of this, so i'm having a hard time wrapping my mind
> > > > around how it'd be possible to program one of those things :\
> > >
> > > > ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> > > > turn the other direction.
> > >
> > > > would you program it the same way you would on a personal computer
> > > > (via c, python, etc)?
> > >
> > > The answers to your questions depend very much on what you're working
> > > with and how the motor is controlled. Is this supposed to be a
> > > self-contained machine, or is it supposed to be connected to a personal
> > > computer as a peripheral device?
> > > [...]
> > I would like the robot to be self contained. basically, I'd like to be
> > able to program functions in python, ex:
> >
> > while True:
> > motor.rotate(1)
>
> Good luck with that. Your best bet IMHO is to find a single-board
> computer (commonly referred to as SBC) that is small enough to fit your
> form-factor, capable of running Linux, and equipped with a suitable I/O
> interface (e.g. serial or parallel port). In theory, this should allow
> you to put Linux and Python on it and control your motor in Python as if
> it were a peripheral device connected to a personal computer. In
> practice, I've never done anything like this, and the devil is in the
> details that you'll need to work out for yourself.
>
> --
> Carsten Haese
> http://informixdb.sourceforge.net
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
/* Carlos A. Guerrero M.   [Alias: Sid]  */
/* ---  */
/* Linux User 390240  */
http://guerrerocarlos.blogspot.com
http://guerrerocarlos.wordpress.com
http://www.tooche.com.ve
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to override PyGridTableBase.SetColLabelValue()?

2007-07-08 Thread ajaksu
On Jul 9, 12:27 am, [EMAIL PROTECTED] wrote:
> Dear all,
>
> the doc is missing, and i failed to find the solution on google search.
> anyone know how to override the function SetColLabel() inside
> the class PyGridTableBase or the class GridTableBase?

Some docs to back up the old code that follows :)
http://wiki.wxpython.org/wxPyGridTableBase
http://wiki.wxpython.org/wxGrid
http://wxwidgets.org/manuals/stable/wx_wxgrid.html#wxgridsetcollabelvalue

I hope this helps, it's old and 2.6, the design had many weird
requirements plus I never got to think about whether it was a good way
to do it. Anyway, the docs are far better :)


> my code,
(snip)
Mine:
class SpeciesBase(object):
def __init__(self, ncols=1, nrows=15, colnames=None,
rownames=None):
self.__data = []
self.rows = []
self.cols = []
def __getitem__(self, col):
return self.__data[col][:]

class SpeciesTableBase(wx.grid.PyGridTableBase):
def __init__(self):
wx.grid.PyGridTableBase.__init__(self)
self.data = SpeciesBase()
self._rows = self.GetNumberRows()
self._cols = self.GetNumberCols()
def SetColLabelValue(self, col, value):
self.data.cols[col] = str(value)
def GetNumberRows(self):
return len(self.data[0])

class SpeciesGrid(wx.grid.Grid):
def __init__(self, parent):
wx.grid.Grid.__init__(self, parent, -1)
self.table = SpeciesTableBase()
def rename_col(self, col, value):
self.table.SetColLabelValue(col, value)
self.table.ResetView(self)

Other useful links:
http://wiki.wxpython.org/UpdatingGridData
http://wiki.wxpython.org/DrawingOnGridColumnLabel

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


Re: How to override PyGridTableBase.SetColLabelValue()?

2007-07-08 Thread Frank Millman
On Jul 9, 5:27 am, [EMAIL PROTECTED] wrote:
> Dear all,
>
> the doc is missing, and
> i failed to find the solution on google search.
> anyone know how to override
> the function SetColLabel() inside the class PyGridTableBase or the
> class GridTableBase?
>
> my code,
> #===
> class MegaTable(wx.grid.PyGridTableBase):
> def __init__(...)
> .
> wx.grid.PyGridTableBase.__init__(self)
>
> def SetColLabelValue(self, col, value):
> value = self.coltags[col]
> -->how to ???
>
> class MegaGrid(wx.grid.Grid):
> def __init__(...)
> .
> wx.grid.Grid.__init__(self, parent, id)
> self._table = MegaTable(self, .)
> self.SetTable(self._table)
> .
> #===
>
> thanks!

You are not supposed to override SetColLabel(), you are supposed to
override GetColLabelValue().

When you use PyGridTableBase, there could potentially be thousands of
columns, and wxPython does not want to keep track of thousands of
column labels.

Therefore, when wxPython needs to display a column label, it calls
GetColLabelValue(self,col). It is up to you to return the value to use
for that column.

HTH

Frank Millman

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


A clean way to program an interface

2007-07-08 Thread rh0dium
Hi all,

I got this new radio scanner (toy!!) this weekend and I can access it
via a serial cable. I want to write a interface around it but I am
looking for some suggestions.  I thought at first I would simply class
the Scanner and write the various methods as attibutes similar to
below..  But then I thought about it and I don't like it for a couple
of obvious reasons - there isn't any data checking, and it's terribly
repetitive.

So I started searching on google - and I think it might be better to
use a (sub)class for each function ( class STS, PRG, etc.). where the
attributes are accessible as both dict items and lists - which
ultimately go and "set" the scanner.

I guess my question is this.

I have a function SIN which when one argument is given does an
effective "get" from the scanner - this returns some 10+ values.  When
some 10+ parameters are given it does an effective "set" to the
scanner.  Given that I can't remember all 10+ parameters I attempted
below to represent them as a dict where the key tells me what the heck
the parameter is supposed to represent.  So a simple translation
occurs on both the set and get which splits the list into a named dict
and vice versa.   Question 1 - I think I should be checking the data
before a set - is this a smart thing or should I just do a try/
except?  Question 2 - Since I only want to do this once (ok twice)
should I represent each function as a class or should I keep the code
I have below?

Thanks



==  My garbage.. ==

class Scanner():

def __init__(self, *args, **kwargs):
 
self.uniden=UnidenConnection.UnidenConnection(port=kwargs.get('port',
PORT), bps=kwargs.get('bps', 115200), loglevel=self.loglevel)

def STS(self):
return self.uniden.write("STS")

def PRG(self):
"""Go into programming mode"""
if self.uniden.write(sys._getframe().f_code.co_name)[0]=="OK":
return True
else: return False

def PRGWrite(self,command):
data = self.uniden.write(command)
if data[0] == "NG":
if self.PRG():
data = self.uniden.write(command)
if not self.EPG():
raise IOError, "Unable to exit programming
mode"
if data[0] == "ERR":
raise IOError, "Error when running command %s" % command
return data

def EPG(self):
"""Get out of programming mode"""
if self.uniden.write(sys._getframe().f_code.co_name)[0]=="OK":
return True
else: return False

def SCT(self):
"""Get the system count"""
self.systems =
int(self.PRGWrite(sys._getframe().f_code.co_name)[0])
return self.systems

def SIH(self):
"""Get the site index head"""
self.sih = int(self.PRGWrite(sys._getframe().f_code.co_name)
[0])
return self.sih

def SIT(self):
"""Get the site index tail"""
self.sit = int(self.PRGWrite(sys._getframe().f_code.co_name)
[0])
return self.sit

def FWD(self,idx):
"""Get the next site index"""
fwd = int(self.PRGWrite("%s,%s" %
(sys._getframe().f_code.co_name,idx))[0])
return fwd

def SIF(self, idx, args=None):
"""Get / Set Site Info"""
if args is None:
p=self.PRGWrite("%s,%s" %
(sys._getframe().f_code.co_name,idx))
t={}
 
t["site_type"],t["name"],t["quick_key"],t["hld"],t["lout"],t["mod"], \
t["att"],t["c-
ch"],t["apco"],t["threshold"],t["rev_index"],t["fwd_index"], \
 
t["sys_index"],t["chn_head"],t["chn_tail"],t["seq_no"],t["start_key"],
\
 
t["latitude"],t["longitude"],t["range"],t["gps_enable"],t["rsv"]=p
delitems=[]
for item in t:
if t[item]=="": delitems.append(item)
for x in delitems: del t[x]
if len(t.keys())==0:
raise IOError, "Unable to program %s - Returned
Nothing" % (sys._getframe().f_code.co_name)
else:
return t
else:
args["rsv"]=""
 
s=[ 
args["index"],args["name"],args["quick_key"],args["hld"],args["lout"],args["mod"],
\
args["att"],args["c-
ch"],args["apco"],args["threshold"],args["start_key"], \
 
args["latitude"],args["longitude"],args["range"],args["gps_enable"],args["rsv"]]
p=self.PRGWrite("%s,%s" %
(sys._getframe().f_code.co_name,",".join(s)))
if p[0] != "OK":
raise IOError, "Unable to program %s - Returned %s" %
(sys._getframe().f_code.co_name,p[0])
else: return True

def SIN(self, idx, args=None):
"""Get / Set System Info"""
if args is None:
p=self.PRGWrite("%s,%s" %
(sys._getframe().f_code.co_name,idx))
t={}
t["sys_type"],t["name"],t["quick_key"],t["hld"],t["lout"],
\
 
t["dly"],t["skp"],t["rsv"],t["rsv"],t["apco"],t["threshold"], \
 
t["rev_index"],t["fwd_index"],t["chn_grp_head"],t["chn_grp_tail"], \
 
t["seq_no"],t["start_key"],t["record"],t["latitude"],t["longitude"]

Re: ANN: gozerbot 0.7 released

2007-07-08 Thread Ben Finney
bthate <[EMAIL PROTECTED]> writes:

> it time for a new gozerbot release ! we made a 0.7 release of
> gozerbot.

When announcing a new release, please include a brief "What is
gozerbot?" explanation section so that readers can know whether the
announcement is of interest.

-- 
 \   "Pinky, are you pondering what I'm pondering?" "Well, I think |
  `\ so, Brain, but first you'd have to take that whole bridge |
_o__)  apart, wouldn't you?"  -- _Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread John Nagle
Paul Rubin wrote:
> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> 
>>>Which implies that even in ADA, runtime type errors are in fact
>>>expected - else there would be no handler for such a case.
>>
>>Well, yes, runtime errors occur - in statically typed languages as
>>well. That's essentially the halting-problem.
> 
> 
> Well, no, it's quite possible for a language to reject every program
> that has any possibility of throwing a runtime type error.  The
> halting problem implies that no algorithm can tell EXACTLY which
> programs throw errors and which do not.  So the language cannot accept
> all programs that are free of runtime type errors and reject all
> programs that definitely have runtime type errors, with no uncertain
> cases.  But it's fine for a language to reject uncertain cases and
> accept only those which it can rigorously demonstrate have no type
> errors.

That's correct.  Speaking as someone who once implemented an automatic
proof of correctness system (here's the manual:
http://www.animats.com/papers/verifier/verifiermanual.pdf), the halting
problem isn't an issue.  If you write a program for which halting is
undecidable, the program is basically broken.

The way you prove loop termination in the real world is to define
some integer value (you can also use tuples like (1,2,1,3), like
paragraph numbers) that gets smaller each time you go through the
loop, but never goes negative.

Most type issues can be resolved at compile time if you can
see the whole program.

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


Re: socket: connection reset by server before client gets response

2007-07-08 Thread Hendrik van Rooyen
 "ahlongxp" <[EMAIL PROTECTED]> wrote:


> 
> > Try to wait a while in the server thread, after sending the
> > message before closing the connection, to give the message
> > time to get transmitted.
> >
> > time.sleep(0.5) should do it...
> >
> > - Hendrik
> 
> OMG, it works.
> I can't believe the problem can be solved so easily.
> 
> Thanks very much.

It's a pleasure.

Sometimes I think that all would be programmers should be
forced to write a "Hello World" to transmit out of a serial port
in assembler on hardware that carries no OS - just to teach 
them about interrupts and time.

I would require them to hand assemble the code too, to make
them appreciate what a compiler or an interpreter does.

And if you fail the test, you get taken out and fed to the 
sacred crocodiles.

- Hendrik

--
For training with a bite, enrol now in Heavy Henry's 
Wholesome Hackadamy for Precocious Programmers



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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-08 Thread John Nagle
Paul Rubin wrote:
> "Diez B. Roggisch" <[EMAIL PROTECTED]> writes:
> 
>>>Which implies that even in ADA, runtime type errors are in fact
>>>expected - else there would be no handler for such a case.
>>
>>Well, yes, runtime errors occur - in statically typed languages as
>>well. That's essentially the halting-problem.
> 
> 
> Well, no, it's quite possible for a language to reject every program
> that has any possibility of throwing a runtime type error.  The
> halting problem implies that no algorithm can tell EXACTLY which
> programs throw errors and which do not.  So the language cannot accept
> all programs that are free of runtime type errors and reject all
> programs that definitely have runtime type errors, with no uncertain
> cases.  But it's fine for a language to reject uncertain cases and
> accept only those which it can rigorously demonstrate have no type
> errors.

Also, if you're really into this, read this DEC SRL report on
Extended Static Checking for Java, a system from the 1990s.

ftp://gatekeeper.research.compaq.com/pub/DEC/SRC/research-reports/SRC-159.pdf

They were doing great work until Compaq bought DEC and killed off research.

The follow up to that is Microsoft's Spec# effort, which is program
verification for C#.  See

http://research.microsoft.com/specsharp/

They have some of the same people, and some of the same code, as the
DEC effort.

Back when I was working on this, we only had a 1 MIPS VAX, and theorem
proving was slow.  That's much less of a problem now.

John Nagle

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


Re: unify els database

2007-07-08 Thread luca72
Many thanks

I will try with Jython

Regards

Luca


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


Re: Where is the syntax for the dict() constructor ?! (OT)

2007-07-08 Thread Hendrik van Rooyen
 "Steve Holden" <[EMAIL PROTECTED]> wrote:

> Would we do that with esteeth?

Ok Steve you've got me - my dictionary goes from
estate to esteem to ester...

The US spelling of "esthete" may have a bearing...

- Hendrik

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


Re: ANN: gozerbot 0.7 released

2007-07-08 Thread bthate
On 9 jul, 07:25, Ben Finney <[EMAIL PROTECTED]>
wrote:
> bthate <[EMAIL PROTECTED]> writes:
> > it time for a new gozerbot release ! we made a 0.7 release of
> > gozerbot.
>
> When announcing a new release, please include a brief "What is
> gozerbot?" explanation section so that readers can know whether the
> announcement is of interest.
>
> --
>  \   "Pinky, are you pondering what I'm pondering?" "Well, I think |
>   `\ so, Brain, but first you'd have to take that whole bridge |
> _o__)  apart, wouldn't you?"  -- _Pinky and The Brain_ |
> Ben Finney

sorry forgot about it ;] will do so the next time.

Bart

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


Re: ANN: gozerbot 0.7 released

2007-07-08 Thread bthate
here is the about:

gozerbot is a Python IRC and Jabber bot
Requirements

* a shell
* python 2.4 or higher
* if you want to remotely install plugins: the gnupg module
* if you want mysql support: the py-MySQLdb module
* if you want jabber support: the xmpppy module

Why gozerbot?

* user management by userhost .. bot will not respond if it
doesn't know you (see /docs/USER/)
* fleet .. use more than one bot in a program (list of bots) (see /
docs/FLEET/)
* use the bot through dcc chat .. partyline
* fetch rss feeds (see /docs/RSS/)
* keep todo and shop lists
* karma
* quote
* remember items
* relaying between bots (see /docs/RELAY/)
* program your own plugins (see /docs/PROGRAMPLUGIN/)
* run the builtin webserver (see /docs/WEBSERVER/)
* query other bots webserver via irc (see /docs/COLLECTIVE/)
* other stuff


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


Re: Is there a way to program a robot with python (ex, an electric motor, control it's speed, etc)

2007-07-08 Thread Hendrik van Rooyen
 <[EMAIL PROTECTED]> wrote:

> i hope someone here can help me.
> 
> basically, me and my friend have a summer project.
> 
> in this project, we need something that would basically function as a
> blender. we know we'll need to buy a motor that spins, but what we're
> having trouble with is figuring out how to program it. we want to be
> able to control the speed of the motor. how would we accomplish this?
> 
> i'm new to all of this, so i'm having a hard time wrapping my mind
> around how it'd be possible to program one of those things :\
> 
> ex: what if i want the motor to turn for 10 seconds. stop for 5. then
> turn the other direction.
> 
> would you program it the same way you would on a personal computer
> (via c, python, etc)?

It needs a bit more than just the motor - you need to organise some i/o
(lines that the computer can control) and some kind of interface to control
the power, and you have to put it all together - can you solder?

It may be easier to forget about the computer stuff and just use relay logic
for direction control - given that it is a DC motor that would turn the other
way, and not a universal motor (like the one in a drill, that turns the same 
way given either AC or DC).

Speed control for a small motor can be accomplished by a heavy rheostat
in series with the motor.

And that should be good enough for a summer project.

On the other hand, if you (or your parents) have pots of money then
you can buy digital to analog hardware that can be used to tell a powerful
DC coupled amplifier what to do, and have a stab at programming the
resultant combination.

But if I were you, I would do the first kind of thing, and use the rest of the 
summer to soak up the sun, instead of breathing solder fumes in a basement,
or crouching over a keyboard ruining your eyes watching a screen...


HTH  - Hendrik



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


  1   2   >