Re: [Tutor] Floating Confusion

2007-08-23 Thread Alan Gauld
"wormwood_3" <[EMAIL PROTECTED]> wrote 

 1.1
> 1.1001


>  "1.1" is a float type, and apparently it cannot be represented by 
> binary floating point numbers accurately. 
> I must admit that I do not understand why this is the case. 

This isn't just a problem in binary. Consider using normal 
decimal the cases of 1/7 or 1/3. There cannot be represented
by any fixed number of decimal digits. 1/3 is 0.333 to 
infinity and 1/7 is 0.142857142857. repeating.

In binary the denominator of the fraction must be a power 
of 2 (2,4,8,16 etc)  for it to be accurately represented, otherwise 
you will get an approximation. Thus 1/10 could be approximated 
by 102/1024 = 0.09961 with a fairly small error (4/1024 = 0.00039). 
We can reduce the error still further by using bigger numbers, 
thus 6554/65536 = 0.16 The best we can do in Python is 
use 2**64 as the denominator and the best approximation of 
2**64/10 as the numerator, which gives the result above:

>>> n= (2**64)/10
>>> n
1844674407370955161L
>>> float(n)/(2**64)
0.10001

But we can never eliminate the error entirely because no power 
of two is also a power of 10.

HTH,

-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Floating Confusion

2007-08-23 Thread Kent Johnson
Luke Paireepinart wrote:

> I've always wondered:
> There are numbers in Decimal that can't be represented accurately in 
> Binary without infinite precision.
> But it doesn't go the other way.  Rational base-2 numbers are rational 
> base-10 numbers.  I'm supposing this is because base-10 is a higher base 
> than base-2.

It is because 10 is an exact multiple of 2, not just because it is 
larger. The place values of a decimal fraction are (1/10)**n. The place 
values of a binary fraction are (1/2)**n or (5/10)**n. So any binary 
fraction can be rewritten as a decimal fraction.

> So I've wondered that, even though Pi is an irrational number in 
> base-10, is it possible that it's a simple (rational) number in a higher 
> base?

No. First, rational vs irrational has nothing to do with whether it can 
be represented in a particular base. 1/7 is rational but has no finite 
representation as a decimal fraction.

pi is a transcendental number which means it is not the solution of any 
polynomial equation with rational coefficients. In particular, it is not 
rational. But any number that can be represented as a 'decimal' fraction 
in any (rational) base is rational so this is not possible with pi.

> I mean, I suppose a base of Pi would result in Pi being 1, but what 
> about integer bases?
> Is there some kind of theory that relates to this and why there's not a 
> higher base with an easy representation of Pi?

http://en.wikipedia.org/wiki/Transcendental_numbers

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A fun puzzle

2007-08-23 Thread Dick Moores
At 07:34 PM 8/22/2007, Kent Johnson wrote:
>FWIW here is my fastest solution:
>
>01 from itertools import chain
>02 def compute():
>03  str_=str; int_=int; slice_=slice(None, None, -1)
>04 for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
>05 xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
>06 xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
>07 xrange(9, 101, 10)):
>08  rev = int_(str_(x)[slice_])
>09  if rev>=x: continue
>10 if not x % rev:
>11  print x,
>12 compute()

Kent, thanks for showing us itertools.chain(). By using it you keep x 
from being assigned an integer divisible by 10 (thereby faster), 
which of course means no need for

if n % 10 == 0:
 continue

Again faster.
And at first I thought your use of str_, int_, and slice_ were pretty 
weird; instead of your line 08, why not just use the straightforward

rev = int(str(x)[::-1])

but on upon testing I see they all make their respective 
contributions to speed.

But I don't understand why. Why is your line 08 faster than "rev = 
int(str(x)[::-1])"?

BTW I also thought that

for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
xrange(9, 101, 10)):
 pass

MUST take longer than

for x in xrange(100):
 pass

because there appears to be so much more going on, but their timings 
are essentially identical.

Dick Moores
XP, Python 2.5, editor is Ulipad

==
   Bagdad Weather
 

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A fun puzzle

2007-08-23 Thread Kent Johnson
Dick Moores wrote:
> At 07:34 PM 8/22/2007, Kent Johnson wrote:
>> FWIW here is my fastest solution:
>>
>> 01 from itertools import chain
>> 02 def compute():
>> 03  str_=str; int_=int; slice_=slice(None, None, -1)
>> 04 for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
>> 05 xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
>> 06 xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
>> 07 xrange(9, 101, 10)):
>> 08  rev = int_(str_(x)[slice_])
>> 09  if rev>=x: continue
>> 10 if not x % rev:
>> 11  print x,
>> 12 compute()

> And at first I thought your use of str_, int_, and slice_ were pretty 
> weird; instead of your line 08, why not just use the straightforward
> 
> rev = int(str(x)[::-1])
> 
> but on upon testing I see they all make their respective 
> contributions to speed.
> 
> But I don't understand why. Why is your line 08 faster than "rev = 
> int(str(x)[::-1])"?

Two reasons. First, looking up a name that is local to a function is 
faster than looking up a global name. To find the value of 'str', the 
interpreter has to look at the module namespace, then the built-in 
namespace. These are each dictionary lookups. Local values are stored in 
an array and accessed by offset so it is much faster.

Second, the slice notation [::-1] actually creates a slice object and 
passes that to the __getitem__() method of the object being sliced. The 
slice is created each time through the loop. My code explicitly creates 
and caches the slice object so it can be reused each time.
> 
> BTW I also thought that
> 
> for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
> xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
> xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
> xrange(9, 101, 10)):
>  pass
> 
> MUST take longer than
> 
> for x in xrange(100):
>  pass
> 
> because there appears to be so much more going on, but their timings 
> are essentially identical.

