Re: is this data structure build-in or I'll have to write my own class?

2008-02-27 Thread Jorge Vargas
On Wed, Feb 20, 2008 at 12:07 PM, thebjorn
<[EMAIL PROTECTED]> wrote:
> On Feb 20, 3:32 pm, "Jorge Vargas" <[EMAIL PROTECTED]> wrote:
>
> > On Feb 20, 2008 8:15 AM, Larry Bates <[EMAIL PROTECTED]> wrote:
>  >
>  > > Jorge Vargas wrote:
>  > > > I need a data structure that will let me do:
>  >
>  > > > - attribute access (or index)
>  > > > - maintain the order (for iter and print)
>  > > > - be mutable.
>  >
>  [...]
>
> >
>  > > Sounds like a good time to learn ElementTree (included in Python 2.5 but
>  > > available for earlier versions).
>  >
>
> > I am using ET, to fetch the data from the XML, after that I want a
>  > plain python object. for the rest of the program.
>
>  Ok, you just lost me... Why do you thin ET is not appropriate (*)?  It
>  fits all your requirements, is optimized for representing hierarchical
>  data (especially xml), it is fast, it is well tested, it has a
>  community of users, it is included in the standard library, etc., etc.
>
sorry for the late reply, I'm running queries on a webservice, nothing
fancy just http post/get and they give me an XML, the XML has a ton of
information, say 200 nodes, from that I only need 1 node that has 6
more inside, so keeping the whole 200 nodes in memory is not
apropiate, I could make a new ET object with only that part but, I
this data should be fetched every X hours, so I'll prefer it to be my
object so I can code the cache part.

>  ...maybe I didn't grok what you meant by "plain python object"?
>
>  -- bjorn
>
>  (*) I just had a flashback to the movie ET -- the scene when he's in
>  the closet ;-)
>
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is this data structure build-in or I'll have to write my own class?

2008-02-27 Thread Jorge Vargas
On Wed, Feb 20, 2008 at 7:34 PM, Carl Banks <[EMAIL PROTECTED]> wrote:
> On Feb 20, 8:12 am, "Jorge Vargas" <[EMAIL PROTECTED]> wrote:
>  > I need a data structure that will let me do:
>  >
>  > - attribute access (or index)
>  > - maintain the order (for iter and print)
>  > - be mutable.
>  >
>  > in case there isn't one. I was thinking having a base class like 
> Bunchhttp://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308and on
>
> > top of that keeping a list of the keys and pop/push to the list when
>  > adding/deleting items. I don't like this idea because I'll have to
>  > keep each key twice. (in the list and in __dict__, is this the only
>  > way of doing it?
>
>  OrderedDict is usually the term used here for this (not to be confused
>  with SortedDict, which is a mapping type with identically sorted
>  keys).  It's asked for pretty often but no one's stepped up to
>  implement one for the standard library.
Yes, what I really nice is an OrderedDict, interesting ... maybe it
could be a nice contribution for
http://docs.python.org/lib/module-collections.html interesting I just
read the docs and it's there. I look around and those seems to be
implement on the C layer.
>
>
>  Carl Banks
>
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: is this data structure build-in or I'll have to write my own class?

2008-02-27 Thread Jorge Vargas
On Thu, Feb 21, 2008 at 2:52 AM, Robert Bossy <[EMAIL PROTECTED]> wrote:
> mkPyVS wrote:
>  > This isn't so optimal but I think accomplishes what you desire to some
>  > extent... I *think* there is some hidden gem in inheriting from dict
>  > or an mapping type that is cleaner than what I've shown below though.
>  >
>  > class dum_struct:
>  >def __init__(self,keyList,valList):
>  >   self.__orderedKeys = keyList
>  >   self.__orderedValList = valList
>  >def __getattr__(self,name):
>  >   return self.__orderedValList[self.__orderedKeys.index(name)]
>  >
>  >
>  > keys = ['foo','baz']
>  > vals = ['bar','bal']
>  >
>  > m = dum_struct(keys,vals)
>  >
>  > print m.foo
>  >
>
>  Let's add:
> __getitem__(self, key):
> return self.__orderedValList[key]
>
this seems like a good start, maybe replacing the internal structures
with a list and a dict will get better  performance, I'll work in it a
little, if I get something productive I'll probably post a recipe
>
>  in order to have: m.foo == m[0]
>
>  RB
>
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How, python with Tk extensions enabled to import Tkinter

2008-02-27 Thread Diez B. Roggisch
Murat Gunduz wrote:

> 
> 
> Dear list member,
> 
> I am using a Linux machine (Fedora Core 7, 64 bit):
> Linux 2.6.21-1.3228.fc7 #1 SMP Tue Jun 12 14:56:37 EDT 2007 x86_64

So you are under linux...
> 4- type "./configure --enable-framework

And now you try to create an OSX-framework-build? Why so, what made you
think that's working?

The missing NS*-class-reference is a sign of the build-process being
confused, because NS* is the class-namespace of OSX for objective-C.

Try the configure without the --enable-framework.

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


Re: Documentation - which format

2008-02-27 Thread grflanagan
On Feb 26, 11:47 pm, Jumping Arne <[EMAIL PROTECTED]> wrote:
> I'm considering using plain text file for documenting certain things (nothing
> to do with Python) and I'm looking at different "formatting systems" ...
> preferable with a python implementation to render the text at least as HTML -
> preferable also other formats like LaTeX.
>
> So far I've found
>
> +   Markdown
> + reST (the web site at sourceforge doesn't seem to have been updated
>   since 2006)
>
> Are there any other I should look at?

Definitely ReST.  See http://rst2a.com/

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


time.time() strangeness

2008-02-27 Thread Nitro
Ok, my final solution is to add the D3DCREATE_FPU_PRESERVE flag. It didn't  
harm performance in a noticeable way at all. I was under the impression  
SSE would be affected by this, too. Additionally I was under the  
impression that float precision would suffice for time.time(). Obviously I  
was blatantly wrong :-)
Thanks to Gabriel, Ross and Roel for commenting on this and sharing their  
insights!

They should really make the fpu preserve flag the default. It just causes  
very sneaky bugs.

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


Re: is there enough information?

2008-02-27 Thread Gabriel Genellina
En Wed, 27 Feb 2008 06:25:25 -0200, Dennis Lee Bieber  
<[EMAIL PROTECTED]> escribió:

> On Wed, 27 Feb 2008 05:46:56 -0200, "Gabriel Genellina"
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>
>> It's like a McDonalds: three guys (the producers) are taking orders from
>> the customers, and place those orders in a queue; in the kitchen, two  
>> guys
>> (the consumers) check the queue and prepare the requested sandwichs (it
>> doesn't matter which one gets which order). The finished sandwichs are  
>> put
>> onto another queue (the kitchen guys are acting as producers now) and
>> another guy -he may or may not be one of the first three; he's acting  
>> as a
>> consumer- takes the sandwich, puts it on a tray with other stuff and
>> delivers it to the customer.
>
>   Has McDonald's changed that much... Last time I was in one, the
> kitchen staff just took trays of finished patties, stuck them on a bun
> with the stock ingredients, wrapped them, and put them on a
> first-in/first-out rack from which the register staff pulled them as
> needed...

I think they work that way at peak hours - but e.g. at 3AM they just  
prepare what is requested.

> (I've not bought at a McD since I got sick off of one back in
> 1970 or so)

That happens from time to time, unfortunately, and not only with McD.
http://www.mcspotlight.org/media/press/mcds/reuters121001.html

>   Now, Burger King... That's different -- they were always assembled
> based upon the most recent register order...

I like BK hamburguers... but I shouldn't eat them, as the doctor told me :(

>   Speak not of Wendy's -- they moved into town in my college days...
> The "hot and juicy" was commonly taken to mean: patty dipped in pan
> drippings, then nuked in microwave... And any CompSci person could
> figure out that the "256 different ways" meant one had access to a tray
> of 8 condiments, and had any combination of on or off for each... 8
> condiments, let's see: ketchup, mayo, mustard, pickle, onion, lettuce,
> tomato, cheese?

I went once to Wendy's, and couldn't finish my sandwich. It was  
ho-rri-ble. It was not a surprise when they closed all their restaurants  
in Argentina and leave the country, after being here for less than 4 years.

-- 
Gabriel Genellina

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


Re: How, python with Tk extensions enabled to import Tkinter

2008-02-27 Thread Martin Franklin
Murat Gunduz wrote:
> 
> Dear list member,
> 
> I am using a Linux machine (Fedora Core 7, 64 bit):
> Linux 2.6.21-1.3228.fc7 #1 SMP Tue Jun 12 14:56:37 EDT 2007 x86_64
> 

Fedora ships ready built Tk/Tcl and Tkinter RPM's so use the Package
Updater (search for tkinter) or command line 'yum install tkinter'

(I may have spelt the tkinter package name wrong so do search for it
first)

Fedora (like RedHat) has loads of Python related packages so worth
checking in the package manager - Search for python- you'll be
pleasantly surprised :)

Cheers,
Martin.



-- 
signature file not found, must be something I ate
-- 
http://mail.python.org/mailman/listinfo/python-list


Logging to HTTP or File

2008-02-27 Thread Robert Rawlins - Think Blue
Hello Chaps,

 

I'm after some advice on the best way to handle a logging job. Essentially I
have data which I'm looking to log to a webservice, it would make good sense
I think to use something like the HTTP handler for the python logging API.

 

The problem comes when the application isn't 'online' as it were, with no
network connection or if the webservice isn't currently available. In this
case I don't want to simply loose all the log data, I want it stored into a
file, I can then run hourly batch/cron tasks to upload to the service when
the system comes back online.

 

How would you manage this? I'm thinking about building my own custom log
handler for the task, which if unable to resolve the webservice will just
log to the file instead, I'm just not sure if there is a better way of
achieving this, what are your thoughts?

 

In addition to this, does anyone know which libararys the HTTP handler uses
to make its call? Is it a good one which will recognise if the system has no
network connection or if the server is temporarily unavailable? Is it
asynchronous?

 

Thanks for any advice guys,

 

Robert

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

Re: Logging to HTTP or File

2008-02-27 Thread Jorge Vargas
On Wed, Feb 27, 2008 at 4:16 AM, Robert Rawlins - Think Blue
<[EMAIL PROTECTED]> wrote:
>
>
>
>
> Hello Chaps,
>
>
>
> I'm after some advice on the best way to handle a logging job. Essentially I
> have data which I'm looking to log to a webservice, it would make good sense
> I think to use something like the HTTP handler for the python logging API.
>
>
>
> The problem comes when the application isn't 'online' as it were, with no
> network connection or if the webservice isn't currently available. In this
> case I don't want to simply loose all the log data, I want it stored into a
> file, I can then run hourly batch/cron tasks to upload to the service when
> the system comes back online.
>
what exactly is this webservice? if you are expecting to have issue
with it why not just store locally and run a backup utility to
duplicate your logs?
>
>
> How would you manage this? I'm thinking about building my own custom log
> handler for the task, which if unable to resolve the webservice will just
> log to the file instead, I'm just not sure if there is a better way of
> achieving this, what are your thoughts?
>
if you really need this then I guess it's the best way to "merge" both
loggers into the same class.
>
>
> In addition to this, does anyone know which libararys the HTTP handler uses
> to make its call? Is it a good one which will recognise if the system has no
> network connection or if the server is temporarily unavailable? Is it
> asynchronous?
yes httplib what else will it use?

One of the things I love about python is that you can just go poke
into your installation to see how "the api" does things.
the relevant code is in /usr/lib/python2.5/logging/handlers.py:857 for
the HTTPHandler and /usr/lib/python2.5/logging/__init__.py:759 for the
FileHandler



>
>
>
> Thanks for any advice guys,
>
>
>
> Robert
> --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: library

2008-02-27 Thread Jorge Vargas
On Tue, Feb 26, 2008 at 11:24 PM, Raj kumar <[EMAIL PROTECTED]> wrote:
>
> hi,
> how to open python api documetation in linux machine?
$ python
import 
help(module|object|whatever)
> i think there should be a way to open installed library as a  HTML pages.
>
pydoc -p 

> Thanks in advance.
>
>
>  
>  Save all your chat conversations. Find them online.
> --
>  http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adobe CS3

2008-02-27 Thread Dotan Cohen
On 26/02/2008, Tobiah <[EMAIL PROTECTED]> wrote:
> But then again, when just adding a quip to a long thread in which
>  the readers have already seen the previous comments, top posting
>  can be an advantage to the reader.

You had to quote my message _five_times_ to get that point across?

Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
א-ב-ג-ד-ה-ו-ז-ח-ט-י-ך-כ-ל-ם-מ-ן-נ-ס-ע-ף-פ-ץ-צ-ק-ר-ש-ת

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: is there enough information?

2008-02-27 Thread castironpi
On Feb 26, 11:45 pm, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> Warning -- long post follows
>
> On Tue, 26 Feb 2008 12:17:54 -0800, Dennis Lee Bieber
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>
>
> >Which is, it seems, totally backwards... Also... to my knowledge,
> > the "with" construct (I'm still on Python 2.4 and don't have "with") is
> > NOT the same thing as a Java "Synchronized" object. The common use of
> > "with" is with objects, like files, that are opened at the start of the
> > block, and need to be closed on block exit, regardless of how the block
> > is exited.
>
> Okay... I do need to retract this part... Looking at the PEP, the
> "with" statement /can/ be made to act as a synchronization method IF
> supplied with an object that performs locking/unlocking as part of the
> "context manager" methods.
>
> But I still don't see any such in your usage. If it is there, it is
> not in the code you show us.
>
> Note that such synchronization of a critical section is meant
> only to ensure that one processing thread can execute the code (or
> access some data) in the critical section at a time. It is NOT meant to
> provide sequential control between threads. Sequential processing needs
> multiple signalling methods. You have four, I believe, critical sections
> (though they aren't critical in terms of being a shared access item --
> nothing is shared between your threads) -- hence you would need four
> separate locking objects.

This is very odd.  Yours -seems- (*subjective) backwards to -me-.  I
get the sense that yours and mine are orthogonal: you approach the
task "horizontally" where I approach it "vertically", for some rather
post-cognitive metric of approach, perhaps like breadth-first vs.
depth-first.  But I digress.

I realize that concrete examples are very useful in a thourough
analysis of the differences between our code.  Mine isn't very
concrete, but it might shed some light, keeping in mind that even if
it spotlights a flaw or weakness in either my or your solution, it's
not (repeat, NOT) a conclusive case for or against either.  Don't get
defensive!

The application is actually a test bed for still another kind of lock
I'm whittling, ironically enough.  The acq( thd, lck ) function sends
a message to thread thd to try to acquire lck.  It's important that
lck be acquired from thd specifically, as (i) there are get_ident()
calls like in threading.RLock, and as (ii) thd should actually block.
acq, however, does not: it fires the call, waits for a completion
event -or- timeout, and returns the return value if there is one, or a
special one if thd blocked.  That way I can check to make sure threads
are blocking on the right calls to the derived acquire method, and
returning the right values if they're not.

Rough overview:

#Case 1
[snip]
assert acq( thread3, lock3 ) is Blocks
assert acq( thread2, lock2 ) is Fails
assert acq( thread4, lock4 ) is Fails
assert acq( thread1, lock1 ) is Acquires
[snip]

The results vary because of other things that happened to the threads
and locks earlier in the case.  So I define acq like this:

def acq( thd, lck ):
   thd.test_lock_to_acquire= lck
   thd.set_cmd_assigned_signal.set()
   thd.set_cmd_completed.wait( 1 )
   ret= thd.cmd_return_value
   thd.set_return_value_read.set()
   return ret

The thread is running a loop, so that I can make multiple test calls
to the same thread, to simulate what happens if a thread acquires one
lock first, then another lock later, but, to repeat, I want the thread
that's governing the case to keep moving, whereas the thread that
makes the real acquire() call does actually block.

With acq, I set up an instruction-acknowledgement sequence, to get one
thread to do something that I don't determine ahead of time.
(Instruction and acknowledgement may not be the right words.)  The
thread runs in a function, thread_loop, that takes the thd parameter,
a probably misnamed container object instance that merely contains the
synchro events, a continue flag, the lock to try to acquire or None,
and the result of trying to acquire it or None.

def thread_loop( thd ):
   while thd.cont:
  thd.set_cmd_assigned_signal.wait()
  thd.cmd_return_value= Vacant
  ret= thd.test_lock_to_acquire.acquire()
  thd.cmd_return_value= ret
  thd.set_cmd_completed.set()
  thd.set_return_value_read.wait()

It first waits to be informed that it has an instruction pending.
Then it preps cmd_return_value, just in case the lock.acquire()
doesn't return, which it then attempts.  Whenever it returns, it sets
cmd_return_value to the returned value, informs acq() that it has
returned and waits for acq() to inform it that it has successfully
copied the value.  It may be that I don't have any use for the last
step, the corner case being if the case tries to use it twice in a
row.

To avoid the confusion of the trio of Event objects,
set_cmd_assigned_signal, set_cmd_completed,

Re: How to pass shell variable to shell script from python

2008-02-27 Thread Christian Heimes
Rockins Chen wrote:
> Hi all,
> 
> I encountered a problem: I have a python script, let's just name it
> caller.py, It calls a shell script, which is named callee.sh. In callee.sh,
> it need a shell variable $target, which should be supplied by caller.py(cannot
> pass by argument). I try to use os.environ to do this, as follows:

Don't use os.system or the popen functions. They have been substituted
with the subprocess module. It has a way to pass a new environment to a
process.

Christian

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


macro in python

2008-02-27 Thread bharath venkatesh
hi ..
how to create macro in python for set of instruction that is done
frequently but too less in number to ignore the overhead of function call
...
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Documentation - which format

2008-02-27 Thread Christian Heimes
Ben Finney wrote:
> Yes, TTBOMK. The site hasn't been updated for a while, but I follow
> the mailing list and activity continues on the code itself.

Python 2.6 and newer are using reST for documentation, see
http://docs.python.org/dev/

Christian


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


Re: How to pass shell variable to shell script from python

2008-02-27 Thread Gerardo Herzig
Rockins Chen wrote:

>Hi all,
>
>I encountered a problem: I have a python script, let's just name it
>caller.py, It calls a shell script, which is named callee.sh. In callee.sh,
>it need a shell variable $target, which should be supplied by caller.py(cannot
>pass by argument). I try to use os.environ to do this, as follows:
>
>caller.py
>--
>#/usr/bin/python
>
>import os
>
>os.environ["target"] = "localhost.localdomain.org"
>os.putenv("target", "localhost.localdomain.org")
>os.system("./callee.sh")
>---
>
>callee.sh
>---
>#!/bin/bash
>
>echo $target
>exit 0
>
>
>But, unluckily, it didn't work. What can I do?
>
>TIA,
>
>
>  
>
Well, if you have to use os.system, that could be
os.system("export target=localhost.localdomain.org; ./callee.sh")

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


refreshing the cache time of a key

2008-02-27 Thread bharath venkatesh
hi ..
   is it possible to refresh the cache time of a key with out having to
retrieving the cached data and storing it back in memcache .. for example if
a data is cached for
1 hour and  at the 50th minute from the time this data has been  cached i
want to   store it in the cache for  1  more  hour  ..is there a  function
to  refresh the cache time by knowing the key of data with out having to do
get and set
i.e
data=mc.get(key)
mc.set(key,data,3600) # 1 more  hour
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: __getattribute__ meta class?

2008-02-27 Thread Carl Banks
On Feb 27, 12:44 am, "bambam" <[EMAIL PROTECTED]> wrote:
> In retrospect, the project has three parts: remove
> side effects, push side effects to a common location, modify code so that
> changes only affect areas that encapsulate side effects.  This code allows
> top level code to pretend that the intermediate code has not changed.

Gah.

Libraries that "helpfully" do things on behalf of the user strike
again, and the mess bambam posted is what you have to do to disable
these "helpful" effects.

I'll grant that it's possible that the library wasn't trying to be
helpful and was just indicriminately letting side effects loose.

Shame on the writer in any case.


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


BaseHTTPServer and do_POST method

2008-02-27 Thread rocksportrocker
Hi,

I am trying to implement a local server for storing and retrieving
numerical data.
So I used BaseHTTPServer as follows:

from BaseHTTPServer import *

class Handler(BaseHTTPRequestHandler):

def do_POST(self):

print "POST"
self.send_response(200)


httpd = HTTPServer(("",8000), Handler)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-URL! - weekly Python news and links (Feb 18)

2008-02-27 Thread Peter Otten
Piet van Oostrum wrote:

>> "Gabriel Genellina" <[EMAIL PROTECTED]> (GG) wrote:
> 
>>GG> "Given this indispensable process and architecture issue, isn't it
>>obvious GG> that it's totally irrelevant to the system's overall safety
>>whether the GG> compiler has performed the further smattering of
>>semantically puny GG> 'verifications' allowed by mandatory-declaration,
>>stating-typing GG> languages?" - Alex Martelli
> 
> I couldn't find the original of this. I would like to see it in its
> context. Googling didn't reveal anything but this Python-URL.

My google is better than yours then:

http://mail.python.org/pipermail/python-list/2003-March/193864.html

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


Re: BaseHTTPServer and do_POST method

2008-02-27 Thread rocksportrocker
On Feb 27, 1:28 pm, rocksportrocker <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I am trying to implement a local server for storing and retrieving
> numerical data.
> So I used BaseHTTPServer as follows:
>
> from BaseHTTPServer import *
>
> class Handler(BaseHTTPRequestHandler):
>
> def do_POST(self):
>
> print "POST"
> self.send_response(200)
>
> httpd = HTTPServer(("",8000), Handler)

Please ignore this post, I accidentally hit the "Send" button before
finishing.

Greetings, Uwe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to pass shell variable to shell script from python

2008-02-27 Thread Philipp Pagel
Gerardo Herzig <[EMAIL PROTECTED]> wrote:
> Rockins Chen wrote:
> Well, if you have to use os.system, that could be
> os.system("export target=localhost.localdomain.org; ./callee.sh")

Or os.system("env target=localhost.localdomain.org ./callee.sh")

cu
Philipp

-- 
Dr. Philipp Pagel
Lehrstuhl f. Genomorientierte Bioinformatik
Technische Universität München
http://mips.gsf.de/staff/pagel
-- 
http://mail.python.org/mailman/listinfo/python-list


Why this ref leak?

2008-02-27 Thread Gerhard Häring
import sys

def foo():
 class C(object):
 pass

foo()
print ">>", sys.gettotalrefcount()
foo()
print ">>", sys.gettotalrefcount()
foo()
print ">>", sys.gettotalrefcount()

 >> 21366
 >> 21387
 >> 21408
[9779 refs]

Both Python 2.4 and 2.5 don't clean up properly here. Why is this? 
Aren't classes supposed to be garbage-collected?

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


Re: Documentation - which format

2008-02-27 Thread Wildemar Wildenburger
[EMAIL PROTECTED] wrote:
> Definitely ReST.  See http://rst2a.com/
> 
Hey, this is sweet! Thanks for that.

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


Re: object identity and hashing

2008-02-27 Thread castironpi
On Feb 25, 7:44 pm, Jeff Schwab <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
> > On Feb 24, 9:28 pm, George Sakkis <[EMAIL PROTECTED]> wrote:
>
> >> [1]http://www.martinfowler.com/eaaCatalog/identityMap.html
>
> > [1] illustrates a case in which 'a is a' returns False, and in the
> > other corner of the DeMorgan table, there is 'a is b' returns True for
> > 'a == b' False.
>
> What is the 'a is a' == False case?  I don't see anything like that
> illustrated on the Identity Map page.  Is it "P of EAA?"

Good point.  I don't know.  Just another logical possibility to go in
the 1% of cases.  What is P of EAA?

Also, notice: For the list and tuple types, x in y is true if and only
if there exists an index i such that x == y[i] is true-- from the
docs.

And:>>> 'abc' is 'abc'
True

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


BaseHTTPServer and do_POST method

2008-02-27 Thread rocksportrocker
Hi,

I am trying to implement a local server for storing and retrieving
numerical data.
So I use BaseHTTPServer as follows:

-
from BaseHTTPServer import *

class Handler(BaseHTTPRequestHandler):

def do_POST(self):

print "POST"
self.send_response(200)


httpd = HTTPServer(("",8000), Handler)
httpd.serve_forever()
-

For testing I use:

-

import httplib


data = "123456789o" * 100

conn = httplib.HTTPConnection("localhost:8000")
print conn.request("POST", "/", data)

---

Executing this client, the server says:

error(10053, 'Software caused connection abort')

If I add "conn.getresponse()" at the end of the test script, the
message disapears, but the server hangs.

Where is my mistake ?

Greetings, Uwe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Official IRC channel for Python?

2008-02-27 Thread js
> You can't join #python on freenode without identifying with nickserv
>  first.

Why is that?
I can join #perl, #php, #ruby, #mysql, #postgres without registration.
What advantage does it have? and the advantage really worth?

If #python were the developer's room, I'd say it's reasonable,
but that's not the case here.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python-URL! - weekly Python news and links (Feb 18)

2008-02-27 Thread Piet van Oostrum
> "Gabriel Genellina" <[EMAIL PROTECTED]> (GG) wrote:

>GG> "Given this indispensable process and architecture issue, isn't it obvious
>GG> that it's totally irrelevant to the system's overall safety whether the
>GG> compiler has performed the further smattering of semantically puny
>GG> 'verifications' allowed by mandatory-declaration, stating-typing
>GG> languages?" - Alex Martelli

I couldn't find the original of this. I would like to see it in its
context. Googling didn't reveal anything but this Python-URL.
-- 
Piet van Oostrum <[EMAIL PROTECTED]>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why this ref leak?

2008-02-27 Thread Thomas Heller
Gerhard Häring schrieb:
> import sys
> 
> def foo():
>  class C(object):
>  pass
> 
> foo()
> print ">>", sys.gettotalrefcount()
> foo()
> print ">>", sys.gettotalrefcount()
> foo()
> print ">>", sys.gettotalrefcount()
> 
>  >> 21366
>  >> 21387
>  >> 21408
> [9779 refs]
> 
> Both Python 2.4 and 2.5 don't clean up properly here. Why is this? 
> Aren't classes supposed to be garbage-collected?
> 
> -- Gerhard

Replace "foo()" with "foo(); gc.collect()" and the refcounts are stable.
Tested the python 2.6 from trunk.

Thomas

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


Re: time.time() strangeness

2008-02-27 Thread Roel Schroeven
Nitro schreef:
> Ok, my final solution is to add the D3DCREATE_FPU_PRESERVE flag. It didn't  
> harm performance in a noticeable way at all. I was under the impression  
> SSE would be affected by this, too. Additionally I was under the  
> impression that float precision would suffice for time.time(). Obviously I  
> was blatantly wrong :-)

Float precision might even be enough but DirectX (without the flag) 
switches to even lower precision than that; only 22 bits IIRC.

> They should really make the fpu preserve flag the default. It just causes  
> very sneaky bugs.

Absolutely.


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


Re: Portable linux python install

2008-02-27 Thread Martin Schmitz
Am 26.02.08 schrieb "Mike M" <[EMAIL PROTECTED]>:
> I have a python application which I'd like to distribute to thousands
> of machines in our server farm.

Install everything you need on the oldest box available and package it
with PyInstaller (http://pyinstaller.python-hosting.com/). Then you get
binaries which are only linked against libc - and as it happens to be
the oldest version of libc around you shouldn't have problems running
the binaries with newer ones.

HTH,
Martin

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


Re: macro in python

2008-02-27 Thread Guilherme Polo
2008/2/27, bharath venkatesh <[EMAIL PROTECTED]>:
> hi ..
> how to create macro in python for set of instruction that is done
> frequently but too less in number to ignore the overhead of function call
> ...
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>

There is lambda, not exactly a macro. Depending on the "macro", just
define a name.
But every program uses functions why cant yours ?

-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Official IRC channel for Python?

2008-02-27 Thread Guilherme Polo
2008/2/27, js <[EMAIL PROTECTED]>:
> > You can't join #python on freenode without identifying with nickserv
>  >  first.
>
>
> Why is that?
>  I can join #perl, #php, #ruby, #mysql, #postgres without registration.
>  What advantage does it have? and the advantage really worth?
>

The direct benefit is a probability of having less spam, and things
like that. Registering a nickname is pretty easy and don't bring you
problems, so I don't know why you wouldn't want to register one. The
benefit of registering your nickname is that other people won't be
able to use it to do something not so cool.

>  If #python were the developer's room, I'd say it's reasonable,
>  but that's not the case here.

Well, a lot of developers hang out there. Some are specifically python
developers and others works in other projects.

There is a rule of NO LOL there too, by the way. It is intended to be
a good channel for answering questions and getting good answers.

-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why this ref leak?

2008-02-27 Thread Peter Otten
Gerhard Häring wrote:

> import sys
> 
> def foo():
>  class C(object):
>  pass
> 
> foo()
> print ">>", sys.gettotalrefcount()
> foo()
> print ">>", sys.gettotalrefcount()
> foo()
> print ">>", sys.gettotalrefcount()
> 
>  >> 21366
>  >> 21387
>  >> 21408
> [9779 refs]
> 
> Both Python 2.4 and 2.5 don't clean up properly here. Why is this?
> Aren't classes supposed to be garbage-collected?

The reference keeping the classes alive is probably object.__subclasses__():

>>> class A(object): pass
...
>>> sum(1 for c in object.__subclasses__() if c.__name__ == "A")
1
>>> class A(object): pass
...
>>> sum(1 for c in object.__subclasses__() if c.__name__ == "A")
2

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

Re: Why this ref leak?

2008-02-27 Thread Peter Otten
Bjoern Schliessmann wrote:

> BTW, where is your method sys.gettotalrefcount supposed to come
> from? My CPython doesn't have it.

It's in the debug build only.

Peter 

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


Re: Why this ref leak?

2008-02-27 Thread Bjoern Schliessmann
Gerhard Häring wrote:

> Both Python 2.4 and 2.5 don't clean up properly here. Why is this?
> Aren't classes supposed to be garbage-collected?

Yes, but not neccessarily immediately.

BTW, where is your method sys.gettotalrefcount supposed to come
from? My CPython doesn't have it.

Regards,


Björn

-- 
BOFH excuse #219:

Recursivity.  Call back if it happens again.

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


Re: Why this ref leak?

2008-02-27 Thread Peter Otten
Peter Otten wrote:

>> Both Python 2.4 and 2.5 don't clean up properly here. Why is this?
>> Aren't classes supposed to be garbage-collected?
> 
> The reference keeping the classes alive is probably
> object.__subclasses__():
> 
 class A(object): pass
> ...
 sum(1 for c in object.__subclasses__() if c.__name__ == "A")
> 1
 class A(object): pass
> ...
 sum(1 for c in object.__subclasses__() if c.__name__ == "A")
> 2

Oops, wrong guess:

>>> import gc
>>> gc.collect()
6
>>> sum(1 for c in object.__subclasses__() if c.__name__ == "A")
1

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


Re: Return value of an assignment statement?

2008-02-27 Thread Bruno Desthuilliers
Jeff Schwab a écrit :
> [EMAIL PROTECTED] wrote:
>>> What you can't do (that I really miss) is have a tree of assign-and-test
>>> expressions:
>>>
>>> import re
>>> pat = re.compile('some pattern')
>>>
>>> if m = pat.match(some_string):
>>> do_something(m)
>>> else if m = pat.match(other_string):
>>> do_other_thing(m)
>>> else:
>>> do_default_thing()
>>
>> What you want is:
>>
>> for astring, afunc in ((some_string, do_something), (other_string,
>> do_other_thing)):
>> m = pat.match(astring)
>> if m:
>> afunc(m)
>> break
>> else:
>> do_default_thing()
> 
> That looks like the first realistic alternative I've seen.  I find the 
> flow a little hard to follow, but I think that's mostly just because I'm 
> not accustomed to the syntax.

Possibly. It may also have to do with the fact that - as Carl mentions - 
it's a bit overkill for quite a few cases.

> Your approach fits in my head a little more comfortably if none of the 
> lines are longer than eighty columns, if the for-loop isn't given an 
> else-clause (which still looks to my untrained eye like it should match 
> the preceding if),

It tooks me some times to get used to the for/else construct, but I now 
find it quite elegant. And helpful, in that it warns me that 'falling 
thru' the iteration is expected to be a special case.

> and if the break-statement is replaced with a 
> return-statement:
> 
> actions = (
> ('some_string', do_something),
> ('other_string', do_other_thing))
> 
> def find_action(pattern):
> for string, action in actions:
> m = pattern.match(string)
> if m:
> return action
> return do_default_thing
 >
> find_action(re.compile('some pattern'))()

As far as I'm concerned, I wouldn't use a function only because I don't 
yet feel confortable with for/else. And using a more generic version of 
this function may not necessarily help, unless it's really a pattern in 
your code (in which case the reader will quickly become familiar with it).

BTW, if you want a more generic version, here's one:

def find_action(test, choices, default):
 for arg, action in choices:
 result = test(arg)
 if result:
 return result, action
 else:
 return None, default


actions = (
 ('some_string', do_something),
 ('other_string', do_other_thing))
   )

pat = re.compile(some_pattern)
test = lambda s: pat.match(s)
match, action = find_action(test, actions, do_default_thing)
action(match)

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


Re: How to pass shell variable to shell script from python

2008-02-27 Thread D'Arcy J.M. Cain
On Wed, 27 Feb 2008 15:37:25 +0800
"Rockins Chen" <[EMAIL PROTECTED]> wrote:
> Clearly, I made some typing mistake, it's the shbang line! it should be:
> #!/usr/bin/python

Side topic - if you want portability use the following:

#! /usr/bin/env python

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: BaseHTTPServer and do_POST method

2008-02-27 Thread 7stud
On Feb 27, 5:33 am, rocksportrocker <[EMAIL PROTECTED]>
wrote:
> Hi,
>
> I am trying to implement a local server for storing and retrieving
> numerical data.
> So I use BaseHTTPServer as follows:
>
> -
>     from BaseHTTPServer import *
>
>     class Handler(BaseHTTPRequestHandler):
>
>         def do_POST(self):
>
>             print "POST"
>             self.send_response(200)
>
>     httpd = HTTPServer(("",8000), Handler)
>     httpd.serve_forever()
> -
>
> For testing I use:
>
> -
>
>     import httplib
>
>     data = "123456789o" * 100
>
>     conn = httplib.HTTPConnection("localhost:8000")
>     print conn.request("POST", "/", data)
>
> ---
>
> Executing this client, the server says:
>
>     error(10053, 'Software caused connection abort')
>
> If I add "conn.getresponse()" at the end of the test script, the
> message disapears, but the server hangs.
>
> Where is my mistake ?
>
> Greetings, Uwe.

I don't get that error.  On the server, I get the output:

POST
localhost - - [27/Feb/2008 06:49:13] "POST / HTTP/1.1" 200 -

and on the client I get:

None

I don't know what's causing the second line of output on the server.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-27 Thread Bruno Desthuilliers
Jeff Schwab a écrit :
(snip)
> This is apparently section 1.9 of the Python Cookbook:
> 
> http://www.oreilly.com/catalog/pythoncook2/toc.html
> 
> Martelli suggests something similar to the "thigamabob" technique I use 
> (he calls it DataHolder).  It's really more like the "xmatch" posted by 
> Paul Rubin.
> 
> Martelli also says, though, that if you need this, you're not thinking 
> Pythonically.

I'd personnaly read this as: "for most concrete cases, there's a Python 
idiom such that you don't need to set-and-test-at-once" - an example 
being given for the concrete case of 'iterating over lines in a file'.

>  I don't know what the Pythonic alternative is.  The 
> iterating-over-pairs approach suggested by Bruno is the only alternative 
> I've seen.

I guess it's considered the "pythonic alternative" for the concrete use 
case where there's no better idiom !-)

Note that as far as I'm concerned, I don't have much problem with 
get-and-set (which I commonly use in most other languages allowing it). 
In fact I'd probably prefer an expression-based version of Python (now 
would it still be Python is another question...) - but that's not been 
so far a string enough reason to switch language...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Getting python docstings

2008-02-27 Thread Rufman
ok...i took a look at epydoc. I can produce html documentation, but
when i try to generate a pdf, I get this error:


Error: latex failed: File `fancyhdr.sty' not found.latex: Error
   response from server: 404

my system:
 - MiKTeX2.7 installed
 - windows xp
 - ghostscript 8.60

Thanks for the help

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


Re: first time use of swig, python and c++ .. it's a mess ... please advice

2008-02-27 Thread Hyuga
On Feb 26, 3:38 pm, Eric von Horst <[EMAIL PROTECTED]> wrote:
> Hi,
>
> we have a third-party product that has a C++ api on HP-UX.
>
> I would like be able to use the API in Python (as I remember Python is
> good at doing this).
>
> I have no experience with this so I Googled and tried to find some
> info on what I had to do.
>
> So, I installed Python 2.4.4 and Swig 1.3.33
>
> The header file to the library is '/opt/OV/include/opcsvcapi.h'.
>
> I created a SWIG file with the following content:
> "
> %module opcsvcapi
>  %{
>  /* Includes the header in the wrapper code */
>  #include "/opt/OV/include/opcsvcapi.h"
>  %}
>
>  /* Parse the header file to generate wrappers */
>  %include "/opt/OV/include/opcsvcapi.h"
> "
> Then I ran the cmd:
> # swig -c++ -python opcsvcapi.i
> with output:
> "
> /opt/OV/include/opcsvcapi.h:41: Warning(362): operator= ignored
> /opt/OV/include/opcsvcapi.h:46: Warning(503): Can't wrap 'operator
> Type' unless renamed to a valid identifier.
> "
>
> The result are two files:
> opcsvcapi.py
> opcsvcapi_wrap.cxx
>
> I created a 'setup.py' file with the following content:
> "
> import distutils
> from distutils.core import setup, Extension
>
> setup(name = "opcsvcapi",
>       version = "1.0",
>       ext_modules = [Extension("_opcsvcapi",
> ["opcsvcapi.i","opcsvcapi.cxx"])])
> "
>
> Then I run: python setup.py build
>
> This results in an extra file:
> opcsvcapi_wrap.c and a 'build' directory
>
> and the following errors:
> "
> running build
> running build_ext
> building '_opcsvcapi' extension
> swigging opcsvcapi.i to opcsvcapi_wrap.c
> swig -python -o opcsvcapi_wrap.c opcsvcapi.i
> creating build
> creating build/temp.hp-ux-B.11.11-9000-800-2.4
> gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-
> prototypes -fPIC -I/usr/local/include/python2.4 -c opcsvcapi_wrap.c -o
> build/temp.hp-ux-B.11.11-9000-800-2.4/opcsvcapi_wrap.o
> In file included from /usr/local/include/python2.4/Python.h:8,
>                  from opcsvcapi_wrap.c:118:
> /usr/local/include/python2.4/pyconfig.h:851:1: warning:
> "_POSIX_C_SOURCE" redefined
> :1:1: warning: this is the location of the previous
> definition
> In file included from opcsvcapi_wrap.c:2490:
> /opt/OV/include/opcsvcapi.h:12:18: error: vector: No such file or
> directory
> In file included from opcsvcapi_wrap.c:2490:
> /opt/OV/include/opcsvcapi.h:15: error: expected '=', ',', ';', 'asm'
> or '__attribute__' before 'SvcAPI'
> opcsvcapi_wrap.c: In function 'Swig_var_SvcAPI_set':
> opcsvcapi_wrap.c:2505: error: 'SvcAPI' undeclared (first use in this
> function)
> opcsvcapi_wrap.c:2505: error: (Each undeclared identifier is reported
> only once
> opcsvcapi_wrap.c:2505: error: for each function it appears in.)
> opcsvcapi_wrap.c:2505: error: 'namespace' undeclared (first use in
> this function)
> opcsvcapi_wrap.c:2505: error: expected expression before ')' token
> opcsvcapi_wrap.c: In function 'init_opcsvcapi':
> opcsvcapi_wrap.c:3064: error: 'Swig_var_SvcAPI_get' undeclared (first
> use in this function)
> error: command 'gcc' failed with exit status 1
> "
>
> and that's it.
>
> Any idea what I am doing wrong?
>
> Any help much appreciated
>
> Kris

Well, the errors you got from the compiler are just confusing to me,
but I suspect it goes back to the warning you got from SWIG.  Some
class in there is overriding the = operator, but since that can't be
done in Python, you need to give it some special instructions on how
to handle that.

For example, if you have Foo::operator=, in your SWIG header include a
line like:
%rename(assign) Foo::operator=

Then in the Python module, the Foo class will have an assign method.

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


Re: BaseHTTPServer and do_POST method

2008-02-27 Thread rocksportrocker

If I ommit send_response() in do_POST() I get no
errormessage. That is an acceptable solution for me.

Greetings, Uwe
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Return value of an assignment statement?

2008-02-27 Thread Bruno Desthuilliers
Paddy a écrit :
> On 21 Feb, 23:33, "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> wrote:
>>> What you can't do (that I really miss) is have a tree of assign-and-test
>>> expressions:
>>> import re
>>> pat = re.compile('some pattern')
>>> if m = pat.match(some_string):
>>> do_something(m)
>>> else if m = pat.match(other_string):
>>> do_other_thing(m)
>>> else:
>>> do_default_thing()
>> What you want is:
>>
>> for astring, afunc in ((some_string, do_something), (other_string,
>> do_other_thing)):
>> m = pat.match(astring)
>> if m:
>> afunc(m)
>> break
>> else:
>> do_default_thing()
> 
> The Bruno transform? :-)

I do not claim any paternity on this idiom. FWIW, must be (in one or 
another variant) in quite a lot of texts / posts / sites / any other 
resource about Python.

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


Re: BaseHTTPServer and do_POST method

2008-02-27 Thread rocksportrocker
On Feb 27, 2:50 pm, 7stud <[EMAIL PROTECTED]> wrote:

> ...

> I don't get that error.  On the server, I get the output:
>
> POST
> localhost - - [27/Feb/2008 06:49:13] "POST / HTTP/1.1" 200 -
>
> and on the client I get:
>
> None
>
In my case the server says:


Traceback (most recent call last):
  File "c:\Python25\lib\SocketServer.py", line 222, in handle_request
self.process_request(request, client_address)
  File "c:\Python25\lib\SocketServer.py", line 241, in process_request
self.finish_request(request, client_address)
  File "c:\Python25\lib\SocketServer.py", line 254, in finish_request
self.RequestHandlerClass(request, client_address, self)
  File "c:\Python25\lib\SocketServer.py", line 522, in __init__
self.handle()
  File "c:\Python25\lib\BaseHTTPServer.py", line 316, in handle
self.handle_one_request()
  File "c:\Python25\lib\BaseHTTPServer.py", line 310, in
handle_one_request
method()
  File "dataserver.py", line 11, in do_POST
self.send_response(200)
  File "c:\Python25\lib\BaseHTTPServer.py", line 370, in send_response
self.send_header('Server', self.version_string())
  File "c:\Python25\lib\BaseHTTPServer.py", line 376, in send_header
self.wfile.write("%s: %s\r\n" % (keyword, value))
  File "c:\Python25\lib\socket.py", line 262, in write
self.flush()
  File "c:\Python25\lib\socket.py", line 249, in flush
self._sock.sendall(buffer)
error: (10053, 'Software caused connection abort')
---

Greetings, Uwe




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


Re: Logging to HTTP or File

2008-02-27 Thread D'Arcy J.M. Cain
On Wed, 27 Feb 2008 10:16:33 -
"Robert Rawlins - Think Blue" <[EMAIL PROTECTED]>
wrote:
> How would you manage this? I'm thinking about building my own custom log
> handler for the task, which if unable to resolve the webservice will just
> log to the file instead, I'm just not sure if there is a better way of
> achieving this, what are your thoughts?

Personally I would write to a local file all the time and have a second
process that reads that file and updates the server.  That way you
don't have to worry about external resources in your main program.  As
a side effect, you automatically get a local backup.  If the server
goes down your secondary process deals with it, not your primary app
that is handling your user requests.

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


MySQL and restore

2008-02-27 Thread Frank Aune
Hi,

Inspired from http://blog.spikesource.com/mysql_hotbackup.htm:
I restore a database from an SQL dump like this:

(...)
f= open('test.sql', 'r')
sql = f.read()
f.close()
self.query("""%s""" % sql)
(...)

This works fine for dumps made with "mysqldump -uroot -B test > test.sql". 
However, if performing a commit afterwards in the above code, I get 
a "command out of sync; you can't run this command now" I even get this when 
trying out the SET FOREIGN_KEY_CHECK properties as suggested in the URL.

How do I properly "clearn up" after processing the raw SQL file in the query 
above? 

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


[ANN] pyTenjin 0.6.2 - a fast and full-featured template engine

2008-02-27 Thread makoto kuwata
I have released pyTenjin 0.6.2.
http://www.kuwata-lab.com/tenjin/
This is a tiny bug fix release.

pyTenjin is the fastest template engine for Python.
Not only very fast, but also full-featured and easy-to-use is
pyTenjin.
You can embed Python statements and expressions into your text file.
Tenjin converts it into Python program and evaluate it.

Features:
* very fast
  - x2 faster than Mako
  - x3 faster than Cheetah and Myghty
  - x9 faster than Django
  - x60 faster than Kid
* Full-featured
  - layout template
  - partial template
  - capturing
  - preprocessing
  - and so on...

You can see the detail of benchmark at:
http://www.kuwata-lab.com/tenjin/
(benchmark script is included in pyTenjin distribution.)


Installation:

   $ easy_install Tenjin
   ## or download, extract, and execute 'setup.py'


Example: template.pyhtml

   ${title}
   
   
 ${item}
 #{item}
   
   

Example: main.py

   import tenjin
   from tenjin.helpers import to_str, escape
   engine = tenjin.Engine()
   context = { 'title': 'pyTenjin Example',
   'items': ['', 'B&B', '"CCC"'] }
   output = engine.render('template.pyhtml', context)
   print output,

Example: result

   $ python main.py
   pyTenjin Example
   
 
 
 B&B
 B&B
 "CCC"
 "CCC"
   


See user's guide and examples at the above page for details.
New release of pyTenjin will be informed at:
http://www.kuwata-lab.com/support/


Release 0.6.2:

[Changes]

  * When '-S', '-a retrieve', '-X', or '-a statements' specified,
pytenjin command replaces text before expressions into spaces
and print it.

[Bugfix]

  * pytenjin command printed "\n\n" instead of "\n" when '-U'
specified.
Fixed to print "\n".


--
regards,
makoto kuwata

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


Re: Why this ref leak?

2008-02-27 Thread Bjoern Schliessmann
Peter Otten wrote:
> Bjoern Schliessmann wrote:
 
>> BTW, where is your method sys.gettotalrefcount supposed to come
>> from? My CPython doesn't have it.
> 
> It's in the debug build only.

Makes sense; thank you.

Regards,


Björn

-- 
BOFH excuse #292:

We ran out of dial tone and we're and waiting for the phone company
to deliver another bottle.

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


Re: Why this ref leak?

2008-02-27 Thread Duncan Booth
Peter Otten <[EMAIL PROTECTED]> wrote:

> Peter Otten wrote:
> 
>>> Both Python 2.4 and 2.5 don't clean up properly here. Why is this?
>>> Aren't classes supposed to be garbage-collected?
>> 
>> The reference keeping the classes alive is probably
>> object.__subclasses__():
>> 
> class A(object): pass
>> ...
> sum(1 for c in object.__subclasses__() if c.__name__ == "A")
>> 1
> class A(object): pass
>> ...
> sum(1 for c in object.__subclasses__() if c.__name__ == "A")
>> 2
> 
> Oops, wrong guess:
> 
 import gc
 gc.collect()
> 6
 sum(1 for c in object.__subclasses__() if c.__name__ == "A")
> 1
> 
The list of subclasses is stored using weak references: that's why you have 
to call a method to create a real list. What actually stops the class just 
vapourising is its __mro__ attribute which creates a cycle, but the garbage 
collector clears that up as you saw.
-- 
http://mail.python.org/mailman/listinfo/python-list


XML expat error

2008-02-27 Thread dirkheld
Hi,

I have written a piece of code that reads all xml files in a directory
in onder to retrieve one element in each of these files. All files
have the same XML structure. After file 123 I receive the following
error :

xml.parsers.expat.ExpatError: not well-formed (invalid token): line
554, column 20

I guess that the element I try to read or the XML(which would be
strange since they have been created with the same code) can't ben
retrieved.

Is there a way to :
1. fix this problems so that I can retrieve it
2. is there a way that after such an error the invalid file is being
skipped and the program continues with reading the subsequent files;
Some sort of error handling?

Here is the code I use :

from xml.dom import minidom
import os
path = "/Documents/programming/data/xml/"


dirList = os.listdir(path)
url_file=open('/Documents/programming/data/xml/test.txt','w')
for file in dirList:
xmldoc = minidom.parse('/Documents/programming/data/xml/'+file)
xml_elem = xmldoc.getElementsByTagName('webpage')
web_elem = xml_elem[0]
url = web_elem.attributes['uri']
url_file.write(url.value + '\n')
url_file.close()
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: network programming: how does s.accept() work?

2008-02-27 Thread Grant Edwards
On 2008-02-27, Micah Cowan <[EMAIL PROTECTED]> wrote:
> Grant Edwards wrote:
>> On 2008-02-26, Micah Cowan <[EMAIL PROTECTED]> wrote:
>> 
>>> 7stud, what you seem to be missing, and what I'm not sure if anyone has
>>> clarified for you (I have only skimmed the thread), is that in TCP,
>>> connections are uniquely identified by a /pair/ of sockets (where
>>> "socket" here means an address/port tuple, not a file descriptor).
>> 
>> Using the word "socket" as a name for an address/port tuple is
>> precisely what's causing all the confusion.  An address/port
>> tuple is simply not a socket from a python/Unix/C point of
>> view, and a socket is not an address/port tuple.
>
> FWIW, the word was used to mean the address/port tuple (RFC
> 793) before there was ever a python/Unix/C concept of
> "socket".

I could claim I was innocently unaware of that usage, though I
have read the RFCs, so I'll go with Steve Martin's classic
excuse: "I forgot."

> And I totally agree that it's confusing; but I submit that
> IETF has a stronger claim over the term than Unix/C/Python,
> which could have just stuck with "network descriptor" or some
> such. ;)

They probably had to come up with a system call name that was
uniquely identified by six characters or something like that.

-- 
Grant Edwards   grante Yow! Does someone from
  at   PEORIA have a SHORTER
   visi.comATTENTION span than me?
-- 
http://mail.python.org/mailman/listinfo/python-list


ANN: ConfigObj 4.5.2 and validate 0.3.2

2008-02-27 Thread Fuzzyman
There was a bug in release 4.5.1 of ConfigObj, so there is now an
updated release:

* `ConfigObj 4.5.2 `_
* `Validate 0.3.2 `_

The bug affected the use of ``None`` as a default value in configspecs
and is now fixed.

What are ConfigObj and Validate?
=

**ConfigObj** is a simple to use but powerful configuration file
management library.
Features include:

* Nested sections to any depth
* Unicode support
* List and multiline values
* Integrated with a powerful validation system

- including automatic type checking/conversion
- repeated sections
- and allowing default values

* All comments in a file are preserved when writing
* The order of keys/sections is preserved
* A powerful unrepr mode for storing basic datatypes

**validate** is the module (optional) used for config file validation
and type marshalling. It
can be used outside of ConfigObj for matching string values against a
text specification which
also does type conversion.


Changes in ConfigObj 4.5.x


Distribution now includes validate 0.3.2 so ``None`` as a default
value in configspecs works again.

BUGFIX: Unicode configspecs now work.

ConfigObj will now guarantee that files will be written terminated
with a newline.

ConfigObj will no longer attempt to import the ``validate`` module,
until/unless you call ``ConfigObj.validate`` with
``preserve_errors=True``. This
makes it faster to import.

New methods ``restore_default`` and ``restore_defaults``.
``restore_default`` resets an entry to its default value (and returns
that value). ``restore_defaults`` resets all entries to their default
value. It doesn't modify entries
without a default value. You must have validated a ConfigObj (which
populates the ``default_values`` dictionary) before calling these
methods.

BUGFIX: Proper quoting of keys, values and list values that contain
hashes (when writing).  When ``list_values=False``, values containing
hashes are triple quoted.

Added the ``reload`` method. This reloads a ConfigObj from file. If
the filename attribute is not set then a ``ReloadError`` (a new
exception inheriting from ``IOError``) is raised.

BUGFIX: Files are read in with 'rb' mode, so that native/non-native
line endings work!

Minor efficiency improvement in ``unrepr`` mode.

Added missing docstrings for some overridden dictionary methods.

Added the ``reset`` method. This restores a ConfigObj to a freshly
created state.

Removed old CHANGELOG file.


Changes in Validate 0.3.x
==

BUGFIX: ``None`` as a default value handled correctly.

BUGFIX: Unicode checks no longer broken.

Improved performance with a parse cache.

New ``get_default_value`` method. Given a check it returns the default
value (converted to the correct type) or raises a ``KeyError`` if the
check doesn't specify a default.

Added 'tuple' check and corresponding 'is_tuple' function (which
always returns a tuple).

BUGFIX: A quoted 'None' as a default value is no longer treated as
None,
but as the string 'None'.

BUGFIX: We weren't unquoting keyword arguments of length two, so an
empty string didn't work as a default.

BUGFIX: Strings no longer pass the 'is_list' check. Additionally, the
list checks always return lists.

A couple of documentation bug fixes.

Removed CHANGELOG from module.

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


Re: Backup Script over ssh

2008-02-27 Thread Christian Kortenhorst
But there is no rsync for windows without using cygwin

On 2/26/08, Gabriel Genellina <[EMAIL PROTECTED]> wrote:
>
> En Thu, 21 Feb 2008 09:32:23 -0200, Christian Kortenhorst
> <[EMAIL PROTECTED]> escribió:
>
>
> > I am new to python and the list.
>
>
> Welcome?
>
>
> > I want to create backup script for my windows PC and upload to Linux
> > server
> > over ssh but whats the best way to go about this.
>
>
> rsync? No need to reinvent the wheel...
>
> --
> Gabriel Genellina
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
CK Computer Solutions
Christian Kortenhorst
+353-(0)87-6183349
+353-(0)1-4966287
-- 
http://mail.python.org/mailman/listinfo/python-list

Instance of inherited nested class in outer class not allowed?

2008-02-27 Thread mrstephengross
I've got an interesting problem with my class hierarchy. I have an
outer class, in which two nested classes are defined:

class Outer:
  class Parent:
def __init__ (self):
  print "parent!"
  class Child(Parent):
def __init__ (self):
  Outer.Parent.__init__(self)
  foo = Child()

Note that the second nested class (Outer.Child) inherits from the
first nested class (Outer.Parent). When I run the above code, python
reports a name error:

Traceback (most recent call last):
  File "./temp.py", line 3, in ?
class Outer:
  File "./temp.py", line 13, in Outer
foo = Child()
  File "./temp.py", line 11, in __init__
Outer.Parent.__init__(self)
NameError: global name 'Outer' is not defined

Apparently, python doesn't like having an instance of a derived nested
class present in the outer class. Interestingly enough, if I change
the foo variable to an instance of the parent class:

  foo = Parent()

everything is hunky-dory. Is there some syntax rule I'm breaking here?

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


Re: Getting python docstings

2008-02-27 Thread grflanagan
On Feb 27, 3:42 pm, Rufman <[EMAIL PROTECTED]> wrote:
> ok...i took a look at epydoc. I can produce html documentation, but
> when i try to generate a pdf, I get this error:
>
> Error: latex failed: File `fancyhdr.sty' not found.latex: Error
>response from server: 404
>
> my system:
>  - MiKTeX2.7 installed
>  - windows xp
>  - ghostscript 8.60
>
> Thanks for the help
>
> Stephane


Don't know anything about EpyDoc (maybe try under cygwin?), but one
way to get a pdf from a reST document is to use `rst2latex.py` which
comes with docutils, then use MikTeX to generate a pdf from the LaTeX.

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


Re: XML expat error

2008-02-27 Thread Richard Brodie

"dirkheld" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> xml.parsers.expat.ExpatError: not well-formed (invalid token): line
> 554, column 20
>
> I guess that the element I try to read or the XML(which would be
> strange since they have been created with the same code) can't ben
> retrieved.

It's fairly easy to write non-robust XML generating code, and also
quick to test if one file is always bad. Drop it into a text editor or
Firefox, and take a quick look at line 554. Most likely some random
control character has sneaked in; it only takes (for example) one NUL
to make the document ill-formed.



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


Making string-formatting smarter by handling generators?

2008-02-27 Thread Tim Chase
Is there an easy way to make string-formatting smart enough to 
gracefully handle iterators/generators?  E.g.

   transform = lambda s: s.upper()
   pair = ('hello', 'world')
   print "%s, %s" % pair # works
   print "%s, %s" % map(transform, pair) # fails

with a """
TypeError:  not enough arguments for format string
"""

I can force it by wrapping the results of my generator in a call 
to tuple() or list()

   print "%s, %s" % tuple(map(transform, pair))

but it feels a bit hackish to me.

I find I hit it mostly with calls to map() where I want to apply 
some transform (as above) to all the items in a list of 
parameters such as

   "%s=%s&%s=%s" % map(urllib.quote, params)

Any suggestions?  (even if it's just "get over your hangup with 
wrapping the results in list()/tuple()" :)

Thanks,

-tkc





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


Raising exception on STDIN read

2008-02-27 Thread Michael Goerz
Hi,

I would like to raise an exception any time a subprocess tries to read 
from STDIN:

latexprocess = subprocess.Popen( \
 'pdflatex' + " " \
  + 'test' + " 2>&1", \
 shell=True, \
 cwd=os.getcwd(), \
 env=os.environ, \
 stdin=StdinCatcher() # any ideas here?
 )

An exception should be raised whenever the pdflatex process
reads from STDIN... and I have no idea how to do it. Any suggestions?

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


Re: Making string-formatting smarter by handling generators?

2008-02-27 Thread grflanagan
On Feb 27, 5:23 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> Is there an easy way to make string-formatting smart enough to
> gracefully handle iterators/generators?  E.g.
>
>transform = lambda s: s.upper()
>pair = ('hello', 'world')
>print "%s, %s" % pair # works
>print "%s, %s" % map(transform, pair) # fails
>
> with a """
> TypeError:  not enough arguments for format string
> """
>
> I can force it by wrapping the results of my generator in a call
> to tuple() or list()
>
>print "%s, %s" % tuple(map(transform, pair))
>
> but it feels a bit hackish to me.
>
> I find I hit it mostly with calls to map() where I want to apply
> some transform (as above) to all the items in a list of
> parameters such as
>
>"%s=%s&%s=%s" % map(urllib.quote, params)
>
> Any suggestions?  (even if it's just "get over your hangup with
> wrapping the results in list()/tuple()" :)
>
> Thanks,
>
> -tkc

FWIW, I had a similar problem and came up with a custom scheme:

http://gflanagan.net/site/python/utils/template.py

(still a work in progress).

>From the doctest:

Map operator. Expects a list (iterator) whose each item is either a
tuple
or a dict. If the variable exists (and optionally is not null), then
for each tuple/dict yield the formatted default.

>>> t = Template("""
... {{names|
... Hello %s %s!
... }}
... """)
>>> print t.replace()
Traceback (most recent call last):
...
KeyError: 'names'
>>> print t.replace(names=[('John', 'Doe'), ('Jane', 'Doe')])
Hello John Doe!
Hello Jane Doe!

HTH

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


Re: Raising exception on STDIN read

2008-02-27 Thread Ian Clark
On 2008-02-27, Michael Goerz <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I would like to raise an exception any time a subprocess tries to read 
> from STDIN:
>
> latexprocess = subprocess.Popen( \
>  'pdflatex' + " " \
>   + 'test' + " 2>&1", \
>  shell=True, \
>  cwd=os.getcwd(), \
>  env=os.environ, \
>  stdin=StdinCatcher() # any ideas here?
>  )
>
> An exception should be raised whenever the pdflatex process
> reads from STDIN... and I have no idea how to do it. Any suggestions?
>
> Thanks,
> Michael

How about with a file-like object? I haven't tested this with subprocess
so you might want to read the manual on files if it doesn't work[1].

import sys 

class ErrorFile(object):
def _error(self, *args, **kwargs):
raise AssertionError("Illegal Access")

def _noop(self, *args, **kwargs):
pass

close = flush = seek = tell = _noop
next = read = readline = readlines = xreadlines = tuncate = 
_error
truncate = write = writelines = _error

sys.stdin = ErrorFile()
print raw_input("? ")

Ian

[1] http://docs.python.org/lib/bltin-file-objects.html

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


Python's BNF

2008-02-27 Thread MartinRinehart
I spent too long Googling for Python's BNF. Eventually found it at
Python.org, but only by accident.

I've put Python's BNF here: 
http://www.martinrinehart.com/articles/python-parse-bnf.html

Extensively cross-referenced.

Addenda:

No, Google, I didn't want the Botswana daily news with its article on
the Botswana
National Front and another on a fellow arrested for having contraband
python skins.

Did this with a Python program. Used to use Perl for this sort of
thing. Doubt I'll ever write another line of Perl.

There's a link to the program, top-right of page. If anyone wants to
look at this no-longer-quite-newbie's code and give a constructive
critique, I'd be grateful.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making string-formatting smarter by handling generators?

2008-02-27 Thread D'Arcy J.M. Cain
On Wed, 27 Feb 2008 10:23:49 -0600
Tim Chase <[EMAIL PROTECTED]> wrote:
> I can force it by wrapping the results of my generator in a call 
> to tuple() or list()

I think you are wrong about list().  Since map() returns a list already
it doesn't change anything.

>print "%s, %s" % tuple(map(transform, pair))

Yes, it works.

> but it feels a bit hackish to me.

I can't imagine what else you could do to turn a list into a tuple that
would be less hackish than simply making it a tuple.

> I find I hit it mostly with calls to map() where I want to apply 
> some transform (as above) to all the items in a list of 
> parameters such as
> 
>"%s=%s&%s=%s" % map(urllib.quote, params)

Isn't map() deprecated?  The above can be done with;

"%s=%s&%s=%s" % tuple([urllib.quote(x) for x in params])

> Any suggestions?  (even if it's just "get over your hangup with 
> wrapping the results in list()/tuple()" :)

Pretty much.  :-)

-- 
D'Arcy J.M. Cain <[EMAIL PROTECTED]> |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Making string-formatting smarter by handling generators?

2008-02-27 Thread Arnaud Delobelle
On Feb 27, 4:23 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> Is there an easy way to make string-formatting smart enough to
> gracefully handle iterators/generators?  E.g.
>
>    transform = lambda s: s.upper()
>    pair = ('hello', 'world')
>    print "%s, %s" % pair # works
>    print "%s, %s" % map(transform, pair) # fails
>
> with a """
> TypeError:  not enough arguments for format string
> """
>
> I can force it by wrapping the results of my generator in a call
> to tuple() or list()

(Are you using python 3.0 ? For python < 3, map returns a list)

list() wouldn't work as % expects a tuple (otherwise it considers that
only one argument is needed).  The problem would arise with any non-
tuple iterable, not just generators.

See http://docs.python.org/lib/typesseq-strings.html

>
>    print "%s, %s" % tuple(map(transform, pair))
>
> but it feels a bit hackish to me.

I think it is the way to do it though.

> I find I hit it mostly with calls to map() where I want to apply
> some transform (as above) to all the items in a list of
> parameters such as
>
>    "%s=%s&%s=%s" % map(urllib.quote, params)
>
> Any suggestions?  (even if it's just "get over your hangup with
> wrapping the results in list()/tuple()" :)

get over your hangup with wrapping the results in tuple()! (not list()
though, as explained above).

Or you could always define

def tmap(*args):
return tuple(map(*args))

--
Arnaud

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


Re: Python's BNF

2008-02-27 Thread Arnaud Delobelle
On Feb 27, 5:23 pm, [EMAIL PROTECTED] wrote:
> I spent too long Googling for Python's BNF. Eventually found it at
> Python.org, but only by accident.

http://www.google.com/search?q=python+grammar

--
Arnaud

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


Re: refreshing the cache time of a key

2008-02-27 Thread Sean Chittenden
>is it possible to refresh the cache time of a key with out having  
> to retrieving the cached data and storing it back in memcache .. for  
> example if a data is cached for
> 1 hour and  at the 50th minute from the time this data has been   
> cached i want to   store it in the cache for  1  more  hour  ..is  
> there a  function  to  refresh the cache time by knowing the key of  
> data with out having to do get and set
> i.e
> data=mc.get(key)
> mc.set(key,data,3600) # 1 more  hour

It's not possible with the current code base.  I posted a patch a few  
years back that did this  here we go:

http://lists.danga.com/pipermail/memcached/2004-November/000880.html

It should be easy to apply the patch by hand if it fails to apply  
cleanly out of the gate.  I'm not sure how memcache can survive as a  
store for session information without this patch, but...  See the post  
for details that I won't bore folks with here.  -sc

-- 
Sean Chittenden
[EMAIL PROTECTED]



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


Re: refreshing the cache time of a key

2008-02-27 Thread Dustin Sallings

On Feb 27, 2008, at 4:17, bharath venkatesh wrote:

>is it possible to refresh the cache time of a key with out having  
> to retrieving the cached data and storing it back in memcache .. for  
> example if a data is cached for
> 1 hour and  at the 50th minute from the time this data has been   
> cached i want to   store it in the cache for  1  more  hour  ..is  
> there a  function  to  refresh the cache time by knowing the key of  
> data with out having to do get and set


There's been talk of a ``touch'' command, but no work has been done  
on implementing such a thing.

-- 
Dustin Sallings

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


how to create eigenface image

2008-02-27 Thread harryos
hi all
I am new to python and learning PCA method by reading up Turk&Petland
papers etc
while trying out PCA on a set of greyscale images using python, and
numpy I tried to create eigenvectors and facespace.

i have
 facesarray--- an NXP numpy.ndarray that contains data of images
   N=numof images,P=pixels in an image
avgarray --1XP array containing avg value for each pixel
 adjustedfaces=facesarray-avgarray
adjustedmatrix=matrix(adjustedfaces)
adjustedmatrix_trans=adjustedmatrix.transpose()
covariancematrix =adjustedmatrix*adjustedmatrix_trans
evalues,evect=eigh(covariancematrix)

after sorting such that most significant eigenvectors are selected
evectmatrix is now my eigenvectors matrix

here is a sample using 4X3 greyscale images

evalues
[ -1.85852801e-13   6.31143639e+02   3.31182765e+03   5.29077871e+03]
evect
[[ 0.5-0.06727772  0.6496399  -0.56871936]
 [ 0.5-0.77317718 -0.37697426  0.10043632]
 [ 0.5 0.27108233  0.31014514  0.76179023]
 [ 0.5 0.56937257 -0.58281078 -0.29350719]]

evectmatrix  (sorted according to largest evalue first)
[[-0.56871936  0.6496399  -0.06727772  0.5   ]
 [ 0.10043632 -0.37697426 -0.77317718  0.5   ]
 [ 0.76179023  0.31014514  0.27108233  0.5   ]
 [-0.29350719 -0.58281078  0.56937257  0.5   ]]



then i can create facespace by
facespace=evectmat*adjustedfaces

what i want to know is how i can create eigenface images .
when you mean an eigenvector ,is that a row of evectmatrix above?  is
evectmatrix[0] the eigenvector for first image and so on? I would
appreciate if someone can make this clear.

also
when i tried to make an image by
im=im = Image.new('L', (width,height))
im.putdata(evectmat[0])
im.save("eigenface0.jpg")

it created an image with all pixels dark with no details to see
the same occurrs if i use
im.putdata(facespace[0])
can someone tell me if i am doing it wrong..




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


Re: time.time() strangeness

2008-02-27 Thread Ross Ridge
Nitro  <[EMAIL PROTECTED]> wrote:
>They should really make the fpu preserve flag the default. It just causes  
>very sneaky bugs.

They did in Direct3D 10, which doesn't change the flags.  It's too late
to change the behaviour Direct3D 9 which was created a time where changing
FPU precision could have an effect on low end configurations.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: European python developers

2008-02-27 Thread Martin P. Hellwig
[EMAIL PROTECTED] wrote:
> Hi Python Enthusiasts,
> 
> I am hoping one or two members of this list might help me locate in Europe
> to begin a small team of developers with a focus on python for the central
> part of the server development. 
> 
> My personal first choice is Spain only because I like it, and will
> eventually have Spanish as a second language, but I am very concerned about
> finding people, especially considering costs. 
> 
> I have worked virtually with three people from Ukraine and Russia, and a
> chap living in Germany all who appear to be talented and others have told me
> about other countries such as Poland. 
> 
> The point is that I can't really afford to run around and experiment, so I
> was hoping for some helpful comments or suggestions on how to research, or
> where to look, or how to recruit.
> 
> If this has already been a topic of the list, I would appreciate any
> pointers.
> 
> Thanks, Jerry
> 

Hello Jerry,

Moving to another country can be a daunting task, I moved from Germany 
to the Netherlands and looking forward to move to the UK. Friends of 
mine have moved to Greece and Spain, by this heard some of their 
troubles along the way.

First things first, you need to be sure that your motivation for moving 
is absolutely unquestionable (for yourself that is). If you move for the 
warm climate, consider buying a better coat :-)

Joking aside, of course you are a bit adventurous, otherwise you 
wouldn't think about it and of course you want to be well prepared, 
otherwise you wouldn't have asked :-)

Personally I think that wherever you go in the world you will be 
surprised how many qualified people live there, the only problem is that 
you have to meet them. Another problem is that you might not notice 
talented people because they have no experience in your area but are 
willing to get it. Saying it short, you won't have trouble finding 
qualified personnel when you are prepared to reward them well and/or 
train them for the purpose of your business.

Personally I always prefer (self) motivating personnel that are curious 
and smart. They might be not valuable instantly because they still have 
to figure out the tools but usually they are more the kind of people I 
like. I am well aware that the people I hire will grow in their 
specialty and eventually go on to better things, that is unfortunate but 
  it is just the way things go.

Never try to restrict people when they want to leave, give them a warm 
goodbye party and help them in their transition as much as you can. Not 
only is that good for the employee that left but it helps with the 
atmosphere among the remaining people and it gives me a good feeling.

One of the biggest problems when settling in another country for 
business purposes is the language, speak/read the language well enough 
before you leave your home country.

Second problem is culture, I am quite strict on my business 
communications and agreements. That means I will get totally frustrated 
in countries like Spain, Italy, Greece, Portugal and the lower parts of 
France. I don't say I am right and they are wrong, the perception on how 
to do _any_ business is different and I can't adopt to theirs (so it is 
my problem and not theirs).

Third problem is regulations, thanks to the EU besides of the normal 
(lack of) regulations you have a ton more of them. The only thing that 
is in common for all of Europe is that it doesn't matter where you are 
or where you from, in a business dispute the local will be favored above 
the foreigner. In countries like I already mentioned and especially the 
sparse populated area's this can go into extremes.

Fourth problem is integration, even if you integrate it doesn't mean 
that locals will except you as a local. Sometimes the best you can get 
is that you are accepted but never be one of their own. Usually that 
does not rise to the surface but especially in disagreements you might 
find it illogical how some decisions are made, even if you get children 
that are born their, they still might be confronted with that.

So to wrap it up:
Speak the language before you arrive
Learn the cultural difference before you arrive
Embrace the new culture and be an active part of it
Be aware that you will always be a foreigner

If you do that, hiring good people will be no problem, that if you are 
not looking for PhD's in a very limited and specialized field that takes 
ages to master.

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


Re: Instance of inherited nested class in outer class not allowed?

2008-02-27 Thread Diez B. Roggisch
mrstephengross schrieb:
> I've got an interesting problem with my class hierarchy. I have an
> outer class, in which two nested classes are defined:
> 
> class Outer:
>   class Parent:
> def __init__ (self):
>   print "parent!"
>   class Child(Parent):
> def __init__ (self):
>   Outer.Parent.__init__(self)
>   foo = Child()
> 
> Note that the second nested class (Outer.Child) inherits from the
> first nested class (Outer.Parent). When I run the above code, python
> reports a name error:
> 
> Traceback (most recent call last):
>   File "./temp.py", line 3, in ?
> class Outer:
>   File "./temp.py", line 13, in Outer
> foo = Child()
>   File "./temp.py", line 11, in __init__
> Outer.Parent.__init__(self)
> NameError: global name 'Outer' is not defined
> 
> Apparently, python doesn't like having an instance of a derived nested
> class present in the outer class. Interestingly enough, if I change
> the foo variable to an instance of the parent class:
> 
>   foo = Parent()
> 
> everything is hunky-dory. Is there some syntax rule I'm breaking here?

It's simple - you try to refer to Outer whilst Outer itself is being 
created. A much simpler version of your problem is this:


class Foo:
  foo = Foo()

You have to live with that. Just do

Outer.foo = Outer.Parent()

after your class-statement to achieve the same result.

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


Re: How about adding rational fraction to Python?

2008-02-27 Thread Ross Ridge
Mark Dickinson  <[EMAIL PROTECTED]> wrote:
>True division and floor division are different operations.  It doesn't
>seem ridiculous to use different operators for them.

I don't have a problem with there being different operators for integer
and floating-point division.  I have a problem with the behviour of the
slash (/) operator changing.

Ross Ridge

-- 
 l/  //   Ross Ridge -- The Great HTMU
[oo][oo]  [EMAIL PROTECTED]
-()-/()/  http://www.csclub.uwaterloo.ca/~rridge/ 
 db  //   
-- 
http://mail.python.org/mailman/listinfo/python-list


Print to end of line in a terminal

2008-02-27 Thread ndlarsen
Hey.

This might seem as a arbitrary question to some. Anyway, I'm wondering 
how I go about printing text to the end of a line in a terminal/console. 
I've been googling it for a few days without any success. Any 
suggestions will be greatly appreciated.

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


Re: Instance of inherited nested class in outer class not allowed?

2008-02-27 Thread mrstephengross
> class Foo:
>   foo = Foo()
>
> You have to live with that. Just do
> Outer.foo = Outer.Parent()
> after your class-statement to achieve the same result.

Hmmm. Well, I see why that works. It's too bad, though. If I want to
keep all executed code safely within a "if __name__ == '__main__'"
block, it ends up a bit ugly. Then again, I guess this is just an
aspect of python I'll have to get used to. Is there a specific reason
it works this way, by chance?

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


X Windows Problems in 2.5.2

2008-02-27 Thread SwimmingApe
Hi there,

first off I'm running MAC OS X 10.4.11 on a Intel MacBook Pro using
Apples X11. For a project I am working on I have to start a separate
gui (in this case based on the Fox toolkit) as a thread in python. So
I have a swig wrapper around some C++ code which starts the thread,
creates the windows etc.. This worked fine in python 2.4 as well as in
python 2.5.1. However with 2.5.2 I am getting a continuous stream of
error messages which seem to be X related.

X Error: code 3 major 12 minor 0: BadWindow (invalid Window
parameter).
X Error: code 9 major 70 minor 0: BadDrawable (invalid Pixmap or
Window parameter).
X Error: code 9 major 62 minor 0: BadDrawable (invalid Pixmap or
Window parameter).
X Error: code 3 major 12 minor 0: BadWindow (invalid Window
parameter).
X Error: code 3 major 12 minor 0: BadWindow (invalid Window
parameter).
X Error: code 9 major 70 minor 0: BadDrawable (invalid Pixmap or
Window parameter).
:
:
:

Does anyone know what difference between 2.5.1 and 2.5.2 could cause
something like this. The identical code call from 2.5.1 or straight
from C++ works perfectly and I don't have enough experience with X
related problems to even know where to look

Thanks

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


threading/Queue: join() and task_done() not working? (deadlock)

2008-02-27 Thread Gal Aviel
Hello All,

I'm seeing strange behavior where one thread waits on a queue using join() and
the later (or so I think, according to order of the printing in STDOUT) another
thread calls task_done() on the very same queue, however the first thread does
not wake up, it keeps blocking forever.

I'm using a queue of size 1, my print's:

# @115000   : DEBUG  PY wait(): waiting for task_done
#on 
# @115000   : DEBUG  PY callback_cb() - 2
# @115000   : DEBUG  PY callback_cb() - signaling
#task_done on 
# @115000   : DEBUG  PY callback_cb() - 3

As you can see, the queue object is the same on both threads. 

Any help would be greatly appreciated, since I've spent days and days on this
already !!

Python 2.5.1, SUSE LINUX Enterprise Server 9.

Thanks in advance, Gal Aviel.





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


Re: BaseHTTPServer and do_POST method

2008-02-27 Thread Gabriel Genellina
En Wed, 27 Feb 2008 10:33:35 -0200, rocksportrocker  
<[EMAIL PROTECTED]> escribi�:

> Hi,
>
> I am trying to implement a local server for storing and retrieving
> numerical data.
> So I use BaseHTTPServer as follows:
>
> -
> from BaseHTTPServer import *
>
> class Handler(BaseHTTPRequestHandler):
>
> def do_POST(self):
>
> print "POST"
> self.send_response(200)
>
>
> httpd = HTTPServer(("",8000), Handler)
> httpd.serve_forever()
> -
>
> For testing I use:
>
> -
>
> import httplib
>
>
> data = "123456789o" * 100
>
> conn = httplib.HTTPConnection("localhost:8000")
> print conn.request("POST", "/", data)
>
> ---
>
> Executing this client, the server says:
>
> error(10053, 'Software caused connection abort')
>
> If I add "conn.getresponse()" at the end of the test script, the
> message disapears, but the server hangs.

If you don't add that line, the client process exits and drops the  
connection, and the server detects that situation when it tries to send  
the response to a dead socket.
The server "hangs" because you told it to "serve_forever"; it's waiting  
for the next request. Use Ctrl-C to stop it.
You may find easier to use urllib or urllib2 to write the client.

-- 
Gabriel Genellina

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

Re: Making string-formatting smarter by handling generators?

2008-02-27 Thread Boris Borcic
D'Arcy J.M. Cain wrote:
>> I find I hit it mostly with calls to map() where I want to apply 
>> some transform (as above) to all the items in a list of 
>> parameters such as
>>
>>"%s=%s&%s=%s" % map(urllib.quote, params)
> 
> Isn't map() deprecated?  The above can be done with;
> 
> "%s=%s&%s=%s" % tuple([urllib.quote(x) for x in params])
> 
>> Any suggestions?  (even if it's just "get over your hangup with 
>> wrapping the results in list()/tuple()" :)
> 
> Pretty much.  :-)
> 

...except for saving on a level of brackets or parens, since you can actually 
write

"%s=%s&%s=%s" % tuple(urllib.quote(x) for x in params)

instead of the above

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


Re: Official IRC channel for Python?

2008-02-27 Thread Paul Rubin
"Guilherme Polo" <[EMAIL PROTECTED]> writes:
> >  I can join #perl, #php, #ruby, #mysql, #postgres without registration.
> >  What advantage does it have? and the advantage really worth?
> 
> The direct benefit is a probability of having less spam, and things
> like that.

I don't remember ever seeing irc spam on freenode.  I see it once in a
while on undernet.  This is a non-problem.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: threading/Queue: join() and task_done() not working? (deadlock)

2008-02-27 Thread Raymond Hettinger
On Feb 27, 11:06 am, Gal Aviel <[EMAIL PROTECTED]> wrote:
> Hello All,
>
> I'm seeing strange behavior where one thread waits on a queue using join() and
> the later (or so I think, according to order of the printing in STDOUT) 
> another
> thread calls task_done() on the very same queue, however the first thread does
> not wake up, it keeps blocking forever.
>
> I'm using a queue of size 1, my print's:


Does the problem persist with a queue size of 2?


Raymond

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


Re: Instance of inherited nested class in outer class not allowed?

2008-02-27 Thread Gabriel Genellina
En Wed, 27 Feb 2008 16:52:57 -0200, mrstephengross  
<[EMAIL PROTECTED]> escribi�:

>> class Foo:
>>   foo = Foo()
>>
>> You have to live with that. Just do
>> Outer.foo = Outer.Parent()
>> after your class-statement to achieve the same result.
>
> Hmmm. Well, I see why that works. It's too bad, though. If I want to
> keep all executed code safely within a "if __name__ == '__main__'"
> block, it ends up a bit ugly. Then again, I guess this is just an
> aspect of python I'll have to get used to. Is there a specific reason
> it works this way, by chance?

class statements (and def, and almost everything in Python) are  
*executable* statements, not declarations.
When you import a module, it is executed. If it contains a class  
statement, it is executed as follows: create an empty namespace (a dict),  
execute the class body in it, create a new class object with __dict__ =  
that namespace, and finally, bind the class name to the newly created  
class object in the module namespace.
Until that last step, you can't refer to the class being created by name.

I don't get your issue with "if __name__==__main__", but I hope that you  
now understand a bit better why a late initialization is required. (Of  
course someone could come up with a metaclass to perform that late  
initialization, but the important thing is to understand that you cannot  
create an instance before the class itself exists)

-- 
Gabriel Genellina

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

Re: Fwd: Problem with threads in python????????

2008-02-27 Thread James Matthews
Yes

On Wed, Feb 27, 2008 at 3:56 AM, <[EMAIL PROTECTED]> wrote:

> On Feb 26, 7:56 pm, "Gabriel Genellina" <[EMAIL PROTECTED]>
> wrote:
> > En Tue, 26 Feb 2008 01:46:48 -0200, Manikandan R <[EMAIL PROTECTED]>
>
> > escribió:
> >
> > > Hai,
> >
> > >   Is it possible to share a single variable between multiple
> > > threads. For eg:
> >
> > > Class A:
> > >  thread_init()
> >
> > >def run():
> > >   fun1()
> >
> > > def fun():
> > >   assume some arithmatic operation is going on according to
> the
> > > input given and each fun will *give different output*
> > > .
> >
> > Store the result inside the thread object; that is, in run, self.result=
> > fun1(...)
> >
> > > Now 10 Thread will be running and each thread will have there
> individual
> > > output.
> >
> > >Here is the problem now i want the sum of output of all the
> > > function.
> >
> >  From your code I imagine you have a list of Thread instances;
> >
> > global_result = sum([t.result for t in list_of_threads])
> >
> > --
> > Gabriel Genellina
>
> You can always hash the thread id: results[get_ident()]= result.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
http://search.goldwatches.com/?Search=Movado+Watches
http://www.jewelerslounge.com
http://www.goldwatches.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: refreshing the cache time of a key

2008-02-27 Thread Sean Chittenden
>is it possible to refresh the cache time of a key with out having  
> to retrieving the cached data and storing it back in memcache .. for  
> example if a data is cached for
> 1 hour and  at the 50th minute from the time this data has been   
> cached i want to   store it in the cache for  1  more  hour  ..is  
> there a  function  to  refresh the cache time by knowing the key of  
> data with out having to do get and set
> i.e
> data=mc.get(key)
> mc.set(key,data,3600) # 1 more  hour

It's not possible with the current code base.  I posted a patch a few  
years back that did this  here we go:

http://lists.danga.com/pipermail/memcached/2004-November/000880.html

It should be easy to apply the patch by hand if it fails to apply  
cleanly out of the gate.  FWIW, I find this functionality invaluable.   
See the post for details.  -sc

--
Sean Chittenden
[EMAIL PROTECTED]
http://sean.chittenden.org/

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


Re: Raising exception on STDIN read

2008-02-27 Thread Michael Goerz
Ian Clark wrote, on 02/27/2008 12:06 PM:
> On 2008-02-27, Michael Goerz <[EMAIL PROTECTED]> wrote:
>> I would like to raise an exception any time a subprocess tries to read 
>> from STDIN:
>> latexprocess = subprocess.Popen( \
>>  'pdflatex' + " " \
>>   + 'test' + " 2>&1", \
>>  shell=True, \
>>  cwd=os.getcwd(), \
>>  env=os.environ, \
>>  stdin=StdinCatcher() # any ideas here?
>>  )
> How about with a file-like object? I haven't tested this with subprocess
> so you might want to read the manual on files if it doesn't work[1].
> 
>   import sys 
>   class ErrorFile(object):
>   def _error(self, *args, **kwargs):
>   raise AssertionError("Illegal Access")
> 
>   def _noop(self, *args, **kwargs):
>   pass
> 
>   close = flush = seek = tell = _noop
>   next = read = readline = readlines = xreadlines = tuncate = 
> _error
>   truncate = write = writelines = _error
> 
>   sys.stdin = ErrorFile()
>   print raw_input("? ")

I was already trying to do that sort of thing. While it works in your 
example code, for some reason it doesn't work in the subprocess. The 
first problem is that ErrorFile needs a fileno() methode (otherwise I 
get AttributeError: 'ErrorFile' object has no attribute 'fileno'). So, 
when I add
 def fileno(self):
 return 0
to ErrorFile, it runs, but it still doesn't work. The exception is never 
raised.

My specific example was running pdflatex on a file test.tex which looks 
like this:

 \documentclass[a4paper,10pt]{article}
 \usepackage{bogus}
 \begin{document}
   test
 \end{document}

When compiled, this should fail because of a missing 'bogus' package. 
The compiler will prompt for a replacement on STDIN, which I want to 
catch with an exception.

So, when I run my python script

 #!/usr/bin/python
 import subprocess
 import os
 import sys
 class ErrorFile(object):
 def _error(self, *args, **kwargs):
 raise AssertionError("Illegal Access")
 def _noop(self, *args, **kwargs):
 pass
 def fileno(self):
 return 0
 close = flush = seek = tell = _noop
 next = read = readline = readlines \
  = xreadlines = tuncate = _error
 truncate = write = writelines = _error
 latexprocess = subprocess.Popen( \
 'pdflatex' + " " \
  + 'test' + " 2>&1", \
 shell=True, \
 cwd=os.getcwd(), \
 env=os.environ, \
 stdin=ErrorFile()
 )

the  compiler notices that it doesn't get any input:
 Enter file name:
 ! Emergency stop.
 
but no exception is raised, and for some reason I have to press Enter to 
finish.

Michael


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


Re: Making string-formatting smarter by handling generators?

2008-02-27 Thread Gabriel Genellina
En Wed, 27 Feb 2008 14:23:49 -0200, Tim Chase  
<[EMAIL PROTECTED]> escribi�:

> Is there an easy way to make string-formatting smart enough to
> gracefully handle iterators/generators?  E.g.
>
>transform = lambda s: s.upper()
>pair = ('hello', 'world')
>print "%s, %s" % pair # works
>print "%s, %s" % map(transform, pair) # fails
>
> with a """
> TypeError:  not enough arguments for format string
> """

Note that your problem has nothing to do with map itself. String  
interpolation using % requires either many individual arguments, or a  
single *tuple* argument. A list is printed as itself.

py> "%s, %s" % ['hello', 'world']
Traceback (most recent call last):
   File "", line 1, in 
TypeError: not enough arguments for format string
py> "%s" % ['hello', 'world']
"['hello', 'world']"

So the answer is always use tuple(...) as others pointed.

-- 
Gabriel Genellina

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

Re: Official IRC channel for Python?

2008-02-27 Thread Guilherme Polo
27 Feb 2008 11:34:54 -0800, Paul Rubin <"http://phr.cx"@nospam.invalid>:
> "Guilherme Polo" <[EMAIL PROTECTED]> writes:
>  > >  I can join #perl, #php, #ruby, #mysql, #postgres without registration.
>  > >  What advantage does it have? and the advantage really worth?
>  >
>
> > The direct benefit is a probability of having less spam, and things
>  > like that.
>
>
> I don't remember ever seeing irc spam on freenode.  I see it once in a
>  while on undernet.  This is a non-problem.

I'm not just guessing, I know it happens and saw it happenning (even
on python that requires registration).

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


-- 
-- Guilherme H. Polo Goncalves
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Raising exception on STDIN read

2008-02-27 Thread Gabriel Genellina
En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark <[EMAIL PROTECTED]>  
escribi�:

> On 2008-02-27, Michael Goerz <[EMAIL PROTECTED]> wrote:
>> Hi,
>>
>> I would like to raise an exception any time a subprocess tries to read
>> from STDIN:
>>
>> latexprocess = subprocess.Popen( \
>>  'pdflatex' + " " \
>>   + 'test' + " 2>&1", \
>>  shell=True, \
>>  cwd=os.getcwd(), \
>>  env=os.environ, \
>>  stdin=StdinCatcher() # any ideas here?
>>  )
>>
>> An exception should be raised whenever the pdflatex process
>> reads from STDIN... and I have no idea how to do it. Any suggestions?

> How about with a file-like object? I haven't tested this with subprocess
> so you might want to read the manual on files if it doesn't work[1].

Won't work for an external process, as pdflatex (and the OS) knows nothing  
about Python objects. The arguments to subprocess.Popen must be actual  
files having real OS file descriptors.

Try with stdin=open("/dev/full") or stdin=open("/dev/null")

-- 
Gabriel Genellina

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

Re: Backup Script over ssh

2008-02-27 Thread Gabriel Genellina
En Wed, 27 Feb 2008 13:32:07 -0200, Christian Kortenhorst  
<[EMAIL PROTECTED]> escribi�:

> But there is no rsync for windows without using cygwin

That's no big deal; rsync doesn't require tons of libraries, just  
cygpopt-0.dll and cygwin1.dll. See this page:  
http://www.brentnorris.net/rsyncntdoc.html
If you prefer a nice GUI around it (mmm... not so nice actually :) )  
http://www.aboutmyip.com/AboutMyXApp/DeltaCopy.jsp

-- 
Gabriel Genellina

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

Re: Making string-formatting smarter by handling generators?

2008-02-27 Thread Tim Chase
>> Is there an easy way to make string-formatting smart enough to
>> gracefully handle iterators/generators?  E.g.
>>
>>transform = lambda s: s.upper()
>>pair = ('hello', 'world')
>>print "%s, %s" % pair # works
>>print "%s, %s" % map(transform, pair) # fails
>>
>> with a """
>> TypeError:  not enough arguments for format string
>> """
> 
> Note that your problem has nothing to do with map itself. String  
> interpolation using % requires either many individual arguments, or a  
> single *tuple* argument. A list is printed as itself.
> 
> py> "%s, %s" % ['hello', 'world']
> Traceback (most recent call last):
>File "", line 1, in 

I hadn't ever encountered this, as I've always used tuples 
because that's what all the example code used.  I thought it had 
to do with indexability/iteration, rather than tuple'ness. 
Apparently, my false assumption.  People apparently use tuples 
because that's the requirement, not just because it reads well or 
is better/faster/smarter than list notation.

:)

> TypeError: not enough arguments for format string
> py> "%s" % ['hello', 'world']
> "['hello', 'world']"
> 
> So the answer is always use tuple(...) as others pointed.

I'll adjust my thinking on the matter, and mentally deprecate 
map() as well.

Thanks to all who responded.

-tkc



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


RE: first time use of swig, python and c++ .. it's a mess ... please advice

2008-02-27 Thread Bronner, Gregory
The operator= stuff is usually innocuous.
The compiler died because it couldn't find 'vector', which is reasonable, since 
it thought it was compiling a C file.

Probably because you swigged the file without the magic "-c++" option -- I'm 
not sure how distutils passes arguments to swig, but if you do it from the 
command line, you'll do something like swig -c++ -python -I 
 and it will generate a .cpp  file and a .py file, which will (hopefully) 
compile.

I'd focus on doing it manually, then getting distutils to work properly.



 

-Original Message-
From: Hyuga [mailto:[EMAIL PROTECTED] 
Sent: Wednesday, February 27, 2008 10:01 AM
To: python-list@python.org
Subject: Re: first time use of swig, python and c++ .. it's a mess ... please 
advice

On Feb 26, 3:38 pm, Eric von Horst <[EMAIL PROTECTED]> wrote:
> Hi,
>
> we have a third-party product that has a C++ api on HP-UX.
>
> I would like be able to use the API in Python (as I remember Python is 
> good at doing this).
>
> I have no experience with this so I Googled and tried to find some 
> info on what I had to do.
>
> So, I installed Python 2.4.4 and Swig 1.3.33
>
> The header file to the library is '/opt/OV/include/opcsvcapi.h'.
>
> I created a SWIG file with the following content:
> "
> %module opcsvcapi
>  %{
>  /* Includes the header in the wrapper code */
>  #include "/opt/OV/include/opcsvcapi.h"
>  %}
>
>  /* Parse the header file to generate wrappers */
>  %include "/opt/OV/include/opcsvcapi.h"
> "
> Then I ran the cmd:
> # swig -c++ -python opcsvcapi.i
> with output:
> "
> /opt/OV/include/opcsvcapi.h:41: Warning(362): operator= ignored
> /opt/OV/include/opcsvcapi.h:46: Warning(503): Can't wrap 'operator 
> Type' unless renamed to a valid identifier.
> "
>
> The result are two files:
> opcsvcapi.py
> opcsvcapi_wrap.cxx
>
> I created a 'setup.py' file with the following content:
> "
> import distutils
> from distutils.core import setup, Extension
>
> setup(name = "opcsvcapi",
>       version = "1.0",
>       ext_modules = [Extension("_opcsvcapi",
> ["opcsvcapi.i","opcsvcapi.cxx"])])
> "
>
> Then I run: python setup.py build
>
> This results in an extra file:
> opcsvcapi_wrap.c and a 'build' directory
>
> and the following errors:
> "
> running build
> running build_ext
> building '_opcsvcapi' extension
> swigging opcsvcapi.i to opcsvcapi_wrap.c swig -python -o 
> opcsvcapi_wrap.c opcsvcapi.i creating build creating 
> build/temp.hp-ux-B.11.11-9000-800-2.4
> gcc -pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict- 
> prototypes -fPIC -I/usr/local/include/python2.4 -c opcsvcapi_wrap.c -o 
> build/temp.hp-ux-B.11.11-9000-800-2.4/opcsvcapi_wrap.o
> In file included from /usr/local/include/python2.4/Python.h:8,
>                  from opcsvcapi_wrap.c:118:
> /usr/local/include/python2.4/pyconfig.h:851:1: warning:
> "_POSIX_C_SOURCE" redefined
> :1:1: warning: this is the location of the previous 
> definition In file included from opcsvcapi_wrap.c:2490:
> /opt/OV/include/opcsvcapi.h:12:18: error: vector: No such file or 
> directory In file included from opcsvcapi_wrap.c:2490:
> /opt/OV/include/opcsvcapi.h:15: error: expected '=', ',', ';', 'asm'
> or '__attribute__' before 'SvcAPI'
> opcsvcapi_wrap.c: In function 'Swig_var_SvcAPI_set':
> opcsvcapi_wrap.c:2505: error: 'SvcAPI' undeclared (first use in this
> function)
> opcsvcapi_wrap.c:2505: error: (Each undeclared identifier is reported 
> only once
> opcsvcapi_wrap.c:2505: error: for each function it appears in.)
> opcsvcapi_wrap.c:2505: error: 'namespace' undeclared (first use in 
> this function)
> opcsvcapi_wrap.c:2505: error: expected expression before ')' token
> opcsvcapi_wrap.c: In function 'init_opcsvcapi':
> opcsvcapi_wrap.c:3064: error: 'Swig_var_SvcAPI_get' undeclared (first 
> use in this function)
> error: command 'gcc' failed with exit status 1 "
>
> and that's it.
>
> Any idea what I am doing wrong?
>
> Any help much appreciated
>
> Kris

Well, the errors you got from the compiler are just confusing to me, but I 
suspect it goes back to the warning you got from SWIG.  Some class in there is 
overriding the = operator, but since that can't be done in Python, you need to 
give it some special instructions on how to handle that.

For example, if you have Foo::operator=, in your SWIG header include a line 
like:
%rename(assign) Foo::operator=

Then in the Python module, the Foo class will have an assign method.

Hyuga

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

This message is intended only for the personal and confidential use of the 
designated recipient(s) named above.  If you are not the intended recipient of 
this message you are hereby notified that any review, dissemination, 
distribution or copying of this message is strictly prohibited.  This 
communication is for information purposes only and should not be regarded as an 
offer to sell or as a solicitation of an offer to buy any financial product, an 
official co

Re: Article of interest: Python pros/cons for the enterprise

2008-02-27 Thread Aahz
In article <[EMAIL PROTECTED]>,
Carl Banks  <[EMAIL PROTECTED]> wrote:
>On Feb 24, 7:03 pm, [EMAIL PROTECTED] (Aahz) wrote:
>> In article <[EMAIL PROTECTED]>,
>> Jeff Schwab  <[EMAIL PROTECTED]> wrote:
>>>
>>>(3) Garbage collection is at least as desirable a language feature as
>>>deterministic destruction.
>>
>> Enh.  There probably are some people who claim that, but I can't think
>> of any off-hand.
>
>I am most certainly claiming it; in fact I'm claiming that GC far more
>desirable, because the cost of deterministic destruction is too high.

I'm trimming the rest of your post because I don't have time to argue
with you, but I want to point out that you're making the same mistake
that Jeff is: garbage collection and deterministic destruction are not
the only techniques for managing memory and resources.  In particular,
CPython primarily relies on reference counting, which has similarities
with *both* GC and deterministic destruction.

Now you know why I said that I don't know anybody who makes Jeff's
claim.  ;-)
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

"All problems in computer science can be solved by another level of 
indirection."  --Butler Lampson
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter: Missing the last piece of the puzzle

2008-02-27 Thread Russell E. Owen
In article 
<[EMAIL PROTECTED]>,
 [EMAIL PROTECTED] wrote:

> Simon Forman wrote:
> > yes! check out 
> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464635
> >
> > HTH,
> > ~Simon
> 
> Thanks, Simon. Looks like that will do it.
> 
> Actually, it looks like that will overdo it. I'll be setting File/Save
> to enabled after every keystroke. Ideally, I'd like to set my statuses
> when the user clicks the File option or types Alt-F. This makes me
> wonder if there's a "mixin" that could find this event. Hmmm.

Set an internal state variables "isChanged" based on the Text callback 
and only modify the menu if the variable is set.

It's trickier to detect "significant" changes vs insigificant ones. 
Personally I would not bother to go that far.

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


Re: macro in python

2008-02-27 Thread Terry Reedy

"Guilherme Polo" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| 2008/2/27, bharath venkatesh <[EMAIL PROTECTED]>:

| > how to create macro in python for set of instruction that is done
| > frequently but too less in number to ignore the overhead of function 
call

You can't in Python.  Use an external macro program or cut/repeated paste 
in an editor.

| There is lambda, not exactly a macro.

Not at all a macro.  Purely an abbreviation for def ...

| But every program uses functions why cant yours ?

Yes, function call overhead is seldom the major slowdown except possibly in 
inner loops, where code can be written inline just once.

tjr



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


Re: Raising exception on STDIN read

2008-02-27 Thread Michael Goerz
Gabriel Genellina wrote, on 02/27/2008 03:26 PM:
> En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark <[EMAIL PROTECTED]> 
> escribi�:
> 
>> On 2008-02-27, Michael Goerz <[EMAIL PROTECTED]> wrote:
>>> Hi,
>>>
>>> I would like to raise an exception any time a subprocess tries to read
>>> from STDIN:
>>>
>>> latexprocess = subprocess.Popen( \
>>>  'pdflatex' + " " \
>>>   + 'test' + " 2>&1", \
>>>  shell=True, \
>>>  cwd=os.getcwd(), \
>>>  env=os.environ, \
>>>  stdin=StdinCatcher() # any ideas here?
>>>  )
>>>
>>> An exception should be raised whenever the pdflatex process
>>> reads from STDIN... and I have no idea how to do it. Any suggestions?
> 
>> How about with a file-like object? I haven't tested this with subprocess
>> so you might want to read the manual on files if it doesn't work[1].
> 
> Won't work for an external process, as pdflatex (and the OS) knows 
> nothing about Python objects. The arguments to subprocess.Popen must be 
> actual files having real OS file descriptors.
> 
> Try with stdin=open("/dev/full") or stdin=open("/dev/null")
using /dev/null works in my specific case (in my posted minimal example 
I still have to press Enter, but in the real program it causes pdflatex 
to fail, like I want it to). However, the solution is limited do Linux, 
as on Windows there's no /dev/null. Is there a platform independent 
solution?


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

Re: Making string-formatting smarter by handling generators?

2008-02-27 Thread Arnaud Delobelle
On Feb 27, 5:25 pm, "D'Arcy J.M. Cain" <[EMAIL PROTECTED]> wrote:
> On Wed, 27 Feb 2008 10:23:49 -0600
>
> Tim Chase <[EMAIL PROTECTED]> wrote:
>
> >    "%s=%s&%s=%s" % map(urllib.quote, params)
>
> Isn't map() deprecated?  The above can be done with;
>
>     "%s=%s&%s=%s" % tuple([urllib.quote(x) for x in params])

I don't think that map() is deprecated.  In python 3.0 it is still
present, only it returns an iterator instead of a list.

In this case

map(urllib.quote, params)

looks for urlib.quote exactly once altogether.  Whereas

[urllib.quote(x) for x in params]

looks for urlib.quote once for every element in params.  (Of course in
the example given params only has 4 elements so it doesn't matter).

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


Re: threading/Queue: join() and task_done() not working? (deadlock)

2008-02-27 Thread 7stud

Gal Aviel wrote:
> Hello All,
>
> I'm seeing strange behavior where one thread waits on a queue using join() and
> the later (or so I think, according to order of the printing in STDOUT) 
> another
> thread calls task_done() on the very same queue,

What is task_done()?  The python docs don't list any such function.
-- 
http://mail.python.org/mailman/listinfo/python-list


anydbm safe for simultaneous writes?

2008-02-27 Thread chris
I need simple data persistence for a cgi application that will be used
potentially by multiple clients simultaneously.  So I need something
that can handle locking among writes.  Sqlite probably does this, but
I am using Python 2.4.4, which does not include sqlite.  The dbm-style
modules would probably be fine, but I have no idea if they are "write
safe" (I have no experience with the underlying unix stuff).  Any tips
appreciated.

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


Re: Raising exception on STDIN read

2008-02-27 Thread Grant Edwards
On 2008-02-27, Michael Goerz <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I would like to raise an exception any time a subprocess tries to read 
> from STDIN:
>
> latexprocess = subprocess.Popen( \
>  'pdflatex' + " " \
>   + 'test' + " 2>&1", \
>  shell=True, \
>  cwd=os.getcwd(), \
>  env=os.environ, \
>  stdin=StdinCatcher() # any ideas here?
>  )
>
> An exception should be raised whenever the pdflatex process
> reads from STDIN... and I have no idea how to do it. Any suggestions?

If I were you, I'd just run LaTeX in batch mode.  That's what I
always used to do when automating the running of LaTeX using a
shell script or makefile.  IIRC, you do something like this:

  ret = os.system("latex \\batchmode\\input %s" % filename)

The return status will be zero for success and non-zero if
there were any errors.

-- 
Grant Edwards   grante Yow! Remember, in 2039,
  at   MOUSSE & PASTA will
   visi.combe available ONLY by
   prescription!!
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >