PythonQt 1.0 released

2007-05-09 Thread Florian Link
We are proud to announce the PythonQt 1.0 major release,
a dynamic and lightweight script binding of the Qt4
framework to the Python language.
Various aspects have been improved since the initial release both on 
functionality and performance side. A number of examples have been added 
to make it easier to get started.

Details on the new functionality can be found at:

http://pythonqt.sourceforge.net/
http://sourceforge.net/projects/pythonqt/

So if you want to embedd Python into your Qt application,
PythonQt is the way to go!

-- 

Florian Link
MeVis Research
Universitaetsallee 29,  D-28359 Bremen,  Germany
http://www.mevis.de  email: [EMAIL PROTECTED]
voice: +49 421 218 7772,   fax: +49 421 218 4236



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

Support the Python Software Foundation:
http://www.python.org/psf/donations.html


CPU usage.

2007-05-09 Thread Navid Parvini
Dear All,
   
  I want to get the CPU usage in my code. 
 Is there any module in Python to get it?
  Also I want to get in on Windows and Linux.
   
  Thank you in advance.
  Navid

   
-
Ahhh...imagining that irresistible new car smell?
 Check outnew cars at Yahoo! Autos.-- 
http://mail.python.org/mailman/listinfo/python-list

Re: interesting exercise

2007-05-09 Thread Charles Sanders
Michael Tobis wrote:
 Here is the bloated mess I came up with. I did see that it had to be
 recursive, and was proud of myself for getting it pretty much on the
 first try, but the thing still reeks of my sorry old fortran-addled
 mentality.

Recursion is not necessary, but is much, much clearer.

Here is one non-recursive version from another aging
fortran programmer. I agree it is less clear than most
of the recursive alternatives. No checks for sorted
input etc, these are left as an exercise for the reader.

def permute( s, n ):
   def _perm( m, n ):
 ilist = [0]*n
 while True:
   yield ilist
   i = n-1
   while i = 0 and ilist[i]=m-1: i = i - 1
   if i = 0:
 ilist = ilist[0:i] + [ilist[i]+1] + [0]*(n-i-1)
   else:
 return

   return [ ''.join([s[i] for i in ilist])
 for ilist in _perm(len(s),n) ]

print permute('abc',2) = , permute('abc',2)
print len(permute('13579',3)) = , len(permute('13579',3))

permute('abc',2) =  ['aa', 'ab', 'ac', 'ba', 'bb', 'bc',
'ca', 'cb', 'cc']
len(permute('13579',3)) =  125

or even this monstrosity ...

def permute2( s, n ):
   return [ ''.join([ s[int(i/len(s)**j)%len(s)]
 for j in range(n-1,-1,-1)])
   for i in range(len(s)**n) ]

print permute2('abc',2) =, permute2('abc',2)
print len(permute2('13579',3)) =, len(permute2('13579',3))

permute2('abc',2) = ['aa', 'ab', 'ac', 'ba', 'bb', 'bc',
  'ca', 'cb', 'cc']
len(permute2('13579',3)) = 125


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


Minor bug in tempfile module (possibly __doc__ error)

2007-05-09 Thread James T. Dennis


 Tonight I discovered something odd in the __doc__ for tempfile
 as shipped with Python 2.4.4 and 2.5: it says:

This module also provides some data items to the user:

  TMP_MAX  - maximum number of names that will be tried before
 giving up.
  template - the default prefix for all temporary names.
 You may change this to control the default prefix.

 ... which would lead one to think that the following code would work:

 import tempfile
 tempfile.template = 'mytest'
 tf = tempfile.NamedTemporaryFile()
 tf.name
'/tmp/mytest-XX'

 It doesn't.

 In fact I realized, after reading through tempfile.py in /usr/lib/...
 that the following also doesn't work like I'd expect:

# foo.py
tst = foo
def getTst(arg):
return foo-%s % arg


# bar.py
import foo
foo.tst = bar
print foo.getTst(testing)

foo-testing - NOT bar-testing

 Now I would feel like a real idiot if I'd come across that in the
 foo/bar case here ... because I clearly don't understand quite *why*
 I can't monkey patch this value.  I would ... but I don't.

 First, I wouldn't have written code like this foo/bar stuff; except
 to test my hypothesis about why changes to tempfile.template don't
 actually affect the values seen by functions in the tempfile namespace.

 Secondly, the author(s) of the tempfile module apparently didn't
 understand this either.  And no one else even noticed that the __doc__
 is wrong (or at least misleading -- since the only way I can see to
 change tempfile.template is to edit the .py file!

 So, I don't feel like an idiot.  But I am curious ...

 ... why can't I change that value in that other namespace?  Is it
 a closure?  (Or like a closure?)  Where is this particular aspect
 of the import/namespace semantics documented?


-- 
Jim Dennis,
Starshine: Signed, Sealed, Delivered

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


Re: changing a var by reference of a list

2007-05-09 Thread Jorgen Bodde
Hi Bruno,

Unfortunately SQLAlchemy will be too involved at this point I will
have to rewrite a lot of code to remove my current DB solution and use
that. Howerver I've learned from my mistake and the next project will
use it, as it seems to be a nice way of mapping objects to databases..

I'v solved it by just sending back the record set from sqlite3 because
I noticed sometimes a 1:1 mapping cannot be done from column value to
variable anyway..

Thanks everyone,
- Jorgen
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Designing a graph study program

2007-05-09 Thread Alexander Schliep
andrea [EMAIL PROTECTED] writes:

 Well then I wanted to draw graphs and I found that pydot is working
 really nicely.
 BUT I'd like to do this, an interactive program to see ho the
 algorithms works...
 For example in the breath search first, every time the algorithm
 colors a node, the program should redraw the graphs. Which modules
 should I use for graphics (I use macosX and I'd like something cross
 platforms).

Check out http://gato.sf.net (LGPL license). It does exactly what you
want to do and there is a binary for MacOS X. Algorithms are implemented 
using Gato's graph class and rudimentary visualizations you get for free
by replacing standard data structures (e.g., a vertex queue) by 
animated ones (AnimatedVertexQueue).

There is a Springer textbook forthcoming. We are also starting to collect 
contributed algorithms, which we would like to make available from
our website.

Full disclosure: I am the author of Gato

Best,
Alexander

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


Re: Strange terminal behavior after quitting Tkinter application

2007-05-09 Thread Chris
On May 7, 10:02 pm, Hamilton, William  [EMAIL PROTECTED] wrote:
  From: Chris
   I'll admit to being surprised at seeing a claim that atkinter
   application, started within an interactive session, without a
 mainloop,
   even runs... I could see it maybe happening from Idle, since Idle is
   running atkintermainloop, so the application bindings may have
 just
   become added widgets to the Idle loop (but of course, a second
   mainloop would conflict heavily).

  You can try by building a workingTkinterGUI interactively from the
  standard Python interpreter, and see that the GUI works (i.e.
  processes events) at the same time.

 If you build it as a class (such as the code in Chris's original post)
 it works; if you do it all directly, nothing happens until you run
 mainloop().  It works, but I'm not sure that it was intended to work
 that way.  I think your problem is related to that difference.

Do you have any idea where I should go to find out the differences
between using mainloop() and not using it? So far I have found this
quitting problem (which does not occur on all platforms), and the need
to call update() or update_idletasks() after some operations, but no
others.

 You'll probably be better off creating a new interpreter window as part
 of your program, if you really need access to the interpreter alongside
 your GUI.  You may be able to extract IDLE's interpreter window and use
 it directly.

I really do need access to the interpreter alongside the GUI in my
real program*, since the GUI cannot really offer all the functionality
of the command line (or is a long way from doing so...). I do offer
simple access to the interpreter in my gui (via
code.InteractiveConsole and a text widget, but I agree with the author
of the comp.lang.python posting Has anybody made a Tkinter text
widget into a terminal emulator? (http://groups.google.com/group/
comp.lang.python/browse_thread/thread/a3f223f563205156/
fc729e1de51ca2dc): it's a shame to force people to use a particular
editor. I don't know if she found a solution; I haven't found anything
reasonable yet.


Thanks

* Actually it's not my program, it's an open-source software package
for modelling neural maps: topographica.org. The GUI code is being
reorganized.

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


Re: change of random state when pyc created??

2007-05-09 Thread Peter Otten
Alan Isaac wrote:

 This may seem very strange, but it is true.
 If I delete a .pyc file, my program executes with a different state!

 Can someone explain this to me?

There is nothing wrong with the random module -- you get the same numbers on
every run. When there is no pyc-file Python uses some RAM to create it and
therefore your GridPlayer instances are located in different memory
locations and get different hash values. This in turn affects the order in
which they occur when you iterate over the GridPlayer.players_played set.

Here is a minimal example:

import test # sic

class T:
def __init__(self, name):
self.name = name
def __repr__(self):
return T(name=%r) % self.name

if __name__ == __main__:
print set(T(i) for i in range(4))

$ python2.5 test.py
set([T(name=2), T(name=1), T(name=0), T(name=3)])
$ python2.5 test.py
set([T(name=3), T(name=1), T(name=0), T(name=2)])
$ python2.5 test.py
set([T(name=3), T(name=1), T(name=0), T(name=2)])
$ rm test.pyc
$ python2.5 test.py
set([T(name=2), T(name=1), T(name=0), T(name=3)])

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


Re: Gui thread and async jobs.

2007-05-09 Thread Jarek Zgoda
king kikapu napisał(a):

 Hi, i am reading the book Python Cookbook, 2nd edition and i
 encountered a very handy recipe, the one that is called Combining
 GUIs and Asynchronous I/O with Threads
 
 It is talking about retain a main GUI thread, doing async work with
 worker threads and have both talk through a Queue object to dispatch
 their messages, so the main (GUI) thread remain responsive.
 It has a very good example by using Tkinter and Qt that is indeed
 working. The only point that make me wonder is that the QUI thread has
 to use some polling to check for messages in the Queue.
 
 Author said that another alternatives exists (by not doing polling)
 but the complexity makes them non-practical for the 90% of ocassions.
 I remember in C# we deal with that sort of things with events/
 delegates.
 Hos the same thing is possible in Python, has anyone any link(s) to
 have a look ?

Another option, although not a silver bullet, is to use a message
dispatcher, like Louie (http://www.pylouie.org/). Unfortunately, the
Louie dispatcher seems to be synchronous, so I wouldn't recommend it for
the environment with high density of events. If your application
dispatches a message then sits idle for some time, Louie will fit
perfectly as the queuing of messages will not happen. Otherwise there
would be no advantage other than code simplification. And this counts
always. :)

-- 
Jarek Zgoda

We read Knuth so you don't have to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Plot with scipy

2007-05-09 Thread redcic
Thank you all for your answers. Setting interactive : True is often
suggested to me but it does not solve my problem.
I tried different other things (following your advices) but I still
have the same problem. Maybe the source of my problem is the fact that
I use the SciTE editor. What do you think about that ? Any other
idea ?
Thanks again,
Cédric

On 7 mai, 14:50, [EMAIL PROTECTED] [EMAIL PROTECTED]
wrote:
 On 4 Mai, 15:57, redcic [EMAIL PROTECTED] wrote:

  I've already got this package. I just wanted to try something new.

  However, since you talk about it, I've got a question regarding this
  package. The execution of the code stops after the line:
  pylab.show()
  which is off course the last line of my code. My problem is that I
  have to close the figure window in order to launch my program another
  time. I'd like to be able to launch my program many times with
  different parameters without having to close the figure windows before
  each launch.
  Just so you know, I'm using TkAgg backend.

  Any hint ?

 There's an option in your matplotlibrc file (personal lives in
 $HOME/.matplotlib, default in $PYTHONPATH/matplotlib/mpl-data):

  CONFIGURATION BEGINS HERE
 # the default backend; one of GTK GTKAgg GTKCairo FltkAgg QtAgg TkAgg
 # Agg Cairo GD GDK Paint PS PDF SVG Template
 backend  : TkAgg
 numerix  : numpy  # numpy, Numeric or numarray
 interactive  : True  # 
 seehttp://matplotlib.sourceforge.net/interactive.html
 .

 Take a look at the quoted webpage for details and troubleshooting.

 Bernhard


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


Re: RotatingFileHandler bugs/errors and a general logging question.

2007-05-09 Thread Vinay Sajip
On May 9, 12:52 am, [EMAIL PROTECTED] wrote:
 The infrastructure in which I am work needs the ability to have log
 files written to from multiple instances of the same script and
 potentially from hundreds or more different machines.

 I know that the documentation suggests using a networkloggingserver
 but I wanted to know if anyone had any other solutions to allow us to
 build off of the current pythonloggingpackages.

Dennis is right - the logging system is threadsafe but not safe
against multiple processes (separate Python instances) writing to the
same file. It certainly sounds like you need a scalable solution - and
having each script send the events to a network logging server seems a
good way of handling the scalability requirement. The logger name used
can include the script instance and machine name, e.g. by starting
with hostname.scriptname.scriptpid... The socket server which receives
the events can demultiplex them based on this information and write
them to a central repository in any arrangement you care to implement
(e.g. into one file or several).

Given that the example in the docs is a (basic) working example, is
there any particular reason why you don't want to follow the suggested
approach?

Regards,

Vinay Sajip

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


error in the if, elif, else statement ?

2007-05-09 Thread juan-manuel . behrendt
Hello together,

I wrote a script for the engineering software abaqus/CAE. It worked
well until I implemented a selection in order to variate the variable
lGwU through an if elif, else statement. I am going to post the
first 82 lines of the script, since the error message points at line
80:

from abaqusConstants import *
from abaqus import *

def CreateSchraube(name, l, flag=None, flag2=None):
import part
vp = session.currentViewportName
model = session.sessionState[vp]['modelName']
m = mdb.models[model]
s = m.ConstrainedSketch(name='__profile__', sheetSize=1000.0)
s.ConstructionLine(point1=(0.0, -500.0), point2=(0.0, 500.0))

if flag==1:

  dh = 15.0
  z = 15.0
  dz = 60.0
  d = 72.0
  f = 1.0
  dD = f*62.0
  lGwO = 110.0

  if flag2==11:   # here appears the
beginning of the new impletation in order to variate lGwU
 lGwU = 0.8*d  # you can see these inner
if, elif, else statement 4 times, because
  elif flag2==12:# the outer if, elif,
else statement (which works!) has 4 cases
 lGwU = 1.0*d
  elif flag==13:
 lGwU = 1.2*d
  else: pass

elif flag==2:

  dh = 15.0
  z = 15.0
  dz = 60.0
  d = 72.0
  f = 1.0
  dD = f*62.0
  lGwO = 110.0

  if flag2==11:
 lGwU = 0.8*d
  elif flag2==12:
 lGwU = 1.0*d
  elif flag==13:
 lGwU = 1.2*d
  else: pass

elif flag==3:

  dh = 25.0
  z = 15.0
  dz = 68.0
  d = 80.0
  f = 1.0
  dD = f*71.5
  lGwO = 120.0

  if flag2==11:
lGwU = 0.8*d
  elif flag2==12:
lGwU = 1.0*d
  elif flag==13:
lGwU = 1.2*d
  else: pass

elif flag==4:

 dh = 25.0
  z = 15.0
  dz = 68.0
  d = 80.0
  f = 1.0
  dD = f*71.5
  lGwO = 120.0

  if flag2==11:
lGwU = 0.8*d
  elif flag2==12:
lGwU = 1.0*d
  elif flag==13:
lGwU = 1.2*d
  else: pass

else: pass

xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0),#
this is line 80, where the error message points at
   (d/2, lGwU), (dD/2, (d-dD)/
(2*tan(radians(12)))+lGwU),
   (dD/2, l-lGwO-z-(d-dD)/
(2*tan(radians(20, (d/2, l-lGwO-z), (d/2, l-z), (dh/2, l-z), (dh/
2, -z))

So, a lot of code, I hope somebody will read it.
My Problem ist the error message, which says:

 #* UnboundLocalError: local variable 'lGwU' referenced before
assignment
  #*File C:\ABAQUS_Products\6.6-3\abaqus_plugins\Schraube.py, line
80, in
  #*CreateSchraube
  #* xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0), 

So the error message is quite clear, however it is not suitable to
what I've written in my script, because the local variable 'lGwU' IS
assigned before referenced and, furthermore in line 80 lGwU does not
appear.
Another strange thing is, that the first two cases, where lGwU = 0.8*d
and lGwU = 1.0*d is, do work in my abaqus script.
So the error message only occurs if I choose lGwU = 1.2*d.

I expect a stupid different error, since I am a Python beginner
(please don't be impatient), but I am not seeing it.

Sincerely,

Manu

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


Re: Minor bug in tempfile module (possibly __doc__ error)

2007-05-09 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED], James T. Dennis wrote:

  Tonight I discovered something odd in the __doc__ for tempfile
  as shipped with Python 2.4.4 and 2.5: it says:
 
   This module also provides some data items to the user:
 
 TMP_MAX  - maximum number of names that will be tried before
giving up.
 template - the default prefix for all temporary names.
You may change this to control the default prefix.
 
  ... which would lead one to think that the following code would work:
 
import tempfile
tempfile.template = 'mytest'
tf = tempfile.NamedTemporaryFile()
  tf.name
   '/tmp/mytest-XX'
 
  It doesn't.

The source says:

__all__ = [
NamedTemporaryFile, TemporaryFile, # high level safe interfaces
mkstemp, mkdtemp,  # low level safe interfaces
mktemp,  # deprecated unsafe interface
TMP_MAX, gettempprefix,# constants
tempdir, gettempdir
   ]

Maybe the doc should be clearer in saying constants too.

  Secondly, the author(s) of the tempfile module apparently didn't
  understand this either.  And no one else even noticed that the __doc__
  is wrong (or at least misleading -- since the only way I can see to
  change tempfile.template is to edit the .py file!

You can change it by simply assigning to the name:

In [15]: tempfile.template = 'spam'

In [16]: tempfile.template
Out[16]: 'spam'

If you want to change the outcome of the functions and objects then simply
give the prefix as argument.

In [21]: tempfile.mktemp(prefix='eggs')
Out[21]: '/tmp/eggsBqiqZD'

In [22]: a = tempfile.NamedTemporaryFile(prefix='eric')

In [23]: a.name
Out[23]: '/tmp/ericHcns14'

  ... why can't I change that value in that other namespace?  Is it
  a closure?  (Or like a closure?)  Where is this particular aspect
  of the import/namespace semantics documented?

You *can* change it, but it is not used by the code in that module.

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


MailingLogger 3.0.0 Released!

2007-05-09 Thread Chris Withers
Mailinglogger enables log entries to be emailed either as the entries 
are logged or as a summary at the end of the running process.

This pair of enhanced emailing handlers for the python logging framework 
is now available as a standard python package and as an egg.

The handlers have the following features:

- customisable and dynamic subject lines for emails sent

- emails sent with an X-Mailer header for easy filtering

- flood protection to ensure the number of emails sent is not excessive

- fully documented and tested

In addition, extra support is provided for configuring the handlers when 
using ZConfig, Zope 2 or Zope 3.

Installation is as easy as:

easy_install mailinglogger

For more information, please see: 
http://www.simplistix.co.uk/software/python/mailinglogger

cheers,

Chris

-- 
Simplistix - Content Management, Zope  Python Consulting
- http://www.simplistix.co.uk

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


Re: error in the if, elif, else statement ?

2007-05-09 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
juan-manuel.behrendt wrote:

 Hello together,
 
 I wrote a script for the engineering software abaqus/CAE. It worked
 well until I implemented a selection in order to variate the variable
 lGwU through an if elif, else statement. I am going to post the
 first 82 lines of the script, since the error message points at line
 80:
 
 from abaqusConstants import *
 from abaqus import *
 
 def CreateSchraube(name, l, flag=None, flag2=None):
 import part
 vp = session.currentViewportName
 model = session.sessionState[vp]['modelName']
 m = mdb.models[model]
 s = m.ConstrainedSketch(name='__profile__', sheetSize=1000.0)
 s.ConstructionLine(point1=(0.0, -500.0), point2=(0.0, 500.0))
 
 if flag==1:
 
   dh = 15.0
   z = 15.0
   dz = 60.0
   d = 72.0
   f = 1.0
   dD = f*62.0
   lGwO = 110.0
 
   if flag2==11:   # here appears the
 beginning of the new impletation in order to variate lGwU
  lGwU = 0.8*d  # you can see these inner
 if, elif, else statement 4 times, because
   elif flag2==12:# the outer if, elif,
 else statement (which works!) has 4 cases
  lGwU = 1.0*d
   elif flag==13:
  lGwU = 1.2*d
   else: pass
 
 elif flag==2:
 
   dh = 15.0
   z = 15.0
   dz = 60.0
   d = 72.0
   f = 1.0
   dD = f*62.0
   lGwO = 110.0
 
   if flag2==11:
  lGwU = 0.8*d
   elif flag2==12:
  lGwU = 1.0*d
   elif flag==13:
  lGwU = 1.2*d
   else: pass
 
 elif flag==3:
 
   dh = 25.0
   z = 15.0
   dz = 68.0
   d = 80.0
   f = 1.0
   dD = f*71.5
   lGwO = 120.0
 
   if flag2==11:
 lGwU = 0.8*d
   elif flag2==12:
 lGwU = 1.0*d
   elif flag==13:
 lGwU = 1.2*d
   else: pass
 
 elif flag==4:
 
  dh = 25.0
   z = 15.0
   dz = 68.0
   d = 80.0
   f = 1.0
   dD = f*71.5
   lGwO = 120.0
 
   if flag2==11:
 lGwU = 0.8*d
   elif flag2==12:
 lGwU = 1.0*d
   elif flag==13:
 lGwU = 1.2*d
   else: pass
 
 else: pass
 
 xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0),#
 this is line 80, where the error message points at
(d/2, lGwU), (dD/2, (d-dD)/
 (2*tan(radians(12)))+lGwU),
(dD/2, l-lGwO-z-(d-dD)/
 (2*tan(radians(20, (d/2, l-lGwO-z), (d/2, l-z), (dh/2, l-z), (dh/
 2, -z))
 
 So, a lot of code, I hope somebody will read it.
 My Problem ist the error message, which says:
 
  #* UnboundLocalError: local variable 'lGwU' referenced before
 assignment
   #*File C:\ABAQUS_Products\6.6-3\abaqus_plugins\Schraube.py, line
 80, in
   #*CreateSchraube
   #* xyCoords = ((dh/2, -z), (dz/2, -z), (dz/2, 0), (d/2, 0), 
 
 So the error message is quite clear, however it is not suitable to
 what I've written in my script, because the local variable 'lGwU' IS
 assigned before referenced and, furthermore in line 80 lGwU does not
 appear.

It is not assigned, otherwise you would not get this error.  The line
number is also correct because it's the start of the construct or logical
line where the name is referenced.  Just look at the very next line in
the source.

 Another strange thing is, that the first two cases, where lGwU = 0.8*d
 and lGwU = 1.0*d is, do work in my abaqus script.
 So the error message only occurs if I choose lGwU = 1.2*d.

Take a look at the condition for that case(s).  You are testing `flag`
instead of `flag2`.  Maybe you should have written ``raise SomeError`` or
``assert False`` instead of all those useless ``else: pass``.  If this
branch is taken, obviously `lGwU` is not bound.

Ciao,
Marc 'BlackJack' Rintsch

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


Re: Towards faster Python implementations - theory

2007-05-09 Thread Hendrik van Rooyen
 John Nagle [EMAIL PROTECTED] wrote:

8 summary of existing work and thinking --

 The point here is that we don't need language changes or declarations
 to make Python much faster.  All we need are a few restrictions that
 insure that, when you're doing something unusual, the compiler can
 tell.
 

I am relatively new on this turf, and from what I have seen so far, it
would not bother me at all to tie a name's type to its first use, so that 
the name can only be bound to objects of the same type as the type
of the object that it was originally bound to.

But maybe I am missing the point of dynamism. 

Would an implementation of the above break lots of stuff in practice?

It seems to me that it could have the effect of a declaration without
the wart of actually doing it.

- Hendrik


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


Re: msbin to ieee

2007-05-09 Thread revuesbio
Hi,

I found something interresting.

First, MBF Files come from metastock software but i use another one
(MLDownloader) to get quotes and convert them to MBF format  probably
using  functions you've just described (C, borland,...). In final, all
my files are created by mldownloader.

2nd, I've tried to modify quotes directly in metastock.
And when you read bytes corresponding to zero ... :
'\x00\x00\x00\x00' !


cheers,
Antoine

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


Using the CSV module

2007-05-09 Thread Nathan Harmston
Hi,

I ve been playing with the CSV module for parsing a few files. A row
in a file looks like this:

some_id\t|\tsome_data\t|t\some_more_data\t|\tlast_data\t\n

so the lineterminator is \t\n and the delimiter is \t|\t, however when
I subclass Dialect and try to set delimiter is \t|\t it says
delimiter can only be a character.

I know its an easy fix to just do .strip(\t) on the output I get,
but I was wondering
a) if theres a better way of doing this when the file is actually
being parsed by the csv module
b) Why are delimiters only allowed to be one character in length.

Many Thanks in advance
Nathan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __getattr__ and __getattribute__

2007-05-09 Thread km

Oh thats lucid!
thanks for the explanation.

regards
KM
-
On 5/9/07, Gabriel Genellina [EMAIL PROTECTED] wrote:


En Tue, 08 May 2007 08:22:03 -0300, km [EMAIL PROTECTED]
escribió:

 i find it difficult to understand the difference between the magic
 methods
 __getattr__ and __getattribute__
 and so donot know when to use former or later.
 can someone  brief me on it ?

This is better understood with a bit of history.
On earlier Python versions (before 2.2) the only object model available
was what we now call classic classes.
Classic instances hold their attributes in a dictionary, called __dict__.
Attribute lookup starts at this instance dictionary; if not found,
continues in the class, and its parent class, all along the inheritance
tree. If still not found, __getattr__ (if it exists) is called, and should
return the attribute value or raise AttributeError. That is, __getattr__
is called *last*, and *only* when the attribute was not previously found
in the usual places.

Since Python 2.2, there are new style classes available; they inherit
directly or indirectly from object. A new style instance may not even have
a __dict__. An existing __getattribute__ method is tried *first*; it
should return the attribute value or raise AttributeError. If no custom
__getattribute__ exists, the default object.__getattribute__ is used. As a
last resort, if __getattr__ is defined, it is called.

OTOH, there is a single version of __setattr__, which is always invoked
when setting an attribute.

--
Gabriel Genellina

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

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

Multiple regex match idiom

2007-05-09 Thread Hrvoje Niksic
I often have the need to match multiple regexes against a single
string, typically a line of input, like this:

if (matchobj = re1.match(line)):
  ... re1 matched; do something with matchobj ...
elif (matchobj = re2.match(line)):
  ... re2 matched; do something with matchobj ...
elif (matchobj = re3.match(line)):


Of course, that doesn't work as written because Python's assignments
are statements rather than expressions.  The obvious rewrite results
in deeply nested if's:

matchobj = re1.match(line)
if matchobj:
  ... re1 matched; do something with matchobj ...
else:
  matchobj = re2.match(line)
  if matchobj:
... re2 matched; do something with matchobj ...
  else:
matchobj = re3.match(line)
if matchobj:
  ...

Normally I have nothing against nested ifs, but in this case the deep
nesting unnecessarily complicates the code without providing
additional value -- the logic is still exactly equivalent to the
if/elif/elif/... shown above.

There are ways to work around the problem, for example by writing a
utility predicate that passes the match object as a side effect, but
that feels somewhat non-standard.  I'd like to know if there is a
Python idiom that I'm missing.  What would be the Pythonic way to
write the above code?
-- 
http://mail.python.org/mailman/listinfo/python-list


view workspace, like in MatLab ?

2007-05-09 Thread Stef Mientki
hello,

is there a function / library / IDE that displays all the user defined 
variables,
like the workspace in MatLab ?

thanks,
Stef Mientki
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Multiple regex match idiom

2007-05-09 Thread Charles Sanders
Hrvoje Niksic wrote:
 I often have the need to match multiple regexes against a single
 string, typically a line of input, like this:
 
 if (matchobj = re1.match(line)):
   ... re1 matched; do something with matchobj ...
 elif (matchobj = re2.match(line)):
   ... re2 matched; do something with matchobj ...
 elif (matchobj = re3.match(line)):
 
[snip]
 
 There are ways to work around the problem, for example by writing a
 utility predicate that passes the match object as a side effect, but
 that feels somewhat non-standard.  I'd like to know if there is a
 Python idiom that I'm missing.  What would be the Pythonic way to
 write the above code?

Only just learning Python, but to me this seems better.
Completely untested.

re_list = [ re1, re2, re3, ... ]
for re in re_list:
   matchob = re.match(line)
   if matchob:
 
 break

Of course this only works it the do something is the same
for all matches. If not, maybe a function for each case,
something like

re1 = re.compile()
def fn1( s, m ):
   
re2 = 
def fn2( s, m ):
   

re_list = [ (re1, fn1), (re2, fn2), ... ]

for (r,f) in re_list:
   matchob = r.match(line)
   if matchob:
 f( line, matchob )
 break
 f(line,m)

Probably better ways than this exist.


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


Re: Using the CSV module

2007-05-09 Thread Stefan Sonnenberg-Carstens
Most of the time I found the CSV module not as useful as it might be -
due to the restrictions you describe.

Why not write a simple parser class ?

On Mi, 9.05.2007, 10:40, Nathan Harmston wrote:
 Hi,

 I ve been playing with the CSV module for parsing a few files. A row
 in a file looks like this:

 some_id\t|\tsome_data\t|t\some_more_data\t|\tlast_data\t\n

 so the lineterminator is \t\n and the delimiter is \t|\t, however when
 I subclass Dialect and try to set delimiter is \t|\t it says
 delimiter can only be a character.

 I know its an easy fix to just do .strip(\t) on the output I get,
 but I was wondering
 a) if theres a better way of doing this when the file is actually
 being parsed by the csv module
 b) Why are delimiters only allowed to be one character in length.

 Many Thanks in advance
 Nathan
 --
 http://mail.python.org/mailman/listinfo/python-list



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


Spotting Crashed Application

2007-05-09 Thread Robert Rawlins - Think Blue
Hello Guys,

 

I've got an application that I've written, and it sits in an embedded
system, from time to time the application will crash, I'm not quite sure
what's causing this, but as we test it more and more we'll grasp a better
understanding and fix the issues.

 

However, until then I need a quick solution which can spot the crash and
reboot the system. Is there any generic way of writing a separate
application that'll spot the crash in my main application? If not then i was
thinking about having my core application log itself as 'alive' every 5
minutes or so. My new 'spotter' application can check this log, if it's not
been written too in say 6 minutes then the main app must have crashed, and
it can reboot.

 

Any suggestions on how best to handle this? Obviously finding the bug in my
main app is paramount, but a failsafe will never hurt.

 

Thanks again guys,

 

Rob

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

Re: Using the CSV module

2007-05-09 Thread Nathan Harmston
I ve just finished writing one, I wanted to stay with the batteries
included approach as much as possible though.

Is there anyway I can request a change to the csv module?

Thanks

Nathan

On 09/05/07, Stefan Sonnenberg-Carstens
[EMAIL PROTECTED] wrote:
 Most of the time I found the CSV module not as useful as it might be -
 due to the restrictions you describe.

 Why not write a simple parser class ?

 On Mi, 9.05.2007, 10:40, Nathan Harmston wrote:
  Hi,
 
  I ve been playing with the CSV module for parsing a few files. A row
  in a file looks like this:
 
  some_id\t|\tsome_data\t|t\some_more_data\t|\tlast_data\t\n
 
  so the lineterminator is \t\n and the delimiter is \t|\t, however when
  I subclass Dialect and try to set delimiter is \t|\t it says
  delimiter can only be a character.
 
  I know its an easy fix to just do .strip(\t) on the output I get,
  but I was wondering
  a) if theres a better way of doing this when the file is actually
  being parsed by the csv module
  b) Why are delimiters only allowed to be one character in length.
 
  Many Thanks in advance
  Nathan
  --
  http://mail.python.org/mailman/listinfo/python-list
 
 


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


Re: Multiple regex match idiom

2007-05-09 Thread Nick Vatamaniuc
On May 9, 5:00 am, Hrvoje Niksic [EMAIL PROTECTED] wrote:
 I often have the need to match multiple regexes against a single
 string, typically a line of input, like this:

 if (matchobj = re1.match(line)):
   ... re1 matched; do something with matchobj ...
 elif (matchobj = re2.match(line)):


   ... re2 matched; do something with matchobj ...
 elif (matchobj = re3.match(line)):
 

 Of course, that doesn't work as written because Python's assignments
 are statements rather than expressions.  The obvious rewrite results
 in deeply nested if's:

 matchobj = re1.match(line)
 if matchobj:
   ... re1 matched; do something with matchobj ...
 else:
   matchobj = re2.match(line)
   if matchobj:
 ... re2 matched; do something with matchobj ...
   else:
 matchobj = re3.match(line)
 if matchobj:
   ...

 Normally I have nothing against nested ifs, but in this case the deep
 nesting unnecessarily complicates the code without providing
 additional value -- the logic is still exactly equivalent to the
 if/elif/elif/... shown above.

 There are ways to work around the problem, for example by writing a
 utility predicate that passes the match object as a side effect, but
 that feels somewhat non-standard.  I'd like to know if there is a
 Python idiom that I'm missing.  What would be the Pythonic way to
 write the above code?

Hrvoje,

To make it more elegant I would do this:

1. Put all the ...do somethings... in functions like
re1_do_something(), re2_do_something(),...

2. Create a list of pairs of (re,func) in other words:
dispatch=[ (re1, re1_do_something), (re2, re2_do_something), ... ]

3. Then do:
for regex,func in dispatch:
if regex.match(line):
  func(...)


Hope this helps,
-Nick Vatamaniuc



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


Re: view workspace, like in MatLab ?

2007-05-09 Thread Nick Vatamaniuc
On May 9, 5:00 am, Stef Mientki [EMAIL PROTECTED]
wrote:
 hello,

 is there a function / library / IDE that displays all the user defined 
 variables,
 like the workspace in MatLab ?

 thanks,
 Stef Mientki

Stef,


In the Python interactive prompt you can try:

[var for var in dir() if not (var.startswith('_') or var=='var')]

Example:
---
 a=10
 b=20
 [var for var in dir() if not (var.startswith('_') or var=='var')]
['a', 'b']

---

Hope that helps,
Nick Vatamaniuc

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


Re: Towards faster Python implementations - theory

2007-05-09 Thread Paul Boddie
On 9 May, 08:09, Hendrik van Rooyen [EMAIL PROTECTED] wrote:

 I am relatively new on this turf, and from what I have seen so far, it
 would not bother me at all to tie a name's type to its first use, so that
 the name can only be bound to objects of the same type as the type
 of the object that it was originally bound to.

But it's interesting to consider the kinds of names you could restrict
in this manner and what the effects would be. In Python, the only kind
of name that can be considered difficult to arbitrarily modify at a
distance - in other words, from outside the same scope - are locals,
and even then there are things like closures and perverse
implementation-dependent stack hacks which can expose local namespaces
to modification, although any reasonable conservative Python
implementation would disallow the latter.

In a local namespace you could restrict names in this way, although
I'd argue that with the limitations on locals, you don't gain as much
as you would by restricting other names similarly. However, by
restricting other kinds of names (eg. instance attributes) you have to
start thinking about polymorphism: what if attribute x on instances of
class C can have different types? If you aren't careful, you've
introduced interfaces as the primary mechanism permitting some kind of
polymorphism.

Paul

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


Re: view workspace, like in MatLab ?

2007-05-09 Thread Dave
Stef Mientki S.Mientki-nospam at mailbox.kun.nl writes:

 
 hello,
 
 is there a function / library / IDE that displays all the user defined 
 variables, like the workspace in MatLab ?
 
 thanks,
 Stef Mientki

Using ipython (which I would highly recommend!) you can use the %whos 'magic'
function. This works as follows (with automagic (no % needed) on and pylab
imported):

In [1]: x = 10

In [2]: y = rand(3)

In [3]: z = 'astring'

In [4]: whos
Variable   Type   Data/Info
---
x  int10
y  ndarray[ 0.57395635  0.92184657  0.16277339]
z  strastring

In [5]: reset
Once deleted, variables cannot be recovered. Proceed (y/[n])?  y

In [6]: whos
Interactive namespace is empty.

In [7]:


Note: the %reset 'magic' function works like the Matlab clear all command.

HTH,
Dave

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


Re: replacing string in xml file

2007-05-09 Thread saif . shakeel
On May 8, 4:46 pm, [EMAIL PROTECTED] wrote:
 On May 8, 4:30 pm, Stefan Behnel [EMAIL PROTECTED] wrote:





  [EMAIL PROTECTED] schrieb:

   Hi,
I need to replace a string in xml file with something else.Ex

   - SERVICEPARAMETER id=_775 Semantics=subfunction DDORef=_54
 SHORTNAMErate/SHORTNAME
 LONGNAMErate/LONGNAME
 VALUE role=constant DataType=unsigned value=1 /
 BYTEPOSITION role=position BytePos=1 /
 /SERVICEPARAMETER
   - SERVICEPARAMETER id=_776 Semantics=localId DDORef=_54

Here i have opened an xml
   file(small part is pasted here).I want to replace the word 'localId'
   with 'dataPackageID' wherever it comes in xml file.I tried this but
   didnt work:

   import sys

   file_input = raw_input(Enter The ODX File Path:)
   input_xml = open(file_input,'r')

  This should say

input_xml = open(file_input,'r').read()

   input_xml.replace('localId','dataPackageId')
This gives error  --- AttributeError: 'file'
   object has no attribute 'replace'
   Can someone help me .
 Thanks

  Stefan- Hide quoted text -

  - Show quoted text -

 There is no error now,but the string is not being replaced,It remains
 the same,should we save the opened file or something- Hide quoted text -

 - Show quoted text -

HI,
 Thanks for the reply.that seems to work,but i was doing this
so as to attach it to a bigger code where it will be utilised before a
parsing.

#Input file and Output file path from user

file_input = raw_input(Enter The ODX File Path:)

(shortname,ext)=os.path.splitext(file_input)
f_open_out=shortname+.ini
log=shortname+.xls
test_file=shortname+testxml.xml

saveout = sys.stdout

input_xml = open(file_input,'r')
xmlcont=input_xml.read()
xmlcont=xmlcont.replace('localId','dataPackageId')
output_file = open(test_file,w)
output_file.write(xmlcont)
output_file.close()

f_open=open(f_open_out, 'w')
logfile=open(log,w)

sys.stdout = f_open

#Parse the input file,and check for correct ODX  version

xmldoc = minidom.parse(input_xml)


I am opening 2 more files in addition to the file
where the new xml goes.One file is written using the sys.stdout
command as most of the output has to go there printing takes place in
many places (so cant use f_open.write) each time.
When i attach the part of replacing the string
'localid' in xml file with something else as given above with
xmlcont=xmlcont.replace('localId','dataPackageId')
the code does not run and hangs.Can more than 3 files be opened at a
time .I dotn know what the problem is here.
 Thanks

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


Problems in string replacement

2007-05-09 Thread saif . shakeel
HI,
 Thanks for the reply.that seems to work,but i was doing this
so as to attach it to a bigger code where it will be utilised before
a
parsing.

#Input file and Output file path from user


file_input = raw_input(Enter The ODX File Path:)


(shortname,ext)=os.path.splitext(file_input)
f_open_out=shortname+.ini
log=shortname+.xls
test_file=shortname+testxml.xml


saveout = sys.stdout


input_xml = open(file_input,'r')
xmlcont=input_xml.read()
xmlcont=xmlcont.replace('localId','dataPackageId')
output_file = open(test_file,w)
output_file.write(xmlcont)
output_file.close()


f_open=open(f_open_out, 'w')
logfile=open(log,w)


sys.stdout = f_open


#Parse the input file,and check for correct ODX  version


xmldoc = minidom.parse(input_xml)


I am opening 2 more files in addition to the file
where the new xml goes.One file is written using the sys.stdout
command as most of the output has to go there printing takes place in
many places (so cant use f_open.write) each time.
When i attach the part of replacing the string
'localid' in xml file with something else as given above with
xmlcont=xmlcont.replace('localId','dataPackageId')
the code does not run and hangs.Can more than 3 files be opened at a
time .I dotn know what the problem is here.
 Thanks

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


Questions about bsddb

2007-05-09 Thread sinoodle
Hello,

I need to build a large database that has roughly 500,000 keys, and a
variable amount of data for each key. The data for each key could
range from 100 bytes to megabytes.The data under each will grow with
time as the database is being built.  Are there some flags I should be
setting when opening the database to handle large amounts of data per
key? Is hash or binary tree recommended for this type of job, I'll be
building the database from scratch, so lots of lookups and appending
of data. Testing is showing bt to be faster, so I'm leaning towards
that. The estimated build time is around 10~12 hours on my machine, so
I want to make sure that something won't get messed up in the 10th
hour.

TIA,
JM

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


Re: psycopg2 error

2007-05-09 Thread Luis P. Mendes
Hello Martin,

Em Wed, 09 May 2007 06:17:09 +0200, Martin v. Löwis escreveu:
 ImportError: libpq.so.5: cannot open shared object file: No such file or
 directory
 
 libpq files are readable by the world: [EMAIL PROTECTED] pgsql # ll lib/ -d
 drwxr-xr-x 3 postgres postgres 1528 2007-05-07 23:25 lib/
 
 Don't try this as the root user, but as the one for whom it is failing:
 What does file /usr/local/psql/lib/libpq.so.5 say?
The problem was that I couldn't issue this command.  Permissions were set
incorrectly:
$ ll /usr/local/pg* -d
drwxr-x--- 10 postgres postgres 712 2007-05-08 20:43 /usr/local/pgsql

Once corrected to:
$ ll /usr/local/pg* -d
drwxr-xr-x 10 postgres postgres 712 2007-05-08 20:43 /usr/local/pgsql

I can import psycopg2 fine.

Thank you for your help!

Best regards,

Luis

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


Re: Using the CSV module

2007-05-09 Thread John Machin
On May 9, 6:40 pm, Nathan Harmston [EMAIL PROTECTED]
wrote:
 Hi,

 I ve been playing with the CSV module for parsing a few files. A row
 in a file looks like this:

 some_id\t|\tsome_data\t|t\some_more_data\t|\tlast_data\t\n

 so the lineterminator is \t\n and the delimiter is \t|\t, however when
 I subclass Dialect and try to set delimiter is \t|\t it says
 delimiter can only be a character.

 I know its an easy fix to just do .strip(\t) on the output I get,
 but I was wondering
 a) if theres a better way of doing this when the file is actually
 being parsed by the csv module