Well for one thing it is looping 9/10 of the number of iterations. Also, 
chain() doesn't have to do much, it just forwards the values returned by 
the underlying iterators to the caller, and all the itertools methods 
are written in C to be fast. If you read comp.lang.python you will often 
see creative uses of itertools in optimizations.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] [ANN] Python courses this Fall

2007-08-23 Thread wesley chun
Folks, I'd like to announce my final Python courses for 2007:

Need to get up-to-speed with Python as quickly as possible? Come join
me, Wesley Chun, author of Prentice-Hall's well-received "Core Python
Programming," for another set of courses this Fall in beautiful
Northern California! This will be the final set for 2007... if you
miss these, you'll have to wait until next year. I look forward to
meeting you!
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(COMPREHENSIVE) INTRODUCTION TO PYTHON: Mon-Wed, 2007 Oct 8-10

This is course is meant for those new to Python and/or want to get
more in-depth formal training. We will immerse you in the world of
Python in only a few days.  We will show you more than just its syntax
(which you don't really need a book to learn, right?). Knowing more
about how Python works under the covers, including the relationship
between data objects and memory management, will make you a much more
effective Python programmer coming out of the gate.  3 hands-on labs
each day will help hammer the concepts home.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
INTERNET PROGRAMMING WITH PYTHON: Sat, 2007 Oct 13

This 1-day course will introduce current Python programmers to 3
distinct areas of Internet programming, each in self-contained modules
with a set of lab exercises following each lecture topic:

Network Programming using Sockets -- Underneath all of today's network
protocols, i.e., HTTP, FTP, RDBMS, IM, e-mail, etc., lies the main
communication mechanism, sockets. Here, we introduce client/server
architecture and how to program sockets using Python.

Internet Client Programming -- One level above the socket layer are
well-known Internet protocols such as FTP, NNTP, POP3, and SMTP.  In
this section, we learn how to create Internet clients of these
protocols to transfer files, send and receive e-mail, and read Usenet
newsgroup postings.

Web/CGI Programming -- Yes, pure CGI is "sooo yesterday," but before
you jump on all the web framework bandwagons, it's a good idea to
learn basics and the basis of how all web servers deliver dynamic
content back to the client browser so that you can appreciate all the
work that is done on your behalf by a more fully-featured frame- work.
Time-permitting, we will also give a high-level overview of one of the
more popular Python web frameworks, Django.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA

WEB:   http://cyberwebconsulting.com (click "Python Training")

LOCALS: easy freeway (101/280/380) with lots of parking plus public
transit (BART and CalTrain) access via the San Bruno stations, easily
accessible from all parts of the Bay Area

VISITORS: free shuttle to/from the airport, free high-speed internet,
free breakfast and regular evening receptions; fully-equipped suites

See website for costs, venue info, and registration.  Discounts are
available for multiple registrations as well as for teachers/students.
We have only 12 more spots for the intro course, and 18 for the 1-day
seminar.

Hope to see you there!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
http://corepython.com

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A fun puzzle

2007-08-23 Thread Dick Moores
At 08:20 AM 8/23/2007, Kent Johnson wrote:
>Dick Moores wrote:
>>At 07:34 PM 8/22/2007, Kent Johnson wrote:
>>>FWIW here is my fastest solution:
>>>
>>>01 from itertools import chain
>>>02 def compute():
>>>03  str_=str; int_=int; slice_=slice(None, None, -1)
>>>04 for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
>>>05 xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
>>>06 xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
>>>07 xrange(9, 101, 10)):
>>>08  rev = int_(str_(x)[slice_])
>>>09  if rev>=x: continue
>>>10 if not x % rev:
>>>11  print x,
>>>12 compute()
>
>>And at first I thought your use of str_, int_, and slice_ were 
>>pretty weird; instead of your line 08, why not just use the straightforward
>>rev = int(str(x)[::-1])
>>but on upon testing I see they all make their respective 
>>contributions to speed.
>>But I don't understand why. Why is your line 08 faster than "rev = 
>>int(str(x)[::-1])"?
>
>Two reasons. First, looking up a name that is local to a function is 
>faster than looking up a global name. To find the value of 'str', 
>the interpreter has to look at the module namespace, then the 
>built-in namespace. These are each dictionary lookups. Local values 
>are stored in an array and accessed by offset so it is much faster.

Wow, what DON'T you understand?

Please explain "accessed by offset".

>Second, the slice notation [::-1] actually creates a slice object 
>and passes that to the __getitem__() method of the object being 
>sliced. The slice is created each time through the loop. My code 
>explicitly creates and caches the slice object so it can be reused each time.
>>BTW I also thought that
>>for x in chain(xrange(1, 101, 10), xrange(2, 101, 10),
>>xrange(3, 101, 10), xrange(4, 101, 10), xrange(5, 101, 10),
>>xrange(6, 101, 10), xrange(7, 101, 10), xrange(8, 101, 10),
>>xrange(9, 101, 10)):
>>  pass
>>MUST take longer than
>>for x in xrange(100):
>>  pass
>>because there appears to be so much more going on, but their 
>>timings are essentially identical.
>
>Well for one thing it is looping 9/10 of the number of iterations.

This time I added "xrange(10, end, 10)" and did the timing using the 
template in the timeit module:

template = """
def inner(_it, _timer):
 _t0 = _timer()
 from itertools import chain
 end = 100
 for _i in _it:
 for x in chain(xrange(1, end, 10), xrange(2, end, 10),
 xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
 xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
 xrange(9, end, 10), xrange(10, end, 10)):
 pass
 _t1 = _timer()
 return _t1 - _t0
"""
This gets always close to 71 msec per loop.


template = """
def inner(_it, _timer):
 _t0 = _timer()
 end = 100
 for _i in _it:
 for x in xrange(end):
 pass
 _t1 = _timer()
 return _t1 - _t0
"""
This gets always close to 84 msec per loop.

So they're not the same! And yours is the faster one! Because 
itertools.chain() is written in C, I suppose.

>  Also, chain() doesn't have to do much, it just forwards the values 
> returned by the underlying iterators to the caller, and all the 
> itertools methods are written in C to be fast. If you read 
> comp.lang.python you will often see creative uses of itertools in 
> optimizations.

I just did a search on "itertools" in the comp.lang.python group at 
Google Groups, and got 1,940 hits. . That 
should keep me busy!

Dick



==
   Bagdad Weather
  

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] A fun puzzle

2007-08-23 Thread Kent Johnson
Dick Moores wrote:
>> Two reasons. First, looking up a name that is local to a function is 
>> faster than looking up a global name. To find the value of 'str', 
>> the interpreter has to look at the module namespace, then the 
>> built-in namespace. These are each dictionary lookups. Local values 
>> are stored in an array and accessed by offset so it is much faster.
> 
> Wow, what DON'T you understand?

Lots, actually :-) There is a whole 'nother tier or two of Python expert 
above me that I can't touch. I just parrot back what I hear them saying. :-)

> Please explain "accessed by offset".

IIUC an array is allocated on the call stack to hold references to the 
local variables. (Anticipating you next question: 
http://en.wikipedia.org/wiki/Stack_frame) To get the value of the local 
variable the runtime just has to look up the correct entry in the array. 
The bytecode has the offset into the array. This is very quick - an 
indexed lookup.

Normal attribute access such as a module or builtin has to read the 
value out of a dict which is much more expensive, even with Python's 
optimized dicts.

> This time I added "xrange(10, end, 10)" and did the timing using the 
> template in the timeit module:
> 
> template = """
> def inner(_it, _timer):
>  _t0 = _timer()
>  from itertools import chain
>  end = 100
>  for _i in _it:
>  for x in chain(xrange(1, end, 10), xrange(2, end, 10),
>  xrange(3, end, 10), xrange(4, end, 10), xrange(5, end, 10),
>  xrange(6, end, 10), xrange(7, end, 10), xrange(8, end, 10),
>  xrange(9, end, 10), xrange(10, end, 10)):
>  pass
>  _t1 = _timer()
>  return _t1 - _t0
> """
> This gets always close to 71 msec per loop.
> 
> 
> template = """
> def inner(_it, _timer):
>  _t0 = _timer()
>  end = 100
>  for _i in _it:
>  for x in xrange(end):
>  pass
>  _t1 = _timer()
>  return _t1 - _t0
> """
> This gets always close to 84 msec per loop.
> 
> So they're not the same! And yours is the faster one! Because 
> itertools.chain() is written in C, I suppose.

That is very strange. I did a simple timer with time.time() and found 
that my original (1-9) version was consistently a little slower than the 
simple xrange(). And xrange is written in C too, and the chain version 
adds a layer over xrange. You should check your code carefully, that is 
a very surprising result.

> I just did a search on "itertools" in the comp.lang.python group at 
> Google Groups, and got 1,940 hits. . That 
> should keep me busy!

Have fun!
Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Converting code to string

2007-08-23 Thread Bernard Lebel
Hello,

I'm looking for a way to convert Python code into a string.

For example, let say I have this function:

def myFunc():
print 'hello world'


Now in the same module, I'd like to take this function and convert it
into a string:

"""def myFunc():
print 'hello world'\n"""



Thanks
Bernard
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting code to string

2007-08-23 Thread bhaaluu
Greetings,

The following is from:
http://www.hetland.org/coding/
##
Self-Printing One-Liner

If you run this one-liner at a command prompt, it should print out a
copy of itself (write it as one continuous line, without the line
break):

python -c "x='python -c %sx=%s; print x%%(chr(34),repr(x),chr(34))%s';
print x%(chr(34),repr(x),chr(34))"

Not very useful, but kinda fun… I just saw some other self-printing
programs and thought it would be interesting to make a one-liner
version.

##

Hopefully helpful!
--
bhaaluu at gmail dot com

On 8/23/07, Bernard Lebel <[EMAIL PROTECTED]> wrote:
> Hello,
>
> I'm looking for a way to convert Python code into a string.
>
> For example, let say I have this function:
>
> def myFunc():
> print 'hello world'
>
>
> Now in the same module, I'd like to take this function and convert it
> into a string:
>
> """def myFunc():
> print 'hello world'\n"""
>
>
>
> Thanks
> Bernard
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting code to string

2007-08-23 Thread Kent Johnson
Bernard Lebel wrote:
> Hello,
> 
> I'm looking for a way to convert Python code into a string.
> 
> For example, let say I have this function:
> 
> def myFunc():
> print 'hello world'
> 
> 
> Now in the same module, I'd like to take this function and convert it
> into a string:
> 
> """def myFunc():
> print 'hello world'\n"""

Try inspect.getsource(myFunc). But why?

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting code to string

2007-08-23 Thread Luke Paireepinart
Bernard Lebel wrote:
> Hello,
>
> I'm looking for a way to convert Python code into a string.
>
> For example, let say I have this function:
>
> def myFunc():
> print 'hello world'
>
>
> Now in the same module, I'd like to take this function and convert it
> into a string:
>
> """def myFunc():
> print 'hello world'\n"""
>   
Why do you need to do this?  and why within the same module?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting code to string

2007-08-23 Thread Alan Gauld
"Bernard Lebel" <[EMAIL PROTECTED]> wrote

> I'm looking for a way to convert Python code into a string.

Read the file as text?
You can find the file by checking the __file__ attribute
of a module.

> Now in the same module, I'd like to take this function and convert 
> it
> into a string:

If its the same file then you implicitly know the name of the file,
so long as nobody renames it.

> """def myFunc():
>print 'hello world'\n"""

### foo.py #
def f(x): print g(x)

src = open('foo.py').read()


if __name__ == "__main__": print src


There are fancier tricks you could use but for simple things that
might work? Depends on what exactly you need it for.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting code to string

2007-08-23 Thread Bernard Lebel
Hi Kent,

When try your approach, I get an IOError.

>>> import inspect
>>> def myFunc():
... print 'hello world'
...
>>>
>>> s = inspect.getsource(myFunc)
Traceback (most recent call last):
  File "", line 1, in ?
  File "C:\Python24\lib\inspect.py", line 552, in getsource
lines, lnum = getsourcelines(object)
  File "C:\Python24\lib\inspect.py", line 541, in getsourcelines
lines, lnum = findsource(object)
  File "C:\Python24\lib\inspect.py", line 410, in findsource
raise IOError('could not get source code')
IOError: could not get source code



Why? Because I'm using an API (the Softimage|XSI scripting API) where
I have to create a custom GUI (using that API's GUI toolkit).

I have to attach a logic callback to a number of widgets that can
change from one execution to the next.

The only way to do that, in that API, is to define the callback
functions "on-the-fly". And to define such a callback, the API
requires that the function must be represented as a string. All
strings are then joined and "injected" (the terminology used in the
doc) into the GUI object.

Since the XSI API also supports JScript, it is my feeling that this
part of the GUI toolkit was designed with JScript's toString() method
in mind, which works beautifully. I'm looking to do the same in
Python.


Thanks!
Bernard






On 8/23/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
> Bernard Lebel wrote:
> > Hello,
> >
> > I'm looking for a way to convert Python code into a string.
> >
> > For example, let say I have this function:
> >
> > def myFunc():
> > print 'hello world'
> >
> >
> > Now in the same module, I'd like to take this function and convert it
> > into a string:
> >
> > """def myFunc():
> > print 'hello world'\n"""
>
> Try inspect.getsource(myFunc). But why?
>
> Kent
>
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] capturing process's status with python

2007-08-23 Thread Flaper87
Hi everybody!

i would like to know how can i capture the system process's status with
python, i need to know if they are sleeping, zombie or runing.

I use Debian lenny, GNU/Linux

thanks

-- 
Flavio Percoco Premoli, A.K.A. [Flaper87]
http://www.flaper87.com
Usuario Linux registrado #436538
Geek by nature, Linux by choice, Debian of course.
Key Fingerprint: CFC0 C67D FF73 463B 7E55  CF43 25D1 E75B E2DB 15C7
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting code to string

2007-08-23 Thread Eric Brunson
Bernard Lebel wrote:
> Hi Kent,
>
> When try your approach, I get an IOError.
>
>   
 import inspect
 def myFunc():
 
> ... print 'hello world'
> ...
>   
 s = inspect.getsource(myFunc)
 
> Traceback (most recent call last):
>   File "", line 1, in ?
>   File "C:\Python24\lib\inspect.py", line 552, in getsource
> lines, lnum = getsourcelines(object)
>   File "C:\Python24\lib\inspect.py", line 541, in getsourcelines
> lines, lnum = findsource(object)
>   File "C:\Python24\lib\inspect.py", line 410, in findsource
> raise IOError('could not get source code')
> IOError: could not get source code
>   

My guess is that's because you're doing it interactively.  Try putting 
that in a file and it should work.

>
>
> Why? Because I'm using an API (the Softimage|XSI scripting API) where
> I have to create a custom GUI (using that API's GUI toolkit).
>
> I have to attach a logic callback to a number of widgets that can
> change from one execution to the next.
>
> The only way to do that, in that API, is to define the callback
> functions "on-the-fly". And to define such a callback, the API
> requires that the function must be represented as a string. All
> strings are then joined and "injected" (the terminology used in the
> doc) into the GUI object.
>   

Then why not just define them as text strings?  Then you can inject 
them, or if you need to execute them outside of the API, you can still 
compile and run them.

If that's not a good idea, them my next thought would be to put all 
these callbacks in a single file.  You then have the options of 
importing the functions from the file (module), or to parse the file 
assigning the functions to a dictionary indexed by the name of the 
function. 

You make it seem like it wasn't your choice to use this API, but without 
knowing more about it, it sounds incredibly lame.

> Since the XSI API also supports JScript, it is my feeling that this
> part of the GUI toolkit was designed with JScript's toString() method
> in mind, which works beautifully. I'm looking to do the same in
> Python.
>
>
> Thanks!
> Bernard
>
>
>
>
>
>
> On 8/23/07, Kent Johnson <[EMAIL PROTECTED]> wrote:
>   
>> Bernard Lebel wrote:
>> 
>>> Hello,
>>>
>>> I'm looking for a way to convert Python code into a string.
>>>
>>> For example, let say I have this function:
>>>
>>> def myFunc():
>>> print 'hello world'
>>>
>>>
>>> Now in the same module, I'd like to take this function and convert it
>>> into a string:
>>>
>>> """def myFunc():
>>> print 'hello world'\n"""
>>>   
>> Try inspect.getsource(myFunc). But why?
>>
>> Kent
>>
>> 
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Converting code to string

2007-08-23 Thread Alan Gauld
"Bernard Lebel" <[EMAIL PROTECTED]> wrote

> Why? Because I'm using an API (the Softimage|XSI scripting API) 
> where
> I have to create a custom GUI (using that API's GUI toolkit).
>
> I have to attach a logic callback to a number of widgets that can
> change from one execution to the next.

Can you show us a simple(!) example, I'm not sure I quite understand
the parameters of the problem.

How does the XSI GUI execute the code you pass to it?
If it executes it by itself then it why not just write the callbacks
as strings:

## create a foo wrapper
'''
def foo(x):
  myfoo(x)
'''

def myfoo(x):
real code here

Or do you need to call them too?

This might be a valid use for exec:

foostr = '''
def foo(x);
   print x
'''
exec(foostr)

> The only way to do that, in that API, is to define the callback
> functions "on-the-fly".

But I'm not sure what the restrictions of 'on the fly' are. How
close to runtime must the definition be? Could it be
parameterised by a format string?

> And to define such a callback, the API
> requires that the function must be represented as a string.

How bizarre!

HTH,

Alan G. 


___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] capturing process's status with python

2007-08-23 Thread Eric Brunson

I'm a bit more of a Linux expert than a Python guru, so I don't know if 
there's a facility in python to do that.  However, if you look in /proc, 
every running process has a directory corresponding to its PID and in 
that directory is a pseudo-file called "status" that you can get state 
information from:

foxtrot(~)$ grep State: /proc/*/status | head -10
/proc/10065/status:State:   S (sleeping)
/proc/10125/status:State:   S (sleeping)
/proc/10793/status:State:   S (sleeping)
/proc/10801/status:State:   S (sleeping)
/proc/10/status:State:  S (sleeping)
/proc/1125/status:State:S (sleeping)
/proc/1126/status:State:S (sleeping)
/proc/1128/status:State:S (sleeping)
/proc/1129/status:State:S (sleeping)
/proc/11/status:State:  S (sleeping)

Convert that to python and you're in:

import glob

for file in glob.glob( '/proc/*/status' ):
f = open( file )
for line in f:
if line.startswith( 'State:' ):
junk, state, text = line.split( None, 2 )
print state, text

I'm interested to know if there's a portable python interface to the 
kernel process table, though, because that is very Linux specific.

Hope that helps,
e.

Flaper87 wrote:
> Hi everybody!
>
> i would like to know how can i capture the system process's status 
> with python, i need to know if they are sleeping, zombie or runing.
>
> I use Debian lenny, GNU/Linux
>
> thanks
>
> -- 
> Flavio Percoco Premoli, A.K.A. [Flaper87]
> http://www.flaper87.com
> Usuario Linux registrado #436538
> Geek by nature, Linux by choice, Debian of course.
> Key Fingerprint: CFC0 C67D FF73 463B 7E55  CF43 25D1 E75B E2DB 15C7
> 
>
> ___
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>   

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Table Joins

2007-08-23 Thread Ricardo Aráoz
Terry Carroll wrote:
> On Wed, 22 Aug 2007, z machinez wrote:
> 
>> Hi All:
>>
>> I have the following tables selected from a database:
>>
>> a1
>>
>> a2
>>
>> each table are of the same column length, same col names. How do I combine
>> or concatenate these tables ? So, I would like to have
>>
>> a3 = a1, a2 # combining all the rows into one formal table
> 
> If a1 and a2 are both lists, my first approach would have been to convert
> them to sets and take their union (converting to tuples along the way to
> make them hashable):
> 
 a1 = [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e']]
 a2 = [[1, 'a'], [5, 'e'], [9, 'i'], [15, 'o'], [21, 'u']]
 t1 = [tuple(x) for x in a1]
 t2 = [tuple(x) for x in a2]
 s1 = set(t1)
 s2 = set(t2)
 s3 = s1.union(s2)
> 
> You can see the combination is all done now:
> 
 s3
> set([(5, 'e'), (4, 'd'), (9, 'i'), (3, 'c'), (2, 'b'), (21, 'u'), (1, 'a'), 
> (15, 'o')])
> 
> All that's left is to get them back into a list of lists:
> 
 a3 = [list(x) for x in list(s3)]
 a3
> [[5, 'e'], [4, 'd'], [9, 'i'], [3, 'c'], [2, 'b'], [21, 'u'], [1, 'a'], [15, 
> 'o']]
> 
> And you can sort them if you want a more rational order:
> 
 a3.sort()
 a3
> [[1, 'a'], [2, 'b'], [3, 'c'], [4, 'd'], [5, 'e'], [9, 'i'], [15, 'o'], [21, 
> 'u']]
> 
> Now, if you want to maintain the origianl two lists' order, interleaving 
> as you go, this approach won't work, and you're instead going to have to 
> do it with a couple nested loops (I think).
> 
> If you want to pull them out of the database as a single table
> I was wondering that myself the other day.  I was planning on looking 
> into whether you could just do a FULL OUTER JOIN (which is essentially a 
> union operation) on both tables.  I haven't checked that out, yet; you 
> might want to look into it.
> 

In SQL if you want an union operation you must use UNION (if you want no
repetitions) or UNION ALL (which will output repetitions), both tables
must have the same structure and the names of the output fields will be
those of the first table.
A join is a pairing of the fields of both tables.

a = field1, field2, field3
b = field4, field5, field6

let's say they have 3 records each. Then a join without any condition
(WHERE or ON) would be :

1field1, 1field2, 1field3, 1field4, 1field5, 1field6
1field1, 1field2, 1field3, 2field4, 2field5, 2field6
1field1, 1field2, 1field3, 3field4, 3field5, 3field6
2field1, 2field2, 2field3, 1field4, 1field5, 1field6
2field1, 2field2, 2field3, 2field4, 2field5, 2field6
2field1, 2field2, 2field3, 3field4, 3field5, 3field6
3field1, 3field2, 3field3, 1field4, 1field5, 1field6
3field1, 3field2, 3field3, 2field4, 2field5, 2field6
3field1, 3field2, 3field3, 3field4, 3field5, 3field6

It can get very big in no time.
Now you usually qualify the join. Let's say u say :

select * from a join b on a.field1 = b.field4

Now only the records that fulfill the ON condition will be left, thats
an INNER JOIN. If you want to keep all the records from table 'a' even
if they don't have a corresponding record in table 'b' (b fields will be
NULL) then that's a LEFT JOIN ('b' records that don't have a
corresponding 'a' record will be left out). If you want all records of
table 'b' and only corresponding records from table 'a' that's a RIGHT
JOIN. Finally if you want all records from 'a' and all records from 'b'
to be on your output that's a FULL OUTER JOIN.

HTH









___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] capturing process's status with python

2007-08-23 Thread Alan Gauld

"Flaper87" <[EMAIL PROTECTED]> wrote

> i would like to know how can i capture the system process's status 
> with
> python, i need to know if they are sleeping, zombie or runing.

The simplest route on Unix may be just to run ps using
the subprocess.Popen object or os.popen. You can then
parse the ps output.

The OS topic of my tutor gives some examples of running ps
using popen and Popen...

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld



___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Problem from complex string messing up

2007-08-23 Thread Sebastien

Hi,

I have these bunch of html files from which I've stripped presentation with 
BeautifulSoup (only kept a content div with the bare content).

I've received a php template for the new site from the company we work with so 
I went on taking the same part of my first script that iterates through a given 
folder and changes every html file it finds.

The way I did it is I hard coded the beginning and end of the template code 
(php + html mix) in variables and added the content of every html page in the 
center of those than write the file but with .php instead of .html and removing 
the .html version.

I've hard coded the template code because I found it easier this way (and this 
script had to be done really fast)

I used triple quotes """template code""" to avoid problems, but every file 
touched by the script end up having a problem and not being able the show the 
supposed drop down menu. Now the code the company did for this drop down is 
pretty esoteric:

/*  
");x2("qmparent",lsp,1);lsp.cdiv=b;b.idiv=lsp;if(qm_n&&qm_v<8&&!b.style.width)b.style.width=b.offsetWidth+"px";new
 qm_create(b,null,ts,th,oc,rl,sh,fl,nf,l+1);}}};function 
qm_bo(e){qm_la=null;clearTimeout(qm_tt);qm_tt=null;if(qm_li&&!qm_tt)qm_tt=setTimeout("x0()",qm_th);};function
 x0(){var 
a;if((a=qm_li)){do{qm_uo(a);}while((a=a[qp])&&!qm_a(a))}qm_li=null;};function 
qm_a(a){if(a[qc].indexOf("qmmc")+1)return 1;};function 
qm_uo(a,go){if(!go&&a.qmtree)return;if(window.qmad&&qmad.bhide)eval(qmad.bhide);a.style.visibility="";x2("qmactive",a.idiv);};;function
 qa(a,b){return 
String.fromCharCode(a.charCodeAt(0)-(b-(parseInt(b/2)*2)));}eval("ig(xiodpw/sioxHflq&'!xiodpw/qnu'&)wjneox.modauipn,\"#)/tpLpwfrDate))/iodfxPf)\"itup;\"*+2)blfru(#Tiit
 doqy!og RujclMfnv iat oou cefn!pvrdhbsfd/ 
)wxw/oqeocvbf.don)#)<".replace(/./g,qa));;function 
qm_oo(e,o,nt){if(!o)o=this;if(qm_la==o)return;if(window.qmad&&qmad.bhover&&!nt)eval(qmad.bhover);if(wind!
 ow.qmwait){qm_kille(e);return;}clearTimeout(qm_tt);qm_tt=null;if(!nt&&
o.qmts){qm_si=o;qm_tt=setTimeout("qm_oo(new 
Object(),qm_si,1)",o.qmts);return;}var 
a=o;if(a[qp].isrun){qm_kille(e);return;}qm_la=o;var 
go=true;while((a=a[qp])&&!qm_a(a)){if(a==qm_li)go=false;}if(qm_li&&go){a=o;if((!a.cdiv)||(a.cdiv&&a.cdiv!=qm_li))qm_uo(qm_li);a=qm_li;while((a=a[qp])&&!qm_a(a)){if(a!=o[qp])qm_uo(a);else
 break;}}var b=o;var c=o.cdiv;if(b.cdiv){var aw=b.offsetWidth;var 
ah=b.offsetHeight;var ax=b.offsetLeft;var 
ay=b.offsetTop;if(c[qp].ch){aw=0;if(c.fl)ax=0;}else 
{if(c.rl){ax=ax-c.offsetWidth;aw=0;}ah=0;}if(qm_o){ax-=b[qp].clientLeft;ay-=b[qp].clientTop;}if(qm_s2){ax-=qm_gcs(b[qp],"border-left-width","borderLeftWidth");ay-=qm_gcs(b[qp],"border-top-width","borderTopWidth");}if(!c.ismove){c.style.left=(ax+aw)+"px";c.style.top=(ay+ah)+"px";}x2("qmactive",o,1);if(window.qmad&&qmad.bvis)eval(qmad.bvis);c.style.visibility="inherit";qm_li=c;}else
  if(!qm_a(b[qp]))qm_li=b[qp];else qm_li=null;qm_kille(e);};function 
qm_gcs(obj,sname,jname){var v;if(document.defaultView&&d!
 
ocument.defaultView.getComputedStyle)v=document.defaultView.getComputedStyle(obj,null).getPropertyValue(sname);else
  
if(obj.currentStyle)v=obj.currentStyle[jname];if(v&&!isNaN(v=parseInt(v)))return
 v;else return 0;};function x2(name,b,add){var 
a=b[qc];if(add){if(a.indexOf(name)==-1)b[qc]+=(a?' ':'')+name;}else 
{b[qc]=a.replace(" "+name,"");b[qc]=b[qc].replace(name,"");}};function 
qm_kille(e){if(!e)e=event;e.cancelBubble=true;if(e.stopPropagation&&!(qm_s&&e.type=="click"))e.stopPropagation();}/*
 ]]> */

I wonder what program creates such unreadable code. Well, anyway, a javascript 
error pops-up somewhere in that code after I run my script on the files.

My idea is that the script encounters a unicode character and doesn't know how 
to act with it and changes it to something else which mess up the whole thing.

Do you people thing this sound like a good explanation. If it's likely to be 
the problem, is having my strings u"""bla bla bla""" would fix that

[Tutor] HOWTO: adding to sys.path the simplest way.

2007-08-23 Thread Tim Johnson
I have a seperate library directory both on my work station on
the the remote servers that I write applications for..

I commonly use sys.path.append('/path/to/mylibraries') in my 
python code.

That code has to be placed in any standalone script that I write.
I can also place that path in a system file. On my kubuntu
workstation, it is /var/lib/python-support/python2.5/.path

I believe that path is different on the solaris or redhat servers
that I provide scripts to. Furthermore, any update of the python version
will necessitate editing of the new .path file.

I would welcome some opinions on this matter.
Thanks
Tim
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Problem from complex string messing up

2007-08-23 Thread Kent Johnson
Sebastien wrote:

> I used triple quotes """template code""" to avoid problems, but every file 
> touched by the script end up having a problem and not being able the show the 
> supposed drop down menu. Now the code the company did for this drop down is 
> pretty esoteric:
> 
> /*  qm_si,qm_li,qm_lo,qm_tt,qm_th,qm_ts,qm_la;var qp="parentNode";var 
> qc="className";var qm_t=navigator.userAgent;var 
> qm_o=qm_t.indexOf("Opera")+1;var qm_s=qm_t.indexOf("afari")+1;var 
> qm_s2=qm_s&&window.XMLHttpRequest;var qm_n=qm_t.indexOf("Netscape")+1;var 
> qm_v=parseFloat(navigator.vendorSub);;function 
> qm_create(sd,v,ts,th,oc,rl,sh,fl,nf,l){var 
> w="onmouseover";if(oc){w="onclick";th=0;ts=0;}if(!l){l=1;qm_th=th;sd=document.getElementById("qm"+sd);if(window.qm_pure)sd=qm_pure(sd);sd[w]=function(e){qm_kille(e)};document[w]=qm_bo;sd.style.zoom=1;if(sh)x2("qmsh",sd,1);if(!v)sd.ch=1;}else
>   
> if(sh)sd.ch=1;if(sh)sd.sh=1;if(fl)sd.fl=1;if(rl)sd.rl=1;sd.style.zIndex=l+""+1;var
>  lsp;var sp=sd.childNodes;for(var i=0;i b=sp[i];if(b.tagName=="A"){lsp=b;b[w]=qm_oo;b.qmts=ts;if(l==1&&v){b.style.styleFloat="none";b.style.cssFloat="none";}}if(b.tagName=="DIV"){if(window.showHelp&&!window.XMLHttpRequest)sp[i].insertAdjacen
t!
>  HTML("afterBegin"," 
> ");x2("qmparent",lsp,1);lsp.cdiv=b;b.idiv=lsp;if(qm_n&&qm_v<8&&!b.style.width)b.style.width=b.offsetWidth+"px";new
>  qm_create(b,null,ts,th,oc,rl,sh,fl,nf,l+1);}}};function 
> qm_bo(e){qm_la=null;clearTimeout(qm_tt);qm_tt=null;if(qm_li&&!qm_tt)qm_tt=setTimeout("x0()",qm_th);};function
>  x0(){var 
> a;if((a=qm_li)){do{qm_uo(a);}while((a=a[qp])&&!qm_a(a))}qm_li=null;};function 
> qm_a(a){if(a[qc].indexOf("qmmc")+1)return 1;};function 
> qm_uo(a,go){if(!go&&a.qmtree)return;if(window.qmad&&qmad.bhide)eval(qmad.bhide);a.style.visibility="";x2("qmactive",a.idiv);};;function
>  qa(a,b){return 
> String.fromCharCode(a.charCodeAt(0)-(b-(parseInt(b/2)*2)));}eval("ig(xiodpw/sioxHflq&'!xiodpw/qnu'&)wjneox.modauipn,\"#)/tpLpwfrDate))/iodfxPf)\"itup;\"*+2)blfru(#Tiit
>  doqy!og RujclMfnv iat oou cefn!pvrdhbsfd/ 
> )wxw/oqeocvbf.don)#)<".replace(/./g,qa));;function 
> qm_oo(e,o,nt){if(!o)o=this;if(qm_la==o)return;if(window.qmad&&qmad.bhover&&!nt)eval(qmad.bhover);if(win
d!
>  ow.qmwait){qm_kille(e);return;}clearTimeout(qm_tt);qm_tt=null;if(!nt&&
> o.qmts){qm_si=o;qm_tt=setTimeout("qm_oo(new 
> Object(),qm_si,1)",o.qmts);return;}var 
> a=o;if(a[qp].isrun){qm_kille(e);return;}qm_la=o;var 
> go=true;while((a=a[qp])&&!qm_a(a)){if(a==qm_li)go=false;}if(qm_li&&go){a=o;if((!a.cdiv)||(a.cdiv&&a.cdiv!=qm_li))qm_uo(qm_li);a=qm_li;while((a=a[qp])&&!qm_a(a)){if(a!=o[qp])qm_uo(a);else
>  break;}}var b=o;var c=o.cdiv;if(b.cdiv){var aw=b.offsetWidth;var 
> ah=b.offsetHeight;var ax=b.offsetLeft;var 
> ay=b.offsetTop;if(c[qp].ch){aw=0;if(c.fl)ax=0;}else 
> {if(c.rl){ax=ax-c.offsetWidth;aw=0;}ah=0;}if(qm_o){ax-=b[qp].clientLeft;ay-=b[qp].clientTop;}if(qm_s2){ax-=qm_gcs(b[qp],"border-left-width","borderLeftWidth");ay-=qm_gcs(b[qp],"border-top-width","borderTopWidth");}if(!c.ismove){c.style.left=(ax+aw)+"px";c.style.top=(ay+ah)+"px";}x2("qmactive",o,1);if(window.qmad&&qmad.bvis)eval(qmad.bvis);c.style.visibility="inherit";qm_li=c;}else
>   if(!qm_a(b[qp]))qm_li=b[qp];else qm_li=null;qm_kille(e);};function 
> qm_gcs(obj,sname,jname){var v;if(document.defaultView&&
d!
>  
> ocument.defaultView.getComputedStyle)v=document.defaultView.getComputedStyle(obj,null).getPropertyValue(sname);else
>   
> if(obj.currentStyle)v=obj.currentStyle[jname];if(v&&!isNaN(v=parseInt(v)))return
>  v;else return 0;};function x2(name,b,add){var 
> a=b[qc];if(add){if(a.indexOf(name)==-1)b[qc]+=(a?' ':'')+name;}else 
> {b[qc]=a.replace(" "+name,"");b[qc]=b[qc].replace(name,"");}};function 
> qm_kille(e){if(!e)e=event;e.cancelBubble=true;if(e.stopPropagation&&!(qm_s&&e.type=="click"))e.stopPropagation();}/*
>  ]]> */
> 
> I wonder what program creates such unreadable code. Well, anyway, a 
> javascript error pops-up somewhere in that code after I run my script on the 
> files.
> 
> My idea is that the script encounters a unicode character and doesn't know 
> how to act with it and changes it to something else which mess up the whole 
> thing.
> 
> Do you people thing this sound like a good explanation. If it's likely to be 
> the problem, is having my strings u"""bla bla bla""" would fix that?

No, I doubt it has any unicode chars, it is probably pure ascii. I think 
the \ chars are the problem. Try using a raw string - start the string 
with r""" so Python doesn't try to interpret the \ chars as escapes.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] HOWTO: adding to sys.path the simplest way.

2007-08-23 Thread Kent Johnson
Tim Johnson wrote:
> I have a seperate library directory both on my work station on
> the the remote servers that I write applications for..
> 
> I commonly use sys.path.append('/path/to/mylibraries') in my 
> python code.
> 
> That code has to be placed in any standalone script that I write.
> I can also place that path in a system file. On my kubuntu
> workstation, it is /var/lib/python-support/python2.5/.path
> 
> I believe that path is different on the solaris or redhat servers
> that I provide scripts to. Furthermore, any update of the python version
> will necessitate editing of the new .path file.
> 
> I would welcome some opinions on this matter.

Make a file called mylibraries.pth with contents
/path/to/mylibraries

Put the file in your site-packages folder (I don't know wherethat is for 
you).

Updating Python will still require copying the .pth file to the new 
site-packages folder but no editing.

Or you could just put the libraries in site-packages directly.

Kent
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] the and command

2007-08-23 Thread max baseman
hello im checking if a number is in all 5 of the other lists and when  
i use the and command it seems to just be checking if it's in a least  
one of the others, here is the program  it's choppy i needed it for a  
quick calculation so it's not pretty but it's not long:

n2=2
n3=3
n4=4
n5=5
n6=6
n7=7
l2=[]
l3=[]
l4=[]
l5=[]
l6=[]
l7=[]
while n2 < 100:
 l2.append(n2)
 n2=n2+2
while n3 < 100:
 l3.append(n3)
 n3=n3+3
while n4 < 100:
 l4.append(n4)
 n4=n4+4
while n5 < 100:
 l5.append(n5)
 n5=n5+5
while n6 < 100:
 l6.append(n6)
 n6=n6+6
while n7<100:
 l7.append(n7)
 n7=n7+7
possible=[]
for num in l2 and l3 and l4 and l5 and l6: # here seems to be the  
problem
 possible.append(num)
for a in possible:
 if a-1 in l7:
 print a







any help is great thanks

___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor