[Tutor] Confused about globals

2006-06-09 Thread Etrade Griffiths
Hi

I have a series of python programs that plot stuff using PYX.  Common to 
these is the need to read in a list of (well) locations in (X,Y) coords so 
I put that code in a separate module called shared_funcs.py.  The coords 
are stored in dictionaries which I want to use later in the main program 
- every time I find a well with data, I can get the well's (x,y) coords by 
looking up the well name in the dictionary.  The code snippet looks like this:

=== main.py 

# define coord dictionaries for global use

DE={}
DN={}

import shared_funcs()

shared_funcs.get_xy_data() # Get coords from file

  ... do plotting stuff


=== shared_funcs.py ===

def get_xy_data():
in_file=open(well_xy.txt,r)
for line in in_file
L=line.split()
well=L[0]
x=L[1]
y=L[2]

DE[well]=x
DN[well]=y
in_file.close()

The problem is that DE and DN appear not to be accessible to get_xy_data - 
presumably this is because shared_funcs.py and main.py don't share the same 
scope.  So, is there any way to let get_xy_data change DE and DN?  I guess 
the obvious way is to pass them to get_xy_data as arguments - but is there 
a more pythonic method?  Thanks in advance!


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


Re: [Tutor] layout ( i guess)

2006-06-09 Thread Kent Johnson
Desk Jet wrote:
 uh ive been wondering if with python you would be able to make layouts?

What's a layout? For a web site, magazine page, printed circuit board...

Kent


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


Re: [Tutor] making a python program part of xhtml

2006-06-09 Thread Ron Phillips
 Emily Fortuna  [EMAIL PROTECTED]  6/8/2006 9:19 AM 
Hola everyone,
I'm working on creating a webpage in which a user can submit data into

fields to be held in a database (there are other details, but this is 
the gist of the idea), and I need to use python. I am unfamiliar with 
manipulating data and web apps as a whole (and new to python), so I
have 
been encountering much unfamiliar terrain. I _think_ I want to somehow

embed the python into the page, but I'm really not sure how to do it. 
After googling I found some programs that generate xhtml from python, 
but I don't think that is what I want, or is it? Your help is
appreciated!
Emily

You might look at http://karrigell.sourceforge.net/: karrigell lets you
embed python in xhtml, xhtml in python, execute straight python scripts,
or execute python from a karrigell application server. Even if you don't
choose karrigell for some reason, at least the documentation can help
you sort out the variations on the python/xhtml theme!
 
Ron
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Maintain SessionID with AMARA

2006-06-09 Thread kieran flanagan
Hi

I want to have a script that can browse through a website and retrieve
information upon request. If I use AMARA for this, in the form i.e.

 for subtree in binderytools.pushbind('panel', source='file1.xml'):
 print subtree.name

And then once on this page 'file1.xml', need to peform an ACTION to
change the page to file2.xml and retrieve information from there. How
can I do the following:

1. Peform the actionURL using AMARA so it returns a different xml
screen that I can parse i.e. peforms a click of a URL and then parses
the resulting xml.
2. Maintain the sessionID across different pages.

Are there any examples of this ?.

Thanks
Kieran
-- Behind every great man, there is a great woman. Behind that woman is Mr.T. 
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Confused about globals

2006-06-09 Thread Dustin Mitchell
As a note, the import should be

   import shared_funcs

In Python, most globals aren't really global -- they're local to the 
module.  If you split your modules by functionality, then variables 
should naturally relate to a specific module, and be located there.  
So, for example, you could move those global variables to 
shared_funcs.py, renamed to wells.py:

=== wells.py ==

DE={}
DN={}

def get_xy_data():
in_file=open(well_xy.txt,r)
for line in in_file
L=line.split()
well=L[0]
x=L[1]
y=L[2]

DE[well]=x
DN[well]=y
in_file.close()

def lookup_well(well):
   return (DE.get(well, None), DN.get(well, None))

=== main.py ===

import wells

def func_that_needs_wells():
   ...
   for e n wells.DE.keys():
 ...
   ...

etc.

On Jun 9, 2006, at 4:42 AM, Etrade Griffiths wrote:

 Hi

 I have a series of python programs that plot stuff using PYX.  Common 
 to
 these is the need to read in a list of (well) locations in (X,Y) 
 coords so
 I put that code in a separate module called shared_funcs.py.  The 
 coords
 are stored in dictionaries which I want to use later in the main 
 program
 - every time I find a well with data, I can get the well's (x,y) 
 coords by
 looking up the well name in the dictionary.  The code snippet looks 
 like this:

 === main.py 

 # define coord dictionaries for global use

 DE={}
 DN={}

 import shared_funcs()

 shared_funcs.get_xy_data() # Get coords from file

   ... do plotting stuff


 === shared_funcs.py ===

 def get_xy_data():
   in_file=open(well_xy.txt,r)
   for line in in_file
   L=line.split()
   well=L[0]
   x=L[1]
   y=L[2]

   DE[well]=x
   DN[well]=y
   in_file.close()

 The problem is that DE and DN appear not to be accessible to 
 get_xy_data -
 presumably this is because shared_funcs.py and main.py don't share the 
 same
 scope.  So, is there any way to let get_xy_data change DE and DN?  I 
 guess
 the obvious way is to pass them to get_xy_data as arguments - but is 
 there
 a more pythonic method?  Thanks in advance!


 ___
 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] Confused about globals

2006-06-09 Thread Kent Johnson
Etrade Griffiths wrote:
 Hi
 
 I have a series of python programs that plot stuff using PYX.  Common to 
 these is the need to read in a list of (well) locations in (X,Y) coords so 
 I put that code in a separate module called shared_funcs.py.  The coords 
 are stored in dictionaries which I want to use later in the main program 
 - every time I find a well with data, I can get the well's (x,y) coords by 
 looking up the well name in the dictionary.  

You don't need a global variable in shared_funcs.get_xy_data() at all. 
It is reading a file and creating two dicts. I would write it to create 
and return the dicts. Then you can save them where you like in the 
caller. Also, I would use one dict whose values are (x, y) pairs, rather 
than two parallel dicts. Then your code looks like this:

=== shared_funcs.py ===

def get_xy_data():
D = {}
in_file=open(well_xy.txt,r)
for line in in_file
L=line.split()
well=L[0]
x=L[1]
y=L[2]

D[well]=(x, y)
in_file.close()
return D

=== main.py ===

import shared_funcs
D = shared_funcs.get_xy_data()

though I suggest a more descriptive name than D...


If there are other related bits of data or operations other than lookup, 
that might point to using a class to wrap the dict, the other data and 
operations.

Kent

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


[Tutor] file attribute of module

2006-06-09 Thread Kermit Rose
  
Message: 2
Date: Thu, 08 Jun 2006 09:28:27 -0400
From: Kent Johnson [EMAIL PROTECTED]
Subject: Re: [Tutor] module versus file
 
Most modules do have corresponding files. The exceptions are the ones
built-in to Python. In fact modules have a __file__ attribute that tells
you where it came from; try typing
factor30.__file__
 
Kent
 
***
 
 import factor30
 factor30._file_
 
Traceback (most recent call last):
  File pyshell#2, line 1, in -toplevel-
factor30._file_
AttributeError: 'module' object has no attribute '_file_'
 
 
 factor30.__file__
'c:\\math\\factoring\\factor30.py'
 
 
Ok.   Now I understand it.
 
The module is named factor30.
 
The file is named factor30.py
 
I presume that if I created another library in the same directory
in a file named factor31.py
that it would create a module named factor31.   ???
 
 
 

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


[Tutor] pyexcelerator

2006-06-09 Thread Paul D. Kraus
Are their docs anywhere for pyexcelerator? the built in docs are a bit lacking.For instance I can't figure out how to set a column width.I am just reading the examples and they kind of help but I don't follow this ...
ws.col(i).width = 0x0d00 + iwhere i is an incrementing integer.so to me it reads if i = 0.set col 0's width to hexnumber plus 0why the hex number? does it have to be written this way?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pyexcelerator

2006-06-09 Thread Kent Johnson
Paul D. Kraus wrote:
 Are their docs anywhere for pyexcelerator? the built in docs are a bit 
 lacking.
 
 For instance I can't figure out how to set a column width.
 I am just reading the examples and they kind of help but I don't follow 
 this ...
 
 ws.col(i).width = 0x0d00 + i
 
 where i is an incrementing integer.
 so to me it reads if i = 0.
 
 set col 0's width to hexnumber plus 0
 
 why the hex number? does it have to be written this way?

Maybe just try without the 0x0d00 and see what happens? or try the 
pyExcelerator mailing list on SourceForge...

Kent

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


[Tutor] errno vs. sys.exc_info

2006-06-09 Thread doug shawhan
I am in need of a clear way to return exceptions within a try loop.

I have been looking at both errno and sys.exc_info. I know that using
errno is not encouraged in threaded programs, but this is no big deal
for my purposes.

I found a good, clear example for translating the rather cryptic output from sys.exc_info:

def formatExceptionInfo(maxTBlevel=5):
 cla, exc, trbk = sys.exc_info()
 excName = cla.__name__
 try:
  excArgs = exc.__dict__[args]
 except KeyError:
  excArgs = no args
 
 excTb = traceback.format_tb(trbk, maxTBlevel)
 return (excName, excArgs, excTb)


Which seems to cover most of the bases, but I have yet to find a good example of using errno.

Can someone provide a quick cut? :-)

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


Re: [Tutor] making a python program part of xhtml

2006-06-09 Thread Dave Kuhlman
On Fri, Jun 09, 2006 at 07:17:02AM -0400, Ron Phillips wrote:
  Emily Fortuna  [EMAIL PROTECTED]  6/8/2006 9:19 AM 

[snip]

 ... I _think_ I want to somehow
 embed the python into the page, but I'm really not sure how to do it. 
 After googling I found some programs that generate xhtml from python, 
 but I don't think that is what I want, or is it? Your help is
 appreciated!
 Emily
 
 You might look at http://karrigell.sourceforge.net/: karrigell lets you
 embed python in xhtml, xhtml in python, execute straight python scripts,
 or execute python from a karrigell application server. Even if you don't
 choose karrigell for some reason, at least the documentation can help
 you sort out the variations on the python/xhtml theme!
  

You may also want to visit the following Web page, then scroll
down and look for Templating Engines:

http://wiki.python.org/moin/WebProgramming

Dave

-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] layout ( i guess)

2006-06-09 Thread Ivan Furone
Desk Jet wrote: uh ive been wondering if with python you would be able to make layouts?Hello,I premise that i don't get the exact meaning you are using for 'layouts',GUI-enabled applications (
i.e. those with windows,buttons,progress bars,notebooks..) could it be?Well,sure Python can :) In the majority of case,programming graphical user interfaces will require you to install additional packages,but there is one that comes along with Python : 
Tkinter.Cheers,Ivan
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pyexcelerator

2006-06-09 Thread Paul D. Kraus
Maybe just try without the 0x0d00 and see what happens? or try thepyExcelerator mailing list on SourceForge...
Mailing list looks dead only 2 messages.Man this is the exact module i need to finish converting about 20 scripts from perl and I have no idea how to use most of it. This is very frustrating.
Is there another excel writer module that has documentation?Or on a broader topic is their a CPAN equivalent? Paul
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] pyexcelerator

2006-06-09 Thread Kent Johnson
Paul D. Kraus wrote:
 
 Maybe just try without the 0x0d00 and see what happens? or try the
 pyExcelerator mailing list on SourceForge... 
 
 
 Mailing list looks dead only 2 messages.
 Man this is the exact module i need to finish converting about 20 
 scripts from perl and I have no idea how to use most of it. This is very 
 frustrating.
 
 Is there another excel writer module that has documentation?

If you are running on Windows and have Excel installed you can talk to 
Excel using COM. Take a look here:
http://www.oreilly.com/catalog/pythonwin32/chapter/ch12.html

If no one on tutor knows about this you can probably get help with COM 
on the python-win32 list or comp.lang.python.

Kent

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


[Tutor] numpy speed problems

2006-06-09 Thread Jeff Peery
hello, I am having some trouble with the speed of numpy. I'm crunching some numbers (see the attached script) and in total I have 1,000,000 grid points over which I am integrating. I'm doing a bunch of adding, mulitply, divide, powers, etc, but in total there are 1,000,000 points to do these operations over and it really shouldn't take this long... as far as I know. my last simulation took about 8+ hours.What might I be doing wrong in my code to cause this to be so slow? big thanks!!Jeff __Do You Yahoo!?Tired of spam?  Yahoo! Mail has the best spam protection around http://mail.yahoo.com from numpy import *


function definitions

def GetPressure(x_coord, y_coord, x_r, y_r, z_r, dx, dy, w_mn, rho, v_mn, k_mn, 
n, m):
#   intialize pressure
p   = 0.0 + 1j

#   sum contributions from all point sources to receiver
for ii in range(n):
for jj in range(m):
r   = ((x_r  - x_coord[ii])**2.0 + (y_r - y_coord[jj])**2.0 + (z_r 
- 0.0)**2)**0.5
p   +=  (1j*w_mn*rho*v_mn[ii][jj])*exp(1j*k_mn*r)*dx*dy/(2.0*pi*r)

p   = sqrt(p*conjugate(p))
return abs(p)



vaiables and constants


problem definition parameter
n   = arange(1,70) #mode number in x direction
m   = arange(1,70) #mode number in y direction
mode_n  = 10  #mode number - 1
mode_m  = 10   #mode number - 1
L   = 1.2   #piston length(m)
W   = 0.6   #piston width(m)

material properties fluid
c   = 343.0 #speed sound in water  (m/s)
rho_a   = 1.21  #density of air (kg/m^3)

piston material properties
E   = 7.0e10#youngs modulus (N/m^2) (stainless 
steel)
nu  = 0.29  #poisson's ratio (stainless steel
rho = 2700.0#density of piston (stainless steel) 
(kg/m^3)
t   = 0.0015#piston thickness (m)

wave speed, wave number, frequency
c_l = (E/(rho*(1 - nu**2)))**0.5#longitudinal wave speed in 
piston
k_x = n*pi/W#wave number x direction
k_y = m*pi/L#wave number y direction
k_mn= (k_x[mode_n]**2 + k_y[mode_m]**2)**0.5#bending wave number for n 
and m mode
w_c = (c**2)/(1.8*c_l*t)#critical frequency (Hz)
w_mn= (k_mn**2)*1.8*c_l*t/(2.0*pi)**2   #frequency for n and m (see 
notes 5/15/06)
k_c = 2.0*pi*(w_c/(1.8*c_l*t))**0.5 #critical wave number
k_a = 2.0*pi*w_mn/c#wave number in 
acoustic medium (air)

piston grid
dx  = 1.0/k_a   #x direction step in space   (m)
dy  = 1.0/k_a   #y direction step in space   (m)

if dx  0.005:
dx = 0.005
dy = 0.005

num_y   = int(L/dy) #number of nodes in y direction
num_x   = int(W/dx) #number of nodes in x direction

#piston grid coordinates
x_coord = arange(num_x, dtype=float)*W/num_x - W/2.0
y_coord = arange(num_y, dtype=float)*L/num_y - L/2.0

field grid
a   = 1
b   = 50
d   = 50
x_r = arange(a, dtype=float)*1.0/float(a) #x position of receiver  (m)
y_r = arange(b, dtype=float)*1.0/float(b) #y position of receiver  (m)
z_r = arange(d, dtype=float)*10.0/float(d)#z position of receiver  (m)

acoustic variables
p   = 0 #amplitude of pressure at receiver   
(Pa)
r   = 0 #distance from origin to receiver(m)
p_field = zeros((a,b,d), dtype=float)   #pressure field  (m)

calculate piston surface velocity amplitude
U_mn= zeros((len(x_coord), len(y_coord)), dtype=float)
for i in range(len(x_coord)):
for j in range(len(y_coord)):
#amplitude of piston surface displacement
U_mn[i][j] = 
sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j]))
#amplitude of piston surface velocity(m/s)
V_mn   = w_mn*U_mn



numerical integration of Raleigh's equation

for i in range(a):
for j in range(b):
for k in range(d):
p_field[i][j][k] = GetPressure(x_coord, y_coord, x_r[i], y_r[j], 
z_r[k], dx, dy, w_mn, rho, V_mn, k_mn, num_x, num_y)
print '%d Percent Complete'%(100.0*j/b)

p_field = 20.0*log10(p_field)

fileHandle  = file('beam pattern.dat', w)
fileHandle.write('TITLE = HW 4\n')
fileHandle.write('VARIABLES = x\ny\nz\npressure\n')
fileHandle.write('ZONE T=%s\n' % 'pressure field')
fileHandle.write('I=%d, J=1, ZONETYPE=Ordered\n' % (a*b*d))
fileHandle.write('DATAPACKING=POINT DT=(DOUBLE DOUBLE DOUBLE DOUBLE)\n')
for ii in range(a):
for jj in range(b):
for kk in range(d):
fileHandle.write('%f %f %f %f\n' % (x_r[ii], y_r[jj], z_r[kk], 
p_field[ii][jj][kk]))
fileHandle.close()




contour of surface velocity


fileHandle  = 

Re: [Tutor] pyexcelerator

2006-06-09 Thread Bob Gailer
Paul D. Kraus wrote:
 Are their docs anywhere for pyexcelerator? the built in docs are a bit 
 lacking.

 For instance I can't figure out how to set a column width.
 I am just reading the examples and they kind of help but I don't 
 follow this ...

 ws.col(i).width = 0x0d00 + i

 where i is an incrementing integer.
 so to me it reads if i = 0.

 set col 0's width to hexnumber plus 0

 why the hex number? does it have to be written this way?
Nothing has to be written in hex. Judging from some of the modules the 
author used hex a lot.

I just looked at my copy of PyExcelerator. It seems to be in poor shape. 
I tried running some of the modules that have if __name__ == '__main__': 
(i.e. self-testing) and they failed with errors! And I find no visible 
documentation or working examples. Sigh.

The only thing I've used it for is parsing an existing Excel Workbook.

-- 
Bob Gailer
510-978-4454

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


[Tutor] problems using PyGTK on cygwin

2006-06-09 Thread Christopher Spears
I have been trying to work throught the PyGTK tutorial
using cygwin, but I have been having problems.  For
example when I try to launch the helloworld.py program
(http://www.pygtk.org/pygtk2tutorial/ch-GettingStarted.html#sec-HelloWorld),
I get this:

$ python helloworld.py 
No fonts found; this probably means that the
fontconfig
library is not correctly configured. You may need to
edit the fonts.conf configuration file. More
information
about fontconfig can be found in the fontconfig(3)
manual
page and on http://fontconfig.org

I located the files, but the content is Greek to me!

Likewise, I tried running pygtkconsole.py program
(http://www.pygtk.org/pygtk2tutorial/examples/pygtkconsole.py)
and got

$ python pygtkconsole.py 
  5 [main] python2.4 1360
C:\cygwin\bin\python2.4.exe: *** fatal error - unable
to remap C:\cygwin\usr\X11R6\bin\cygXcursor-1.dll to
same address as parent(0x1887) != 0x188A
  6 [main] python 1588 child_copy: loaded dll data
write copy failed, 0x60084000..0x60085150, done 0,
windows pid 2286452, Win32 error 5
Traceback (most recent call last):
  File pygtkconsole.py, line 119, in ?
interact()
  File pygtkconsole.py, line 101, in interact
gi = GtkInterpreter()
  File pygtkconsole.py, line 81, in __init__
child_pid = os.fork()
OSError: [Errno 11] Resource temporarily unavailable

Any suggestions?  I have been seriously thinking of
just downloading PyGTK for Windows instead of trying
to run it in the faux Unix environment of cygwin.

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


Re: [Tutor] pyexcelerator CORRECTION

2006-06-09 Thread Bob Gailer




Bob Gailer wrote:

  Paul D. Kraus wrote:
  
  
Are their docs anywhere for pyexcelerator? the built in docs are a bit 
lacking.

For instance I can't figure out how to set a column width.
I am just reading the examples and they kind of help but I don't 
follow this ...

ws.col(i).width = 0x0d00 + i

where i is an incrementing integer.
so to me it reads if i = 0.

set col 0's width to hexnumber plus 0

why the hex number? does it have to be written this way?

  
  Nothing has to be written in hex. Judging from some of the modules the 
author used hex a lot.

I just looked at my copy of PyExcelerator. It seems to be in poor shape. 
I tried running some of the modules that have if __name__ == '__main__': 
(i.e. self-testing) and they failed with errors! And I find no visible 
documentation or working examples. Sigh.
  

I was looking in the wrong place. Now I see the examples folder. Double
Sigh. I'll take a look at them.

  
The only thing I've used it for is parsing an existing Excel Workbook.

  



-- 
Bob Gailer
510-978-4454


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


Re: [Tutor] pyexcelerator

2006-06-09 Thread Paul D. Kraus
I just looked at my copy of PyExcelerator. It seems to be in poor shape.I tried running some of the modules that have if __name__ == '__main__':
(i.e. self-testing) and they failed with errors! And I find no visibledocumentation or working examples. Sigh.You might want to check out the recent source from sourceforge its seems very functional and it has a bunch of examples. Not very useful for ones as far as I am concrened.
I have not tried to run the modules by themselves.I hate the idea of having to pass or make a call to a perl script to handle the excel stuff its just seems wrong. I wish there was some kind of *open* format that i could write the spreadsheets to that both open office and excel 2000/2003 could read natively. 
Paul
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] numpy speed problems

2006-06-09 Thread Bob Gailer
Jeff Peery wrote:
 hello, I am having some trouble with the speed of numpy. I'm crunching 
 some numbers (see the attached script) and in total I have 1,000,000 
 grid points over which I am integrating. I'm doing a bunch of adding, 
 mulitply, divide, powers, etc, but in total there are 1,000,000 points 
 to do these operations over and it really shouldn't take this long... 
 as far as I know. my last simulation took about 8+ hours.

 What might I be doing wrong in my code to cause this to be so slow? 
 big thanks!!
I don't have time to analyze all your code but I'll point out that it is 
repeating some calculations many times. Example:

x_coord[ii])**2.0
y_coord[jj])**2.0 


are calculated every time GetPressure is called. I suggest you calculate 
these one time outside any loops and pass the result into GetPressure.

Inside GetPressure:

1j*w_mn*rho
exp(1j*k_mn*r)*dx*dy/(2.0*pi*r


are repeatedly calculated inside the for loop. Move them out of the loop.

Then look for other loop invariants.

sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j]))

is another place to look.


 

 from numpy import *

 
 function definitions
 
 def GetPressure(x_coord, y_coord, x_r, y_r, z_r, dx, dy, w_mn, rho, v_mn, 
 k_mn, n, m):
 #   intialize pressure
 p   = 0.0 + 1j

 #   sum contributions from all point sources to receiver
 for ii in range(n):
 for jj in range(m):
 r   = ((x_r  - x_coord[ii])**2.0 + (y_r - y_coord[jj])**2.0 + 
 (z_r - 0.0)**2)**0.5
 p   +=  (1j*w_mn*rho*v_mn[ii][jj])*exp(1j*k_mn*r)*dx*dy/(2.0*pi*r)

 p   = sqrt(p*conjugate(p))
 return abs(p)

 
 
 vaiables and constants
 

 problem definition parameter
 n   = arange(1,70) #mode number in x direction
 m   = arange(1,70) #mode number in y direction
 mode_n  = 10  #mode number - 1
 mode_m  = 10   #mode number - 1
 L   = 1.2   #piston length(m)
 W   = 0.6   #piston width(m)

 material properties fluid
 c   = 343.0 #speed sound in water  (m/s)
 rho_a   = 1.21  #density of air (kg/m^3)

 piston material properties
 E   = 7.0e10#youngs modulus (N/m^2) (stainless 
 steel)
 nu  = 0.29  #poisson's ratio (stainless steel
 rho = 2700.0#density of piston (stainless steel) 
 (kg/m^3)
 t   = 0.0015#piston thickness (m)

 wave speed, wave number, frequency
 c_l = (E/(rho*(1 - nu**2)))**0.5#longitudinal wave speed 
 in piston
 k_x = n*pi/W#wave number x direction
 k_y = m*pi/L#wave number y direction
 k_mn= (k_x[mode_n]**2 + k_y[mode_m]**2)**0.5#bending wave number for 
 n and m mode
 w_c = (c**2)/(1.8*c_l*t)#critical frequency (Hz)
 w_mn= (k_mn**2)*1.8*c_l*t/(2.0*pi)**2   #frequency for n and m 
 (see notes 5/15/06)
 k_c = 2.0*pi*(w_c/(1.8*c_l*t))**0.5 #critical wave number
 k_a = 2.0*pi*w_mn/c#wave number in 
 acoustic medium (air)

 piston grid
 dx  = 1.0/k_a   #x direction step in space   (m)
 dy  = 1.0/k_a   #y direction step in space   (m)

 if dx  0.005:
 dx = 0.005
 dy = 0.005
 
 num_y   = int(L/dy) #number of nodes in y direction
 num_x   = int(W/dx) #number of nodes in x direction

 #piston grid coordinates
 x_coord = arange(num_x, dtype=float)*W/num_x - W/2.0
 y_coord = arange(num_y, dtype=float)*L/num_y - L/2.0

 field grid
 a   = 1
 b   = 50
 d   = 50
 x_r = arange(a, dtype=float)*1.0/float(a) #x position of receiver  (m)
 y_r = arange(b, dtype=float)*1.0/float(b) #y position of receiver  (m)
 z_r = arange(d, dtype=float)*10.0/float(d)#z position of receiver  (m)

 acoustic variables
 p   = 0 #amplitude of pressure at receiver   
 (Pa)
 r   = 0 #distance from origin to receiver
 (m)
 p_field = zeros((a,b,d), dtype=float)   #pressure field  (m)

 calculate piston surface velocity amplitude
 U_mn= zeros((len(x_coord), len(y_coord)), dtype=float)
 for i in range(len(x_coord)):
 for j in range(len(y_coord)):
 #amplitude of piston surface displacement
 U_mn[i][j] = 
 sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j]))
 #amplitude of piston surface velocity(m/s)
 V_mn   = w_mn*U_mn


 
 numerical integration of Raleigh's equation
 
 for i in range(a):
 for j in range(b):
 for k in range(d):
 p_field[i][j][k] = GetPressure(x_coord, y_coord, x_r[i], y_r[j], 
 z_r[k], dx, dy, w_mn, rho, V_mn, k_mn, num_x, num_y)
 

[Tutor] Difference between popens

2006-06-09 Thread Bernard Lebel
Hi,

I'd like to know what are the differences at the various os.popenX
flavors. I read the documentation and I can see they return file
objects. so what can you do with these file objects? I mean, why
would you need a set of file objects rather than another?

Sorry the difference is very not clear to me.


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


[Tutor] An Introduction and a question

2006-06-09 Thread Michael Sullivan
My name is Michael Sullivan.  I am a 26 year-old college student in
Oklahoma. My wife and I have a small (three PCs) computer network that
we operate out of our home.  We have our own domain (as one could tell
by examining my email address)  I have novice-level experience with VB,
C/C++, Java, and PHP, but I'm just starting out with Python.  

Here's the situation:  My wife likes to play the game Chuzzle, found at
Yahoo Games.  We use primarily Linux, however Chuzzle is written as an
ActiveX control, which only works on Windows.  I have not been able to
get Internet Explorer to work correctly through Wine, so I determined to
write a Chuzzle-like game (with many of my own enhancements) for Linux.
I've been playing around with some Pygame examples lately, and thought
that I'd try writing the game in Python (I've been meaning to learn
Python for years, but just never got around to it.)  Today I started on
writing the game.  I've decided (at least for now) to call my version,
LinePuzzle.  For those of you unfamiliar with Chuzzle, here's the basic
concept:  There are individual pieces of different colors arranged on a
grid.  The pieces can be moved on a line either vertically or
horizontally.  The object of the game is to position three similarly
colored pieces ajacent to each other.  At this point the three pieces
will disappear, and the pieces above them will fall to take their place.
As the levels progress, locks are added so that the player cannot move a
locked piece either horizontally or vertically.  The game is over when
no more pieces can be removed.  

I started my script by creating a class called LinePuzzlePiece which
represents a single coloured piece.  I wanted a random colour chosen
from a list to be assigned to the piece, and then to prove that I had it
set up correctly, I wanted to call a method that would print out the
color of the piece.  Here is my code:

#!/usr/bin/env python

import random
import time
import math

class LinePuzzlePiece:
   This class defines a single playing piece for LinePuzzle
   def __init__(self):
  seed(time)
  index = int(math.floor(uniform(1, 10)))   colorlist = [red,
blue, green yellow, purple]   self.color = colorlist[index]

   def printcolor():
  print self.color

mypiece = LinePuzzlePiece
mypiece.printcolor


I saved the script and made it chmod +x.  However, when I run it, I get
this:

[EMAIL PROTECTED] ~ $ ./linepuzzle.py
[EMAIL PROTECTED] ~ $

Now, I'm no expert, but I really think something should have been
printed, if even a blank line.  What am I doing wrong here?  Why is
nothing printing?  Is my printcolor method even being called
successfully?
-Michael Sullivan-



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


Re: [Tutor] An Introduction and a question

2006-06-09 Thread Andre Roberge
On 6/9/06, Michael Sullivan [EMAIL PROTECTED] wrote:
 My name is Michael Sullivan.  I am a 26 year-old college student in
 Oklahoma. My wife and I have a small (three PCs) computer network that
 we operate out of our home.  We have our own domain (as one could tell
 by examining my email address)  I have novice-level experience with VB,
 C/C++, Java, and PHP, but I'm just starting out with Python.

 Here's the situation:  My wife likes to play the game Chuzzle, found at
 Yahoo Games.  We use primarily Linux, however Chuzzle is written as an
 ActiveX control, which only works on Windows.  I have not been able to
 get Internet Explorer to work correctly through Wine, so I determined to
 write a Chuzzle-like game (with many of my own enhancements) for Linux.
 I've been playing around with some Pygame examples lately, and thought
 that I'd try writing the game in Python (I've been meaning to learn
 Python for years, but just never got around to it.)  Today I started on
 writing the game.  I've decided (at least for now) to call my version,
 LinePuzzle.  For those of you unfamiliar with Chuzzle, here's the basic
 concept:  There are individual pieces of different colors arranged on a
 grid.  The pieces can be moved on a line either vertically or
 horizontally.  The object of the game is to position three similarly
 colored pieces ajacent to each other.  At this point the three pieces
 will disappear, and the pieces above them will fall to take their place.
 As the levels progress, locks are added so that the player cannot move a
 locked piece either horizontally or vertically.  The game is over when
 no more pieces can be removed.

 I started my script by creating a class called LinePuzzlePiece which
 represents a single coloured piece.  I wanted a random colour chosen
 from a list to be assigned to the piece, and then to prove that I had it
 set up correctly, I wanted to call a method that would print out the
 color of the piece.  Here is my code:

 #!/usr/bin/env python

 import random
 import time
 import math

 class LinePuzzlePiece:
This class defines a single playing piece for LinePuzzle
def __init__(self):
   seed(time)
   index = int(math.floor(uniform(1, 10)))   colorlist = [red,
 blue, green yellow, purple]   self.color = colorlist[index]

def printcolor():
   print self.color

 mypiece = LinePuzzlePiece
 mypiece.printcolor

1.  try mypiece.printcolor() instead.

2. I'm cc-ing the pygame user group.  I suggest that future questions
related to pygame be sent over to that group instead.  They are just
as friendly as the folks on the tutor list.

André


 I saved the script and made it chmod +x.  However, when I run it, I get
 this:

 [EMAIL PROTECTED] ~ $ ./linepuzzle.py
 [EMAIL PROTECTED] ~ $

 Now, I'm no expert, but I really think something should have been
 printed, if even a blank line.  What am I doing wrong here?  Why is
 nothing printing?  Is my printcolor method even being called
 successfully?
 -Michael Sullivan-



 ___
 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] An Introduction and a question

2006-06-09 Thread Kent Johnson
Michael Sullivan wrote:
   Here is my code:
 
 #!/usr/bin/env python
 
 import random
 import time
 import math
 
 class LinePuzzlePiece:
This class defines a single playing piece for LinePuzzle
def __init__(self):
   seed(time)
   index = int(math.floor(uniform(1, 10)))   colorlist = [red,
 blue, green yellow, purple]   self.color = colorlist[index]
 
def printcolor():
   print self.color
 
 mypiece = LinePuzzlePiece
 mypiece.printcolor
 
 
 I saved the script and made it chmod +x.  However, when I run it, I get
 this:
 
 [EMAIL PROTECTED] ~ $ ./linepuzzle.py
 [EMAIL PROTECTED] ~ $
 
 Now, I'm no expert, but I really think something should have been
 printed, if even a blank line.  What am I doing wrong here?  Why is
 nothing printing?  Is my printcolor method even being called
 successfully?

No, you have not created a LinePuzzlePiece or called printcolor.

In Python, parentheses are required for function calls. A class or 
function name without the parentheses is a reference to the class or 
function object itself, not a call to the object. This can be very 
useful but it's not what you want!

mypiece = LinePuzzlePiece # This makes mypiece refer to the class, not 
an instace

mypiece.printcolor # This is a reference to a method of the class, but 
you don't do anything with the reference

What you really want:
mypiece = LinePuzzlePiece()
mypiece.printcolor()

Kent



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


[Tutor] Function list that might have a tuple that might have one of its indexs set to 's'

2006-06-09 Thread Paul D. Kraus
I am writing my first python program(at least in a really long time). Its purpose is to take csv or pipe delimintaed files and convert them to html pages. Was going to be excel but its just not worth the headache. Everyone viewing the reports is doing just that viewing simple tables.
I need to scan through a list that contains headers to my table.If one of the elements is a tuple and one of the elements of the tuple is s set self.sort to the index of the tuple in the header list and then replace the element in header with a two field tuple containing everything that was not 's'.
header = ['my first column',('my second num column','s','r'),(' my third num column','r') ]I pass header to a function actually a method but lets pretend its just a plain old function. Be careful reading the below code may cause random strokes. I have woken up twice laying on the floor disoriented :)
Actual code in my working example used to call function ...report.set_header( ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max Talk','r') ] ) def set_header(self,header):
 list = [] for cindex in range(len(header)): if type(()) == type(header[cindex]): for index in range(len(header[cindex]) ): if header[cindex][index] == 's':
 self.sort = cindex for tindex in range(len(header[cindex])): if tindex != index: list.append(header[cindex][tindex]) header[cindex] = tuple(list)
 self.header = header
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between popens

2006-06-09 Thread Dave Kuhlman
On Fri, Jun 09, 2006 at 03:38:58PM -0400, Bernard Lebel wrote:
 Hi,
 
 I'd like to know what are the differences at the various os.popenX
 flavors. I read the documentation and I can see they return file
 objects. so what can you do with these file objects? I mean, why
 would you need a set of file objects rather than another?
 


See documentation at
http://docs.python.org/lib/os-newstreams.html#l2h-1552.

And, notice how the return values from the various versions of
popen are different file types: stdin, stdout, and stderr.

A summary:

- popen() gives you either an input pipe (stdin) or an output
  pipe (stdout) but not both.

- popen2() gives you both an input pipe (stdin) and output pipe
  (stdout).

- popen3() gives you an input pipe (stdin) and output pipe
  (stdout) and an error pipe (stderr).

- popen4() gives you an input pipe and a pipe that combines output
  and errors (stdout and stderr).

Specifically, if you want to run a command, just like you would
with os.system(), but:

1. You want to *either* feed (pipe) text to your command *or* read
   results from your command, use os.popen() and use mode= 'w' or
   'r'.

2. You want to both feed (pipe) text to your command *and* read
   results from your command, use os.popen2().

Etc.

If you get an input pipe, you should write text to that pipe, then
close that stream.  Doing close() is what triggers execution of the
command.

If you get an output pipe, then (after the command runs), read
from that pipe to get the results of your command (i.e. the text
that the command wrote to stdout).

Here is a simple example that uses popen2::

import os

def test():
instream, outstream = os.popen2('grep dave')
instream.write('Line #1\n')
instream.write('Line #2 dave is here\n')
instream.write('Line #3\n')
instream.write('Line #4 dave is also here\n')
instream.write('Line #5\n')
instream.close()
for line in outstream:
print 'Line: %s' % line.rstrip()

test()

Note that there is also a popen module, which has functions with
the same names and functionality:

This functionality is also available in the popen2 module
using functions of the same names, but the return values of
those functions have a different order.

See: http://docs.python.org/lib/module-popen2.html

Hope this helps.

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] An Introduction and a question (continuing)

2006-06-09 Thread Michael Sullivan
OK.  I've got it working this far.  Now I want the script to generate
eight pieces, each with a random colour.  Here's my current code:

#!/usr/bin/env python

import random
import time
import math

class LinePuzzlePiece:
   This class defines a single playing piece for LinePuzzle
   def __init__(self):
  random.seed(time)
  index = int(math.floor(random.uniform(0, 8)))
  colorlist = [red, blue, green, yellow, purple, cyan,
orange, white]
  self.color = colorlist[index]

   def printcolor(self):
  print self.color

piececount = 0
mypiece = [, , , , , , , , ]
while (piececount  9):
   mypiece[piececount] = LinePuzzlePiece()
   mypiece[piececount].printcolor()
   piececount += 1

The problem is that while eight pieces are created and assigned a
colour, the colour is always the same.  I need the colours of the pieces
to be in a somewhat random order.  What am I doing wrong?

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


Re: [Tutor] numpy speed problems

2006-06-09 Thread Dave Kuhlman
On Fri, Jun 09, 2006 at 11:57:32AM -0700, Bob Gailer wrote:
 Jeff Peery wrote:
  hello, I am having some trouble with the speed of numpy. I'm crunching 
  some numbers (see the attached script) and in total I have 1,000,000 
  grid points over which I am integrating. I'm doing a bunch of adding, 
  mulitply, divide, powers, etc, but in total there are 1,000,000 points 
  to do these operations over and it really shouldn't take this long... 
  as far as I know. my last simulation took about 8+ hours.
 
  What might I be doing wrong in my code to cause this to be so slow? 
  big thanks!!
 I don't have time to analyze all your code but I'll point out that it is 
 repeating some calculations many times. Example:
 
 x_coord[ii])**2.0
 y_coord[jj])**2.0 
 
 
 are calculated every time GetPressure is called. I suggest you calculate 
 these one time outside any loops and pass the result into GetPressure.
 
 Inside GetPressure:
 
 1j*w_mn*rho
 exp(1j*k_mn*r)*dx*dy/(2.0*pi*r
 
 
 are repeatedly calculated inside the for loop. Move them out of the loop.
 
 Then look for other loop invariants.
 
 sin(n[mode_n]*pi*(L/2.0+x_coord[i]))*sin(m[mode_m]*pi*(W/2.0+y_coord[j]))
 
 is another place to look.
 

Also, if you are serious about SciPy, NumPy, etc, be sure to visit
http://scipy.org/, *and* check into the mailing lists there.
That's not just for your benefit; if there are problems with
SciPy, the people at that list will want to know about them.

[snip]

Dave


-- 
Dave Kuhlman
http://www.rexx.com/~dkuhlman
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Fwd: Difference between popens

2006-06-09 Thread Ivan Furone
2006/6/9, Bernard Lebel [EMAIL PROTECTED]:
Hi,I'd like to know what are the differences at the various os.popenXflavors. I read the documentation and I can see they return fileobjects. so what can you do with these file objects? I mean, why
would you need a set of file objects rather than another?Sorry the difference is very not clear to me.ThanksBernard___Tutor maillist-
Tutor@python.orghttp://mail.python.org/mailman/listinfo/tutorHello,The common idea behind the various popen implementation is to provide the creation of 
pipes.A pipe is a flavor of a file object.A pipe serves the job to address data from a process to another,but what if sometimes you want to execute a commandout of the parent process on a child process?You should be able to issue the command,catch the result and even to know which way the thing has ended,at times.
If you are familiar with the concept of 'streams',the input,output and error stream are the resource of communication provided by Unix to handle these tasks,respectively.Nevertheless
,at times you don't need to gather data from all the streams,but just to control two of them out of three,for example.The reason could be that of sparing system resources,time or just that you don't need or want to.popen2
,popen3 and popen4 are designed to catch exactly the streams you want to control.So:popen2:returns the file objects corresponding to the child 
stdin and stdout;popen3:returns the file objects corresponding to the child 
stdin,stdout and stderr;popen4:returns the file objects corresponding to the child stdout and stderr (
together as a single object) and stdin.The file objects,you see,are what you normally make use to manipulate data within processes.
They are memory structures which assume peculiar names based on their type : Queues,Semaphores,Pipes and so on...And they can persist a) in the scope of a process b) of a machine session c) on the filesystem (the strongest kind of persistence).
Choosing the right one for each task a matter depending on what you want to do with them.I recognize I'm not being exhaustive but hope that helps.Cheers,Ivan
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] An Introduction and a question (continuing)

2006-06-09 Thread Python
On Fri, 2006-06-09 at 16:28 -0500, Michael Sullivan wrote:
 OK.  I've got it working this far.  Now I want the script to generate
 eight pieces, each with a random colour.  Here's my current code:
 
 #!/usr/bin/env python
 
 import random
 import time
 import math
 
 class LinePuzzlePiece:
This class defines a single playing piece for LinePuzzle
def __init__(self):
   random.seed(time)

The seed allows you to reuse a particular set of random numbers - which
can be highly useful in testing so that successive runs use the same
numbers.  In general, there is no need to call seed.

You are calling seed with the same value every time, a reference to the
time module.  You really wanted:
random.seed(time.time())
I'd recommend simply deleting the call to random.seed.  

If you do find you want to re-use the same set of random numbers, call
seed once right after you import random with a known value.  If your
computer really needs to call seed to randomize effectively, then you
can try seeding with time.time().

   index = int(math.floor(random.uniform(0, 8)))
   colorlist = [red, blue, green, yellow, purple, cyan,
 orange, white]
   self.color = colorlist[index]
 
def printcolor(self):
   print self.color
 
 piececount = 0
 mypiece = [, , , , , , , , ]
 while (piececount  9):
mypiece[piececount] = LinePuzzlePiece()
mypiece[piececount].printcolor()
piececount += 1

A suggestion:
mypieces = []   # pluralize container names
piececount = 9
for x in range(piececount):
 
 The problem is that while eight pieces are created and assigned a
 colour, the colour is always the same.  I need the colours of the pieces
 to be in a somewhat random order.  What am I doing wrong?
 
 ___
 Tutor maillist  -  Tutor@python.org
 http://mail.python.org/mailman/listinfo/tutor
-- 
Lloyd Kvam
Venix Corp

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


Re: [Tutor] An Introduction and a question (continuing)

2006-06-09 Thread Bob Gailer




Michael Sullivan wrote:

  OK.  I've got it working this far.  Now I want the script to generate
eight pieces, each with a random colour.  Here's my current code:

#!/usr/bin/env python

import random
import time
import math

class LinePuzzlePiece:
   """This class defines a single playing piece for LinePuzzle"""
   def __init__(self):
  random.seed(time)
  index = int(math.floor(random.uniform(0, 8)))
  colorlist = ["red", "blue", "green", "yellow", "purple", "cyan",
"orange", "white"]
  self.color = colorlist[index]

   def printcolor(self):
  print self.color

piececount = 0
mypiece = ["", "", "", "", "", "", "", "", ""]
while (piececount  9):
   mypiece[piececount] = LinePuzzlePiece()
   mypiece[piececount].printcolor()
   piececount += 1

The problem is that while eight pieces are created and assigned a
colour, the colour is always the same.  I need the colours of the pieces
to be in a somewhat random order.  What am I doing wrong?
  

random.seed(time) sets the seed to the same value each time. (You are
passing a module object, whose ID becomes the seed). Try
random.seed(time.time()). Also you can set the seed once, then let each
call to uniform get the next "random" number.

Also consider:
mypiece = []
for piececount in range(8):
   mypiece.append(LinePuzzlePiece())
   mypiece[piececount].printcolor()



-- 
Bob Gailer
510-978-4454

BroadbandPhoneServiceforlocalandlongdistance$19.95/moplus1moFree


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


[Tutor] XML: Expletive Deleted

2006-06-09 Thread doug shawhan
I realize XML is going to save us all from something or other, but I just can't get my head around it. 

I have been trying to do what should be a very simple action: Extract values from element tags.

I first grab my data from a website with httplib:


 connection = httplib.HTTPSConnection(serverUrl)
 connection.request(POST, serverDir, buildRequestXml(ReturnAll, 1), buildHttpHeaders())
 response = connection.getresponse()

 from xml.dom.minidom import parse, parseString

 data = "">
 connection.close()
 response = parseString(data)
 itemIDs = response.getElementsByTagName(ItemID)
 response.unlink()


I have tried everything I can find to extract the values from the ItemID elements:

 for item in itemIDs:
  print item

yeilds

DOM Element: ItemID at 0x7f532c0c
DOM Element: ItemID at 0x7f5400cc
DOM Element: ItemID at 0x7f54656c
DOM Element: ItemID at 0x7f54ea0c
DOM Element: ItemID at 0x7f555eac

Okay, no problem. Now all I have to do is figure out which
particlular.string.of.words.interconnected.by.periods to pass to
extract the values.

 for item in itemIDs:
 print item.nodeValue

Seems logical:

None
None
None
None
None

Oh for crying out loud ...

Hmmm ... I have saved the output from response.read() to a file and
sure enough, amid all the other element tags, I find the expected
values in ItemID

My problem is: I'm ignorant. I don't know whether my data is being
returned from parseString() as text, or a list or a beautiful rainbow
made of skittles and pixie droppings. The Python/XML howto and
the bajillion other XML made clear to YOU! sites I have looked at
have left me more confused ... I'm just completely lost in the
(apparently arbitrary) nomeclature of lists, nodes, elements, trees,
habitrails and intestines. (Yes, I'm just complaining now, but dang it!
I'm frustrated!

*ahem*

Could someone kindly point out where I am going wrong and perhaps send
me to a very *practical* introduction to reading data from a dom?

Thanks!




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


[Tutor] Is there a better way to write this function?

2006-06-09 Thread Paul D. Kraus
This is a second... the first one never hit the list. *shrug* should i be using a different interface to post? is this a gateway to newsgroup?I am writing my first python program(at least in a really long time).
Its purpose is to take csv or pipe delimintaed files and convert them
to html pages. Was going to be excel but its just not worth the
headache. Everyone viewing the reports is doing just that viewing
simple tables.
I need to scan through a list that contains headers to my table.If
one of the elements is a tuple and one of the elements of the tuple is
s set self.sort to the index of the tuple in the header list and then
replace the element in header with a two field tuple containing
everything that was not 's'.
header = ['my first column',('my second num column','s','r'),(' my third num column','r') ]I
pass header to a function actually a method but lets pretend its just a
plain old function. Be careful reading the below code may cause random
strokes. I have woken up twice laying on the floor disoriented :)
Actual code in my working example used to call function ...report.set_header( ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max Talk','r') ] ) def set_header(self,header):
 list = [] for cindex in range(len(header)): if type(()) == type(header[cindex]): for index in range(len(header[cindex]) ): if header[cindex][index] == 's':
 self.sort = cindex for tindex in range(len(header[cindex])): if tindex != index: list.append(header[cindex][tindex]) header[cindex] = tuple(list)
 self.header = header
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Difference between popens

2006-06-09 Thread Alan Gauld
 I'd like to know what are the differences at the various os.popenX
 flavors. I read the documentation and I can see they return file
 objects. so what can you do with these file objects? I mean, why
 would you need a set of file objects rather than another?

My OS topic covers some of the popen variants with explanation.
It might help.

Here are the most relevant two paragraphs:

--
In fact there are several variations of the popen command called 
popen, popen2, popen3 and popen4. The numbers refer to the various 
data stream combinations that are made available. The standard data 
streams were described in a sidebar in the Talking to the User topic. 
The basic version of popen simply creates a single data stream where 
all input/output is sent/received depending on a mode parameter passed 
to the function. In essence it tries to make executing a command look 
like using a file object.

By contrast, popen2 offers two streams, one for standard output and 
another for standard input, so we can send data to the process and 
read the output without closing the process. popen3 provides stderr 
access in addition to stdin/stdout. Finally there is popen4 that 
combines stderr and stdout into a single stream which appears very 
like normal console output. In Python 2.4 all of these popen calls 
have been superseded by a new Popen class found in a new subprocess 
module which we will look at later. For now we will only look at the 
standard os.popen() function, the others I will leave as a research 
exercise!

---

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] XML: Expletive Deleted

2006-06-09 Thread Danny Yoo
 from xml.dom.minidom import parse, parseString

 data = response.read()
 connection.close()
 response = parseString(data)
 itemIDs = response.getElementsByTagName(ItemID)
 response.unlink()
 ^


Hi Doug,

What's going on here?  Why unlink()?



 Okay, no problem. Now all I have to do is figure out which 
 particlular.string.of.words.interconnected.by.periods to pass to extract 
 the values.

 for item in itemIDs:
 print item.nodeValue


You may want to look at the minidom example here:

 http://www.python.org/doc/lib/dom-example.html

Does this help?
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Function list that might have a tuple that might have one of its indexs set to 's'

2006-06-09 Thread Paul D. Kraus
I am writing my first python program(at least in a really long time).
Its purpose is to take csv or pipe delimited files and convert them
to html pages. Was going to be excel but its just not worth the
headache. Everyone viewing the reports is doing just that viewing
simple tables.
I need to scan through a list that contains headers to my table.If
one of the elements is a tuple and one of the elements of the tuple is
s set self.sort to the index of the tuple in the header list and then
replace the element in header with a two field tuple containing
everything that was not 's'.
header = ['my first column',('my second num column','s','r'),(' my third num column','r') ]I
pass header to a function actually a method but lets pretend its just a
plain old function. Be careful reading the below code may cause random
strokes. I have woken up twice laying on the floor disoriented :)
Actual code in my working example used to call function ...report.set_header( ['','Ext','Name','',('Calls','r','s'),('Ring','r'),('Talk','r'),('Wait','r'),('Max Talk','r') ] ) def set_header(self,header):
 list = [] for cindex in range(len(header)): if type(()) == type(header[cindex]): for index in range(len(header[cindex]) ): if header[cindex][index] == 's':
 self.sort = cindex for tindex in range(len(header[cindex])): if tindex != index: list.append(header[cindex][tindex]) header[cindex] = tuple(list)
 self.header = headerTIA,Paul
___
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor