Python Engineers

2008-09-06 Thread William Currence
Good morning,

I'm having trouble finding experienced Python engineers in the Annapolis/DC 
area.  Is this list an appropriate place to look?

Thanks,

Bill Currence




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

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


GPCE'08 Call for Participation

2008-09-06 Thread Emir Pasalic

 http://gpce08.gpce.org 
Seventh International Conference on
Generative Programming and Component Engineering (GPCE'08)
Nashville, Tennessee
(co-located with OOPSLA 2008)

*  Only Six Days Left for Early Registration  *

*** CALL FOR PARTICIPATION

Generative and component approaches are revolutionizing software
development similar to how automation and components revolutionized
manufacturing. Generative Programming (developing programs that
synthesize other programs), Component Engineering (raising the level
of modularization and analysis in application design), and
Domain-Specific Languages (elevating program specifications to compact
domain-specific notations that are easier to write, maintain, and
analyze) are key technologies for automating program development.

GPCE provides a venue for researchers and practitioners interested in
foundational techniques for enhancing the productivity, quality, and
time-to-market in software development that stems from deploying
standard components and automating program generation. In addition to
exploring cutting-edge techniques for developing generative and
component-based software, our goal is to foster further
cross-fertilization between the software engineering research
community and the programming languages community.

GPCE 2008 will be co-located with OOPSLA, in Nashville, Tennessee. The
GPCE technical program will take place on Oct. 19-20, before the OOPSLA
technical program begins. Other GPCE events (workshops and tutorials)
will run in parallel with OOPSLA events on Oct 21-23. GPCE'08 is
sponsored by ACM SIGPLAN, in cooperation with ACM SIGSOFT.  GPCE'08
proceedings published by ACM Press.

For full conference program and the latest news, check the GPCE'08 web  
site

(http://gpce08.gpce.org).

 REGISTRATION

Registration for GPCE'08 is handled through the OOPSLA registration
page (http://www.regmaster.com/conf/oopsla2008.html). Early
registration deadline is Septermber 11.

*** TECHNICAL PROGRAM
Sunday, October 19

8:50-9:00 Welcome

9:00-10:00 Keynote
Session Chair: Julia Lawall

  * Emerging Challenges for Large Scale Systems Integration
Dr. Andrew Fano (Accenture)

10:30-12:00 Technical papers 1
Session Chair: Julia Lawall


  * Code Generation to Support Static and Dynamic Composition of
Software Product Lines
Marko Rosenmueller, Norbert Siegmund, Sven Apel and Gunter Saake.
  * Efficient Compilation Techniques for Large Scale Feature Models
Marcilio Mendonca, Andrzej Wasowski, Krzysztof Czarnecki and Don  
Cowan.

  * On the Modularity of Feature Interactions
Chang Hwan Peter Kim, Christian Kaestner and Don Batory.

13:30-15:00 Technical papers 2
Session Chair: Jaakko Jarvi

  * Using Simple Mathematics as a Modeling Language
Don Batory.
  * From Generic to Specific: Off-line Optimization for
General Constraint Solver
Ye Zhang, Torben Amtoft and Flemming Nielson.
  * Generating Incremental Implementations of Object-Set Queries
Tom Rothamel and Yanhong A. Liu.

15:30-17:00 Technical papers 3
Session Chair: Aniruddha Gokhale

  * Integrating Semantics and Compilation
Peter Gottschling and Andrew Lumsdaine.
  * Generating Customized Verifiers for Automatically Generated Code
Ewen Denney and Bernd Fischer.
  * Property Models: From Incidental Algorithms to Reusable Components
Jaakko Jarvi, Mat Marcus, Sean Parent, John Freeman and Jacob  
Smith.


17:00-17:30 PC chair's report

Monday, October 20

9:00-10:00 Keynote
Session Chair: William Cook

  * Fundamentalist Functional Programming
Erik Meijer (Microsoft)

10:30-12:00 Technical papers 4
Session Chair: William Cook

  * Feature Featherweight Java: A Calculus for Feature-Oriented
Programming and Stepwise Refinement
Sven Apel, Christian Kastner and Christian Lengauer.
  * Lightweight Dependent Classes
Tetsuo Kamina and Tetsuo Tamai.
  * Typing Communicating Component Assemblages
Michael Lienhardt, Vivien Quema, Alan Schmitt and Jean-Bernard  
Stefani.


14:00-15:00 Technical papers 5
Session Chair: David Abrahams

  * Polymorphic Embedding of DSLs
Christian Hofer, Klaus Ostermann, Tillmann Rendel and Adriaan  
Moors.

  * Pantaxou: a Domain-Specific Language for Developing
Safe Coordination Services
Julien Mercadal, Nicolas Palix, Charles Consel and Julia Lawall.

15:30-17:00 Technical papers 6
Session Chair: Mark Grechanik

  * Program Refactoring using Functional Aspects
Sven Apel, Christian Kastner and Don Batory.
  * Rigorous and Practical Refactoring-Based Framework Upgrade
Ilie Savga, Michael Rudolf, Sebastian Gotz and Uwe Assmann.
  * An abstraction for reusable MDD components
Vinay Kulkarni and Sreedhar Reddy.--
http://mail.python.org/mailman/listinfo/python-announce-list

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


[ANN] pysqlite 2.5.0 released

2008-09-06 Thread Gerhard Häring
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

pysqlite 2.5.0 released
===

I'm pleased to announce the availability of pysqlite 2.5.0. This is
a release with major new features.

Go to http://pysqlite.org/ for downloads, online documentation and
reporting bugs.

What is pysqlite?

 pysqlite is a DB-API 2.0-compliant database interface for SQLite.

 SQLite is a in-process library that implements a self-contained,
 serverless, zero-configuration, transactional SQL database
 engine.

 pysqlite makes this powerful embedded SQL engine available to
 Python programmers. It stays compatible with the Python database
 API specification 2.0 as much as possible, but also exposes most
 of SQLite's native API, so that it is for example possible to
 create user-defined SQL functions and aggregates in Python.

 If you need a relational database for your applications, or even
 small tools or helper scripts, pysqlite is often a good fit. It's
 easy to use, easy to deploy, and does not depend on any other
 Python libraries or platform libraries, except SQLite. SQLite
 itself is ported to most platforms you'd ever care about.

 It's often a good alternative to MySQL, the Microsoft JET engine
 or the MSDE, without having any of their license and deployment
 issues.

pysqlite can be downloaded from http://pysqlite.org/ - Sources and
Windows binaries for Python 2.5, 2.4 and Python 2.3 are available.

===
CHANGES
===

- - Windows binaries are now cross-built using mingw on Linux
- - import various fixes from Python 2.6 version
- - Connection has new method iterdump() that allows you to create
  a script file
  that can be used to clone a database
- - the docs are now built using Sphinx and were imported from
  Python 2.6's sqlite3 module
- - Connection.enable_load_extension(enabled) to allow/disallow extension
  loading. Allows you to use fulltext search extension, for example ;-)
- - Give the remaining C functions used in multiple .c source files
  the pysqlite_ prefix.
- - Release GIL during sqlite3_prepare() calls for better concurrency.
- - Automatically download the SQLite amalgamation when building
  statically.
-BEGIN PGP SIGNATURE-
Version: GnuPG v1.4.6 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFIwZV3dIO4ozGCH14RAp1YAJwPIdgtCZY7E8YcDUjO/dzoAThblgCggfhs
OATfXAb6JYXqb8eTadl9k74=
=KU3f
-END PGP SIGNATURE-
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


ANN: cocos2d v0.3.0 released

2008-09-06 Thread Lucio Torre
ANN: cocos2d v0.3.0 released
get it at: http://cocos2d.org

see our 45 minutes presentation of cocos2d at:
http://blip.tv/file/1075646/

Whats new:
--
v0.3.0 - September 5th, 2008
  - Added particle systems: Sun, Fire, Fireworks, Meteor, Galaxy,
Flower, Exposion, Spiral
  - Added lerp actions
  - Applied patch by naveen.michaudagrawal
  - Applied patch by Kao Cardoso Félix
  - Applied patch by JeanpierreDA
  - Fixed Camera once locate bug
  - Many bugfixes
  - Primitive vector based line drawing.
  - Tile-map editor

About cocos2d:
--
   cocos2d is a framework for building 2D games, demos, and other
graphical/interactive applications.

Main Features:
--
* Flow control: Manage the flow control between different scenes
in an easy way
* Sprites: Fast and easy sprites
* Actions: Just tell sprites what you want them to do. Composable
actions like move, rotate, scale and much more
* Effects: Effects like waves, twirl, lens and much more
* Tiled Maps: Support for rectangular and hexagonal tiled maps
* Transitions: Move from scene to scene with style
* Menus: Built in classes to create menus
* Text Rendering: Label and HTMLLabel with action support
* Documentation: Programming Guide + API Reference + Video
Tutorials + Lots of simple tests showing how to use it
* Built-in Python Interpreter: For debugging purposes
* BSD License: Just use it
* Pyglet Based: No external dependencies
* OpenGL Based: Hardware Acceleration

more info:
--
home: http://cocos2d.org
download: http://los-cocos.googlecode.com/files/cocos2d-0.3.0.tar.gz
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


short python talk available from osbootcamp.org

2008-09-06 Thread Andrew Ross
Hi All,
 
Open Source Bootcamp (osbootcamp) teaches skills with open source. We
recently had a python talk which we've recorded and made freely available
from the osbootcamp.org videos section. Enjoy!
 
Andrew
http://osbootcamp.org
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


Release 0.3 of Evoque Templating

2008-09-06 Thread Mario Ruggier
Happy to announce release version 0.3 of the Evoque Templating engine  
for python. Other than the bug fixes, a couple recent changes that are  
particularly worthy of mention are:


- Significantly more dynamic
In particular you can now do things like determine the base template  
of a template hierarchy chain dynamically at runtime -- how it is done  
boils down to just using a variable to select which template to to use  
as base template i.e. a template just declares an overlay directive  
such as  $overlay{name=my_site_theme}  and the runtime value of  
my_site_theme will determine which template will be overlaid. This can  
be a very nice way to manage a site theme as per user preferences. For  
further explanations, see:

http://evoque.gizmojo.org/howto/site-template/

- Seamless integration with Pylons
The code for using Evoque as the templating engine in a Pylons  
application is included in the distribution, and detailed description  
of the process is at:

http://evoque.gizmojo.org/ext/pylons/


What is Evoque?
Evoque is a lightweight full-featured generic text templating engine  
for python with sandbox-ability, versatility and simplicity as key  
feature priorities. In spite of its feature-richness, it has a small  
footprint (972 SLOC) and is very fast.


[license] Academic Free License version 3.0
[documentation] http://evoque.gizmojo.org/
[features] http://evoque.gizmojo.org/features/
[download] http://evoque.gizmojo.org/download/
[installation] easy_install evoque

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

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


[ANN] Leipzig Python User Group Meeting, September 09, 2008, 08:00 pm

2008-09-06 Thread Stefan Schwarzer
=== Leipzig Python User Group ===

We will meet on Tuesday, September 09 at 8:00 pm at the training
center of Python Academy in Leipzig, Germany
( http://www.python-academy.com/center/find.html ).

Food and soft drinks are provided. Please send a short
confirmation mail to [EMAIL PROTECTED] , so we can prepare
appropriately.

Everybody who uses Python, plans to do so or is interested in
learning more about the language is welcome.

While the meeting language will be mainly German, we will provide
English translation if needed.

Current information about the meetings are at
http://www.python-academy.com/user-group .

Stefan


== Leipzig Python User Group ===

Wir treffen uns am Dienstag, 09.09.2008 um 20:00 Uhr
im Schulungszentrum der Python Academy in Leipzig
( http://www.python-academy.de/Schulungszentrum/anfahrt.html ).

Für das leibliche Wohl wird gesorgt. Eine Anmeldung unter
[EMAIL PROTECTED] wäre nett, damit wir genug Essen
besorgen können.

Willkommen ist jeder, der Interesse an Python hat, die Sprache
bereits nutzt oder nutzen möchte.

Aktuelle Informationen zu den Treffen sind unter
http://www.python-academy.de/User-Group zu finden.

Viele Grüße
Stefan
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


[ANN] ftputil 2.3 released

2008-09-06 Thread Stefan Schwarzer
ftputil 2.3 is now available from
http://ftputil.sschwarzer.net/download .

Changes since version 2.2.4
---

ftputil has got support for the ``with`` statement which was introduced
by Python 2.5. You can now construct host and remote file objects in
``with`` statements and have them closed automatically (contributed
by Roger Demetrescu). See the documentation for examples.

What is ftputil?


ftputil is a high-level FTP client library for the Python programming
language. ftputil implements a virtual file system for accessing FTP
servers, that is, it can generate file-like objects for remote files.
The library supports many functions similar to those in the os,
os.path and shutil modules. ftputil has convenience functions for
conditional uploads and downloads, and handles FTP clients and servers
in different timezones.

Read the documentation at
http://ftputil.sschwarzer.net/documentation .

License
---

ftputil is Open Source software, released under the revised BSD
license (see http://www.opensource.org/licenses/bsd-license.php ).

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

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


Jython 2.5 Alpha 2 Released!

2008-09-06 Thread Frank Wierzbicki
On behalf of the Jython development team, I'm pleased to announce that
Jython 2.5a2+ is available for download
http://voxel.dl.sourceforge.net/sourceforge/jython/jython_installer-2.5a2.jar.

See the installation instructions http://jython.org/Project/installation.html.

Django runs pretty well on this release. I am attending Djangocon
where Jim Baker and Leo Soto will be presenting on Django on Jython,
and I wanted them to be able to tell people to grab a release instead
of telling them to grab Jython from svn.

There are many bug fixes, but also many bugs that have not yet been fixed.

This is an alpha release so be careful!
--
http://mail.python.org/mailman/listinfo/python-announce-list

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


Re: use str as variable name

2008-09-06 Thread Marco Bizzarri
On Fri, Sep 5, 2008 at 9:16 PM, Bruno Desthuilliers
[EMAIL PROTECTED] wrote:
 Marco Bizzarri a écrit :

 Just a question: generic functions are not meant in the sense of
 generic functions of CLOS, am I right?

 Nope. Just generic in the sense that they accept any object implementing a
 very minimal interface.

 If you want something like CLOS multimethods, you may be interested in
 Philip Eby's ruledispatch.


Even though I loved them when I used at university, I'm not looking
for them right now... but nice to know that they are available under
python :-)


-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: use str as variable name

2008-09-06 Thread Marco Bizzarri
On Sat, Sep 6, 2008 at 7:52 AM, Fredrik Lundh [EMAIL PROTECTED] wrote:
 Marco Bizzarri wrote:

 (...as Bruno implies, setattr(), len() et al can be and should be viewed
 as
 generic functions.

 Just a question: generic functions are not meant in the sense of
 generic functions of CLOS, am I right?

 it's meant in exactly that sense: len(L) means of all len() implementations
 available to the runtime, execute the most specific code we have for the
 object L.


It is a generic functions like a CLOS one, as long as we remain to one
parameter.

I mean, there will be just one implemenatation of

foo(bar, man)

which the python interpretr can find; am I right?

-- 
Marco Bizzarri
http://notenotturne.blogspot.com/
http://iliveinpisa.blogspot.com/
--
http://mail.python.org/mailman/listinfo/python-list


Re: use str as variable name

2008-09-06 Thread Michele Simionato
On Sep 6, 8:02 am, Marco Bizzarri [EMAIL PROTECTED] wrote:
 On Fri, Sep 5, 2008 at 9:16 PM, Bruno Desthuilliers

 [EMAIL PROTECTED] wrote:
  Marco Bizzarri a écrit :

  Just a question: generic functions are not meant in the sense of
  generic functions of CLOS, am I right?

  Nope. Just generic in the sense that they accept any object implementing a
  very minimal interface.

  If you want something like CLOS multimethods, you may be interested in
  Philip Eby's ruledispatch.

 Even though I loved them when I used at university, I'm not looking
 for them right now... but nice to know that they are available under
 python :-)

Actually they are already available in the standard library but they
are undocumented. See for instance
this recent blog post of mine:

http://www.artima.com/weblogs/viewpost.jsp?thread=237764

(as well as the comment below by P.J. Eby)
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-06 Thread Steven D'Aprano
On Sat, 06 Sep 2008 00:33:25 -0400, Manu Hack wrote:

 Actually it's even more natural to state sum([x]) = x, and this way you
 can never conclude that sum([]) = 0 from there.

But what you can say is that for any list L, sum(L) = sum(L + [0]).

Therefore sum([]) = sum([] +[0]) = 0



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


wxPython problem

2008-09-06 Thread Peter Anderson
I am trying to teach myself how to program in Python and use wxPython 
for GUIs. I am using PyScripter, IDLE and EditPlus as my IDEs. I have 
experienced an odd problem where I run a script once and it runs fine. 
Run it again and I get an error and the script fails.


If the script is run directly from Python ('Run' from Windows Explorer) 
or from EditPlus (in which I have a user-defined tool which calls 
C:\Python25\pythonw.exe with the parameter of $(FileName)) then there is 
*never* any error, no matter how many times the script is run.


Close down PyScripter or IDLE and then start either up again, load the 
script and run it - it runs fine. Run it again and it fails. It seems 
like something is already set in memory and cant be re-set (my lack of 
knowledge is showing here :-( ).


More details are shown below. Any help or hints would be greatly 
appreciated.


Regards,
Peter


RUNNING SIMPLE.PY (AND OTHER SCRIPTS USING WXPYTHON) FROM PYSCRIPTER I 
GET THE FOLLOWING ERROR MESSAGE:


PyNoAppError: The wx.App object must be created first!

PyScripter loads a module (I presume from wxPython) called _windows.py 
and highlights a particular line in red and displays the error message 
from above. I have Googled the error message but the results have not 
helped.



LISTING FOR SIMPLE.PY

#!/usr/bin/python

# simple.py

import wx

app = wx.App()

frame = wx.Frame(None, -1, 'simple.py')
frame.Show()

app.MainLoop()


EXERPT FROM _WINDOWS.PY - PYSCRIPTER HIGHLIGHTS SECOND LAST LINE

class Frame(TopLevelWindow):
Proxy of C++ Frame class
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), 
doc='The membership flag')

__repr__ = _swig_repr
def __init__(self, *args, **kwargs):

__init__(self, Window parent, int id=-1, String title=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) - Frame


# The following line is highlighted as where the error occures

_windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs))
self._setOORInfo(self)


RUNNING THE SIMPLE.PY SCRIPT FROM WITHIN IDLE PRODUCES THE FOLLOWING 
ERROE MESSAGE:


Traceback (most recent call last):
File C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython 
Tutorial\absolute.py, line 28, in module

Absolute(None, -1, '')
File C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython 
Tutorial\absolute.py, line 9, in __init__

wx.Frame.__init__(self, parent, id, title, size=(250, 180))
File C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py, 
line 505, in __init__

_windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs))
PyNoAppError: The wx.App object must be created first!


--
*Peter Anderson*
There is nothing more difficult to take in hand, more perilous to 
conduct, or more uncertain in its success, than to take the lead in the 
introduction of a new order of things—Niccolo Machiavelli, /The Prince/, 
ch. 6

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


Re: max(), sum(), next()

2008-09-06 Thread Manu Hack
On Sat, Sep 6, 2008 at 12:57 AM, castironpi [EMAIL PROTECTED] wrote:
 On Sep 5, 9:20 pm, Manu Hack [EMAIL PROTECTED] wrote:
 On Fri, Sep 5, 2008 at 1:04 PM, castironpi [EMAIL PROTECTED] wrote:
  On Sep 5, 3:28 am, Manu Hack [EMAIL PROTECTED] wrote:
  On Thu, Sep 4, 2008 at 4:25 PM, castironpi [EMAIL PROTECTED] wrote:
   On Sep 4, 2:42 pm, [EMAIL PROTECTED] wrote:
   David C. Ullrich:

At least in mathematics, the sum of the elements of
the empty set _is_ 0, while the maximum element of the
empty set is undefined.

   What do you think about my idea of adding that 'default' argument to
   the max()/min() functions?

   Bye,
   bearophile

   For max and min, why can't you just add your argument to the set
   itself?

   The reason max([]) is undefined is that max( S ) is in S.

  It makes sense.

  The reason sum([]) is 0 is that sum( [ x ] ) - x = 0.

  It doesn't make sense to me.  What do you set x to?

  For all x.

 But then how can you conclude sum([]) = 0 from there?  It's way far
 from obvious.

 You can define sum([a1,a2,...,aN]) recursively as
 sum([a1,a2,...a(N-1)])+aN.  Call the sum sum([a1,a2,...,aN]) X, then
 subtract aN.

 sum([a1,a2,...a(N-1)])+aN=X
 sum([a1,a2,...a(N-1)])+aN-aN=X-aN

 For N=2, we have:

 sum([a1,a2])=X
 sum([a1,a2])-a2=X-a2
 sum([a1,a2])-a2-a1=X-a2-a1

 Since X= a1+ a2, replace X.

 sum([a1,a2])-a2-a1=(a1+a2)-a2-a1

 Or,

 sum([a1,a2])-a2-a1=0

 Apply the recursive definition:

 sum([a1])+a2-a2-a1=0

 And again:

 sum([])+a1+a2-a2-a1=0

 And we have:

 sum([])=0.

It makes more sense now, I just wanted to point out that only with
sum([x]) = x, you can't get sum([]) = 0.
--
http://mail.python.org/mailman/listinfo/python-list


Re: embed python in ms-word?

2008-09-06 Thread Gerhard Häring
oyster wrote:
 In my ms-word documnet, there are some calculation whihc I have to
 change due to different argumnet. is there any way to embed python
 code in word, so that I can write the following as a macro or
 something else, then the result (i.e. 2) is shown in the word
 documnet?
 
 def f(n):
   if n2:
 return 1
   else:
 return f(n-1)+f(n-2)
 main()
   return 'fib(3)=%0i' % f(3)
 
 if that is impossible, does there exist such word-addons can do that? thanx

With Python and the win32 extensions you can write COM servers. These
you can use from Visual Basic for Applications (VBA).

But it's really only worth the effort if you're doing something less
trivial than above ;-)

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


Re: wxPython problem

2008-09-06 Thread Stef Mientki

Peter Anderson wrote:
I am trying to teach myself how to program in Python and use wxPython 
for GUIs. I am using PyScripter, IDLE and EditPlus as my IDEs. I have 
experienced an odd problem where I run a script once and it runs fine. 
Run it again and I get an error and the script fails.


If the script is run directly from Python ('Run' from Windows 
Explorer) or from EditPlus (in which I have a user-defined tool 
which calls C:\Python25\pythonw.exe with the parameter of $(FileName)) 
then there is *never* any error, no matter how many times the script 
is run.


Close down PyScripter or IDLE and then start either up again, load the 
script and run it - it runs fine. Run it again and it fails. It seems 
like something is already set in memory and cant be re-set (my lack of 
knowledge is showing here :-( ).


In PyScripter, you should run wxPython in the plain remote machine (not 
the wxPython remote),
and you should set reset before run flag or reset the remote machine 
each time yourself.


cheers,
Stef
More details are shown below. Any help or hints would be greatly 
appreciated.


Regards,
Peter


RUNNING SIMPLE.PY (AND OTHER SCRIPTS USING WXPYTHON) FROM PYSCRIPTER I 
GET THE FOLLOWING ERROR MESSAGE:


PyNoAppError: The wx.App object must be created first!

PyScripter loads a module (I presume from wxPython) called _windows.py 
and highlights a particular line in red and displays the error message 
from above. I have Googled the error message but the results have not 
helped.



LISTING FOR SIMPLE.PY

#!/usr/bin/python

# simple.py

import wx

app = wx.App()

frame = wx.Frame(None, -1, 'simple.py')
frame.Show()

app.MainLoop()


EXERPT FROM _WINDOWS.PY - PYSCRIPTER HIGHLIGHTS SECOND LAST LINE

class Frame(TopLevelWindow):
Proxy of C++ Frame class
thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), 
doc='The membership flag')

__repr__ = _swig_repr
def __init__(self, *args, **kwargs):

__init__(self, Window parent, int id=-1, String title=EmptyString,
Point pos=DefaultPosition, Size size=DefaultSize,
long style=DEFAULT_FRAME_STYLE, String name=FrameNameStr) - Frame


# The following line is highlighted as where the error occures

_windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs))
self._setOORInfo(self)


RUNNING THE SIMPLE.PY SCRIPT FROM WITHIN IDLE PRODUCES THE FOLLOWING 
ERROE MESSAGE:


Traceback (most recent call last):
File C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython 
Tutorial\absolute.py, line 28, in module

Absolute(None, -1, '')
File C:\Documents and Settings\Peter\My Documents\Dev\Python\WxPython 
Tutorial\absolute.py, line 9, in __init__

wx.Frame.__init__(self, parent, id, title, size=(250, 180))
File 
C:\Python25\Lib\site-packages\wx-2.8-msw-unicode\wx\_windows.py, 
line 505, in __init__

_windows_.Frame_swiginit(self,_windows_.new_Frame(*args, **kwargs))
PyNoAppError: The wx.App object must be created first!




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


Cancel instance create

2008-09-06 Thread Aigars Aigars
Good day,

I want MyClass to perform some tests and if them fail, I do not want
instance to be created. 

But in code I wrote instance is created and also has parameters, that
it should not have in case of tests failure.

Is there a way to perform tests in MyClass.__init__ and set instance
to None without any parameters?

I do not want che code outside MyClass.__init__ to know anything
about tests performed, and make decision to allow or prevent instance
creation.  

The code I wrote is:
**
class MyClass():
 def __init__(self):
  self.param = spam
  Test = False
   if Test == True: 
  print Creating
instance...
   return 
 else:
  print Instance creation
not allowed...
  self = None
  return None
a = MyClass()
print a
print a.param
*

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

Re: use str as variable name

2008-09-06 Thread Fredrik Lundh

Marco Bizzarri wrote:


Just a question: generic functions are not meant in the sense of
generic functions of CLOS, am I right?



it's meant in exactly that sense: len(L) means of all len() implementations
available to the runtime, execute the most specific code we have for the
object L.



It is a generic functions like a CLOS one, as long as we remain to one
parameter.

I mean, there will be just one implemenatation of

foo(bar, man)

which the python interpretr can find; am I right?


Let's see if I can sort this out without causing even more confusion.

The Python *language* doesn't support generic functions in the CLOS 
sense, but a given Python *implementation* may use a dispatching 
machinery to select the best possible implementation for any call to a 
built-in function.


Or in other words, the len() function shouldn't just be seen as a 
function that *always* does


def len(L):
return L.__len__()

because if you look under the covers, it might be more like (using a 
hypothetical Python dialect):


def generic len(L: list):
return list::get_size(L) # fast internal dispatch

def generic len(L: tuple):
return tuple::get_size(L) # fast internal dispatch

def generic len(L: object):
return L.__len__() # fallback behaviour, using method dispatch

where len represents a plurality of possible len implementations.

How the dispatching is actually done is up to the specific Python 
implementation; CPython, for example, offers a slot mechanism for 
types implemented in C that's quite a bit faster than the method call 
machinery.  And the slot mechanism isn't always single dispatch.  For 
example, internal getattr(obj, name) calls use one of several slots, 
depending on what name is.


Other Python implementations may use different approaches, but the point 
remains: a builtin function operation(a, b, c) isn't always mapped to 
a.__operation__(b, c) by the runtime; code that uses the latter form 
may be less efficient.  And it's definitely less Pythonic.


/F

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


Re: Cancel instance create

2008-09-06 Thread Fredrik Lundh

Aigars Aigars wrote:

I want MyClass to perform some tests and if them fail, I do not want 
instance to be created.


But in code I wrote instance is created and also has parameters, that it 
should not have in case of tests failure.


Is there a way to perform tests in MyClass.__init__ and set instance to 
None without any parameters?


if you want construction to fail, raise an exception.

...

def __init__(self):
self.param = spam
Test = False
if Test: # please don't use explicit tests for truth
print Creating instance...
else:
raise ValueError(some condition failed)

(pick an exception class that matches the actual error, or create your 
own class if necessary)


/F

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


Re: Cancel instance create

2008-09-06 Thread Mohamed Yousef
ًWhat about no Constructor , and a custom instancing function that can
return either None or the instance wanted
--
http://mail.python.org/mailman/listinfo/python-list

Re: Cancel instance create

2008-09-06 Thread Diez B. Roggisch

Mohamed Yousef schrieb:

ًWhat about no Constructor , and a custom instancing function that can
return either None or the instance wanted


That doesn't solve the underlying problem - the instance is created. 
Just because it wasn't *returned*, doesn't mean it isn't there.


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

Re: Cancel instance create

2008-09-06 Thread Aigars Aigars
I do not want code outside my class to perform tests and decide to
create instance or not.
Fredrik Lundh's advice to rise exception works perfectly.

Thanks to all,
Aigars
 Quoting Mohamed Yousef : #1611;What about no Constructor , and a
custom instancing function that can
 return either None or the instance wanted
 --
 http://mail.python.org/mailman/listinfo/python-list
 

Links:
--
[1] mailto:[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list

Re: quake like multicoloured text

2008-09-06 Thread Durand
On Sep 5, 10:32 pm, Gabriel Genellina [EMAIL PROTECTED]
wrote:
 En Fri, 05 Sep 2008 16:24:08 -0300, Durand [EMAIL PROTECTED] escribió:





  I'm wondering how I could render text with PIL in which different
  parts of the text are different characters. This is for a game stats
  script where names are written like:
  ^1Red ^2Green ^3Yellow, etc.
  The problem is that I currently use text in the ImageDraw module but
  the only way I can think of rendering text is by rendering each bit of
  text in a separate colour.

  Example:

  draw.text((0,0),Red, fill=red)
  draw.text((30,0),Green, fill=green)
  draw.text((60,0),Yellow, fill=green)

  except that I'm not sure how much spacing there is between each
  coloured bit of text(30px is assumed in the example)...Would there be
  an alternate method of doing this?

 You could use the draw.textsize method to measure how much space will take  
 each part...

 --
 Gabriel Genellina

Thanks, I guess I should have done more research...
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-06 Thread Ken Starks

castironpi wrote:

On Sep 5, 9:20 pm, Manu Hack [EMAIL PROTECTED] wrote:

On Fri, Sep 5, 2008 at 1:04 PM, castironpi [EMAIL PROTECTED] wrote:

On Sep 5, 3:28 am, Manu Hack [EMAIL PROTECTED] wrote:

On Thu, Sep 4, 2008 at 4:25 PM, castironpi [EMAIL PROTECTED] wrote:

On Sep 4, 2:42 pm, [EMAIL PROTECTED] wrote:

David C. Ullrich:

At least in mathematics, the sum of the elements of
the empty set _is_ 0, while the maximum element of the
empty set is undefined.

What do you think about my idea of adding that 'default' argument to
the max()/min() functions?
Bye,
bearophile

For max and min, why can't you just add your argument to the set
itself?
The reason max([]) is undefined is that max( S ) is in S.

It makes sense.

The reason sum([]) is 0 is that sum( [ x ] ) - x = 0.

It doesn't make sense to me.  What do you set x to?

For all x.

But then how can you conclude sum([]) = 0 from there?  It's way far
from obvious.


You can define sum([a1,a2,...,aN]) recursively as
sum([a1,a2,...a(N-1)])+aN.  Call the sum sum([a1,a2,...,aN]) X, then
subtract aN.

sum([a1,a2,...a(N-1)])+aN=X
sum([a1,a2,...a(N-1)])+aN-aN=X-aN

For N=2, we have:

sum([a1,a2])=X
sum([a1,a2])-a2=X-a2
sum([a1,a2])-a2-a1=X-a2-a1

Since X= a1+ a2, replace X.

sum([a1,a2])-a2-a1=(a1+a2)-a2-a1

Or,

sum([a1,a2])-a2-a1=0

Apply the recursive definition:

sum([a1])+a2-a2-a1=0

And again:

sum([])+a1+a2-a2-a1=0

And we have:

sum([])=0.



This is not necessarily so.

The flaw is that you provide a recursive definition with no start value,
which is to say it is not a recursive definition at all.

A recursive definition should be (for lists where elements
can be added, and ignoring pythonic negative indexing):

Define 'sum(L)' by
a.  sum(L[0]) = L[0]
b.  sum(L[0:i]) = sum(L[0:i-1]) + L[i]  ... if i  0

From this you can prove the reverse recursion
sum{L[0:k]) = sum(L[0:k+1]) - L[k+1]
   __only__ if k = 0

It says nothing about the empty list.

You could add, as part of the definition, that sum{[]) = 0, or any other 
value.


A rather different approach, not quite simple recursion, would be to
start with

A. a slicing axiom, something like:

  for all non-negative integers, a,b,c with a =b = c:

  sum(L[a:c]) = sum(L[a:b]) + sum(L[b:c])

B. a singleton axiom:

  for all integers a where L[a] exists:
 sum(L[a:a]) = L[a]




2a.  sum{
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-06 Thread Ken Starks

castironpi wrote:

On Sep 5, 9:20 pm, Manu Hack [EMAIL PROTECTED] wrote:

On Fri, Sep 5, 2008 at 1:04 PM, castironpi [EMAIL PROTECTED] wrote:

On Sep 5, 3:28 am, Manu Hack [EMAIL PROTECTED] wrote:

On Thu, Sep 4, 2008 at 4:25 PM, castironpi [EMAIL PROTECTED] wrote:

On Sep 4, 2:42 pm, [EMAIL PROTECTED] wrote:

David C. Ullrich:

At least in mathematics, the sum of the elements of
the empty set _is_ 0, while the maximum element of the
empty set is undefined.

What do you think about my idea of adding that 'default' argument to
the max()/min() functions?
Bye,
bearophile

For max and min, why can't you just add your argument to the set
itself?
The reason max([]) is undefined is that max( S ) is in S.

It makes sense.

The reason sum([]) is 0 is that sum( [ x ] ) - x = 0.

It doesn't make sense to me.  What do you set x to?

For all x.

But then how can you conclude sum([]) = 0 from there?  It's way far
from obvious.


You can define sum([a1,a2,...,aN]) recursively as
sum([a1,a2,...a(N-1)])+aN.  Call the sum sum([a1,a2,...,aN]) X, then
subtract aN.

sum([a1,a2,...a(N-1)])+aN=X
sum([a1,a2,...a(N-1)])+aN-aN=X-aN

For N=2, we have:

sum([a1,a2])=X
sum([a1,a2])-a2=X-a2
sum([a1,a2])-a2-a1=X-a2-a1

Since X= a1+ a2, replace X.

sum([a1,a2])-a2-a1=(a1+a2)-a2-a1

Or,

sum([a1,a2])-a2-a1=0

Apply the recursive definition:

sum([a1])+a2-a2-a1=0

And again:

sum([])+a1+a2-a2-a1=0

And we have:

sum([])=0.



This is not necessarily so.

The flaw is that you provide a recursive definition with no start value,
which is to say it is not a recursive definition at all.

A recursive definition should be (for lists where elements
can be added, and ignoring pythonic negative indexing):

Define 'sum(L)' by
a.  sum(L[0:1]) = L[0]
b.  sum(L[0:i]) = sum(L[0:i-1]) + L[i]  ... if i  1

From this you can prove the reverse recursion
sum{L[0:k]) = sum(L[0:k+1]) - L[k+1]
   __only__ if k = 0

It says nothing about the empty list.

You could add, as part of the definition, that sum{[]) = 0, or any other
value.

A rather different approach, not quite simple recursion, would be to
start with

A. a slicing axiom, something like:

  for all non-negative integers, a,b,c with a =b = c:

  sum(L[a:c]) = sum(L[a:b]) + sum(L[b:c])

B. a singleton axiom:

  for all integers a where L[a] exists:
 sum(L[a:a]) = L[a]




2a.  sum{
--
http://mail.python.org/mailman/listinfo/python-list


Re: embed python in ms-word?

2008-09-06 Thread oyster
in fact, during my work, I often write documnets in ms-word. But the
doc has many numbers in it, which need to be calculated and to be
modified frequently.

Is there a method to write a ms-word add-in, so that
1.I can type in the calculation steps in some program language,
please have a look at http://blender.bokee.com/inc/word_add_in1.jpg

2.then the result (here, it is 8) is shown in the doc when I close this window?
please have a look at http://blender.bokee.com/inc/word_add_in2.jpg

3.when I double-click the result 8, I can view/edit the code again

4.the code for calculation  is stored in DOC file too, I can change it later

mathtype equation is a kind of such thing, but only for displaying
nice equation

I don't think vba is a good answer, the main reason is: the vba code
has an incompact link with its result in the documnet
--
http://mail.python.org/mailman/listinfo/python-list


Re: why is self not passed to id()? solution

2008-09-06 Thread Ruediger

I found following solution to the problem.

Instead of assigning id directly to __hash__ it has to be wrapped with an
instancemethod object. It is somehow strange that this doesn't happen
automatically and it is also strange that instancemethod isn't exposed in
the type module. However it can easily be done and is speeding things up
by almost an factor of 2.

Thank's again for all the help.

Rüdiger

**

class foo(list):
__hash__ = lambda x: id(x)

instancemethod = type(foo.__hash__)

class bar(list):
pass
bar.__hash__ = instancemethod(id, None, bar)

def test0( obj ):
_s_ = set()
_s_add = _s_.add
_s_pop = _s_.pop
for _i_ in xrange(100):
_s_add(obj())
_s_pop()

def test1():
return test0(foo)
def test2():
return test0(bar)

if __name__ == '__main__':
test1()
test2()
pass

**
python -m cProfile test01.py

 610 function calls in 30.547 CPU seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
10.0000.000   30.547   30.547 string:1(module)
10.0000.000   30.547   30.547 test01.py:1(module)
10.0000.0000.0000.000 test01.py:1(foo)
2   10.7845.392   30.547   15.273 test01.py:10(test0)
10.0000.000   19.543   19.543 test01.py:18(test1)
  1004.5540.0006.7000.000 test01.py:2(lambda)
10.0000.000   11.003   11.003 test01.py:20(test2)
10.0000.0000.0000.000 test01.py:6(bar)
10.0010.001   30.547   30.547 {execfile}
  1002.1460.0002.1460.000 {id}
  2008.6260.000   15.3270.000 {method 'add' of 'set'objects}
  2004.4360.0004.4360.000 {method 'pop' of 'set'objects}

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

Re: embed python in ms-word?

2008-09-06 Thread Diez B. Roggisch

oyster schrieb:

in fact, during my work, I often write documnets in ms-word. But the
doc has many numbers in it, which need to be calculated and to be
modified frequently.

Is there a method to write a ms-word add-in, so that
1.I can type in the calculation steps in some program language,
please have a look at http://blender.bokee.com/inc/word_add_in1.jpg

2.then the result (here, it is 8) is shown in the doc when I close this window?
please have a look at http://blender.bokee.com/inc/word_add_in2.jpg

3.when I double-click the result 8, I can view/edit the code again

4.the code for calculation  is stored in DOC file too, I can change it later

mathtype equation is a kind of such thing, but only for displaying
nice equation

I don't think vba is a good answer, the main reason is: the vba code
has an incompact link with its result in the documnet


I don't know what you mean with the last sentence - but I still think 
VBA is the answer. There is no other way to write a plugin or some such 
for word than using COM, and VB *is* COM. So whatever you can do in 
Word, it's exposed in VBA. Bringing python into the mixture is just 
creating a lot of hassle.


Automating word with Python is a different thing - that seems to be 
popular and powerful.


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


Re: running python as a dameon

2008-09-06 Thread Michael Palmer
On Sep 5, 9:56 pm, Sean Davis [EMAIL PROTECTED] wrote:
  What I want
  to do is to provide the python NLP program as a service to any other
  PHP/Java/Ruby process request. So the mapping is

  http - apache - PHP/Java/Ruby/... - Python NLP

 Why not use a simple CGI script or wsgi application?  You could make
 the service online and interactive and with the same application and
 code make an XMLRPC web service.  So, things would look more like:

 http - apache - Python (running NLP and serving requests)

 You can use apache to proxy requests to any one of a dozen or so
 python-based webservers.  You could also use mod_wsgi to interface
 with a wsgi application.

 Sean

xmlrpc is the right idea, as it interfaces easily across languages.
--
http://mail.python.org/mailman/listinfo/python-list


How to bring subprocess to the foreground?

2008-09-06 Thread dudeja . rajat
Hi,

I've a batch file that I open with the subprocess .Popen() . When this
batch file is run I want to bring it to the foreground.

Please suggest how can I do this?


Regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to bring subprocess to the foreground?

2008-09-06 Thread Diez B. Roggisch

[EMAIL PROTECTED] schrieb:

Hi,

I've a batch file that I open with the subprocess .Popen() . When this
batch file is run I want to bring it to the foreground.

Please suggest how can I do this?


You can't. You can capture the stdout using the pipe-arguments, and in 
your main-process, read that and write it to the main process' stdout.


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


Re: wxPython problem

2008-09-06 Thread Peter Anderson
Stef Mientki said: In PyScripter, you should run wxPython in the plain 
remote machine (not the wxPython remote),and you should set reset 
before run flag or reset the remote machine each time yourself.


Stef,

Thanks for the help! It has taken several hours to find and install the 
correct version of Rpyc (which is required to run the remote Python 
engine but it now seems to be working fine. And the Reinitialise the 
Python engine {Alt]+[F2] does need to be done between script runs. 
Given all that, the script now runs multiple times in PyScripter. The 
script still only runs ONCE in IDLE but I can live with that.


In case others find this message from a search; I am using Python 2.5.2 
and it requires rpyc-2.60.zip from the Rpyc download page (see 
http://rpyc.wikispaces.com/ click on the Download link and make sure 
you select the main link under the Packages column at Sourceforge. 
You will be shown a list of Rpyc versions. For Python 2.5.2 choose 
Relese 2.60. This will save you the several hours its cost me.


Thanks again Stef.

Regards,
Peter
--
Peter Anderson
There is nothing more difficult to take in hand, more perilous to 
conduct, or more uncertain in its success, than to take the lead in the 
introduction of a new order of things—Niccolo Machiavelli, /The Prince/, 
ch. 6

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


Re: max(), sum(), next()

2008-09-06 Thread Mel
Steven D'Aprano wrote:

 On Sat, 06 Sep 2008 00:33:25 -0400, Manu Hack wrote:
 
 Actually it's even more natural to state sum([x]) = x, and this way you
 can never conclude that sum([]) = 0 from there.
 
 But what you can say is that for any list L, sum(L) = sum(L + [0]).
 
 Therefore sum([]) = sum([] +[0]) = 0

Yep.  The way it is preserves the distributive property

sum(a+b) = sum(a) + sum(b)

This would matter in cases like (untested code..)

suvsales = sum (sum (s.price for s in d.sales if s.class='suv') for d in
districts)


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


Canonical way to build Python 2.6/svn on MacIntel/MacOSX10.5 with icc 32bits 10.1.014

2008-09-06 Thread Mathieu Prevot
Hi,

I would like to build Python (svn) on Macosx 10.5 with icc in
/opt/intel/cc (32 bit). Can you help me to determine the right way to
do this ?

I got a prototype with:

export CC=icc
export CXX=icpc
export CFLAGS=-w
./configure --with-framework-name=PythonIntel

1) It seems to be unsufficient. Does someone have links/mail
archives/patches/scripts ?

2) Python needs gettext for _locale package, but I fail to compile it with icc.

3) How can I build an autonomous and sufficient distribution (a dmg
file with everything in it) ?

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


Re: How to bring subprocess to the foreground?

2008-09-06 Thread dudeja . rajat
On Sat, Sep 6, 2008 at 3:13 PM, Diez B. Roggisch [EMAIL PROTECTED] wrote:
 [EMAIL PROTECTED] schrieb:

 Hi,

 I've a batch file that I open with the subprocess .Popen() . When this
 batch file is run I want to bring it to the foreground.

 Please suggest how can I do this?

 You can't. You can capture the stdout using the pipe-arguments, and in your
 main-process, read that and write it to the main process' stdout.

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


Hi Diez,

Thanks for the information.
That's valuable information.

I though of displayin an information message on the screen through
tkMessageBox while the subprocess is running, I did it using:

try:
testing = subprocess.Popen([batchFilePath], \
   shell = True)

retCode = testing.wait()
tkMessageBox._show(Test Harness execution, \
   icon = 'info', \
   message=Testing %s in progress... % libName)
except:
tkMessageBox._show(Error, \
   type='ok', icon='error', \
   message=Error executing %s Test
Harness % libName)
return None
else:
print retCode


But the message is never displayed. Please suggest if there is
something wrong with this code

-- 
Regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


[matplotlib] Overlapping axis text

2008-09-06 Thread Durand
I got a really annoying problem with datetime graphs. The problem is
that with a long range time graph, the text on the x axis keeps
overlapping like here: http://durand.zephyrhosting.net/tremcs/graph_all.png

Would there be any way to fix this? I was thinking of rotating the
text so that there was enough space for each one but the best solution
would be to only display text with the right scale. IE, with a 7 day
graph, each day would have text, with a year long graph, each month
would be displayed, etc...

This is the code I use at the moment but its pretty messy:

import dateutil,pylab
from matplotlib.dates import MonthLocator, WeekdayLocator

fig = pylab.figure()
ax = fig.add_subplot(111)
days= MonthLocator()   # every monday
months   = MonthLocator()  # every month
ax.xaxis.set_major_locator(months)
ax.xaxis.set_minor_locator(days)

pylab.plot_date(pylab.date2num(dates), allkills, '.-', color='blue')
pylab.plot_date(pylab.date2num(dates), alldeaths, '.-',
color='red')
pylab.plot_date(pylab.date2num(dates), kills, '.-',
color='darkgreen')
pylab.plot_date(pylab.date2num(dates), deaths, '.-',
color='orange')
if legend == 1:
pylab.legend((Total Kills,Total Deaths, Single
Session Kills, Single Session Deaths), 'lower left')
pylab.xlabel('Date')
pylab.ylabel('Stats')
ax2 = pylab.twinx()
pylab.plot_date(pylab.date2num(dates), allratio, '.-',
color='purple')
pylab.plot_date(pylab.date2num(dates), ratio, '.-',
color='yellow')
pylab.ylabel('Ratio')
ax2.yaxis.tick_right()
pylab.show()
Please excuse the extra tabbing, it's part of an if statement.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Overlapping axis text

2008-09-06 Thread Durand
Err...made a mistake there.

days= WeekdayLocator()   # every monday
months   = MonthLocator()  # every month

That doesn't change my question though.

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


Calling global functions from a class?

2008-09-06 Thread Robert Dailey
HI,

I have the following python script:


def __normalizePath( path ):
return osp.abspath( osp.normpath( path ) )

class AbsolutePath:
def __init__( self, root= ):
_root = __normalizePath( root )


When I create an AbsolutePath object, I get the following error:

NameError: global name '_AbsolutePath__normalizePath' is not defined


Is there a reason for this? How can I make this work?
--
http://mail.python.org/mailman/listinfo/python-list

Want to display a message box while subprocess is running

2008-09-06 Thread dudeja . rajat
Hi,


I m using subprocess module and using the Popen call. While the
subprocess if running, I want to display a tkMessageBox().

Does some one has a sample code for this?


Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calling global functions from a class?

2008-09-06 Thread Fredrik Lundh

Robert Dailey wrote:


I have the following python script:

def __normalizePath( path ):
return osp.abspath( osp.normpath( path ) )
   
class AbsolutePath:

def __init__( self, root= ):
_root = __normalizePath( root )


When I create an AbsolutePath object, I get the following error:

NameError: global name '_AbsolutePath__normalizePath' is not defined

Is there a reason for this?


the __ prefix (double underscores) is reserved for private attributes 
and methods in a class.  it does not work for module-level names.


 How can I make this work?

rename the global function.

/F

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


Failure in building ctypes with intel icc

2008-09-06 Thread Mathieu Prevot
Hi,

I got this error in compilation, and I don't know how to solve it:

*** WARNING: renaming _ctypes since importing it failed:
dlopen(build/lib.macosx-10.3-i386-2.6/_ctypes.so, 2): Symbol not
found: ___builtin_dwarf_cfa
  Referenced from:
/Users/mathieuprevot/svn/python/build/lib.macosx-10.3-i386-2.6/_ctypes.so
  Expected in: dynamic lookup

Any hints ?

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


Re: Cancel instance create

2008-09-06 Thread Terry Reedy



Fredrik Lundh wrote:

Aigars Aigars wrote:

I want MyClass to perform some tests and if them fail, I do not want 
instance to be created.


If you do not want the instance created at all, you would have to write 
a custom .__new__ method, but that is tricky, something I would have to 
look up how to do, and most likely not needed.  Fredrik's solution below 
is much easier and the one I would use if at all possible.


But in code I wrote instance is created and also has parameters, that 
it should not have in case of tests failure.


Is there a way to perform tests in MyClass.__init__ and set instance 
to None without any parameters?


if you want construction to fail, raise an exception.

...

def __init__(self):


At this point, you have an instance of your class bound to local name 
'self'.  Usually, its only individual attributes are (in 3.0, anyway, as 
far as I can tell) .__class__ and an empty .__dict__.  Of course, it 
inherits class and superclass attributes, but it is otherwise blank. 
(The main exception would be if you were inheriting from an immutable 
class that set attributes in .__new__, but then you would not be writing 
.__init__.)



self.param = spam
Test = False
if Test: # please don't use explicit tests for truth
print Creating instance...
else:
raise ValueError(some condition failed)

(pick an exception class that matches the actual error, or create your 
own class if necessary)


Once the exception gets disposed of (if not before), the blank instance 
gets unbound from 'self' and since it does not get bound to anything 
else, it becomes eligible for garbage collection.


tjr

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


Re: How to bring subprocess to the foreground?

2008-09-06 Thread Paul Boddie
On 6 Sep, 17:58, [EMAIL PROTECTED] wrote:

 I though of displayin an information message on the screen through
 tkMessageBox while the subprocess is running, I did it using:

 try:
 testing = subprocess.Popen([batchFilePath], \
shell = True)

 retCode = testing.wait()

Note that you wait for the process to finish here...

 tkMessageBox._show(Test Harness execution, \
icon = 'info', \
message=Testing %s in progress... % libName)

...and that you show a message about the process running *after*
waiting until it isn't running any more.

 except:
 tkMessageBox._show(Error, \
type='ok', icon='error', \
message=Error executing %s Test
 Harness % libName)
 return None
 else:
 print retCode

 But the message is never displayed. Please suggest if there is
 something wrong with this code

I think you should first show your message, *then* wait for the
process to finish.

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


Re: why is self not passed to id()? solution

2008-09-06 Thread Terry Reedy



Ruediger wrote:

I found following solution to the problem.

Instead of assigning id directly to __hash__ it has to be wrapped with an
instancemethod object. It is somehow strange that this doesn't happen
automatically and it is also strange that instancemethod isn't exposed in
the type module.


There are several internal implementation types not exposed in types 
because they are subject to change from version to version  In 3.0, your 
code does not work.  Instancemethod may to added to 3.0 or 3.1 as a 
built-in function.



**

class foo(list):
__hash__ = lambda x: id(x)
type
instancemethod = type(foo.__hash__)


In 2.x, this gives you 'instancemethod'.  In 3.0, you get 'function' as 
unbound methods are no longer wrapped when the underlying function is a 
'function' (resulting from def or lambda abbreviation).



class bar(list):
pass
bar.__hash__ = instancemethod(id, None, bar)


Calling a 'function' with those parameters will not work.
Did you miss the following from my previous response?

There *is* a third alternative, which works in this case, and which 
should be closer in speed to id.  I will leave you to do a speed test.


 class bang(list):
__hash__ = object.__hash__

 s=set()
 s.add(bang())
 s
{[]}

 __eq__ = object.__eq__ should also work instead of the Python 
implementation I gave in my response to another response.


I would expect the already-wrapped id should work in 2.x also.

Terry Jan Reedy

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


Re: max(), sum(), next()

2008-09-06 Thread Mensanator
On Sep 5, 10:45�pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Fri, 05 Sep 2008 22:20:06 -0400, Manu Hack wrote:
  On Fri, Sep 5, 2008 at 1:04 PM, castironpi [EMAIL PROTECTED] wrote:

snip

 [The rest of this is (mostly) aimed at Mensanator,

Ok, I see where you're coming from.

 Fundamentally, the abstract function sum and the concrete Python
 implementation of sum() are both human constructs. It's not like there is
 some pure Platonic[1] Ideal Sum floating in space that we can refer to.
 Somewhere, sometime, some mathematician had to *define* sum(), and other
 mathematicians had to agree to use the same definition.

 They could have decided that sum must take at least two arguments,
 because addition requires two arguments and it's meaningless to talk
 about adding a single number without talking about adding it to something
 else. But they didn't.

Ok. But the problem is they DID in SQL: x + Null = Null.

Earlier, you said that an empty box contains 0 widgets.
Fine, empty means 0. But Null doesn't mean empty. Say
your widget supplier just delivers a box and you haven't
opened it yet. Is the box likely to be empty? Probably
not, or they wouldn't have shipped it. In this case,
Null means unknown, not 0. The number of widgets you
have on hand is Null (unknown) because inventory + Null = Null.

SQL will correctly tell you that the amount on hand is unknown,
whereas Python will tell you the amount on hand is inventory,
which is incorrect.

 Similarly, they might have decided that sum must
 take at least one argument, and therefore prohibit sum([]), but they
 didn't: it's more useful for sum of the empty list to give zero than it
 is for it to be an error. As I mentioned earlier, mathematicians are
 nothing if not pragmatists.


Here's a real world example (no ivory tower stuff):

An oil refinery client has just excavated a big pile of
dirt to lay a new pipeline. Due to the volume of the
pipe, there's dirt left over. Ideally, the client
would like to use that dirt as landfill (free), but it
must be tested for HAPS (by summing the concentrations of
organic constituents) to see whether it is considered
hazardous waste, it which cas it must be taken off site
and incinerated (costly).

In MOST cases, a HAPS sum of 0 would be illegal because
0's generally cannot be reported in analytical tests,
you can't report a result less than it's legal reporting
limit. If ALL the consituents were undetected, the sum
should be that of the sum of the reporting limits, thus,
it cannot be 0.

Can't I just use a sum of 0 to tell me when data is missing?
No, because in some cases the reporting limit of undetected
compounds is set to 0.

In which case, a 0 HAPS score means we can confidently
reccomend that the dirt is clean and can be freely reused.

But if the analysis information is missing (hasn'r arrived
yet or still pending validation) we WANT the result to be
UNKNOWN so that we don't reccomend to the client that he take
an illegal course of action.

In this case, SQL does the correct thing and Python would
return a false result.

 --
 Steven

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

Re: How to bring subprocess to the foreground?

2008-09-06 Thread dudeja . rajat
On Sat, Sep 6, 2008 at 6:53 PM, Paul Boddie [EMAIL PROTECTED] wrote:
 On 6 Sep, 17:58, [EMAIL PROTECTED] wrote:

 I though of displayin an information message on the screen through
 tkMessageBox while the subprocess is running, I did it using:

 try:
 testing = subprocess.Popen([batchFilePath], \
shell = True)

 retCode = testing.wait()

 Note that you wait for the process to finish here...

 tkMessageBox._show(Test Harness execution, \
icon = 'info', \
message=Testing %s in progress... % libName)

 ...and that you show a message about the process running *after*
 waiting until it isn't running any more.

 except:
 tkMessageBox._show(Error, \
type='ok', icon='error', \
message=Error executing %s Test
 Harness % libName)
 return None
 else:
 print retCode

 But the message is never displayed. Please suggest if there is
 something wrong with this code

 I think you should first show your message, *then* wait for the
 process to finish.

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


Such a silly mistake I'm committing.
Thanks a ton.

-- 
Regrads,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list


How to run PyOS_InputHook from python code (i.e. yield to event loops)

2008-09-06 Thread Ville M. Vainio
Background: PyOS_InputHook is something that gets run when python is
doing raw_input. TkInter and friends use it to run their event loops,
so that their events are handled while python is doing raw_input.

What I'd like to do is run the same function without having to do
raw_input. I.e. I'd like to run whatever event loop is available,
without incorporating any gui-specific code (PyOS_InputHook seems like
a nifty way to accomplish this).

My actual use case is to keep a tkinter application responsive while
launching a background process (and waiting for it to complete!).

My eventual code would be something like:

launch_process_in_thread('bzr pull')

while not is_done:
  pyos_inputhook()
  time.sleep(0.1)

print Done!
--
http://mail.python.org/mailman/listinfo/python-list


Re: running python as a dameon

2008-09-06 Thread kaer
On 6 sep, 15:44, Michael Palmer [EMAIL PROTECTED] wrote:
 On Sep 5, 9:56 pm, Sean Davis [EMAIL PROTECTED] wrote:



   What I want
   to do is to provide the python NLP program as a service to any other
   PHP/Java/Ruby process request. So the mapping is

   http - apache - PHP/Java/Ruby/... - Python NLP

  Why not use a simple CGI script or wsgi application?  You could make
  the service online and interactive and with the same application and
  code make an XMLRPC web service.  So, things would look more like:

  http - apache - Python (running NLP and serving requests)

  You can use apache to proxy requests to any one of a dozen or so
  python-based webservers.  You could also use mod_wsgi to interface
  with a wsgi application.

  Sean

 xmlrpc is the right idea, as it interfaces easily across languages.

I just daemonize some utility script these week. For that I took one
of the scripts in the ASPN python cookbook : google those 3 words then
search python and you will find out your solution faster than I end up
this mail. It worked like a charm on my linux box.
BTW, I wouldn't complicate with xml stuffs if you don't need it.

Good luck.


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


Re: List of modules available for import inside Python?

2008-09-06 Thread clurker
Michele Simionato wrote:

 On Aug 28, 6:21 am, ssecorp [EMAIL PROTECTED] wrote:
 Is there a way to view all the modules I have available for import
 from within Python?
 Like writing in the interpreter:
 
 Try:
 
 help()
 help modules
 Please wait a moment while I gather a list of all available modules...
 snip

This looks like it could be a useful tool, but when I try it
I get the following:

Please wait a moment while I gather a list of all available modules...

/usr/lib/python2.5/site-packages/reportlab/lib/PyFontify.py:35:
Warning: 'with' will become a reserved keyword in Python 2.6
/usr/lib/python2.5/site-packages/reportlab/lib/PyFontify.py:36:
Warning: 'with' will become a reserved keyword in Python 2.6
Traceback (most recent call last):
  File stdin, line 1, in module
  File /usr/lib/python2.5/site.py, line 346, in __call__
return pydoc.help(*args, **kwds)
  File /usr/lib/python2.5/pydoc.py, line 1645, in __call__
self.interact()
  File /usr/lib/python2.5/pydoc.py, line 1663, in interact
self.help(request)
  File /usr/lib/python2.5/pydoc.py, line 1679, in help
elif request == 'modules': self.listmodules()
  File /usr/lib/python2.5/pydoc.py, line 1797, in listmodules
ModuleScanner().run(callback)
  File /usr/lib/python2.5/pydoc.py, line 1848, in run
for importer, modname, ispkg in pkgutil.walk_packages():
  File /usr/lib/python2.5/pkgutil.py, line 110, in walk_packages
__import__(name)
  File /usr/local/lib/python2.5/site-packages/PIL/__init__.py, line 1342,
in module

  File /usr/local/lib/python2.5/site-packages/PIL/__init__.py, line 927,
in main

UnboundLocalError: local variable 'given_files' referenced before assignment
  

which could be because I am fairly free and unrestrained when
it comes to installing stuff, and I see now I have modules
on both /usr/lib/python2.5 and /usr/local/lib/python2.5

Apparently python knows about them both, but I don't know I
haven't introduced an incompatibility somewhere...and that PIL
package showing up at the tail of the errors was one of my
more recent additions...

Any help will be appreciated,

sc

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

Re: running python as a dameon

2008-09-06 Thread kaer
On 6 sep, 22:16, kaer [EMAIL PROTECTED] wrote:
 On 6 sep, 15:44, Michael Palmer [EMAIL PROTECTED] wrote:



  On Sep 5, 9:56 pm, Sean Davis [EMAIL PROTECTED] wrote:

What I want
to do is to provide the python NLP program as a service to any other
PHP/Java/Ruby process request. So the mapping is

http - apache - PHP/Java/Ruby/... - Python NLP

   Why not use a simple CGI script or wsgi application?  You could make
   the service online and interactive and with the same application and
   code make an XMLRPC web service.  So, things would look more like:

   http - apache - Python (running NLP and serving requests)

   You can use apache to proxy requests to any one of a dozen or so
   python-based webservers.  You could also use mod_wsgi to interface
   with a wsgi application.

   Sean

  xmlrpc is the right idea, as it interfaces easily across languages.

 I just daemonize some utility script these week. For that I took one
 of the scripts in the ASPN python cookbook : google those 3 words then
 search python and you will find out your solution faster than I end up
 this mail. It worked like a charm on my linux box.
 BTW, I wouldn't complicate with xml stuffs if you don't need it.

 Good luck.

you obviously search daemon not search python. Her is the link:
http://www.google.com/search?q=daemonhl=enie=UTF-8btnG=Google%2BSearchqdr=allocct=anydt=isitesearch=code.activestate.com
--
http://mail.python.org/mailman/listinfo/python-list


How to merge a module into a package w/ distutils?

2008-09-06 Thread skip
The bsddb module is on the way out (deprecated in 2.6, gone in 3.0).  That
leaves Python without a cross-platform dbm module to sit underneath anydbm
and shelve.  I figured it might be useful to base something on top of
sqlite3, which is cross-platform.  The result is available in the Python
sandbox:

http://svn.python.org/view/sandbox/trunk/dbm_sqlite/

There are three files, a dbm.sqlite module, a test case and a modified bit
of dbm documentation.

For testing I'd like to install this in such a way that I can simply 

import dbm.sqlite

but not overwrite the core install.  I'd also not like to lose dbm.gdbm, etc
during this testing phase.  Is there some way to do this with distutils?
Ideally, I'd like there to be a dbm package in site-packages but which falls
back to the central installation when, say, dbm.gdbm isn't found.

Thx,

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


String/Number Conversion

2008-09-06 Thread Andreas Hofmann

Hello Folks!

I've got a little problem here, which which really creeps me out at the 
moment.
I've got some strings, which only contain numbers plus eventually one 
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying 
to convert those strings to integers, with this function:



def eliminate_postfix(value):
if type(value) is str:
value.upper()
if value.endswith('K'):
mult = 1000
elif value.endswith('M'):
mult = 100
elif value.endswith('G'):
mult = 10
else:
mult = 1

if mult is 1:
value = string.atoi(value)
else:
value = string.atoi(value[:-1]) * mult
return value



The problem is as follows: Everytime a string with a postfix should get 
converted, mult does not get set properly. It is always 1. Does anyone 
have an idea how to fix this? I just don't see it, maybe because I'm 
pretty new to python or because I'm just blind I would be really greatful.


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


Re: String/Number Conversion

2008-09-06 Thread josh logan
On Sep 6, 5:04 pm, Andreas Hofmann [EMAIL PROTECTED]
wrote:
 Hello Folks!

 I've got a little problem here, which which really creeps me out at the
 moment.
 I've got some strings, which only contain numbers plus eventually one
 character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
 to convert those strings to integers, with this function:

 def eliminate_postfix(value):
          if type(value) is str:
                  value.upper()
                  if value.endswith('K'):
                          mult = 1000
                  elif value.endswith('M'):
                          mult = 100
                  elif value.endswith('G'):
                          mult = 10
                  else:
                          mult = 1

                  if mult is 1:
                          value = string.atoi(value)
                  else:
                          value = string.atoi(value[:-1]) * mult
          return value

 The problem is as follows: Everytime a string with a postfix should get
 converted, mult does not get set properly. It is always 1. Does anyone
 have an idea how to fix this? I just don't see it, maybe because I'm
 pretty new to python or because I'm just blind I would be really greatful.

 Kind regards,
 Andy

Hello,

1. You call value.upper(), but you do not capture the results of that
method. Strings are immutable in Python.
 value = value.upper()

2. You should use == instead of is in the comparison of mult being
1.
 if mult == 1:
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to write verbose scripts

2008-09-06 Thread Lie
On Sep 3, 6:31 pm, Uwe Schmitt [EMAIL PROTECTED] wrote:
 On 2 Sep., 18:55, Steven D'Aprano [EMAIL PROTECTED]



 cybersource.com.au wrote:
  I find myself writing command line tools in Python where I wish to
  include verbose output to stdout.

  I start with a helper function:

  def print_(obj, level=0):
      if _verbosity = level:
          print obj

  And then I end up with functions or methods looking like this:

  def parrot(x)
      print_(precondition, level=2)
      do_something()
      print_(status is good..., level=1)
      print_(parrot is squawking strongly now, level=2)
      do_something_else()
      print_(squawk squawk squawk, level=3)
      do_more()
      print_(postcondition, level=1)
      return something

  That often means that my functions end up with more message printing code
  than actual code. The whole thing seems messy and hard to manage for all
  but the smallest scripts.

  Worst of all, sometimes the messages I wish to print may be expensive to
  compute, and I don't want to waste time computing them if they aren't
  going to be printed because the verbosity is too low. But nor do I wish
  to fill my code with this:

  if _verbosity = 3:
      x = calculate_complicated_thing()
      print_(x, level=3)

  Is there a better way of doing this than the way I am going about it?

  --
  Steven

 You can save some code if you use function decorators for logging
 input and output values of
 functions.
 So write lots of functions containing one statement and your problem
 is solved ;-)

 Greetings, Uwe

That would be perfect if python is a fully functional language (read
that as: purely functional language). Functional language dictates no
side effects, so logging input and output of functions is pretty much
everything needed to do debugging (which is the main reason for having
verbose mode). It would still be feasible, though, if you keep
yourself from using functions with side-effects (or use as few of them
as possible).

Bjorn Lindqvist says:
 One big downside with that approach is that it becomes much harder to
 grep for the log message. Usually when I go through logs, I don't care
 what exactly the message says, just that it is easily googleable (uses
 some kind of identifying text) and that it is unique so I can know
 exactly where it was emitted.

Actually, I'd prefer a log code (perhaps also as an option, to use -e
for showing up log code besides the log message). The log code would
be unique and referenced only once in the whole application (to nail
down who said what to a single point). The code would make a call to
the log printer with the log code (not the error string) and a few
arguments to be interpolated to the error string (taken from a
dictionary indexed by error code).

The downside is loss of inline documentation by the logging codes.
--
http://mail.python.org/mailman/listinfo/python-list


Re: String/Number Conversion

2008-09-06 Thread Wojtek Walczak
On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote:

Hi,

 I've got a little problem here, which which really creeps me out at the 
 moment.
 I've got some strings, which only contain numbers plus eventually one 
 character as si-postfix (k for kilo, m for mega, g for giga). I'm trying 
 to convert those strings to integers, with this function:

  if mult is 1:
   ^^
You're testing for identity, not for equality.
Change it to if mult == 1. Is it alright now?


-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: String/Number Conversion

2008-09-06 Thread John Machin
On Sep 7, 7:04 am, Andreas Hofmann [EMAIL PROTECTED]
wrote:
 Hello Folks!

 I've got a little problem here, which which really creeps me out at the
 moment.
 I've got some strings, which only contain numbers plus eventually one
 character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
 to convert those strings to integers, with this function:

 def eliminate_postfix(value):
  if type(value) is str:

Don't use is unless you are really sure that == won't do the job.
Better idiom:
if isinstance(value, str):

  value.upper()

This causes your mult is always 1 problem. You need:
value = value.upper()
Why? Because strings are immutable. String methods like upper return a
new string, they don't change the existing string.

  if value.endswith('K'):
  mult = 1000
  elif value.endswith('M'):
  mult = 100
  elif value.endswith('G'):
  mult = 10
  else:
  mult = 1

  if mult is 1:

Lose is. In fact, lose the whole if statement. See below.

  value = string.atoi(value)

Don't use deprecated functions from the string module. Use the built-
in float function to convert from text.

  else:
  value = string.atoi(value[:-1]) * mult
  return value

Those last few statements look somewhat tortuous. Try this:
else: # mult would be 1, but we don't need it
return float(value)
return float(value[:-1]) * mult

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


Re: String/Number Conversion

2008-09-06 Thread John Machin
On Sep 7, 7:29 am, Wojtek Walczak [EMAIL PROTECTED] wrote:
 On Sat, 06 Sep 2008 23:04:14 +0200, Andreas Hofmann wrote:
                   if mult is 1:

                            ^^
 You're testing for identity, not for equality.
 Change it to if mult == 1. Is it alright now?


Although he definitely should not be using is here, that can not be
the problem if he is using CPython. As an optimisation, small integers
are interned i.e. for each small integer, there is only one object.

 a = 1
 b = 1
 a is 1
True
 b is 1
False
 id(a)
10897704
 id(1)
10897704
 id(b)
11893004
 id(1)
12633044


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


Re: String/Number Conversion

2008-09-06 Thread bearophileHUGS
Andreas Hofmann, there are several problems in your code:

  if type(value) is str:

Better to use isinstance() and to compare it with basestring instead.


  value.upper()

This does nothing, python strings are immutable, so they don't get
changed in-place, so you have to assign that result to some name,
possibly a different name.
I also suggest you to strip the uppered string, to remove head/tail
spaces.
Your indenting isn't much good, I suggest you to use only four spaces
for each indent (you can also use one tab, but I don't suggest this).


  if value.endswith('K'):
  mult = 1000
  elif value.endswith('M'):
  mult = 100
  elif value.endswith('G'):
  mult = 10
  else:
  mult = 1

This is okay. You can also put those key-values in a dict, that you
can access with the get method with a default 1, but it may be
overkill.


  if mult is 1:
  value = string.atoi(value)
  else:
  value = string.atoi(value[:-1]) * mult
  return value

Instead of using string.atoi, use the int() builtin.

If you follow my suggestions you will have a function that works in
many situations. It will raise exceptions in other situations, but
that's good.

But to not need much of our help in your future code I suggest you to
use the Python shell and test every line you write. I also suggest you
to start right now using tests, for example like this:

def eliminate_postfix(value):

 el_post = eliminate_postfix
 el_post(1)
1
 el_post(100)
100
 el_post()
Traceback (most recent call last):
  ...
ValueError: invalid literal for int() with base 10: ''
 el_post(100g)
1000L
 el_post(100G )
1000L
 el_post(100 G )
1000L
 el_post(100hg)
Traceback (most recent call last):
  ...
ValueError: invalid literal for int() with base 10: '100H'
 el_post( 100  k  )
10
 el_post(  100m)
1
 el_post(u100m)
1

... function code ...


if __name__ == __main__:
import doctest
doctest.testmod()
print Doctests done.\n

That will improve your coding a LOT, reducing your bug count, etc.

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


modules path

2008-09-06 Thread Python

Hi there,

I moved a few modules into the modules folder (on OSX: /opt/local/lib/ 
python2.5/site-packages/).

They don't show up though when I start IDLE...

Is there a way to reload the modules folders in sys.path without  
logging out and back in?


something like source .cshrc in a shell...


thanks in advance,

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


Re: String/Number Conversion

2008-09-06 Thread Andreas Hofmann

Thanks a lot, I got it working now.
Thanks also to the other guys, your numerous hints were really valuable!

Kind regards,
Andy

John Machin schrieb:

On Sep 7, 7:04 am, Andreas Hofmann [EMAIL PROTECTED]
wrote:

Hello Folks!

I've got a little problem here, which which really creeps me out at the
moment.
I've got some strings, which only contain numbers plus eventually one
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying
to convert those strings to integers, with this function:

def eliminate_postfix(value):
 if type(value) is str:


Don't use is unless you are really sure that == won't do the job.
Better idiom:
if isinstance(value, str):


 value.upper()


This causes your mult is always 1 problem. You need:
value = value.upper()
Why? Because strings are immutable. String methods like upper return a
new string, they don't change the existing string.


 if value.endswith('K'):
 mult = 1000
 elif value.endswith('M'):
 mult = 100
 elif value.endswith('G'):
 mult = 10
 else:
 mult = 1

 if mult is 1:


Lose is. In fact, lose the whole if statement. See below.


 value = string.atoi(value)


Don't use deprecated functions from the string module. Use the built-
in float function to convert from text.


 else:
 value = string.atoi(value[:-1]) * mult
 return value


Those last few statements look somewhat tortuous. Try this:
else: # mult would be 1, but we don't need it
return float(value)
return float(value[:-1]) * mult

HTH,
John

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


RE: Xpath for HTML processing

2008-09-06 Thread bruce
Hi Astley

I can probably help here. Can you tell me exactly what you're trying to
accomplish.

the xpath query that you listed can be processed using libxml2dom (and a
fewo other libs)

are you looking to parse a web page, an xml doc, etc...

let me know, and we'll see if we can help



-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of Astley Le Jasper
Sent: Thursday, September 04, 2008 6:17 AM
To: python-list@python.org
Subject: Xpath for HTML processing


Can anyone suggest something inthat can process an XPath like the
following:

/html/body/table[2]/tbody/tr/td[5]/table/tbody/tr[3]/td/table[3]/
tbody/tr[5]/td

Cheers

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

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


Directory creation

2008-09-06 Thread srinivasan srinivas
Can someone tell me is there any module available to create directories??

I tried os, tempfile.
I was facing some issues with os.mkdir(). The mode setting was not proper with 
this method.

I created the directory 'stdin' with '0700' mode using os.mkdir() method.

$ ls -alR stdin/
stdin/:
total 12
drwx--S---   2 munisams munisams 4096 Sep  3 02:00 .

What is that 'S' in the group permission field??

Thanks,
Srini


  Unlimited freedom, unlimited storage. Get it now, on 
http://help.yahoo.com/l/in/yahoo/mail/yahoomail/tools/tools-08.html/
--
http://mail.python.org/mailman/listinfo/python-list


found a bug with smtpd, where can i report this?

2008-09-06 Thread Marcus.CM

Hi,

Where should i report the bug?
smtpd bug.

Marcus.CM

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


Learning Python

2008-09-06 Thread James Pilling
Hi im currently starting to learn python in sixth form at school any tips?


GET FREE 5GB EMAIL - Check out spam free email with many cool features!
Visit http://www.inbox.com/email to find out more!
--
http://mail.python.org/mailman/listinfo/python-list


Re: max(), sum(), next()

2008-09-06 Thread Hendrik van Rooyen
David C. Ullrich dullr...rynet.com wrote:

Think about all the previously elected female or black
presidents of the US. Which one was the tallest?

The current King of France?

- Hendrik



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


Re: atomic section in code

2008-09-06 Thread Hendrik van Rooyen
Fredrik Lundh fredr...ware.com wrote:

sounds like he wants/needs non-cooperative, mandatory locking.

Could one get there using ctypes to disable interrupts?

Cross Platform?

I can think of lots of hassles, starting with permissions
to use the privileged instructions.

- Hendrik



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


Use BeautifulSoup to delete certain tag while keeping its content

2008-09-06 Thread Jackie Wang
Dear all,

I have the following html code:

td valign=top headers=col1
 font size=2
  Center Bank
  br /
  Los Angeles, CA
 /font
/td

td valign=top headers=col1
 font size=2
  Salisbury
Bank and Trust Company
  font face=arial, helvetica size=2 color=#000
   br /
   Lakeville, CT
  /font
 /font
/td

How should I delete the 'font' tags while keeping the content inside?
Ideally I want to get:

td valign=top headers=col1
  Center Bank
  br /
  Los Angeles, CA
/td

td valign=top headers=col1
  Salisbury
Bank and Trust Company
   br /
   Lakeville, CT
/td

Thank you.

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


Multicore-programming?

2008-09-06 Thread cnb
If I buy a multicore computer and I have really intensive program. How
would that be distributed across the cores?

Will algorithms always have to be programmed and told specifically to
run on several cores so if not told it will only utilize one core?

So is the free lunch really over or is this just an overhyped
phenomena?

Is threading with Python hard? Can you start several processes with
Python or just threads?
--
http://mail.python.org/mailman/listinfo/python-list


Cathing several potential errors?

2008-09-06 Thread cnb
if i do
try:
something
except TypeError, IndexError:
pass

only the first error will get caught. I dont want to use Exception and
catch all errors, but just 2. how can i do that?
--
http://mail.python.org/mailman/listinfo/python-list


Re: modules path

2008-09-06 Thread John Machin
On Sep 7, 8:03 am, Python [EMAIL PROTECTED] wrote:
 Hi there,

 I moved a few modules into the modules folder (on OSX: /opt/local/lib/
 python2.5/site-packages/).
 They don't show up though when I start IDLE...

 Is there a way to reload the modules folders in sys.path without  
 logging out and back in?


I know nothing about OS X, but no reload step should be necessary.
Each Python process, whether run from IDLE or some other tool or from
the shell, will form its own idea of sys.path.

So: What modules? What type of file (.py, .pyc, .egg, .zip, .so) are
you talking about? Did their documentation say that moving the files
into site-packages was all the installation that was needed? What does
don't show up when I start IDLE mean?

When you start IDLE and do
import sys, pprint
pprint.pprint(sys.path)
do you see the site-packages directory containing the module files?

What happens when you do
   import amodule # substitute correct module name here
?

Repeat the above two steps for each of
(1) running Python from the shell
(2) running Python from the shell with the -v option

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


Re: String/Number Conversion

2008-09-06 Thread Scott David Daniels

Andreas Hofmann wrote:
I've got some strings, which only contain numbers plus eventually one 
character as si-postfix (k for kilo, m for mega, g for giga). I'm trying 
to convert those strings to integers, with this function:


Why bother to always switch the case if you only use a few values?
Also, the Python style is to do an operation and handle failures, rather
than test first.

Try something like:

_units = dict(K=1000, M=100, G=10,
  k=1000, m=100, g=10)

def eliminate_postfix(value):
try:
return _units[value[-1]] * int(value[: -1])
except (TypeError, KeyError):
return int(value)

If you normally do not have the suffixes, then switch it around:

def eliminate_postfix(value):
try:
return int(value)
except ValueError:
return _units[value[-1]] * int(value[: -1])


If this is really SI units, you likely are doing real measurements,
so I'd consider using float instead of int in the above.


--Scott David Daniels
[EMAIL PROTECTED]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cathing several potential errors?

2008-09-06 Thread Wojtek Walczak
On Sat, 6 Sep 2008 15:13:45 -0700 (PDT), cnb wrote:
 if i do
 try:
 something
 except TypeError, IndexError:
 pass

Parenthesize them:

except (TypeError, IndexError):

-- 
Regards,
Wojtek Walczak,
http://tosh.pl/gminick/
--
http://mail.python.org/mailman/listinfo/python-list


Re: Cathing several potential errors?

2008-09-06 Thread John Machin
On Sep 7, 8:13 am, cnb [EMAIL PROTECTED] wrote:
 if i do
 try:
     something
 except TypeError, IndexError:
     pass

 only the first error will get caught. I dont want to use Exception and
 catch all errors, but just 2. how can i do that?

The syntax for what you can have between except and : is:
[expression  [, target]]
'target' is an optional name to be bound to the actual exception
object that is raised.
If you want to catch multiple kinds of exception, 'expression' needs
to be a tuple.

See
http://docs.python.org/tut/node10.html#SECTION001030
and
http://docs.python.org/ref/try.html

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


Re: Learning Python

2008-09-06 Thread subeen
On Sep 6, 3:17 pm, James Pilling [EMAIL PROTECTED] wrote:
 Hi im currently starting to learn python in sixth form at school any tips?


Just pickup a good book and make sure you code all the examples and
exercises yourself, even if it seems easy.
Have fun with Python!

regards,
Subeen.
http://love-python.blogspot.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multicore-programming?

2008-09-06 Thread Terry Reedy



cnb wrote:

If I buy a multicore computer and I have really intensive program. How
would that be distributed across the cores?

Will algorithms always have to be programmed and told specifically to
run on several cores so if not told it will only utilize one core?


I believe that has always been true.


So is the free lunch really over or is this just an overhyped
phenomena?

Is threading with Python hard? 


Opinions vary, mostly depending on experience.  But Python threads do 
not distribute across processors.


Can you start several processes with

Python or just threads?


import subprocess
and read the manual for that module

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


Re: Cathing several potential errors?

2008-09-06 Thread Gary Josack

cnb wrote:

if i do
try:
something
except TypeError, IndexError:
pass

only the first error will get caught. I dont want to use Exception and
catch all errors, but just 2. how can i do that?
--
http://mail.python.org/mailman/listinfo/python-list
  

what you're doing is assigning the value of TypeError to the name IndexError

try:
 somthing
except (TypeError, IndexError):
 pass

use

except (TypeError, IndexError), e:
 print e

if you want to print the error
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multicore-programming?

2008-09-06 Thread Paul Boddie
On 7 Sep, 00:06, cnb [EMAIL PROTECTED] wrote:
 If I buy a multicore computer and I have really intensive program. How
 would that be distributed across the cores?

It typically depends on how the work done by the program is performed.

 Will algorithms always have to be programmed and told specifically to
 run on several cores so if not told it will only utilize one core?

Some algorithms lend themselves to parallelisation; others do not.
Sometimes tools and runtimes can help by executing some instructions
in parallel.

 So is the free lunch really over or is this just an overhyped
 phenomena?

The free lunch ended a few minutes ago. ;-)

 Is threading with Python hard? Can you start several processes with
 Python or just threads?

You can start both processes and threads with Python, although the
effect of starting many threads - the actual concurrency - will depend
on which implementation of Python you're using and where the bulk of
the work is performed.

If you're spending a lot of CPU time in processing data, and if that
processing is taking place in Python code, then for the most effective
threading you should consider an implementation like Jython or
IronPython which supports free-threading. If most of the work happens
in extension code (where you'd probably have little choice about using
CPython, anyway), then it might be the case that the extension
releases the global interpreter lock in CPython and you might then be
able to benefit from having many threads doing work simultaneously,
although I imagine that the extension would itself need to be thread-
safe, too.

If you're spending a lot of time moving data around, performing
communication, and so on, then multiple threads may still be effective
in CPython, since some of them might be getting a system call to read
or write data, thus freeing the CPU for the others. These kinds of
situations lend themselves to other approaches such as asynchronous
processing of data, however. It doesn't sound like this is like your
program, if by intensive you mean high levels of CPU activity.

As you note, the alternative to threads is processes, and many people
advocate multi-process, shared nothing solutions. Here's a list
which covers multicore and SMP-related solutions as well as high-end
clustering solutions:

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

Although the processing module is part of Python 2.6/3.0 as the
multiprocessing module, you might want to at least look at the pp,
pprocess and papyros solutions. My aim with pprocess was to target
multicore UNIX-like systems with an unintrusive API; pp and papyros,
on the other hand, seek to cover larger scale systems as well, and I
think that the way papyros has been done has some merit, mostly
because if you wanted to combine convenience with distributed
processing, you'd want to choose distributed object technologies as
the foundation (CORBA would have been good for this, too, at least for
multi-language support, but its APIs can also seem quite
intimidating).

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


Re: Multicore-programming?

2008-09-06 Thread John Machin
On Sep 7, 8:06 am, cnb [EMAIL PROTECTED] wrote:
 If I buy a multicore computer and I have really intensive program. How
 would that be distributed across the cores?

AFAIK, a single process wouldn't be distributed automatically.

 Will algorithms always have to be programmed and told specifically to
 run on several cores so if not told it will only utilize one core?

AFAIK, yes. See (for example) http://www.parallelpython.com/

 So is the free lunch really over

There is no such thing as a free lunch. Something which has never
existed can't be over.

 or is this just an overhyped
 phenomena?

These days, every IT phenomenon is over-hyped.

If you have a CPU-intensive Python program, you may want to consider:
(1) checking that there are not faster/better algorithms for doing
what you want in Python, either built-in or in a 3rd-party library
(2) using psyco
(3) checking your code for sub-optimal constructs

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


RE: Use BeautifulSoup to delete certain tag while keeping its content

2008-09-06 Thread bruce
hi jackie,

if you don't mind... can i ask what you're looking to accomplish? are you
looking to simply get the text/string data, or something else???



-Original Message-
From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED] Behalf
Of Jackie Wang
Sent: Saturday, September 06, 2008 8:12 AM
To: python-list@python.org
Subject: Use BeautifulSoup to delete certain tag while keeping its
content


Dear all,

I have the following html code:

td valign=top headers=col1
 font size=2
  Center Bank
  br /
  Los Angeles, CA
 /font
/td

td valign=top headers=col1
 font size=2
  Salisbury
Bank and Trust Company
  font face=arial, helvetica size=2 color=#000
   br /
   Lakeville, CT
  /font
 /font
/td

How should I delete the 'font' tags while keeping the content inside?
Ideally I want to get:

td valign=top headers=col1
  Center Bank
  br /
  Los Angeles, CA
/td

td valign=top headers=col1
  Salisbury
Bank and Trust Company
   br /
   Lakeville, CT
/td

Thank you.

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

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


Re: Numeric literal syntax

2008-09-06 Thread Alan G Isaac

[EMAIL PROTECTED] writes:


For Python 2.7/3.1 I'd now like to write a PEP regarding the
underscores into the number literals, like: 0b_0101_, 268_435_456
etc.


+1 on such a capability.

-1 on underscore as the separator.



On 9/1/2008 9:13 PM Ben Finney apparently wrote:

When you proposed this last year, the counter-proposal was made
URL:http://groups.google.com/group/comp.lang.python/msg/18123d100bba63b8?dmode=source
to instead use white space for the separator, exactly as one can now
do with string literals.


Yuck.
Repeating a mistake means two mistakes.

But I would hate less the use of nobreak spaces,
since any decent editor can reveal them.

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


Re: modules path

2008-09-06 Thread Python


On 7 sep 2008, at 00:25, John Machin wrote:


On Sep 7, 8:03 am, Python [EMAIL PROTECTED] wrote:

Hi there,

I moved a few modules into the modules folder (on OSX: /opt/local/ 
lib/

python2.5/site-packages/).
They don't show up though when I start IDLE...

Is there a way to reload the modules folders in sys.path without
logging out and back in?



I know nothing about OS X, but no reload step should be necessary.
Each Python process, whether run from IDLE or some other tool or from
the shell, will form its own idea of sys.path.

So: What modules? What type of file (.py, .pyc, .egg, .zip, .so) are
you talking about? Did their documentation say that moving the files
into site-packages was all the installation that was needed? What does
don't show up when I start IDLE mean?

When you start IDLE and do
   import sys, pprint
   pprint.pprint(sys.path)
do you see the site-packages directory containing the module files?

What happens when you do
  import amodule # substitute correct module name here
?

Repeat the above two steps for each of
(1) running Python from the shell
(2) running Python from the shell with the -v option

HTH,
John
--

I installed pyGTK from MacPorts
for some reason Macports installs these modules in the /opt/  folder
even in an old python folder: python 2.4, while my current version is  
2.5

both are not in sys.path...

i appended the path and IDLE found them
I should have thought a bit more before asking...
saturday night... why am I here anyway ;)

now one question came up, how do I make those path permanent?
i mean, sys.path.append(path) adds it for the current session,
yet when i logout of IDLE and start it again it's gone...
how do i keep it in there?

thanks for the answer John...

Arno

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


Re: Learning Python

2008-09-06 Thread Colin J. Williams

James Pilling wrote:

Hi im currently starting to learn python in sixth form at school any tips?


GET FREE 5GB EMAIL - Check out spam free email with many cool features!
Visit http://www.inbox.com/email to find out more!
There are suggestions here: 
http://wiki.python.org/moin/PythonBooks


Good luck,

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


Re: Seeking ideas for a cron implementation

2008-09-06 Thread Karthik Gurusamy
On Aug 22, 1:51 pm, Sean DiZazzo [EMAIL PROTECTED] wrote:
 On Aug 22, 1:30 pm, Karthik Gurusamy [EMAIL PROTECTED] wrote:



  Hi,

  I'm working on acronlike functionality for my application.
  The outer loops runs continuously waking every x seconds (say x=180,
  300, ..).
  It needs to know what events incronhas expired and for each event do
  the work needed.

  It's basically like unixcronor like a calendar application with some
  restrictions. The outer loop may come back a lot later and many events
  might have missed their schedule -- but this is okay.. We don't have
  to worry about missed events (if there were n misses, we just need to
  execute call back once).

  Let's take some examples [Let e denotes an event]
  e1: hour=1  min=30                             # Run every day once at
  1:30 AM
  e2: wday=0, hour=1  min=0                   # run every Monday at 1 AM
  e3: month=10, day=10, hour=10 min=0  # run on October 10th, 10 AM
  every year

  class Cron_Event (object):
      def __init__ (year=None, month=None, day=None, hour=None ..etc)
        #  do init

  classCron(object):
      def __init__ ():
          # do init
      def event_add (e):
          # add an event
      def execute()
          # see if any events has expired .. call it's callback
          # I'm looking for ideas on how to manage the events here

  From outer loop
 cron=Cron()
  # create various events like
  e1 = Cron_Event(hour=1)
 cron.event_add(e1)
  e2 = Cron_Event(wday=0, hour=1)
 cron.event_add(e2)

  while True:
      sleep x seconds (or wait until woken up)
     cron.execute()
      # do other work.. x may change here

  If I can restrict to hour and minute, it seems manageable as the
  interval between two occurrences is a constant. But allowing days like
  every Monday or 1st of every month makes things complicated. Moreover
  I would like each constraint in e to take on multiple possibilities
  (like every day at 1AM,  2 AM and 4 AM do this).

  I'm looking for solutions that can leverage datetime.datetime
  routines.
  My current ideas include for each e, track the next time it will fire
  (in seconds since epoch as given by time.time()). Once current time
  has passed that time, we execute the event. e.g. datetime.datetime.now()

  datetime.datetime(2008, 8, 22, 13, 19, 54, 5567) time.time()

  1219436401.741966    --- compute event's next firing in a format like
  this

  The problem seems to be how to compute that future point in time (in
  seconds since epoch)  for a generic Cron_Event.

  Say how do I know the exact time in future  that will satisfy a
  constraint like:
   month=11, wday=1, hour=3, min=30    # At 3:30 AM on a Tuesday in
  November

  Thanks for your thoughts.

  Karthik

 I only scanned your message, but maybe datetime.timedelta() will
 help..

  import datetime
  now = datetime.datetime.now()
  print now

 2008-08-22 13:48:49.335225 day = datetime.timedelta(1)
  print day
 1 day, 0:00:00
  print now + day

 2008-08-23 13:48:49.335225

Thanks, I found using a more efficient algorithm tricky and seemed
error prone.
[I do welcome ideas still if anyone has a cool solution]

I used your idea and took the easy way out by using a brute-force
search.

Here is an outline if anyone faces similar problem:
hours, minutes are lists: say for every day at 1:30 pm and 2:45 pm,
hours=[13, 14] and minutes=[30, 45,].
I restricted myself to minutes and hours (and every day) to simplify
the problem.

def set_expiry_time_check_in_a_day (self, now, target,
hours, mins, flags=set()):

   A small utility routine to simulate 'goto'
   Looks like now could be computed inside this function --
the small
   drift due to time taken in this function should be
negligible

# let's see if in today we can find an expiry
# we do brute force search starting with the smallest hour
for hour in hours:
for min in mins:
target = target.replace(hour=hour, minute=min,
second=0,
 microsecond=0)
if 'is_debug_1' in flags:
print Trying target time: %s... % target
if target  now:
if 'is_debug_1' in flags:
print Found target time: %s % (target, )
return target   # simulates a break from two loops
return None

   def set_expiry_time (self, event, flags=set()):

For a given event, compute and remember when it will fire
next

now = datetime.datetime.now()

target = now # start checking from now..

# assumption, hours and mins are atleast one int element array
# and they are in sorted order
hours = event.spec['hours']
mins = event.spec['minutes']

tries = 0
while True:  # runs of each day.. tomorrow ...
tries += 1
if tries  50: # 

Re: Use BeautifulSoup to delete certain tag while keeping its content

2008-09-06 Thread Paul Boddie
On 6 Sep, 17:11, Jackie Wang [EMAIL PROTECTED] wrote:

 I have the following html code:

 td valign=top headers=col1
  font size=2
   Center Bank
   br /
   Los Angeles, CA
  /font
 /td

 td valign=top headers=col1
  font size=2
   Salisbury
 Bank and Trust Company
   font face=arial, helvetica size=2 color=#000
br /
Lakeville, CT
   /font
  /font
 /td

 How should I delete the 'font' tags while keeping the content inside?

This sounds like an editing exercise, really. If you're comfortable
learning a new tool, I can recommend XSLT for this kind of job. Here's
the stylesheet:

?xml version=1.0?
xsl:stylesheet version=1.0 xmlns:xsl=http://www.w3.org/1999/XSL/
Transform

  xsl:template match=font
xsl:apply-templates/
  /xsl:template

  xsl:template match=@*|node()
xsl:copy
  xsl:apply-templates select=@*|node()/
/xsl:copy
  /xsl:template

/xsl:stylesheet

This just describes two things: firstly, that you want to recognise
font elements and to include their contents, not each element's start
and end tags; secondly, that all other parts of the document should be
copied.

You can apply stylesheets using a number of XSL processors. The
xsltproc program is usually available where libxslt is installed, and
although I'm sure others will be along to tell you  all about their
favourite libraries and tools, here's how I use mine within Python:

# XSLTools: http://www.python.org/pypi/XSLTools
# libxml2dom: http://www.python.org/pypi/libxml2dom
import XSLTools.XSLOutput
import libxml2dom
# If s is the document text...
d = libxml2dom.parseString(s)
# Save the above stylesheet to a file somewhere, then...
proc = XSLTools.XSLOutput.Processor([/tmp/no-font.xsl])
# Get the result document
d2 = proc.get_result(d)

Anyway, this is just one option of many to deal with this kind of
problem.

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


Setter Propertys' mro?

2008-09-06 Thread cipher
Whats the mro (method resolution order) of a setter property (__set__
on a descriptor).
i seem to be experiencing some weird issue with them.
for example

 class test:
...  def _test(self):
...   return 4
...  def _stest(self):pass # dont change value
...  def _dtest(self,value):pass
...  p=property(_test,_stest,_dtest)
 t=test()
 t.p
4
 t.p=5
 t.p
5

Why is that being 'overridden' ( by that i mean that it is storing
that value in t's __dict__)

 t.__dict__
{'t': 5}

why DIDNT the setter get hit?
however, if i specify the metaclass in the class definition it works
just fine...

class test:
 __metaclass__=type
 def _test(self):
  return 4
 def _stest(self,value):pass # dont change value
 def _dtest(self):pass
 p=property(_test,_stest,_dtest)
 t=test()
 t.p
4
 t.p=5
 t.p
4

why do i have to set the __metaclass__ ? this seems like a bug?
i know that i probably shouldn't worry about this because if a
programmer does want to set my value and it causes an error, thats his
problem but this bothers me. whats the point of the __set__ method
then?


Thanks in advanced.

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


Re: found a bug with smtpd, where can i report this?

2008-09-06 Thread cipher
On Sep 5, 4:01 am, Marcus.CM [EMAIL PROTECTED] wrote:
 Hi,

 Where should i report the bug?
 smtpd bug.

 Marcus.CM

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


Re: Learning Python

2008-09-06 Thread Peter Anderson

James,

I have several Python books and am currently working my way through John 
Zelle's PYTHON PROGRAMMING: An Introduction to Computer Science 
(Publisher: Franklin, Beedle  Associates, ISBN-10: 1887902996, ISBN-13: 
978-1887902991). I think this is a very good introduction to both Python 
AND programming I would highly recommend it.


If you finish the Zelle book then you can go onto Problem Solving With 
Algorithms And Data Structures Using Python by Bradley N. Miller and 
David L. Ranum (Publisher: Franklin Beedle  Associates, ISBN-10: 
1590280539, ISBN-13: 978-1590280539).


These are equivalent to Python 101 and 201.

Regards,
Peter
--
*Peter Anderson*
There is nothing more difficult to take in hand, more perilous to 
conduct, or more uncertain in its success, than to take the lead in the 
introduction of a new order of things—Niccolo Machiavelli, /The Prince/, 
ch. 6

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


Re: Setter Propertys' mro?

2008-09-06 Thread Tommy Grav

On Sep 6, 2008, at 9:15 PM, cipher wrote:


Whats the mro (method resolution order) of a setter property (__set__
on a descriptor).
i seem to be experiencing some weird issue with them.
for example


class test:


You have to use class test(object). Only new style classes accepts  
properties.


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


Re: atomic section in code

2008-09-06 Thread Tim Roberts
Hendrik van Rooyen [EMAIL PROTECTED] wrote:

Fredrik Lundh fredr...ware.com wrote:

sounds like he wants/needs non-cooperative, mandatory locking.

More accurately, he THINKS he wants/needs mandatory locking.  We need to
find out what he's really trying to accomplish before we can suggest
something that is actually achievable.

Could one get there using ctypes to disable interrupts?

No.  That can't be done in user mode in any operating system where Python
runs.  Even in kernel mode, it's not reliable, because disabling interrupts
only affects one core.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Determining Processor Vender

2008-09-06 Thread Tim Roberts
aha [EMAIL PROTECTED] wrote:

Dose anyone know of a cross-platform method for determining the vendor
of a processor?  Under linux I can check /proc/cpuinfo.  What I'd like
to be able to do is determine if a processor is AMD or Intel, so that
I can use the appropriate numerical libraries for my application.

If you have a numerical library that uses processor-specific instructions,
then the library must be in C with assembler.  If so, just add another
function that does a cpuid instruction and return the results.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Multicore-programming?

2008-09-06 Thread Tim Roberts
cnb [EMAIL PROTECTED] wrote:

So is the free lunch really over or is this just an overhyped
phenomena?

Remember that your computer is not running one single program.  An idle
computer on either Windows or Linux typically has dozens of processes
running.  Even if all of those programs are single-threaded, you'll still
be able to keep all of the cores busy.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza  Boekelheide, Inc.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Numeric literal syntax

2008-09-06 Thread Steven D'Aprano
On Sat, 06 Sep 2008 23:30:03 +, Alan G Isaac wrote:

 [EMAIL PROTECTED] writes:
 
 For Python 2.7/3.1 I'd now like to write a PEP regarding the
 underscores into the number literals, like: 0b_0101_, 268_435_456
 etc.
 
 +1 on such a capability.
 
 -1 on underscore as the separator.
 
 
 On 9/1/2008 9:13 PM Ben Finney apparently wrote:
 When you proposed this last year, the counter-proposal was made
 URL:http://groups.google.com/group/comp.lang.python/
msg/18123d100bba63b8?dmode=source
 to instead use white space for the separator, exactly as one can now do
 with string literals.
 
 Yuck.
 Repeating a mistake means two mistakes.

A lot of us don't think that white space between string literals was a 
mistake. A lot of us consider it a desirable feature.


 But I would hate less the use of nobreak spaces, since any decent editor
 can reveal them.

How do you type a nobreak space? 

It's also probably a bad idea for Python the language to depend on 
developers using a decent editor, since many people disagree on what a 
decent editor is, and many other people don't have access to whatever you 
consider a decent editor.



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


Re: max(), sum(), next()

2008-09-06 Thread Steven D'Aprano
On Sat, 06 Sep 2008 11:22:07 -0700, Mensanator wrote:

[...]

 They could have decided that sum must take at least two arguments,
 because addition requires two arguments and it's meaningless to talk
 about adding a single number without talking about adding it to
 something else. But they didn't.
 
 Ok. But the problem is they DID in SQL: x + Null = Null.

Sheesh. That's not a problem, because Python is not trying to be a 
dialect of SQL.

If you want a NULL object, then there are recipes on the web that will 
give you one. Then all you need to do is call sum(alist or [NULL]) and it 
will give you the behaviour you want.


[...]
 Here's a real world example (no ivory tower stuff):
 
 An oil refinery client has just excavated a big pile of dirt to lay a
 new pipeline. 
[snip details]
 Can't I just use a sum of 0 to tell me when data is missing? No, because
 in some cases the reporting limit of undetected compounds is set to 0.

You can't use a sum of 0 to indicate when data is missing, full stop. The 
data may require 15 tests when only 3 have actually been done:

sum([1.2e-7, 9.34e-6, 2.06e-8])

Missing data and a non-zero sum. How should sum() deal with that?

The answer is that sum() can't deal with that. You can't expect sum() to 
read your mind, know that there should be 15 items instead of 3, and 
raise an error. So why do you expect sum() to read your mind and 
magically know that zero items is an error, especially when for many 
applications it is NOT an error?

The behaviour you want for this specific application is unwanted, 
unnecessary and even undesirable for many other applications. The 
solution is for *you* to write application-specific code to do what your 
application needs, instead of relying on a general purpose function 
magically knowing what you want.



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


Re: Setter Propertys' mro?

2008-09-06 Thread Steven D'Aprano
On Sat, 06 Sep 2008 18:15:33 -0700, cipher wrote:

 Whats the mro (method resolution order) of a setter property (__set__ on
 a descriptor).
 i seem to be experiencing some weird issue with them. for example
 
 class test:


Unless you're using Python 3, there's your problem right there. In Python 
2.x, properties only work correctly for new style classes, not classic 
classes. Change the above line to:

class Test(object):  # by convention, classes start with Uppercase.

and all should work (or at least you'll discover new and exciting 
different problems with your code).


 however, if i specify the metaclass in the class definition it works
 just fine...
 
 class test:
  __metaclass__=type

which is more or less the same as inheriting from object, except uglier.



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


Mail delivery problems

2008-09-06 Thread Peter Anderson
In the last two days I have posted relies twice to the Python List. Each 
time my e-mail has listed successfully but I have received a reply like 
the following:


   This is an automatically generated Delivery Status Notification.

   Delivery to the following recipients failed.

   [EMAIL PROTECTED]

   

   Reporting-MTA: dns;delhi-prod01.india.kring.com
   Received-From-MTA: dns;kring-vt01
   Arrival-Date: Sun, 7 Sep 2008 07:16:17 +0530

   Final-Recipient: rfc822;[EMAIL PROTECTED]
   Action: failed
   Status: 5.2.2
   X-Display-Name: Ajay Deshpande


   Subject: Re: Learning Python
   From: Peter Anderson [EMAIL PROTECTED]
   Date: Sun, 07 Sep 2008 11:41:03 +1000
   To: python-list@python.org

   The text of my message...

Is this a problem?

Peter
--
*Peter Anderson*
There is nothing more difficult to take in hand, more perilous to 
conduct, or more uncertain in its success, than to take the lead in the 
introduction of a new order of things—Niccolo Machiavelli, /The Prince/, 
ch. 6

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


Re: Multicore-programming?

2008-09-06 Thread sturlamolden
On 7 Sep, 00:06, cnb [EMAIL PROTECTED] wrote:

 If I buy a multicore computer and I have really intensive program. How
 would that be distributed across the cores?

Distribution of processes and threads across processors (cores or
CPUs) is managed by the operating system.


 Will algorithms always have to be programmed and told specifically to
 run on several cores so if not told it will only utilize one core?

One particular program has to be programmed for concurrency to utilize
multiple cores. But you typically have more than one program running.


 So is the free lunch really over or is this just an overhyped
 phenomena?

Two slow cores are better than one fast for most purposes. For one
thing, it saves power. It's good for the battries and environment
alike.


 Is threading with Python hard?

It's not harder than with other systems. You just subclass
threading.Thread, which has almost the same interface as Java threads.
Threading with Python is perhaps a bit easier than with other common
platforms, due to the Queue.Queue object and the lack of volatile
objects.


 Can you start several processes with Python or just threads?

You can do both. However, remember that Python threads only do what
threads were designed to do back in the 1990s. That is asynchrony for
I/O and UIs, not concurrency on multiple processors for CPU bound
computing. This is due to the Global Interpreter Lock. The GIL is
better than fine-grained locks for single-threading and concurrency
with multiple processes, but prevent python threads form being used
for concurrency (just as well).

You can do concurrency with Java threads or Win32 threads, but this is
merely a side-effect. You will often see claims form novice
programmers that threads are the only route to concurrency on multi-
core CPUs. In addition to the existence of processes, direct use of
threads from Java, .NET, POSIX, or Win32 APIs is not even the
preferred way of programming for concurrency. Tinkering with low-level
threading APIs for concurrency is error-prone and inefficient. You
will spend a lot of time cleansing your code of dead-locks, live-
locks, volatile objects not being declared volatile, and race
conditions. In addition to that, chances are your code will not
perform or scale very well due to memory contention, cache line
misses, inefficient use of registers due to volatile objects, etc. The
list is endless. That is why Java 6 and .NET 3.5 provide other
abstractions for multi-core concurrency, such as ForkJoin and
Parallel.For. This is also the rationale for using an OpenMP enabled
compiler for C or Fortran, auto-vectorizing C or Fortran compilers,
and novel languages like cilk and erlang.

Traditionally, concurrency om parallel computers have been solved
using tools like BSPlib, MPI, vectorizing Fortran compilers, and even
ebarassingly parallel (running multiple instances of the same
program on different data). OpenMP is a recent addition to the
concurrency toolset for SMP type parallel computers (to which multi-
core x86 processors belong).

If you really need concurrency with Python, look into MPI (PyMPI,
PyPAR, mpi4py), Python/BSP, subprocess module, os.fork (excluding
Windows), pyprocessing package, or Parallel Python. BSP is probably
the least error-prone paradigm for multi-core concurrency, albeit not
the most efficient.

If you decide to move an identified bottleneck from Python to C or
Fortran, you also have the option of using OpenMP or cilk to ease the
work of programming for concurrency. This is my preferred way of
dealing with bad bottlenecks in numerical computing. Remember that you
need not learn the overly complex Python C API. Cython, ctypes, f2py,
or scipy.weave will do just as well. This approach will require you to
manually release the GIL, which can be done in several ways:

- In C extensions between Py_BEGIN_ALLOW_THREADS and
Py_END_ALLOW_THREADS macros.

- When calling DLL methods using ctypes.cdll or ctypes.windll (not
ctypes.pydll).

- In a with nogil: block in a Cython/Pyrex extension.

- With f2py or SWIG, although I have not looked at the details. (I
don't use them.)


Other things to consider:

- Programs that run fast enough run fast enough, even if they only
utilize one core. To qoute C.A.R. Hoare and Donald Knuth, premature
optimization is the root of all evil in computer programming.

- Psyco, a Python JIT compiler, will often speed up algorithmic code.
Using psyco require to change to your code. Try it and see if your
programs runs fast enough afterwards. YouTube is rumoured to use psyco
to speed ut their Python backend.

- Always use NumPy or SciPy if you do numerical work. They make
numerical code easier to program. The numerical code also runs a lot
faster than a pure python equivalent.

- Sometimes Python is faster than your hand-written C. This is
particularly the case for Python code that make heavy use of built-in
primitives and objects from the standard library. You will spend a lot
of time tuning a linked list or 

Re: Multicore-programming?

2008-09-06 Thread sturlamolden
On 7 Sep, 06:24, sturlamolden [EMAIL PROTECTED] wrote:

 - Psyco, a Python JIT compiler, will often speed up algorithmic code.
 Using psyco require to change to your code.

Typo. It should say Using psyco does not require you to change your
code.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Setter Propertys' mro?

2008-09-06 Thread cipher
On Sep 6, 9:10 pm, Steven D'Aprano [EMAIL PROTECTED]
cybersource.com.au wrote:
 On Sat, 06 Sep 2008 18:15:33 -0700, cipher wrote:
  Whats the mro (method resolution order) of a setter property (__set__ on
  a descriptor).
  i seem to be experiencing some weird issue with them. for example

  class test:

 Unless you're using Python 3, there's your problem right there. In Python
 2.x, properties only work correctly for new style classes, not classic
 classes. Change the above line to:

 class Test(object):  # by convention, classes start with Uppercase.

 and all should work (or at least you'll discover new and exciting
 different problems with your code).

  however, if i specify the metaclass in the class definition it works
  just fine...

  class test:
   __metaclass__=type

 which is more or less the same as inheriting from object, except uglier.

 --
 Steven

Thanks to both of you!! that solved it.
i wonder why the getters would work fine though??
neways, wtf do i care :)


again, thank you both.

__
Cipher

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


This group contains information about IT Requirements in USA as well as Hotlist of Candidates from the participating members

2008-09-06 Thread reddy
This group contains information about IT Requirements in USA as well
as Hotlist of Candidates from the participating members



CLICK  REGISTER U GET MORE DEDAILS


   *
  *  http://homologie.blogspot.com/*
*   http://germanfriendfinder.com/go/g107-ppc *
  *  http://amigos.com/go/g106-pmem  *
 
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >