Direct Client-Web Designer/Web Architect-Bay Area,CA

2007-07-19 Thread Kan
Hello,

We have requirement for Web Designer/Web Architect in bay area CA. The
person needs to have experience in building Commerce Site where Actual
Shopping has been done. If your skills and experience matches with the
same, send me your resume asap with contact # and rate to
'[EMAIL PROTECTED]'.

Title = Contract Information Architect/User Experience Designer
6 month contract
Location: Redwood city

Requirements:

The person needs to have experience in building Commerce Site where
Actual Shopping has been done
Strong knowledge of site design; mastery in principles of Web design
(HCI, HTML, CSS)
Strong knowledge of user interface design processes and methodology
Working knowledge of User Centered Design Principles and Practices
Knowledge of architecture-related software (Illustrator, Visio,
Photoshop, SQL Server, MS Office, Acrobat, Dreamweaver)
Strong Preference given to those with::
Experience with digital media commerce sites

Kan
BTech Inc
Recruiter
510-438-6834
[EMAIL PROTECTED]
www.tbiinc.org

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


Direct Client -Sr.Software Engineer Python-San Jose CA -Locals only

2007-07-19 Thread Kan
Hello,


We have requirement for Sr.Software Engineer in San Jose CA with very
strong experinece in PYTHON AND LINUX .  If your skills and experience
matches with the same, send me your resume asap with contact # and
rate to '[EMAIL PROTECTED]'. Locals only pls apply

TECHNICAL SKILLS REQUIREMENTS:

* Knowledge of Internet protocols such as TCP/IP, HTTP, FTP, POP3,
IMAP, SMTP, SNMP, etc. is a huge plus
*Very Strong Knowledge of Python, Java, C++ or other object-oriented
language is a plus



Kan
BTech Inc
Recruiter
510-438-6834
[EMAIL PROTECTED]
www.tbiinc.org

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


class C: vs class C(object):

2007-07-19 Thread nvictor
Hi,

I'm not an experienced developer, and I came across this statement by
reading a code. I search for explanation, but can't find anything
meaningful. I read the entire document written by python's creator
about the features of version 2.2 The one named unifying types and
classes. But This document only blew my head away.

I ended here and think somebody can explain me more about this. The
only thing I have noticed is that when you do dir(C) on a classic
class you get a bunch of attributes; and when you do the same thing on
a class defined using class C(object), you get less attributes.

Thanks for all replies.

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


Re: class C: vs class C(object):

2007-07-19 Thread Bruno Desthuilliers
nvictor a écrit :
> Hi,
> 
> I'm not an experienced developer, and I came across this statement by
> reading a code. I search for explanation, but can't find anything
> meaningful. I read the entire document written by python's creator
> about the features of version 2.2 The one named unifying types and
> classes. But This document only blew my head away.
 >
> I ended here and think somebody can explain me more about this. 

To make a long story short: Python 2.2 introduced a new object model 
which is more coherent and more powerful than the original one. The old 
one was kept so far for compatibility reasons, but there's absolutely no 
reason to use it no more since "new-style" classes can do anything 
"Classic" classes did and much more. IOW, don't even bother with 
old-style classes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class C: vs class C(object):

2007-07-19 Thread Lutz Horn
Hi,

On Thu, 19 Jul 2007 09:40:24 +0200, Bruno Desthuilliers  
<[EMAIL PROTECTED]> wrote:
> there's absolutely no reason to use it no more since "new-style" classes  
> can do anything "Classic" classes did and much more. IOW, don't even  
> bother with old-style classes.

Just for the records: the new and preferred style is

class C(object):
 ...

Regards
Lutz
-- 
Using Opera's revolutionary e-mail client: http://www.opera.com/mail/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython and threads

2007-07-19 Thread Josiah Carlson
Benjamin wrote:
> I'm writing a search engine in Python with wxPython as the GUI. I have
> the actual searching preformed on a different thread from Gui thread.
> It sends it's results through a Queue to the results ListCtrl which
> adds a new item. This works fine or small searches, but when the
> results number in the hundreds, the GUI is frozen for the duration of
> the search. I suspect that so many search results are coming in that
> the GUI thread is too busy updating lists to respond to events. I've
> tried buffer the results so there's 20 results before they're sent to
> the GUI thread and buffer them so the results are sent every .1
> seconds. Nothing helps. Any advice would be great.

Sending results one at a time to the GUI is going to be slow for any 
reasonably fast search engine (I've got a pure Python engine that does 
50k results/second without breaking a sweat).  Don't do that.  Instead, 
have your search thread create a list, which it fills with items for 
some amount of time, *then* sends it off to the GUI thread (creating a 
new list that it then fills, etc.).  While you *could* use a Queue, it 
is overkill for what you want to do (queues are really only useful when 
there is actual contention for a resource and you want to block when a 
resource is not available).  Create a deque, and use append() and popleft().

To signal to the GUI thread that there are results available in your 
deque, you can use wx.CallAfter(), which will be run in the GUI thread 
when the event comes up.  Alternatively, you can use a combination of 
wx.PostEvent() and wx.lib.newevent (see: 
http://wiki.wxpython.org/CustomEventClasses ) to pass the results, or 
even just signal that 'more results are available in the deque'.  I 
would suggest merely signaling that more results are in the deque (using 
wx.PostEvent() or wx.CallAfter()), as there are no guarantees on the 
order of execution when events are posted (I have found that the event 
queue sometimes behaves like a stack).

I would also suggest never polling any queue from the GUI thread.  It's 
wasteful.  Just have it respond to an event (either explicitly from 
wx.PostEvent() or implicitly with wx.CallAfter()).


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


Re: class C: vs class C(object):

2007-07-19 Thread Steven D'Aprano
On Thu, 19 Jul 2007 07:31:06 +, nvictor wrote:

> Hi,
> 
> I'm not an experienced developer, and I came across this statement by
> reading a code. I search for explanation, but can't find anything
> meaningful. I read the entire document written by python's creator
> about the features of version 2.2 The one named unifying types and
> classes. But This document only blew my head away.
> 
> I ended here and think somebody can explain me more about this. The
> only thing I have noticed is that when you do dir(C) on a classic
> class you get a bunch of attributes; and when you do the same thing on
> a class defined using class C(object), you get less attributes.
> 
> Thanks for all replies.


The short answer is, unless you are writing code that has to be backwards
compatible with very old versions of Python, always use new style classes
by inheriting from object instead of old-style classes.

It isn't wrong to use the old style, but it is deprecated, and they will
eventually go away. Old style classes are the way classes used to be, back
in Ancient Days. You couldn't inherit from built-in types like str or int,
which used a different mechanism under the hood.

Certain very useful features simply will not work correctly with old-style
classes, like properties and slots. Also, multiple inheritance works
better with new-style classes: there is a subtle design flaw in the way it
works for old-style classes, which can lead to bugs.

For the technical answer about the difference, go back and read the
document about unifying classes and types.


-- 
Steven.

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


Re: Interprocess communication woes

2007-07-19 Thread Nick Craig-Wood
Murali <[EMAIL PROTECTED]> wrote:
>  After some investigation, I found out that this problem had nothing to
>  do with my GUI app not getting refreshed and I was able to reproduce
>  this problem with normal python scripts. Here is one such script
> 
>  #File test.py
>  from subprocess import Popen
>  from subprocess import PIPE
>  import sys
>  if __name__ == '__main__':
>   prog = sys.argv[1]
>   proc = Popen(prog, shell = True, stdout = PIPE, bufsize = 0)
>   out = proc.stdout
>   while proc.poll() is None:
> print out.readline()
> 
>  Run this program as follows
>  $ test.py "ping -c 10 www.google.com"
> 
>  Now, you would see the responses as if you just launched ping on the
>  command line. Now, lets look at another program. Here is a simple C++
>  program that prints numbers 1 to 10 at the passage of every second
>  (sort of a stopwatch)
> 
>  #include 
>  #include 
>  #include 
>  main ( )
>  {
>   timeval t1, t2;
>   gettimeofday(&t1, NULL);
>   int prev = -1;
>   int cur = 0;
>   while (true)
>   {
> gettimeofday(&t2,NULL);
> if(t2.tv_sec - t1.tv_sec > 10)
>   break;
> else
> {
>   cur = t2.tv_sec-t1.tv_sec;
>   if (cur != prev)
>   {
> printf("%d\r\n",cur);
> prev = cur;
>   }
> }
>   }
>  }
> 
>  if you would build this program and call it lets say timer ($ g++ -o
>  timer timer.cpp)  and run it with our python script like this
> 
>  $python test.py "./timer"
> 
>  you would see that every time you run the program your results vary
>  and on top of this the stdout of the timer program gets displayed all
>  at once presumably when the timer program has completed execution.
> 
>  Why this discrepancy between the ping and timer programs? Is my
>  test.py script correct? Is there a better or a preferred method for
>  doing interprocess communication in Python.

Buffering is your problem.

If you add a fflush(stdout); after the printf(...); you'll find the
c++ program works as you expect.

It is just a fact of life of the C stdio system.  If it is connected
to a terminal then it will turn off buffering.  If it is connected
anything else (eg a pipe via subprocess) then it will buffer stuff as
you've seen.

So you can

a) modify the c++ prog to add fflush() in or use setvbuf()
b) use the pexpect module - http://pexpect.sourceforge.net/
c) use the pty module (unix only)

The pexpect module will connect to the subprogram with pseudo-ttys,
fooling the program, and the C library, into thinking that it is
speaking to a terminal and turn off buffering.  Pexpect doesn't work
on windows.

The fact that ping works is because it uses fflush() - you can see
this if you "ltrace" it.

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


New Python opportunity in Boston

2007-07-19 Thread Sandy Kontos

Hello,

 

My name is Sandy Kontos and I have a Python/Jython role here in Boston for 3-6 
months.  

 

Should you have any interest in the Boston area please give either myself 
and/or Mo Bitahi a call at 781 449 0600

 

Thank you 

 

Sandy 



 

 

Sandy Kontos

Overture Partners, LLC

75 Second Avenue

Suite 710

Needham, MA 02494

www.overturepartners.com

[EMAIL PROTECTED]

781 449 0600


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

Re: Real-time Update

2007-07-19 Thread Hendrik van Rooyen
"ReTrY" <[EMAIL PROTECTED]> wrote:

> I'm writing a program with Tkinter GUI, When the program is running it
> need to be updated every five seconds (data comes from internet). How
> should I do that ? How to make a function in main loop ?

Short answer:

use the after method to set up a periodic scan of a queue.

In another thread, look for the new stuff, and put it on the queue when found.

there is a recipe for this sort of thing, but I keep losing links.

- Hendrik

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


Re: Interpreting os.lstat()

2007-07-19 Thread Hrvoje Niksic
Adrian Petrescu <[EMAIL PROTECTED]> writes:

> I checked the online Python documentation at 
> http://python.org/doc/1.5.2/lib/module-stat.html
> but it just says to "consult the documentation for your system.".

The page you're looking for is at
http://www.python.org/doc/current/lib/os-file-dir.html .  For lstat it
says "Like stat(), but do not follow symbolic links."  For stat it
says:

Perform a stat() system call on the given path. The return value
is an object whose attributes correspond to the members of the
stat structure, namely: st_mode (protection bits), st_ino (inode
number), st_dev (device), st_nlink (number of hard links), st_uid
(user ID of owner), st_gid (group ID of owner), st_size (size of
file, in bytes), st_atime (time of most recent access), st_mtime
(time of most recent content modification), st_ctime (platform
dependent; time of most recent metadata change on Unix, or the
time of creation on Windows)
[...]
For backward compatibility, the return value of stat() is also
accessible as a tuple of at least 10 integers giving the most
important (and portable) members of the stat structure, in the
order st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size,
st_atime, st_mtime, st_ctime. More items may be added at the end
by some implementations. The standard module stat defines
functions and constants that are useful for extracting information
from a stat structure. (On Windows, some items are filled with
dummy values.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Log Memory Usage

2007-07-19 Thread Robert Rawlins - Think Blue
Hello Guys,

 

I have an embedded application with a suspected memory leak which I'm trying
to confirm. You see, the application seems to crash unexpectedly and when
looking at the resource consumption after the crash system memory has crept
up to nearly 100%.

 

However this takes quite a long time to occur, so sitting and watching the
application run isn't a very effective way of doing it, so I'm looking for
the best way to log the system memory every minute or two.

 

I have a scheduled event which occurs every minute, i just need a code
solution to give me the systems current memory consumptions details, is
there perhaps something in the os module?

 

Thanks for any suggestions guys,

 

Rob

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

Re: Log Memory Usage

2007-07-19 Thread Will Maier
On Thu, Jul 19, 2007 at 09:52:36AM +0100, Robert Rawlins - Think Blue wrote:
> I have a scheduled event which occurs every minute, i just need a
> code solution to give me the systems current memory consumptions
> details, is there perhaps something in the os module?

I don't know of anything in the standard library that does this sort
of thing. Instead, you'll probably need to rely on your system's
tools. sysstat is available on Linux and provides the sar(1) command
for examining logs of various system attributes. The tool to use
depends on the system you're running.

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Log Memory Usage

2007-07-19 Thread Will Maier
On Thu, Jul 19, 2007 at 04:35:56AM -0500, Will Maier wrote:
> On Thu, Jul 19, 2007 at 09:52:36AM +0100, Robert Rawlins - Think Blue wrote:
> > I have a scheduled event which occurs every minute, i just need a
> > code solution to give me the systems current memory consumptions
> > details, is there perhaps something in the os module?
> 
> I don't know of anything in the standard library that does this sort
> of thing. Instead, you'll probably need to rely on your system's
> tools. sysstat is available on Linux and provides the sar(1) command
> for examining logs of various system attributes. The tool to use
> depends on the system you're running.

The other obvious approach would be to profile[0] your Python
application.

[0] http://docs.python.org/lib/profile.html

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython and threads

2007-07-19 Thread Iain King
On Jul 18, 3:41 am, Benjamin <[EMAIL PROTECTED]> wrote:
> I'm writing a search engine in Python with wxPython as the GUI. I have
> the actual searching preformed on a different thread from Gui thread.
> It sends it's results through a Queue to the results ListCtrl which
> adds a new item. This works fine or small searches, but when the
> results number in the hundreds, the GUI is frozen for the duration of
> the search. I suspect that so many search results are coming in that
> the GUI thread is too busy updating lists to respond to events. I've
> tried buffer the results so there's 20 results before they're sent to
> the GUI thread and buffer them so the results are sent every .1
> seconds. Nothing helps. Any advice would be great.

I do something similar - populating a bunch of comboboxes from data
takes a long time so I run the generator for the comboboxes in another
thread (and let the user use some textboxes in the mean time).  A
rough edit toward what you might be doing:

import thread

class Processor(object):
def __init__(self):
self.lock = thread.allocate_lock()
self.alive = False
self.keepalive = False

def start(self):
if not self.alive:
self.alive = True
self.keepalive = True
thread.start_new_thread(self.Process, (None,))

def stop(self):
self.keepalive = False

def process(self, dummy=None):
self.alive = False


class SearchProcessor(Processor):
def __init__(self, entries, lookfor, report):
Processor.__init__(self)
self.entries = entries
self.lookfor = lookfor
self.report = report

def process(self, dummy=None):
for entry in self.entries:
if lookfor in entry:
self.report(entry)
if not self.keepalive:
break
self.report(None)
self.alive = False


results = []

def storeResult(result):
if result != None:
results.append(result)
else:
notifySomeMethod(results)

sp = SearchProcessor(someListOfData, someTextToSearchFor, storeResult)
sp.start()

when the search is done it will call notifySomeMethod with the
results.  Meanwhile you could, for example, bind sp.stop() to a cancel
button to stop the thread, or add a counter to the storeResult
function and set a status bar to the total found, or whatever else you
want to do.

Iain

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


Re: Open HTML file in IE

2007-07-19 Thread imageguy
On Jul 18, 3:20 am, gravey <[EMAIL PROTECTED]> wrote:
> Hello.
>
> Apologies if this is a basic question, but I want to open a HTML
> file from my local drive (is generated by another Python script)
> in Internet Explorer. I've had a look at the webbrowser module and
> this doesn't seem to be what I need. Any help much appreciated.

check out the os module.
os.startfile("your_htmlfile.html") should do it.

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


Re: wxPython and threads

2007-07-19 Thread Nick Craig-Wood
Josiah Carlson <[EMAIL PROTECTED]> wrote:
>  Sending results one at a time to the GUI is going to be slow for any 
>  reasonably fast search engine (I've got a pure Python engine that does 
>  50k results/second without breaking a sweat).  Don't do that.  Instead, 
>  have your search thread create a list, which it fills with items for 
>  some amount of time, *then* sends it off to the GUI thread (creating a 
>  new list that it then fills, etc.).  While you *could* use a Queue, it 
>  is overkill for what you want to do (queues are really only useful when 
>  there is actual contention for a resource and you want to block when a 
>  resource is not available).

I'd dispute that.  If you are communicating between threads use a
Queue and you will save yourself thread heartache.  Queue has a non
blocking read interface Queue.get_nowait().

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Implementaion of random.shuffle

2007-07-19 Thread Neil Cerutti
On 2007-07-19, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> On Wed, 18 Jul 2007 19:32:35 +, George Sakkis wrote:
>
>> On Jul 16, 10:51 pm, Steven D'Aprano
>> <[EMAIL PROTECTED]> wrote:
>>> On Mon, 16 Jul 2007 16:55:53 +0200, Hrvoje Niksic wrote:
>>> > 2**19937 being a really huge number, it's impossible to exhaust the
>>> > Mersenne twister by running it in sequence.
>>>
>>> "Impossible"?
>>>
>>> Surely this will do it:
>>>
>>> for n in xrange(2**19937 + 1):
>>> random.random()
>>>
>>> Admittedly, if each call to random() took a picosecond, it would still
>>> take 1e5982 centuries to run through the lot. You might want to go make a
>>> coffee or something while you're waiting...
>> 
>> Wow, can you make a coffee in.. 57ms ?
>
> [snip demonstration of xrange raising an exception]
>
> Of course! Can't you?
>
> And if I use a microwave oven, the coffee is made so quickly
> that I actually go backwards in time...

But what happens if you use a microwave oven? ... What the!?!?

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


UDP broadcast over a specific interface

2007-07-19 Thread [EMAIL PROTECTED]
I am trying to send UDP broadcast packets over a specific interface
and I
am having trouble specifying the interface:

host='192.168.28.255'
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('',0))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
socket.inet_aton(host))

socket.error: (49, "Can't assign requested address")

What am I doing wrong? How can I force my broadcast packets to go out
a specific interface?

TIA!
-larry

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


Re: wxPython, searching, and threads

2007-07-19 Thread kyosohma
On Jul 18, 11:38 am, Benjamin <[EMAIL PROTECTED]> wrote:
> Hello! I am writing a search engine with wxPython as the GUI. As the
> search thread returns items, it adds them to a Queue which is picked
> up by the main GUI thread calling itself recursively with
> wx.CallAfter. These are then added to a ListCtrl. This works fine for
> small searches, but with larger and longer searchs the GUI is clogged
> and won't respond. I suspect (I may be wrong) that there are so many
> results being sent to the ListCtrl that the event loop doesn't have
> time to respond to events. I've tried buffering the results before
> sending them to the GIU, but that doesn't help at all. Please advise.

The standard wxPython user's group reply to a question like this is,
check out http://wiki.wxpython.org/LongRunningTasks. I've used a
variation of what's on this page to create a fairly complex installer
than keeps a textctrl updated with its progress. Since the installer
runs for almost an hour, I think this method works great.

Admittedly, you work with threads, which is intimidating to some
degree and if you use WMI, then you'll need to use some special
commands to make it work in a thread.

The wxPython mailing list is here: http://www.wxpython.org/maillist.php

Hope that helps.

Mike

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


Re: UDP broadcast over a specific interface

2007-07-19 Thread Jean-Paul Calderone
On Thu, 19 Jul 2007 12:32:02 -, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> 
wrote:
>I am trying to send UDP broadcast packets over a specific interface
>and I
>am having trouble specifying the interface:
>
>host='192.168.28.255'
>sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
>sock.bind(('',0))
>sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
>sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
>socket.inet_aton(host))
>
>socket.error: (49, "Can't assign requested address")
>
>What am I doing wrong? How can I force my broadcast packets to go out
>a specific interface?

IP_MULTICAST_IF is for multicast UDP, which doesn't have anything to do
with broadcast UDP.

Try just doing this, instead:

host='192.168.28.255'
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host,0))
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)

You shouldn't need to mess with anything beyond that.

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


Re: Posted messages not appearing in this group

2007-07-19 Thread kyosohma
On Jul 18, 5:50 am, Alex Popescu <[EMAIL PROTECTED]>
wrote:
> Sanjay  gmail.com> writes:
>
>
>
> > Hi All,
>
> > I tried posting in this group twice since last week, but the messages
> > did not appear in the forum. Don't know why. Trying this message
> > again...
>
> > Sanjay
>
> Something similar seemed to happen to me too, but when checking with gmane 
> I've
> noticed that all my posts got in (and now I am trying to figure out how can I
> apologize for multiple posts :-) ).
>
> bests,
> ./alex
> --
> .w( the_mindstorm )p.

If you use google groups to post, then it's something to do with
Google. It seems to be having some serious issues this week. And I've
had it not post my posts before even though it ended up on gmane.
Google seems to forward the message, but it does a lousy job updating
itself of late.

Mike

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


Re: How do you debug when a unittest.TestCase fails?

2007-07-19 Thread Emin.shopper Martinian.shopper

After poking around the unittest source code, the best solution I could come
up with was to do


import unittest; unittest.TestCase.run = lambda self,*args,**kw:

unittest.TestCase.debug(self)

before running my tests. That patches things so that I can use pdb.pm() when
a test fails. Still, that seems like an ugly hack and I would think there is
a better solution...

Thanks,
-Emin


On 7/18/07, Emin.shopper Martinian.shopper <[EMAIL PROTECTED]> wrote:


Thanks for the reply, but neither of those work for me. I don't seem to
have the "trial" program installed. Where do you get it?

Also, when I use the try/catch block, I get the following error:

Traceback (most recent call last):
  File "_test.py", line 10, in 
pdb.pm()
  File "c:\python25\lib\pdb.py", line 1148, in pm
post_mortem(sys.last_traceback)
AttributeError: 'module' object has no attribute 'last_traceback'


 On 7/18/07, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
>
> On Wed, 18 Jul 2007 16:40:46 -0400, "Emin.shopper Martinian.shopper" <[EMAIL 
PROTECTED]>
> wrote:
> >Dear Experts,
> >
> >How do you use pdb to debug when a TestCase object from the unittest
> module
> >fails? Basically, I'd like to run my unit tests and invoke pdb.pm when
> >something fails.
> >
> >I tried the following with now success:
> >
> >Imagine that I have a module _test.py that looks like the following:
> >
> >---
> >import unittest
> >class MyTest(unittest.TestCase):
> >def testIt(self):
> >raise Exception('boom')
> >if __name__ == '__main__':
> >unittest.main()
> >---
> >
> >If I do
> import _test; _test.unittest()
> >
> >no tests get run.
> >
> >If I try
> import _test; t = _test.MyTest()
> >
> >I get
> >
> >Traceback (most recent call last):
> >  File "", line 1, in 
> >  File "c:\python25\lib\unittest.py", line 209, in __init__
> >(self.__class__, methodName)
> >ValueError: no such test method in : runTest
> >
> >If I try
> import _test; t = _test.MyTest(methodName='testIt'); t.run()
> >
> >nothing happens.
>
> I use `trial -b ', which automatically enables a bunch of nice
>
> debugging functionality. ;)  However, you can try this, if you're not
> interested in using a highly featureful test runner:
>
>try:
>unittest.main()
>except:
>import pdb
>pdb.pm ()
>
> This will "post-mortem" the exception, a commonly useful debugging
> technique.
>
> Jean-Paul
> --
> http://mail.python.org/mailman/listinfo/python-list
>


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

Re: Real-time Update

2007-07-19 Thread kyosohma
On Jul 18, 3:24 am, ReTrY <[EMAIL PROTECTED]> wrote:
> I'm writing a program with Tkinter GUI, When the program is running it
> need to be updated every five seconds (data comes from internet). How
> should I do that ? How to make a function in main loop ?

I'm pretty sure the book "Programming Python 3rd Ed." by Lutz covers
this stuff in detail. I think it mentions using threads for this sort
of thing. The wxPython wiki has a good example that I think you could
adapt for Tkinter. Just use the threading code and wrap it in your
Tkinter code and I think you'll be good to go. Here's the link:
http://www.wxpython.org/maillist.php

Good luck,

Mike

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


Re: Issue with CSV

2007-07-19 Thread Harry George
Rohan <[EMAIL PROTECTED]> writes:

> Hello,
> I'm working on a script which collects some data and puts into a csv
> file which could be exported to excel.
> so far so good, I'm able to do what I described.
> When I run the script for the second time after a certain period of
> time the results should appear next to the results of the last run,
> I'm unable to make a new column when the script is run after the first
> time.
> Ideally I would like to have an output which looks like this.
> 1/20   1/27
> we.pywe.py
> gh.pygj.py   <- Indicating tht the file has changed
> fg.pyfg.py
>
> Please help me out.
> Thanks
>

We'd need to see code to tell what you are doing wrong.   The solution is 
pretty obvious:   

1. Model the needed structure, which is a 2D matrix of script x date.
Assuming the above output is the nromal case, this can be done with a
list of rows, each of which has a list of entries by date.

2. Write reader code which reads a csv and loads it into this structure.

3. Write writer code which writes this structure out to csv.

4. Write orchestration code to a) read the old csv, b) check the
loaded structure's data against the new data-on-disk to find changed
files, c) update the structure appropriately, d) write out the
resulting new csv.

-- 
Harry George
PLM Engineering Architecture
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Embedding/Extending Python in/with C++: non-static members?

2007-07-19 Thread [EMAIL PROTECTED]
On Jul 16, 9:45 am, dmoore <[EMAIL PROTECTED]> wrote:
> Hi Folks:
>
> I have a question about the use of static members in Python/C
> extensions. Take the simple example from the "Extending and Embedding
> the Python Interpreter" docs:
>
> A simple module method:
>
> static PyObject *
> spam_system(PyObject *self, PyObject *args)
> {
>  ...
>
> }
>
> listed in a method table:
>
> static PyMethodDef SpamMethods[] = {
> ...
> {"system",  spam_system, METH_VARARGS,
>  "Execute a shell command."},
> ...
> {NULL, NULL, 0, NULL}/* Sentinel */
>
> };
>
> that is registered with:
>
> PyMODINIT_FUNC
> initspam(void)
> {
> (void) Py_InitModule("spam", SpamMethods);
>
> }
>
> I have an application that embed multiple interpreters. I want to be
> able to register methods for each interpreter that access C++ state
> data relevant to that particular interpreter. In other words I want to
> be able to register non-static class members in a class like the
> following:
>
> class PythonSpamModuleInstance
> {
> PythonSpamModuleInstance()
> {
> SpamMethods[0]={"system",  spam_system, METH_VARARGS,"Execute
> a shell command."};
> SpamMethods[1]={NULL, NULL, 0, NULL};
> PyObject *spammodule=Py_InitModule("spam", SpamMethods); //
> Needs an INCREF call?
> }
> ~PythonSpamModuleInstance()
> {
> PyObject_Del("spam", SpamMethods);
> }
> PyObject *spam_system(PyObject *self, PyObject *args)
> {
>  // accesses non-static data in this class
> }
> PyMethodDef SpamMethods[2];
> PyObject *spammodule;
> // Other data specific to this instance of the module
>
> };
>
> The idea is that each time my app launches an embedded Interpreter it
> will create an accompanying instance of PythonSpamModuleInstance that
> allows the Interpreter to call the registered non-static C++ member
> function spam_system. Calls to that member function will also affect
> state information.
>
> So the questions: will this work? In particular, will the use of non-
> static member functions cause problems? Is there a better way of
> creating extension modules for multiple embedded interpreters? If I am
> forced to use static methods, how do i figure out which interpreter is
> calling them?
test posting.

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


Re: Real-time Update

2007-07-19 Thread kyosohma
On Jul 18, 4:43 pm, [EMAIL PROTECTED] (Aahz) wrote:
> In article <[EMAIL PROTECTED]>,
>
> ReTrY  <[EMAIL PROTECTED]> wrote:
>
> >I'm writing a program with Tkinter GUI, When the program is running it
> >need to be updated every five seconds (data comes from internet). How
> >should I do that ? How to make a function in main loop ?
>
> See the Tkinter example from my threads tutorial on my website.
> --
> Aahz ([EMAIL PROTECTED])   <*>http://www.pythoncraft.com/
>
> I support the RKAB

There's also a good example on the wxPython wiki dealing with threads
that you should be able to adapt to Tkinter.

http://wiki.wxpython.org/LongRunningTasks

Mike

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


Re: How do you debug when a unittest.TestCase fails?

2007-07-19 Thread Jean-Paul Calderone
On Thu, 19 Jul 2007 09:25:50 -0400, "Emin.shopper Martinian.shopper" <[EMAIL 
PROTECTED]> wrote:
>After poking around the unittest source code, the best solution I could come
>up with was to do
import unittest; unittest.TestCase.run = lambda self,*args,**kw:
>unittest.TestCase.debug(self)
>
>before running my tests. That patches things so that I can use pdb.pm() when
>a test fails. Still, that seems like an ugly hack and I would think there is
>a better solution...

trial:

  http://twistedmatrix.com/trac/wiki/TwistedTrial

It's distributed with Twisted:

  http://twistedmatrix.com/trac/wiki/Downloads

I don't use unittest directly very much.  I'm only slightly surprised that
it is doing something which breaks post-morteming.  If you want, you could
probably fix it (probably something related to how it handles exceptions
from test methods) and contribute a patch to Python.

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


Re: Real-time Update

2007-07-19 Thread Alex Martelli
Hendrik van Rooyen <[EMAIL PROTECTED]> wrote:

> "ReTrY" <[EMAIL PROTECTED]> wrote:
> 
> > I'm writing a program with Tkinter GUI, When the program is running it
> > need to be updated every five seconds (data comes from internet). How
> > should I do that ? How to make a function in main loop ?
> 
> Short answer:
> 
> use the after method to set up a periodic scan of a queue.
> 
> In another thread, look for the new stuff, and put it on the queue when found.
> 
> there is a recipe for this sort of thing, but I keep losing links.

 .


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


A way to re-organize a list

2007-07-19 Thread beginner
Hi Everyone,

I have a simple list reconstruction problem, but I don't really know
how to do it.

I have a list that looks like this:

l=[ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A",
"b", 2), ("B", "a", 1), ("B", "b", 1)]

What I want to do is to reorganize it in groups, first by the middle
element of the tuple, and then by the first element. I'd like the
output look like this:

out=[
   [#group by first element "A"
  [("A", "a", 1), ("A", "a", 2), ("A", "a", 3)], #group by
second element "a"
  [ ("A", "b", 1), ("A", "b", 2)], #group by second element
"b"
   ],
   [   #group by first element "B"
  [("B", "a", 1)],
  [("B", "b", 1)]
   ]
]


All the solutions I came up with are difficult to read and even harder
to go back and change, and I just feel are too complicated for such a
simple problem. I am wondering if anyone here has some insight.

If there is a 'functional' way to do this, it would be even greater.


Thanks,
Geoffrey

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


Re: A way to re-organize a list

2007-07-19 Thread Alex Martelli
beginner <[EMAIL PROTECTED]> wrote:

> Hi Everyone,
> 
> I have a simple list reconstruction problem, but I don't really know
> how to do it.
> 
> I have a list that looks like this:
> 
> l=[ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A",
> "b", 2), ("B", "a", 1), ("B", "b", 1)]
> 
> What I want to do is to reorganize it in groups, first by the middle
> element of the tuple, and then by the first element. I'd like the
> output look like this:
> 
> out=[
>[#group by first element "A"
>   [("A", "a", 1), ("A", "a", 2), ("A", "a", 3)], #group by
> second element "a"
>   [ ("A", "b", 1), ("A", "b", 2)], #group by second element
> "b"
>],
>[   #group by first element "B"
>   [("B", "a", 1)],
>   [("B", "b", 1)]
>]
> ]
> 
> 
> All the solutions I came up with are difficult to read and even harder
> to go back and change, and I just feel are too complicated for such a
> simple problem. I am wondering if anyone here has some insight.
> 
> If there is a 'functional' way to do this, it would be even greater.

If it's already sorted as in your example, itertools.groupby may be what
you want.  To pick a key, you can use operator.itemgetter, which builds
functions picking a specified N-th item of a sequence.

Consider...:

>>> l
[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3), ('A', 'b', 1), ('A', 'b',
2), ('B', 'a', 1), ('B', 'b', 1)]
>>> itm=operator.itemgetter
>>> gb=itertools.groupby
>>> list(gb(l, itm(0)))
[('A', ), ('B',
)]

the items in the sequence groupby returns are (key, subsequence) pairs;
you don't care about the key, so here's a first step (grouping by first
item only):

>>> [list(ss) for k, ss in gb(l, itm(0))]
[[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3), ('A', 'b', 1), ('A', 'b',
2)], [('B', 'a', 1), ('B', 'b', 1)]]

However, you want a second level of grouping -- so, instead of the plain
list(ss), you need to apply this concept again:

>>> [[list(sss) for k,sss in gb(ss,itm(1))] for k, ss in gb(l, itm(0))]
[[[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3)], [('A', 'b', 1), ('A',
'b', 2)]], [[('B', 'a', 1)], [('B', 'b', 1)]]]

...and there you are.

May be more readable with a little auxiliary function to capture what I
just called "this concept" with a readable name:

>>> def group(s, i): return [list(ss) for k, ss in gb(s, itm(i))]
... 
>>> [group(ss,1) for ss in group(l,0)]
[[[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3)], [('A', 'b', 1), ('A',
'b', 2)]], [[('B', 'a', 1)], [('B', 'b', 1)]]]

This does one more "list(...)" step, but if your lists aren't huge the
readability may be worth the small slow-down.


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


Re: Interpreting os.lstat()

2007-07-19 Thread Sion Arrowsmith
Adrian Petrescu  <[EMAIL PROTECTED]> wrote:
 print os.stat.__doc__
>stat(path) -> stat result
>
>Perform a stat system call on the given path.
>
>I checked the online Python documentation at 
>http://python.org/doc/1.5.2/lib/module-stat.html

Someone else has already pointed out that this is hopelessly out of
date. Even if you are constrained to using 1.5.2, the current
documentation at least tells you what the elements of the tuple are.

>but it just says to "consult the documentation for your system.". At
>this point I'm guessing that os.lstat is nothing more than a wrapper
>for some Linux system call, so I looked up the results of running
>'stat' on the same file, [ ... ]

(a) Running 'stat' is *not the same* as a system call.

(b) "Consult[ing] the documentation" may be more productive than
running random(ish) programs. You should find

$ man 2 stat

informative.

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

Re: A way to re-organize a list

2007-07-19 Thread Carsten Haese
On Thu, 2007-07-19 at 15:05 +, beginner wrote:
> Hi Everyone,
> 
> I have a simple list reconstruction problem, but I don't really know
> how to do it.
> 
> I have a list that looks like this:
> 
> l=[ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A",
> "b", 2), ("B", "a", 1), ("B", "b", 1)]
> 
> What I want to do is to reorganize it in groups, first by the middle
> element of the tuple, and then by the first element. I'd like the
> output look like this:
> 
> out=[
>[#group by first element "A"
>   [("A", "a", 1), ("A", "a", 2), ("A", "a", 3)], #group by
> second element "a"
>   [ ("A", "b", 1), ("A", "b", 2)], #group by second element
> "b"
>],
>[   #group by first element "B"
>   [("B", "a", 1)],
>   [("B", "b", 1)]
>]
> ]

That's easy with the magic of itertools.groupby and operator.itemgetter:

>>> from itertools import groupby
>>> from operator import itemgetter
>>> from pprint import pprint
>>> first = itemgetter(0)
>>> second = itemgetter(1)
>>> l = [ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A",
... "b", 2), ("B", "a", 1), ("B", "b", 1)]
>>> result = [[list(g2) for _,g2 in groupby(g1,second)] for _,g1 in 
>>> groupby(l,first)]
>>> pprint(result)
[[[('A', 'a', 1), ('A', 'a', 2), ('A', 'a', 3)],
  [('A', 'b', 1), ('A', 'b', 2)]],
 [[('B', 'a', 1)], [('B', 'b', 1)]]]

HTH,

-- 
Carsten Haese
http://informixdb.sourceforge.net


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


Re: wxPython and threads

2007-07-19 Thread Josiah Carlson
Nick Craig-Wood wrote:
> Josiah Carlson <[EMAIL PROTECTED]> wrote:
>>  Sending results one at a time to the GUI is going to be slow for any 
>>  reasonably fast search engine (I've got a pure Python engine that does 
>>  50k results/second without breaking a sweat).  Don't do that.  Instead, 
>>  have your search thread create a list, which it fills with items for 
>>  some amount of time, *then* sends it off to the GUI thread (creating a 
>>  new list that it then fills, etc.).  While you *could* use a Queue, it 
>>  is overkill for what you want to do (queues are really only useful when 
>>  there is actual contention for a resource and you want to block when a 
>>  resource is not available).
> 
> I'd dispute that.  If you are communicating between threads use a
> Queue and you will save yourself thread heartache.  Queue has a non
> blocking read interface Queue.get_nowait().

If you have one producer and one consumer, and the consumer will be 
notified when there is an item available, AND deques (in Python 2.4, 
2.5, and presumably later) are threadsafe, then the *additional* 
locking, blocking, etc., that a Queue provides isn't necessary.

Whether one wants to use a Queue for 'piece of mind', or for future 
expansion possibilities is another discussion entirely, but his 
application (as stated) will work with a deque for the worker thread -> 
GUI thread communication path.

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


Re: odbc module for python

2007-07-19 Thread Steve Holden
Sean Davis wrote:
> What are the alternatives for accessing an ODBC source from python
> (linux 64-bit, python 2.5)?  It looks like mxODBC is the only one
> available?
> 
There is, I understand, a pyodbc module as well. Having never used it I 
can't say how good it is.

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: odbc module for python

2007-07-19 Thread Tim Golden
Steve Holden wrote:
> Sean Davis wrote:
>> What are the alternatives for accessing an ODBC source from python
>> (linux 64-bit, python 2.5)?  It looks like mxODBC is the only one
>> available?
>>
> There is, I understand, a pyodbc module as well. Having never used it I 
> can't say how good it is.

This post seems pertinent:

http://www.devpicayune.com/entry/200707181242

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


Itertools question: how to call a function n times?

2007-07-19 Thread Matthew Wilson
I want to write a function that each time it gets called, it returns a
random choice of 1 to 5 words from a list of words.

I can write this easily using for loops and random.choice(wordlist) and
random.randint(1, 5).

But I want to know how to do this using itertools, since I don't like
manually doing stuff like:

phrase = list()
for i in random.randint(1, 5):

phrase.append(random.choice(wordlist))

It just seems slow. 

All advice welcome.

TIA

Matt

-- 
A better way of running series of SAS programs:
http://tplus1.com/wilsonwiki/SasAndMakefiles
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Posted messages not appearing in this group

2007-07-19 Thread Adrian Petrescu
On Jul 18, 3:05 am, Sanjay <[EMAIL PROTECTED]> wrote:
> Hi All,
>
> I tried posting in this group twice since last week, but the messages
> did not appear in the forum. Don't know why. Trying this message
> again...
>
> Sanjay

I think I'm having the exact same problem. I posted a new thread last
night and it still hasn't shown up for me. I'm using Google Groups for
both posting and reading.

Maybe it has shown up and Google simply isn't showing it yet. Can
anyone confirm that a thread posted yesterday (July 18th, 2007) whose
title was something like "interpreting os.lstat() output" exists or
not?

This is quite distressing :(

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


Re: A way to re-organize a list

2007-07-19 Thread marduk
On Thu, 2007-07-19 at 15:05 +, beginner wrote:
> Hi Everyone,
> 
> I have a simple list reconstruction problem, but I don't really know
> how to do it.
> 
> I have a list that looks like this:
> 
> l=[ ("A", "a", 1), ("A", "a", 2), ("A", "a", 3), ("A", "b", 1), ("A",
> "b", 2), ("B", "a", 1), ("B", "b", 1)]
> 
> What I want to do is to reorganize it in groups, first by the middle
> element of the tuple, and then by the first element. I'd like the
> output look like this:
> 
> out=[
>[#group by first element "A"
>   [("A", "a", 1), ("A", "a", 2), ("A", "a", 3)], #group by
> second element "a"
>   [ ("A", "b", 1), ("A", "b", 2)], #group by second element
> "b"
>],
>[   #group by first element "B"
>   [("B", "a", 1)],
>   [("B", "b", 1)]
>]
> ]

One way of doing it:

def group_by(i, my_list):
d = {}
for t in my_list:
d[t[i]] = d.get(t[i], []) + [t]

return d.values()


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


Re: Break up list into groups

2007-07-19 Thread Matimus
> A little renaming of variables helps it be a bit more elegant I think ...
>
> def getgroups8(seq):
>  groups = []
>  iseq = iter(xrange(len(seq)))
>  for start in iseq:
>  if seq[start] & 0x80:
>  for stop in iseq:
>  if seq[stop] & 0x80:
>  groups.append(seq[start:stop])
>  start = stop
>  groups.append(seq[start:])
>  return groups

Excellent work! One more modification and I get below 10us/pass:

def getgroups(seq):
 groups = []
 push = groups.append
 iseq = iter(xrange(len(seq)))
 for start in iseq:
 if seq[start] & 0x80:
 for stop in iseq:
 if seq[stop] & 0x80:
 push(seq[start:stop])
 start = stop
 push(seq[start:])
 return groups

-Matt

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


Re: wxPython, searching, and threads

2007-07-19 Thread kyosohma
On Jul 18, 3:15 pm, Benjamin <[EMAIL PROTECTED]> wrote:
> Hello! I am writing a search engine with wxPython as the GUI. As the
> search thread returns items, it adds them to a Queue which is picked
> up by the main GUI thread calling itself recursively with
> wx.CallAfter. These are then added to a ListCtrl. This works fine for
> small searches, but with larger and longer searchs the GUI is clogged
> and won't respond. I suspect (I may be wrong) that there are so many
> results being sent to the ListCtrl that the event loop doesn't have
> time to respond to events. I've tried buffering the results before
> sending them to the GIU, but that doesn't help at all. Please advise.

I think what you need to look at is http://wiki.wxpython.org/LongRunningTasks

That's what the people on the wxPython list usually recommend when
doing what you're doing. I've used the techniques there and they work
great!

Mike

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


Re: Itertools question: how to call a function n times?

2007-07-19 Thread Bruno Desthuilliers
Matthew Wilson a écrit :
> I want to write a function that each time it gets called, it returns a
> random choice of 1 to 5 words from a list of words.
> 
> I can write this easily using for loops and random.choice(wordlist) and
> random.randint(1, 5).
> 
> But I want to know how to do this using itertools, since I don't like
> manually doing stuff like:
> 
> phrase = list()
> for i in random.randint(1, 5):
> 
> phrase.append(random.choice(wordlist))

what's wrong with:

phrases = [random.choice(wordList) for i in random.randint(1, 5)]

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


Re: Itertools question: how to call a function n times?

2007-07-19 Thread Wojciech Muła
Matthew Wilson wrote:
> I want to write a function that each time it gets called, it returns a
> random choice of 1 to 5 words from a list of words.
>
> I can write this easily using for loops and random.choice(wordlist) and
> random.randint(1, 5).
>
> But I want to know how to do this using itertools, since I don't like
> manually doing stuff like:
>
> phrase = list()
> for i in random.randint(1, 5):
>
> phrase.append(random.choice(wordlist))

Use list comprehension:

phrase = [random.choice(wordlist) for i in xrange(random.randint(1, 5))]

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


Re: Copy List

2007-07-19 Thread Falcolas
On Jul 18, 6:56 am, "Rustom Mody" <[EMAIL PROTECTED]> wrote:
> This is shallow copy
> If you want deep copy then
> from copy import deepcopy

What will a "deep copy" of a list give you that using the slice
notation will not?

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


Re: Posted messages not appearing in this group

2007-07-19 Thread George Sakkis
On Jul 18, 6:50 am, Alex Popescu <[EMAIL PROTECTED]>
wrote:
> Sanjay  gmail.com> writes:
>
>
>
> > Hi All,
>
> > I tried posting in this group twice since last week, but the messages
> > did not appear in the forum. Don't know why. Trying this message
> > again...
>
> > Sanjay
>
> Something similar seemed to happen to me too, but when checking with gmane 
> I've
> noticed that all my posts got in (and now I am trying to figure out how can I
> apologize for multiple posts :-) ).

Same here, my last three posts haven't appeared (yet) at the google
group but they show up on the mailing list:
http://mail.python.org/pipermail/python-list/2007-July/thread.html

George

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


Re: Posted messages not appearing in this group

2007-07-19 Thread David H Wild
In article <[EMAIL PROTECTED]>,
   Adrian Petrescu <[EMAIL PROTECTED]> wrote:
> Maybe it has shown up and Google simply isn't showing it yet. Can
> anyone confirm that a thread posted yesterday (July 18th, 2007) whose
> title was something like "interpreting os.lstat() output" exists or
> not?

That thread is there, with four postings.

-- 
David Wild using RISC OS on broadband
www.davidhwild.me.uk
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Itertools question: how to call a function n times?

2007-07-19 Thread Stargaming
Matthew Wilson schrieb:
> I want to write a function that each time it gets called, it returns a
> random choice of 1 to 5 words from a list of words.
> 
> I can write this easily using for loops and random.choice(wordlist) and
> random.randint(1, 5).
> 
> But I want to know how to do this using itertools, since I don't like
> manually doing stuff like:
> 
> phrase = list()
> for i in random.randint(1, 5):
> 
> phrase.append(random.choice(wordlist))
> 
> It just seems slow. 
> 
> All advice welcome.
> 
> TIA
> 
> Matt
> 

You could do it either using the previously suggested list comprehension 
way or, if you don't need to have all choices in memory at once, use 
generator expressions. They're basically like list comprehensions, 
except that you wrap them into parentheses (), not brackets [].

phrase = (random.choice(wordlist) for i in xrange(random.randint(1, 5)))

You loose the ability to slice it directly (eg. phrase[3]), though. (See 
itertools.islice for a way to do it.)

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


Re: Copy List

2007-07-19 Thread Marc 'BlackJack' Rintsch
On Thu, 19 Jul 2007 09:21:54 -0700, Falcolas wrote:

> On Jul 18, 6:56 am, "Rustom Mody" <[EMAIL PROTECTED]> wrote:
>> This is shallow copy
>> If you want deep copy then
>> from copy import deepcopy
> 
> What will a "deep copy" of a list give you that using the slice
> notation will not?

Well, a deep copy of course.  ;-)

In [6]: import copy

In [7]: a = [[1, 2], [3, 4]]

In [8]: b = a[:]

In [9]: c = copy.deepcopy(a)

In [10]: a[0][1] = 42

In [11]: a
Out[11]: [[1, 42], [3, 4]]

In [12]: b
Out[12]: [[1, 42], [3, 4]]

In [13]: c
Out[13]: [[1, 2], [3, 4]]

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


Re: Copy List

2007-07-19 Thread James Matthews

A slice still has some references to the old objects a deep copy is a
totally new object!

On 19 Jul 2007 17:04:00 GMT, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]>
wrote:


On Thu, 19 Jul 2007 09:21:54 -0700, Falcolas wrote:

> On Jul 18, 6:56 am, "Rustom Mody" <[EMAIL PROTECTED]> wrote:
>> This is shallow copy
>> If you want deep copy then
>> from copy import deepcopy
>
> What will a "deep copy" of a list give you that using the slice
> notation will not?

Well, a deep copy of course.  ;-)

In [6]: import copy

In [7]: a = [[1, 2], [3, 4]]

In [8]: b = a[:]

In [9]: c = copy.deepcopy(a)

In [10]: a[0][1] = 42

In [11]: a
Out[11]: [[1, 42], [3, 4]]

In [12]: b
Out[12]: [[1, 42], [3, 4]]

In [13]: c
Out[13]: [[1, 2], [3, 4]]

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





--
http://www.goldwatches.com/Watches.asp?Brand=14
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Posted messages not appearing in this group

2007-07-19 Thread James Matthews

I am also having some issues. There is a post on the list that appeared 7
times because of this issue i think.

On 7/19/07, David H Wild <[EMAIL PROTECTED]> wrote:


In article <[EMAIL PROTECTED]>,
   Adrian Petrescu <[EMAIL PROTECTED]> wrote:
> Maybe it has shown up and Google simply isn't showing it yet. Can
> anyone confirm that a thread posted yesterday (July 18th, 2007) whose
> title was something like "interpreting os.lstat() output" exists or
> not?

That thread is there, with four postings.

--
David Wild using RISC OS on broadband
www.davidhwild.me.uk
--
http://mail.python.org/mailman/listinfo/python-list





--
http://www.goldwatches.com/watches.asp?Brand=14
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: wxPython, searching, and threads

2007-07-19 Thread James Matthews

I have seen this thread for a while and i do not see it on the wxpython list
so i am posting it there now and will post a reply if i still see this
later!

James

On 7/19/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:


On Jul 18, 3:15 pm, Benjamin <[EMAIL PROTECTED]> wrote:
> Hello! I am writing a search engine with wxPython as the GUI. As the
> search thread returns items, it adds them to a Queue which is picked
> up by the main GUI thread calling itself recursively with
> wx.CallAfter. These are then added to a ListCtrl. This works fine for
> small searches, but with larger and longer searchs the GUI is clogged
> and won't respond. I suspect (I may be wrong) that there are so many
> results being sent to the ListCtrl that the event loop doesn't have
> time to respond to events. I've tried buffering the results before
> sending them to the GIU, but that doesn't help at all. Please advise.

I think what you need to look at is
http://wiki.wxpython.org/LongRunningTasks

That's what the people on the wxPython list usually recommend when
doing what you're doing. I've used the techniques there and they work
great!

Mike

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





--
http://www.goldwatches.com/watches.asp?Brand=14
http://www.jewelerslounge.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: help with create menu in wxpython

2007-07-19 Thread franciscodg
On 18 jul, 13:55, Stef Mientki <[EMAIL PROTECTED]>
wrote:
> better ask in the wx discussion group:
>[EMAIL PROTECTED]
>
> cheers,
> Stef Mientki

thks

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


Re: class C: vs class C(object):

2007-07-19 Thread Aahz
In article <[EMAIL PROTECTED]>,
Bruno Desthuilliers  <[EMAIL PROTECTED]> wrote:
>
>To make a long story short: Python 2.2 introduced a new object model 
>which is more coherent and more powerful than the original one. The old 
>one was kept so far for compatibility reasons, but there's absolutely no 
>reason to use it no more since "new-style" classes can do anything 
>"Classic" classes did and much more. IOW, don't even bother with 
>old-style classes.

And I'll make my usual knee-jerk response disagreeing with this.  For
more info, search groups.google.com.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

I support the RKAB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class C: vs class C(object):

2007-07-19 Thread Aahz
In article <[EMAIL PROTECTED]>,
Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
>
>It isn't wrong to use the old style, but it is deprecated, [...]

Really?  Can you point to some official documentation for this?  AFAIK,
new-style classes still have not been integrated into the standard
documentation.  Maybe I missed something, though.

Note very carefully that "going away eventually" is *not* the same as
deprecation.
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

I support the RKAB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: wxPython and threads

2007-07-19 Thread Nick Craig-Wood
Josiah Carlson <[EMAIL PROTECTED]> wrote:
>  Nick Craig-Wood wrote:
> > I'd dispute that.  If you are communicating between threads use a
> > Queue and you will save yourself thread heartache.  Queue has a non
> > blocking read interface Queue.get_nowait().
> 
>  If you have one producer and one consumer, and the consumer will be 
>  notified when there is an item available, AND deques (in Python 2.4, 
>  2.5, and presumably later) are threadsafe, then the *additional* 
>  locking, blocking, etc., that a Queue provides isn't necessary.
> 
>  Whether one wants to use a Queue for 'piece of mind', or for future 
>  expansion possibilities is another discussion entirely, but his 
>  application (as stated) will work with a deque for the worker thread -> 
>  GUI thread communication path.

You are right deque's do say they are thread safe - I didn't know
that.  From the docs :-

  Deques support thread-safe, memory efficient appends and pops from
  either side of the deque with approximately the same O(1) performance
  in either direction.

I think I'd go for the peace of mind option, but YMMV of course ;-)

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


Python version changes, sys.executable does not

2007-07-19 Thread Jeffrey Froman
Hello All,

I have two python versions installed, one in /usr/bin, and one in
/usr/local/bin. However, when invoking python without a full path,
I get the wrong executable with the right sys.executable string!

[EMAIL PROTECTED] ~]# ls -l /usr/local/bin/python*
-rwxr-xr-x  2 root root 3783810 Jul 19 09:15 /usr/local/bin/python
-rwxr-xr-x  2 root root 3783810 Jul 19 09:15 /usr/local/bin/python2.5
-rwxr-xr-x  1 root root1281 Jul 19 09:16 /usr/local/bin/python2.5-config
lrwxrwxrwx  1 root root  16 Jul 19 09:16 /usr/local/bin/python-config -> 
python2.5-config

[EMAIL PROTECTED] ~]# ls -l /usr/bin/python*
-rwxr-xr-x  2 root root 5396 May  2 16:28 /usr/bin/python
lrwxrwxrwx  1 root root6 Jul 18 12:20 /usr/bin/python2 -> python
-rwxr-xr-x  2 root root 5396 May  2 16:28 /usr/bin/python2.3

[EMAIL PROTECTED] ~]# which python
/usr/local/bin/python

[EMAIL PROTECTED] ~]# /usr/local/bin/python -c "import sys; print 
sys.executable; print sys.version; set()"
/usr/local/bin/python
2.5 (r25:51908, Jul 19 2007, 09:13:48)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]

[EMAIL PROTECTED] ~]# env python -c "import sys; print sys.executable; print 
sys.version; set()"
/usr/local/bin/python
2.5 (r25:51908, Jul 19 2007, 09:13:48)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]

[EMAIL PROTECTED] ~]# python -c "import sys; print sys.executable; print 
sys.version; set()"
/usr/local/bin/python
2.3.4 (#1, May  2 2007, 19:26:00)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]
Traceback (most recent call last):
  File "", line 1, in ?
NameError: name 'set' is not defined
-


On a different machine, with same setup (as far as I can tell), I get the 
expected
results:
-
[EMAIL PROTECTED] ~]# /usr/local/bin/python -c "import sys; print 
sys.executable; print sys.version; set()"
/usr/local/bin/python
2.5 (r25:51908, Feb  8 2007, 16:29:18)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]

[EMAIL PROTECTED] ~]# env python -c "import sys; print sys.executable; print 
sys.version; set()"
/usr/local/bin/python
2.5 (r25:51908, Feb  8 2007, 16:29:18)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]

[EMAIL PROTECTED] ~]# python -c "import sys; print sys.executable; print 
sys.version; set()"
/usr/local/bin/python
2.5 (r25:51908, Feb  8 2007, 16:29:18)
[GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]
-

Can anyone tell me what might be causing the erroneous behavior in the first 
example?

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


Re: A way to re-organize a list

2007-07-19 Thread Gordon Airporte
beginner wrote:
> 
> What I want to do is to reorganize it in groups, first by the middle
> element of the tuple, and then by the first element. I'd like the
> output look like this:

itertools.groupby has already been mentioned, but it has a very specific 
and complex behavior which may not be exactly what you need. I found 
this handy class:

class groupby(dict):
 def __init__(self, seq, key=lambda x:x):
 for value in seq:
 k = key(value)
 self.setdefault(k, []).append(value)
 __iter__ = dict.iteritems

which you would use like this:

byfirst = groupby(l, lambda x: x[0])
print byfirst['A']
print byfirst['B']
bysecond = groupby(l, lambda x: x[1])
print bysecond['a']
print bysecond['b']

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


Re: Interpreting os.lstat()

2007-07-19 Thread Adrian Petrescu
On Jul 19, 4:27 am, Hrvoje Niksic <[EMAIL PROTECTED]> wrote:
> Adrian Petrescu <[EMAIL PROTECTED]> writes:
> > I checked the online Python documentation 
> > athttp://python.org/doc/1.5.2/lib/module-stat.html
> > but it just says to "consult the documentation for your system.".
>
> The page you're looking for is 
> athttp://www.python.org/doc/current/lib/os-file-dir.html.  For lstat it
> says "Like stat(), but do not follow symbolic links."  For stat it
> says:
>
> Perform a stat() system call on the given path. The return value
> is an object whose attributes correspond to the members of the
> stat structure, namely: st_mode (protection bits), st_ino (inode
> number), st_dev (device), st_nlink (number of hard links), st_uid
> (user ID of owner), st_gid (group ID of owner), st_size (size of
> file, in bytes), st_atime (time of most recent access), st_mtime
> (time of most recent content modification), st_ctime (platform
> dependent; time of most recent metadata change on Unix, or the
> time of creation on Windows)
> [...]
> For backward compatibility, the return value of stat() is also
> accessible as a tuple of at least 10 integers giving the most
> important (and portable) members of the stat structure, in the
> order st_mode, st_ino, st_dev, st_nlink, st_uid, st_gid, st_size,
> st_atime, st_mtime, st_ctime. More items may be added at the end
> by some implementations. The standard module stat defines
> functions and constants that are useful for extracting information
> from a stat structure. (On Windows, some items are filled with
> dummy values.)

Thank you, both Will and Hrvoje. Those links answer my questions. :)

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


Pure Python equivalent of unix "file" command?

2007-07-19 Thread W3
Hi all,

Just a quick one... Is there such a thing?

Thanks,
/Walter
-- 

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


Re: Pure Python equivalent of unix "file" command?

2007-07-19 Thread Will Maier
On Thu, Jul 19, 2007 at 03:29:35PM -0400, W3 wrote:
> Just a quick one... Is there such a thing?

Debian et al ship Python bindings[0] for file(1)[1]. file works by
using a file (/etc/magic) with 'magic' numbers in it to figure out
the type of a file. Googling 'python magic' will turn up a few
interesting threads.

[0] http://packages.debian.org/unstable/python/python-magic
[1] http://www.darwinsys.com/file/

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Converting between objects

2007-07-19 Thread Nathan Harmston
Hi,

I have being thinking about this and was wondering with built in types
you can do things like

float(1) or str(200)

is there way I can define conversion functions like this:

say i have a class A and a class B

bobj = B()
aobj = a(bobj)

in a neater way than just defining a set of methods

def a(object_to_convert)
# if object_to_convert of type..
# do some stuff
   return A()

def b(object_to_convert)
# if object_to_convert of type..
# do some stuff
   return B()

Cause this seems a little verbose and not very OO.

Please correct me if I m wrong or offer me hints as to a better way to do it ?

Many Thanks

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


Re: UDP broadcast over a specific interface

2007-07-19 Thread [EMAIL PROTECTED]
On Jul 19, 7:09 am, Jean-Paul Calderone <[EMAIL PROTECTED]> wrote:
> On Thu, 19 Jul 2007 12:32:02 -, "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> 
> wrote:
> >I am trying to send UDP broadcast packets over a specific interface
> >and I
> >am having trouble specifying the interface:
>
> >host='192.168.28.255'
> >sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> >sock.bind(('',0))
> >sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
> >sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_IF,
> >socket.inet_aton(host))
>
> >socket.error: (49, "Can't assign requested address")
>
> >What am I doing wrong? How can I force my broadcast packets to go out
> >a specific interface?
>
> IP_MULTICAST_IF is for multicast UDP, which doesn't have anything to do
> with broadcast UDP.
>
> Try just doing this, instead:
>
> host='192.168.28.255'
> sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
> sock.bind((host,0))
> sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
>
> You shouldn't need to mess with anything beyond that.

Thanks! This works perfectly.

-larry

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


Re: Embedding/Extending Python in/with C++: non-static members?

2007-07-19 Thread dmoore
thanks for the responses Nick and "AnonMail"

> I'm doing a similar thing, and I would imagine others are also.
>
> 1. In a python file, set up wrapper functions that the python user
> actually uses (e.g FunctionA).  Each function corresponds to a
> particular C/C++ extension function that you are exposing (e.g.
> CFunctionA).
>
...
> 4. Now when you enter you C/C++ function you can find your object by
> looking
> it up in some predefined table using the id.  What we actually do is
> not use
> an integer but instead use a void pointer which is cast appropriately
> once
> inside C/C++.  This avoids the lookup.

step 4 is smart :)

It's good to know that there is at least one data point of success
using the approach. I won't give up just yet.

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


Data type conversion

2007-07-19 Thread ervin ramonllari

Hello everybody,

I'm trying to read some tables from a MS Access database and dump them into
a Postgres database.
When I read the attributes data types, I get some numeric values, i.e. if
the data type
of an attribute is TEXT, I get a value 202. I don't know how to convert this
number into
a valid data type in Postgres. If someone can help me with this problem, I
would really
appreciate that.

Thank you in advance,

Regards,

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

Re: Converting between objects

2007-07-19 Thread Bjoern Schliessmann
Nathan Harmston wrote:

> is there way I can define conversion functions like this:
> 
> say i have a class A and a class B
> 
> bobj = B()
> aobj = a(bobj)
> 
> in a neater way than just defining a set of methods
> 
> def a(object_to_convert)
> # if object_to_convert of type..
> # do some stuff
>return A()
> 
> def b(object_to_convert)
> # if object_to_convert of type..
> # do some stuff
>return B()
> 
> Cause this seems a little verbose and not very OO.

Yes, simply write something like

class a(object):
def __init__(self, parameter):
if isinstance(parameter, B):
# conversion from B to a
else:
# something else

Something like that is called "conversion constructor". At least in
C++.

Regards,


Björn

-- 
BOFH excuse #55:

Plumber mistook routing panel for decorative wall fixture

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


Re: Pickled objects over the network

2007-07-19 Thread Irmen de Jong
Rustom Mody wrote:
> Sure pyro may be the solution but it may also be overkill
> Why not use safe_load from the yaml module?

In what way would Pyro be overkill where Yaml (also a module that you need
to install separately) wouldn't be?

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


win32com ppt embedded object numbers reverting back to original numbers

2007-07-19 Thread Lance Hoffmeyer
Hey all,

I have a script that takes numbers from XL and inserts them into an embedded
MSGRAPH dataset in PPT.  The problem is that when I reopen the modified document
that has been saved as a new filename and activate the embedded datasheet the
new numbers that were inserted disappear and the old, original numbers come 
back?


I thought that adding these lines and resetting these variables was supposed to 
prevent
this from happening?

del oGraph
del PWB
del oHEADER
del oVALUE

Anyone had experience with this and know what I need to do to keep the embedded 
datasheet
from reverting back to it's original numbers after modification?

Thanks in advance,

Lance





#
#
# ADD THIS INTO A MODULE IN PPT TO OBTAIN THE PROG ID OF A SLIDE
#Sub test()
#MsgBox "The Slide ID of the current slide is:" & _
#   ActiveWindow.View.Slide.SlideID
#End Sub
#
def attributesbyID(row,base,slideID,spreadsheet):
sh = wb.Worksheets (spreadsheet)
sh.Select()
LIST = xlparams(row, base)
 POWERPOINT SECTION ##
for shape in WB.Slides.FindBySlideID(slideID).Shapes:
if (shape.Type== 7):
for oXLROW,oXLBASE,oXLLASTCOL,oPPTCELL,oPPTHEADERCELL 
in LIST:
oVALUE = sh.Cells(oXLROW,oXLLASTCOL).Value
oHEADER = sh.Cells(base-1,oXLLASTCOL).Value  + 
" (n="  +  str(int(sh.Cells(oXLBASE,oXLLASTCOL).Value))  + ")"
PWB = 
WB.Slides.FindBySlideID(slideID).Shapes(shape.Name)
oGraph = PWB.OLEFormat.Object

oGraph.Application.datasheet.Range(oPPTCELL).Value = oVALUE

oGraph.Application.datasheet.Range(oPPTHEADERCELL).Value = oHEADER
oGraph.Application.datasheet.Font.Bold=False
del oGraph
del PWB
del oHEADER
del oVALUE
###
#
#
#

def xlparams(row, base):
lastcol=LASTCOL
### EXCEL SECTION TO GET NUMBERS #

thelist=((row,base,lastcol,"A13","013"),(row,base,lastcol-1,"A14","014"),(row,base,lastcol-2,"A15","015"),(row,base,lastcol-3,"A16","016"),
  
(row+20,base+20,lastcol,"A9","09"),(row+20,base+20,lastcol-1,"A10","010"),(row+20,base+20,lastcol-2,"A11","011"),(row+20,base+20,lastcol-3,"A12","012"),
  
(row+40,base+40,lastcol,"A5","05"),(row+40,base+40,lastcol-1,"A6","06" ), 
(row+40,base+40,lastcol-2,"A7","07" ), (row+40,base+40,lastcol-3,"A8","08" ),
  
(row+60,base+60,lastcol,"A1","01"),(row+60,base+60,lastcol-1,"A2","02" ), 
(row+60,base+60,lastcol-2,"A3","03" ), (row+60,base+60,lastcol-3,"A4","04" ))
##
return thelist


## attribute(ROW NUMBER, BASE ROW NUMBER, SLIDE NUMBER)
attributesbyID(14,12,839,"Attributes(116-144)") # This medication has a 
convenient dosing frequency
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom for RE matching

2007-07-19 Thread Roger Miller
On Jul 18, 6:52 pm, Gordon Airporte <[EMAIL PROTECTED]> wrote:

> ...
> I've also been assuming that using the re functions that create match
> objects is slower/heavier than dealing with the simple list returned by
> findall(). I've profiled it and these matches are the biggest part of
> the running time of the program, so I really would rather not use
> anything slower.

My guess would be that searching for more matches after finding the
first would be more expensive than creating a match object.  But that
would probably depend on the nature of your data and REs, so you need
to test it both ways if you are concerned about performance.

It would be nice if findall() had an optional parameter to limit the
number of matches, similar to the maxsplit parameter of string.split().

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


How to check if an item exist in a nested list

2007-07-19 Thread Arash Arfaee

Hi All,

Is there any way to check if an item in specific location in a multiple
dimension nested exist?  For example something like:

if M_list[line][row][d] exist:
 do_something_0
else:
 do_something_1

One way is to check the length of each dimension. Does any body know a
simpler way? is there any way to check if "IndexError: list index out of
range" happened or going to happen and stop program from terminating?

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

Re: Copy List

2007-07-19 Thread Jason
On Jul 19, 10:21 am, Falcolas <[EMAIL PROTECTED]> wrote:
> On Jul 18, 6:56 am, "Rustom Mody" <[EMAIL PROTECTED]> wrote:
>
> > This is shallow copy
> > If you want deep copy then
> > from copy import deepcopy
>
> What will a "deep copy" of a list give you that using the slice
> notation will not?

With a shallow copy, you end up with a new list object, but the items
contained within the new list object are the same as in the original
list object.  This makes no real difference if the original list only
contains immutable values (such as strings, integers, or floats), but
it can make a big difference if the values are mutable.

>>> originalList = [1, 2, [3, 4]]
>>> shallowCopy = originalList[:]
>>> shallowCopy.append(5)
>>> print str(originalList), '\n', str(shallowCopy)
[1, 2, [3, 4]]
[1, 2, [3, 4], 5]
>>> originalList[2].append(100) # Mutate the list inside this list
>>> print str(originalList), '\n', str(shallowCopy)
[1, 2, [3, 4, 100]]
[1, 2, [3, 4, 100], 5]
>>>

As you can see in the above code snipped, the original list contains a
list at index 2.  The slice copy is a different list, so appending a 5
to it doesn't modify the original list.  However, the result of
appending 100 to the object at index 2 can be seen in both lists.  A
deep copy creates a new object for ever item in the list, and all
items in those items, and so forth, so the lists guaranteed to be
truly disconnected:

>>> from copy import deepcopy
>>> originalList = [1, [2, [3, 4]]]
>>> fullCopy = deepcopy(originalList)
>>> originalList[1][1].append(100)
>>> print originalList, '\n', fullCopy
[1, [2, [3, 4, 100]]]
[1, [2, [3, 4]]]
>>>


  --Jason

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


Re: How to check if an item exist in a nested list

2007-07-19 Thread Matt McCredie

Is there any way to check if an item in specific location in a multiple
dimension nested exist?  For example something like:

if M_list[line][row][d] exist:
  do_something_0
else:
  do_something_1



Certainly:

try:
   M_list[line][row][d]
except IndexError:
   do_something_1
else:
   do_something_0


Assuming that you want to check because something in `do_someting_0' fails
if the item isn't defined, it is very likely that this can be shortened to:


try:
   do_something_0
except IndexError:
   do_something_1


The try/except should be wrapped as tightly as possible around the specific
code that actually throws the exception.

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

Re: How to check if an item exist in a nested list

2007-07-19 Thread Will Maier
On Thu, Jul 19, 2007 at 02:43:13PM -0700, Arash Arfaee wrote:
> One way is to check the length of each dimension. Does any body
> know a simpler way? is there any way to check if "IndexError: list
> index out of range" happened or going to happen and stop program
> from terminating?

If I understand what you're getting at, you could probably use a
dictionary (indexed by (x, y) tuples), too. If you want to test if
an item is in a list, use 'in':

>>> dinner = ['spam', 'eggs', 'spam', 'spam']
>>> 'spam' in dinner
True

'in' uses the __contains__() method implemented by lists.

-- 

[Will [EMAIL PROTECTED]|http://www.lfod.us/]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: really small values

2007-07-19 Thread Zentrader
On Jul 17, 2:13 pm, "Dee Asbury" <[EMAIL PROTECTED]> wrote:
> In multiplying a value of xe^-325 with ye^-4, Python is returning zero. How
> do I get it to give me back my tiny value?
>
> Thanks!
> Dee

Also, Python's decimal class allows theoretically unlimited
precision.  I have extremely limited knowledge here.  It gives the
following for 2**-325.  I have no idea if the answer is correct.
You'll have to see if gmpy or decimal works better for this.  One
piece of advice is to use whichever exclusively.  If you use a float
and then covert to either one, the result will be corrupted.
import decimal
decimal.getcontext().prec = 375  ## set precision at 375
print "2**-325 =", decimal.Decimal(str(2**-325))

2**-325 = 1.46302386084E-98

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


Re: Itertools question: how to call a function n times?

2007-07-19 Thread jrbj
On Jul 19, 8:35 am, Matthew Wilson <[EMAIL PROTECTED]> wrote:
> I want to write a function that each time it gets called, it returns a
> random choice of 1 to 5 words from a list of words.
>
> I can write this easily using for loops and random.choice(wordlist) and
> random.randint(1, 5).
>
> But I want to know how to do this using itertools, since I don't like
> manually doing stuff like:
>
> phrase = list()
> for i in random.randint(1, 5):
>
> phrase.append(random.choice(wordlist))

All the previous suggestions in this thread are good. If you *must*
use itertools, you can use the itertools.repeat function to return an
object x many times:

phrase = [somewords(wordlist) for somewords in
  itertools.repeat(random.choice, random.randint(1, 5))]


Hope it helps,
John

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


Re: class C: vs class C(object):

2007-07-19 Thread James Stroud
Aahz wrote:
> In article <[EMAIL PROTECTED]>,
> Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
> 
>>It isn't wrong to use the old style, but it is deprecated, [...]
> 
> 
> Really?  Can you point to some official documentation for this?  AFAIK,
> new-style classes still have not been integrated into the standard
> documentation.  Maybe I missed something, though.
> 
> Note very carefully that "going away eventually" is *not* the same as
> deprecation.

How about "broke" instead of "deprecated":


 >>> class Old:
...   def __init__(self):
... self._value = 'broke'
...   value = property(lambda self: self._value)
...
 >>>
 >>> class New(object):
...   def __init__(self):
... self._value = 'works'
...   value = property(lambda self: self._value)
...
 >>> broke = Old()
 >>> broke.value
'broke'
 >>> broke.value = 'still broke'
 >>> broke.value
'still broke'
 >>>
 >>> works = New()
 >>> works.value
'works'
 >>> works.value = 'expected result of assignment here'
Traceback (most recent call last):
   File "", line 1, in 
AttributeError: can't set attribute


James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: class C: vs class C(object):

2007-07-19 Thread Aahz
In article <[EMAIL PROTECTED]>,
James Stroud  <[EMAIL PROTECTED]> wrote:
>Aahz wrote:
>> In article <[EMAIL PROTECTED]>,
>> Steven D'Aprano  <[EMAIL PROTECTED]> wrote:
>>> 
>>>It isn't wrong to use the old style, but it is deprecated, [...]
>> 
>> 
>> Really?  Can you point to some official documentation for this?  AFAIK,
>> new-style classes still have not been integrated into the standard
>> documentation.  Maybe I missed something, though.
>> 
>> Note very carefully that "going away eventually" is *not* the same as
>> deprecation.
>
>How about "broke" instead of "deprecated":
>
>
> >>> class Old:
>...   def __init__(self):
>... self._value = 'broke'
>...   value = property(lambda self: self._value)
>...

How is this broken?  Properties are not supported for old-style classes.
They may not support features introduced in new-style classes, but that's
hardly the same as "broken".
-- 
Aahz ([EMAIL PROTECTED])   <*> http://www.pythoncraft.com/

I support the RKAB
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: idiom for RE matching

2007-07-19 Thread Reddy

On 7/19/07, Gordon Airporte <[EMAIL PROTECTED]> wrote:


I have some code which relies on running each line of a file through a
large number of regexes which may or may not apply. For each pattern I
want to match I've been writing

gotit = mypattern.findall(line)




Try to use iterator function finditer instead of findall. To see the
difference run below code by calling findIter or findAll function one at a
time in for loop.  You can have achieve atleast 4x better performance.

---
import re
import time

m = re.compile(r'(\d+/\d+/\d+)')
line = "Today's date is 21/07/2007 then yesterday's  20/07/2007"

def findIter(line):
   m.finditer(line)
   glist = [x.group(0) for x in g]

def findAll(line):
   glist = m.findall(line)

start = time.time()
for i in xrange(100):
   #findIter(line)
   findAll(line)
end = time.time()

print end-start


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

Re: class C: vs class C(object):

2007-07-19 Thread Matt McCredie


>How about "broke" instead of "deprecated":
>
>
> >>> class Old:
>...   def __init__(self):
>... self._value = 'broke'
>...   value = property(lambda self: self._value)
>...

How is this broken?  Properties are not supported for old-style classes.
They may not support features introduced in new-style classes, but that's
hardly the same as "broken".



What does that give you that this does not:

class Old:
def __init__(self):
 self.value = 'broke'

To further illustrate, what happens when you do this:

class Old:
def __init__(self):
 self._value = 'broke'
def _set_value(self, val):
 print "set called"
def _get_value(self):
 print "get called"
 return self._value
value = property(_get_value, _set_value)

x = Old()
print x.value
x.value = "not broke"
print x.value
print type(x.value)
print x._value

This is what happens:


x = Old()
print x.value

get called
broke

x.value = "not broke"
print x.value

not broke

print type(x.value)



print x._value

broke

Now, no exceptions were raised or anything, but with old-style classes I'm
having difficulty thinking of a scenario where they might actually be
useful. I suppose you could use it to do a calculation on instance variables
and return the result. You are probably better of using a method for that
anyway though.

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

Re: Converting between objects

2007-07-19 Thread Ben Finney
"Nathan Harmston" <[EMAIL PROTECTED]> writes:

> I have being thinking about this and was wondering with built in types
> you can do things like
> 
> float(1)

Calls the constructor for the 'float' type, passing the integer 1; the
constructor returns a new float object.

> str(200)

Calls the constructor for the 'str' type, passing the integer 200; the
constructor returns a new str object.

> is there way I can define conversion functions like this

These are not "conversion functions"; they are the constructors of the
corresponding types.

You can hook into the instance creation by modifying the '__new__'
method of the metaclass; but probably the easier way is to hook into
the instance initialisation (after it is created) by modifying the
'__init__' method of the class.

> say i have a class A and a class B
> 
> bobj = B()
> aobj = a(bobj)
> 
> in a neater way than just defining a set of methods
> 
> def a(object_to_convert)
># if object_to_convert of type..
># do some stuff
>   return A()

Rather than this, define '__init__' to do some stuff to 'self', that
is, modify attributes of the instance during its initialisation. The
'__init__' method is automatically called during object initialisation
and receives all the parameters that were passed to the constructor.

class B(object):
def __init__(self, obj):
self.foo = do_stuff(obj)

aobj = B(42)

-- 
 \"Pinky, are you pondering what I'm pondering?" "Wuh, I think |
  `\   so, Brain, but if we didn't have ears, we'd look like weasels." |
_o__) -- _Pinky and The Brain_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Efficiently removing duplicate rows from a 2-dimensional Numeric array

2007-07-19 Thread Alex Mont
I have a 2-dimensional Numeric array with the shape (2,N) and I want to
remove all duplicate rows from the array. For example if I start out
with:

[[1,2],

[1,3],

[1,2],

[2,3]]

 

I want to end up with

[[1,2],

[1,3],

[2,3]].

 

(Order of the rows doesn't matter, although order of the two elements in
each row does.)

 

The problem is that I can't find any way of doing this that is efficient
with large data sets (in the data set I am using, N > 100)

The normal method of removing duplicates by putting the elements into a
dictionary and then reading off the keys doesn't work directly because
the keys - rows of Python arrays - aren't hashable.

The best I have been able to do so far is:

 

def remove_duplicates(x):

d = {}

for (a,b) in x:

d[(a,b)] = (a,b)

return array(x.values())

 

According to the profiler the loop takes about 7 seconds and the call to
array() 10 seconds with N=1,700,000.

 

Is there a faster way to do this using Numeric?

 

-Alex Mont

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

Re: Efficiently removing duplicate rows from a 2-dimensional Numeric array

2007-07-19 Thread Matt McCredie

Could you use a set of tuples?


set([(1,2),(1,3),(1,2),(2,3)])

set([(1, 2), (1, 3), (2, 3)])

Matt

On 7/19/07, Alex Mont <[EMAIL PROTECTED]> wrote:


 I have a 2-dimensional Numeric array with the shape (2,N) and I want to
remove all duplicate rows from the array. For example if I start out with:

[[1,2],

[1,3],

[1,2],

[2,3]]



I want to end up with

[[1,2],

[1,3],

[2,3]].



(Order of the rows doesn't matter, although order of the two elements in
each row does.)



The problem is that I can't find any way of doing this that is efficient
with large data sets (in the data set I am using, N > 100)

The normal method of removing duplicates by putting the elements into a
dictionary and then reading off the keys doesn't work directly because the
keys – rows of Python arrays – aren't hashable.

The best I have been able to do so far is:



def remove_duplicates(x):

d = {}

for (a,b) in x:

d[(a,b)] = (a,b)

return array(x.values())



According to the profiler the loop takes about 7 seconds and the call to
array() 10 seconds with N=1,700,000.



Is there a faster way to do this using Numeric?



-Alex Mont

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

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

Re: How to check if an item exist in a nested list

2007-07-19 Thread zacherates
> One way is to check the length of each dimension. Does any body
> know a simpler way?

No need to check the length of the list:
"""
>>> foo = [0, 1, 2, [3, 4, 5, 6, 7, [8, 9, 10]]]
>>> isInNested(0, foo)
True
>>> isInNested(11, foo)
False
>>> isInNested(3, foo)
True
>>> isInNested(8, foo)
True
"""

def isInNested(k, l):
try:
if k in l:
return True

for i in l:
if isInNested(k, i):
return True
except TypeError:
#l is not iterable
pass

return False

if __name__ == "__main__":
   import doctest
   doctest.testmod()

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


Re: Data type conversion

2007-07-19 Thread Steve Holden
ervin ramonllari wrote:
> Hello everybody,
> 
> I'm trying to read some tables from a MS Access database and dump them 
> into a Postgres database.
> When I read the attributes data types, I get some numeric values, i.e. 
> if the data type
> of an attribute is TEXT, I get a value 202. I don't know how to convert 
> this number into
> a valid data type in Postgres. If someone can help me with this problem, 
> I would really
> appreciate that.
> 
> Thank you in advance,
> 
Given that you already have something that partly solves your problem 
you might be abel to ge thte rest of hte information you need from this 
Cookbook recipe:

   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52267

Hope it help!

regards
  Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd   http://www.holdenweb.com
Skype: holdenweb  http://del.icio.us/steve.holden
--- Asciimercial --
Get on the web: Blog, lens and tag the Internet
Many services currently offer free registration
--- Thank You for Reading -

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


Re: Python version changes, sys.executable does not

2007-07-19 Thread Jim Langston
"Jeffrey Froman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello All,
>
> I have two python versions installed, one in /usr/bin, and one in
> /usr/local/bin. However, when invoking python without a full path,
> I get the wrong executable with the right sys.executable string!
> 
> [EMAIL PROTECTED] ~]# ls -l /usr/local/bin/python*
> -rwxr-xr-x  2 root root 3783810 Jul 19 09:15 /usr/local/bin/python
> -rwxr-xr-x  2 root root 3783810 Jul 19 09:15 /usr/local/bin/python2.5
> -rwxr-xr-x  1 root root1281 Jul 19 09:16 
> /usr/local/bin/python2.5-config
> lrwxrwxrwx  1 root root  16 Jul 19 09:16 
> /usr/local/bin/python-config -> python2.5-config
>
> [EMAIL PROTECTED] ~]# ls -l /usr/bin/python*
> -rwxr-xr-x  2 root root 5396 May  2 16:28 /usr/bin/python
> lrwxrwxrwx  1 root root6 Jul 18 12:20 /usr/bin/python2 -> python
> -rwxr-xr-x  2 root root 5396 May  2 16:28 /usr/bin/python2.3
>
> [EMAIL PROTECTED] ~]# which python
> /usr/local/bin/python
>
> [EMAIL PROTECTED] ~]# /usr/local/bin/python -c "import sys; print 
> sys.executable; 
> print sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Jul 19 2007, 09:13:48)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]
>
> [EMAIL PROTECTED] ~]# env python -c "import sys; print sys.executable; print 
> sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Jul 19 2007, 09:13:48)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]
>
> [EMAIL PROTECTED] ~]# python -c "import sys; print sys.executable; print 
> sys.version; set()"
> /usr/local/bin/python
> 2.3.4 (#1, May  2 2007, 19:26:00)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]
> Traceback (most recent call last):
>  File "", line 1, in ?
> NameError: name 'set' is not defined
> -
>
>
> On a different machine, with same setup (as far as I can tell), I get the 
> expected
> results:
> -
> [EMAIL PROTECTED] ~]# /usr/local/bin/python -c "import sys; print 
> sys.executable; 
> print sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Feb  8 2007, 16:29:18)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]
>
> [EMAIL PROTECTED] ~]# env python -c "import sys; print sys.executable; print 
> sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Feb  8 2007, 16:29:18)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]
>
> [EMAIL PROTECTED] ~]# python -c "import sys; print sys.executable; print 
> sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Feb  8 2007, 16:29:18)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]
> -
>
> Can anyone tell me what might be causing the erroneous behavior in the 
> first example?

I think it's because your python directory is in the path before your 
python2.5 directory. 


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


Re: Python version changes, sys.executable does not

2007-07-19 Thread Jim Langston
"Jeffrey Froman" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Hello All,
>
> I have two python versions installed, one in /usr/bin, and one in
> /usr/local/bin. However, when invoking python without a full path,
> I get the wrong executable with the right sys.executable string!
> 
> [EMAIL PROTECTED] ~]# ls -l /usr/local/bin/python*
> -rwxr-xr-x  2 root root 3783810 Jul 19 09:15 /usr/local/bin/python
> -rwxr-xr-x  2 root root 3783810 Jul 19 09:15 /usr/local/bin/python2.5
> -rwxr-xr-x  1 root root1281 Jul 19 09:16 
> /usr/local/bin/python2.5-config
> lrwxrwxrwx  1 root root  16 Jul 19 09:16 
> /usr/local/bin/python-config -> python2.5-config
>
> [EMAIL PROTECTED] ~]# ls -l /usr/bin/python*
> -rwxr-xr-x  2 root root 5396 May  2 16:28 /usr/bin/python
> lrwxrwxrwx  1 root root6 Jul 18 12:20 /usr/bin/python2 -> python
> -rwxr-xr-x  2 root root 5396 May  2 16:28 /usr/bin/python2.3
>
> [EMAIL PROTECTED] ~]# which python
> /usr/local/bin/python
>
> [EMAIL PROTECTED] ~]# /usr/local/bin/python -c "import sys; print 
> sys.executable; 
> print sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Jul 19 2007, 09:13:48)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]
>
> [EMAIL PROTECTED] ~]# env python -c "import sys; print sys.executable; print 
> sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Jul 19 2007, 09:13:48)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]
>
> [EMAIL PROTECTED] ~]# python -c "import sys; print sys.executable; print 
> sys.version; set()"
> /usr/local/bin/python
> 2.3.4 (#1, May  2 2007, 19:26:00)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-8)]
> Traceback (most recent call last):
>  File "", line 1, in ?
> NameError: name 'set' is not defined
> -
>
>
> On a different machine, with same setup (as far as I can tell), I get the 
> expected
> results:
> -
> [EMAIL PROTECTED] ~]# /usr/local/bin/python -c "import sys; print 
> sys.executable; 
> print sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Feb  8 2007, 16:29:18)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]
>
> [EMAIL PROTECTED] ~]# env python -c "import sys; print sys.executable; print 
> sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Feb  8 2007, 16:29:18)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]
>
> [EMAIL PROTECTED] ~]# python -c "import sys; print sys.executable; print 
> sys.version; set()"
> /usr/local/bin/python
> 2.5 (r25:51908, Feb  8 2007, 16:29:18)
> [GCC 3.4.6 20060404 (Red Hat 3.4.6-3)]
> -
>
> Can anyone tell me what might be causing the erroneous behavior in the 
> first example?

er, of course I meant python2.3 before python2.5 


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


[2.5] Script to POST to web page with cookies?

2007-07-19 Thread Gilles Ganault
Hello

I need to write a script to automate fetching data from a web site:
1. using the POST method, log on, with login/password saved as cookies
2. download page and extract relevent information using regexes
3. log off
4. wait for a random number of minutes, and GOTO 1

I'm a bit confused with how to get POST and cookies in the same
script: 
- urllib vs urllib2 vs httplib?
- "ClientCookie.urlopen("www") behaves identically to urllib2.urlopen,
except that it deals with cookies automatically"

Has anyone some working code that I could borrow (er... steal) to do
this?

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


subprocess (spawned by os.system) inherits open TCP/UDP/IP port

2007-07-19 Thread alf

Hi,

I need a help with explaining following behavior. Although it is not 
python issue per say, python helped me to write sample programs and 
originally I encountered the issue using python software. So let's 
assume we have two following programs:



[myhost] ~> cat ss.py
import socket
UDPSock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDPSock.bind(("",12345))
import os
os.system('python cc.py')

[myhost] ~> cat cc.py
import time
time.sleep(2036)



then I start master one, do ctrl-Z and bg.

[myhost] ~> python ss.py

Suspended
[myhost] ~> bg
[1]python ss.py &
[myhost] ~> ps
UIDPID  PPID  C STIME TTY  TIME CMD
myuser00  3192  3189  0 14:57 pts/000:00:00 -tcsh
myuser00  3247  3192  0 14:57 pts/000:00:00 python ss.py
myuser00  3248  3247  0 14:57 pts/000:00:00 python cc.py



[myhost] ~> netstat -uanp |grep 12345
(Not all processes could be identified, non-owned process info
  will not be shown, you would have to be root to see it all.)
udp0  0 0.0.0.0:12345   0.0.0.0:* 
 3247/python



As expected netstat indicates process 3247 having port allocated. Then I 
kill the master process and interestingly the child inherits the port open.


[myhost] ~> kill 3247
[myhost] ~> netstat -uanp | grep 12345
(Not all processes could be identified, non-owned process info
  will not be shown, you would have to be root to see it all.)
udp0  0 0.0.0.0:12345   0.0.0.0:* 
 3248/python
[1]  + Terminatedpython ss.py



Why it is happening? I know that os.system uses fork, but still this is 
something unexpected.


Thx, Alf



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


Re: Newbie: freebsd admin scripting

2007-07-19 Thread Muffin
Thx for the advise.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: subprocess (spawned by os.system) inherits open TCP/UDP/IP port

2007-07-19 Thread Jeff McNeil

What's unexpected about it? Child processes inherit all of the open file
descriptors of their parent.  A socket is simply another open file
descriptor.  When your parent process exits, your child still holds a valid,
open file descriptor.

import sys
import socket
import os
import time

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, 0)
s.bind(('', ))

pid = os.fork()
if pid > 0:
   time.sleep(100)
elif pid == 0:
   time.sleep(100)

$ lsof | grep python | grep jeff | grep 
python13048  jeff3u IPv4 212689  UDP
*:
python13049  jeff3u IPv4 212689  UDP
*:

-Jeff

On 7/19/07, alf <[EMAIL PROTECTED]> wrote:



Hi,

I need a help with explaining following behavior. Although it is not
python issue per say, python helped me to write sample programs and
originally I encountered the issue using python software. So let's
assume we have two following programs:



[myhost] ~> cat ss.py
import socket
UDPSock=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
UDPSock.bind(("",12345))
import os
os.system('python cc.py')

[myhost] ~> cat cc.py
import time
time.sleep(2036)



then I start master one, do ctrl-Z and bg.

[myhost] ~> python ss.py

Suspended
[myhost] ~> bg
[1]python ss.py &
[myhost] ~> ps
UIDPID  PPID  C STIME TTY  TIME CMD
myuser00  3192  3189  0 14:57 pts/000:00:00 -tcsh
myuser00  3247  3192  0 14:57 pts/000:00:00 python ss.py
myuser00  3248  3247  0 14:57 pts/000:00:00 python cc.py



[myhost] ~> netstat -uanp |grep 12345
(Not all processes could be identified, non-owned process info
  will not be shown, you would have to be root to see it all.)
udp0  0 0.0.0.0:12345   0.0.0.0:*
 3247/python



As expected netstat indicates process 3247 having port allocated. Then I
kill the master process and interestingly the child inherits the port
open.


[myhost] ~> kill 3247
[myhost] ~> netstat -uanp | grep 12345
(Not all processes could be identified, non-owned process info
  will not be shown, you would have to be root to see it all.)
udp0  0 0.0.0.0:12345   0.0.0.0:*
 3248/python
[1]  + Terminatedpython ss.py



Why it is happening? I know that os.system uses fork, but still this is
something unexpected.


Thx, Alf



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

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

Re: Efficiently removing duplicate rows from a 2-dimensional Numeric array

2007-07-19 Thread Terry Reedy

"Alex Mont" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
I have a 2-dimensional Numeric array with the shape (2,N) and I want to
remove all duplicate rows from the array. For example if I start out
with:
[[1,2],
[1,3],
[1,2],
[2,3]]

I want to end up with
[[1,2],
[1,3],
[2,3]].
=

If you can define a 1-1 map of rows to ints (or even float or strings), you 
can put intsnumbers into a set and then convert (unique) items back to 
rows.  For example above, the obvious 10*r[0] + r[1] would do.  So would 
chr(r[0]) + chr(r[1]).  More generally, you need the min and max of the 
second numbers and not have them be too far apart/

tjr



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


Using eggs or py2exe to distribute apps

2007-07-19 Thread Marcus
Hi,

I'm to the stage where I need to deploy the app I built with wxPython. 
I've been able to successfully build it w/py2exe into a binary (about 
10MB size in total).

What I'd like to do is create an automatic updater, so that I can have 
users download updated versions of my *application code* without having 
to have them redownload everything (the interpreter, etc) via a complete 
redownload (I want to package some things as "components").

Eggs seem like an ideal solution, but I haven't had any luck using them 
in conjunction with py2exe.

It would seem that the most effective solution would be to package a 
python interpreter (with wxPython, etc already included) into the 
distributed app's directory and not use py2exe at all; however, since 
everything would be included in the distribution, it would seem that the 
full python distro would be huge (50MB at least), which defeats the 
purpose of wanting to build the app into "components".

Worst-case scenario would be to have them redownload the 10MB update 
each time, but that's less than ideal, since the audience for my program 
would have more frequent/less substantial updates over time, rather than 
big updates all at once.

Any guidance or suggestions are very much appreciated.

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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-19 Thread Juergen Erhard
On Thu, Jul 12, 2007 at 11:26:22AM -0700, Paul Rubin wrote:
> 
> Guy Steele used to describe functional programming -- the evaluation
> of lambda-calculus without side effects -- as "separation of Church
> and state", a highly desirable situation ;-).
> 
> (For non-FP nerds, the above is a pun referring to Alonzo Church, who
> invented lambda calculus in the 1920's or so).

Wow, I didn't realize I was an FP nerd :)

On proving programs correct... from my CS study days I distinctly
remember thinking "sure, you can prove it correct, but you cannot do
actual useful stuff with it".  We might have come a long way since
then (late 80s :P), but I don't hold out much hope (especially since
the halting problem does exist, and forever will).

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


Pickled objects over the network

2007-07-19 Thread Rustom Mody
Irmen de Jong wrote
> In what way would Pyro be overkill where Yaml (also a module that you need
> to install separately) wouldn't be?

Sure they are the same to install and sure pyro can do the job (pyro
is a nice package).

But I got the impression that the questioner wanted to do the
networking stuff himself at a low level (using sockets) and the data
management using some available library -- pickle.

Since pickle has problems
-- does not interface well with networking
-- security issues
-- has an xml option that according to the docs is an order of magnitude slower

I thought I would point out yaml (with safe-load) which sits somewhere
inbetween the xml-pickle and the default pickle.

I should also mention here that I find yaml is much more known and
used in the ruby and perl world than in the python world.  This is
unfortunate considering that both ruby and perl have a traditional
syntax (begin end, { } etc ).  On the other hand, python and yaml have
similar modern syntactic structures -- structure follows indentation
-- and are therefore well matched to each other.

So in summary the 'competition' is not between yaml and pyro -- pyro
could easily have a pickle-using-yaml option -- but between yaml and
xml.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: really small values

2007-07-19 Thread [EMAIL PROTECTED]
On Jul 19, 5:11?pm, Zentrader <[EMAIL PROTECTED]> wrote:
> On Jul 17, 2:13 pm, "Dee Asbury" <[EMAIL PROTECTED]> wrote:
>
> > In multiplying a value of xe^-325 with ye^-4, Python is returning zero. How
> > do I get it to give me back my tiny value?
>
> > Thanks!
> > Dee
>
> Also, Python's decimal class allows theoretically unlimited
> precision.  I have extremely limited knowledge here.  It gives the
> following for 2**-325.  I have no idea if the answer is correct.

Looks ok, you should get about 0.3 as many decimal digits as bits.

> You'll have to see if gmpy or decimal works better for this.  One
> piece of advice is to use whichever exclusively.  If you use a float
> and then covert to either one, the result will be corrupted.
> import decimal
> decimal.getcontext().prec = 375  ## set precision at 375
> print "2**-325 =", decimal.Decimal(str(2**-325))
>
> 2**-325 = 1.46302386084E-98

Interestingly, using str() causes you to lose precision.
>>> a = 2**-325
>>> a
1.463023860841312e-098
>>> b = str(a)
>>> b
'1.46302386084e-098'

Setting the precision to 375 didn't help because you
corrupted the value before you converted it to decimal.

Although the 375 will allow you to do this:

>>> a = decimal.Decimal('1e-325')
>>> b = decimal.Decimal('1e-4')
>>> a
Decimal("1E-325")
>>> b
Decimal("0.0001")
>>> a+b
Decimal("0.00011")


You can also do this in gmpy, although you set precision in bits, not
decimal digits.



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


Re: PEP 3107 and stronger typing (note: probably a newbie question)

2007-07-19 Thread John Nagle
Juergen Erhard wrote:
> On proving programs correct... from my CS study days I distinctly
> remember thinking "sure, you can prove it correct, but you cannot do
> actual useful stuff with it".  We might have come a long way since
> then (late 80s :P), but I don't hold out much hope (especially since
> the halting problem does exist, and forever will).

The halting problem only applies to systems with infinite memory.

Proof of correctness is hard, requires extensive tool support, and
increases software development costs.  But it does work.

Check out the "Spec#" effort at Microsoft for current work.
Work continues in Europe on Extended Static Checking for Java,
which was developed at DEC before DEC disappeared.

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


Re: How to check if an item exist in a nested list

2007-07-19 Thread Miles
Arash Arfaee wrote:
> is there any way to check if "IndexError: list index out of
> range" happened or going to happen and stop program from terminating?

Use a try/except block to catch the IndexError
http://docs.python.org/tut/node10.html#SECTION001030

try:
do_something_0(M_list[line][row][d])
except IndexError:
do_something_1()

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


Re: Open HTML file in IE

2007-07-19 Thread gravey
On Jul 19, 5:59 am, brad <[EMAIL PROTECTED]> wrote:
> gravey wrote:
> > Hello.
>
> > Apologies if this is a basic question, but I want to open a HTML
> > file from my local drive (is generated by another Python script)
> > in Internet Explorer. I've had a look at the webbrowser module and
> > this doesn't seem to be what I need. Any help much appreciated.
>
> You may try something like this example:
>
> import time
> import win32com.client
>
> wie = win32com.client.Dispatch('InternetExplorer.Application')
>
> # Make IE Window Visible.
> wie.Visible = 1
>
> # Open this URL
> wie.Navigate('www.your_url.com')
>
> # Print 'Busy' while Busy.
> while wie.Busy:
>  print 'Busy'
>
> # Sleep 2 secs, then go home.
> time.sleep(2)
> wie.GoHome()
>
> # Sleep 2 secs, then go back.
> time.sleep(2)
> wie.GoBack()
>
> # Refresh the page
> time.sleep(2)
> wie.Refresh()
>
> # Close IE Window
> time.sleep(2)
> wie.Quit()

Thanks to all who replied. All your approaches work but (!!) the HTML
page that I want to open contains Javascript that parses some
parameters
from the URL. The URL looks like this:

file:///C|/Temp/Google%20Maps/linktothis.htm?lat=45.0&lng=-20.0&zoom=4&type=k

The Javascript gets the URL from the Javascript location object and
parses it. I'm assuming that the location object has some kind of
Windows equivalent that might be set using win32com.client. Can anyone
shed any light on this?

Thanks



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


Re: Pickled objects over the network

2007-07-19 Thread Walker Lindley

Right, I could use Pyro, but I don't need RPC, I just wanted an easy way to
send objects across the network. I'm sure both Pyro and Yami can do that and
I may end up using one of them. For the initial version pickle will work
because we have the networking issues figured out with it, just not the
security problem. So we may end up just sending strings back and forth that
will let us fill out an object's member variables on the other end. It's
much less cool, but it seems like it'd be more secure.


-Walker

On 7/19/07, Rustom Mody <[EMAIL PROTECTED]> wrote:


Irmen de Jong wrote
> In what way would Pyro be overkill where Yaml (also a module that you
need
> to install separately) wouldn't be?

Sure they are the same to install and sure pyro can do the job (pyro
is a nice package).

But I got the impression that the questioner wanted to do the
networking stuff himself at a low level (using sockets) and the data
management using some available library -- pickle.

Since pickle has problems
-- does not interface well with networking
-- security issues
-- has an xml option that according to the docs is an order of magnitude
slower

I thought I would point out yaml (with safe-load) which sits somewhere
inbetween the xml-pickle and the default pickle.

I should also mention here that I find yaml is much more known and
used in the ruby and perl world than in the python world.  This is
unfortunate considering that both ruby and perl have a traditional
syntax (begin end, { } etc ).  On the other hand, python and yaml have
similar modern syntactic structures -- structure follows indentation
-- and are therefore well matched to each other.

So in summary the 'competition' is not between yaml and pyro -- pyro
could easily have a pickle-using-yaml option -- but between yaml and
xml.
--
http://mail.python.org/mailman/listinfo/python-list





--
This e-mail is licensed under the Creative Commons
Attribution-NoDerivs 2.5License. To view a copy of this license, visit
http://creativecommons.org/licenses/by-nd/2.5/ or send a letter to Creative
Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105,
USA.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Script to POST to web page with cookies?

2007-07-19 Thread Miki
Hello Gille,

> I need to write a script to automate fetching data from a web site:
> 1. using the POST method, log on, with login/password saved as cookies
> 2. download page and extract relevent information using regexes
> 3. log off
> 4. wait for a random number of minutes, and GOTO 1
> ...
http://wwwsearch.sourceforge.net/mechanize/

HTH,
--
Miki <[EMAIL PROTECTED]>
http://pythonwise.blogspot.com

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


Re: Interpreting os.lstat()

2007-07-19 Thread Martin v. Löwis
> (a) Running 'stat' is *not the same* as a system call.

Why do you say that? It is *exactly* the same, at least
on a POSIX system (on Windows, there is no stat, so the
implementation has to map that to several system calls).

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


  1   2   >