Re: UI toolkits for Python

2005-10-17 Thread Steve Holden
Claudio Grondi wrote:
> "Steve Holden" <[EMAIL PROTECTED]> schrieb im Newsbeitrag
[...]
[Claudio]
>>>I don't fully understand your attitude here. The Web Browser interface
> 
> has
> 
>>>all I can imagine is required for a GUI, so what is missing when you
>>>consider, that you can generate custom images on the fly on the server
> 
> and
> 
>>>let the user shape the page without requesting CPU power from the server
>>>using JavaScript.
>>
>>In this case then, I'm afraid the failure is in your imagination :-)
> 
> 
> Any useful hints towards enlightenment except criticism?
> 
Perhpas the mistake I made was bearing in mind the title of the thread, 
and the fact that this is a Python newsgroup.
> 
>>>I don't even name here the not really beeing itegral part of Internet
>>>Browsers JavaApplets and any other kind of plugin stuff.
>>>The only issue I can see with this approach is the speed of responding
> 
> to
> 
>>>user interactions, but for really optimize this one needs a compiled
>>>language anyway.
>>>What is that complex, that it can't be solved using an Internet Browser
> 
> as a
> 
>>>GUI?
>>>Do I miss here something?
>>>
>>
>>While you are correct in saying (I paraphrase) that HTML interfaces
>>nowadays can offer a rich graphical interface, it can be quite difficult
>>to manage state maintenance between the two components (web server, web
>>client) in the system.
> 
> 
> The cause of confusion here is, that HTML interfaces don't necessary need a
> web server and HTTP to work. I mean, that Internet Browsers
> have an API which allow access to them directly, so they can be used without
> a server as a kind of GUI library supporting widgets programmed
> in HTML and JavaScript  (I haven't used them yet in this form, but I think
> it should be no problem - right or not?).
> 
You are perfectly correct that interfaces can be programmed in the 
browser. As has already been said, with the adoption of standards like 
CSS2, it's even possible to make such stuff run across multiple browser 
platforms (at the moment, though, just try writing an interface that 
makes table rows appear and disappear in a cross-browser fashion: you'll 
find the stylesheet techniques you need to use for Mozilla and IE are 
very different). But this doesn't help you at all if you are trying to 
interface to Python logic.
> 
>>A "proper" GUI runs all functionality inside a single process, and
>>allows much easier control over complex interactions, creation of
>>dynamic dialogues, and so on.
> 
> Complex and dynamic is in my eyes possible with HTML and JavaScript, so I
> still don't see where is a problem with this approach. I have programmed
> already a HTML and JavaScript driven server platform and know about (the
> solvable) problems with the back-button and sessions (it is sure not the
> easiest way of programming a GUI).
> The only disadvantage of not using plugins or Java is, that real time
> interactions are not possible, but this is in my eyes usually not the
> requirement for a standard kind of GUI with no gaming, no Virtual Reality
> and no timing of user response down to milliseconds (but consider, that with
> a good speed of connection it is even possible to play blitz chess over the
> Internet).
> 
So, back to the subject: with an HTML/Javascript interface, how do you 
propose to bolt Python logic into the same process? Or do you admit that 
the application that interacts with such an interface either has to be 
all JavaScript or in a separate process?

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: can a cut-down Python still be Python?

2005-10-17 Thread Paddy
If you mean missing out some of the libraries then that would be
different to missing out core functionality sucjh as generators or list
expressions,...

In general, if the end task is not to present the world with a new
programming language then it's usually best to choose from the
available, supported languages rather than creating your own.

Maybe you should take a look at, for example, Lua:
  http://www.lua.org/

But if the trail leads back to Python, then go for it :-)

- Pad.

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


Re: can a cut-down Python still be Python?

2005-10-17 Thread Fredrik Lundh
"The Eternal Squire" wrote:

> Regardless of the technical difficulties involved (and I know they are
> legion), I am considering developing a very limited subset of Python
> fit to run on embedded systems using 80188 or 68332 microchips.   My
> main question regarding this is:  even if I am successful, would the
> results be rejected out of hand by y'all as not meeting the Zen of
> Python?

some blabbermouths will probably reject it, but no matter how you
twist words, a subset of Python is indeed a subset of Python.

magnus lie hetland's mini-python is a good base to build upon:

http://hetland.org/python/mini-python.php





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


Re: How do you draw this layout with wxpython?

2005-10-17 Thread Tim
Young H. Rhiu wrote:
> See: http://hilug.org/img/app_layout.GIF
> 
> I'm implementing an album-like application with wxpython but I'm new to
> wxPython though I know how to program with python. The problem is that
> it's not easy for me to deal with drawing layout stuff with wxpython.
> What layout I'm thinking of looks like the gif image above.
> 
> The application is about saving some comments for each pictures on the
> filesystem. There are two windows. The above one is a window for
> loading some images and the below one is a TextCtrl for writing
> comments and if img1, for instance, is clicked, the first notebook(?)
> folder should be active.
> 
> Below is the program I tried but I don't know how to attach a notebook
> window under the image window.
> Any help is greatly appreciated.
> 
> Thanks in Advance, Rhiu
> 
> My Code:
> from wxPython.wx import *
> 
> class smallAppFrame(wxFrame):
> def __init__(self, parent, id, title):
> wxFrame.__init__(self, parent = None, id = -1,
>  title = "MySmallApp", pos = wxPoint(200, 200),
>  size = wxSize(460, 200), style =
> wxDEFAULT_FRAME_STYLE)
> 
> self.bitmap01 = wxStaticBitmap(self, -1,
> wxEmptyBitmap(100,100))
> self.bitmap02 = wxStaticBitmap(self, -1,
> wxEmptyBitmap(100,100))
> self.bitmap03 = wxStaticBitmap(self, -1,
> wxEmptyBitmap(100,100))
> self.bitmap04 = wxStaticBitmap(self, -1,
> wxEmptyBitmap(100,100))
> 
> box = wxBoxSizer(wxHORIZONTAL)
> 
> box.Add((10,10))
> box.Add(self.bitmap01, 0, wxALIGN_CENTER)
> box.Add((10,10))
> box.Add(self.bitmap02, 0, wxALIGN_CENTER)
> box.Add((10,10))
> box.Add(self.bitmap03, 0, wxALIGN_CENTER)
> box.Add((10,10))
> box.Add(self.bitmap04, 0, wxALIGN_CENTER)
> box.Add((10,10))
> 
> self.SetAutoLayout(True)
> self.SetSizer(box)
> 
> class MySmallApp(wxApp):
> def OnInit(self):
> frame = smallAppFrame(None, -1, "MySmallApp")
> frame.Show(true)
> self.SetTopWindow(frame)
> return true
> 
> app = MySmallApp(0)
> app.MainLoop()
> 
Hi
Take a LONG look at Boa Constructor. Boa is young, imperfect, and a 
little emotional at times.

BUT after spending a few hours with it - I think I could create your 
screen layout in a matter of minutes.

Really is worth the steep learning curve and the frustration.
timb

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


Outdated documentation

2005-10-17 Thread Laszlo Zsolt Nagy

Hi All,


This is from the documentation of the dbhash module:

Returns the key next key/value pair in a database traversal. The
following code prints every key in the database |db|, without having
to create a list in memory that contains them all:

print db.first()
for i in xrange(1, len(db)):
print db.next()


Apparently, it is different for gdbm:

k = db.firstkey()
while k != None:
print k
k = db.nextkey(k)

I think both of them is outdated. This should be:

for key,value in db.iteritems():
print key,value

Is this the good place to post?

  Les

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


Repost: Text not showing up

2005-10-17 Thread Simone
Simone wrote:

>Hi all, I am new to python and trying to write a simple GUI that would 
>call 2 growisofs processes (dvd burning) at the same time, and retrive 
>the exit code to be printed on a text box (couldn't find any program 
>that could use multiple dvd burners, not even k3b). Excuse me if this is 
>really a simple problem, but two days of googling didn't help.
> The program is really simple, I developed the GUI using glade and it 
>works.
>The only thing I would like to improve is that I'd like it to show in 
>the text boxes messages like "Waiting for use input" or "Burning dvd 
>please wait", but it looks like even though I don't have any error, the 
>message won't show up until the burning process is finished (showing 
>either "burning successfully" or "an error occurred").
>I am not sure I made myself clear on this, but I will post the relevant 
>code trying to explain it:
>
>import os, sys
>import gtk.glade
>   
>class DVD:
>   
> 
>def __init__(self):
>print "Initializing the Graphic User Interface: This may take 
>some time"
>self.xml=gtk.glade.XML("./dvd2.xml") 
>self.window=self.xml.get_widget("dvd")
>self.xml.signal_connect('on_quit_clicked', self.Quit)
>self.xml.signal_connect('on_burn_clicked', self.Burn)   
>
>self.OrdKeys=["comboentry1","entry1","spinbutton1","entry2","esitotext","esitotext1"]
>  
># here esitotext is the box I want the text to show up
>
>
>
>def Quit(self, *args):
>gtk.mainquit()
>
>def Burn(self, *args):
>
>comand=""
>comand2=""
>
>name=self.xml.get_widget("entry1").get_text()#name 
>for the dvd
>path=self.xml.get_widget("comboentry1").get_text()   #path to 
>dvd AUDIO_TS and VIDEO_TS
>num=self.xml.get_widget("spinbutton1").get_text()  #chosing 
>the number of dvd to burn
>pub=self.xml.get_widget("entry2").get_text()
>#publisher
>self.xml.get_widget("esitotext").set_text("Waiting for 
>input") #THIS NEVER SHOWS UP
>
>   
>dvd1="/dev/hda" # this is the first dvd 
>burner, edit as needed
>dvd2="/dev/hdc" # this is the second dvd 
>burner, edit as needed
>
>
>
>comand+="growisofs -dvd-compat -Z "+dvd1+" -dvd-video -V 
>"+name+" -publisher "+pub+" "+path 
>comand2+="growisofs -dvd-compat -Z "+dvd2+" -dvd-video -V 
>"+name+" -publisher "+pub+" "+path
>
>
>if num == "1":
>self.xml.get_widget("esitotext").set_text("Burning the dvd, 
>please wait")#  THIS NEVER SHOWS UP, unless i have an error and 
>the program
>
>   #  quits 
>before executing the command
>self.xml.get_widget("esitotext").show() 
>   #  don't know if this is correct, 
>but it doesn't work either
>f = os.popen(comand, 'r')
>line = f.readline()
>
>error_in_prog = f.close()
>if error_in_prog:
>error=str(error_in_prog)
>self.xml.get_widget("esitotext").set_text("An error 
>occurred. Burn not completed")  # THIS COMES UP as it should
>self.xml.get_widget("esitotext").show()
>else:
>self.xml.get_widget("esitotext").set_text("Burn 
>completed successfully")# THIS COMES UP as it should
>self.xml.get_widget("esitotext").show()
>
>
>if __name__=='__main__':
>main=DVD()
>gtk.main()
>
>
>Any comment, help, url, really appreciated.
>
>Have a nice day
>Simone
>
>
>
>  
>

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


Re: TypeError: unbound method PrintInput() must be called with test instance as first argument (got test instance instead)

2005-10-17 Thread arotem
Thanks... it solves the problem :-)

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


Re: TypeError: unbound method PrintInput() must be called with test instance as first argument (got test instance instead)

2005-10-17 Thread arotem
Thanks... it solves the problem :-)

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


graphic memory & animation

2005-10-17 Thread Peres



Thanks a lot for your answer, Fredrik,
Slow means more than 20ms to erase the screen. 
After double buffering it improved a lot , of course (16 ms) but I'll need a 
faster speed.
I program 2D animated sequences on a PC. Do you 
think OpenGL is the correct direction to take? If so is it easy to interface 
with Python (it seems PyOpenGL is not freeware...)
 
Thanks again for your kind help
 
Valerie Peres
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: bizarro world (was Re: Python Doc Problem Example: sort() (reprise))

2005-10-17 Thread Xah Lee

Bryan wrote:
> mr. xah... would you be willing to give a lecture at pycon 2006?  i'm sure you
> would draw a huge crowd and a lot of people would like to meet you in 
> person...
>
> thanks.

I'd be delight to.

My requirements are: 1 cup of fat-free milk, free, and free pizza.

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

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

Re: graphic memory & animation

2005-10-17 Thread Fredrik Lundh
"Peres" wrote:

> Slow means more than 20ms to erase the screen. After double buffering it
> improved a lot , of course (16 ms) but I'll need a faster speed.

are you measuring the time it takes to go from a populated screen to a blank
screen?  if so, you're probably seeing the screen refresh time (16 ms = 60 fps)
rather than the time it takes to draw things.

try disabling vertical sync in your display driver to see if that fixes the 
problem

(if you do things the right way, you shouldn't have to do that: you should 
clear/copy
and draw the new screen before you flip the buffers)

 



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


Re: popen4

2005-10-17 Thread Piet van Oostrum
> "billie" <[EMAIL PROTECTED]> (b) wrote:

>b> Hi all. I'm trying to execute system commands and capture the output by 
>b> using popen4:

>b> stdout example:
> exec_cmd = popen2.popen4("echo hello!")
> output = exec_cmd[0].read()
>b> hello

>b> stderr example:
> exec_cmd = popen2.popen4("echobv hello!")
> output = exec_cmd[0].read()
>b> Unrecognized command

>b> The problem occurs when I try to execute interactive commands like ftp, 
>b> python intepreter etc...
>b> In this case the program crashes without even giving an error.

Crashes?

>b> Suggestions?

I think you need something like pyexpect for this.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Question on class member in python

2005-10-17 Thread Johnny Lee
Class A:
   def __init__(self):
  self.member = 1

   def getMember(self):
  return self.member

a = A()

So, is there any difference between a.member and a.getMember? thanks
for your help. :)

Regards, 
Johnny

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


Re: How to get a raised exception from other thread

2005-10-17 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> Nevermind.  I found a better solution.  I used shared memory to create
> a keep-alive flag.  I then use the select function with a specified
> timeout, and recheck the keep-alive flag after each timeout.

Definitely a better architecture.  Anyway, one supported way for a
thread to raise an exception in a different thread is function
thread.interrupt_main(), which raises a KeyboardInterrupt in the *main*
thread (the one thread that's running at the beginning of your program).

There's also a supported, documented function to raise any given
exception in any existing thread, but it's deliberately NOT directly
exposed to Python code -- you need a few lines of  C-coded extension (or
pyrex, ctypes, etc, etc) to get at the functionality.  This small but
non-null amount of "attrition" was deliberately put there to avoid
casual overuse of a facility intended only to help in very peculiar
cases (essentially in debuggers &c, where the thread's code may be buggy
and fail to check a keep-alive flag correctly...!-).


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


Re: How to get a raised exception from other thread

2005-10-17 Thread Antoon Pardon
Op 2005-10-14, dcrespo schreef <[EMAIL PROTECTED]>:
> Hi all,
>
> How can I get a raised exception from other thread that is in an
> imported module?
>
> For example:

You could try the following class, it needs ctypes and if the exception
is raised while in a C-extention, the exception will be delayed until
the extention is left. Some delay is unavoidable. You may also need
to fiddle with the length of the sleep at the end of this script 
or the values in the xrange calls in the Continue threads

 except.py 

import os
import ctypes
from time import sleep
from random import randint


class TimeOut(Exception):
  pass


class Alarm(Exception):
  pass

import threading

class Xthread(threading.Thread):


  def start(self):
self.__original_run = self.run
self.run = self.__run 
threading.Thread.start(self)


  def __run(self):
self.__thrd_id = threading._get_ident()
try:
  self.__original_run()
finally:
  self.run = self.__original_run


  def raize(self, excpt):

Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, 
ctypes.py_object(excpt))
while Nr > 1:
  ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, None)
  sleep(0.1)
  Nr = ctypes.pythonapi.PyThreadState_SetAsyncExc(self.__thrd_id, 
ctypes.py_object(excpt))

  def alarm(self, tm):

alrm = threading.Timer(tm, self.raize, (TimeOut,))
alrm.start()
return alrm

class Continue(Xthread):

  def run(self):

self.id = os.getpid()
print self.id, "Begin"
i = 0
try:
  for _ in xrange(randint(0,20)):
for e in xrange(4 * 10):
i = i + e
  print self.id, "Finished"
except Alarm:
  print self.id, "Interupted"


lst = [Continue() for _ in xrange(10)]

for T in lst:
  T.start()

try:
  sleep(15)
finally:
  for T in lst:
T.raize(Alarm)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subtyping a builtin type in a C extension

2005-10-17 Thread Gerhard Häring
shawn wrote:
> I am trying to make a subtype of a string. Initially it will have no
> new methods or attributes, the C equivalent of:
> 
> class myStr(str):
> pass
> 
> I have experimented a bit, but am currently making a mess of it. Does
> anybody have an example they can point to of inheriting from a builtin,
> or a suggestion to point me in the right direction?

The Python source distribution contains an example module xxsubtype that 
shows how to subclass builtins:

http://cvs.sourceforge.net/viewcvs.py/python/python/dist/src/Modules/xxsubtype.c?rev=2.15.2.1&view=markup

-- Gerhard

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


wxPython advice

2005-10-17 Thread vpr
Hi Guys

I have a question re. socketserver and wx.

I've written a p2p program using socketserver that's nice and quick.
I'd like to give the user a tray applet (part of the p2p service) that
will allow the user to activate / deactivate / config and exit the
service.
However I'm starting to bang my head on the mainloop funtions that
manage
wx and socket events.

Anyone been down this road that can give me some advice

Marinus

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


Re: Comparing lists

2005-10-17 Thread Alex Martelli
Christian Stapfer <[EMAIL PROTECTED]> wrote:

>  This is why we would like to have a way of (roughly)
> estimating the reasonableness of the outlines of a
> program's design in "armchair fashion" - i.e. without
> having to write any code and/or test harness.

And we would also like to consume vast amounts of chocolate, while
similarly reclining in comfortable armchairs, without getting all fat
and flabby.  Unfortunately, what we would like and what reality affords
are often pretty uncorrelated.  No matter how much theoreticians may
love big-O because it's (relatively) easy to compute, it still has two
failings which are often sufficient to rule out its sufficiency for any
"estimate [of] the reasonableness" of anything: [a] as we operate on
finite machines with finite wordsize, we may never be able reach
anywhere even remotely close to the "asymptotic" region where big-O has
some relationship to reality; [b] in many important cases, the
theoretical worst-case is almost impossible to characterize and hardly
ever reached in real life, so big-O is of no earthly use (and much
harder to compute measures such as big-Theta should be used for just
about any practical purpose).

Consider, for example, point [b].  Quicksort's big-O is N squared,
suggesting that quicksort's no better than bubblesort or the like.  But
such a characterization is absurd.  A very naive Quicksort, picking its
pivot very systematically (e.g., always the first item), may hit its
worst case just as systematically and in cases of practical importance
(e.g., already-sorted data); but it takes just a little extra care (in
the pivot picking and a few side issues) to make the worst-case
occurrences into ones that will not occur in practice except when the
input data has been deliberately designed to damage by a clever and
determined adversary.

Designing based on worst-case occurrences hardly ever makes sense in any
field of engineering, and blind adherence to worst-case assessments can
be an unmitigated disaster, promoting inferior technology just because,
in the WORST imaginable case, the best available technology would fare
no better than the inferior one (even though in 99.9% of cases the
best technology would perform better, if you're designing based on
worst-case analyses you may not even NOTICE that -- and NEVER, *NEVER*
forget that big-O is nothing BUT "extreme-worst-case" analysis!).  Why
bother using prestressed concrete, when, should a large asteroid score a
direct hit, the costly concrete will stand up no better than cheap
bricks, or, for that matter, slightly-damp straw?  Why bother doing
(e.g.) random pivot selection in quicksort, when its big-O (i.e.,
worst-case) behavior will remain N-squared, just like naive quicksort,
or, for that matter, bubblesort?


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


Re: Queue question

2005-10-17 Thread Alex Martelli
Steve M <[EMAIL PROTECTED]> wrote:

> According to my "Python in a Nutshell":
> 
> q.get(block=True)
> 
> is the signature, so, as you use it above, the call will hang until
> something is on the queue. If block is false and the queue is empty,
> q.get() will raise the exception Empty.
> 
> q.get_nowait is apparently synonymous with q.get(block=False)

Yep.  Nowadays you can also have an optional timeout= argument to the
.get method, to obtain the Empty exception only after the get attempt
has waited for some time for some item to arrive.


> q.not_empty, if it existed, I expect would be true just in case there
> was at least one item in the queue. But according to my book there is
> q.empty and q.full, which is true when the queue has the maximum
> allowed number of items (a value specified when the queue is created).

not_empty and not_full are not methods but rather instances of the
threading.Condition class, which gets waited on and notified
appropriately.  I'm not entirely sure exactly WHAT one is supposed to do
with the Condition instances in question (I'm sure there is some design
intent there, because their names indicate they're public); presumably,
like for the Lock instance named 'mutex', they can be used in subclasses
that do particularly fiendish things... but I keep planning not to cover
them in the 2nd edition of the Nutshell (though there I _will_ cover the
idea of subclassing Queue to implement queueing disciplines other than
FIFO without needing to worry about synchronization, which I had skipped
in the 1st edition).

 
> Also, I don't think you can rely on q.empty in the way you may expect.
> For example, another thread can empty the queue between the time you
> test whether q.empty is false and the time you call q.get.

Absolutely true.  "Anything can happen" right after you call q.empty(),
so the existence of that method isn't a good idea (it's somewhat of an
"attractive nuisance" -- its existence prompts some programmers who
don't read docs to try and use it, possibly producing unreliable code
which works when tested but silently breaks in real-life use).


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


Re: Problems with properties

2005-10-17 Thread Alex Martelli
Michael Schneider <[EMAIL PROTECTED]> wrote:

> Thanks to all,  I added the object as a subclass (should this be 
> required for 2.4.1 ???)

It _IS_ required, because Python these days moves *very slowly indeed*
before changing semantics of existing code in any way that is not
backwards compatible -- we just don't want to break good working code,
and there are many millions of lines' worth of such Python code in use
around the world.  The newstyle object model cannot have identical
semantics to the legacy (AKA "classic") one, so it can't become the
default without LOTS AND LOTS of years spent with the old-style mode
being discouraged and deprecated... but STILL the default.

As usual, "should" is a harder question to answer -- one might
reasonably say that maintainers of legacy code have had PLENTY of
warning time by now, and newstyle OM "should" become the default by,
say, 2.6, rather than waiting for 3.0.  But, that's not an easy issue to
call!


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


Re: Question on class member in python

2005-10-17 Thread Peter Otten
Johnny Lee wrote:

> Class A:
>def __init__(self):
>   self.member = 1
> 
>def getMember(self):
>   return self.member
> 
> a = A()
> 
> So, is there any difference between a.member and a.getMember? thanks
> for your help. :)

Yes. accessor methods for simple attributes are a Javaism that should be
avoided in Python. You can always turn an attribute into a property if the
need arises to do some calculations behind the scene

>>> class A(object):
... def getMember(self):
... return self.a * self.b
... member = property(getMember)
... def __init__(self):
... self.a = self.b = 42
...
>>> A().member
1764

I. e. you are not trapped once you expose a simple attribute.

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


Re: Question on class member in python

2005-10-17 Thread Tau
Get answer by typing:
id(a.member)==id(a.getMember())

You will often find id() useful when in doubt whether the two objects
are distinct.

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


[PIL]: Question On Changing Colour

2005-10-17 Thread Andrea Gavana



Hello Terry,
 
> new_hue   # your 'basic color', 
just the hue part> rgb_base  # color from the basic button 
image> rgb_new   # the new color you want to replace rgb_base 
with> > rgb_new = hsv_to_rgb( (new_hue,) + 
rgb_to_hsv(rgb_base)[1:])
    thanks a lot for your 
suggestion! However, either I did not understand it correctly or I am doing 
something stupid in my code. Here is a small example:
 
from colorsys import *
 
# that is the old colour --> GREYrgb_old = 
(0.7, 0.7, 0.7)
 
# Transform the new colour in HSVhsv_old = 
rgb_to_hsv(rgb_old[0], rgb_old[1], rgb_old[2])
 
# this is the new colour --> BLUErgb_new = 
(0.0, 0.0, 1.0)
 
# Transform the new colour in HSVhsv_new = 
rgb_to_hsv(rgb_new[0], rgb_new[1], rgb_new[2])
 
# I take only the Hue part of the new 
colournew_hue = hsv_new[0]
 
# Get the new colourrgb_new = 
hsv_to_rgb(new_hue, hsv_old[1], hsv_old[2])
 
print rgb_oldprint rgb_newprint rgb_old 
== rgb_new
 
This prints:
 
(0.69996, 0.69996, 
0.69996)(0.69996, 0.69996, 
0.69996)True
 
So, no matter what colour I choose as a "new" 
colour, the Hue part of the new colour doesn't change in RGB. In other words, 
leaving the old value for "Saturation" and "Value" makes the presence of the 
"Hue" part useless. But why in the world does this happen? If a colour is 
defined by 3 values, changes in every single value should change the 
colour too... 
Ah, thanks God for the existence of RGB 
;-)
 
Thanks a lot for every suggestion.
 
Andrea.
 
"Imagination Is The Only Weapon In The War 
Against Reality."http://xoomer.virgilio.it/infinity77
-- 
http://mail.python.org/mailman/listinfo/python-list

setup.py dll linking

2005-10-17 Thread brussel13
Hi,
I'd like to link a dll/pyd against another which was
compiled by a distutils script and mingw32, winxp obviously.
there aren't any symbols in the symbol table of the
first pyd.  i removed the -s which distutils sends to mingw32
but that only made symbols appear with nm.  pexports still
reports only __init__.  mingw still complains that the functions
in the first dll can't be found when compiling the second.


ross




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


Python Programmer Urgently Required

2005-10-17 Thread dashkedar123
Job Description:

The position holder will supplement the existing pool of application
development and programming pool of OWSA technical team. In particular
S/he will be responsible for developing Python based overlay
application – to be mounted on existing software tools and solutions.
The position will report to Team Manager, Training & Technical Services.

Required Skills:

* A degree in Computer Application, Engineering or another
numerate subject
* 1+ years experience of web application development in Python or PHP
* Good understanding of MySQL, PostGreSQL or another RDBMS platform.
* Aptitude and experience of technical writing and process
documentation
* Good oral and written communication abilities; and ability to
work in multi-disciplinary team


To apply for any of these above positions, please send your latest
resume along with details of your current role and how do your propose
to contribute in this position. Women candidates with the requisite
skills & qualifications are especially encouraged to apply. OneWorld
South Asia is an equal opportunity employer.

Applications along with a one page write up explaining the suitability
to the job may be sent (preferably through email) to:


Kedar Dash
Team Leader, Web Development
OneWorld South Asia,
C-5 Qutab Institutional Area
New Delhi – 110016
Tel: 91 11 51689001 Ext 108
Fax: 91 11 51689001

Email : [EMAIL PROTECTED]



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


Re: Send password over TCP connection

2005-10-17 Thread dcrespo
I think you said the same as me:
Client:
Password = "password"
h = Hash(Password)
h is "GddTHww90lze7vnmxG" (whatever)

Sends h over the network to the server.

h is a string, so this approach is simply vulnerable.

SRP seems to be very good, but because I don't know it well, I think
I'll delay it for a while.

Thank you

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


Expression templates for arithmetic operations in python

2005-10-17 Thread David Welch
Hi,

I am new to python so I thought I would write a quick and simple 
vector/matrix multiplication class in c++ and use it in python.

Is it possible to overload the operators in python such a way that a 
tree of calculations is built which I can then pass to an evaluator 
written in c++ to calculate the tree with max efficiency.

My thought train is that the args are passed to c++ only once and so 
there is less overhead in unpacking them.

Is there are an existing implementation in python which does this?

What is the best way to implement this?

Thanks for your help.

David

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


Stripping ASCII codes when parsing

2005-10-17 Thread David Pratt
I am working with a text format that advises to strip any ascii control 
characters (0 - 30) as part of parsing data and also the ascii pipe 
character (124) from the data. I think many of these characters are 
from a different time. Since I have never seen most of these characters 
in text I am not sure how these first 30 control characters are all 
represented (other than say tab (\t), newline(\n), line return(\r) ) so 
what should I do to remove these characters if they are ever 
encountered. Many thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-17 Thread Jim Benson

(sorry for the top post...but given the subject
line (OP), hopefully I won't offend more than one)

...and just when I was beginning to think that 
Mr. Xah Lee was a changed man and had dropped his
compulsion to use profanity to express his thoughts.
I didn't actually do a grep on his last several 
posts, so I may have been mistaken prior to his most
recent post. RFC actually stands for "request for comments".
...gee what a nice idea. I did not read past his
definition of RFC.

Oh well,

Sorry for breaking the rule "don't feed the troll".
Enough said.

Jim

On 14 Oct 2005, Xah Lee wrote:

> Microsoft Hatred, FAQ
> 
> Xah Lee, 20020518
> 
> Question: U.S. Judges are not morons, and quite a few others are
> not morons. They find MS guilty, so it must be true.
> 
> Answer: so did the German population thought Jews are morons by
> heritage, to the point that Jews should be exterminated from earth.
> Apparently, the entire German population cannot be morons, they must be
> right.
> 
> Judge for yourself, is a principle i abide by. And when you judge, it
> is better to put some effort into it.
> 
> How much you invest in this endearvor depends on how important the
> issue is to you. If you are like most people, for which the issue of
> Microsoft have remote effect on your personal well-being, then you can
> go out and buy a case of beer on one hand and pizza on the other, and
> rap with your online confabulation buddies about how evil is MS. If you
> are an author writing a book on this, then obviously its different
> because your reputation and ultimately daily bread depend on what you
> put down. If you are a MS competitor such as Apple or Sun, then
> obviously you will see to it with as much money as you can cough out
> that MS is guilty by all measures and gets put out of business. If you
> are a government employee such as a judge, of course it is your
> interest to please your boss, with your best accessment of the air.
> 
> When i judge things, i like to imagine things being serious, as if my
> wife is a wager, my daughter is at stake, that any small factual error
> or mis-judgement or misleading perspective will cause unimaginable
> things to happen. Then, my opinions becomes better ones.
> 
> Q: Microsoft's Operating System is used over 90% of PCs. If that's
> not monopoly, i don't know what is.
> 
> A: Now suppose there is a very ethical company E, whose products have
> the best performance/price ratio, and making all the competitors
> looking so majorly stupid and ultimately won over 90% of the market as
> decided by consumers. Is E now a monopoly? Apparently, beer drinkers
> and pizza eaters needs to study a bit on the word monopoly, from the
> perspectives of language to history to law. If they have some extra
> time, they can sharpen views from philosophy & logic contexts as well.
> 
> Q: What about all the people in the corporate environments who are
> forced to use MS products and aren't allowed the option/choice to use
> Mac/Linux/UNIX?
> 
> A: Kick your boss's ass, or, choose to work for a company who have
> decisions that you liked.
> 
> Q: What about MS buying out all competitors?
> 
> A: Microsoft offered me $1 grand for saying good things about them.
> They didn't put a gunpoint on my head. I CHOOSE to take the bribe.
> Likewise, sold companies can and have decided what's best for them.
> It's nothing like under gunpoint.
> 
> Q: Microsoft forced computer makers to not install competitor's
> applications or OSes.
> 
> A: It is free country. Don't like MS this or that? Fuck MS and talk to
> the Solaris or BeOS or AIX or HP-UX or Apple or OS/2 or Amiga or NeXT
> or the Linuxes with their free yet fantastically easy-to-use and
> network-spamming X-Windows. Bad business prospects? Then grab the
> opportunity and become an entrepreneur and market your own beats-all
> OS. Too difficult? Let's sue Microsoft!
> 
> Q: Microsoft distributed their Internet Explorer web browser free,
> using their “monopoly” power to put Netscape out of business.
> 
> A: entirely inane coding monkeys listen: It takes huge investment to
> give away a quality software free. Netscape can give away Operating
> Systems free to put MS out of business too. Nobody is stopping Sun
> Microsystem from giving Java free, or BeOS a browser free, or Apple to
> bundle QuickTime deeply with their OS free.
> 
> Not to mention that Netscape is worse than IE in just about every
> version till they become the OpenSource mozilla shit and eventually
> bought out by AOL and still shit.
> 
> • Netscape struggles, announced open browser source code in 1998-01,
> industry shock
> http://wp.netscape.com/newsref/pr/newsrelease558.html
> 
> • Netscape browser code released in 1998-03. Mozilla FAQ.
> http://mozilla.org/docs/mozilla-faq.html
> 
> • AOL buys Netscape in 1998-11 for 4.2 billion.
> http://news.com.com/2100-1023-218360.html?legacy=cnet
> 
> • Jamie Zawinski, resignation and postmortem, 1999-04
> http:

Name Lookups

2005-10-17 Thread zhu_dave
Hello All,

I would like to gather some information on Python's performance. As far as I 
understand, it 
deals with a lot of string objects. It looks up all names. 
- Is there a way to find out how many name look up operations take place in a 
Python 
program?
- Is it the name lookup operation or hash operation that degrades performance?
- What function does Python use for name lookup operations? Is it the lookdict 
function in
Objects/dictobject.c?

Thank you for your help!



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


OT: On Microsoft monopolies, was MS FAQ

2005-10-17 Thread Adriaan Renting
>>>"Jeroen Wenting" <"jwenting athornetdotdemondotnl"@bag.python.org> 10/16/05 
>>>11:49 am >>> 
% 
%"Peter T. Breuer" <[EMAIL PROTECTED]> wrote in message 
%news:[EMAIL PROTECTED] 
%>In comp.os.linux.misc Jeroen Wenting  
%>wrote: 
%>>Without Microsoft 90% of us would never have seen a computer more 
%>>powerful 
%>>than a ZX-81 and 90% of the rest of us would never have used only dumb 
%>>mainframe terminals. 
%> 
%>Uh - when microsoft produced dos 1.0, or whatever it was, I was sitting 
%>at my Sun 360 workstation (with 4M of RAM, later upgraded to 8M), 
%>running SunOS 3.8 or thereabouts. 
%> 
%And how many people who now have $500 PCs ($200 of which is the cost of the 
%OS) would have been able to afford those? 
% 
%My point is that Microsoft made computers that were more than glorified 
%gaming consoles affordable for the common man. 
%They are the ones who lowered the price of shrinkwrapped software for home 
%and office application from thousands or tens of thousands to hundreds of 
%dollars. 
% 
% 

Microsoft never made any computers (before Xbox that is) and never had any 
control over the hardware price. The prices of hardware have very little to do 
with the software they run, but mostly with developements in IC manufacturing 
techniques.

As for prices on software, they went down because the market expanded, because 
of cheaper hardware.

The only real technological advantage MS had over a lot of it's competitors, is 
that it tried to have it's OS run on as much hardware as possible. Not being 
tied to a single hardware vendor is what made MS big. IBM's choice not to 
create their own OS, and use of the shelve parts, has enabled all the clone 
builders (most notably Compaq) to enter the PC-compatible market easily.

I think commercial software in general is a market that tends towards creating 
monopolies, because of the network effect. MS played the right tactics to 
become the OS monopoly. It has since been using all kinds of shady, sometimes 
illegal tactics to maintain this monopoly, and leverage it to gain others.

The Car+engine analogy is flawed, another analogy could be if sandwiches were 
only sold with Heinz products, you could choose betweeen peanut butter, 
strawberry jam or sandwichspread, but if you wanted Calve peanut butter, you 
would still need to pay for a jar of Heinz peanut butter too.


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


OT: OS monopolies, was MS FAQ

2005-10-17 Thread Adriaan Renting
>>>John Bokma <[EMAIL PROTECTED]> 10/17/05 5:27 am >>> 
#Roel Schroeven <[EMAIL PROTECTED]> wrote: 
# 
#> 
#>Maybe they can force it, maybe not, but that's not the point (again). 
#>The point is what their intentions are, and that is trying to lock 
#>people into using their software. 
# 
#Can you name big companies that don't do this? 
# 

I know that some companies, for example Adobe with PDF and postscript, have 
been much nicer in having other software interoperate/compete with them. I 
think it's why MS is currently targetting them (Metro, Digital Image).

Don't be to surprised if Acrobat, Illustrator or Photoshop has trouble running 
on Vista.

I do agree that most companies would probably try some of the same tactics, but 
that's why it's illegal to abuse monopoly power. Some of MS faults are inherent 
to how the software market works, for example that it's pace is much higher as 
what the justice system can keep up with.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Stripping ASCII codes when parsing

2005-10-17 Thread Steve Holden
David Pratt wrote:
> I am working with a text format that advises to strip any ascii control 
> characters (0 - 30) as part of parsing data and also the ascii pipe 
> character (124) from the data. I think many of these characters are 
> from a different time. Since I have never seen most of these characters 
> in text I am not sure how these first 30 control characters are all 
> represented (other than say tab (\t), newline(\n), line return(\r) ) so 
> what should I do to remove these characters if they are ever 
> encountered. Many thanks.

You will find the ord() function useful: control characters all have 
ord(c) < 32.

You can also use the chr() function to return a character whose ord() is 
a specific value, and you can use hex escapes to include arbitrary 
control characters in string literals:

   myString = "\x00\x01\x02"

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


[newbie]Is there a module for print object in a readable format?

2005-10-17 Thread James Gan
I want the object printed in a readable format. For example,
x =[a, b, c, [d e]] will be printed as:
x--a
  |_b
  |_c
  |___d
|_e

I tried pickled, marshel. They do different work. Is there another 
module which do this kind of job?

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


Re: [newbie]Is there a module for print object in a readable format?

2005-10-17 Thread bruno modulix
James Gan wrote:
> I want the object printed in a readable format. For example,
> x =[a, b, c, [d e]] will be printed as:
> x--a
>  |_b
>  |_c
>  |___d
>|_e
> 
> I tried pickled, marshel. They do different work. 
>
> Is there another
> module which do this kind of job?
> 

pprint

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


ANN: MathDOM 0.5.2 - MathML in Python - now featuring lxml API!

2005-10-17 Thread Stefan Behnel
Hi everyone,

MathDOM 0.5.2 is ready for download from SourceForge.

http://mathdom.sourceforge.net/

MathDOM is a set of Python modules (using pyparsing and either PyXML or lxml)
that import mathematical terms as a Content MathML DOM. It currently parses
MathML and literal infix terms into a DOM and writes out MathML and literal
infix, prefix, postfix or Python terms. The DOM elements are enhanced by
domain specific methods that make using the DOM a little easier.

You can call it the shortest way between different term representations and an
enhanced Content MathML DOM. Ever noticed the annoying differences between
terms in different programming languages? Build your application around the
DOM and stop caring about the term representation that users prefer or that
your machine can execute. If you need a different representation, add a
converter, but don't change the model. Literal terms are connected through an
intermediate AST step that makes writing converters for
Python/SQL/yourfavorite easier.

** New in 0.5.2 **

This release features the original 4DOM based API as well as a completely new
API based on a patched version of lxml. lxml is an ElementTree like API on top
of libxml2, which combines fast XPath, XSLT, XInclude, etc. computation with
the ease of a pythonesque API. Try it, it's worth making the change.

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


Re: [newbie]Is there a module for print object in a readable format?

2005-10-17 Thread enrico . sirola_NOSPAM
> "James" == James Gan <[EMAIL PROTECTED]> writes:

James> I want the object printed in a readable format. For

[...]

James> I tried pickled, marshel. They do different work. Is there
James> another module which do this kind of job?

from pprint import pprint
pprint(object)

bye,
e.

-- 
Enrico Sirola <[EMAIL PROTECTED]>

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


Re: Question on class member in python

2005-10-17 Thread bruno modulix
Johnny Lee wrote:
> Class A:

s/C/c/

>def __init__(self):
>   self.member = 1
> 
>def getMember(self):
>   return self.member
> 
> a = A()
> 
> So, is there any difference between a.member and a.getMember? 

yes : a.member is an integer, a.getMember is a bound method. You could
have found this by yourself...

Note that the getter/setter plague is useless and unpythonic. Use
properties instead if you need to control attributes access. There are
decorator idioms to make clean and easy properties, look here:
http://wiki.python.org/moin/PythonDecoratorLibrary


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


Any 3state Check Tree Ctrl for wxPython available?

2005-10-17 Thread Petr Prikryl
Hi,

I am experimenting with wxPython on Windows box. 
What I need to implement is a check tree control
with 3 states for each checkbox: unchecked, checked,
gray checked. The status of the checkbox should reflect
the status of the children. When ALL children are checked,
then the status should be checked. When NO children
are checked, the status should be unchecked. When 
SOME children are selected, the status should be
checked with gray background.

I have found something else that could be valuable
after I start understand that:

http://mitglied.lycos.de/drpython/CheckTreeCtrl.tar 

Anyway, is there something similar with 3 states
available around?

Thanks for your time and experience,

pepr

-- 
Petr Prikryl (prikrylp at skil dot cz) 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Outdated documentation

2005-10-17 Thread Kent Johnson
Laszlo Zsolt Nagy wrote:
> Is this the good place to post?

Follow the "About this document" link at the bottom of any page of Python docs 
for information about submitting change requests.

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


Re: UI toolkits for Python

2005-10-17 Thread Wolfgang Keller
> With OS X compatibility you tend to come across with the
> fact that many "OS X compatible" things are actually X11
> things. X11 certainly looks different from Aqua (the native
> interface). 

But imho, Gnome _does_ "look and feel" quite Mac-ish in the sense that 
its ergonomics has certain things in common with the Mac, even more 
with the old MacOS classic than with the pretty "gadget-ish" Aqua 
interface.

For example, with its hierarchical multi-column listview, Nautilus 
"looks" and "feels" perfectly like the old MacOS classic Finder, 
something that lots of long-time Mac users miss a lot on MacOS X.

Another example is MDI (or "windows inside windows"), which is a no-no 
on the Mac (and afaik not supported by GTK), or multi-pains (sic!). As 
a long-time Mac user (since system 6.0.x), I did like a lot the GUI of 
WingIDE (which uses GTK) because it allows me to switch from a 
multi-pain layout to a multi-window layout.

> GTK is an example of this. There is an Aqua version of
> GTK, but it seems to be rather outdated.

There's a new effort for a "aqua-native" implementation:

http://micke.hallendal.net/archives/2005/10/gtk-macosx.html

> The newer versions
> run on X11 but installing them may be just laborious or
> then plain pain depending on your luck. And you still need
> the X11 installed.

One advantage of an X11 application is, obviously, the possibility to 
use it from a different computer without the requirement to install it 
there.

"Hey, my Mac can do that for free, while your Windows needs an 
expensive "Server" license.!" >;-> Shhh, don't tell them about 
Cygwin...

> So, if you are looking for something that looks like Mac
> and works like Mac, do not touch anything with X11. 

As a long-time Mac user, I somewhat disagree, see above. :-)

To me, a GTK application with a really well-thought ergonomic user 
interface is a lot more Mac-ish than a pile of "aqua-native" visual 
gadgetry.

Sincerely,

Wolfgang Keller


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


Re: array subset could be improved? -repost ;)

2005-10-17 Thread Jim O'D

> With the new numeric, you'll be able to do:
> 
> negatives = a[a<0]
> 
> Cheers,
> 
> f
> 

Ooh, that's nice.

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


xmlrpclib: how to marshal special instances

2005-10-17 Thread Willi Langenberger
Hi!


We have an application server (Zope) and make heavy use of
xml-rpc. One problem arised, when we tried to return a zope.DateTime
instance. xmlrpclib (naturally) knows nothing about zope.DateTime and 
marshalls it as instance, which gives a structure (of zope.DateTime
attributes) on the client side (which isnt very usable).

It seems we have two possibilities:

1) Convert all zope.DateTime instances to xmlrpclib.DateTime instances
   in our appserver program. (This would be a burden for every
   appserver programmer.)

2) Tell xmlrpclib how to marshal zope.DateTime instances as
   xmlrpclib.DateTime objects.

We are in favour of 2, and would like to patch Zope, so that
zope.DateTime objects automatically recieve as xmlrpc date types on
the client side.

Schematically:

  import xmlrpclib

  # zope.DateTime must have an "encode" method
  xmlrpclib.WRAPPERS = xmlrpclib.WRAPPERS + (zope.DateTime,)

However, we do not know, if the WRAPPERS tuple is an "official" API,
and if we should use it that way. (We'd like to know before we try to
get a patch into the Zope core...)

Or, are there other (better!) ways to solve the problem (marshal
zope.DateTime as xml-rpc date without modifying xmlrpclib)?


Thanks!


\wlang{}

-- 
[EMAIL PROTECTED]Fax: +43/1/31336/9207
Zentrum fuer Informatikdienste, Wirtschaftsuniversitaet Wien, Austria
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to get a raised exception from other thread

2005-10-17 Thread Antoon Pardon
Op 2005-10-17, Alex Martelli schreef <[EMAIL PROTECTED]>:
><[EMAIL PROTECTED]> wrote:
>
>> Nevermind.  I found a better solution.  I used shared memory to create
>> a keep-alive flag.  I then use the select function with a specified
>> timeout, and recheck the keep-alive flag after each timeout.
>
> Definitely a better architecture.  Anyway, one supported way for a
> thread to raise an exception in a different thread is function
> thread.interrupt_main(), which raises a KeyboardInterrupt in the *main*
> thread (the one thread that's running at the beginning of your program).
>
> There's also a supported, documented function to raise any given
> exception in any existing thread, but it's deliberately NOT directly
> exposed to Python code -- you need a few lines of  C-coded extension (or
> pyrex, ctypes, etc, etc) to get at the functionality.  This small but
> non-null amount of "attrition" was deliberately put there to avoid
> casual overuse of a facility intended only to help in very peculiar
> cases (essentially in debuggers &c, where the thread's code may be buggy
> and fail to check a keep-alive flag correctly...!-).

I find this rather arrogant. It is not up to the developers of python
to decide how the users of python will use the language. If someone
has use of specific functionality he shouldn't be stopped because his
use is outside the intentions of the developers.

Just suppose you are writing a chess program. You let the program
"think" while it is the users move, but this thinking has to be
interrupted and some cleanup has to be made after the users move
has made a lot of this thinking obsolete by his move. Such code
could be mixture of loops and recursion that makes use of a simple
flag to end it all, unpractical. Use of an exception raised from
somewhere else would IMO in this case be an acceptable choice.

Why should the coder of this software have to go through this
deliberate set up attrition, to get at this functionality, just
because it wasn't intented to be used in such a way by the
developers?

As far as I know, pyrex and ctypes weren't intended to get
at the Python/C api. But they didn't create extra hurdles
for those who could use it that way.

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


generic xmerge ?

2005-10-17 Thread [EMAIL PROTECTED]
Hi,

I was reading this recipe and am wondering if there is a generic
version of it floating around ? My list is a tuple (date, v1, v2, v3)
and I would like it to sort on date. The documentation doesn't mention
how the items are compared and the example only use integers.

http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/141934

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


Re: How to get a raised exception from other thread

2005-10-17 Thread Steve Holden
Antoon Pardon wrote:
> Op 2005-10-17, Alex Martelli schreef <[EMAIL PROTECTED]>:
> 
>><[EMAIL PROTECTED]> wrote:
>>
>>
>>>Nevermind.  I found a better solution.  I used shared memory to create
>>>a keep-alive flag.  I then use the select function with a specified
>>>timeout, and recheck the keep-alive flag after each timeout.
>>
>>Definitely a better architecture.  Anyway, one supported way for a
>>thread to raise an exception in a different thread is function
>>thread.interrupt_main(), which raises a KeyboardInterrupt in the *main*
>>thread (the one thread that's running at the beginning of your program).
>>
>>There's also a supported, documented function to raise any given
>>exception in any existing thread, but it's deliberately NOT directly
>>exposed to Python code -- you need a few lines of  C-coded extension (or
>>pyrex, ctypes, etc, etc) to get at the functionality.  This small but
>>non-null amount of "attrition" was deliberately put there to avoid
>>casual overuse of a facility intended only to help in very peculiar
>>cases (essentially in debuggers &c, where the thread's code may be buggy
>>and fail to check a keep-alive flag correctly...!-).
> 
> 
> I find this rather arrogant. It is not up to the developers of python
> to decide how the users of python will use the language. If someone
> has use of specific functionality he shouldn't be stopped because his
> use is outside the intentions of the developers.
> 
The developers have to support (at no cost) what the users do, so if 
they want to make use of certain features inaccessible to users who are 
likely to go wrong then that's up to them.

> Just suppose you are writing a chess program. You let the program
> "think" while it is the users move, but this thinking has to be
> interrupted and some cleanup has to be made after the users move
> has made a lot of this thinking obsolete by his move. Such code
> could be mixture of loops and recursion that makes use of a simple
> flag to end it all, unpractical. Use of an exception raised from
> somewhere else would IMO in this case be an acceptable choice.
> 
In *your* opinion, possibly. In my opinion it would seem to make more 
sense to have the worker thread code examine a shared flag and raise an 
exception at some convenient point in its calculation cycle. Otherwise 
you have to write the worker thread to be capable of handling 
asynchronous signals, which is a notoriously difficult task. I presume 
this is why Alex commented that he thought the OP's "better solution" 
was "definitely a better architecture."

> Why should the coder of this software have to go through this
> deliberate set up attrition, to get at this functionality, just
> because it wasn't intented to be used in such a way by the
> developers?
> 
Because otherwise people who know no better will use the feature for 
purposes where it's not the best way to achieve the required 
functionality, leading to yet more endless discussions about why "it 
doesn't work". Asynchronous signalling between threads is an accident 
waiting to happen in the hands of an inexperienced programmer.

> As far as I know, pyrex and ctypes weren't intended to get
> at the Python/C api. But they didn't create extra hurdles
> for those who could use it that way.
> 
This seems like a complete non sequitur to me. Let's stick to the point.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: generic xmerge ?

2005-10-17 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> Hi,
> 
> I was reading this recipe and am wondering if there is a generic
> version of it floating around ? My list is a tuple (date, v1, v2, v3)
> and I would like it to sort on date. The documentation doesn't mention
> how the items are compared and the example only use integers.
> 
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/141934

I'm not sure what "my list is a tuple" mean (list and tuple being
different types) nor what this has to do with the recipe.  Anyway...
sequences are compared lexicographically -- first items first, then
second items if the first items are equal, and so on.  So, if you have a
list X whose items tuples and want X sorted on the tuples' first items,
X.sort() will suffice -- if the tuples never have equal first-items, or
if you're OK with second-items getting compared when the first-items are
equal.  If you want to sort on first-items ONLY, leaving the tuples in
the same order in the list when their first-items are equal:

import operator
X.sort(key=operator.itemgetter(0))


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


Re: How to get a raised exception from other thread

2005-10-17 Thread Paul Rubin
Steve Holden <[EMAIL PROTECTED]> writes:
> Otherwise you have to write the worker thread to be capable of
> handling asynchronous signals, which is a notoriously difficult task.

Doing it properly needs a language extension.

http://www.cs.williams.edu/~freund/papers/02-lwl2.ps
-- 
http://mail.python.org/mailman/listinfo/python-list


Run process with timeout

2005-10-17 Thread Natan
Hi.

I have a python script under linux where I poll many hundreds of
interfaces with mrtg every 5 minutes. Today I create some threads and
use os.system(command) to run the process, but some of them just hang.
I would like to terminate the process after 15 seconds if it doesn't
finish, but os.system() doesn't have any timeout parameter.

Can anyone help me on what can I use to do this?

Thank you

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


Re: generic xmerge ?

2005-10-17 Thread [EMAIL PROTECTED]
oops, sorry. I meant

l1=[(date,v1,v2,v3), ...]
l2=[ another set of tuples ]


Thanks. so I have to concat the multiple lists first(all of them are
sorted already) ?

Alex Martelli wrote:
> I'm not sure what "my list is a tuple" mean (list and tuple being
> different types) nor what this has to do with the recipe.  Anyway...
> sequences are compared lexicographically -- first items first, then
> second items if the first items are equal, and so on.  So, if you have a
> list X whose items tuples and want X sorted on the tuples' first items,
> X.sort() will suffice -- if the tuples never have equal first-items, or
> if you're OK with second-items getting compared when the first-items are
> equal.  If you want to sort on first-items ONLY, leaving the tuples in
> the same order in the list when their first-items are equal:
> 
> import operator
> X.sort(key=operator.itemgetter(0))
> 
> 
> Alex

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


Re: Microsoft Hatred FAQ

2005-10-17 Thread Roel Schroeven
John Bokma wrote:
> Roel Schroeven <[EMAIL PROTECTED]> wrote:
>>But that's not the point; the point is that they have the choice. 
>>If MS had it its way, they wouldn't have that choice.
> 
> 
> I doubt that. But even if you're right, do you really think that MS is 
> the only evil company on earth working like this? Do you really think 
> that companies like Disney, Sony, Intel, AMD, Apple, etc work any 
> different?

No, I do not think that MS is the only company that uses shady tactics.
Also I didn't use the word 'evil', since I think it is too strong for
what even MS does. But the fact is that MS is convicted for abusing its
monopoly position.

- An application works in IE, Firefox, Konqueror, Safari, Lynx,
Links, Opera, ... -> users can use it with any browser on any OS
>>>
>>>I think that we both understand that one browser will be more
>>>compatible then an other. It will only happen if all use exactly the
>>>same render engine, or all web recommendations are frozen.
>>
>>Thousands and thousands of website work perfectly in all of the
>>aforementioned websites right now.
> 
> 
> Maybe you define perfectly different then me, but have a look at the 
> Acid tests for example. Even between minor versions of for example 
> Firefox, or Opera there are differences in rendering. I won't call that 
> perfectly, but maybe because I am a programmer.

Differences in rendering are perfectly acceptable on the World Wide Web.
 That's one point where web graphics differ from graphics in press.

>>>Look at processors: which one would you buy at the moment? AMD?
>>>Intel? and if you pick a brand, which type?
>>
>>Depends on my needs, budget and the specs and price of the available
>>offers. Plus I always have a small, admittedly perhaps unjustified,
>>preference for the underdog; in the past that was AMD, in the future
>>that may very well be Intel. But I don't see the point of that
>>question.
> 
> 
> Others just pick Intel, because it's Intel. The same is happening for
> MS. People just buy MS, they don't care that it's cheaper (or maybe 
> "cheaper") to install Linux + OpenOffice (for example). MS, so it's 
> good.

Popularity is not the same as quality.

I still fail to see your point. The original issue was the browser wars.
Tim Roberts wondered why Microsoft went through the efforst of
dominating the browser market, even if they don't make any money on IE.
David Schwartz gave the answer: MS did it to prevent the OS from
becoming a commodity, since that would allow users to freely choose
their own OS.

You seem to be saying that that is not their intention, since users will
always prefer Windows as their OS anyhow. Well I don't think so, but
just maybe you're right. But I'm pretty sure MS didn't want to take the
chance, and did what it did for the reason David gave.

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

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


Re: generic xmerge ?

2005-10-17 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> oops, sorry. I meant
> 
> l1=[(date,v1,v2,v3), ...]
> l2=[ another set of tuples ]
> 
> Thanks. so I have to concat the multiple lists first(all of them are
> sorted already) ?

You can do it either way -- simplest, and pretty fast, is to concatenate
them all and sort the result (the sort method is very good at taking
advantage of any sorting that may already be present in some parts of
the list it's sorting), but you can also try a merging approach.  E.g.:


import heapq

def merge_by_heap(*lists):
  sources = [[s.next(), i, s.next]
for i, s in enumerate(map(iter,lists))]
  heapq.heapify(sources)
  while sources:
best_source = sources[0]
yield best_source[0]
try: best_source[0] = best_source[-1]()
except StopIteration: heapq.heappop(sources)
else: heapq.heapreplace(sources, best_source)

Now, L=list(merge_by_heap(l1, l2, l3)) should work, just as well as,
say, L = sorted(l1+l2+l3).  I suspect the second approach may be faster,
as well as simpler, but it's best to _measure_ (use the timeit.py module
from the standard library) if this code is highly speed-critical for
your overall application.


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


Re: can a cut-down Python still be Python?

2005-10-17 Thread Kay Schluehr
The Eternal Squire wrote:

> My main question regarding this is:  even if I am successful, would the
> results be rejected out of hand by y'all as not meeting the Zen of
> Python?

Have you ever asked a Zen master about Zen?

Kay

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


Re: Run process with timeout

2005-10-17 Thread Alex Martelli
Natan <[EMAIL PROTECTED]> wrote:

> Hi.
> 
> I have a python script under linux where I poll many hundreds of
> interfaces with mrtg every 5 minutes. Today I create some threads and
> use os.system(command) to run the process, but some of them just hang.
> I would like to terminate the process after 15 seconds if it doesn't
> finish, but os.system() doesn't have any timeout parameter.
> 
> Can anyone help me on what can I use to do this?

Use the subprocess module.  With a subprocess.Popen object, you can then
sleep a while, check (with .poll()) if it's finished, otherwise kill it
(use its .pid attribute).


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


Re: generic xmerge ?

2005-10-17 Thread [EMAIL PROTECTED]
million thanks. So the default compare funcion of heapq also do it like
sort ?

The size of the list is not very large but has the potential of being
run many times(web apps). So I believe second one should be faster(from
the app perspective) as it goes into the optimized code quickly without
all the overheads in the merge case.

Alex Martelli wrote:
> You can do it either way -- simplest, and pretty fast, is to concatenate
> them all and sort the result (the sort method is very good at taking
> advantage of any sorting that may already be present in some parts of
> the list it's sorting), but you can also try a merging approach.  E.g.:
>
>
> import heapq
>
> def merge_by_heap(*lists):
>   sources = [[s.next(), i, s.next]
> for i, s in enumerate(map(iter,lists))]
>   heapq.heapify(sources)
>   while sources:
> best_source = sources[0]
> yield best_source[0]
> try: best_source[0] = best_source[-1]()
> except StopIteration: heapq.heappop(sources)
> else: heapq.heapreplace(sources, best_source)
>
> Now, L=list(merge_by_heap(l1, l2, l3)) should work, just as well as,
> say, L = sorted(l1+l2+l3).  I suspect the second approach may be faster,
> as well as simpler, but it's best to _measure_ (use the timeit.py module
> from the standard library) if this code is highly speed-critical for
> your overall application.
> 
> 
> Alex

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


Re: Calling an exe from Python?

2005-10-17 Thread Jorgen Grahn
On 16 Oct 2005 15:23:08 -0700, SPE - Stani's Python Editor <[EMAIL PROTECTED]> 
wrote:
> Slightly offtopic, but you can translate any double clicking (*.exe,
> *.pdf, *.html, ...) in the Windows Explorer into:
>
> import os
> os.startfile(fileName)

That would be Windows-specific, though.

But yes, it's that one, or os.system, or one of the os.popen*, or one of the
os.spawn*, or module subprocess mentioned elsewhere in the thread.
-- Depending on exactly what you want to do.

/Jorgen

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


Re: Perl-Python-a-Day: split a file full path

2005-10-17 Thread Dr.Ruud
Xah Lee:

> In Perl, spliting a full path into parts is done like this:

And then follows Perl-code that only works with an optional .html
"extension",
which is similar to the code in the File::Basename description.
http://www.perl.com/doc/manual/html/lib/File/Basename.html


It is best practice to derive and store the normalized (or absolute)
path, because relative paths can get loose so will get loose.


Consider this:

  $myPath = './example/basename.ext';


and this:

  $myPath = './example/filename.1.23.45-beta';


and this:

  $myPath = 'x:.\example\basename.ext';


(some platforms have a wd per device)


-- 
Affijn, Ruud

"Gewoon is een tijger."

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


Re: generic xmerge ?

2005-10-17 Thread Alex Martelli
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> million thanks. So the default compare funcion of heapq also do it like
> sort ?

By defaults, all comparisons in Python occur by the same mechanisms: by
preference, specific comparison operators such as < , <= , and so on
(corresponding to special methods __lt__, __le__, and so on) -- missing
that, the three-way comparison done by built-in function cmp
(corresponding to speial method __cmp__).  For built-in sequences, in
particular (both tuples and lists), the comparisons are lexicographical.

Some (but not all) occasions that imply comparisons let you specify
something else than the default, for example by such mechanisms as the
cmp= optional argument to .sort (which tends to have unpleasant
performance impacts) and the key= optional argument (which tends to have
good performance impact).  heapq does not offer this feature in today's
Python (i.e., 2.4), but I believe it's planned to have it in the future
2.5 release.

But in your case the default comparisons appear to be OK, so you should
have no problem either way.


> The size of the list is not very large but has the potential of being
> run many times(web apps). So I believe second one should be faster(from
> the app perspective) as it goes into the optimized code quickly without
> all the overheads in the merge case.

Yes, the simpler solution may well perform better.  Note that:

L = list(l1)
L.extend(l2)
L.extend(l3)
L.sort()

may perform better than L = sorted(l1+l2+l3) -- if speed matters a lot,
be sure to try (and measure!) both versions.


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


Dynamic generation of doc-strings of dynamically generated classes

2005-10-17 Thread Mikael Olofsson
Hi!

I've asked Google, but have not found any useful information there.

Situation: I have a base class, say

 >>> class base(object):
 ImportantClassAttribute = None

Now, I want to dynamically generate subclasses of base. That's not a 
problem. However, I very much want those subclasses to have individual 
doc-strings. More precicely, I want that important class attribute to be 
reflected in the doc-string. That's the problem. The only way I've 
managed to accomplish that is something like the following.

 >>> ImportantClassAttribute = 7
 >>> docString = 'The case %s.' % (ImportantClassAttribute,)
 >>> exec('''class new(base):
  """%s"""
  pass ''' % (docString,))
 >>> new.ImportantClassAttribute = ImportantClassAttribute
 >>> new.__doc__
'The case 7.'

This works as intended. The subclasses do get the doc-strings I want 
them to have, and I can live with this solution. But: This solution does 
not strike me as especially beautiful or readable. My first naïve 
attempt was instead the following.

 >>> class new(base):
pass

 >>> new.ImportantClassAttribute = 7
 >>> new.__doc__ = ('The case %(ImportantClassAttribute)s.'
   % new.__dict__)

Traceback (most recent call last):
   File "", line 1, in -toplevel-
 new.__doc__ = ('The case %(ImportantClassAttribute)s.'
TypeError: attribute '__doc__' of 'type' objects is not writable

This is readable to me, but apparently not the way to go, since I'm not 
allowed to replace the doc-string like this. I've also tried a number of 
other ways, but they all stumble on similar reasons.

Any ideas? Am I stuck with the clumsy exec-solution, or are there other 
ways to dynamically generate doc-strings of classes?

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


Re: Problems with properties

2005-10-17 Thread bruno modulix
[EMAIL PROTECTED] wrote:
> If you change it to this it works. You should provide a get and a set
> function for a property.

The OP did:
->   command=property(getCommand, setNothing)



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


Re: How to get a raised exception from other thread

2005-10-17 Thread Antoon Pardon
Op 2005-10-17, Steve Holden schreef <[EMAIL PROTECTED]>:
> Antoon Pardon wrote:
>> Op 2005-10-17, Alex Martelli schreef <[EMAIL PROTECTED]>:
>> 
>>><[EMAIL PROTECTED]> wrote:
>>>
>>>
Nevermind.  I found a better solution.  I used shared memory to create
a keep-alive flag.  I then use the select function with a specified
timeout, and recheck the keep-alive flag after each timeout.
>>>
>>>Definitely a better architecture.  Anyway, one supported way for a
>>>thread to raise an exception in a different thread is function
>>>thread.interrupt_main(), which raises a KeyboardInterrupt in the *main*
>>>thread (the one thread that's running at the beginning of your program).
>>>
>>>There's also a supported, documented function to raise any given
>>>exception in any existing thread, but it's deliberately NOT directly
>>>exposed to Python code -- you need a few lines of  C-coded extension (or
>>>pyrex, ctypes, etc, etc) to get at the functionality.  This small but
>>>non-null amount of "attrition" was deliberately put there to avoid
>>>casual overuse of a facility intended only to help in very peculiar
>>>cases (essentially in debuggers &c, where the thread's code may be buggy
>>>and fail to check a keep-alive flag correctly...!-).
>> 
>> 
>> I find this rather arrogant. It is not up to the developers of python
>> to decide how the users of python will use the language. If someone
>> has use of specific functionality he shouldn't be stopped because his
>> use is outside the intentions of the developers.
>> 
> The developers have to support (at no cost) what the users do,

Only in so far that correct programs behave correctly. The developers
are not obligated to correct buggy programs. They have every right to
say that if a programmor can handle certain concepts he should seek
help with that concept elsewhere.

> so if 
> they want to make use of certain features inaccessible to users who are 
> likely to go wrong then that's up to them.

But the way it is made inaccessible has nothing to do with knowing
how to use the feature. That you can dable with C-extententions, pyrex
or ctypes says nothing about your ability to handle threads that
raise exceptions in each other.

>> Just suppose you are writing a chess program. You let the program
>> "think" while it is the users move, but this thinking has to be
>> interrupted and some cleanup has to be made after the users move
>> has made a lot of this thinking obsolete by his move. Such code
>> could be mixture of loops and recursion that makes use of a simple
>> flag to end it all, unpractical. Use of an exception raised from
>> somewhere else would IMO in this case be an acceptable choice.
>> 
> In *your* opinion, possibly. In my opinion it would seem to make more 
> sense to have the worker thread code examine a shared flag and raise an 
> exception at some convenient point in its calculation cycle.

What it there is no such convenient point? What if you have a number
of differnt routines that recursively call each other each with its
own number of nested loops. If you want something that is a bit
responsive you will have to put a check for this flag in any loop.

> Otherwise 
> you have to write the worker thread to be capable of handling 
> asynchronous signals, which is a notoriously difficult task. I presume 
> this is why Alex commented that he thought the OP's "better solution" 
> was "definitely a better architecture."

IMO the flag is the better architecture in this case because python
can't interrupt a tread with an exception while that thread is in
C-code.

>> Why should the coder of this software have to go through this
>> deliberate set up attrition, to get at this functionality, just
>> because it wasn't intented to be used in such a way by the
>> developers?
>> 
> Because otherwise people who know no better will use the feature for 
> purposes where it's not the best way to achieve the required 
> functionality, leading to yet more endless discussions about why "it 
> doesn't work".

Then don't react to those questions. A lot of questions about threads
are already answered as follows: "Don't use threads", "use twised" or
"If you have to use threads, use Queues". IMO there is nothing wrong
with telling people that if they want to use certain features it is
expected they know what thet are doing.

> Asynchronous signalling between threads is an accident 
> waiting to happen in the hands of an inexperienced programmer.

So? Do we want python to be limited to features that can't
cause problems in the hands of an inexperienced programmer?

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


Re: Microsoft Hatred FAQ

2005-10-17 Thread Steven D'Aprano
On Mon, 17 Oct 2005 00:17:03 -0400, Mike Meyer wrote:

> Yup. When NS was the 800 lb gorilla 

When was this? When did Netscape have a monopoly in any market?

Netscape was never the 800 lb gorilla.

> on they acted like MS, 

When did Netscape executives perjure themselves in court?

When did Netscape commit fraud? Astro-turfing? Patent infringement? Theft
of code?

If you really wanted to compare apples with apples (no pun intended), IBM
and Microsoft would be the two to compare. IBM had an effective monopoly
once, and they acted like Microsoft, although even they never had the
gall to just ignore the court's rulings as Microsoft has done, and
continues to do. Twenty years ago, Microsoft were the knights in shining
armour going to save Apple Macintosh from the Big Blue evil empire. But
that was then, this is now, and unlike IBM, Microsoft hasn't yet learnt
about karma.

-- 
Steven.

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


Re: Microsoft Hatred FAQ

2005-10-17 Thread Tim Tyler
In comp.lang.java.programmer Richard Gration <[EMAIL PROTECTED]> wrote or 
quoted:
> On Sun, 16 Oct 2005 11:51:16 +, Tim Tyler wrote:

> > Acorn computers.  Manufacturers of the best computer I ever owned.
> 
> I'm willing to bet that was an Arc ... ? I never used one but everyone
> I've ever talked to who used one said it was fantastic. Myself I was
> pretty impressed with the BBC B ...

I had a BBC B - and then a couple of Archimedies computers.

The BBC computer was cool.  However, the Archimedies had a 32-bit
RISC chip in 1987, was quite affordable, and did rather blow the
socks off its predecessor.
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Microsoft Hatred FAQ

2005-10-17 Thread Tim Tyler
In comp.lang.java.programmer Jeroen Wenting  wrote or quoted:
> "Mike Meyer" <[EMAIL PROTECTED]> wrote in message 
> > "Jeroen Wenting"  writes:

[Microsoft]

> >> no, they got their by clever marketing [snip]
> >
> > What you call "clever marketing" the DOJ calls "monopolistic
> > practices". The courts agreed with the DOJ. Having had several large
> > PC manufacturers refuse to sell me a system without some form of
> > Windows because MS made it impossible for them to compete if they
> > didn't agree to do so, I agree with the courts and the DOJ.
> 
> And were later forced to rescind. [...]

That is inaccurate.
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [newbie]Is there a module for print object in a readable format?

2005-10-17 Thread Steven D'Aprano
On Mon, 17 Oct 2005 17:25:35 +0800, James Gan wrote:

> I want the object printed in a readable format. For example,
> x =[a, b, c, [d e]] will be printed as:
> x--a
>   |_b
>   |_c
>   |___d
> |_e

I think you missed an "un-" in your first sentence.

:-)

In general, if you want special/fancy/bizarre printing, you should either
write your own custom functions, or sub-class the objects in question.

E.g. 

def multiline_print(L, indent=""):
"""Multi-line printing of lists.
WARNING: Untested and probably full of bugs.
"""
for item in L:
if type(item) == list:
multiline_print(item, indent + "")
else:
print indent + "|_" + str(item)


Hope this helps.



-- 
Steven.

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


Re: Microsoft Hatred FAQ

2005-10-17 Thread Tim Tyler
Tim Roberts <[EMAIL PROTECTED]> wrote or quoted:

[Microsoft]

> Part of their behavior really escape me.  The whole thing about browser
> wars confuses me.  Web browsers represent a zero billion dollar a year
> market.  Why would you risk anything to own it?

Power.  Minshare.  Controlling the planet's gateway to the internet.
That sort of thing.
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [newbie]Is there a module for print object in a readable format?

2005-10-17 Thread Steven D'Aprano
On Mon, 17 Oct 2005 11:31:46 +0200, enrico.sirola_NOSPAM wrote:

>> "James" == James Gan <[EMAIL PROTECTED]> writes:
> 
> James> I want the object printed in a readable format. For
> 
> [...]
> 
> James> I tried pickled, marshel. They do different work. Is there
> James> another module which do this kind of job?
> 
> from pprint import pprint
> pprint(object)

I don't think that even comes *close* to what James wants.

py> import pprint
py> pprint.pprint([1,2,3,4,[0,1,2], 5])
[1, 2, 3, 4, [0, 1, 2], 5]


-- 
Steven.

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


Re: Microsoft Hatred FAQ

2005-10-17 Thread Tim Tyler
In comp.lang.java.programmer Roedy Green <[EMAIL PROTECTED]> wrote or quoted:

> MS has held BACK computer evolution by tying their OS so heavily to
> the Pentium architecture. The chip architecture has nowhere near
> enough registers.  MS refused to believe the Internet was more than a
> passing fad. They are still frantically patching security holes in
> their OS over a decade  later.

Another big problem appears to be sitting on their customers and milking 
them - rather than working on improving things.  There has been some
progress with their OS - but it seems to be going very slowly.
-- 
__
 |im |yler  http://timtyler.org/  [EMAIL PROTECTED]  Remove lock to reply.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Run process with timeout

2005-10-17 Thread P
Natan wrote:
> Hi.
> 
> I have a python script under linux where I poll many hundreds of
> interfaces with mrtg every 5 minutes. Today I create some threads and
> use os.system(command) to run the process, but some of them just hang.
> I would like to terminate the process after 15 seconds if it doesn't
> finish, but os.system() doesn't have any timeout parameter.
> 
> Can anyone help me on what can I use to do this?

The new subprocess module has that functionality.
If your python version doesn't have that you
could try my unix specific version:
http://www.pixelbeat.org/libs/subProcess.py

Pádraig.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic generation of doc-strings of dynamically generated classes

2005-10-17 Thread Alex Martelli
Mikael Olofsson <[EMAIL PROTECTED]> wrote:
   ...
> Any ideas? Am I stuck with the clumsy exec-solution, or are there other
> ways to dynamically generate doc-strings of classes?

The best way to make classes on the fly is generally to call the
metaclass with suitable parameters (just like, the best way to make
instances of any type is generally to call that type):

derived = type(base)('derived', (base,), {'__doc__': 'zipp'})


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


Re: Profiling results

2005-10-17 Thread Magnus Lycka
Dave wrote:
> I'm trying to profile a Python program using gprof,

I don't think you will learn anything meaningful about
a Python program from gprof. Use the profiling tools
in Python. http://docs.python.org/lib/profile.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic generation of doc-strings of dynamically generated classes

2005-10-17 Thread George Sakkis
"Mikael Olofsson" <[EMAIL PROTECTED]> wrote:

> Hi!
>
> I've asked Google, but have not found any useful information there.
>
> Situation: I have a base class, say
>
>  >>> class base(object):
>  ImportantClassAttribute = None
>
> Now, I want to dynamically generate subclasses of base. That's not a
> problem. However, I very much want those subclasses to have individual
> doc-strings. More precicely, I want that important class attribute to be
> reflected in the doc-string. That's the problem. The only way I've
> managed to accomplish that is something like the following.
>
>  >>> ImportantClassAttribute = 7
>  >>> docString = 'The case %s.' % (ImportantClassAttribute,)
>  >>> exec('''class new(base):
>   """%s"""
>   pass ''' % (docString,))
>  >>> new.ImportantClassAttribute = ImportantClassAttribute
>  >>> new.__doc__
> 'The case 7.'
>
> This works as intended. The subclasses do get the doc-strings I want
> them to have, and I can live with this solution. But: This solution does
> not strike me as especially beautiful or readable. My first naïve
> attempt was instead the following.
>
>  >>> class new(base):
> pass
>
>  >>> new.ImportantClassAttribute = 7
>  >>> new.__doc__ = ('The case %(ImportantClassAttribute)s.'
>% new.__dict__)
>
> Traceback (most recent call last):
>File "", line 1, in -toplevel-
>  new.__doc__ = ('The case %(ImportantClassAttribute)s.'
> TypeError: attribute '__doc__' of 'type' objects is not writable
>
> This is readable to me, but apparently not the way to go, since I'm not
> allowed to replace the doc-string like this. I've also tried a number of
> other ways, but they all stumble on similar reasons.
>
> Any ideas? Am I stuck with the clumsy exec-solution, or are there other
> ways to dynamically generate doc-strings of classes?

There's nothing specifically about doc-strings, but you can create and 
customise a whole class
dynamically:

def makeBaseSubclass(impClassAttr):
return type('new_%s' % impClassAttr,
 (base,object),
{'ImportantClassAttribute': impClassAttr,
  '__doc__': 'The case %s' % impClassAttr})

>>> new = makeBaseSubclass(7)
>>> new.ImportantClassAttribute
7
>>> new.__doc__
'The case 7'


HTH,
George


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

reading hebrew text file

2005-10-17 Thread hagai26
I have a hebrew text file, which I want to read in python
I don't know which encoding I need to use & how I do that

thanks,
hagai

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


Re: How to get a raised exception from other thread

2005-10-17 Thread Lasse Vågsæther Karlsen
Steve Holden wrote:

>> Why should the coder of this software have to go through this
>> deliberate set up attrition, to get at this functionality, just
>> because it wasn't intented to be used in such a way by the
>> developers?
>>
> Because otherwise people who know no better will use the feature for 
> purposes where it's not the best way to achieve the required 
> functionality, leading to yet more endless discussions about why "it 
> doesn't work". Asynchronous signalling between threads is an accident 
> waiting to happen in the hands of an inexperienced programmer.

I can't agree with that opinion. There's tons of features of existing 
programming languages and systems, Python included, that is pretty much 
guaranteed to be misused, and badly at that. We can't remove those just 
on the off chance someone might start a thread on a newsgroup about why 
this is or isn't the best way to do things. If we do that then I guess 
list comprehension is out the window because there's tons of posts (from 
me included) that get this wrong.

The point of a programming language is not to dumb down the environment 
to a point where it is impossible to write bad code. Instead it's about 
empowering the programmers to be able to accomplish their tasks.

In any case, this exception-in-another-thread problem has inherent 
issues which must be solved, among others:

- C extension code can't be interrupted
- an exception thrown at the wrong time in a finally/except block might 
cause more problems than it intends to solve

So until a good implementation exists, there shouldn't be any point in 
actually discussing the motives of the programmers who wishes to use the 
feature.



-- 
Lasse Vågsæther Karlsen
http://usinglvkblog.blogspot.com/
mailto:[EMAIL PROTECTED]
PGP KeyID: 0x2A42A1C2
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading hebrew text file

2005-10-17 Thread Alex Martelli
<[EMAIL PROTECTED]> wrote:

> I have a hebrew text file, which I want to read in python
> I don't know which encoding I need to use & how I do that

As for the "how", look to the codecs module -- but if you don't know
what codec the textfile is written in, I know of no ways to guess from
here!-)


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


Re: reading hebrew text file

2005-10-17 Thread jepler
I looked for "VAV" in the files in the "encodings" directory
(/usr/lib/python2.4/encodings/*.py on my machine).  I found that the following
character encodings seem to include hebrew characters:
cp1255
cp424
cp856
cp862
iso8859-8
A file containing hebrew text might be in any one of these encodings, or
any unicode-based encoding.

To open an encoded file for reading, use
f = codecs.open(file, 'r', encoding='...')
Now, calls like 'f.readline()' will return unicode strings.

Here's an example, using a file in UTF-8 I have laying around:
>>> f = codecs.open("/users/jepler/txt/UTF-8-demo.txt", "r", "utf-8")
>>> for i in range(5): print repr(f.readline())
... 
u'UTF-8 encoded sample plain-text file\n'
u'\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\u203e\n'
u'\n'
u'Markus Kuhn [\u02c8ma\u02b3k\u028as ku\u02d0n] <[EMAIL PROTECTED]> \u2014 
1999-08-20\n'
u'\n'

Jeff


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

Re: reading hebrew text file

2005-10-17 Thread Fredrik Lundh
[EMAIL PROTECTED] wrote:

> I have a hebrew text file, which I want to read in python
> I don't know which encoding I need to use

that's not a good start.  but maybe it's one of these:

http://sites.huji.ac.il/tex/hebtex_fontsrep.html

?

> how I do that

f = open(myfile)
text = f.readline()

followed by one of

text = text.decode("iso-8859-8")
text = text.decode("cp1255")
text = text.decode("cp862")

alternatively, use:

f = codecs.open(myfile, "r", encoding)

to get a stream that decodes things on the fly.





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


Re: win32api.FindFiles Win2003, problem with Short Name

2005-10-17 Thread Frank Borell

Neil Hodgson wrote:
> Frank Borell:
> > On all three types of PC/Servers they are set to 0.
> >
> > For now I'll have to process this script on non 2003 servers?!?
>
> What do you get if you call win32api.GetShortPathName on the long name?
>
> Neil

Neil,

It seems I'm in a catch 22.

My initial issue was trying to rename/move files on a SAN that were
written from Mac's. While the easier messed up files names were easy to
convert and move, I quickly came across a few types that were not.
Files with spaces at the end seemed to only be solved with the
win32api.FindFiles(fullpath + '*').

The catch 22:
All other commands reported the path structure but the output could not
be used because Python/the system reported that it could not find the
file/path specified. (Including GetShortName).

Unfortunately I've been testing on an XP with all working fine, the
Win2003 simply does not show anything on the SAN for FindFiles(last
tuple).

It DOES show shortnames for other directories like 'c:/python24/lib'

Win2003 on ''c:/python24/lib'

Original Name | Short Name

aifc.py|
anydbm.py|
asynchat.py|
asyncore.py|
atexit.py|
atexit.pyc|
audiodev.py|
base64.py|
base64.pyc|
BaseHTTPServer.py|BASEHT~1.PY
Bastion.py|


WinXP on SAN:

Original Name | Short Name

^2aCOSBY SON PROFILE^2fNYT18|A^2ACOSB.1A7
Jimmy Carter|JIMMY_CF.86A
Allende's Last Day-jpgd.|ALLENDEC.9D3
archives 1959|ARCHIVE6.330
Barbara Jordan|BARBARAF.714
Bettmann-Mine 24.6mgs|BETTMAN7.D79
Bosley Crowther 16-095.jpg|BOSLEY_F.148
Calvin Klein.jpg|CALVIN_5.0B1
Carl Erskine Bkyln Dodger.jpg|CARL_ER8.683

Win2003 on SAN:

Original Name | Short Name

A^2aCOSBY SON PROFILE^2fNYT18|
Jimmy Carter|
Allende's Last Day-jpgd.|
archives 1959|
Barbara Jordan|
Bettmann-Mine 24.6mgs|
Bosley Crowther 16-095.jpg|
Calvin Klein.jpg|
Carl Erskine Bkyln Dodger.jpg|
Chess^2fConrad|
Coco Chanel portrait 18-940.jpg|
Coco Chanel1 18-940.jpg|


Frank

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


Installing Python at Work

2005-10-17 Thread Nikola
I'm currently learning Python for my own use.
I'm considering installing it on a work laptop, knowing that it is
non-licensed, distributable software.

However, does it access communication ports?  I know the company checks
their ports regularly for activity.

I won't be doing anything very serious; I'm just trying out Python,
learning the basics from 'Learning Python' by O'Reilly.

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


ANN: Leo 4.4a1 released

2005-10-17 Thread Edward K. Ream
Leo 4.4 alpha 1 is now available at:

http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106
To learn about Leo, see: http://webpages.charter.net/edreamleo/intro.html

Leo 4.4 adds an Emacs-like minibuffer and support for all frequently-used 
Emacs commands. Emacs users will be able to choose key bindings compatible 
with their present finger habits. Eventually, Vim users will be able to do 
the same.

This is definitely an alpha release; several minibuffer commands are buggy. 
However, this release also significantly improves Leo's error recovery 
capabilities.  This may be the most robust version of Leo ever released.

The highlights of Leo 4.4 alpha 1:
--
- Support for all frequently-used Emacs commands, including cursor and 
screen movement, basic character, word and paragraph manipulation, and 
commands to manipulate buffers, the kill ring, regions and rectangles.

- An Emacs-like minibuffer: you can now execute any command by name from the 
minibuffer, both the new Emacs-style commands and traditional Leo commands.

- You can define key bindings for all commands, including the new minibuffer 
commands, using @shortcuts nodes in leoSettings.leo files. You can define 
multiple sets of key bindings and switch between those sets easily.

- Several fixes to the 4.3 code base.

Coming in later releases of Leo 4.4:

- Support for 'mouseless Leo'. There will be commands to manipulate all 
aspects of Leo using commands, so your fingers will never have to leave the 
keyboard.

- Support for Vim and other 'plain-key' command modes.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Home: http://sourceforge.net/projects/leo/
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
CVS:  http://sourceforge.net/cvs/?group_id=3458
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html

Edward K. Ream
October 17, 2005

Edward K. Ream   email:  [EMAIL PROTECTED]
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: Stripping ASCII codes when parsing

2005-10-17 Thread David Pratt
Many thanks Steve. This is good information. I think this should work 
fine. I was doing a string.replace in a cleanData() method with the 
following characters but don't know if that would have done it. This 
contains all the control characters that I really know about in normal 
use. ord(c) < 32 sounds like a much better way to go and comprehensive. 
  So I guess instead of string.replace, I should do a...  for char 
in ...and check evaluate each character, correct? - or is there a 
better way of eliminating these other that reading a string in 
character by character.

'\a','\b','\e','\f','\n','\r','\t','\v','|'

Regards,
David


On Monday, October 17, 2005, at 06:04 AM, Steve Holden wrote:

> David Pratt wrote:
>> I am working with a text format that advises to strip any ascii 
>> control
>> characters (0 - 30) as part of parsing data and also the ascii pipe
>> character (124) from the data. I think many of these characters are
>> from a different time. Since I have never seen most of these 
>> characters
>> in text I am not sure how these first 30 control characters are all
>> represented (other than say tab (\t), newline(\n), line return(\r) ) 
>> so
>> what should I do to remove these characters if they are ever
>> encountered. Many thanks.
>
> You will find the ord() function useful: control characters all have
> ord(c) < 32.
>
> You can also use the chr() function to return a character whose ord() 
> is
> a specific value, and you can use hex escapes to include arbitrary
> control characters in string literals:
>
>myString = "\x00\x01\x02"
>
> regards
>   Steve
> -- 
> Steve Holden   +44 150 684 7255  +1 800 494 3119
> Holden Web LLC www.holdenweb.com
> PyCon TX 2006  www.python.org/pycon/
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


[no subject]

2005-10-17 Thread Finn Waldrip


404 Not Found

Not Found
The requested URL was not found on this server.

Apache/1.3.31



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


Re: Installing Python at Work

2005-10-17 Thread Jaime Wyant
The python interpreter doesn't do anything other than what you tell
it.  That is, the standard python installation does not install any
`secret programs' that run in the background.

Like most tools, Python is as benign as it's user.  However, unlike
most tools even benign users can be powerful.  Wow, I just stated
somewhat conflicting statements ;)

jw

On 17 Oct 2005 08:12:35 -0700, Nikola <[EMAIL PROTECTED]> wrote:
> I'm currently learning Python for my own use.
> I'm considering installing it on a work laptop, knowing that it is
> non-licensed, distributable software.
>
> However, does it access communication ports?  I know the company checks
> their ports regularly for activity.
>
> I won't be doing anything very serious; I'm just trying out Python,
> learning the basics from 'Learning Python' by O'Reilly.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Writing an immutable object in python

2005-10-17 Thread Mapisto
Hi,

I've noticed that if I initialize list of integers in the next manner:

>>> my_list = [0] * 30

It works just fine, even if I'll try to assign one element:

>>> id( my_list[4] )
10900116
>>> id( my_list[6] )
10900116
>>> my_list[4] = 6
>>> id( my_list[4] )
10900044
>>> id( my_list[6] )
10900116

The change in the poision occurs becouse int() is an immutable object.

if I will do the same with a user-defined object, This reference
manipulating will not happen. So, every entry in the array will refer
to the same instance.

Is there a way to bypass it (or perhaps to write a self-defined
immutable object)?

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


NYLUG meeting: 10/26 The Python Object Model with Alex Martelli & Google (open bar and food!)

2005-10-17 Thread Ron Guerin
(date and time inadvertently omitted last time. sorry!)

The New York Linux User's Group invites you to a special presentation
by Alex Martelli of Google, on the Python Object Model.  This
presentation will be held at P.J. Clarke's Sidecar, rather than our
usual location, and Google is picking up the tab for an hour and a half
of open bar and food.  Additionally, if you're looking for a job as a
Python developer, bring your resume.

Please RSVP at http://rsvp.nylug.org to attend, as seating is limited.

PS: You may wish to bring ID and a GPG fingerprint for keysigning.

- Ron

(announcement follows)

   The New York Linux User's Group Presents
Alex Martelli
   - on -
   The Python Object Model

Held at P.J. Clarke's Sidecar
  October 26, 2005  6:00pm-10:00pm
 915 Third Avenue @ 55th Street - NY

Python is a multi-paradigm programming language, but, out of the
paradigms it supports, there is no doubt that OOP (Object Oriented
Programming) is the paradigm that forms Python's core. If you have done
any substantial programming with Python, you have, most likely, used
some of its OOP features. But -- have you ever stopped to really think
about those OOP features, the mechanisms that Python uses (and exposes!)
to implement them, and how best to make use of the possibilities this
state of things offers?

This subject is generally known as the "Object Model" of a language.
This talk stops a bit short of examining every level of Python's Object
Model -- in particular, it does not get into metatypes (metaclasses) and
similar levels of "Black Magic". Rather, the talk sticks to the most
practically interesting aspects of Python's Object Model as seen from
the point of view of a programmer using Python -- understanding exactly
what's going on in all kind of everyday OOP-usage situation, what
alternatives and trade-offs these mechanisms imply (for example, when
should you use closures, and when should you use functors instead? when
to inherit, and when to delegate instead?), and how Design Patterns play
into the mix (Python subsumes and build-ins some classic DPs, and makes a
few others irrelevant due to its highly dynamic typing, but other classic
DPs yet remain extremely relevant and important for optimal day to day
use of OOP in Python).

About Alex Martelli
---
Alex Martelli is Uber Technical Lead at Google, in Production Software.
He wrote Python in a Nutshell and co-edited the Python Cookbook, and is
a member of the Python Software Foundation. Before joining Google,
Martelli spent 8 years with IBM, 12 with think3 inc, and 3 as a Python
freelance consultant, mostly for AB Strakt (Sweden).

P. J. Clarke's Sidecar
--
915 Third Avenue @ 55th Street - NY

Sidecar is PJ Clarkes handsome semiprivate upstairs dining room.  You
enter Sidecar through a distinct yet discreet door on East 55th Street.

Subway:
Take the E, V or 6 Subways to 51st Street, cut over to Third Avenue and
walk north 4 blocks.

Take the 4, 5 or 6 Trains to 59th Street, cut over to Third and walk 4
blocks south.

Bus:
Take the 101, 102 or 103 Buses to 55th. If you're coming downtown on
Lexington, cut across to Third. If you're coming up on Third, it's right
across the street.

http://pjclarkes.com/htm/sidecar.htm

About NYLUG
---
NYLUG is the New York Linux Users Group, which has met every month
without fail for the last six years.  Meetings are free and open to the
public, but require advance RSVP due to fire code and security
requirements at our usual meeting space at the IBM Building.

Our announcements mailing list at
http://nylug.org/mailman/listinfo/nylug-announce provides a low-volume
but steady stream of Linux, Free and Open Source, and related community
and other user group announcements for the tri-state area.

Our technical discussion list is a moderate-volume list featuring a
diverse group that from home users to enterprise security experts.
http://nylug.org/mailman/listinfo/nylug-talk

http://www.nylug.org/

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


Re: can a cut-down Python still be Python?

2005-10-17 Thread The Eternal Squire
No, but the BFDL has the corner on the Zen of Python.  What he says,
evidently goes.

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


Re: can a cut-down Python still be Python?

2005-10-17 Thread The Eternal Squire
Oops, I meant to say BDFL.   Sorry about the transpose.

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


Problem Pythoncard tutorial

2005-10-17 Thread LenS
Under the "Getting Started with Pythoncard" there is a short little
example of changing the starter1.py.  I have made the 2 changes and
when I run the program I get the following error:

Traceback error

...
result = dialog.alertDialog(self, 'It works!', 'Showing Off')
NameError: name 'self' is not defined

whats up

Len Sumnler

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


Re: Stripping ASCII codes when parsing

2005-10-17 Thread Steve Holden
David Pratt wrote:
[about ord(), chr() and stripping control characters]
> Many thanks Steve. This is good information. I think this should work 
> fine. I was doing a string.replace in a cleanData() method with the 
> following characters but don't know if that would have done it. This 
> contains all the control characters that I really know about in normal 
> use. ord(c) < 32 sounds like a much better way to go and comprehensive. 
>   So I guess instead of string.replace, I should do a...  for char 
> in ...and check evaluate each character, correct? - or is there a 
> better way of eliminating these other that reading a string in 
> character by character.
> 
> '\a','\b','\e','\f','\n','\r','\t','\v','|'
> 

There are a number of different things you might want to try. One is 
translate() which, given a string and a translate table, will perform 
the translation all in one go. For example:

  >>> delchars = "".join(chr(i) for i in range(32)) + "|"
  >>> print repr(delchars)
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\
x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f|'
  >>> nultxfrm = "".join(chr(i) for i in range(256))
  >>>

So delchars is a list of characters you want to remove, and nultxfrm is 
a 256-character string where the nultxfrm[n] == chr(n) - this performs 
no translation at all. So then

 s = s.translate(nultxfrm, delchars)

will remove all the "illegal" characters from s.

Note that I am sort-of cheating here, as this is only going to work for 
8-bit characters. Once Unicode enters the picture all bets are off.

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Writing an immutable object in python

2005-10-17 Thread Diez B. Roggisch
> The change in the poision occurs becouse int() is an immutable object.
> 
> if I will do the same with a user-defined object, This reference
> manipulating will not happen. So, every entry in the array will refer
> to the same instance.
> 
> Is there a way to bypass it (or perhaps to write a self-defined
> immutable object)?

This has nothing to do with int being mutable or not. It only has to do 
with _list_ being mutable, and of course teh semantics of the

_ * _ : list x int -> list

operator, which simply shallow copies the list. So assigning to some

l[i]


will replace that entry - regardless of what is stored there. And that 
is all you do. The mutablity of an object only comes into place if you 
try and do

l[i].some_mutating_op()

That catches many people by surprise - but you don't do such a thing :)

And besides: making an object immutable would mean that the only way to 
create an instance would be the constructor - rendering the purpose of 
the whole exercise somewhat moot - as then you'd have to call the 
constructor individually for each index you want to alter anyway. Which 
you have to do in the case of mutable objects, too. So - no gain there.

Regards,

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


Re: Installing Python at Work

2005-10-17 Thread Nikola
Many thanks. I know it sounds like a silly question, but it's the
company's laptop etc.  

Does Python allow conflicting statements? :)

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


newbie regex

2005-10-17 Thread csselo
Hi

I want to filter some strings,but i don t know how to use compile
method.

first character must be [a-zA-z] group and others can only be digits or
letters.

like

a24354trt,Tsd1234

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


Dr. Dobb's Python-URL! - weekly Python news and links (Oct 17)

2005-10-17 Thread Cameron Laird
QOTW: "If you don't have the time to be paranoid, try taking the time to
straighten out identity theft." -- K. G. Schneider

"The best way to make classes on the fly is generally to call the
metaclass with suitable parameters (just like, the best way to make
instances of any type is generally to call that type)." -- Alex Martelli


What code is good to read?  The Standard Library.  The Indexed
Packages.  The Cheese Shop.  Bit Torrent.  Much else--that is,
far more than any one person can digest:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/da095d94c77fe2c7/

Windows demands a developer rely on poorly-documented tricks
in order to be productive.  What *are* those tricks?  IPython,
autoit, ...:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/3c6f3201a61d41f0/

Most Python programmers live happily without thought of what
codecs do for them.  If you're among the few for whom charmap
performance is an issue, though, you'll be thankful to Tony
Nelson for this Fastcharmap contribution:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/481fda74e4c69dc/

Do you want to iterate over the same iterable multiple times?
There's help (itertool's tee(), for example) for your sort:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/77def05340a81dec/

Jeff Epler and Peter Otten explain the very first step--often
the most puzzling one--in working with other-than-English texts:

http://groups.google.com/group/comp.lang.python/browse_thread/thread/5b9e46bbc66e19f8/

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ee3feda62cfe42cd/



Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily  
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html 
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

For far, FAR more Python reading than any one mind should
absorb, much of it quite interesting, several pages index
much of the universe of Pybloggers.
http://lowlife.jp/cgi-bin/moin.cgi/PythonProgrammersWeblog
http://www.planetpython.org/
http://mechanicalcat.net/pyblagg.html

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Steve Bethard, Tim Lesher, and Tony Meyer continue the marvelous
tradition early borne by Andrew Kuchling, Michael Hudson and Brett
Cannon of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/   

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance. 
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch
   
Cetus collects Python hyperlinks.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http://python.faqts.com/

The Cookbook is a collaborative effort to capture useful and
interesting recipes.
http://aspn.activestate.com/ASPN/Cookbook/Python

Among several Python-oriented RSS/RDF feeds available are
http://www.python.org/channews.rdf
http://bootleg-rss.g-blog.net/pythonware_com_daily.pcgi
http://python.de/backend.php
For more, see
http://www.syndic8.com/feedlist.php

Re: Run process with timeout

2005-10-17 Thread Micah Elliott
On Oct 17, Alex Martelli wrote:
> Natan <[EMAIL PROTECTED]> wrote:
> > I have a python script under linux where I poll many hundreds of
> > interfaces with mrtg every 5 minutes. Today I create some threads and
> > use os.system(command) to run the process, but some of them just hang.
> > I would like to terminate the process after 15 seconds if it doesn't
> > finish, but os.system() doesn't have any timeout parameter.
> 
> Use the subprocess module.  With a subprocess.Popen object, you can
> ... kill it (use its .pid attribute).

The problem I've run into with this approach is the inability to kill
the pid's children.  Most often I'm not so fortunate to be able to
depend on the process to not be doing its own forking.  So here's a
simplified use case:

   $ cat sleep10.sh
   #! /bin/bash
   sleep 10  # does not get killed
   $
   $ cat to3.py
   #! /usr/bin/env python

   from subprocess import Popen
   from time import sleep
   from os import kill
   from signal import SIGTERM

   p = Popen(['./sleep10.sh'])
   sleep(3)
   kill(p.pid, SIGTERM) # Oops, won't kill p.pid's children.
   ##kill(-p.pid, SIGTERM)  # Won't work since not group leader,
#  and I'd rather avoid fork/dup/exec.
   $
   $ ./to3.py
   $ # to3.py finished but sleep 10 still running 

If you try this you will see that sleep10.sh gets killed, but its 
"sleep 10" subprocess does not, and runs for an additional 7 seconds.

I presently rely on an ugly script to do this properly.  It uses low
level calls such as pipe, close, dup2, fork, exec, setpgrp, etc.  I
won't post that here for brevity's sake (unless requested).  For this
case it would fork/exec sleep10.sh, make it a group leader, and the
parent would kill its group.

Is there any way to enable Python's subprocess module to do (implicit?)
group setup to ease killing of all children?  If not, is it a reasonable
RFE?

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


Re: Installing Python at Work

2005-10-17 Thread Steve Holden
Nikola wrote:
> Many thanks. I know it sounds like a silly question, but it's the
> company's laptop etc.  
> 
> Does Python allow conflicting statements? :)
> 
Actually it sounds like a meaningless question, but that's only because 
I'm not a mind-reader. ;-) I'm sure *you* know what you mean, it's just 
a matter of finding out how to help *us* understand.

What sort of conflicts are you concerned about?

Basically Python isn't going to do anything horrible unless you ask it 
to, or start running programs you don't understand (which is rarely a 
good idea anyway).

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: How do you draw this layout with wxpython?

2005-10-17 Thread Tony Nelson
In article <[EMAIL PROTECTED]>,
 "Young H. Rhiu" <[EMAIL PROTECTED]> wrote:

> See: http://hilug.org/img/app_layout.GIF
> 
> I'm implementing an album-like application with wxpython but I'm new to
> wxPython though I know how to program with python. The problem is that
> it's not easy for me to deal with drawing layout stuff with wxpython.
> What layout I'm thinking of looks like the gif image above.
> 
> The application is about saving some comments for each pictures on the
> filesystem. There are two windows. The above one is a window for
> loading some images and the below one is a TextCtrl for writing
> comments and if img1, for instance, is clicked, the first notebook(?)
> folder should be active.
> 
> Below is the program I tried but I don't know how to attach a notebook
> window under the image window.
> Any help is greatly appreciated.
> 
> Thanks in Advance, Rhiu
> 
> My Code:
> from wxPython.wx import *
> 
> class smallAppFrame(wxFrame):
> def __init__(self, parent, id, title):
> wxFrame.__init__(self, parent = None, id = -1,
>  title = "MySmallApp", pos = wxPoint(200, 200),
>  size = wxSize(460, 200), style =
> wxDEFAULT_FRAME_STYLE)
> 
> self.bitmap01 = wxStaticBitmap(self, -1,
> wxEmptyBitmap(100,100))
> self.bitmap02 = wxStaticBitmap(self, -1,
> wxEmptyBitmap(100,100))
> self.bitmap03 = wxStaticBitmap(self, -1,
> wxEmptyBitmap(100,100))
> self.bitmap04 = wxStaticBitmap(self, -1,
> wxEmptyBitmap(100,100))
> 
> box = wxBoxSizer(wxHORIZONTAL)
> 
> box.Add((10,10))
> box.Add(self.bitmap01, 0, wxALIGN_CENTER)
> box.Add((10,10))
> box.Add(self.bitmap02, 0, wxALIGN_CENTER)
> box.Add((10,10))
> box.Add(self.bitmap03, 0, wxALIGN_CENTER)
> box.Add((10,10))
> box.Add(self.bitmap04, 0, wxALIGN_CENTER)
> box.Add((10,10))
> 
> self.SetAutoLayout(True)
> self.SetSizer(box)
> 
> class MySmallApp(wxApp):
> def OnInit(self):
> frame = smallAppFrame(None, -1, "MySmallApp")
> frame.Show(true)
> self.SetTopWindow(frame)
> return true
> 
> app = MySmallApp(0)
> app.MainLoop()

I've never used (or learned) wxWidgets, and I'm even new to GTK, but I 
think you just need a deeper structure.  SmallAppFrame() would contain 
two subwindows, probably using something like wxBoxSizer(wxVERTICAL).  
The top subwindow would contain what you've done now, and the bottom one 
would have the rest of your stuff.

TonyN.:'[EMAIL PROTECTED]
  '  
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: List of strings to list of floats ?

2005-10-17 Thread Madhusudan Singh
[EMAIL PROTECTED] wrote:

> 
> Madhusudan> Is it possible to convert a very long list of strings to a
> Madhusudan> list of floats in a single statement ?
> 
> Madhusudan> I have tried float(x) and float(x[:]) but neither work. I
> Madhusudan> guess I would have to write a loop if there isn't a way.
> 
> Try:
> 
> >>> los = ["123.0", "2", "1e-6"]
> >>> map(float, los)
> [123.0, 2.0, 9.9995e-07]
> >>> [float(s) for s in los]
> [123.0, 2.0, 9.9995e-07]
> 
> Skip

Thanks. Now, a slightly more complicated question.

Say I have two lists of floats. And I wish to generate a list of floats that
is a user defined function of the two lists.

I tried :

def rpyth(x,y):
r=sqrt(pow(x,2.0)+pow(y,2.0))
return r

r1n=map(rpyth,x2n[1:len(x2n)-1],y2n[1:len(y2n)-1])

And I get an error complaining about floats.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Comparing lists

2005-10-17 Thread Christian Stapfer
"Alex Martelli" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Christian Stapfer <[EMAIL PROTECTED]> wrote:
>
>>  This is why we would like to have a way of (roughly)
>> estimating the reasonableness of the outlines of a
>> program's design in "armchair fashion" - i.e. without
>> having to write any code and/or test harness.
>
> And we would also like to consume vast amounts of chocolate, while
> similarly reclining in comfortable armchairs,

Maybe some of my inclination towards design
based on suitable *theories* (instead of
self-conditioning through testing) goes back
to the fact that I tend to think about the
design of my programs when no computer happens
to be near at hand to do some such experimenting,
or self-conditioning...

> without getting all fat and flabby.

Well, thinking can be hard work. There is no need
to suggest an image of laziness. Thought experiments
are also quite often successful. Hardware engineers
can design very often entire gadgets without doing
a great deal of testing. They usually need to resort
to testing only if they know (or feel?) not to have
a sufficiently clear *theoretical* grasp of the
behavior of some part of their design.

>  Unfortunately, what we would like and what reality affords
> are often pretty uncorrelated.  No matter how much theoreticians may
> love big-O because it's (relatively) easy to compute, it still has two
> failings which are often sufficient to rule out its sufficiency for any
> "estimate [of] the reasonableness" of anything: [a] as we operate on
> finite machines with finite wordsize, we may never be able reach
> anywhere even remotely close to the "asymptotic" region where big-O has
> some relationship to reality; [b] in many important cases, the
> theoretical worst-case is almost impossible to characterize and hardly
> ever reached in real life, so big-O is of no earthly use (and much
> harder to compute measures such as big-Theta should be used for just
> about any practical purpose).

But the fact remains that programmers, somewhat
experienced with the interface a module offers,
have a *rough*idea* of that computational complexity
attaches to what operations of that interface.
And having such a *rough*idea* helps them to
design reasonably performing programs much more
quickly.
  Big-Oh and other asymptotic complexity measures
really do have *this* advantage over having
acquired, by way of conditioning experiences,
some such *rough*idea* of computational complexity:
they capture at least some of that "rough idea"
in a somewhat more easily communicable and much
more precise fashion.

  Maybe you and Steven prefer to be conditioned,
Pavlov style, by the wonderful experiences that
you get while testing? - This is perhaps really
one of my *worst* psychological handicaps, I must
admit: that I don't *like* to get conditioned
like that, no matter how good it feels, no matter
how effective it might be for "practical" work that
one has to do.
  I want to be able to really think *about* what
I am doing. And in order to be able to think about
it one usually needs some information about the
implementation, performance wise, of the language
features and the system modules that one might
want to use. If you happen to know of any *better*
way of offering the requisite information than
asymptotic complexity measures then, of course,
I am very grateful to hear more about it.

> Consider, for example, point [b].  Quicksort's big-O is N squared,
> suggesting that quicksort's no better than bubblesort or the like.  But
> such a characterization is absurd.  A very naive Quicksort, picking its
> pivot very systematically (e.g., always the first item), may hit its
> worst case just as systematically and in cases of practical importance
> (e.g., already-sorted data); but it takes just a little extra care (in
> the pivot picking and a few side issues) to make the worst-case
> occurrences into ones that will not occur in practice except when the
> input data has been deliberately designed to damage by a clever and
> determined adversary.
>
> Designing based on worst-case occurrences hardly ever makes
> sense in any field of engineering,

What's wrong with wanting to have a rough idea
of what might happen in the worst case? I believe
many engineers are actually expected to think
about at least some "worst-case" scenarios.
Think of nuclear reactors, airplanes, or
telephone exchanges (and dont' think of Google
for a change). Don't you expect engineers
and scientists designing, for example, a nuclear
reactor, to think hard about what the worst-case
scenario might be? And how likely it might happen?
(And *no* testing whatsoever in that direction,
please!) Not thinking is, admittedly, a lot easier.



> Why bother doing
> (e.g.) random pivot selection in quicksort, when its big-O (i.e.,
> worst-case) behavior will remain N-squared, just like naive quicksort,
> or, for that matter, bubblesort?

Because worst-case is not the only measure of
computational comple

Re: Microsoft Hatred FAQ

2005-10-17 Thread Alan Balmer
On Sat, 15 Oct 2005 02:31:33 GMT, Roedy Green
<[EMAIL PROTECTED]> wrote:

>On 14 Oct 2005 19:01:42 -0700, "Xah Lee" <[EMAIL PROTECTED]> wrote or
>quoted :
>
>>
>>Q: Microsoft's Operating System is used over 90% of PCs. If that's
>>not monopoly, i don't know what is.
>
>They got where they are  by CHEATING.  That is why they are evil, not
>because they have a large market share.

You've been around long enough to learn to recognize this poster and
ignore him.
-- 
Al Balmer
Balmer Consulting
[EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: graphic memory & animation

2005-10-17 Thread Mike C. Fletcher
Peres wrote:

> Thanks a lot for your answer, Fredrik,
> Slow means more than 20ms to erase the screen. After double buffering 
> it improved a lot , of course (16 ms) but I'll need a faster speed.
> I program 2D animated sequences on a PC. Do you think OpenGL is the 
> correct direction to take? If so is it easy to interface with Python 
> (it seems PyOpenGL is not freeware...)

PyOpenGL has a BSD-style license, that's about as 'free' as one can get 
in the freeware sense.

Just a note,
Mike

-- 

  Mike C. Fletcher
  Designer, VR Plumber, Coder
  http://www.vrplumber.com
  http://blog.vrplumber.com

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


  1   2   3   >