No; usually one would want at least to do .strip() on each field
anyway to remove *all* leading and trailing whitespace. Replacing
multiple whitespace characters with one space is often a good idea.
One may want to get fancier and ensure that NO-BREAK SPACE aka nbsp;
(\xA0 in many encodings) is treated as whitespace.

So your gloriously redundant tabs vanish, for free.

 b) Why are delimiters only allowed to be one character in length.

Speed. The reader is a hand-crafted finite-state machine designed to
operate on a byte at a time. Allowing for variable-length delimiters
would increase the complexity and lower the speed -- for what gain?
How often does one see 2-byte or 3-byte delimiters?

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


Boolean confusion

2007-05-09 Thread Greg Corradini

Hello all,
I'm having trouble understanding why the following code evaluates as it
does:

 string.find('020914A','.') and len('020914A')  10
True
 len('020914A')  10 and string.find('020914A','.')
-1

In the 2.4 Python Reference Manual, I get the following explanation for the
'and' operator in 5.10 Boolean operations:
 The expression x and y first evaluates x; if x is false, its value is
returned; otherwise, y is evaluated and the resulting value is returned.

Based on what is said above, shouldn't my first expression (
string.find('020914A','.') and len('020914A')  10) evaluate to
false b/c my 'x' is false? And shouldn't the second expression evaluate to
True?

Thanks for your help
Greg

-- 
View this message in context: 
http://www.nabble.com/Boolean-confusion-tf3715438.html#a10393362
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Boolean confusion

2007-05-09 Thread Diez B. Roggisch
Greg Corradini wrote:

 
 Hello all,
 I'm having trouble understanding why the following code evaluates as it
 does:
 
 string.find('020914A','.') and len('020914A')  10
 True
 len('020914A')  10 and string.find('020914A','.')
 -1
 
 In the 2.4 Python Reference Manual, I get the following explanation for
 the 'and' operator in 5.10 Boolean operations:
  The expression x and y first evaluates x; if x is false, its value is
 returned; otherwise, y is evaluated and the resulting value is returned.
 
 Based on what is said above, shouldn't my first expression (
 string.find('020914A','.') and len('020914A')  10) evaluate to
 false b/c my 'x' is false? And shouldn't the second expression evaluate to
 True?

The first evaluates to True because len(...)  10 will return a boolean -
which is True, and the semantics of the and-operator will return that
value.

And that precisely is the reason for the -1 in the second expression. 

y=-1

and it's just returned by the and.

in python, and is implemented like this (strict evaluation nonwithstanding):

def and(x, y):
if bool(x) == True:
   return y
return x

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


Re: Boolean confusion

2007-05-09 Thread Antoon Pardon
On 2007-05-09, Greg Corradini [EMAIL PROTECTED] wrote:

 Hello all,
 I'm having trouble understanding why the following code evaluates as it
 does:

 string.find('020914A','.') and len('020914A')  10
 True
 len('020914A')  10 and string.find('020914A','.')
 -1

 In the 2.4 Python Reference Manual, I get the following explanation for the
 'and' operator in 5.10 Boolean operations:
  The expression x and y first evaluates x; if x is false, its value is
 returned; otherwise, y is evaluated and the resulting value is returned.

 Based on what is said above, shouldn't my first expression (
 string.find('020914A','.') and len('020914A')  10) evaluate to
 false b/c my 'x' is false? And shouldn't the second expression evaluate to
 True?

The find method doesn't return a boolean, but returns the index where
the substring was found with -1 indicating it wasn't found. If you just
want to check wether one string is a substring of an other, use the in
operator.

 '.' in '020914A' and len('020914A')  10
False
 len('020914A')  10 and  '.' in '020914A'
False

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


Re: error in the if, elif, else statement ?

2007-05-09 Thread John Machin
On May 9, 5:46 pm, [EMAIL PROTECTED] wrote:
 Hello together,

 I wrote a script for the engineering software abaqus/CAE. It worked
 well until I implemented a selection in order to variate the variable
 lGwU through an if elif, else statement. I am going to post the
 first 82 lines of the script, since the error message points at line
 80:

 from abaqusConstants import *
 from abaqus import *

 def CreateSchraube(name, l, flag=None, flag2=None):
 import part
 vp = session.currentViewportName
 model = session.sessionState[vp]['modelName']
 m = mdb.models[model]
 s = m.ConstrainedSketch(name='__profile__', sheetSize=1000.0)
 s.ConstructionLine(point1=(0.0, -500.0), point2=(0.0, 500.0))

 if flag==1:

   dh = 15.0
   z = 15.0
   dz = 60.0
   d = 72.0
   f = 1.0
   dD = f*62.0
   lGwO = 110.0

   if flag2==11:   # here appears the
 beginning of the new impletation in order to variate lGwU
  lGwU = 0.8*d  # you can see these inner
 if, elif, else statement 4 times, because
   elif flag2==12:# the outer if, elif,
 else statement (which works!) has 4 cases

You have an error in your code (flag instead of flag2).

Your coding style is not conducive to ease of maintenance and
avoidance of errors. Here are some suggestions:

Rip out the three-fold repetition of the same code, replace that code
by:

assert 11 = flag2 = 13
lGwU = (flag2 * 0.2 - 1.4) * d

and move it down the end.

Also get rid of any remaining instances of else: pass.

Then consider replacing all those tedious assignments ...

data = (
(15., 15., 60, ..),
(.),
etc,
etc,
)
assert 1 = flag = len(data) == 4
dh, z, dz, .. = data[flag-1]

Then chose some meaningful names instead of flag and flag2.

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


Re: Boolean confusion

2007-05-09 Thread Greg Corradini

Thank you Diez and Antoon for demystifing this problem. I see where I've been
going wrong.

Diez B. Roggisch-2 wrote:
 
 Greg Corradini wrote:
 
 
 Hello all,
 I'm having trouble understanding why the following code evaluates as it
 does:
 
 string.find('020914A','.') and len('020914A')  10
 True
 len('020914A')  10 and string.find('020914A','.')
 -1
 
 In the 2.4 Python Reference Manual, I get the following explanation for
 the 'and' operator in 5.10 Boolean operations:
  The expression x and y first evaluates x; if x is false, its value is
 returned; otherwise, y is evaluated and the resulting value is returned.
 
 Based on what is said above, shouldn't my first expression (
 string.find('020914A','.') and len('020914A')  10) evaluate to
 false b/c my 'x' is false? And shouldn't the second expression evaluate
 to
 True?
 
 The first evaluates to True because len(...)  10 will return a boolean -
 which is True, and the semantics of the and-operator will return that
 value.
 
 And that precisely is the reason for the -1 in the second expression. 
 
 y=-1
 
 and it's just returned by the and.
 
 in python, and is implemented like this (strict evaluation
 nonwithstanding):
 
 def and(x, y):
 if bool(x) == True:
return y
 return x
 
 Diez
 -- 
 http://mail.python.org/mailman/listinfo/python-list
 
 

-- 
View this message in context: 
http://www.nabble.com/Boolean-confusion-tf3715438.html#a10393705
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Boolean confusion

2007-05-09 Thread Greg Corradini



On 2007-05-09, Greg Corradini [EMAIL PROTECTED] wrote:

 Hello all,
 I'm having trouble understanding why the following code evaluates as it
 does:

 string.find('020914A','.') and len('020914A')  10
 True
 len('020914A')  10 and string.find('020914A','.')
 -1

 In the 2.4 Python Reference Manual, I get the following explanation for
 the
 'and' operator in 5.10 Boolean operations:
  The expression x and y first evaluates x; if x is false, its value is
 returned; otherwise, y is evaluated and the resulting value is returned.

 Based on what is said above, shouldn't my first expression (
 string.find('020914A','.') and len('020914A')  10) evaluate to
 false b/c my 'x' is false? And shouldn't the second expression evaluate to
 True?

The find method doesn't return a boolean, but returns the index where
the substring was found with -1 indicating it wasn't found. If you just
want to check wether one string is a substring of an other, use the in
operator.

 '.' in '020914A' and len('020914A')  10
False
 len('020914A')  10 and  '.' in '020914A'
False

Thank you Diez and Antoon for demystifing this problem. I see where I've
been going wrong. 
-- 
View this message in context: 
http://www.nabble.com/Boolean-confusion-tf3715438.html#a10393765
Sent from the Python - python-list mailing list archive at Nabble.com.

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


Re: Specification for win32com.client package

2007-05-09 Thread kyosohma
On May 8, 7:34 am, Tim Golden [EMAIL PROTECTED] wrote:
 Peter Fischer wrote:
  Hello Tim,

  thank you for your answer and sorry for the multiple e-mails. Thank you 
  also for
  the hint on the book. I already read into it in our local library. Its 
  good, but a
  little outdated (Jan. 2000) as I mentioned in

 http://mail.python.org/pipermail/python-list/2007-May/438800.html

 Ah, yes. Didn't spot that. Although the book is outdated,
 so is COM! It's been around in pretty much its present
 format for wasily as long as that.

  Do you know, whether something has changed, since the book was written, in
  the use of the dcomcnfg tool?

 I wouldn't know, but I doubt it; it looks pretty
 old-fashioned to me. Worth checking some microsoft newsgroups.

  I am not clear what steps are necessary under today's WinXP Professional
  to get DCOM run. But it is said that it shouldn't be difficult.

 Certainly I've got no problem running simple stuff. My main
 area of expertise - WMI - uses it under the covers and it
 only gives me problems when there's security involved.

  One short question back to the documentation: I read that 'makepy' could be
  helpful to generate documentation to the package?

 AFAIK, makepy's got nothing to do with the pywin32 docs. It
 can be used to generate a proxy Python module for an
 existing COM package, eg:

 code
 from win32com.client import gencache
 xl = gencache.EnsureDispatch (Excel.Application)

 #
 # Behind the scenes this has called makepy to generate
 # a module which on my machine is under
 # c:\python24\lib\site-packages\win32com\gen_py
 #

 help (xl.__class__)

 /code

 Sorry I can't be more help. I know Mark Hammond follows
 the python-win32 list; I don't know if he follows the
 main Python list, so it might be worth posting to
 python-win32.

 TJG

The win32com module seems to get short shrift, which I could say about
a lot of the win32 modules and other 3rd party modules in general.
However, I have found the following pages helpful for Python and COM:

http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/html/com/win32com/HTML/docindex.html
http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/html/win32/help/process_info.html#pythoncom

And this is good for just general info on win32:

http://aspn.activestate.com/ASPN/docs/ActivePython/2.4/pywin32/win32_modules.html

The wiki idea sounds like a good one. I was thinking about doing some
kind of Python site about the modules and I think the popular 3rd
party ones would be a good place to start, maybe starting with win32.
How much information do you think would need to be on a site like this
to start out with?

Mike

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


Re: Specification for win32com.client package

2007-05-09 Thread Tim Golden
[EMAIL PROTECTED] wrote:
 The wiki idea sounds like a good one. I was thinking about doing some
 kind of Python site about the modules and I think the popular 3rd
 party ones would be a good place to start, maybe starting with win32.
 How much information do you think would need to be on a site like this
 to start out with?

Someone did start a Python Win32 Wiki recently (check the 
python-win32 archives for location etc.) I did mean to put 
things on there myself, but real life has taken over. Often, 
these things just need someone with a bit of oomph to at 
least get the thing going.

I think what's needed (if you're offering :) is for someone 
to put a *framework* in place on such a site which would 
make it easy for anyone to come along and fill in the gaps 
with their particular 3rd-party app or brand of knowledge. 
As I say, someone did start something, but I've not heard 
anything from him since then and I haven't found the time 
myself. If you were to kick something off and actually get 
it going I wouldn't say no.

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


Does RETURN_VALUE always result in an empty stack?

2007-05-09 Thread dwhall
I'm developing PyMite and would like to know a little detail about
Python 2.5's design.  Is it true that when the RETURN_VALUE executes
and pops its argument, that at that point the stack should *always* be
empty?  I mean just the argument stack for that execution frame.  I
want to use this knowledge to test if PyMite is working properly.

thanks,

!!Dean

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


Re: change of random state when pyc created??

2007-05-09 Thread Alan Isaac

Peter Otten [EMAIL PROTECTED] wrote in message
news:[EMAIL PROTECTED]
 Alan Isaac wrote:
 There is nothing wrong with the random module -- you get the same numbers
on
 every run. When there is no pyc-file Python uses some RAM to create it and
 therefore your GridPlayer instances are located in different memory
 locations and get different hash values. This in turn affects the order in
 which they occur when you iterate over the GridPlayer.players_played set.

Thanks!!
This also explains Steven's results.

If  I sort the set before iterating over it,
the anomaly disappears.

This means that currently the use of sets
(and, I assume, dictionaries) as iterators
compromises replicability.  Is that a fair
statement?

For me (and apparently for a few others)
this was a very subtle problem.  Is there
a warning anywhere in the docs?  Should
there be?

Thanks again!!

Alan Isaac


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


Re: change of random state when pyc created??

2007-05-09 Thread Diez B. Roggisch
Alan Isaac wrote:

 
 Peter Otten [EMAIL PROTECTED] wrote in message
 news:[EMAIL PROTECTED]
 Alan Isaac wrote:
 There is nothing wrong with the random module -- you get the same numbers
 on
 every run. When there is no pyc-file Python uses some RAM to create it
 and therefore your GridPlayer instances are located in different memory
 locations and get different hash values. This in turn affects the order
 in which they occur when you iterate over the GridPlayer.players_played
 set.
 
 Thanks!!
 This also explains Steven's results.
 
 If  I sort the set before iterating over it,
 the anomaly disappears.
 
 This means that currently the use of sets
 (and, I assume, dictionaries) as iterators
 compromises replicability.  Is that a fair
 statement?

Yes.
 
 For me (and apparently for a few others)
 this was a very subtle problem.  Is there
 a warning anywhere in the docs?  Should
 there be?

Not really, but that depends on what you know about the concept of sets and
maps as collections of course.

The contract for sets and dicts doesn't imply any order whatsoever. Which is
essentially the reason why

set(xrange(10))[0]

doesn't exist, and quite a few times cries for an ordered dictionary as part
of the standard libraries was made.

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


Re: N00b question on Py modules

2007-05-09 Thread Sion Arrowsmith
 [EMAIL PROTECTED] wrote:
Thanks a lot for the responses ppl. Python's treatment of global
variables was an eye-opener. I have coded in Java  C/C++ in the past
and there the behaviour is diametrically opposite.

How so? Python style gurus discourage use of global variables. So
does all the C++ (and to a lesser extent C) advice I've ever
encountered. And Java outright forbids the concept. It's one area
where there seems to be universal agreement.

-- 
\S -- [EMAIL PROTECTED] -- http://www.chaos.org.uk/~sion/
   Frankly I have no feelings towards penguins one way or the other
-- Arthur C. Clarke
   her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Simulating simple electric circuits

2007-05-09 Thread Bjoern Schliessmann
Stef Mientki wrote:
 Bjoern Schliessmann wrote:

 - sources (here begin currents)
 - ground (here end currents)

 that doesn't bring you anywhere ;-)

It does :)

 Current doesn't start or end at some location,
 current flows through a closed circuit.

The part I omit is the voltage source. All currents I need in my
system flow from plus to ground.

 And let's forget about capacitors, inductors and semi-conductors
 for this moment !

Yep, because I largely don't have any here, only in few special
cases (where I also can use some kind of current priority).
 
 Here is a simulation package, although designed for MatLab,
 it might give you a good idea of what your need.
http://www.swarthmore.edu/NatSci/echeeve1/Ref/mna/MNA6.html

Wow ... Overkill :)

 There are few simulation related packages,
 but not directly suited for electronics
 http://www.mcs.vuw.ac.nz/cgi-bin/wiki/SimPy

I once looked at this, but couldn't find out how to use it with my
problem. :\

 http://www.linuxjournal.com/article/7542
 http://pyastra.sourceforge.net/
 http://www.nelsim.com/scriptsim/python_man.html

Those are all a bit daunting ...
 
 As an little test I wrote a PIC simulator (only core) in Python,
 it's very rough code (generated in a few evenings),
 if you're interested I could look it up.

Thank you for the offer. I'm presently having problems understanding
even the examples, so I'll call in if I get so far.

Regards,


Björn

-- 
BOFH excuse #380:

Operators killed when huge stack of backup tapes fell over.

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


IDLE can't import Tkinter

2007-05-09 Thread Romain FEUILLETTE

Hello,

I'have just install Python 2.5.1 on Linux and the IDLE doesn't seem to
works because it didn't find Tcl/Tk

Is there someone to explain how to modify the file setup.py
to tell the install that Tcl/Tk are at the paht : /usr/bin/tclsh and 
usr/bin/wish/ ?


I have attached to log file of my terminal.

Thanks a lot in advance.

Romain


[EMAIL PROTECTED] : ll
total 8212
drwxr-s---   19 fr18 Dk_pcell 4096 May  3 15:14 ./
drwxr-s---3 fr18 Dk_pcell 4096 May  3 14:01 ../
-rw-r-1 fr18 Dk_pcell77512 May  3 15:15 
2007_05_03_1505_python_install.log
drwxr-s---5 fr18 Dk_pcell 4096 May  3 10:12 build/
-rw-r-1 fr18 Dk_pcell   336280 May  3 10:09 config.log
-rwxr-x---1 fr18 Dk_pcell57416 May  3 10:09 config.status*
-rwxr-x---1 fr18 Dk_pcell   637991 Mar 12 11:50 configure*
-rw-r-1 fr18 Dk_pcell96904 Mar 12 11:50 configure.in
drwxr-s---   22 fr18 Dk_pcell 4096 Apr 18 05:56 Demo/
drwxr-s---   24 fr18 Dk_pcell 4096 Apr 18 06:01 Doc/
drwxr-s---2 fr18 Dk_pcell 4096 Apr 18 05:56 Grammar/
drwxr-s---2 fr18 Dk_pcell 8192 Apr 18 05:55 Include/
-rwxr-x---1 fr18 Dk_pcell 7122 Jun 14  2003 install-sh*
drwxr-s---   42 fr18 Dk_pcell20480 May  3 15:14 Lib/
-rw-r-1 fr18 Dk_pcell  3949072 May  3 15:14 libpython2.5.a
-rw-r-1 fr18 Dk_pcell13615 Apr  5 06:52 LICENSE
drwxr-s---   11 fr18 Dk_pcell 4096 Apr 18 05:57 Mac/
-rw-r-1 fr18 Dk_pcell38219 May  3 10:09 Makefile
-rw-r-1 fr18 Dk_pcell35107 May  3 10:09 Makefile.pre
-rw-r-1 fr18 Dk_pcell35070 Dec  8 21:46 Makefile.pre.in
drwxr-s---4 fr18 Dk_pcell 4096 Apr 18 05:56 Misc/
drwxr-s---7 fr18 Dk_pcell12288 May  3 15:14 Modules/
drwxr-s---3 fr18 Dk_pcell 8192 May  3 15:14 Objects/
drwxr-s---2 fr18 Dk_pcell 4096 May  3 15:14 Parser/
drwxr-s---8 fr18 Dk_pcell 4096 Apr 18 05:58 PC/
drwxr-s---2 fr18 Dk_pcell 4096 Apr 18 05:55 PCbuild/
drwxr-s---2 fr18 Dk_pcell 4096 Apr 18 06:08 PCbuild8/
-rw-r-1 fr18 Dk_pcell28357 May  3 10:09 pyconfig.h
-rw-r-1 fr18 Dk_pcell27049 Oct 27  2006 pyconfig.h.in
-rwxr-x---1 fr18 Dk_pcell  2661658 May  3 15:14 python*
drwxr-s---2 fr18 Dk_pcell 8192 May  3 15:14 Python/
-rw-r-1 fr18 Dk_pcell77512 May  3 14:51 python_install.log
-rw-r-1 fr18 Dk_pcell55678 Apr  5 06:52 README
drwxr-s---5 fr18 Dk_pcell 4096 Apr 18 05:58 RISCOS/
-rw-r-1 fr18 Dk_pcell67931 May  3 15:18 setup.py
drwxr-s---   19 fr18 Dk_pcell 4096 Apr 18 05:58 Tools/

[EMAIL PROTECTED] : build/scripts-2.5/idle
** IDLE can't import Tkinter.  Your Python may not be configured for Tk. **


[EMAIL PROTECTED] : which wish
/usr/bin/wish
[EMAIL PROTECTED] : wish
% [EMAIL PROTECTED] : which tclsh
/usr/bin/tclsh
[EMAIL PROTECTED] : tclsh
% info tcl
8.3
% exit

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

Re: String parsing

2007-05-09 Thread HMS Surprise

 This looks to be simple HTML (and I'm presuming that's a type on
 that ? ending). A quick glance at the Python library reference (you do
 have a copy, don't you) reveals at least two HTML parsing modules...


No that is not a typo and bears investigation. Thanks for the find.

I found HTMLParser but had trouble setting it up.

 About five minutes work gave me this:


My effort has been orders of magnitude greater in time.

Thanks all for all the excellent suggestions.


jh

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


Re: Questions about bsddb

2007-05-09 Thread Nick Vatamaniuc
On May 9, 8:23 am, [EMAIL PROTECTED] wrote:
 Hello,

 I need to build a large database that has roughly 500,000 keys, and a
 variable amount of data for each key. The data for each key could
 range from 100 bytes to megabytes.The data under each will grow with
 time as the database is being built.  Are there some flags I should be
 setting when opening the database to handle large amounts of data per
 key? Is hash or binary tree recommended for this type of job, I'll be
 building the database from scratch, so lots of lookups and appending
 of data. Testing is showing bt to be faster, so I'm leaning towards
 that. The estimated build time is around 10~12 hours on my machine, so
 I want to make sure that something won't get messed up in the 10th
 hour.

 TIA,
 JM

JM,

How will you access your data?
If you access the keys often in a sequencial manner, then bt is
better.

In general, the rule is:

1) for small data sets, either one works
2) for larger data sets, use bt. Also, bt is good for sequential key
access.
3) for really huge data sets where the metadata of the the btree
cannot even fit in the cache, the hash will be better. The reasoning
is since the metadata is larger than the cache there will be at least
an I/O operation, but with a btree there might be mulple I/O to just
find the key because the tree is not all in the memory and will have
multiple levels.

Also consider this:
I had somewhat of a similar problem. I ended up using MySQL as a
backend. In my application, the data actually was composed of a number
of fields and I wanted to select based on some of those fields as well
(i.e. select based on part of the value, not just the keys).  and thus
needed to have indices for those fields. The result was that my disk I/
O was saturated (i.e. the application was running as fast as the hard
drive would let it), so it was good enough for me.

Hope this helps,
-Nick Vatamaniuc

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


Re: Simulating simple electric circuits

2007-05-09 Thread Bjoern Schliessmann
Dave Baum wrote:
 Are you trying to do logic simulation (digital) or analog circuit
 simulation?

Mh, a mix of both :) I want to simulate (in principle simple)
magnetic relay circuits. The only evil tricks that are used are 

- shortcuts (e. g. a relay coil is bypassed and thus the relay gets
  no voltage and it relaxes)
- low currents (so a relay has current but doesn't switch)

 I don't want to go into too much more detail about this one
 because I have a hunch you are really looking at digital, but if
 you're interested in the analog approach let me know and I'll fill
 in more of the details.

Good hunch :) But thanks for the explanations. The fully analog
network approach is definitely overkill here.
 
 For digital:
 
 Event based simulation is typical here.  These simulations
 generally are concerned with voltage, not current.  A circuit
 consists of signals and devices.  At any given time, each signal
 has a certain state (high/low, on/off, 9 level logic, whatever). 
 Devices are connected to one another by signals.  You'll also need
 events (a signal, a time, and a new state), and an event queue
 (events sorted by time).  This is easier if each signal is driven
 by at most one device: 
  
 1) pop the next event off the queue
 2) if the event's signal's state is the same as the new state, go
 to 1 
 3) set the event's signal's state to the new state 
 4) for each device that is attached to the signal, run the
 device's code, which should look at all of its inputs, and post
 new events to the queue for any outputs (do this even if the
 computed output is the same as the current output).  These events
 are usually posted for some time in the future (1
 simulation 'tick' is fine).  
 5) go to 1
 
 This approach is pretty simple to do in Python.  I wrote a sample
 digital simulator a while back and the core of the simulator was
 around 50 lines of code.  Rounded out with some basic logic gates
 and helper functions to probe the simulation, it was around 150
 lines.  It was only 2 level logic and signals could only be driven
 by a single device.
 
 The devices that you want to model (switches, loads, etc) don't
 have explicit inputs and outputs, and you'll need to deal with a
 signal being driven from multiple sources, so it will get a bit
 more complicated. You will probably also need 9 level logic (or
 something equivalent) to deal with the fact that ground beats a
 source through a load when determining a node's state.
 
 The basic idea is that each signal has multiple drivers, each of
 which has an internal state.  When a device wants to set an
 output, it only changes its driver's state.  The signal then has
 code that looks at the state of all drivers and combines them in
 some way (this is called a resolution function).  That combined
 state is what devices see when they read the signal.
 
 It isn't *that* complicated to implement, but if you can turn your
 problem into one with 2 level logic and no multiple drivers, then
 it will be easier to write and debug.

Sounds more familiar than the analog approach. Maybe I misunderstood
something ... but I can't transfer my problem to this way of
thinking yet. My biggest problem is the fact that relays aren't
really interested in voltage, but current. 

Also, I find it difficult to transfer this circuit logic to boolean
logic I can contruct logic gates from. Sometimes, electric circuits
are used in different directions.

This is how far I've come with my first approach yet:

I set up the mentioned controller which, at the beginning, tries
out all possible ways through the network and saves them. So, for
every possible circuit it knows which switches must be closed and
which relays will work if it's on. In theory, it should now be
possible to try out every path, tell the relays if they have
voltage/current, and let the relays report back in to the
controller if their status changes so it can again test the
circuits that may have changed. I haven't tried out the last step,
but I will in the next days. Is there any logic error in my
strategy?

Regards,


Björn

-- 
BOFH excuse #122:

because Bill Gates is a Jehovah's witness and so nothing can work on
St. Swithin's day.

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


Re: Suggestions for how to approach this problem?

2007-05-09 Thread John Salerno
Necmettin Begiter wrote:

 Is this how the text looks like:
 
 123
 some information
 
 124 some other information
 
 126(tab here)something else
 
 If this is the case (the numbers are at the beginning, and after the numbers 
 there is either a newline or a tab, the logic might be this simple:

They all seem to be a little different. One consistency is that each 
number is followed by two spaces. There is nothing separating each 
reference except a single newline, which I want to preserve. But within 
each reference there might be a combination of spaces, tabs, or newlines.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggestions for how to approach this problem?

2007-05-09 Thread John Salerno
Dave Hansen wrote:

 Questions:
 
 1) Do the citation numbers always begin in column 1?

Yes, that's one consistency at least. :)

 2) Are the citation numbers always followed by a period and then at
 least one whitespace character?

Yes, it seems to be either one or two whitespaces.

 find the beginning of each cite.  then I would output each cite
 through a state machine that would reduce consecutive whitespace
 characters (space, tab, newline) into a single character, separating
 each cite with a newline.

Interesting idea! I'm not sure what state machine is, but it sounds 
like you are suggesting that I more or less separate each reference, 
process it, and then rewrite it to a new file in the cleaner format? 
That might work pretty well.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Simulating simple electric circuits

2007-05-09 Thread Bjoern Schliessmann
Arnaud Delobelle wrote:

 When you turn a switch off, it would send a message to the paths
 that depend on it (maybe via the controller?) so that they would
 be
 deactivated.  In turn the lightbulbs on these paths would be
 informed that they are no longer active.
 
 When you turn a switch on, it would send a message to the paths
 that depend on it so that those who do not have another off switch
 would be
 activated.  In turn the lightbulbs on these paths would be
 informed that they have a new power source.

Wow, as I read your reply again, this is exactly the approach I
thought of yesterday. :) As mentioned in an adjacent posting, I'll
try it out.

Thanks to all for comments. This list is great. :)

Regards,


Björn

-- 
BOFH excuse #133:

It's not plugged in.

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


Re: Suggestions for how to approach this problem?

2007-05-09 Thread John Salerno
James Stroud wrote:

 If you can count on the person not skipping any numbers in the 
 citations, you can take an AI approach to hopefully weed out the rare 
 circumstance that a number followed by a period starts a line in the 
 middle of the citation.

I don't think any numbers are skipped, but there are some cases where a 
number is followed by a period within a citation. But this might not 
matter since each reference number begins at the start of the line, so I 
could use the RE to start at the beginning.
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: Simulating simple electric circuits

2007-05-09 Thread Hamilton, William
 From: Bjoern Schliessmann
 Sounds more familiar than the analog approach. Maybe I misunderstood
 something ... but I can't transfer my problem to this way of
 thinking yet. My biggest problem is the fact that relays aren't
 really interested in voltage, but current.
 
 Also, I find it difficult to transfer this circuit logic to boolean
 logic I can contruct logic gates from. Sometimes, electric circuits
 are used in different directions.

You shouldn't have to worry about current degrading.  You apply a
current to the relay's coil, and it passes through the coil to ground
and triggers the relay.  The relay's outputs open or close connections
from the current source to the connected devices' inputs.  The only time
you'd have to worry about low currents is if a single relay is connected
to a lot of device inputs, because the current is split across the
inputs.

From a logic standpoint, all you care about is whether each input and
output is on or off.


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


Re: String parsing

2007-05-09 Thread HMS Surprise
BTW, here's what I used, the other ideas have been squirreled away in
my neat tricks and methods folder.

for el in data.splitlines():
if el.find('LastUpdated')  -1:
s = el.split(=)[-1].split('')[1]
print 's:', s


Thanks again,

jh

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


Re: Newbie prob: How to write a file with 3 threads?

2007-05-09 Thread Bjoern Schliessmann
est wrote:

 I'd like to say VERY VERY VERY thank you for your detailed
 information, that's a lot encourage for a beginner. In fact I am
 writing a multi thread download ultility, and I found that very
 hard for me. 

You don't need any system threads for multiple download threads.
Since network connections are buffered and much slower than CPU
cycles, you can also use event based mechanisms. (I've written 30+
connection servers like this already.)

The general pseudocode strategy is 

while True:
waitForEvents()
event = getEvent()
processEvent(event)
# in here, you inspect the event, 
# e. g. from which connection it is,
# and get or write data

The only drawback to event based programming is that processor
cycle rationing is decided in your code and not by the OS, which
can make difficulties with really long calculations. But if these
problems arise you usually spawn a seperate worker thread :)

 Can you recommand any sample code where I can start 
 with? 

If you choose event based programming, definitely have a look at
Twisted. It lets you create multiple connection clients and servers
in few code lines without synchronisation hassle.

http://twistedmatrix.com/projects/core/documentation/howto/
http://twistedmatrix.com/projects/core/documentation/howto/clients.html

(BTW, don't get scared by Deferreds, I never explicitly used them
in my code ... though they often work in the background)

Regards,


Björn

-- 
BOFH excuse #376:

Budget cuts forced us to sell all the power cords for the servers.

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


Re: Gui thread and async jobs.

2007-05-09 Thread Grant Edwards
On 2007-05-08, king kikapu [EMAIL PROTECTED] wrote:

 Hi, i am reading the book Python Cookbook, 2nd edition and i
 encountered a very handy recipe, the one that is called
 Combining GUIs and Asynchronous I/O with Threads

 It is talking about retain a main GUI thread, doing async work
 with worker threads and have both talk through a Queue object
 to dispatch their messages, so the main (GUI) thread remain
 responsive. It has a very good example by using Tkinter and Qt
 that is indeed working. The only point that make me wonder is
 that the QUI thread has to use some polling to check for
 messages in the Queue.

It sounds to me like Qt is missing some rather important
features and/or convenience functions.  In other toolkits (e.g.
wxPython), invoking GUI methods/functions from non-GUI threads
is trivial and involves no polling by the GUI thread.

For example, if in a wxPython application you wanted to call
someGUIobject.method(foo,bar) from a non-GUI thread you just do
this:

   wx.CallAfter(someGUIobject.method,foo,bar)

If you look under the covers there is a queue involved, but
it's nothing the user has to poll or worry about.
   
-- 
Grant Edwards   grante Yow! Can I have an IMPULSE
  at   ITEM instead?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: N00b question on Py modules

2007-05-09 Thread Ant
On May 9, 2:47 pm, Sion Arrowsmith [EMAIL PROTECTED]
wrote:
...
 How so? Python style gurus discourage use of global variables. So
 does all the C++ (and to a lesser extent C) advice I've ever
 encountered. And Java outright forbids the concept.

Class variables (public static), are the equivalent of global
variables in Java, and can be an equal pain. Singleton objects can
cause similar problems, since they are essentially global objects, and
changing the values of any of their members can cause wierd behaviour
in otherwise unrelated parts of the code. So Java isn't by any means
immune to the global variable problem, it just has different names for
them!


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


Boost python : get the shape of a numpy ndarray in C++ code.

2007-05-09 Thread TG
Hi there.

I'm strugling here with some boost python code (damn I hate C++) :

All I want to do is to initialize the content of an array with a numpy
ndarray parameter. I have this, which actually works. But I want to
add some kind of data check such as :

* is array two dimensional ?
* are the dimensions corresponding to map's width / height ?
* is array field with floats or ints ?

void
Layer::set_potentials (numeric::array array)
{
  for (int h=0; hmap-height; h++){
for (int w=0; wmap-width; w++){
  units[w+h*map-width]-potential =
extractfloat(array[make_tuple(w,h)]);
}
  }
}


Some help is very welcome here ... thanks.

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


Re: Towards faster Python implementations - theory

2007-05-09 Thread Terry Reedy

Hendrik van Rooyen [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| I am relatively new on this turf, and from what I have seen so far, it
| would not bother me at all to tie a name's type to its first use, so that
| the name can only be bound to objects of the same type as the type
| of the object that it was originally bound to.
|
| But maybe I am missing the point of dynamism.
|
| Would an implementation of the above break lots of stuff in practice?

For function local variables, if you mean 'originally bound to' in the 
current call invocation, that would sometimes be ok (and that is sort of 
what Psycho does).  But if you mean in the original binding in the first 
call invocation, then that would cripple many functions.


tjr



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


Re: Specification for win32com.client package

2007-05-09 Thread kyosohma
On May 9, 8:25 am, Tim Golden [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  The wiki idea sounds like a good one. I was thinking about doing some
  kind of Python site about the modules and I think the popular 3rd
  party ones would be a good place to start, maybe starting with win32.
  How much information do you think would need to be on a site like this
  to start out with?

 Someone did start a Python Win32 Wiki recently (check the
 python-win32 archives for location etc.) I did mean to put
 things on there myself, but real life has taken over. Often,
 these things just need someone with a bit of oomph to at
 least get the thing going.

 I think what's needed (if you're offering :) is for someone
 to put a *framework* in place on such a site which would
 make it easy for anyone to come along and fill in the gaps
 with their particular 3rd-party app or brand of knowledge.
 As I say, someone did start something, but I've not heard
 anything from him since then and I haven't found the time
 myself. If you were to kick something off and actually get
 it going I wouldn't say no.

 TJG

I think I found the thread you were talking about:
http://mail.python.org/pipermail/python-win32/2007-March/005585.html

I went to the site listed: www.wazoozle.com and I see nothing related
to python there. In fact, James (the poster) doesn't appear to be
listed anywhere either. Very weird.

While I am not a wiki wizard, I will look into it. I might be able to
bamboozle some free space on my friend's hosting service for such a
project. If so, I'll let you know.

Mike

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


Re: which is more pythonic/faster append or +=[]

2007-05-09 Thread 7stud
On May 8, 11:05 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
 alf [EMAIL PROTECTED] wrote:
  two ways of achieving the same effect

  l+=[n]

  or

  l.append(n)

  so which is more pythonic/faster?

 .append - easy to measure, too:

 brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)'
 100 loops, best of 3: 1.31 usec per loop

 brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]'
 100 loops, best of 3: 1.52 usec per loop

 Alex

Why is it necessary to copy L?

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


Re: How safe is a set of floats?

2007-05-09 Thread Dave Borne
On 4 May 2007 07:21:49 -0700, Thomas Nelson [EMAIL PROTECTED] wrote:
 I want to generate all the fractions between 1 and limit (with
 limit1) in an orderly fashion, without duplicates.

Might I suggest the Stern-Brocot tree
(http://en.wikipedia.org/wiki/Stern-Brocot_tree)
It will eliminate the need for sets as the algorithm gurantees: Every
positive rational number can be found in this tree exactly once and in
lowest terms. The order will be different than your algorithm,
though.

#An overly simplified fraction class for this example:
class Fraction:
  def __init__ (self, num, den):
self.num = num
self.den = den
  def __repr__ (self):
  return '%(num)d/%(den)d' % self.__dict__

def all_ratios(limit):
seq = [Fraction(1,1), Fraction(limit,1)]
while True:
newseq = seq[:1]
pairs = [seq[x:x+2] for x in range(len(seq)-1)]
for pair in pairs:
#find the mediant value between each pair in the series
newval = Fraction(pair[0].num+pair[1].num, pair[0].den+pair[1].den)
yield newval
newseq.append(newval)
newseq.append(pair[1])
seq = newseq


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


Re: Gui thread and async jobs.

2007-05-09 Thread Phil Thompson
On Wednesday 09 May 2007 3:58 pm, Grant Edwards wrote:
 On 2007-05-08, king kikapu [EMAIL PROTECTED] wrote:
  Hi, i am reading the book Python Cookbook, 2nd edition and i
  encountered a very handy recipe, the one that is called
  Combining GUIs and Asynchronous I/O with Threads
 
  It is talking about retain a main GUI thread, doing async work
  with worker threads and have both talk through a Queue object
  to dispatch their messages, so the main (GUI) thread remain
  responsive. It has a very good example by using Tkinter and Qt
  that is indeed working. The only point that make me wonder is
  that the QUI thread has to use some polling to check for
  messages in the Queue.

 It sounds to me like Qt is missing some rather important
 features and/or convenience functions.  In other toolkits (e.g.
 wxPython), invoking GUI methods/functions from non-GUI threads
 is trivial and involves no polling by the GUI thread.

 For example, if in a wxPython application you wanted to call
 someGUIobject.method(foo,bar) from a non-GUI thread you just do
 this:

wx.CallAfter(someGUIobject.method,foo,bar)

 If you look under the covers there is a queue involved, but
 it's nothing the user has to poll or worry about.

In Qt it's all part of the signal/slot mechanism which works across threads. 
Surprise, surprise, under the covers there is a queue involved.

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


Re: Specification for win32com.client package

2007-05-09 Thread Tim Golden
[EMAIL PROTECTED] wrote:
 On May 9, 8:25 am, Tim Golden [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
 The wiki idea sounds like a good one. I was thinking about doing some
 kind of Python site about the modules and I think the popular 3rd
 party ones would be a good place to start, maybe starting with win32.
 How much information do you think would need to be on a site like this
 to start out with?
 Someone did start a Python Win32 Wiki recently (check the
 python-win32 archives for location etc.) I did mean to put
 things on there myself, but real life has taken over. Often,
 these things just need someone with a bit of oomph to at
 least get the thing going.

 I think what's needed (if you're offering :) is for someone
 to put a *framework* in place on such a site which would
 make it easy for anyone to come along and fill in the gaps
 with their particular 3rd-party app or brand of knowledge.
 As I say, someone did start something, but I've not heard
 anything from him since then and I haven't found the time
 myself. If you were to kick something off and actually get
 it going I wouldn't say no.

 TJG
 
 I think I found the thread you were talking about:
 http://mail.python.org/pipermail/python-win32/2007-March/005585.html
 
 I went to the site listed: www.wazoozle.com and I see nothing related
 to python there. In fact, James (the poster) doesn't appear to be
 listed anywhere either. Very weird.

Strange. Maybe he gave up and hosted something
else instead. It's not as though the name was
related :)

 While I am not a wiki wizard, I will look into it. I might be able to
 bamboozle some free space on my friend's hosting service for such a
 project. If so, I'll let you know.

Personally, if only to save startup pain, I'd be inclined to
use the main Python wiki, at least to get going. I know I
said at the time that I was willing to kick something off,
but days led to weeks... and you can guess the rest.

Why not corner an area on http://wiki.python.org/moin/
and put headings in place? I'm not a great fan of MoinMoin,
but it's there and it carries a (certain) measure of
authority. That said, if you want to set up on your own
space, I'm not objecting. I'll do my best (this time) to 
supply info and keep things going.

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


Sorting attributes by catagory

2007-05-09 Thread Ron Adam

This is for a new version of pydoc if I can get the class attributes sorted 
out.  The module level attributes aren't too difficult to categorize.

(I might be just too tired to see the obvious.)

The original pydoc did this a somewhat round about way, so I would like to 
find a more direct method if possible.


Where dir(obj) is used to get all attributes of a module or class.  And 
they are then sorted into categories depending on what they are.

(In order of precedence.)

For modules:

 - imported_items (defined in another module,
 or is another module)
 - classes
 - functions
 - other_objects  (everything else)


For classes:

 - from_else_where(object created someplace else)
 - inherited_attributes   (from parents classes or type)
 - static_methods_here
 - class_methods_here
 - other_methods
 - properties
 - getset_descriptors
 - other_descriptors
 - other_attributes   (everything else)


A single function that accepts an object and can return one of the above 
(or equivalent) strings would be ideal.  Finer grained categorizing is ok 
as long as they don't overlap more than one group.

It seems I can get some of these fairly easy with the inspect module, but 
others I need to test in multiple ways.

Any ideas?


Cheers,
Ron





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


Re: Suggestions for how to approach this problem?

2007-05-09 Thread John Salerno
John Salerno wrote:

 So I need to remove the line breaks too, but of course not *all* of them 
 because each reference still needs a line break between it.

After doing a bit of search and replace for tabs with my text editor, I
think I've narrowed down the problem to just this:

I need to remove all newline characters that are not at the end of a
citation (and replace them with a single space). That is, those that are
not followed by the start of a new numbered citation. This seems to
involve a look-ahead RE, but I'm not sure how to write those. This is
what I came up with:


\n(?=(\d)+)

(I can never remember if I need parentheses around '\d' or if the + 
should be inside it or not!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: String parsing

2007-05-09 Thread Paul Boddie
On 9 May, 06:42, Dennis Lee Bieber [EMAIL PROTECTED] wrote:


[HTMLParser-based solution]

Here's another approach using libxml2dom [1] in HTML parsing mode:

import libxml2dom

# The text, courtesy of Dennis.
sample = input type=hidden name=RFP value=-1/
!--input type=hidden name=EnteredBy value=john/--
input type=hidden name=EnteredBy value=john/
input type=hidden name=ServiceIndex value=1/
input type=hidden name=LastUpdated value=1178658863/
input type=hidden name=NextPage value=../active/active.php/
input type=hidden name=ExistingStatus value=10 /
table width=98% cellpadding=0 cellspacing=0 border=0
align=center 

# Parse the string in HTML mode.
d = libxml2dom.parseString(sample, html=1)

# For all input fields having the name 'LastUpdated',
# get the value attribute.
last_updated_fields = d.xpath(//[EMAIL PROTECTED]'LastUpdated']/@value)

# Assuming we find one, print the contents of the value attribute.
print last_updated_fields[0].nodeValue

Paul

[1] http://www.python.org/pypi/libxml2dom

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


Re: Getting some element from sets.Set

2007-05-09 Thread [EMAIL PROTECTED]
On May 4, 5:06 pm, John Machin [EMAIL PROTECTED] wrote:
 Errmm, union and intersection operations each apply to two (or more)
 sets, not to the elements of a set.

 You have n sets set0, set1, 

 Let u be the number of unique somevalues (1 = u = n)

 If u  1, then after setn = union(set0, set1), setn may not conform to
 the rule -- does this matter?


I've also previously run into the same need as the original poster.  I
no longer recall the details, but I think maybe I was implementing a
union/find type algorithm.  This basically involves partitioning a
universe set into partitions, where any element of a partition can be
used as a name/handle/etc for the partition in question.  Sets are the
obvious representation for these partitions, esp since they implement
union efficiently.  And given this representation, it's very obvious
to want to generate a name when you have a set in hand.  Since any
element of the set serves as a name (and you know the sets are all non-
empty), it'd be very nice to have a .element() method, or some such.
I guess iter(s).next() works okay, but it's not very readable, and I
wonder if it's efficient.

This is at least the second time this has come up, so maybe there is a
need.

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


Re: change of random state when pyc created??

2007-05-09 Thread Alan G Isaac
Diez B. Roggisch wrote:
 Not really, but that depends on what you know about the concept of sets and
 maps as collections of course.
 
 The contract for sets and dicts doesn't imply any order whatsoever. Which is
 essentially the reason why
 
 set(xrange(10))[0]
 
 doesn't exist, and quite a few times cries for an ordered dictionary as part
 of the standard libraries was made.


It seems to me that you are missing the point,
but maybe I am missing your point.

The question of whether a set or dict guarantees
some order seems quite different from the question
of whether rerunning an **unchanged program** yields the
**unchanged results**.  The latter question is the question
of replicability.

Again I point out that some sophisticated users
(among which I am not numbering myself) did not
see into the source of this anomaly.  This
suggests that an explicit warning is warranted.

Cheers,
Alan Isaac

PS I know ordered dicts are under discussion;
what about ordered sets?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: which is more pythonic/faster append or +=[]

2007-05-09 Thread 7stud
On May 8, 11:05 pm, [EMAIL PROTECTED] (Alex Martelli) wrote:
 alf [EMAIL PROTECTED] wrote:
  two ways of achieving the same effect

  l+=[n]

  or

  l.append(n)

  so which is more pythonic/faster?

 .append - easy to measure, too:

 brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x.append(n)'
 100 loops, best of 3: 1.31 usec per loop

 brain:~ alex$ python -mtimeit 'L=range(3); n=23' 'x=L[:]; x+=[n]'
 100 loops, best of 3: 1.52 usec per loop

 Alex

Ah, I see.  The list would grow too large with all that appending, so
you begin again with the original list for every loop.

Is there any documentation for the syntax you are used with timeit?  I
checked 'man python', and I also read the example in the python docs,
but  you seem to be using a hybrid syntax.

Thanks.

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


Re: BUSTED!!! 100% VIDEO EVIDENCE that WTC7 was controlled demolition!! NEW FOOTAGE!!! Ask yourself WHY havn't I seen this footage before?

2007-05-09 Thread James Beck
In article [EMAIL PROTECTED], [EMAIL PROTECTED] 
says...
 James Beck wrote:
  
  In article [EMAIL PROTECTED], [EMAIL PROTECTED]
  says...
   James Beck wrote:
   
Yep, you must have access to better drugs than I do.
You get to hallucinate your stuff up.
Don't forget to adjust your tin beanie!
  
  
  Its not a beanie.  He had his head tin plated. :(
  
  I just the How it's Made that showed how they make bronzed baby shoes.
  Maybe they can adapt that process to tin plate heads.
  Would save these guys thousands of $$$ on foil.
  
 Jim
 
 
 
Yeah, they wouldn't need it done very often.  Only when the dead skin
 builds up so much it pushes the old one off their bald heads.
 
 
Now that made me laugh.
The visual of a tin skull cap popping off from sluffing skin.
POP!

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


tkinter - Screen Resolution

2007-05-09 Thread rahulnag22
Hi,
I have developed a GUI using tkinter (grid geometory manager).
The structure is a top frame containing multiple subframes. Each
subframe has a combination of widgets like(Entry, label,
button,listboxes). The subframes are placed with a padx and pady
offset with regards to the other subframes. And the widgets within
these subframes have their own padx and pady offsets. The GUI runs
fine on my linux box, but on a different linux box things get wierd.
I see things like-
1) The frame width increasing
2) The widget padx translating to much bigger offsets with reference
to the subframe edges
3) Widget widths like that for Entry become bigger

I Know its to do with the screen resolution settings and user settings
on different machines. Can anyone point me in the right
direction(before I start looking into it)as how to account for
different screen resolutions so as to have as uniform a GUI look as
possible across different user machines.
A smaller version of my GUI layout looks something like--

===Top Frame=
=- SubFrame - -SubFrame-
=-- -
'
-
=-- - '   Widget   ' -
=-- -
' -
=-   Widget   - -
=-
-
=-- -SubFrame-
=-- -
-
=-- -
'
-
=-   Widget- -   '   Widget   '  -
=-- -
'   -
=-- -
-
=-- -
'
-
=-- -   '   Widget   '   -
=-  Widget- -   '
-
=--- -
=


Thanks
Rahul

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


Re: Getting some element from sets.Set

2007-05-09 Thread Steven Bethard
[EMAIL PROTECTED] wrote:
 I've also previously run into the same need as the original poster.  I
 no longer recall the details, but I think maybe I was implementing a
 union/find type algorithm.  This basically involves partitioning a
 universe set into partitions, where any element of a partition can be
 used as a name/handle/etc for the partition in question.  Sets are the
 obvious representation for these partitions, esp since they implement
 union efficiently.  And given this representation, it's very obvious
 to want to generate a name when you have a set in hand.  Since any
 element of the set serves as a name (and you know the sets are all non-
 empty), it'd be very nice to have a .element() method, or some such.
 I guess iter(s).next() works okay, but it's not very readable, and I
 wonder if it's efficient.

You can find out::

 $ python -m timeit -s s = set('abcdef') x = iter(s).next()
 100 loops, best of 3: 0.399 usec per loop

 $ python -m timeit -s s = set('abcdef') x = s.pop(); s.add(x)
 100 loops, best of 3: 0.339 usec per loop

So it looks like it's more efficient to use s.pop() + s.add().

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


Re: tkinter - Screen Resolution

2007-05-09 Thread rahulnag22
On May 9, 10:37 am, [EMAIL PROTECTED] wrote:
 Hi,
 I have developed a GUI using tkinter (grid geometory manager).
 The structure is a top frame containing multiple subframes. Each
 subframe has a combination of widgets like(Entry, label,
 button,listboxes). The subframes are placed with a padx and pady
 offset with regards to the other subframes. And the widgets within
 these subframes have their own padx and pady offsets. The GUI runs
 fine on my linux box, but on a different linux box things get wierd.
 I see things like-
 1) The frame width increasing
 2) The widget padx translating to much bigger offsets with reference
 to the subframe edges
 3) Widget widths like that for Entry become bigger

 I Know its to do with the screen resolution settings and user settings
 on different machines. Can anyone point me in the right
 direction(before I start looking into it)as how to account for
 different screen resolutions so as to have as uniform a GUI look as
 possible across different user machines.
 A smaller version of my GUI layout looks something like--

 ===Top Frame=
 =- SubFrame - -SubFrame-
 =-- - ' -
 =-- - '   Widget   ' -
 =-- - ' -
 =-   Widget   - -
 =-  -
 =-- -SubFrame-
 =-- -   -
 =-- - ' -
 =-   Widget- -'   Widget   ' -
 =-- - ' -
 =-- -   -
 =-- - ' -
 =-- - '   Widget   ' -
 =-  Widget- - '  -
 =--- -
 =

 Thanks
 Rahul


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


Single precision floating point calcs?

2007-05-09 Thread Grant Edwards
I'm pretty sure the answer is no, but before I give up on the
idea, I thought I'd ask...

Is there any way to do single-precision floating point
calculations in Python?   

I know the various array modules generally support arrays of
single-precision floats.  I suppose I could turn all my
variables into single-element arrays, but that would be way
ugly...

-- 
Grant Edwards   grante Yow! -- I have seen the
  at   FUN --
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


ctypes: Problems using Windows-DLL from VB example code

2007-05-09 Thread Noralf Tr�nnes
Hi

I'm trying to use a DLL from Python using ctypes.
The call to dso_lib.capture_hold_chk() does return 232. So it seem to work.
The call to dso_lib.port_init(init_data) gives:
WindowsError: exception: access violation reading 0x0006

Any suggestions?

Thanks.

Noralf


Here is my python code:
import os
from ctypes import *

# Hardware control data
class A_INIT(Structure):
_fields_ = [(time_d_va, c_long),
(tri_in_sel, c_int),
(ch1_div, c_int),
(ch1_in_sel, c_int),
(ch2_div, c_int),
(ch2_in_sel, c_int),
(ram_rw_mode, c_int),
(ram_copy_mode, c_int),
(ram_copy_delay, c_int),
(ho_mode, c_int),
(ho_mode1, c_int),
(CH, c_int),
(TRI_12E, c_int),
(Ch1_To_Gnd, c_int),
(Ch2_To_Gnd, c_int)]

dso_lib_filepath = os.path.join(os.path.dirname(__file__), 
'dso_2100usb_s.dll')
dso_lib = cdll.LoadLibrary(dso_lib_filepath)
init_data = A_INIT()

init_data.time_d_va = 0
init_data.tri_in_sel = 7
init_data.ch1_div = 4
init_data.ch1_in_sel = 1
init_data.ch2_div = 4
init_data.ch2_in_sel = 1
init_data.ram_rw_mode = 1
init_data.ram_copy_mode = 14
init_data.ram_copy_delay = 0
init_data.ho_mode = 1
init_data.ho_mode1 = 0
init_data.CH = 0
init_data.TRI_12E = 0
init_data.Ch1_To_Gnd = 0
init_data.Ch2_To_Gnd = 0

print dso_lib.capture_hold_chk()  # returns 232

print dso_lib.port_init(init_data)  # WindowsError exception


Here is the code from a Visual Basic example using the DLL:

Type A_INIT   'hardware control data
time_d_va As Long
tri_in_sel As Integer
ch1_div As Integer
ch1_in_sel As Integer
ch2_div As Integer
ch2_in_sel As Integer
ram_rw_mode As Integer
ram_copy_mode As Integer
ram_copy_delay As Integer
ho_mode As Integer
ho_mode1 As Integer
CH As Integer
TRI_12E As Integer
Ch1_To_Gnd As Integer
Ch2_To_Gnd As Integer
End Type
Public init_data As A_INIT

Public RESULT As Integer

Public Declare Function port_init Lib dso_2100usb_s.dll (init_data As 
A_INIT) As Integer

Sub init()
  init_data.ch1_div = 4
  init_data.ch1_in_sel = 1
  init_data.Ch1_To_Gnd = 0
  init_data.ch2_div = 4
  init_data.ch2_in_sel = 1
  init_data.Ch2_To_Gnd = 0
  init_data.ho_mode = 1
  RESULT = port_init(init_data)
End Sub


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


Re: Towards faster Python implementations - theory

2007-05-09 Thread John Nagle
Paul Boddie wrote:
 On 9 May, 08:09, Hendrik van Rooyen [EMAIL PROTECTED] wrote:
 
I am relatively new on this turf, and from what I have seen so far, it
would not bother me at all to tie a name's type to its first use, so that
the name can only be bound to objects of the same type as the type
of the object that it was originally bound to.
 
 
 But it's interesting to consider the kinds of names you could restrict
 in this manner and what the effects would be. In Python, the only kind
 of name that can be considered difficult to arbitrarily modify at a
 distance - in other words, from outside the same scope - are locals,
 and even then there are things like closures and perverse
 implementation-dependent stack hacks which can expose local namespaces
 to modification, although any reasonable conservative Python
 implementation would disallow the latter.

 Modifying at a distance is exactly what I'm getting at.  That's the
killer from an optimizing compiler standpoint.  The compiler, or a
maintenance programmer, looks at a block of code, and there doesn't seem
to be anything unusual going on.  But, if in some other section of
code, something does a setattr to mess with the first block of code,
something unusual can be happening.  This is tough on both optimizing
compilers and maintenance programmers.

 Python has that capability mostly because it's free in an
everything is a dictionary implementation.  (When all you have
is a hash, everything looks like a dictionary.)  But that limits
implementation performance.  Most of the time, nobody is using
setattr to mess with the internals of a function, class, or
module from far, far away.  But the cost for that flexibility is
being paid, unnecessarily.

 I'm suggesting that the potential for action at a distance somehow
has to be made more visible.

 One option might be a class simpleobject, from which other classes
can inherit.  (object would become a subclass of simpleobject).
simpleobject classes would have the following restrictions:

- New fields and functions cannot be introduced from outside
the class.  Every field and function name must explicitly appear
at least once in the class definition.  Subclassing is still
allowed.
- Unless the class itself uses getattr or setattr on itself,
no external code can do so.  This lets the compiler eliminate the
object's dictionary unless the class itself needs it.

This lets the compiler see all the field names and assign them fixed slots
in a fixed sized object representation.  Basically, this means simple objects
have a C/C++ like internal representation, with the performance that comes
with that representation.

With this, plus the Shed Skin restrictions, plus the array features of
numarray, it should be possible to get computationally intensive code
written in Python up to C/C++ levels of performance.  Yet all the dynamic
machinery of Python remains available if needed.

All that's necessary is not to surprise the compiler.

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


Re: Getting some element from sets.Set

2007-05-09 Thread Marc 'BlackJack' Rintsch
In [EMAIL PROTECTED],
[EMAIL PROTECTED] wrote:

 Since any element of the set serves as a name (and you know the sets are
 all non- empty), it'd be very nice to have a .element() method, or some
 such. I guess iter(s).next() works okay, but it's not very readable,
 and I wonder if it's efficient.

Give it a name and it gets more readable:

def get_name(setobj):
return iter(setobj).next()

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


Re: ctypes: Problems using Windows-DLL from VB example code

2007-05-09 Thread Thomas Heller
Noralf Trønnes schrieb:
 Hi
 
 I'm trying to use a DLL from Python using ctypes.
 The call to dso_lib.capture_hold_chk() does return 232. So it seem to work.
 The call to dso_lib.port_init(init_data) gives:
 WindowsError: exception: access violation reading 0x0006
 
 Any suggestions?
 

Have you tried to pass the structure by reference?

dso_lib.port_init(byref(init_data))

Thomas

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


Re: Boost python : get the shape of a numpy ndarray in C++ code.

2007-05-09 Thread Roman Yakovenko
On 9 May 2007 08:08:46 -0700, TG [EMAIL PROTECTED] wrote:
 Hi there.

 I'm strugling here with some boost python code (damn I hate C++) :

 All I want to do is to initialize the content of an array with a numpy
 ndarray parameter. I have this, which actually works. But I want to
 add some kind of data check such as :

 * is array two dimensional ?

This question has nothing to do with Boost.Python

 * are the dimensions corresponding to map's width / height ?

Same as above

 * is array field with floats or ints ?

Read extract documentation http://boost.org/libs/python/doc/v2/extract.html

 void
 Layer::set_potentials (numeric::array array)
 {
   for (int h=0; hmap-height; h++){
 for (int w=0; wmap-width; w++){
   units[w+h*map-width]-potential =
 extractfloat(array[make_tuple(w,h)]);
 }
   }
 }


 Some help is very welcome here ... thanks.

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



-- 
Roman Yakovenko
C++ Python language binding
http://www.language-binding.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ctypes: Problems using Windows-DLL from VB example code

2007-05-09 Thread Noralf Tr�nnes
 Have you tried to pass the structure by reference?

 dso_lib.port_init(byref(init_data))

 Thomas


That gives me another exeption:

print dso_lib.port_init(byref(init_data))
ValueError: Procedure called with not enough arguments (4 bytes missing) or 
wrong calling convention

Noralf. 


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


preferred windows text editor?

2007-05-09 Thread T. Crane
Right now I'm using Notepad++.  What are other people using?

trevis 


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


Inheritance problem

2007-05-09 Thread amidzic . branko
I'm trying to solve a problem using inheritance and polymorphism in
python 2.4.2



I think it's easier to explain the problem using simple example:



class shortList:

def __init__(self):

self.setList()



def setList(self):

a = [1,2,3]

print a



class longList(shortList):

def __init__(self):

shortList.setList()

self.setList()



def setList(self):

a.extend([4,5,6])

print a



def main():

a = raw_input('Do you want short or long list? (s/l)')

if a.upper() == 'S':

lst = shortList()

else:

lst = longList()



lst.setList()



if __name__ == '__main__':

main()



After that I'm getting a message:

TypeError: unbound method setList() must be called with shortList
instance as first argument (got nothing instead)



Where is the problem?



Thanks in advance...

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


Re: ctypes: Problems using Windows-DLL from VB example code

2007-05-09 Thread Thomas Heller
 Have you tried to pass the structure by reference?

 dso_lib.port_init(byref(init_data))
 
 That gives me another exeption:
 
 print dso_lib.port_init(byref(init_data))
 ValueError: Procedure called with not enough arguments (4 bytes missing) or 
 wrong calling convention

Please try using 'windll' instead of 'cdll' to load the library; then call 
'dso_lib.port_init(byref(init_data))'.

Thomas

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


path stuff

2007-05-09 Thread fscked
I am walking some directories looking for a certain filename pattern.
This part works fine, but what if I want to exclude results from a
certain directory being printed?

eg

d:\dir\mydir1\filename.txt  --I want to
see this one
d:\dir\mydir2\archived\filename.txt --I don't want to
see anything in the archived directory
d:\dir\mydir2\filename.txt  --Again, I do
want to see this one

I am having a bit of trouble figuring out how to use the path module
to hack up the path to determine if I am in a subdir I care about. So
either don show me the results from a certain directory or just plain
skip a certain directory.

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


Re: Inheritance problem

2007-05-09 Thread Neil Cerutti
On 2007-05-09, [EMAIL PROTECTED] [EMAIL PROTECTED] wrote:
 I'm trying to solve a problem using inheritance and
 polymorphism in python 2.4.2

It's not an inheritance problem, it's a notation problem. Python
uses explicit 'self', saving you the trouble of devising a naming
convention for data members.

 I think it's easier to explain the problem using simple example:

 class shortList:
 def __init__(self):
 self.setList()

 def setList(self):
 a = [1,2,3]
 print a

You need to use

 self.a = [1, 2, 3]
 print self.a

The notation you used creates a local variable, but you need a
data member.

 class longList(shortList):
 def __init__(self):
 shortList.setList()
 self.setList()

 def setList(self):
 a.extend([4,5,6])
 print a

Similarly:

 self.a.extend([4, 5, 6])
 print self.a

Does that give you better results?

-- 
Neil Cerutti
If we stay free of injuries, we'll be in contention to be a healthy team.
--Chris Morris
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: path stuff

2007-05-09 Thread kyosohma
On May 9, 1:11 pm, fscked [EMAIL PROTECTED] wrote:
 I am walking some directories looking for a certain filename pattern.
 This part works fine, but what if I want to exclude results from a
 certain directory being printed?

 eg

 d:\dir\mydir1\filename.txt  --I want to
 see this one
 d:\dir\mydir2\archived\filename.txt --I don't want to
 see anything in the archived directory
 d:\dir\mydir2\filename.txt  --Again, I do
 want to see this one

 I am having a bit of trouble figuring out how to use the path module
 to hack up the path to determine if I am in a subdir I care about. So
 either don show me the results from a certain directory or just plain
 skip a certain directory.

Hi,

One way to do it would be to grab just the directory path like this:

dirPath = os.path.dirname(path)

and then use and if:

if 'archived' in dirPath:
   # skip this directory

That should get you closer to the answer anyway.

Mike

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


Re: preferred windows text editor?

2007-05-09 Thread kyosohma
On May 9, 1:06 pm, T. Crane [EMAIL PROTECTED] wrote:
 Right now I'm using Notepad++.  What are other people using?

 trevis

For Python, I still prefer IDLE or PythonWin.

For other things like cmd, ini, and other text files, I use either
Notepad++ or UltraEdit.

Mike

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


input

2007-05-09 Thread HMS Surprise
Just wanted a input routine that would let me pause my jython program
until I press enter. Searched tutorial, lang ref, and lib and found
input and raw_input. Both hang the program and it must be killed.

s = raw_input('-- ')

What has Mr Duh done wrong now?

jh

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


RE: preferred windows text editor?

2007-05-09 Thread Looney, James B
I'm using Vim (http://www.vim.org/).
-JB

-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] On
Behalf Of T. Crane
Sent: Wednesday, May 09, 2007 12:07 PM
To: python-list@python.org
Subject: preferred windows text editor?

Right now I'm using Notepad++.  What are other people using?

trevis 


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


Re: Inheritance problem

2007-05-09 Thread Bjoern Schliessmann
[EMAIL PROTECTED] wrote:

 class longList(shortList):
 
 def __init__(self):
 
 shortList.setList()
 
 self.setList()

Addition: Always call the base class __init__ in your constructor if
there exists one, i. e.

class longList(shortList)
def __init__(self):
shortlist.__init__()
# [...]

Regards,


Björn

-- 
BOFH excuse #108:

The air conditioning water supply pipe ruptured over the machine
room

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


Re: preferred windows text editor?

2007-05-09 Thread Stef Mientki
PyScripter or JALcc
Stef
T. Crane wrote:
 Right now I'm using Notepad++.  What are other people using?
 
 trevis 
 
 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: preferred windows text editor?

2007-05-09 Thread Jason
On May 9, 12:06 pm, T. Crane [EMAIL PROTECTED] wrote:
 Right now I'm using Notepad++.  What are other people using?

 trevis

IDLE for short scripts, PyDev under Eclipse for big Python projects,
and the Python shell for basic one-offs.

  --Jason

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


Re: Inheritance problem

2007-05-09 Thread attn . steven . kuo
On May 9, 11:33 am, Bjoern Schliessmann usenet-
[EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] wrote:
  class longList(shortList):

  def __init__(self):

  shortList.setList()

  self.setList()

 Addition: Always call the base class __init__ in your constructor if
 there exists one, i. e.

 class longList(shortList)
 def __init__(self):
 shortlist.__init__()
 # [...]



Delegating to an ancestor class by
calling an unbound method is fine as
long as one remembers to pass an instance
as the first argument.  So, this means:

shortList.setList(self)

and

  shortList.__init__(self)

for the examples above.

--
Regards,
Steven


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


Re: Single precision floating point calcs?

2007-05-09 Thread Terry Reedy

Grant Edwards [EMAIL PROTECTED] wrote in message 
news:[EMAIL PROTECTED]
| I'm pretty sure the answer is no, but before I give up on the
| idea, I thought I'd ask...

| Is there any way to do single-precision floating point
| calculations in Python?

Make your own Python build from altered source.  And run it on an ancient 
processor/OS/C compiler combination that does not automatically convert C 
floats to double when doing any sort of calculation.

Standard CPython does not have C single-precision floats.

The only point I can think of for doing this with single numbers, as 
opposed to arrays of millions, is to show that there is no point.  Or do 
you have something else in mind?

Terry Jan Reedy





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


Re: ctypes: Problems using Windows-DLL from VB example code

2007-05-09 Thread Noralf Tr�nnes
Thank you very much!

That did the trick.

Noralf. 


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


Re: preferred windows text editor?

2007-05-09 Thread nufuhsus
On May 9, 2:06 pm, T. Crane [EMAIL PROTECTED] wrote:
 Right now I'm using Notepad++.  What are other people using?

I am very noob to this Python game (though it has been around since
1995 me thinks) and currently (I was using ActivePython and then IDLE)
I have been using a combination of Notepad2 urlhttp://www.flos-
freeware.ch/notepad2.html/url and the interpreter (Python 2.5) on a
Windblows X[crement]P[roblem] SP2 machine.

I like IDLE but it seems to stop working after the first few times and
I would then re-install it and it would work a few times more.
ActivePython was cool but I could not find a version of it that used
Python 2.5 (as far as I can see, it only uses 2.4)

Notepad2 allows you to launch your script directly from the editor
(just like IDLE) and has configurable code highlighting. And it is
FREE.

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


  1   2   >