Re: don't understand popen2

2006-03-22 Thread Martin P. Hellwig
gry@ll.mit.edu wrote:

> 
> You gave it a single string, not a list(sequence) of strings.  Try
> something like:
> std_in.writelines(["notgood"])
> 

I got this output then:
 >>>
something:
Traceback (most recent call last):
   File "F:\coding\pwSync\popen_test\popen_test.py", line 8, in ?
 std_in.writelines(["notgood"])
IOError: [Errno 22] Invalid argument
 >>>
something:
Traceback (most recent call last):
   File "F:\coding\pwSync\popen_test\popen_test.py", line 8, in ?
 std_in.write("notgood")
IOError: [Errno 22] Invalid argument
 >>>

It seems that it doesn't matter.

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


searching imap mail folder but excluding one subfolder

2006-03-22 Thread Kevin F
I have code that searches under the default folder (inbox) but I would 
like to modify it to search for everything in that folder with the 
exception of one subfolder where I would like it not to search.

my current code is:


from imaplib import *
import getpass

server = IMAP4("webmail.x..edu")

server.login('username', getpass.getpass())

r = server.select("Inbox")

r, data = server.search(None, 'SUBJECT', 'WALLET ENLARGEMENT')
for num in data[0].split():
server.store(num, '+FLAGS', '\\Deleted')
server.expunge()


how do i modify it so that, for example, it searches in inbox but does 
not search in a specific subfolder 'opim' under inbox?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Programming challenge: wildcard exclusion in cartesian products

2006-03-22 Thread Dirk Thierbach
[EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> What are some good references for finite state machines? Minimization?

A classic is "Introduction to automata theory, languages and computation"
by Hopcroft and Ullman. But any other book about finite state machines
should cover these topics, too. There are good chances that you can just
google for a detailed explanation.

- Dirk

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


__slots__

2006-03-22 Thread David Isaac
1. "Without a __dict__ variable,
instances cannot be assigned new variables not listed in the __slots__
definition."

So this seemed an interesting restriction to impose in some instances,
but I've noticed that this behavior is being called by some a side effect
the reliance on which is considered unPythonic.  Why?

2. What is a simple example where use of slots has caused "subtle" problems,
as some claim it will?

3. What is a simple example of a Pythonic use of __slots__ that does NOT
involved the creation of **many** instances.

Thanks,
Alan Isaac


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


Re: Good thread pool module

2006-03-22 Thread Kinsley Turner
> There isn't a thread pool module in the standard library, but I'm sure 
> many have been written by people in the python community.
> Anyone have a favorite? Is there one particular implementation that's 
> recommended?
> 
> Not looking for anything fancy, just something that lets me queue up 
> tasks to be performed by a pool of threads and then retrieve results 
> when the tasks complete.


I wrote this one the other day, it doesn't save the results though.
You could probably just add to an output queue at the end of
threadFunction().  It was designed to handle short-running HTTP requests,
not larger jobs, this is reflected in the probablyIdle().


Use it like this:
pool.addJob(,,,...,)

e.g.:

def greet(times):
for i in range(times):
print "Hello World"

pool = ThreadPool(64)
poll.addJob(greet,3)
...




# -*- coding: iso-8859-1 -*-
import Queue
import thread

class ThreadPool:
"A pool of worker threads, efficiently waiting for a task" 
def __init__(self,max=0):
self.queue = Queue.Queue()
self.threads   = []
self.stopping  = False
self.max_threads   = 16

if (max > 0):
self.max_threads = max

### Start the threads up, waiting on the empty Queue
for i in range(self.max_threads):
 self.threads.append(thread.start_new_thread(self.threadFunction,()))

def addJob(self,function,*args,**kwargs):
self.queue.put((function,args,kwargs),True)

def threadFunction(self):
while (not self.stopping):
task = self.queue.get(True)
if (task != None):
function,args,kwargs = task
function(*args,**kwargs)
 
def probablyIdle(self):
return self.queue.empty()

def getApproximateQueueSize(self):
return self.queue.qsize()




Please consider our environment before printing this email.

WARNING - This email and any attachments may be confidential. If received in 
error, please delete and inform us by return email. Because emails and 
attachments may be interfered with, may contain computer viruses or other 
defects and may not be successfully replicated on other systems, you must be 
cautious. Westpac cannot guarantee that what you receive is what we sent. If 
you have any doubts about the authenticity of an email by Westpac, please 
contact us immediately.

It is also important to check for viruses and defects before opening or using 
attachments. Westpac's liability is limited to resupplying any affected 
attachments.

This email and its attachments are not intended to constitute any form of 
financial advice or recommendation of, or an offer to buy or offer to sell, any 
security or other financial product. We recommend that you seek your own 
independent legal or financial advice before proceeding with any investment 
decision.

Westpac Institutional Bank is a division of Westpac Banking Corporation, a 
company registered in New South Wales in Australia under the Corporations Act 
2001 (Cth). Westpac is authorised and regulated in the United Kingdom by the 
Financial Services Authority and is registered at Cardiff in the United Kingdom 
as Branch No. BR 106. Westpac operates in the United States of America as a 
federally chartered branch, regulated by the Office of the Comptroller of the 
Currency.

Westpac Banking Corporation ABN 33 007 457 141.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: LONG_BIT PROBLEM on Sun Solaris 5.8 linking python

2006-03-22 Thread Martin v. Löwis
Nancy wrote:
> I know there are lots of messages about this already posted but Im
> seeing this on Solaris 5.8. Sunfire
> I'm using the sun compiler. All the other messages blamed it on linux
> red hat gcc compilers and glib.  Thanks.

So what is the value of SIZEOF_LONG in pyconfig.h?
When you compile the file

#include 

LOOK HERE: LONG_BIT

with

cc -E -D_XOPEN_SOURCE=500 -D_XOPEN_SOURCE_EXTENDED=1 a.c

what output do you get after LOOK HERE?

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


Help: why python odbc module can not fetch all over?

2006-03-22 Thread zxo102
Hi everyone,
I need your help for using python odbc module. I have a simple
table defined as

create table A (
  userId char(10),
  courseid char(10),
  grade  integer,
  primary key(userId,courseId)
)

  userIdcourseId   grade
 1  1001 50
 1  1002 89
 2  1001 90
 2  1002 98

  in SQL server. Now I run the following query in SQL server Query
Analyzer:

select userId, grade from A  group by grade, userId order by userId
DESC compute count(userId), sum(grade) by userId

and got the results in two parts for each user in the Query Analyzer:
The results are shown like the following pattern

userId grade  < part1 results for user 1
  .  1   50
 1   89
-
 cnt sum   <--- part2 result for user 1
  2   139
===
 userId grade <--- part1 results for user 2
   2  90
   2  98
---
  cnt  sum <--- part2 results for user 2
   2188


But when I use python odbc to fetch the results from the database in
SQL server, I can only get part1 of results for user 2. All other
results are gone, for example, part2 for user 2 and all for user 1.

userId grade  < part1 results for user 2
  .  290
 298

Here is what I did:
>>> import odbc
>>> cc = odbc.odbc('dsn=student_info')
>>> c2=cc.cursor()
>>> c2.execute("select userId, grade from A  group by grade, userId order by 
>>> userId DESC compute count(userId), sum(grade) by userId")
>>> r = c2.fetchall()
>>> print r
[('2', 90), ('2', 98)]

Any body knows what is going on with python odbc module and how to get
"cnt" and "sum" in part 2 and others?

Thanks for your help in advance. I really appreciate that.

Ouyang

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


Embed Mozilla ActiveX Browser Control or MSIE the easy WAY!

2006-03-22 Thread sukhpalsingh
With this little DLL you can embed either Mozilla ActiveX Browser
Control or MSIE by just calling it's EmbedBrowser(HWND hwnd, int
i[0,1]) function. 0 = Mozilla Activex Browser Control and 1 = MSIE.

Other available methods include:
>> UnEmbedBrowser()

>> ResizeBrowser(HWND hwnd)
Where hwnd is an handle to a control where the browser
control is
embedded.

>> DisplayPage(STRING url)
Where url is a string that contains the URL of a
location to be
displayed.

>> DoPageActionGoBack()
>> DoPageActionGoForward()
>> DoPageActionRefresh()
>> DoPageActionStop()

You can download the DLL from:

http://embedbrowser.gurugranthji.com

Thanks for your attention!

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


Re: Good thread pool module

2006-03-22 Thread Raymond Hettinger
David Hirschfield wrote:
> There isn't a thread pool module in the standard library, but I'm sure
> many have been written by people in the python community.
> Anyone have a favorite? Is there one particular implementation that's
> recommended?

Because of the GIL, thread pools are not as useful in Python as you
might expect -- they execute one at a time and do not take advantage of
hyper-threading or multiple processors.  If that kind of efficiency is
what you are after, then take a look at PyLinda which can coordinate
communication between multiple instances of Python running in separate
threads:

http://www-users.cs.york.ac.uk/~aw/pylinda/

> Not looking for anything fancy, just something that lets me queue up
> tasks to be performed by a pool of threads and then retrieve results
> when the tasks complete.

FWIW, I wrote a small enchancement to the Queue module that makes it a
little bit easier to use a pool of worker threads and then be able to
tell when they are all done with processing:

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


Raymond

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


Re: C API: Testing my reference counting

2006-03-22 Thread Tim Peters
[lord trousers]
>>> Is there a way I can get hold of these kinds of statistics for
>>> debugging?

[Martin v. Löwis]
>> This is best done when Python is build in debug mode.
>> sys.gettotalrefcount then gives you the number of INCREF
>> calls for which no DECREF has been made; you said that
>> this shouldn't change.
>>
>> If it does change, sys.get_counts() will give you the
>> number of objects per type.
>>
>> Furthermore, sys.getobjects() will give you a list of
>> all objects allocated (excluding the result list).

[lord trousers]
> Wonderful! That's just what I was looking for.
>
> Is this kind of thing documented somewhere public? (As attributes that
> only show up in the debug build, they aren't documented in the regular
> library docs.) There might be more nifty goodies like this, and I'd
> like to check them out.

Actually, sys.getcounts() only exists in a COUNT_ALLOCS build (which
can be combined with a debug build, but is not implied by a debug
build).

All that (and other esoterica) is documented in
Misc/SpecialBuilds.txt, in any Python source distribution.  The Python
Windows installer does not contain that file.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: multiple assignment

2006-03-22 Thread Anand
>> Wouldn't it be nice to say
>> id, *tokens = line.split(',')
>
>
> id, tokens_str = line.split(',', 1)

But then you have to split tokens_str again.

id, tokens_str = line.split(',', 1)
tokens = tokens_str.split(',')

this is too verbose.

anand

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


removing file by inode

2006-03-22 Thread s99999999s2003
hi
this is pertain to unix environment.
is it possible to remove a file by it's inode and not it's filename
using Python? Just curious...
thanks.

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


Re: C API: Testing my reference counting

2006-03-22 Thread lord trousers
Martin v. Löwis wrote:
> lord trousers wrote:
> > Is there a way I can get hold of these kinds of statistics for
> > debugging?
>
> This is best done when Python is build in debug mode.
> sys.gettotalrefcount then gives you the number of INCREF
> calls for which no DECREF has been made; you said that
> this shouldn't change.
>
> If it does change, sys.get_counts() will give you the
> number of objects per type.
>
> Furthermore, sys.getobjects() will give you a list of
> all objects allocated (excluding the result list).
>
> HTH,
> Martin

Wonderful! That's just what I was looking for.

Is this kind of thing documented somewhere public? (As attributes that
only show up in the debug build, they aren't documented in the regular
library docs.) There might be more nifty goodies like this, and I'd
like to check them out.

Thanks again!

Neil

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


Re: don't understand popen2

2006-03-22 Thread Donn Cave
Quoth gry@ll.mit.edu:
| Martin P. Hellwig wrote:
...
|> import popen2
|>
|> std_out, std_in = popen2.popen2("testia.py")
|>
|> x=std_out.readline()
|> print(x)
|>
|> std_in.writelines("notgood")
|>
|> x=std_out.readline()
|> print(x)
...
|> Traceback (most recent call last):
|>File "F:\coding\pwSync\popen_test\popen_test.py", line 8, in ?
|>  std_in.writelines("notgood")
|> IOError: [Errno 22] Invalid argument
|>  >>>
...

| You gave it a single string, not a list(sequence) of strings.  Try
| something like:
| std_in.writelines(["notgood"])

Did you try it?  For me, writelines(string) works fine.  Since in
Python, a string is in a sense a sequence of strings, this doesn't
even really contradict the documentation -

| ... The sequence can be any iterable object producing strings.

Anyway, it seems unlikely he would get that INVARG error for this
reason.  That's an error from the host operating system, not the
interpreter, and it mostly likely refers to the file descriptor.
Since it works for me, I guess his problem is basically this:

|> (python 2.4 + win32 extensions on XPProSP2)

Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: need SOAPpy help

2006-03-22 Thread Ravi Teja
Did you read
http://diveintopython.org/soap_web_services/index.html ?
and specifically
http://diveintopython.org/soap_web_services/introspection.html ?

These docs are slightly dated but I doubt much has changed. If there is
a problem, you can always try the older version from the site.

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


Re: UML from py sources

2006-03-22 Thread Ravi Teja
Not to interrupt the valuable lesson with Google :-)
Boa Constructor.

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


Re: Can't get the real contents form page in internet as the tag "no-chche"

2006-03-22 Thread I V
dongdong wrote:
> using web browser can get page's content formally, but when use
> urllib2.open("http://tech.163.com/2004w11/12732/2004w11_1100059465339.html";).read()
>
> the result is
>
>  CONTENT="0;URL=http://tech.163.com/04/1110/12/14QUR2BR0009159H.html";>

This line here instructs the browser to go to
http://tech.163.com/04/1110/12/14QUR2BR0009159H.html . If you try
loading that with urllib2, do you get the right content?

If the people behind that web page new how to use the web, they
wouldn't use the META HTTP-EQUIV hack,  and instead would have
instructed their web server to return a 300 redirect response, which
would have allowed urllib2 to follow the redirect and get the right
content automatically. If you have any influence with them, you could
try and persuade them to set up their web server properly.

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


Re: Using PyExcelerator

2006-03-22 Thread John Machin
On 23/03/2006 9:01 AM, [EMAIL PROTECTED] wrote:
> I have just installed PyExcelerator, and now want to use it to read
> Excel spreadsheets with a variable number of rows and columns and with
> multiple sheets. Unfortunately, no documentation seems to accompany
> PyExcelerator. Does anyone know of a good source of documentations
> and/or examples? The author provides some examples, but these tend to
> involve writing data into spreadsheets one cell at a time.
> 

Thomas,
Look at pyExcelerator's tools/xls2*.py for examples
or
Look at the xlrd package (which doesn't *write* xls files, but does read 
them tolerably well -- even if I do say so myself -- and has documentation).
http://cheeseshop.python.org/pypi/xlrd

What do you mean by "with a variable number of rows and columns"?

Cheers,
John


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


Re: newbie question

2006-03-22 Thread John Machin
On 23/03/2006 1:53 PM, Kevin F wrote:
> what does it mean when there are [0] or [1] after a variable?
> 
> e.g. print 'Message %s\n%s\n' % (num, data[0][1])

Here's the section in the Python Tutorial that should answer your question:

http://docs.python.org/tut/node5.html#SECTION00514

You may like to start at the *beginning* of the Tutorial :-)

... or you might like to ask another question, stating your experience 
if any with other languages, what you want to do with Python, and asking 
for general advice on how to learn Python.

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


Re: Can't get the real contents form page in internet as the tag "no-chche"

2006-03-22 Thread dongdong
yeah,u r right, the page uses chinese.(I'm a chinese too.^_^,)

using urllib2.urlopen('').read(),I can't get the contents
between '' and '' ,the reason isn't the chinese encoding
but the 'no-cache' set,I think.

I want to get the contents between

can you find the problem why i can't read the contents? thanks.

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


Re: years later DeprecationWarning

2006-03-22 Thread Enigma Curry
> (That long-gone guy is actually me, according to the notes in the program.
> However those brain cells are long gone now, so it might as well not be me.)

I had a great long laugh with this bit. I guess it's because I can
relate so well :)

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


newbie question

2006-03-22 Thread Kevin F
what does it mean when there are [0] or [1] after a variable?

e.g. print 'Message %s\n%s\n' % (num, data[0][1])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: UML from py sources

2006-03-22 Thread skip

sbaush> Hi all, i'm searching for a tool that draw the UML of a python
sbaush> project. Have you idea about the best way to do it? I prefer a
sbaush> Linux tool, but it's the same, i have only a little bit of
sbaush> time...

Did you try Googling for "UML from Python"?

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


Re: Can't get the real contents form page in internet as the tag "no-chche"

2006-03-22 Thread Kent Johnson
dongdong wrote:
> using web browser can get page's content formally, but when use
> urllib2.open("http://tech.163.com/2004w11/12732/2004w11_1100059465339.html";).read()
> 
> the result is
> 
>  CONTENT="0;URL=http://tech.163.com/04/1110/12/14QUR2BR0009159H.html";>
>  content="no-cache">?y?ú'ò?aò3??...

The page is in Chinese (I think), when you print the data it is printing 
in your console encoding which is apparently not Chinese. What did you 
expect to see?

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


Re: don't understand popen2

2006-03-22 Thread gry

Martin P. Hellwig wrote:
> Hi all,
>
> I was doing some popen2 tests so that I'm more comfortable using it.
> I wrote a little python script to help me test that (testia.py):
>
> -
> someline = raw_input("something:")
>
> if someline == 'test':
>  print("yup")
> else:
>  print("nope")
> -
>
> And another little thing that does it's popen2 stuff:
>
> -
> import popen2
>
> std_out, std_in = popen2.popen2("testia.py")
>
> x=std_out.readline()
> print(x)
>
> std_in.writelines("notgood")
>
> x=std_out.readline()
> print(x)
> -
>
> Now what I expected was that I got the return one the first line:
> "something:" and on the second "nope", but instead of that I got:
>
>  >>>
> something:
> Traceback (most recent call last):
>File "F:\coding\pwSync\popen_test\popen_test.py", line 8, in ?
>  std_in.writelines("notgood")
> IOError: [Errno 22] Invalid argument
>  >>>
>
> I played around a bit with flush, write and the order of first writing
> and then reading, the best I can get is no error but still not the
> expected output. I googled a bit copied some examples that also worked
> on my machine, reread the manual and the only conclusion I have is that
> I don't even understand what I'm doing wrong.
>
> Would you please be so kind to explain my wrong doing?
> (python 2.4 + win32 extensions on XPProSP2)

>>> help(sys.stdin.writelines)
Help on built-in function writelines:

writelines(...)
writelines(sequence_of_strings) -> None.  Write the strings to the
file.

Note that newlines are not added.  The sequence can be any iterable
object
producing strings. This is equivalent to calling write() for each
string>

You gave it a single string, not a list(sequence) of strings.  Try
something like:
std_in.writelines(["notgood"])

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


need SOAPpy help

2006-03-22 Thread Sells, Fred
I've just been asked to do a soap client for some vendor software.  I'm able
to load the WSDL and discover the methods, but when I go to call a method it
doesn't see it.  I should be passing in a string that is named "testValue"

I've been working from the soap demoes with soappy 0.12.0.  I've found so
much via google that I don't know where to start or what matches this
version of soappy and what is based on older releases.  

I would appreciate some links or code snippets that illustrate using soap
0.12.0.  

I apologize for not including my code, but I'm on a different computer
tonight.

---
The information contained in this message may be privileged and / or
confidential and protected from disclosure. If the reader of this message is
not the intended recipient, you are hereby notified that any dissemination,
distribution or copying of this communication is strictly prohibited. If you
have received this communication in error, please notify the sender
immediately by replying to this message and deleting the material from any
computer.
---
-- 
http://mail.python.org/mailman/listinfo/python-list


Can't get the real contents form page in internet as the tag "no-chche"

2006-03-22 Thread dongdong
using web browser can get page's content formally, but when use
urllib2.open("http://tech.163.com/2004w11/12732/2004w11_1100059465339.html";).read()

the result is

http://tech.163.com/04/1110/12/14QUR2BR0009159H.html";>
?y?ú'ò?aò3??...

,I think the reson is the no-cache, are there person would help me?

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


Re: import random module

2006-03-22 Thread Carl Banks
Ben Finney wrote:
> "DataSmash" <[EMAIL PROTECTED]> writes:
> > * random.py:
> >
> > import random
>
> Now that you've tripped over this ambiguity of Python's current
> 'import' behaviour, you may be interested to know that the behaviour
> will change to solve this:
>
> http://www.python.org/dev/peps/pep-0328/>

I don't believe this change will solve the problem at hand, at least
there's nothing in the PEP that says it will.  "import random" is an
absolute import even in random.py is in the current directory, because
current directory is in sys.path.  Unless there's a change sys.path
planned, the shadowing should still happen.


Carl Banks

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


Re: Spidering Hacks for Python, not Perl

2006-03-22 Thread John J. Lee
[EMAIL PROTECTED] writes:

> O'Reilly's Spidering Hacks books terrific. One problem. All the code
> samples are in Perl. Nothing Pythonic. Is there a book out there for
> Python which covers spidering / crawling in depth?

A fair number of the examples in that book use WWW::Mechanize.  I
ported that to Python (it has evolved a bit since then):

http://wwwsearch.sf.net/mechanize


The distribution includes an example from the book ported to Python,
in fact -- porting other examples should be fairly straightforward.

A stable release of mechanize is (finally!) coming soon(-ish).


John

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


Re: Dynamically growing numarray array.

2006-03-22 Thread Carl Banks
Ivan Vinogradov wrote:
> Hello All,
>
> this seems like a trivial problem, but I just can't find an elegant
> solution neither by myself, nor with google's help.
>
> I'd like to be able to keep an array representing coordinates for a
> system of points.
> Since I'd like to operate on each point's coordinates individually,
> for speed and ufuncs
> numarray fits the bill perfectly, especially since system.coordinates
> [4] would return proper vector for a 5th point.
> To start, read the coordinates from a text file and add them to our
> array one by one.
> Here it gets un-elegant and probably wasteful for a large number of
> points, by converting the whole array to a list only to use append
> method and then convert it back to array(sample code below). Also,
> there is potential need to add more points later on.
>
> Any pointers would be greatly appreciated.

Very simple thing to do, actually.  The following class implements a
very basic array grower for an array of 3-D points:

class ArrayGrower(object):
def __init__(self,initsize=100):
self.memarray = zeros((initsize,3),Float)
self.npoints = 0
def add_point(self,point):
if self.npoints >= len(self.memarray):
oldlen = len(self.memarray)
newmemarray = zeros((oldlen*2,3),Float)
newmemarray[:oldlen] = self.memarray
self.memarray = newmemarray
self.memarray[self.npoints] = point
self.npoints += 1
def get_current_array(self):
return self.memarray[:self.npoints]

It simply uses a slice of a larger array to hold all your points.  It
keeps track of the number of points and automatically grows the array
when there's no room to add another point.  (You can use a factor less
than 2 if you have to conserve memory.)  Whenever you need the current
array for a calculation, use get_current_array() to get an array slice
of the proper size.

>>> x = ArrayGrower(2)
>>> x.add_point([0,1,2])
>>> x.get_current_array()
array([   [ 0.,  1.,  2.]])
>>> x.add_point([0,0,0])
>>> x.add_point([1,1,1])
>>> x.get_current_array()
array([[ 0.,  1.,  2.],
   [ 0.,  0.,  0.],
   [ 1.,  1.,  1.]])


Carl Banks

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


Re: python linking

2006-03-22 Thread Serge Orlov

Nancy wrote:
> When i link with python2.4.a i get this error.
>
> ld: Dwarf Error: Invalid or unhandled FORM value: 14.
>
> I am NOT  using the gcc compiler but the linux icc compiler. Google
> hits blame it on gcc compiler binutils being out of date. i dont think
> thats the problem here.
> thanks.

And how was python2.4.a was built? with gcc? If you mix compilers you
always risk to hit corner cases of integration that compiler writers
have not debugged.

  Serge.

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


UML from py sources

2006-03-22 Thread Sbaush
Hi all, i'm searching for a tool that draw the UML of a python project. Have you idea about the best way to do it? I prefer a Linux tool, but it's the same, i have only a little bit of time...
-- Sbaush

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

UML from py sources

2006-03-22 Thread Sbaush
Hi all, i'm searching for a tool that draw the UML of a python project. Have you idea about the best way to do it? I prefer a Linux tool, but it's the same, i have only a little bit of time...-- Sbaush
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: COM Client / Server creation?

2006-03-22 Thread John J. Lee
"Dan" <[EMAIL PROTECTED]> writes:

> Ive got the chapter from the net on COM. It looks pretty old, 2000.
> Also the very first example in the chapter on COM doesn't seem to work.
> Is what I am wanting to do possible with Python?

As long as you're doing IDispatch, essentially anything is possible
with pywin32's COM support.

What went wrong with the first example in the book?

Not covered in the book, and particularly useful for implementing
native clients and servers is ctypes / comtypes (but still not stable;
also, I've only personally used it for writing a client, and a very
simple one at that):

http://starship.python.net/crew/theller/ctypes/com.html


John

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


Re: Use of Python with GDAL. How to speed up ?

2006-03-22 Thread Serge Orlov
Julien Fiore wrote:
> Thanks for the psyco information, Serge.
>
> > 2) Rewrite the code to be vectorized (don't use psyco) Right now your
> > code *doesn't* get any speed benefit from numpy
>
> I do not understand this point. How to rewrite the code ?

vectorized code means one operation work on multiple items. Here is
three variants of the most easy part of your function (i'm sure this
part is not hot, it's just an example, the hottest part I'm pretty sure
is the *whole* openness loop)

setup = """
import numpy, array
R = 4
winSize= 2*R + 1
cellSizeX = 11
cellSizeY = 23
"""
code1 = """
dist=numpy.zeros((winSize,winSize),float)
for i in range(winSize):
for j in range(winSize):
dist[i][j]=numpy.sqrt((cellSizeX*(i-R))**2
+(cellSizeY*(j-R))**2)
"""
code2 = """
ind = numpy.indices((winSize,winSize))
dist = numpy.sqrt((cellSizeX*(ind[0]-R))**2 +(cellSizeY*(ind[1]-R))**2)
"""
code3 = """
dist=array.array('f',chr(0)*(4*winSize*winSize))
for i in range(winSize):
for j in range(winSize):
dist[i*winSize+j]=((cellSizeX*(i-R))**2
+(cellSizeY*(j-R))**2)**0.5
"""

The first one is original, the second is vectorized, the last one is
using array.array. Here is the timing in microseconds for R=1,2,5,6,50

68.2184467579
95.1533784322
17.6263407779
>>>
173.079790867
108.401514718
39.155870369
>>>
802.235479649
174.977043172
161.933094849
>>>
1126.00120965
206.326781756
221.849145632
>>>
67636.3336681
6736.00415695
12675.9099271
>>>

As you see if R >=6 vectorized version is the fastest, otherwise
array.array is faster. You should also try psyco + array.array

> Do you mean in C ?

I didn't mean it, but it's also an option if you need the best speed.
You can try pyrex first, before resorting to raw C.

  Serge.

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


don't understand popen2

2006-03-22 Thread Martin P. Hellwig
Hi all,

I was doing some popen2 tests so that I'm more comfortable using it.
I wrote a little python script to help me test that (testia.py):

-
someline = raw_input("something:")

if someline == 'test':
 print("yup")
else:
 print("nope")
-

And another little thing that does it's popen2 stuff:

-
import popen2

std_out, std_in = popen2.popen2("testia.py")

x=std_out.readline()
print(x)

std_in.writelines("notgood")

x=std_out.readline()
print(x)
-

Now what I expected was that I got the return one the first line: 
"something:" and on the second "nope", but instead of that I got:

 >>>
something:
Traceback (most recent call last):
   File "F:\coding\pwSync\popen_test\popen_test.py", line 8, in ?
 std_in.writelines("notgood")
IOError: [Errno 22] Invalid argument
 >>>

I played around a bit with flush, write and the order of first writing 
and then reading, the best I can get is no error but still not the 
expected output. I googled a bit copied some examples that also worked 
on my machine, reread the manual and the only conclusion I have is that 
I don't even understand what I'm doing wrong.

Would you please be so kind to explain my wrong doing?
(python 2.4 + win32 extensions on XPProSP2)

Thanks in advance!

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


Re: a problem to solve

2006-03-22 Thread [EMAIL PROTECTED]

John Salerno wrote:
> Ok, here's a problem I've sort of assigned to myself for fun, but it's
> turning out to be quite a pain to wrap my mind around. It's from a
> puzzle game. It will help if you look at this image:
>
> http://www.johnjsal.devisland.net/switches.jpg
>
> Here's the situation: Each of the four rows in the diagram is considered
> a single 'panel'. Each panel has eight 'switches', which are composed of
> two columns each, and these columns have a total of 20 lights (10 in one
> column, 10 in the other). The picture hopefully makes this description
> clear.
>
> The shaded boxes denote which lights turn on when you select that
> particular switch. So, the very first switch in the first row, if turned
> on, would turn on the first four lights, not the fifth, turn on the
> sixth, not the seventh, and turn on 8-14, etc. up to the 20th light.
>
> You can only turn on one switch per panel, so eventually you will have
> four switches lit.
>
> What you are shooting for is to find a combination of four switches so
> that exactly three lights in the same location are lit, no more or less.
> So turning on the first switch in each row would not work, because that
> would mean that the second light in each switch would be lit, and you
> can't have all four lit, just three.
>
> So anyway, the reason I describe all this isn't so you can solve it for
> me, because I really want to figure it out. I just was hoping you can
> give me some tips as to how to implement the algorithm. Maybe Python has
> some functions that I can use to make it easier than it seems.
>
> My plan right now is to do a comparison of panel 1, switch 1, light 1
> with panel 2, switch 1, light 1, then panel 3, switch 1, light 1, etc.,
> which sounds scary. I didn't know if Python had a way to compare the
> whole switch in one step, perhaps.
>
> Also, I was wondering how I might implement the switches as data
> structures. Right now I have them as a list of 32 strings, but I thought
> maybe some type of bitwise comparisons could help.

Then you'll want to represent the lights as a 20-bit binary number.

Each bit position corresponds to 4 lamps, so there are 16 possible
ways those 4 lamps could be lit. Construct a truth table and see which
of the outcomes have exactly 3 lit.

A   B   C   D   Y
0   0   0   0   0
0   0   0   1   0
0   0   1   0   0
0   0   1   1   0
0   1   0   0   0
0   1   0   1   0
0   1   1   0   0
0   1   1   1   1
1   0   0   0   0
1   0   0   1   0
1   0   1   0   0
1   0   1   1   1
1   1   0   0   0
1   1   0   1   1
1   1   1   0   1
1   1   1   1   0

The boolean equation (where  ~ means NOT,  + means OR,  x means XOR)
for Y is thus

Y = ~ABCD + A~BCD + AB~CD + ABC~D

which can be reduced to

Y = CD(AxB) + AB(CxD)

You'll need to do that for each bit position.

Now for each combination of four switches, look for one that
gives you  when you calculate the
20 Y values.

For eaxample, the first switch in each panel (using hex)
would be:

>>> A1 = 0xf5fdc
>>> B1 = 0xddb7d
>>> C1 = 0xf33bd
>>> D1 = 0x77edb

>>> Y = ((C1 & D1) & (A1 ^ B1)) | ((A1 & B1) & (C1 ^ D1))
>>> Y
674245

But which positions have 3 lights lit?

Printing Y in base 2 will tell us:

>>> import gmpy
>>> print gmpy.digits(Y,2)
10100100100111000101

Now you'll want A,B,C,D to be lists and adjust the formula for Y
accordingly. Then simply try every combination of ABCD.


>
> Anyway, any advice for how to proceed would be great! I hope I described
> it well enough.

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


Re: Uploading files from IE

2006-03-22 Thread Tim Williams (gmail)
On 22/03/06, AB <[EMAIL PROTECTED]> wrote:
>> try something like this:> filename = os.path.basename(fullpathname)
I tried the following with the same result:myName = ulImage.filenamenewFile = file (os.path.join(upload_dir, os.path.basename(myName)), 'wb')Any other ideas?  Seems like it shouldn't be a browser issue though...


In Karrigell,  this upload script works in IE and firefox,   and the basics are similar to yours.

import os
f = _myfile.file # file-like object
dest_name = os.path.basename(_myfile.filename)
out = open('c:/WINNT/Profiles/tw/Desktop/webupload/'+dest_name,'wb')
# copy file
import shutil
shutil.copyfileobj(f,out)
out.close()
print "File Uploaded Succesfully" #print to browser

Maybe your cgi is returning something strange, have you tried some
print statements to see what's going on at various parts of the script ?

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

Re: Uploading files from IE

2006-03-22 Thread AB

"Irmen de Jong" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> AB wrote:
>> All right... I already hated IE.  But, now I do even more.  My scripts 
>> upload function is working in Firefox, but not in IE.  If I upload a file 
>> from Internet Explorer I get a file on the system named for the full path 
>> from the users computer...
>>
>> example...
>> They user uploads C:\mydocs\test.jpg
>> it ends up at /path/to/webdir/C:\mydocs\test.jpg
>> instead of /path/to/webdir/test.jpg
>
> try something like this:
> filename = os.path.basename(fullpathname)

I tried the following with the same result:
myName = ulImage.filename
newFile = file (os.path.join(upload_dir, os.path.basename(myName)), 'wb')

Any other ideas?  Seems like it shouldn't be a browser issue though... 


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


Re: a problem to solve

2006-03-22 Thread Claudio Grondi
John Salerno wrote:
> Ok, here's a problem I've sort of assigned to myself for fun, but it's 
> turning out to be quite a pain to wrap my mind around. It's from a 
> puzzle game. It will help if you look at this image:
> 
> http://www.johnjsal.devisland.net/switches.jpg
> 
> Here's the situation: Each of the four rows in the diagram is considered 
> a single 'panel'. Each panel has eight 'switches', which are composed of 
> two columns each, and these columns have a total of 20 lights (10 in one 
> column, 10 in the other). The picture hopefully makes this description 
> clear.
> 
> The shaded boxes denote which lights turn on when you select that 
> particular switch. So, the very first switch in the first row, if turned 
> on, would turn on the first four lights, not the fifth, turn on the 
> sixth, not the seventh, and turn on 8-14, etc. up to the 20th light.
> 
> You can only turn on one switch per panel, so eventually you will have 
> four switches lit.
> 
> What you are shooting for is to find a combination of four switches so 
> that exactly three lights in the same location are lit, no more or less. 
> So turning on the first switch in each row would not work, because that 
> would mean that the second light in each switch would be lit, and you 
> can't have all four lit, just three.
> 
> So anyway, the reason I describe all this isn't so you can solve it for 
> me, because I really want to figure it out. I just was hoping you can 
> give me some tips as to how to implement the algorithm. Maybe Python has 
> some functions that I can use to make it easier than it seems.
> 
> My plan right now is to do a comparison of panel 1, switch 1, light 1 
> with panel 2, switch 1, light 1, then panel 3, switch 1, light 1, etc., 
> which sounds scary. I didn't know if Python had a way to compare the 
> whole switch in one step, perhaps.
> 
> Also, I was wondering how I might implement the switches as data 
> structures. Right now I have them as a list of 32 strings, but I thought 
> maybe some type of bitwise comparisons could help.
> 
> Anyway, any advice for how to proceed would be great! I hope I described 
> it well enough.

1. implement the switches as a list of integers composed out of bits for 
each light (1 for light turned on, 0 for off).
2. you can find if four lights are turned on by doing bit comparison of 
four integers (the & operator). If you get as result a non-zero value 
you know, that there are four lights in same location switched on
3. run a loop over the first eight switches and in this loop a loop over 
the second row, etc., so that you get all possible arrangement tested 
(four nested loops)
4. if you find a case the four switches gives a zero value, test if you 
have exactly three ligths on

You need to know:
   what is a list of integers
   how to do bitwise and with integers (the & operator)
   how to loop over list elements using their index
 ( e.g with "for listIndex in range(0,8):")
   how to set single bits of an integer
 ( e.g. intVal | 0x01, intVal | 0x02, intVal | 0x04, etc. )

Hope this helps

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


Re: Why "class exceptions" are not deprecated?

2006-03-22 Thread rurpy

Fredrik Lundh wrote:
> Gregory Petrosyan wrote:
>
> > 1) From 2.4.2 documentation:
> > There are two new valid (semantic) forms for the raise statement:
> > raise Class, instance
> > raise instance
> >
> > 2) In python:
> > >>> raise NameError
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > NameError
> > >>> help(NameError)
> > Help on class NameError in module exceptions: ...
> > >>> raise 0
> > Traceback (most recent call last):
> >   File "", line 1, in ?
> > TypeError: exceptions must be classes, instances, or strings
> > (deprecated), not i
> > nt
> >
> > So, if it's a bug in documentation, it should be corrected. Otherwise,
> > (IMHO!) raising classes should be deprecated.
>
> it could be that the tutorial author expected you to read chapter 8
> before you read chapter 9, and used "new" to mean forms that hadn't
> already been described:
>
> http://docs.python.org/tut/node10.html
>
> > Does raising class make sence? As for me, I can't find any usefull
> > case for it.
>
> as explained in the language reference,
>
> raise Class
>
> is the same thing as
>
> raise Class()

The OP points out an ambiguity in the docs, and as usual,
gets told he can't read, etc.  How typical.  Maybe if comments
like this were encouraged and acted upon, the docs would be
a little better than they are.  But I guess the current practice
of intimidation has benefits too in that it allows the response,
"nobody has complained, so the docs must be really great
and we can go on writing Python instead of that grungy
English."

And maybe if there were a decent language reference manual
people wouldn't be so inclined to use the Tutorial as one, with
the resultant out-of-sequence reading.

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


Re: Python equivalent of Perl-ISAPI?

2006-03-22 Thread rurpy

[EMAIL PROTECTED] wrote:
> Atanas Banov wrote:
> > [EMAIL PROTECTED] wrote:
> > > Steve Holden wrote:
> > > > [EMAIL PROTECTED] wrote:
> > >
> > > > > Pure cgi is too slow.  "Active Scripting" means ASP, yes?
> > > > > I need something that will do cgi scripts (a lot of which I already
> > > > > have
> > > > > and can modify but don't want to rewrite extensively, partly because
> > > > > of time issues, partly because I want to preserve some degree of
> > > > > portability back to a unix environment.).   I want something that does
> > > > > for IIS what mod_python does for apache.  Fastcgi looked scary even
> > > > > on unix plaforms, seems like an act of desperation on Windows,
> > > > >
> > > > Yes, ASP is Active Scripting.
> > > >
> > > Except I need cgi, not asp, for the reasons i gave.
> >
> > it seems to me you have no clear idea what you need.
> >
> > you say you have a lot of CGIs written but you don't clarify if that is
> > Python or Perl. since you look for python intergration, it seems they
> > are in python, however in previous posting you say you'll have to
> > revert to Perl for solution. it just doesnt make sense! if you use
> > Perl, you will have to REWRITE the scripts and if you do so, it's
> > unclear why wouldnt you use a superior technology like PHP/ASP/JSP -
> > any of those is way easier to manage.
> >
> > it's also unclear why don't you use apache on windows, if mod_python is
> > your poison.
> >
> > here is how i imagine you have the layers:
> >[scripts (CGI?)]
> >[glue]
> >[web server (IIS?)]
> >
> > where the discussion is about the "glue" between them. you say CGI is
> > too slow for you, so you will want something maintaining the CGI
> > programming model, but faster. this thing is called FastCGI - but you
> > are unhappy about it either. there is no way any perl "glue" can solve
> > your problem between your web server and your python scripts
> > whatsoever. you'll have to re-code the scripts for perl.
>
> The final solution must run in a Windows/IIS environment.
> Those are part of the requirements which I do not control.
> There is code in both Perl and Python.  I wrote the Python
> stuff and inherited the Perl stuff.  It is not web-based now
> but conversion to generate html output instead of text is
> probably straightforward.  Additional requirement is that
> is should be movable to unix without too much work.
> The layers are:
>
> [database] [equipment interface]
> [glue]
> [cgi]
> [webserver - IIS]
>
> As fo PHP/ASP/JSP?  I am doing all the work.  I know Perl
> and Python.  I don't know PHP/JSP.   (Also, JSP will require
> a lot of new Java infrastructure support, yes?)  As for ASP,
> I wonder about the "easily moved to unix" requirement.
> (I know apache has an asp module but I don't know if other
> web servers do, or how compatible apache's is, and I don't
> know if I have time to reliably answer those questions.)
> Why do you say PHP/JSP/ASP are superior technologies?
>
> All I want to do is avoid the cost of starting a new Python
> (or Perl) interpreter on each page request.  This is what
> I understand Perl-isapi and Perl-Ex does.  My question
> is simply if there is something similar for Python.
> I have concluded the answer is no but hope I'm wrong.

Din't find anything more and no further replies
here so here is a quick timing I did...
  Perl-Ex:0.014 sec/page
  Perl-ISAPI: 0.168 sec/page
  Perl-cgi:   0.187 sec/page
  Python-cgi: 0.286 sec/page

I can't ignore the 20X better performance of
Perl-Ex vs Python, so I guess this is a loss
for Python and a win for Perl.

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


Re: reading binary data written in C

2006-03-22 Thread Sheldon
Thanks,

I later discovered that it was a big edian binary as well.

Sheldon

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


LONG_BIT PROBLEM on Sun Solaris 5.8 linking python

2006-03-22 Thread Nancy
I know there are lots of messages about this already posted but Im
seeing this on Solaris 5.8. Sunfire
I'm using the sun compiler. All the other messages blamed it on linux
red hat gcc compilers and glib.  Thanks.

"/depot/Python-2.4/include/python2.4/pyport.h", line 612: #error:
"LONG_BIT definition appears wrong for platform (bad gcc/glibc config?).

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


Re: years later DeprecationWarning

2006-03-22 Thread Ben Finney
Dan Jacobson <[EMAIL PROTECTED]> writes:

> Here's the deal: I have to maintain this long gone guy's programs and
> lately they've been saying
> ./north_pass.py:14: DeprecationWarning: integer argument expected, got float
>   fl=range(1000*(math.floor(25000*f2m/1000)),46000*f2m,1000)

You haven't shown us the value of all the terms there; specifically,
we don't know what value has been bound to 'f2m'.

Ideally, this code would have been written to be more easily readable
and explicit. This is an illustration that it's never too late to do
so, and that it can help you understand what the heck is going wrong.

Replace those literals with named constants, that indicate what the
heck they are.

import math
f2m = 1.0   # assuming this is where the float value gets introduced
some_increment_thing = 1000
some_starting_count = 25
some_ending_count = 46
some_starting_scale = some_starting_count * some_increment_thing
some_ending_scale = some_ending_count * some_increment_thing
fl = 
range(some_increment_thing*(math.floor(some_starting_scale*f2m/some_increment_thing)),
 some_ending_scale*f2m, some_increment_thing)

Use names that make sense in the problem domain, of course. The idea
is to not keep the reader (that's you, months or years from now)
guessing why '1000' is used three times, or whether it's mere
coincidence that all the other values seem to be multiples of 1000, or
whether each of those 1000s is meant to be the same thing, or whether
one of them can change, etc.

Split out this mess into separate operations, so you can see what's
failing.

range_start = some_increment_thing * 
math.floor(some_starting_scale*f2m/some_increment_thing)
range_limit = some_ending_scale * f2m
fl = range(range_start, range_limit, some_increment_thing)

That will get you closer to the point of knowing what's causing the
error. It will also (if you've chosen meaningful names) make the code
much more understandable; and perhaps even give you ways to re-think
the algorithm used.

> (That long-gone guy is actually me, according to the notes in the
> program.  However those brain cells are long gone now, so it might
> as well not be me.)

One should always write code for some unknown future person, months or
years after the original context of the problem is forgotten, to
understand, without the benefit of your explanation. As you've found,
that person is most frequently oneself.

-- 
 \  "Friendship is born at that moment when one person says to |
  `\another, 'What!  You too?  I thought I was the only one!'"  -- |
_o__)   C.S. Lewis |
Ben Finney

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


Re: Getting a loop to activate a loop above it

2006-03-22 Thread Terry Hancock
On 22 Mar 2006 13:07:33 -0800
"Byte" <[EMAIL PROTECTED]> wrote:
> The following code will not work for me:
> 
> x = 1
> 
> while x == 1:
> print 'hello'
> x = input('What is x now?: ')
> 
> while x == 2:
> print 'hello again'
> x == input('What is x now?: ')
> 
> The second loop dose not seem to be able to activate the
> loop above it
> Proof from my command line:
> 
> $ python program-that-dose-not-work.py
> hello
> What is x now?: 2
> hello again
> What is x now?: 1
> hello again
> What is x now?:
> 
> So, now I ask you: how do I make it work?

Curious.

What did you expect it to do, and what sort of experience
made you think it ought to do that?

It seems like anyone who had ever seen an Algol-derived
programming language would expect exactly what happens, and
I think so would a "naive" user.

My impression is that you imagine you are writing "rules"
instead of a "program".  That's such an odd expectation, I
am curious what led you to think that way.  Do you
have prior experience with inference engines or something?

Jordan Greenberg has already answered your actual question,
so I won't repeat. :-)

Cheers,
Terry

-- 
Terry Hancock ([EMAIL PROTECTED])
Anansi Spaceworks http://www.AnansiSpaceworks.com

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


Re: Good thread pool module

2006-03-22 Thread Steve M
I believe "Python in a Nutshell" has a couple of clear examples using
Queue and Threading, including one with a pool of worker threads that
wait for entries in one queue and place results in another.

Also you should look at the Python Cookbook, which probably includes
the same or similar examples from the Nutshell book, since the author
of that is an editor of Cookbook.

http://aspn.activestate.com/ASPN/Cookbook/Python?kwd=Threads

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


Re: Good thread pool module

2006-03-22 Thread Rune Hansen
I think you want the Queue module in standard lib. Haven't started a
thread yet without it :)

regards
/rune

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


Re: Uploading files from IE

2006-03-22 Thread Irmen de Jong
AB wrote:
> All right... I already hated IE.  But, now I do even more.  My scripts 
> upload function is working in Firefox, but not in IE.  If I upload a file 
> from Internet Explorer I get a file on the system named for the full path 
> from the users computer...
> 
> example...
> They user uploads C:\mydocs\test.jpg
> it ends up at /path/to/webdir/C:\mydocs\test.jpg
> instead of /path/to/webdir/test.jpg

try something like this:
filename = os.path.basename(fullpathname)

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


Re: Programming challenge: wildcard exclusion in cartesian products

2006-03-22 Thread [EMAIL PROTECTED]
"And it doesn't really matter what language you use to implement this
algorithm, it's the idea that counts. Notation aside, all
implementations will be quite similar."

I'll guess I'll get out my Turing tape. ;)

What are some good references for finite state machines? Minimization?

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


Re: Why TypeError: 'str' object is not callable?

2006-03-22 Thread James Stroud
Randall Parker wrote:
> Using Python 2.4.2 on Windows 2000 in SPE.
> 
> Getting:
> TypeError: 'str' object is not callable
> 
> on this line:
> 
> TmpErrMsg1 = "State machine %s " (StateMachineName)
> 
> In Winpdb 1.0.6 the StateMachineName is of type str in the Namespace |
> Local window of local variables. It even has the string value I expect
> of 'ExampleAO'. That string variable was originally set in another
> variable by reading a socket packet field. Then it was assigned to
> StateMachineName.
> 
> I'm not using str as a variable. I searched all my source code.
> 
> So why can't I do this?
> 
> Is there a way to test what "str" is? Maybe importing the minidom
> messed up what str is? This code used to work. I am trying to figure
> out what caused it to cease to work.
> 
> Any ideas?
> 

I know several other people have given this answer:

TmpErrMsg1 = "State machine %s " % (StateMachineName)

But it deserves comment. Note that

   py> Name = 'bob'
   py> (Name) == Name
   True

Implying that the parentheses are not neccesary. But,

   py> (Name,) == Name
   False

Which may cause some confusion because

   py> "%s" % Name == "%s" % (Name,)
   True

Implying that a tuple is not necessary. Now,

   py> Name, Name
   ('bob', 'bob')

So one would expect

   py> (Name, Name) == (Name, Name)
   True

But, by the same token, one would not expect

   py> Name, Name == (Name, Name)
   ('bob', False)

This comes from operator precedence, where == binds tighther than does 
",", and so does '%' bind tighter than ",". For example,

   py> "%s" % StateMachineName == "%s" % (StateMachineName,)
   True
   py> "%s%s" % StateMachineName, StateMachineName
   Traceback (most recent call last):
 File "", line 1, in ?
   TypeError: not enough arguments for format string

So Beware!

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


Good thread pool module

2006-03-22 Thread David Hirschfield
There isn't a thread pool module in the standard library, but I'm sure 
many have been written by people in the python community.
Anyone have a favorite? Is there one particular implementation that's 
recommended?

Not looking for anything fancy, just something that lets me queue up 
tasks to be performed by a pool of threads and then retrieve results 
when the tasks complete.

Thanks,
-Dave

-- 
Presenting:
mediocre nebula.

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


Re: import random module

2006-03-22 Thread Ben Finney
"DataSmash" <[EMAIL PROTECTED]> writes:
> * random.py:
>
> import random

Now that you've tripped over this ambiguity of Python's current
'import' behaviour, you may be interested to know that the behaviour
will change to solve this:

http://www.python.org/dev/peps/pep-0328/>

In brief: Python will disambiguate relative imports (from the current
package) from absolute imports (from the sys.path), by only allowing
relative imports by a specific syntax; the default import behaviour
will be absolute import.

In line with Python's procedure for introducing changes to behaviour,
the new behaviour will be introduced in backward-compatible stages. In
Python 2.5, a 'from __future__ import absolute_import' will enable the
import behaviour specified in the PEP; in Python 2.6, the Python 2.4
behaviour will occur but raise a DeprecationWarning; in Python 2.7,
the import behaviour specified in the PEP will be the default.

-- 
 \ "I may disagree with what you say, but I will defend to the |
  `\death your right to mis-attribute this quote to Voltaire."  -- |
_o__)  Avram Grumer, rec.arts.sf.written, May 2000 |
Ben Finney

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


Re: doctest, unittest, or if __name__='__main__'

2006-03-22 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, john_sips_tea
wrote:

> For writing testcode, it looks like there's three ways that it's
> typically done:
> 
> (1). using the doctest module,
> 
> (2). using the unittest module (i.e. "pyunit"), or else
> 
> (3). just putting an "if __name__ = '__main__':" at the bottom of your
> module containing code to manually run your class through its paces.
> 
> So, which way is preferred? Seems to me that unittest is the way to go,
> at least because it has you separate your test code from the code being
> tested.
> 
> If unittest is the standard way to write test code, why do we still
> have doctest? (I notice there's no mention in PEP 3000 of deprecating
> the doctest module).

I see it this way: `unittest` is for testing code and `doctest` is for
testing examples in docstrings.  If you put all your tests in the
docstrings there will be much code that's quite irrelevant for documenting
the function/method/class.

Testing real examples in doctstrings, or external documentation like
tutorials, is important because it's very frustrating for people reading
the docs if the examples don't work as advertised.

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


Re: parsing downloaded mail via POP3

2006-03-22 Thread Gerard Flanagan
Kevin F wrote:

> I have the following script:
>
> emails = []
> for msg in messagesInfo:
>  msgNum = int(msg.split()[0])
>  msgSize = int(msg.split()[1])
>  if(msgSize < 2):
> message = server.retr(msgNum)[1]
> Message = join(message, "\n")
> emails.append(message)
>
>
> It downloads messages for me via my POP3 server, however, the message
> format (attached below) includes ridiculous amounts of data and I just
> want to return the from, subject, and body.  Any pointers on how to do this?
>

Have you tried server.top ?

MAX_SUMMARY_LINES = 20

def get_headers(self):
server = poplib.POP3(self.server_name)
server.user(self.user_name)
server.pass_(self.password)
hdrs = []
try:
msgCount, msgBytes = server.stat()
for i in range(msgCount):
msgNum = i+1
hdr, message, octets = server.top(msgNum,
MAX_SUMMARY_LINES)
hdrs.append(message)
finally:
server.quit()

alternatively, something like:


import poplib, email
from email.Utils import getaddresses, parseaddr

def download_mail(self):
server = poplib.POP3(self.server_name)
server.user(self.user_name)
server.pass_(self.password)
try:
msgCount, msgBytes = server.stat()
self.messages = []
for i in range(msgCount):
msgNum = i+1
hdr, message, octets = server.retr(msgNum)
mail_msg = '\n'.join( message)
self.messages.append(
email.message_from_string(mail_msg) )
finally:
server.quit()

def print_headers(self):
for message in self.messages:
print '#' * 80
print parseaddr( message['from'] )
print message['subject']
print message['date']
print getaddresses( message.get_all('to', []) )
print getaddresses( message.get_all('cc', []) )

Gerard

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


Using PyExcelerator

2006-03-22 Thread tkpmep
I have just installed PyExcelerator, and now want to use it to read
Excel spreadsheets with a variable number of rows and columns and with
multiple sheets. Unfortunately, no documentation seems to accompany
PyExcelerator. Does anyone know of a good source of documentations
and/or examples? The author provides some examples, but these tend to
involve writing data into spreadsheets one cell at a time.

Thanks in advance

Thomas Philips

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


Re: years later DeprecationWarning

2006-03-22 Thread Chris Lasher
Two things:
1) math.floor returns a float, not an int. Doing an int() conversion on
a float already floors the value, anyways. Try replacing
math.floor(...) with int(...)
e.g.
>>> math.floor(5.9)
5.0
>>> int(5.9)
5

2) What kind of data is in f2m? If f2m is a float, you will get float
values in the expressions that f2m is a multiplicand.

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


Re: years later DeprecationWarning

2006-03-22 Thread Terry Reedy

"Dan Jacobson" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> Here's the deal: I have to maintain this long gone guy's programs and
> lately they've been saying
> ./north_pass.py:14: DeprecationWarning: integer argument expected, got 
> float
>  fl=range(1000*(math.floor(25000*f2m/1000)),46000*f2m,1000)

The warning is from the range function.  If f2m is float, so too the first 
2 args.  Either convert f2m to int first or both args to int.  The second 
is what happens now.  A long too large to convert to int also raises an 
error.

Terry Jan Reedy



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


Re: SWIGing problem

2006-03-22 Thread Robert Kern
Tommy Grav wrote:
> This might not be the venue to ask this but I do not know where else to
> turn. 
> I am trying to install a package that is swig'ed from some C code. 
> Unfortunately the readme file isn't to informative.  Does anyone
> know which libraries to link to to remove the undefined symbols
> below?
> 
> [EMAIL PROTECTED] Python/pynovas -> ld -dynamic novas_wrap.o libnovas.a -lm
> -lpython -o _novas.so
> ld: Undefined symbols:
> _fprintf$LDBLStub
> _printf$LDBLStub
> dyld_stub_binding_helper
> restFP
> saveFP

Ouch! Are they really not using distutils to build the extension modules? Even
when you fix the specific issue above (if you're on OS X, add -lcc_dynamic to
the link line; otherwise, I don't know), you're still probably going to have
other problems. distutils knows how to build Python extensions modules. The
pynovas Makefile doesn't.

-- 
Robert Kern
[EMAIL PROTECTED]

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Need help with restricting number of new objects a user script can create

2006-03-22 Thread Sybren Stuvel
vj enlightened us with:
> Run using lua generates:
>
> Fatal error:  Allowed memory size of 8388608 bytes exhausted (tried
> to allocate 35 bytes) in
> /home/groups/d/do/doris/htdocs/lua/weblua.php on line 109

Ehm... this can also be done with Python & ulimit.

Sybren
-- 
The problem with the world is stupidity. Not saying there should be a
capital punishment for stupidity, but why don't we just take the
safety labels off of everything and let the problem solve itself? 
 Frank Zappa
-- 
http://mail.python.org/mailman/listinfo/python-list


SWIGing problem

2006-03-22 Thread Tommy Grav
This might not be the venue to ask this but I do not know where else to turn. I am trying to install a package that is swig'ed from some C code. Unfortunately the readme file isn't to informative.  Does anyoneknow which libraries to link to to remove the undefined symbolsbelow?[EMAIL PROTECTED] Python/pynovas -> ld -dynamic novas_wrap.o libnovas.a -lm -lpython -o _novas.sold: Undefined symbols:_fprintf$LDBLStub_printf$LDBLStubdyld_stub_binding_helperrestFPsaveFP CheersTommy[EMAIL PROTECTED]http://homepage.mac.com/tgrav/"Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction"                         -- Albert Einstein -- 
http://mail.python.org/mailman/listinfo/python-list

python linking

2006-03-22 Thread Nancy
When i link with python2.4.a i get this error.

ld: Dwarf Error: Invalid or unhandled FORM value: 14.

I am NOT  using the gcc compiler but the linux icc compiler. Google
hits blame it on gcc compiler binutils being out of date. i dont think
thats the problem here.
thanks.

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


ANN: SCSIPYTHON on Sourceforge

2006-03-22 Thread sam
I have updated and moved my SCSI diagnostic tools from starship to
sourceforge. I will be still maintaining these files at both locations
as long as starship exists. These tools allow low level tests to be
conducted on storage devices under the Windows operating system. These
routines access all storage devices through the Windows SCSIPASSTHROUGH
layer, which maps all storage devices (SCSI,IDE/ATA,USB,PCMCIA,DVD,CD)
to look like a SCSI device that is accessed using SCSI command
descripter blocks.
The move to Sourceforge also places the sourcecode,and files under CVS
control.


Starship link:
http://starship.python.net/crew/samschul

Sourceforge link:
https://sourceforge.net/projects/scsipython

Sam Schulenburg

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


Re: Convert (sorted) list of dics to nested list ?

2006-03-22 Thread Gerard Flanagan
[EMAIL PROTECTED] wrote:

> Hi - I want to take something like ...
>
> lstIn = []
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 10, 'LEA_AUTOID': 1000})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2000})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2001})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2003})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3000})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3001})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3002})
> lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3003})
> lstIn.append({'COM_AUTOID': 2, 'PRG_AUTOID': 110, 'LEA_AUTOID': 4000})
>
>
> ... and produce something like ...
>
> sampleOut =
> [[1,[10,1000]],[1,[11,[2000,2001,2003]]],[1,[12,[3000,3001,3002,3003]]],[2,[110,4000]]
>
>

lstIn = []
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 10, 'LEA_AUTOID': 1000})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2000})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2001})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2003})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3000})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3001})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3002})
lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3003})
lstIn.append({'COM_AUTOID': 2, 'PRG_AUTOID': 110, 'LEA_AUTOID': 4000})

C="COM_AUTOID"
P="PRG_AUTOID"
L="LEA_AUTOID"

d = {}

# convert data to nested dictionary structure
for item in lstIn:
c, p, l = item[C], item[P], item[L]
if c not in d:
d[c] = dict( {p : [l]} )
else:
if p not in d[c]:
d[c][p] = [l]
else:
d[c][p].append(l)

def dict2list( adict ):
for key in sorted(adict.keys()):
if isinstance( adict[key], dict ):
for item in dict2list(adict[key]):
yield [key] + item
else:
yield [[key] + [adict[key]]]

result = list(dict2list(d))

cigar =
[[1,[10,1000]],[1,[11,[2000,2001,2003]]],[1,[12,[3000,3001,3002,3003]]],[2,[110,4000]]]
no_cigar =
[[1,[10,[1000]]],[1,[11,[2000,2001,2003]]],[1,[12,[3000,3001,3002,3003]]],[2,[110,[4000

assert result == no_cigar

print
print 'nested dict: ', d
print
print 'result: ', result

nested dict:  {1: {10: [1000], 11: [2000, 2001, 2003], 12: [3000, 3001,
3002, 3003]}, 2: {110: [4000]}}

result:  [[1, [10, [1000]]], [1, [11, [2000, 2001, 2003]]], [1, [12,
[3000, 3001, 3002, 3003]]], [2, [110, [4000

Gerard

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


years later DeprecationWarning

2006-03-22 Thread Dan Jacobson
Here's the deal: I have to maintain this long gone guy's programs and
lately they've been saying
./north_pass.py:14: DeprecationWarning: integer argument expected, got float
  fl=range(1000*(math.floor(25000*f2m/1000)),46000*f2m,1000)

As I don't know python, I tried sticking an int( ) in various places
in that line but couldn't get whatever is bothering python to shut up. Help.

(That long-gone guy is actually me, according to the notes in the program.
However those brain cells are long gone now, so it might as well not be me.)

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


Re: Getting a loop to activate a loop above it

2006-03-22 Thread Jordan Greenberg
x=1
while not x==3:
if x==1:
print 'hello'
x = input('what is x now?: ')
   if x==2:
print 'hello again'
x=input('what is x now?: ')

any code you want to repeat needs to be in some sort of a loop
structure. Program execution doesn't just jump around unless you tell
it to.

-- 
Jordan T. Greenberg
Spork Polisher

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


Re: Per instance descriptors ?

2006-03-22 Thread Michael Spencer
Bruno Desthuilliers wrote:
> Michael Spencer a écrit :

>> I may be missing the subtlety of what you're up to, but why is 
>> overriding __getattribute__ more desirable than simply defining the 
>> descriptor in a  subclass?
> 
> The code snippet I gave as an example was not supposed to reflect how I 
> effectively mean to use per-instance descriptors, it was just a kind of 
> Minimal Working Code (tm). The real life code is about 500 LOC, and 
> explaining the whole thing would take far too long. Also, as I said, 
> this is mostly syntactic sugar - there are simpler, less 'hackish' (but 
> also less elegant) solutions to the actual 'problem'.So, to answer your
> question, no, subclassing would not be a solution - I'd almost need a 
> subclass per controller function, which would reintroduce the 
> boilerplate I'm trying to get rid of.
> 

> BTW, there may be other use case for per-instance descriptors... 

Agreed.  Per-instance descriptors could be interesting (that's why the subject 
line caught my attention).
But your solution involves a custom __getattribute__ in the class, which I 
would 
always avoid if possible (and I gather you're uneasy about it too).
Here, I don't see why that's better than having a descriptor in the class and, 
if it needs per-instance behavior, then make it dependent on something provided 
by the instance.

e.g.,
class DummyDescriptor1(object):
   def __get__(self, obj, objtype=None):
 if isinstance(obj, objtype):
 return obj.foo.__get__(obj)
 else:
 return self

class MyClass4(object):
   baaz = DummyDescriptor1()
   def __init__(self, foo, bar = None):
 self.foo = foo
 self.bar = bar

 >>> mc4 = MyClass4(lambda self: self.bar, "I'm bar")
 >>> mc4.baaz
 >>> mc4.baaz()
"I'm bar"
 >>> mc5 = MyClass4(lambda self: "I ignore bar", "I'm another bar")
 >>> mc5.baaz()
"I ignore bar"
 >>>


Python
> is so dynamic that you can almost use it like a prototype-based language.
> 
> 
Almost, yes.

Michael

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


Uploading files from IE

2006-03-22 Thread AB
All right... I already hated IE.  But, now I do even more.  My scripts 
upload function is working in Firefox, but not in IE.  If I upload a file 
from Internet Explorer I get a file on the system named for the full path 
from the users computer...

example...
They user uploads C:\mydocs\test.jpg
it ends up at /path/to/webdir/C:\mydocs\test.jpg
instead of /path/to/webdir/test.jpg

This only happens in IE.  Firefox, Safari, Opera... all work fine.

This code is to show how I am going about getting the name... not the actual 
code from my program.

upload_dir = "/path/to/webdir/"
myForm = cgi.FieldStorage
ulImage = myForm["ulImage"]
myName = ulImage.filename
newFile = file (os.path.join(upload_dir, myName), 'wb')
while 1:
chunk = ulImage.file.read(10)
if not chunk: break
newFile.write(chunk)
newFile.close()


Thanks for any help.
AG 


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


Re: Server.sendmail with no "to_addrs" parameter.

2006-03-22 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Jeffrey Froman  <[EMAIL PROTECTED]> wrote:
>EdWhyatt wrote:
>
>> But are you serious about that RFC Compliant thing?
>
>RFC 2822 obsoletes RFC 822, and I don't know of any specification in RFC
>2822 that requires an email address to be present in the To: header. My
>mail seems to generally work fine without a To: header.
>
>I haven't memorized RFC 2822 though, so you may want to read it yourself if
>you're concerned ;-)
>

>From RFC 2822:

   The following table indicates limits on the number of times each
   field may occur in a message header as well as any special
   limitations on the use of those fields.  An asterisk next to a
   value
   in the minimum or maximum column indicates that a special
   restriction
   appears in the Notes column.

Field   Min number  Max number  Notes
...
to  0   1

cc  0   1

bcc 0   1

...


So the answere is, that it's not required to have any destinations
listed in the headers of the message.

It appears that it's not kosher to have an empty To: header, though
I think that few MUAs will balk at this


-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Re: COM Client / Server creation?

2006-03-22 Thread Dan
Ive got the chapter from the net on COM. It looks pretty old, 2000.
Also the very first example in the chapter on COM doesn't seem to work.
Is what I am wanting to do possible with Python?

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


Re: Server.sendmail with no "to_addrs" parameter.

2006-03-22 Thread Jim Segrave
In article <[EMAIL PROTECTED]>,
Dennis Lee Bieber  <[EMAIL PROTECTED]> wrote:
>On 22 Mar 2006 08:31:16 -0800, "EdWhyatt" <[EMAIL PROTECTED]>
>declaimed the following in comp.lang.python:
>
>> So it's a restriction of Python?
>>
>   RFC822 is the /standard/ (well, there are newer versions -- 2822?)
>for email... It is not Python specific.
> 
>> What I am trying to simulate here is the sending of mail to addresses
>> solely in the CC and/or BCC fields - both of which are possible through
>> Outlook.
>
>   Technically, then -- Outlook is in violation of the standard (you
>expected Microsoft to be following standards?)

RFC822 and its followup 2822 do not require a To: address line in the
headers - rfc2822 has the minimum number listed as 0

There is a difference between the SMTP time recipient address list
(RCPT TO:) which detemines what the receiving MTA should do with the
message and the email header To:/CC:/Bcc: lines, which don't (or
should not in any working system) affect mail routing at all. You
can't get mail delivered via SMTP without a RCPT TO command at SMTP
time. Many programs extract this address, in the absence of some other
means of specifying it, by taking the addresses from the To:, CC: and
Bcc: headers, but that's a programming convenience, not an RFC
requirement. Since most people composing emails would find it annoying
to have to enter the RCPT TO addresses separately, the message
composition builds header lines, then sends the message to an MTA
using those addresses. But consider bouncing a mail - then the
desintation for SMTP is the address you are bouncing the mail to, and
the header lines are unchanged (one hopes, if not, replace your mail client)

Much as it pains me to admit it, Outlook, for all its many faults is
correct if it allows sending messages where the To: CC: and or Bcc:
headers are empty.


-- 
Jim Segrave   ([EMAIL PROTECTED])

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


Getting a loop to activate a loop above it

2006-03-22 Thread Byte
The following code will not work for me:

x = 1

while x == 1:
print 'hello'
x = input('What is x now?: ')

while x == 2:
print 'hello again'
x == input('What is x now?: ')

The second loop dose not seem to be able to activate the loop above
it
Proof from my command line:

$ python program-that-dose-not-work.py
hello
What is x now?: 2
hello again
What is x now?: 1
hello again
What is x now?:

So, now I ask you: how do I make it work?

Thanks in advance,
 -- /usr/bin/byte

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


Re: COM Client / Server creation?

2006-03-22 Thread Rene Pijlman
Dan:
>New to python. Running under windows xp. Need help getting started
>writing COM server and client. 

Highly recommended:
http://safari.oreilly.com/?XmlId=1-56592-621-8
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Per instance descriptors ?

2006-03-22 Thread Steven Bethard
bruno at modulix wrote:
> Hi
> 
> I'm currently playing with some (possibly weird...) code, and I'd have a
> use for per-instance descriptors, ie (dummy code):
> 
> class DummyDescriptor(object):
>   def __get__(self, obj, objtype=None):
> if obj is None:
>   return self
> return getattr(obj, 'bar', 'no bar')
> 
> class MyClass1(object):
>   def __init__(self, bar=None):
> if bar is not None:
>   self.bar = bar
> self.baaz = DummyDescriptor()
> 
> mc1 = MyClass1(bar='back')
> mc1.baaz
> -> <__main__.DummyDescriptor object at 0x2bc6c390>
> 
> Which is of course what one would expect...  Now I tried the following
> hack^Mworkaround:
> 
> class MyClass2(MyClass1):
> def __getattribute__(self, key):
> v = MyClass1.__getattribute__(self, key)
> if hasattr(v, '__get__'):
> return v.__get__(self, self.__class__)
> return v
> 
> And it *seems* to work just fine:
> 
> mc2 = MyClass2(bar='foo')
> mc2.baaz
> ->  'foo'
> 
> Now the question: is there any obvious (or non-obvious) drawback with
> this approach ?

Don't know if this matters, but if you override __getattribute__, you'll 
slow down all attribute accesses to this object.  If this matters, you 
could write something like:

 class MyClass(object):
 def __init__(self, bar=None):
 if bar is not None:
 self.bar = bar
 def __getattr__(self, name):
 if name == 'baaz':
 return self.bar
 elif name == 'bar':
 return 'no bar'

Then you only incur the penalty on the ``baaz`` lookup and the ``bar`` 
lookup when it's missing -- not on all attribute lookups.

Could you explain again why you don't want baaz to be a class-level 
attribute?

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


parsing downloaded mail via POP3

2006-03-22 Thread Kevin F
I have the following script:

emails = []
for msg in messagesInfo:
 msgNum = int(msg.split()[0])
 msgSize = int(msg.split()[1])
 if(msgSize < 2):
message = server.retr(msgNum)[1]
Message = join(message, “\n”)
emails.append(message)


It downloads messages for me via my POP3 server, however, the message 
format (attached below) includes ridiculous amounts of data and I just 
want to return the from, subject, and body.  Any pointers on how to do this?

/// sample message downloaded

fe5.bluebottle.com (fe5 [209.144.225.81])', '\t by 
bluebottle-be1.bluebottle.com (Cyrus v2.2.8) with LMTPA;', '\t Tue, 21 
Mar 2006 23:47:22 -0600', 'X-Sieve: CMU Sieve 2.2', 'Received: from 
fe7.bluebottle.com (fe7 [209.144.225.70])', '\tby fe5.bluebottle.com 
(8.13.4/8.13.4) with ESMTP id k2M5hhkd023264', '\tfor 
<[EMAIL PROTECTED]>; Tue, 21 Mar 2006 23:44:35 -0600', 
'Received: from smtp-relay.wharton.upenn.edu 
(smtp-relay.wharton.upenn.edu [130.91.161.218])', '\tby 
fe7.bluebottle.com (8.13.4/8.13.4) with ESMTP id k2M5hea4022775', 
'\t(version=TLSv1/SSLv3 cipher=DHE-RSA-AES256-SHA bits=256 verify=NO)', 
'\tfor <[EMAIL PROTECTED]>; Tue, 21 Mar 2006 23:43:41 -0600', 
'Received: from FAIRMOUNT.wharton.upenn.edu 
(fairmount2.wharton.Upenn.Edu [128.91.87.58])', '\tby 
smtp-relay.wharton.upenn.edu (8.13.1/8.13.1) with ESMTP id 
k2M5heQv007094', '\tfor <[EMAIL PROTECTED]>; Wed, 22 Mar 2006 
00:43:40 -0500', 'X-DomainKeys: Sendmail DomainKeys Filter v0.3.2 
smtp-relay.wharton.upenn.edu k2M5heQv007094', 'DomainKey-Signature: 
a=rsa-sha1; s=smtp-relay; d=wharton.upenn.edu; c=nofws; q=dns;', 
'\tb=TZ7xn8PLJNMsq8iCl7eqlME0EDnCC7fKUvpKmALqe1FQ5gG/fG+V/bomQMKyblplJ', 
'\tlg6wTqPoeao6lkM4yu+Rw==', 'Received: from webmail1.wharton.upenn.edu 
([172.16.32.58]) by FAIRMOUNT.wharton.upenn.edu with Microsoft 
SMTPSVC(6.0.3790.1830);', '\t Wed, 22 Mar 2006 00:43:39 -0500', 
'Received: from [165.123.150.168] ([165.123.150.168]) by 
webmail1.wharton.upenn.edu over TLS secured channel with Microsoft 
SMTPSVC(6.0.3790.1830);', '\t Wed, 22 Mar 2006 00:43:39 -0500', 
'User-Agent: Microsoft-Entourage/11.0.0.040405', 'Date: Wed, 22 Mar 2006 
00:43:37 -0500', 'Subject: KNOCKITY-KNOCK-WHOS-THERE', 
'From: Kevin Feng <[EMAIL PROTECTED]>', 'To: 
"[EMAIL PROTECTED]" <[EMAIL PROTECTED]>', 
'Message-ID: <[EMAIL PROTECTED]>', 'Mime-version: 
1.0', 'Content-type: text/plain;', '\tcharset="US-ASCII"', 
'Content-transfer-encoding: 7bit', 'X-OriginalArrivalTime: 22 Mar 2006 
05:43:39.0441 (UTC) FILETIME=[921A4210:01C64D73]', 'X-Virus-Scanned: 
ClamAV version 0.88, clamav-milter version 0.87 on fe7.bluebottle.com', 
'X-Virus-Status: Clean', 'Trusted-Delivery-Validation-State: Not 
validated', '', 'ANITA-ANITA WHOANITA BETTER JOKE', '', ''], 2266)
-- 
http://mail.python.org/mailman/listinfo/python-list


COM Client / Server creation?

2006-03-22 Thread Dan
New to python. Running under windows xp. Need help getting started
writing COM server and client. Want to basically have two interfaces on
the server, register() and fire_event1(). register registers a client
to receive the fire_event1() event. The client will then need an event
handler implemented to receive the events. Each new client that calls
register should be tracked in the server so that all of the clients
receive the event. I have done this very easiliy with traditional
programming languages but don't reall know where to start here. Dan

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


Re: read a file line by line using readline()

2006-03-22 Thread Bruno Desthuilliers
Phoe6 a écrit :
> Hi all,
> I just read the manual and got to know I can use a for loop to iterate
> through the lines in the file.
> 
> But so far, I was strugling with the following:
> 
> import os
> file = open('File1.txt','r')

'file' is the builtin type for file objects (like the one returned by 
open()). Avoid using it as an identifier, this shadows the file type.

> line = file.readline()
> while line !=' ':

As Thomas pointed out, this is not an empty string !-)

Also, this is not a for loop...

> print line
> line = file.readline()

Do yourself a favor, use a for loop. Also, a file opened in read mode is 
already an iterator :

f = open('path/to/file')
for line in f:
   do_something_with(line)
f.close()



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


Re: Dynamically growing numarray array.

2006-03-22 Thread Robert Kern
Ivan Vinogradov wrote:
> Hello All,
> 
> this seems like a trivial problem, but I just can't find an elegant  
> solution neither by myself, nor with google's help.
> 
> I'd like to be able to keep an array representing coordinates for a  
> system of points.
> Since I'd like to operate on each point's coordinates individually,  
> for speed and ufuncs
> numarray fits the bill perfectly, especially since system.coordinates 
> [4] would return proper vector for a 5th point.

BTW, numpy is replacing numarray, so if you're just getting started, you will
probably want to be using numpy.

  http://numeric.scipy.org

> To start, read the coordinates from a text file and add them to our  
> array one by one.
> Here it gets un-elegant and probably wasteful for a large number of  
> points, by converting the whole array to a list only to use append  
> method and then convert it back to array(sample code below). Also,  
> there is potential need to add more points later on.

Well, you can accumulate points in a list, and them concatenate them wholesale
when you are done. Something like the following (untested):

  import numpy
  a1 = ... # some pre-existing array of points
  f = open('mypoints.txt')
  newpoints = []
  for point in points_from_file(f):
newpoints.append(point)
  f.close()
  a1 = numpy.vstack((a1, newpoints))

Doing the "a1 = numpy.vstack(...)" for each point is rather slow.

numpy arrays do have a .resize() method, but it's not very safe and probably
just as slow as doing numpy.vstack() for each new point. Now, you could do a
preallocation strategy like lists do internally, but it's probably not worth it.

-- 
Robert Kern
[EMAIL PROTECTED]

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: multiple assignment

2006-03-22 Thread Steven Bethard
Anand wrote:
> Wouldn't it be nice to say
> 
> id, *tokens = line.split(',')

id, tokens_str = line.split(',', 1)

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


Louie + Twisted

2006-03-22 Thread Richard Townsend
I recently came across the Louie package (http://louie.berlios.de/)

I am particularly interested in the TwistedDispatchPlugin, however the
documentation is very sparse.

Does anyone have some example code showing how to use it, please?


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


Re: Per instance descriptors ?

2006-03-22 Thread Bruno Desthuilliers
Michael Spencer a écrit :
> bruno at modulix wrote:
> 
>> Ziga Seilnacht wrote:
>>
>>> bruno at modulix wrote:
>>>
 Hi

 I'm currently playing with some (possibly weird...) code, and I'd 
 have a
 use for per-instance descriptors, ie (dummy code):
>>>
>>>
>>> 
>>>
 Now the question: is there any obvious (or non-obvious) drawback with
 this approach ?
>>>
>>>
> ...
> 
>>
>>> ... def __getattribute__(self, name):
>>> ... v = object.__getattribute__(self, name)
>>> ... if not isinstance(v, types.FunctionType) \
>>
>> and hasattr(v, '__get__'):
>>
>>> ... return v.__get__(self, self.__class__)
>>> ... return v
>>
>>
>>
> I may be missing the subtlety of what you're up to, but why is 
> overriding __getattribute__ more desirable than simply defining the 
> descriptor in a  subclass?

The code snippet I gave as an example was not supposed to reflect how I 
effectively mean to use per-instance descriptors, it was just a kind of 
Minimal Working Code (tm). The real life code is about 500 LOC, and 
explaining the whole thing would take far too long. Also, as I said, 
this is mostly syntactic sugar - there are simpler, less 'hackish' (but 
also less elegant) solutions to the actual 'problem'. So, to answer your 
question, no, subclassing would not be a solution - I'd almost need a 
subclass per controller function, which would reintroduce the 
boilerplate I'm trying to get rid of.

BTW, there may be other use case for per-instance descriptors... Python 
is so dynamic that you can almost use it like a prototype-based language.


(snip code)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why TypeError: 'str' object is not callable?

2006-03-22 Thread Randall Parker
Argh!

I do not know what happened to the percent signs. They used to be
there. Sorry to waste the time of so many people.

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


Re: Why TypeError: 'str' object is not callable?

2006-03-22 Thread Kent Johnson
Carl J. Van Arsdall wrote:
> Randall Parker wrote:
>>
>>Getting:
>>TypeError: 'str' object is not callable
>>
>>on this line:
>>
>>  
> 
> You have a boo boo
> 
> 
>>TmpErrMsg1 = "State machine %s " (StateMachineName)
>>  
> 
> Should be
> 
> TmpErrMsg1 = "State machine %s " %(StateMachineName)

And the reason for the error message is, when you write
   a(b)

Python interprets this as, call the object a, passing the parameter b. 
If a is a string - a 'str' object - Python attempts to call the string. 
Strings are not callable so you get the error message you see.

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


Dynamically growing numarray array.

2006-03-22 Thread Ivan Vinogradov
Hello All,

this seems like a trivial problem, but I just can't find an elegant  
solution neither by myself, nor with google's help.

I'd like to be able to keep an array representing coordinates for a  
system of points.
Since I'd like to operate on each point's coordinates individually,  
for speed and ufuncs
numarray fits the bill perfectly, especially since system.coordinates 
[4] would return proper vector for a 5th point.
To start, read the coordinates from a text file and add them to our  
array one by one.
Here it gets un-elegant and probably wasteful for a large number of  
points, by converting the whole array to a list only to use append  
method and then convert it back to array(sample code below). Also,  
there is potential need to add more points later on.

Any pointers would be greatly appreciated.


 >>> from numarray import array
 >>> p1 = [0,0,1]
 >>> p2 = [0,0,2]
 >>> p3 = [0,0,3]
 >>> a1 = array((p1,p2))
 >>> a1array([[0, 0, 1],
  [0, 0, 2]])
 >>> a2 = array((a1,p3))Traceback (most recent call last):
File "", line 1, in ?
File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/ 
site-packages/numarray/numarraycore.py", line 417, in arrayreturn  
fromlist(sequence,type,shape)
File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/ 
site-packages/numarray/numarraycore.py", line 267, in fromlist
arr.fromlist(seq)
ValueError: Nested sequences with different lengths.
 >>> temp = list(a1)
 >>> temp.append(p3)
 >>> a2 = array(temp)
 >>> a2array([[0, 0, 1],
  [0, 0, 2],
  [0, 0, 3]])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: RPC client class?

2006-03-22 Thread Richard Tew
>From Dick Watson:
> We have a legacy device that exposes an RPC server. We have an RPCL
> defininition of its interface. We want to develop an RPC client of this
> interface in Python that will be usable in both Win32 and open systems
> environments.
>
> I can find some *very* dated references to a demo/rpc.py, but I can't find
> such a file on my Win Python install. There is an rpc.py in idle, but it
> doesn't seem to be a general purpose implementation. (I can find **lots** of
> references to xmlrpc.py, but the server predates all of this neato XML
> stuff. I also found the "Stackless" rpc.py; it wants to modify base Python.
> I'd rather not diverge from the stock Python.)

The "stackless" rpc.py is also not an implementation of Sun RPC.  It
just uses Stackless tasklets to enable direct Python function function
calls from server to client and vice versa.  Perhaps it was bad naming
on my part, but I assumed remote procedure calls was a general
technique rather than just a Sun RPC protocol.

Richard.

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


a problem to solve

2006-03-22 Thread John Salerno
Ok, here's a problem I've sort of assigned to myself for fun, but it's 
turning out to be quite a pain to wrap my mind around. It's from a 
puzzle game. It will help if you look at this image:

http://www.johnjsal.devisland.net/switches.jpg

Here's the situation: Each of the four rows in the diagram is considered 
a single 'panel'. Each panel has eight 'switches', which are composed of 
two columns each, and these columns have a total of 20 lights (10 in one 
column, 10 in the other). The picture hopefully makes this description 
clear.

The shaded boxes denote which lights turn on when you select that 
particular switch. So, the very first switch in the first row, if turned 
on, would turn on the first four lights, not the fifth, turn on the 
sixth, not the seventh, and turn on 8-14, etc. up to the 20th light.

You can only turn on one switch per panel, so eventually you will have 
four switches lit.

What you are shooting for is to find a combination of four switches so 
that exactly three lights in the same location are lit, no more or less. 
So turning on the first switch in each row would not work, because that 
would mean that the second light in each switch would be lit, and you 
can't have all four lit, just three.

So anyway, the reason I describe all this isn't so you can solve it for 
me, because I really want to figure it out. I just was hoping you can 
give me some tips as to how to implement the algorithm. Maybe Python has 
some functions that I can use to make it easier than it seems.

My plan right now is to do a comparison of panel 1, switch 1, light 1 
with panel 2, switch 1, light 1, then panel 3, switch 1, light 1, etc., 
which sounds scary. I didn't know if Python had a way to compare the 
whole switch in one step, perhaps.

Also, I was wondering how I might implement the switches as data 
structures. Right now I have them as a list of 32 strings, but I thought 
maybe some type of bitwise comparisons could help.

Anyway, any advice for how to proceed would be great! I hope I described 
it well enough.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why TypeError: 'str' object is not callable?

2006-03-22 Thread Richard Townsend
On 22 Mar 2006 12:10:49 -0800, Randall Parker wrote:

> 
> TmpErrMsg1 = "State machine %s " (StateMachineName)
> 

TmpErrMsg1 = "State machine %s " % (StateMachineName)

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


Re: Why TypeError: 'str' object is not callable?

2006-03-22 Thread Carl J. Van Arsdall
Randall Parker wrote:
> Using Python 2.4.2 on Windows 2000 in SPE.
>
> Getting:
> TypeError: 'str' object is not callable
>
> on this line:
>
>   
You have a boo boo

> TmpErrMsg1 = "State machine %s " (StateMachineName)
>   
Should be

TmpErrMsg1 = "State machine %s " %(StateMachineName)



> In Winpdb 1.0.6 the StateMachineName is of type str in the Namespace |
> Local window of local variables. It even has the string value I expect
> of 'ExampleAO'. That string variable was originally set in another
> variable by reading a socket packet field. Then it was assigned to
> StateMachineName.
>
> I'm not using str as a variable. I searched all my source code.
>
> So why can't I do this?
>
> Is there a way to test what "str" is? Maybe importing the minidom
> messed up what str is? This code used to work. I am trying to figure
> out what caused it to cease to work.
>
> Any ideas?
>
>   


-- 

Carl J. Van Arsdall
[EMAIL PROTECTED]
Build and Release
MontaVista Software

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


Why TypeError: 'str' object is not callable?

2006-03-22 Thread Randall Parker
Using Python 2.4.2 on Windows 2000 in SPE.

Getting:
TypeError: 'str' object is not callable

on this line:

TmpErrMsg1 = "State machine %s " (StateMachineName)

In Winpdb 1.0.6 the StateMachineName is of type str in the Namespace |
Local window of local variables. It even has the string value I expect
of 'ExampleAO'. That string variable was originally set in another
variable by reading a socket packet field. Then it was assigned to
StateMachineName.

I'm not using str as a variable. I searched all my source code.

So why can't I do this?

Is there a way to test what "str" is? Maybe importing the minidom
messed up what str is? This code used to work. I am trying to figure
out what caused it to cease to work.

Any ideas?

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


Re: Trouble with generator as method

2006-03-22 Thread Peter Cole
Peter Otten wrote:
> Peter Cole wrote:
> 
>> I'm having difficulty understanding why this doesn't work:
> 
>> import sys, new, inspect
>>
>> class T:
>>  def foo(self):
>> yield 1
>> yield 2
>> yield 3
>>
>>
>> t = T()
> 
> im = new.instancemethod(T.foo, t, T)
> 
>> print t.foo
>> print im
> 
> # prints
> # >
> # >
> 
> From the output you can see that both are equivalent bound methods. 
>  
>> print 't.foo().next() = %s' % t.foo().next()
>> print 'im.next() = %s' % im.next()
> 
> Yet you call t.foo() while you don't call im.
> 
> Peter
>  

Right, I've got it now, thanks.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrap a dictionary in a class?

2006-03-22 Thread Michael Spencer
Joseph Turian wrote:
> In another thread, it was recommended that I wrap a dictionary in a
> class.
> How do I do so?
> 
>Joseph
> 
> that thread:
> http://groups.google.com/group/comp.lang.python/browse_frm/thread/9a0fbdca450469a1/b18455aa8dbceb8a?q=turian&rnum=1#b18455aa8dbceb8a
> 
Perhaps like this?

 >>> adict = dict(a=1,b=2,c=3)
 >>> class Bunch(object):
... def __init__(self, other):
... self.__dict__ = other
...
 >>> b = Bunch(adict)
 >>> b.a
1
 >>> b.b
2
 >>> b.c
3
 >>> b.c= 42
 >>> adict
{'a': 1, 'c': 42, 'b': 2}
 >>>

Be careful: attribute access to the dictionary works only if the keys are valid 
identifiers, and not special names (which Python looks up in the class).


HTH
Michael

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


Re: Per instance descriptors ?

2006-03-22 Thread Michael Spencer
bruno at modulix wrote:
> Ziga Seilnacht wrote:
>> bruno at modulix wrote:
>>
>>> Hi
>>>
>>> I'm currently playing with some (possibly weird...) code, and I'd have a
>>> use for per-instance descriptors, ie (dummy code):
>>
>> 
>>
>>> Now the question: is there any obvious (or non-obvious) drawback with
>>> this approach ?
>>
...
> 
>> ... def __getattribute__(self, name):
>> ... v = object.__getattribute__(self, name)
>> ... if not isinstance(v, types.FunctionType) \
> and hasattr(v, '__get__'):
>> ... return v.__get__(self, self.__class__)
>> ... return v
> 
> 
I may be missing the subtlety of what you're up to, but why is overriding 
__getattribute__ more desirable than simply defining the descriptor in a  
subclass?
i.e.,
class MyClass3(MyClass1):
   def __init__(self, bar=None):
 if bar is not None:
   self.bar = bar
   baaz = DummyDescriptor()


Michael

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


Re: Newbie: Print question

2006-03-22 Thread Tommy Grav
Thanks. That works. Like I said I am a newbie :)Cheers  TommyOn Mar 22, 2006, at 1:17 PM, Fredrik Lundh wrote:Tommy Grav wrote:      for testobs in obslist:         print testobs.printmpc() print.      def printmpc(self):         if self.mag!="":             print "%14s  %12.5f  %5.2f  %6.2f  %8.3f  %3i" and print. I don't understand where these None's are coming from. for each testobs, you're printing stuff inside the printmpc method, and you'rethen printing the return value from the method.  removing the extra print    for testobs in obslist:        testobs.printmpc()should fix this.-- http://mail.python.org/mailman/listinfo/python-list  CheersTommy[EMAIL PROTECTED]http://homepage.mac.com/tgrav/"Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius -- and a lot of courage -- to move in the opposite direction"                         -- Albert Einstein -- 
http://mail.python.org/mailman/listinfo/python-list

Re: Conversion from string to integer

2006-03-22 Thread Mark Warburton
Grant Edwards wrote:
> On 2006-03-22, Mark Warburton <[EMAIL PROTECTED]> wrote:
> > Ahh, right.  Batteries included!  Thanks for the enlightenment.  :)
>
> I think that's the third time _today_ that question has been
> answered.  Where can we put that information such that you
> would have found it?

Don't ask me -- I didn't ask the original question!  I just answered it
in a different way.

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


Re: Need help with restricting number of new objects a user script can create

2006-03-22 Thread vj
I think the only option is to come up with my own mini language.
Searching on google, I found several examples where people replaced
python with lua for scripting. Am reading up on lua and looks very
promissing. I also tried doing the following:

for i=1,1 do print(i) end

on:
http://doris.sourceforge.net/lua/weblua.php

and got the following error:

Lua script:

for i=1,1 do print(i) end

Run using lua generates:

Fatal error:  Allowed memory size of 8388608 bytes exhausted (tried to
allocate 35 bytes) in /home/groups/d/do/doris/htdocs/lua/weblua.php on
line 109

Very cool. I need to now find out if this error is being caught by the
lua script or the underlying os. There also seems to be a 2-way
lua-python bridge converted which will allow me to embed lua in my
applciation.

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


Re: Conversion from string to integer

2006-03-22 Thread Grant Edwards
On 2006-03-22, Mark Warburton <[EMAIL PROTECTED]> wrote:
> Peter Otten wrote:
>> To convert them you need struct.unpack()
>
> Ahh, right.  Batteries included!  Thanks for the enlightenment.  :)

I think that's the third time _today_ that question has been
answered.  Where can we put that information such that you
would have found it?

-- 
Grant Edwards   grante Yow!  World War Three can
  at   be averted by adherence
   visi.comto a strictly enforced
   dress code!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie: Print question

2006-03-22 Thread xkenneth
doesnt look like you're passing any data to the print statement,
shouldn't it be something like

print '%d' % 4

output:
4\n

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


Re: Objective Cairo

2006-03-22 Thread Paul Boddie
[EMAIL PROTECTED] wrote:
> As pycairo is one of the less pythonish things I ever saw, it went into
> my mind to create some sort of objective wrapper over its python api
> making graphic manipulation much more coherent to the python way.

[...]

> Before going on with more complex forms and objects, I was wondering if
> this could be useful to anyone or if I'd better giving up.

What you've done looks interesting. However, before venturing too far,
I'd recommend looking at the other graphics APIs for Python and keeping
as compatible as possible to the way they do things (without offending
your sense of "Pythonicity" or conflicting with the Cairo mechanisms,
of course). Sadly, I'm not really up-to-date with what people use for
canvas-style drawing in Python - once upon a time there was the Piddle
project, renamed to Sping, and then seemingly abandoned - but I'm sure
a few people can suggest similar projects.

Keep up the good work, though!

Paul

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


Re: Conversion from string to integer

2006-03-22 Thread Mark Warburton
Peter Otten wrote:
> To convert them you need struct.unpack()

Ahh, right.  Batteries included!  Thanks for the enlightenment.  :)

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


Re: Conversion from string to integer

2006-03-22 Thread Mark Warburton
You want something like this:

>>> a = '\x1dz'
>>> (ord(a[0])<<8) + ord(a[1])
7546

Each of the two characters represents one byte of a 16-bit integer.  It
doesn't matter if they are ascii or hex -- there are still exactly two
bytes in each of your strings.

The ord() function converts a character to its 8-bit ASCII code.  The
<< operator shifts the first character 8 bits to the left.  Note that
the byte order might need to be swapped, depending on the
implementation of your custom hardware.  e.g.  (ord(a[1])<<8) +
ord(a[0])

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


  1   2   3   >