Re: Monitoring the output of an external program

2007-12-13 Thread Vladimir Rusinov
On 12/13/07, Caleb Marcus <[EMAIL PROTECTED]> wrote:
>
>  I'm writing something that has to invoke an external program, and every
> time the external program prints something, update a UI. How would I go
> about doing this?
>

Use sys.popen or pexpect module.
With pexpect you can even use single thread.

-- 
Vladimir Rusinov
GreenMice Solutions: IT-решения на базе Linux
http://greenmice.info/
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Difference between del and remove?

2007-12-13 Thread Tim Roberts
Yansky <[EMAIL PROTECTED]> wrote:
>
>Got a quick n00b question. What's the difference between del and
>remove?

It would have been easier to answer if you had given a little context.

"del" is a Python statement that removes a name from a namespace, an item
from a dictionary, or an item from a list.

"remove" is a member function of the 'list' class that finds a specific
entry in the list and removes it.

Example:

>>> e = [9,8,7,6] ; del e[2] ; e
[9, 8, 6]

>>> e = [9,8,7,6] ; e.remove(2) ; e
Traceback (most recent call last):
  File "", line 1, in ?
ValueError: list.remove(x): x not in list

>>> e = [9,8,7,6] ; e.remove(8) ; e
[9, 7, 6]

Note that "del e[2]" removed item number 2 (counting from 0).  e.remove(8)
removed the item that had the value 8 from the list.  e.remove(2) failed
because the number 2 was not in the list.

Dictionaries do not have a "remove" method.  You have to use the "del"
statement.
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic or not?

2007-12-13 Thread Tim Roberts
[EMAIL PROTECTED] wrote:
>
>I'm trying to write a program that will find the distance between two
>groups of points in space, which have cartesian co-ordinates X,Y and
>Z.
>
>I need to find the distances between each point in one group and every
>point in the other group. So if group 1 has 6 points and group 2 had 8
>points, I will calculate 6 x 8 = 48 distances. But I do not know the
>number of points the user will want to use. It is typically between 50
>and 500 in both groups combined, but may be more. Since the memory
>required for the distances will be much larger than the points
>themselves, I am wondering if I will have to allocate memory
>dynamically or if there are easier ways of solving such problems in
>Python.

Python already allocates memory dynamically.  With 500 in each group,
you'll have 250,000 distances.  If you use floating point, that's only 2
megabytes.  Piece of cake.  With 1,000 in each group, it's 8 megabytes.
Still no sweat.

What are you going to do with these distances?  Why do you need them all in
memory?
-- 
Tim Roberts, [EMAIL PROTECTED]
Providenza & Boekelheide, Inc.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic or not?

2007-12-13 Thread John Machin
On Dec 13, 3:33 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Wed, 12 Dec 2007 19:18:20 -0800, rishiyoor wrote:
> > I'm trying to write a program that will find the distance between two
> > groups of points in space, which have cartesian co-ordinates X,Y and Z.
>
> points1 = [ (1.2, 3.4), (5.7, 9.2) ]
> points2 = [ (-6.3, 0.0), (14.1, -7.8), (2.6, 12.8) ]
>
> import math
> def distance(p1, p2):
> return math.hypot(p1[0]-p2[0], p1[1]-p2[1])

X, Y,  umm, aren't we short a dimension?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie NameError problem

2007-12-13 Thread cokofreedom
On Dec 12, 7:03 pm, Paul Rudin <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] writes:
> > On Dec 12, 5:51 pm, Paul Rudin <[EMAIL PROTECTED]> wrote:
> >> [EMAIL PROTECTED] writes:
> >> > I don't understand what I don't understand in the following:
>
> >> I haven't tried to understand what your code is doing - but the
> >> NameError arises because you try to use Loc before its definition. Put
> >> the definition first and the error should go away.
>
> > Class Loc must be placed ABOVE the code that uses it.
>
> Isn't that what I said?

I had had a few too many Coffee's, had thought the extra commenting
would aid :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic or not?

2007-12-13 Thread Steven D'Aprano
On Thu, 13 Dec 2007 00:39:55 -0800, John Machin wrote:

> X, Y,  umm, aren't we short a dimension?

I'm not going to do *everything* for the OP. He can extend it to three 
dimensions.


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


looping list?

2007-12-13 Thread datulaida ali
hi..
i'm trying to insert value into list according to the key (ASCII) that i
generate..

example :

win = 95, so must insert into list[95]
and = 70, so must insert into list[70]

this is my coding..
__ 

list = []

try:
conn = MySQLdb.connect (host = "localhost",
user = "root",
passwd = "508420",
db = "myimg")
except MySQLdb.Error, e:
print "Error %d: %s" % (e.args[0], e.args[1])
sys.exit (1)

cursor = conn.cursor()


cursor.execute ("SELECT word,id,freq,indeks FROM tablesusun")

for(word,id,freq,indeks) in cursor.fetchall():

first = ord(word[0])
second = ord(word[1])
last = first * second
key = last % 100

for i in range (100):
if i == key :
list.append([i,word])

else :
list.append([0])

print list

cursor.close ()
conn.commit ()
conn.close ()
__ 

the ouput is :
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [and], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0];

[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [win], [0], [0], [0], [0];
__ 

i want the output is like this :

[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [and], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0], [0],
[0], [0], [0], [0], [0], [win], [0], [0], [0], [0];

any ideas?
-- 
http://mail.python.org/mailman/listinfo/python-list

what the heck does this mean?

2007-12-13 Thread katie smith
Traceback (most recent call last):
  File "C:\Python25\empire\Empire Strategy.pyw", line 322
Maty = Searched(number)
TypeError: 'list' object is not callable

My list is NewMap1 =[0,0,0,0,0,0,2,0,2,2,3,2,0,0,0,0]

so Maty Searched(number is supposed to give me 0 when
Search = "NewMap"
number = 0
bignum = 1
bignumer = repr(bignum)
Searching = Search+bignumer
Searched = eval(Searching)
Maty = Searched[number]

instead i get that error whats up? i thought it is suppose to give me 
NewMap1(0).when I print it it works fine  and gives me the result 0 but when I 
go to save the number as Maty-(randomletters) it keeps giving me the stupid 
error.

please help

Ps: rather than doing in your head making a test prgram to run exactly that 
might be better


  

Looking for last minute shopping deals?  
Find them fast with Yahoo! Search.  
http://tools.search.yahoo.com/newsearch/category.php?category=shopping-- 
http://mail.python.org/mailman/listinfo/python-list

Re: what the heck does this mean?

2007-12-13 Thread Gary Herron
katie smith wrote:
> Traceback (most recent call last):
>   File "C:\Python25\empire\Empire Strategy.pyw", line 322
> Maty = Searched(number)
> TypeError: 'list' object is not callable
>  
> My list is NewMap1 =[0,0,0,0,0,0,2,0,2,2,3,2,0,0,0,0]
>  
> so Maty Searched(number is supposed to give me 0 when
> Search = "NewMap"
> number = 0
> bignum = 1
> bignumer = repr(bignum)
> Searching = Search+bignumer
> Searched = eval(Searching)
> Maty = Searched[number]
>  
> instead i get that error whats up? i thought it is suppose to give me
> NewMap1(0).when I print it it works fine  and gives me the result 0
> but when I go to save the number as Maty-(randomletters) it keeps
> giving me the stupid error.
You're not telling us something important.   When I execute the
statements you give, I do indeed get 0 for the value of Maty, which is
what you expect -- so I see no problem.

But then in your next claim, you say "save the number as
Maty-(randomletters)".  What does that mean?  What Python statement are
you running?  What means "save"?  What is "randomletters"? 

The error you are getting is usually gotten by code that tries to treat
a variable containing a list as a function.  Example:

someList = [1,2,3]
someList(99)

Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'list' object is not callable



Gary Herron



>  
> please help
>  
> Ps: rather than doing in your head making a test prgram to run exactly
> that might be better
>
> 
> Looking for last minute shopping deals? Find them fast with Yahoo!
> Search.
> 

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


Re: Is Python really a scripting language?

2007-12-13 Thread Bruno Desthuilliers
Doug Morse a écrit :

top-post corrected

 But here's my problem,
 most of my coworkers, when they see my apps and learn that they are
 written in Python ask questions like, "Why would you write that in a
 scripting language?"  Whenever I hear a comment like that I can feel
 myself boiling inside.
> although perhaps not a part of the definition of scripting languages per se,

I still wait to see any clear, unambiguous definition of "scripting 
language". Which one are you refering to here ?

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


Re: Is Python really a scripting language?

2007-12-13 Thread Bruno Desthuilliers
Terry Reedy a écrit :
> "Ron Provost" <[EMAIL PROTECTED]> wrote in message 
> news:[EMAIL PROTECTED]
> But here's my problem, most of my coworkers, when they see my apps and 
> learn that they are written in Python ask questions like, "Why would you 
> write that in a scripting language?" 

Then ask them what's a "scripting language" exactly... or download this, 
print it and put it on the wall near your desktop:

http://apipes.blogspot.com/2005/01/choose-python.html

> Whenever I hear a comment like that I 
> can feel myself boiling inside.

As far as I'm concerned, anyone (I mean, anyone pretending to be a 
programmer) being ignorant enough to ask such a question ranks high in 
my bozo list. Don't waste time with bozos.


> 
> I don't blame you.  Python is an full-fledged algorithm/programming 
> language that was designed to *also* be used a scripting language.

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


MySQLdb extracting to a list

2007-12-13 Thread dave . dex
Hi all,

I've been searching the docs like mad and I'm a little new to python
so apologies if this is a basic question.

I would like to extract the results of the following query into a list
- SELECT columnname FROM tablename. I use the following code.

# Create a connection object and create a cursor
db = MySQLdb.Connect(http://mail.python.org/mailman/listinfo/python-list


Re: Is Python really a scripting language?

2007-12-13 Thread Marco Mariani
Bruno Desthuilliers wrote:

> As far as I'm concerned, anyone (I mean, anyone pretending to be a 
> programmer) being ignorant enough to ask such a question ranks high in 
> my bozo list. Don't waste time with bozos.


Alan Kay said it well enough without using words like "pretending", 
"ignorant" and "bozo" :)

http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273

It's worth a read.

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


Re: what the heck does this mean?

2007-12-13 Thread Bruno Desthuilliers
(Answering to Katie Smith)
> katie smith wrote:
>> Traceback (most recent call last):
>>   File "C:\Python25\empire\Empire Strategy.pyw", line 322
>> Maty = Searched(number)
>> TypeError: 'list' object is not callable

And which is line 322 ?

>> My list is NewMap1 =[0,0,0,0,0,0,2,0,2,2,3,2,0,0,0,0]
>>  
>> so Maty Searched(number is supposed to give me 0 when
>> Search = "NewMap"
>> number = 0
>> bignum = 1
>> bignumer = repr(bignum)
>> Searching = Search+bignumer
>> Searched = eval(Searching)
>> Maty = Searched[number]

Out of context, this really looks like a major WTF to me. Whenever you 
see 'eval' in your code, you can suspect a serious conception problem. 
You may want to read the doc, specially about getattr(), locals() and 
globals(). Or simply learn how to pass params... to functions.

>> instead i get that error whats up? i thought it is suppose to give me
>> NewMap1(0).

If NewMap1 is a list, trying to apply the call operator to it will 
indeed raise a TypeError with a message similar to the one you posted. 
Hint: in Python, parens are the function call operator. If you want 
subscripting, use brackets (ie : "some_list[index]", not 
"some_list(index)". Here again, reading the FineManual would be a good 
idea, because this is really Python 101.

>>when I print it it works fine  and gives me the result 0
>> but when I go to save the number as Maty-(randomletters) it keeps
>> giving me the stupid error.

The "stupid error" is usually indicating a problem in the code. Now 
since I don't see any readable code here, I just can't help. If you hope 
help, please post minimal working code[1] reproducing your problem. 
FWIW, chances are you'll spot the problem in the way...

[1] meaning: anyone can copy/paste the code snippet and run it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python really a scripting language?

2007-12-13 Thread Bruno Desthuilliers
Marco Mariani a écrit :
> Bruno Desthuilliers wrote:
> 
>> As far as I'm concerned, anyone (I mean, anyone pretending to be a 
>> programmer) being ignorant enough to ask such a question ranks high in 
>> my bozo list. Don't waste time with bozos.
> 
> 
> Alan Kay said it well enough without using words like "pretending", 
> "ignorant" and "bozo" :)

Probably. But I do like using these words, and having the opportunity to 
use them three in a same post really made me happy !-)

> http://acmqueue.com/modules.php?name=Content&pa=showpage&pid=273
> 
> It's worth a read.

Whenever I'll get a couple minutes.

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


Re: MySQLdb extracting to a list

2007-12-13 Thread John Machin
On Dec 13, 9:03 pm, [EMAIL PROTECTED] wrote:
> Hi all,
>
> I've been searching the docs like mad and I'm a little new to python
> so apologies if this is a basic question.
>
> I would like to extract the results of the following query into a list
> - SELECT columnname FROM tablename. I use the following code.
>
> # Create a connection object and create a cursor
> db = MySQLdb.Connect( cursor = db.cursor()
> # Make SQL string and execute it
> sql = "SELECT columnname FROM tablename"
> cursor.execute(sql)
> # Fetch all results from the cursor into a sequence and close the
> connection
> results = cursor.fetchall()
> db.close()
> print results
>
> The output from the above gives the following:
>
> (('string1',), ('string2',), ('string3',))
>
> When I'm expecting
> ('string1', 'string2', 'string3')
>
> I could pass this through some string manipulation but I'd guess I'm
> doing something wrong. Please could someone point me in the right
> direction.
>

Your SQL query has returned 3 rows. Each row contains only 1 column.

Each row is returned as a tuple of 1 element. The whole result is a
tuple of 3 rows. You don't need string manipulation, you need tuple
manipulation.

Better example:
select name, hat_size from friends;
results in:
(('Tom', 6), ('Dick', 7), ('Harry', 8))

so:
>>> result = (('Tom', 6), ('Dick', 7), ('Harry', 8))
>>> [row[0] for row in result]
['Tom', 'Dick', 'Harry']
>>> for n, h in result:
...print 'Name: %s; hat size: %d' % (n, h)
...
Name: Tom; hat size: 6
Name: Dick; hat size: 7
Name: Harry; hat size: 8
>>> result[2][1]
8
>>>

HTH,
John

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


Re: what the heck does this mean?

2007-12-13 Thread Remco Gerlich
On Dec 13, 2007 4:57 AM, katie smith <[EMAIL PROTECTED]> wrote:

> Traceback (most recent call last):
>   File "C:\Python25\empire\Empire Strategy.pyw", line 322
> Maty = Searched(number)
> TypeError: 'list' object is not callable
>

This is the error message. The first line basically says "This is what
happened:"

The second shows the file, and the line number.

The third is the actual line.

Then the error message: you had a list object, and you tried to call it.

Well, looking at that line, we see Searched(number). Search is apparently a
list, and you used ( ) on it, which tries to call it, but that's not
possible.
So that's the mistake - you meant to use [ ], but used ( ).


> so Maty Searched(number is supposed to give me 0 when
> Search = "NewMap"
> number = 0
> bignum = 1
> bignumer = repr(bignum)
> Searching = Search+bignumer
> Searched = eval(Searching)
> Maty = Searched[number]
>

This isn't the actual code that gave the error message - here you used  [
].

>

Anyway, doing it like this is really bad and likely to go wrong, but that's
not your question.

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

Very beautiful girls and many useful resources and more, please check it out

2007-12-13 Thread [EMAIL PROTECTED]
Very beautiful girls and many useful resources and more,please check
it out
http://groups.google.com/group/all-good-things/web/beautiful-girls-and-ladies
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: MySQLdb extracting to a list

2007-12-13 Thread dave . dex
On Dec 13, 10:40 am, John Machin <[EMAIL PROTECTED]> wrote:
> On Dec 13, 9:03 pm, [EMAIL PROTECTED] wrote:
>
>
>
> > Hi all,
>
> > I've been searching the docs like mad and I'm a little new to python
> > so apologies if this is a basic question.
>
> > I would like to extract the results of the following query into a list
> > - SELECT columnname FROM tablename. I use the following code.
>
> > # Create a connection object and create a cursor
> > db = MySQLdb.Connect( > cursor = db.cursor()
> > # Make SQL string and execute it
> > sql = "SELECT columnname FROM tablename"
> > cursor.execute(sql)
> > # Fetch all results from the cursor into a sequence and close the
> > connection
> > results = cursor.fetchall()
> > db.close()
> > print results
>
> > The output from the above gives the following:
>
> > (('string1',), ('string2',), ('string3',))
>
> > When I'm expecting
> > ('string1', 'string2', 'string3')
>
> > I could pass this through some string manipulation but I'd guess I'm
> > doing something wrong. Please could someone point me in the right
> > direction.
>
> Your SQL query has returned 3 rows. Each row contains only 1 column.
>
> Each row is returned as a tuple of 1 element. The whole result is a
> tuple of 3 rows. You don't need string manipulation, you need tuple
> manipulation.
>
> Better example:
> select name, hat_size from friends;
> results in:
> (('Tom', 6), ('Dick', 7), ('Harry', 8))
>
> so:>>> result = (('Tom', 6), ('Dick', 7), ('Harry', 8))
> >>> [row[0] for row in result]
>
> ['Tom', 'Dick', 'Harry']>>> for n, h in result:
>
> ...print 'Name: %s; hat size: %d' % (n, h)
> ...
> Name: Tom; hat size: 6
> Name: Dick; hat size: 7
> Name: Harry; hat size: 8
>
> >>> result[2][1]
> 8
>
> HTH,
> John

Many thanks John,

Really well explained and I understand what to do now. It's much
appreciated.

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


Re: Is a "real" C-Python possible?

2007-12-13 Thread Bruno Desthuilliers
sturlamolden a écrit :
> On 12 Des, 17:00, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> 
>> Python has not become what it is, and achieved the success it has,
>> because a bunch of people really wanted to use Lisp but didn't think
>> other people could handle it.
>>
>> The goal of these sorts of discussions should be to make Python a
>> better Python.
> 
> I do not want to use Lisp. The syntax is awkward and strange, and does
> not fit in my brain. I cannot read Lisp code and get a mental image of
> what it does. Readability is what sets Python apart.

Part of this readability comes from opiniated choices wrt/ syntax. 
Letting anyone invent it's own syntax could well ruin this.

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


kniterbasdb and datetime

2007-12-13 Thread Laszlo Nagy

  Hi All,

I connected to a FireBird 1.5 database this way:

import kinterbasdb
kinterbasdb.init(type_conv=200) # See 
http://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_is_mxdatetime_required

Then I try to update the database:

sql = "UPDATE TABLE1 SET DATEFIELD=? where ID = ?"
params=[datetime.date(2007,11,01),2341]
cursor.execute(sql,params)

I get this error:

kinterbasdb.ProgrammingError: (-413, 'isc_dsql_execute: \n  conversion 
error from string "2007-11-01"')

What is wrong here?

Thanks,

Laszlo

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


releasing the reference returned by PyLong_FromLong, PyString_FromString & friends

2007-12-13 Thread grbgooglefan
I am having a object tuple created at application startup. This tuple
I pass on to a python function in call to:
PyObject_CallObject(pcatInfo->pPyEvalFunction,pTuple);

For setting the values in this tuple, I am using PyLong_FromLong,
PyString_FromString & friends functions.
PyTuple_SetItem(pTuple,nCtr,PyString_FromString(szOrdValue));

My worry is that I will be doing this operation lot many times in the
active duration of my application. During this time I do not want to
delete the tuple (pTuple) object passed to PyObject_CallObject, to
avoid the time taken for creating the object every time.

But this poses another problem. Every call I make to PyLong_FromLong,
PyString_FromString & friends & functions, they return references.
How do we release the references or objects returned by these
functions?
What is the optimum strategy in this?
Please guide.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "do" as a keyword

2007-12-13 Thread Tommy Grav

On Wed, 12 Dec 2007 09:46:09 -0600, Chris Mellon wrote:

> I agree that it's fundamental, but I'd like to mention that I've  
> written
> many thousands of lines of Python code, from throwaway code for
> demonstration to enterprisey servers and all sorts of things in  
> between
> and I've *never* written a "1 or more times" loop except when I was
> demonstrating that exact thing. One thing that Python has definitely
> changed my thinking about is that I tend to formulate both problems  
> and
> solutions in terms of iteration over sequence rather than as  
> traditional
> conditional based looping. If I need a "1 or more" loop I formulate  
> the
> problem as a sequence of 1 or more elements.

How would you code an integrator-loop to stop when its error goes below
some limit with iterations? While loops are as far as I can tell  
essential for
a number of problems in math and physics.

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


Re: "do" as a keyword

2007-12-13 Thread BJörn Lindqvist
On Dec 11, 2007 4:06 PM, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>
> However, did you have an specific need for a do-while construct?
> Perhaps we could show you the alternatives.

I have wanted do-while loops in exactly one kind of algorithms, when
you generate something and you have to keep trying until it gets
right. For example, generating random and non-overlapping points on a
grid:

import random
grid = dict()
for i in range(10):
while True:
x = random.randint(0, 4)
y = random.randint(0, 4)
if not (x, y) in grid:
break
grid[x, y] = 1

The loop runs one or more times until a vacant spot in the grid is
found. This type problem would be better expressed using a do-while:

import random
grid = dict()
for i in range(10):
do:
x = random.randint(0, 4)
y = random.randint(0, 4)
while (x, y) in grid
grid[x, y] = 1


-- 
mvh Björn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: determining bytes read from a file.

2007-12-13 Thread Diez B. Roggisch
vineeth wrote:

> Hello all,
>I have come across a weird problem, I need to determine the amount
> of bytes read from a file, but couldn't figure it out ,
>My program does this :
> __
>file = open("somefile")
>data = file.read()
>print "bytes read ", len(data)
> ---
> 
>   But the bytes read is not being printed correctly, I think bytes are
> being counted only till the first occurance of '\0' is encountered.
> Even though the file is of a very large size, the bytes till the first
> '\0' are counted.

I doubt that. Python doesn't interpret data when reading, and byte-strings
don't have a implicit 0-based length.

So I think you must be doing something different - clearly the above is not
actual code, but something made up for this post. Show us your actual code,
please.

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


Re: Difference between del and remove?

2007-12-13 Thread Yansky
Thanks for the clarification guys. :)

On Dec 13, 7:05 pm, Tim Roberts <[EMAIL PROTECTED]> wrote:
> Yansky <[EMAIL PROTECTED]> wrote:
>
> >Got a quick n00b question. What's the difference between del and
> >remove?
>
> It would have been easier to answer if you had given a little context.
>
> "del" is a Python statement that removes a name from a namespace, an item
> from a dictionary, or an item from a list.
>
> "remove" is a member function of the 'list' class that finds a specific
> entry in the list and removes it.
>
> Example:
>
> >>> e = [9,8,7,6] ; del e[2] ; e
>
> [9, 8, 6]
>
> >>> e = [9,8,7,6] ; e.remove(2) ; e
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> ValueError: list.remove(x): x not in list
>
> >>> e = [9,8,7,6] ; e.remove(8) ; e
>
> [9, 7, 6]
>
> Note that "del e[2]" removed item number 2 (counting from 0).  e.remove(8)
> removed the item that had the value 8 from the list.  e.remove(2) failed
> because the number 2 was not in the list.
>
> Dictionaries do not have a "remove" method.  You have to use the "del"
> statement.
> --
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.

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


determining bytes read from a file.

2007-12-13 Thread vineeth
Hello all,
   I have come across a weird problem, I need to determine the amount
of bytes read from a file, but couldn't figure it out ,
   My program does this :
__
   file = open("somefile")
   data = file.read()
   print "bytes read ", len(data)
---

  But the bytes read is not being printed correctly, I think bytes are
being counted only till the first occurance of '\0' is encountered.
Even though the file is of a very large size, the bytes till the first
'\0' are counted.

 Can someone pls advise me regarding this.
 Thanks.

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


Re: determining bytes read from a file.

2007-12-13 Thread John Machin
On Dec 13, 11:04 pm, vineeth <[EMAIL PROTECTED]> wrote:
> Hello all,
>I have come across a weird problem, I need to determine the amount
> of bytes read from a file, but couldn't figure it out ,
>My program does this :
> __
>file = open("somefile")
>data = file.read()
>print "bytes read ", len(data)
> ---
>
>   But the bytes read is not being printed correctly, I think bytes are
> being counted only till the first occurance of '\0' is encountered.
> Even though the file is of a very large size, the bytes till the first
> '\0' are counted.
>
>  Can someone pls advise me regarding this.
>  Thanks.
>
> Best Regards,
> Vineeth.

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


Re: determining bytes read from a file.

2007-12-13 Thread vineeth
On Dec 13, 5:13 pm, "Diez B. Roggisch" <[EMAIL PROTECTED]> wrote:
> vineeth wrote:
> > Hello all,
> >I have come across a weird problem, I need to determine the amount
> > of bytes read from a file, but couldn't figure it out ,
> >My program does this :
> > __
> >file = open("somefile")
> >data = file.read()
> >print "bytes read ", len(data)
> > ---
>
> >   But the bytes read is not being printed correctly, I think bytes are
> > being counted only till the first occurance of '\0' is encountered.
> > Even though the file is of a very large size, the bytes till the first
> > '\0' are counted.
>
> I doubt that. Python doesn't interpret data when reading, and byte-strings
> don't have a implicit 0-based length.
>
> So I think you must be doing something different - clearly the above is not
> actual code, but something made up for this post. Show us your actual code,
> please.
>
> diez

Hi,
 The program tries to create a C Byte array of HEX data from a binary
input file (for ex : to embed a .png image with the application as an
array),
 Here is the program :

"""
python script to create a bit stream of a input binary file.
Usage : bit_stream_creator.py -i input_file -b bytes_to_dump
"""

import sys
from binascii  import hexlify
from optparse import OptionParser

if len(sys.argv) != 5:
print "incorrect args, usage : %s -i input_file -b bytes_to_dump" %
(sys.argv[0])
sys.exit(0)

parser = OptionParser()
parser.add_option("-i", "--input", dest="inputfilename")
parser.add_option("-b", "--bytes", dest="bytes")

(options, args) = parser.parse_args()

print "-i",options.inputfilename
print "-b",options.bytes

# open input file
infile = open(options.inputfilename)

# create the member variable name.
mem_var_name = options.inputfilename
mem_var_name = mem_var_name.replace(' ','_')
mem_var_name = mem_var_name.replace('.','_')

outfile_c = open(mem_var_name + ".c","w")
outfile_h = open(mem_var_name + ".h","w")

# read the data.
print " Reading %d bytes. " % (int(options.bytes))
bytes_reqd = int(options.bytes)
data = infile.read(bytes_reqd)
print "Bytes Read ", len(data)

# convert to hex decimal representation
hex_data = hexlify(data)
i = 0

# Write the c file with the memory dump.
outfile_c.write ( "unsigned char %s[%d] = {\n" %
(mem_var_name,bytes_reqd) )
while i < len(hex_data):
outfile_c.write( "0x%c%c" % ( hex_data[i],hex_data[i+1] ) )
i += 2
if i != len(hex_data):
outfile_c.write(",")
if i % 32 == 0:
outfile_c.write("\n")
outfile_c.write ( "\n};\n" )

# Write the .h file with forward declaration.
cpp_macro = "__"+mem_var_name.upper()+"_H__"
outfile_h.write("#ifndef "+cpp_macro + "\n")
outfile_h.write("#define "+cpp_macro + "\n")
outfile_h.write( "//%s, size %d \n" % (mem_var_name,len(data)) )
outfile_h.write( "extern unsigned char %s[%d];\n" %
(mem_var_name,bytes_reqd) )
outfile_h.write("#endif //"+cpp_macro + "\n")

#close the files.
outfile_c.close()
outfile_h.close()
infile.close()




But len(data) never proceeds beyond the NULL character.

Any help and tips is appreciated.

Thanks and Regards,
Vineeth.
-- 
http://mail.python.org/mailman/listinfo/python-list


problem in reading indices

2007-12-13 Thread Xavier Barthelemy
Hi all

I'm becoming mad, because I can't see what's wrong:

I am constructing a GUI, to plot some data.
so let's have a look of what's wrong:



in my code I have a variable named choice[i].current which is the
current selection of the i-th Listbox object. it is a tuple, with one
element.

so when I write

print type(i),type(choice[i].current)
I have: int and tuple

print type(i),type(choice[i].current[0])
I have: int and str

print type(i),type(int(choice[i].current[0]))
I have: int and int

so when I call another array with these indices
ArrayWithData[i,int(choice[i].current[0])]

I have the following error: TypeError: list indices must be integers

so I tried an intermediate value, because sometimes, the oneliner code
doesn't work, so with an intermediate passage:
value=int(choice[i].current[0])
ArrayWithData[i,value]

I have the same error

and I don't understand why. What's wrong?
May anyone have an idea?
Xavier

pm:
and print type(ArrayWithData), ArrayWithData gives me
 [array([ 2.01,  5.01]),...]

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


Re: determining bytes read from a file.

2007-12-13 Thread Matt Nordhoff
vineeth wrote:
> parser.add_option("-b", "--bytes", dest="bytes")

This is an aside, but if you pass 'type="int"' to add_option, optparse
will automatically convert it to an int, and (I think), give a more
useful error message on failure.
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: determining bytes read from a file.

2007-12-13 Thread vineeth
On Dec 13, 5:27 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 13 Dec 2007 04:04:59 -0800, vineeth wrote:
> >I have come across a weird problem, I need to determine the amount
> > of bytes read from a file, but couldn't figure it out ,
> >My program does this :
> > __
> >file = open("somefile")
> >data = file.read()
> >print "bytes read ", len(data)
> > ---
>
> >   But the bytes read is not being printed correctly, I think bytes are
> > being counted only till the first occurance of '\0' is encountered.
> > Even though the file is of a very large size, the bytes till the first
> > '\0' are counted.
>
> If you want to deal with bytes better open the file in binary mode.
> Windows alters line endings and stops at a specific byte (forgot the
> value) otherwise.
>
> Ciao,
> Marc 'BlackJack' Rintsch

Thanks, opening the file in binary mode helped, thanks a lot.
-- 
http://mail.python.org/mailman/listinfo/python-list


XML partial validation.

2007-12-13 Thread Jos� Rui Faustino de Sousa
Hi!

I am writing a text to XML parser that as to be easily extensible (via 
new text format plug-ins) and modifiable if the XML format used changes.

Since the text order does not match the XML document order I have to use 
a package that allows DOM-like handling of XML (elementtree for 
instance).

The XML DTD is still (and most likelly will be) in a state of evolution.

To make life much easier for future developers what I really needed was 
some package that implemented something like DOM level 3 XML partial 
validation.

There seems to be already something implemented in PyXML (at least the 
Validition-Err exception is there) but there is no documentation and I 
can not figure how to turn partial validation on.

Any advice?

Thank you very much.

Best regards
José Rui



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

Re: Improvements to the Python core

2007-12-13 Thread Paul Boddie
On Dec 13, 3:56 am, Christian Heimes <[EMAIL PROTECTED]> wrote:
> Paul Boddie wrote:
> > Then you haven't been reading the right IRC channel recently. ;-)
>
> What's the right channel? I'm on #python and #python-dev

But where are people who might know Psyco likely to hang out? ;-)
Anyway, it remains to be seen what happens, but by reading various
conversations I get the impression that something could be afoot. I
wouldn't want to preempt any announcements, however, so I'll say no
more on the matter.

[Cross-compilation]

> I don't get your point, especially when you talk about distutils. Please
> elaborate.

>From memory, once the Python executable is built, there's some kind of
process where modules get built with the newly built Python (perhaps
the rule labelled "Build the shared modules" in the Makefile). This
doesn't go down well when cross-compiling Python.

> (C)Python has a well known process to get new features or changes into
> the language: Write a PEP, convince enough core developers and/or Guido,
> implement the feature. I don't see a PEP about JIT in the list at
> abouthttp://www.python.org/dev/peps/, do you? :]

PEPs are very much skewed towards language changes, which then
encourages everyone and their dog to submit language changes, of
course.

> Besides nobody is going to stop you from creating a fork. Christian
> Tismer forked of stackless years ago. It's a successful branch with
> useful additions to the language. It got never merged back because
> Christian didn't feel right about it.

I think we all appreciate the work done by the core developers to
improve Python's stability and performance; new language features
don't interest me quite as much: it was, after all, possible to write
working systems in Python 1.x, with the addition of Unicode probably
rounding out quite a decent subset of what the language offers today.
The demands for greater performance enhancements than those possible
by modifying the existing virtual machine conservatively may, however,
eventually lead people to consider other paths of development just as
Stackless emerged as a fork in order to offer things that CPython
could not.

I think the pressure to fork Python will only increase over time,
considering the above together with the not inconsiderable impact of
Python 3.0 and the dependencies on Python 2.x out there in lots of
places, typically out of sight (or at least, the immediate
consideration) of the core developers.

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


Re: kniterbasdb and datetime

2007-12-13 Thread DarkBlue
On Dec 13, 7:45 pm, Laszlo Nagy <[EMAIL PROTECTED]> wrote:
>   Hi All,
>
> I connected to a FireBird 1.5 database this way:
>
> import kinterbasdb
> kinterbasdb.init(type_conv=200) # 
> Seehttp://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_is_mx...
>
> Then I try to update the database:
>
> sql = "UPDATE TABLE1 SET DATEFIELD=? where ID = ?"
> params=[datetime.date(2007,11,01),2341]
> cursor.execute(sql,params)
>
> I get this error:
>
> kinterbasdb.ProgrammingError: (-413, 'isc_dsql_execute: \n  conversion
> error from string "2007-11-01"')
>
> What is wrong here?
>
> Thanks,
>
> Laszlo


Kinterbasdb probably expects the format looking like

month/day/year

rather than

year-month-day


I have an old pythoncard app where there was the same issue
when picking a date using the wx.calendar widget,
Rearranging the format solved the problem.

here is the relevant code snippet ,maybe it gives you the idea:

def on_doCalDate_command(self,event):
# this the way to get a wx.calendar date into a
#  format suitable for kinterbasdb

D=[]
MYDATE=str(self.components.Calendar1.date)
SPLITDATE=MYDATE.split('-')
for data in SPLITDATE:
D.append(data)
YR=D[0]
MO=D[1]
DY=D[2]
JOBDATE=MO+"/"+DY+"/"+YR




DB



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


Re: determining bytes read from a file.

2007-12-13 Thread Marc 'BlackJack' Rintsch
On Thu, 13 Dec 2007 04:04:59 -0800, vineeth wrote:

>I have come across a weird problem, I need to determine the amount
> of bytes read from a file, but couldn't figure it out ,
>My program does this :
> __
>file = open("somefile")
>data = file.read()
>print "bytes read ", len(data)
> ---
> 
>   But the bytes read is not being printed correctly, I think bytes are
> being counted only till the first occurance of '\0' is encountered.
> Even though the file is of a very large size, the bytes till the first
> '\0' are counted.

If you want to deal with bytes better open the file in binary mode. 
Windows alters line endings and stops at a specific byte (forgot the
value) otherwise.

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


Re: determining bytes read from a file.

2007-12-13 Thread John Machin
On Dec 13, 11:04 pm, vineeth <[EMAIL PROTECTED]> wrote:
> Hello all,
>I have come across a weird problem, I need to determine the amount
> of bytes read from a file, but couldn't figure it out ,
>My program does this :
> __
>file = open("somefile")
>data = file.read()
>print "bytes read ", len(data)
> ---
>
>   But the bytes read is not being printed correctly, I think bytes are
> being counted only till the first occurance of '\0' is encountered.
> Even though the file is of a very large size, the bytes till the first
> '\0' are counted.

Python will not stop on reading '\0'. On Windows in text mode (the
default), '\r\n' will be converted to '\n', and it will stop on
reading ^Z aka chr(26) aka '\x1A'. If you don't want that to happen,
use open('somefile', 'rb') to get binary mode.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: E-Mail Parsing

2007-12-13 Thread Merrigan
On Dec 13, 9:29 am, Matt Nordhoff <[EMAIL PROTECTED]> wrote:
> Merrigan wrote:
> > I am writing a script to administer my E-Mail Server. The One thing
> > I'm currently struggling with is kind of Parsing the E-Mail adress
> > that I supply to the script.
>
> > I need to get the username (The part BEFORE the @ sign) out of the
> > address so that I can use it elsewhere. The problem I have with this
> > is that both the domain, and the username are variable lenghts and
> > that I have no idea how to split the two parts.
>
> > Is there any way that I can do this?
>
> > Thank ye very much.
> >>> addr = "[EMAIL PROTECTED]"
> >>> addr.split("@")
>
> ['user', 'example.com']
>
> If it's formatted like a To header ("User <[EMAIL PROTECTED]>"), use
> email.Utils.parseaddr() to get the address out of it.\
>
> The email modules might help you a lot:
>
> 
> --

Hi Matt,

Thank you very much for the help. It was exactly what I was looking
for, and made my script much safer and easier to use.

Blessings!

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


Re: E-Mail Parsing

2007-12-13 Thread Matt Nordhoff
Merrigan wrote:
> Hi Matt,
> 
> Thank you very much for the help. It was exactly what I was looking
> for, and made my script much safer and easier to use.
> 
> Blessings!
> 
>  -- Merrigan

You're welcome. :-)
-- 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: efficient data loading with Python, is that possible possible?

2007-12-13 Thread bearophileHUGS
igor:
> The fundamental difference is that in C++, I create a single object (a
> line buffer) that's reused for each input line and column values are
> extracted straight from that buffer without creating new string
> objects. In python, new objects must be created and destroyed by the
> million which must incur serious memory management overhead.

Python creates indeed many objects (as I think Tim once said "it
allocates memory at a ferocious rate"), but the management of memory
is quite efficient. And you may use the JIT Psyco (that's currently
1000 times more useful than PyPy, despite sadly not being developed
anymore) that in some situations avoids data copying (example: in
slices). Python is designed for string processing, and from my
experience string processing Psyco programs may be faster than similar
not-optimized-to-death C++/D programs (you can see that manually
crafted code, or from ShedSkin that's often slower than Psyco during
string processing). But in every language I know to gain performance
you need to know the language, and Python isn't C++, so other kinds of
tricks are necessary.

The following advice is useful too:

DouhetSukd:
>Bottom line:  Python built-in data objects, such as dictionaries and
sets, are very much optimized.  Relying on them, rather than writing a
lot of ifs and doing weird data structure manipulations in Python
itself, is a good approach to try.  Try to build those objects outside
of your main processing loops.<

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


Re: kniterbasdb and datetime

2007-12-13 Thread Laszlo Nagy
DarkBlue írta:
> On Dec 13, 7:45 pm, Laszlo Nagy <[EMAIL PROTECTED]> wrote:
>   
>>   Hi All,
>>
>> I connected to a FireBird 1.5 database this way:
>>
>> import kinterbasdb
>> kinterbasdb.init(type_conv=200) # 
>> Seehttp://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_is_mx...
>>
>> Then I try to update the database:
>>
>> sql = "UPDATE TABLE1 SET DATEFIELD=? where ID = ?"
>> params=[datetime.date(2007,11,01),2341]
>> cursor.execute(sql,params)
>>
>> I get this error:
>>
>> kinterbasdb.ProgrammingError: (-413, 'isc_dsql_execute: \n  conversion
>> error from string "2007-11-01"')
>>
>> What is wrong here?
>>
>> Thanks,
>>
>> Laszlo
>> 
>
>
> Kinterbasdb probably expects the format looking like
>
> month/day/year
>
> rather than
>
> year-month-day
>   
It is not that. The parameter passed to cursor.execute() is a 
datetime.datetime instance. It is not a string, so if there is a 
formatting problem then it must be inside kinterbasdb. (How would you 
control the format if you have no string representation?)

However, I'm 100% sure that others are also using this module and 
probably there is something that I should change, just don't know what 
it is.

Thanks,

   Laszlo



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


Re: problem in reading indices

2007-12-13 Thread Bjoern Schliessmann
Xavier Barthelemy wrote:

> so when I call another array with these indices
> ArrayWithData[i,int(choice[i].current[0])]

You don't "call" "arrays" "with indices". You are indexing the list
ArrayWithData using the index "i,int(blah)" which is invalid.
Indices must be integers, not comma seperated values.
 
> so I tried an intermediate value, because sometimes, the oneliner
> code doesn't work, so with an intermediate passage:
> value=int(choice[i].current[0])
> ArrayWithData[i,value]
> 
> I have the same error
> 
> and I don't understand why. What's wrong?
> May anyone have an idea?

I'm afraid not! You didn't specify at all what you'd like to achieve
(just "it doesn't work! why?), and clairvoyance isn't as easy as it
looks.

If you want to slice, don't use Perl syntax. Python uses a colon for
index separation to eliminate ambiguities.

some_elements = my_list[3:10]

Regards,


Björn


-- 
BOFH excuse #343:

The ATM board has run out of 10 pound notes.  We are having a whip
round to refill it, care to contribute ?

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


Re: problem in reading indices

2007-12-13 Thread Bruno Desthuilliers
Xavier Barthelemy a écrit :
> Hi all
> 
> I'm becoming mad, because I can't see what's wrong:
> 
> I am constructing a GUI, to plot some data.
> so let's have a look of what's wrong:
> 
> 
> 
> in my code I have a variable named choice[i].current which is the
> current selection of the i-th Listbox object. it is a tuple, with one
> element.
> 
> so when I write
> 
> print type(i),type(choice[i].current)
> I have: int and tuple
> 
> print type(i),type(choice[i].current[0])
> I have: int and str
> 
> print type(i),type(int(choice[i].current[0]))
> I have: int and int
> 
> so when I call another array with these indices
> ArrayWithData[i,int(choice[i].current[0])]
> 
> I have the following error: TypeError: list indices must be integers

the syntax for list subscripting is:

   thelist[index]

not:

   thelist[index,index]


If the item at thelist[index] is itself an object that supports 
subscripting and you want to subscript it to (which seems to be the case 
here), the syntax is:

   thelist[index][subindex]

IOW, try with:

   ArrayWithData[i][int(choice[i].current[0])]

> so I tried an intermediate value, because sometimes, the oneliner code
> doesn't work,

if you're sure that choice[i].current[0] exists and can be passed to the 
int type, there's no reason for the oneliner to behave differently.

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


Re: doctest quiet again before exit how

2007-12-13 Thread pelavarre
By the way, I copied this 2006-10 clp issue into Bugs.python.org. --
Pat LaVarre

""" http://bugs.python.org/issue1611

TITLE: doctest.testmod gets noisy if called more than once per
SystemExit

SUMMARY:

Calling doctest.testmod more than once before SystemExit spews stderr
messages such as "*** DocTestRunner.merge: '__main__' in both
testers;
summing outcomes"

ACTUAL RESULTS:

$ python ./tttestmod.py
*** DocTestRunner.merge: '__main__' in both testers; summing outcomes.
*** DocTestRunner.merge: '__main__' in both testers; summing outcomes.
$

EXPECTED RESULTS:

$ python ./tttestmod.py
$

NOTES:

We can reasonably expect newbies to doctest random things
that need to be doctested more than once.

We can't reasonably expect newbies to know to how to filter doctest
stdout, for example as ... http://wiki.python.org/moin/doctest

"""

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


Re: sqlite weirdness

2007-12-13 Thread kyosohma
On Dec 13, 12:12 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Wed, 12 Dec 2007 16:02:35 -0800 (PST), [EMAIL PROTECTED] declaimed
> the following in comp.lang.python:
>
>
>
> > Thanks Duncan and John! That makes sense. But why does the official
> > Python docs show an example that seems to imply that there is a "date"
> > type? See link below:
>
> >http://docs.python.org/lib/node349.html
>
> You missed two items... The open specified options to use either the
> type /name/ declared in the CREATE TABLE or a type name attached to the
> field names in a select -- and those are used to /call/ a data converter
> function that has to be registered. Key phrases:
>
> """
> There are default adapters for the date and datetime types in the
> datetime module. They will be sent as ISO dates/ISO timestamps to
> SQLite.
>
> The default converters are registered under the name "date" for
> datetime.date and under the name "timestamp" for datetime.datetime.
> """
>
> """
> con = sqlite3.connect(":memory:",
> detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
> """
> Note the "detect_types" specification. Also take care, if your
> database was populated by some other application that used that
> mm/dd/ format, you may have problems as the converters above specity
> /sending/ ISO format to the database from Python datetime objects, and
> probably expecting to convert them back on input.
> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/

Well, that makes sense. I read the parts you mentioned earlier, but I
guess I just wasn't getting my head around the concepts.

Thanks for clearing that up.

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


Re: sqlite weirdness

2007-12-13 Thread kyosohma
On Dec 13, 1:54 am, Tim Roberts <[EMAIL PROTECTED]> wrote:
> [EMAIL PROTECTED] wrote:
>



> >I'll have to refactor my code somewhat to force it to use the '-MM-
> >DD' format.
>
> Another possible solution is to use a real database.

I am using a "real" database: MS SQL Server 2000. Unfortunately, my
program will also need to run in an offsite location that cannot
connect to that server right now. Thus the need to use sqlite or some
flat-file format.

Thanks for the advice.

Mike


> --
> Tim Roberts, [EMAIL PROTECTED]
> Providenza & Boekelheide, Inc.

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


Re: to Doctest as SystemExit is to Python

2007-12-13 Thread pelavarre
> Sent: 2006-11-09; To: comp.lang.python
>
> Can doctest ... be persuaded to exit after a catastroph[e]...?
> ...
> sys.exit() doesn't do what I mean:
> it raises SystemExit ... [and doesn't exit]
> ...
> doctest.REPORT_ONLY_FIRST_FAILURE doesn't do what I mean
> [it filters stdout but doesn't exit]

Yes doctest can be asked to HALT_AT_NTH_FAILURE, including
HALT_AT_FIRST_FAILURE.

Merely (1) construct an object to replace stdout, so that (2) you can
redefine the stdout.write calls of doctest, so that (3) you can filter
the bytes written there, so that (4) you can raise KeyboardInterrupt,
so that (5) you can exit when you please.

Not a documented feature. Mostly works all the same.

A working example appeared at http://wiki.python.org/moin/doctest on
2007-11-12.

-- Pat LaVarre

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


Re: determining bytes read from a file.

2007-12-13 Thread Chris
A couple potential optimizations:

>
> # create the member variable name.
> mem_var_name = options.inputfilename
> mem_var_name = mem_var_name.replace(' ','_')
> mem_var_name = mem_var_name.replace('.','_')
>

mem_var_name = options.inputfilename.replace(' ','_').replace('.','_')
No need to assign it 3 times.

> while i < len(hex_data):
> outfile_c.write( "0x%c%c" % ( hex_data[i],hex_data[i+1] ) )
> i += 2
> if i != len(hex_data):
> outfile_c.write(",")
> if i % 32 == 0:
> outfile_c.write("\n")

This could be re-written as such:

for x in xrange(0, len(hex_data), 32):
output_c.write('%s\n' % ','.join(['0x%s'%''.join(['%c'%a for a in
hex_data[x:x+32][i:i+2]]) for i in xrange(0, 32, 2)]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic or not?

2007-12-13 Thread rishiyoor
On Dec 12, 11:33 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Wed, 12 Dec 2007 19:18:20 -0800, rishiyoor wrote:
> > I'm trying to write a program that will find the distance between two
> > groups of points in space, which have cartesian co-ordinates X,Y and Z.
>
> > I need to find the distances between each point in one group and every
> > point in the other group. So if group 1 has 6 points and group 2 had 8
> > points, I will calculate 6 x 8 = 48 distances. But I do not know the
> > number of points the user will want to use. It is typically between 50
> > and 500 in both groups combined, but may be more. Since the memory
> > required for the distances will be much larger than the points
> > themselves, I am wondering if I will have to allocate memory dynamically
> > or if there are easier ways of solving such problems in Python.
>
> Writing in Python, you never need to manually allocate memory. Sometimes,
> for especially complicated data structures, you need to take care about
> _de_allocating memory, but that's rare.
>
> In this case, you may not have enough memory to calculate all the
> combinations at once, so you should consider an iterator-based solution.
> Read up on generators and iterators.
>
> points1 = [ (1.2, 3.4), (5.7, 9.2) ]
> points2 = [ (-6.3, 0.0), (14.1, -7.8), (2.6, 12.8) ]
>
> import math
> def distance(p1, p2):
> return math.hypot(p1[0]-p2[0], p1[1]-p2[1])
>
> def distances(list1, list2):
> """Yield the distances from every pair of points."""
> for pt1 in list1:
> for pt2 in list2:
> yield distance(pt1, pt2)
>
> Now, if you want the distances one at a time you do this:
>
> >>> D = distances(points1, points2)
> >>> for d in D:
>
> ... print d
> ...
> 8.23468275042
> 17.0836178838
> 9.50368349641
> 15.1208465371
> 18.9620673978
> 4.75078940809
>
> and if you want them all at once, you can do this:
>
> >>> list(distances(points1, points2))
>
> [8.2346827504160718, 17.083617883809037, 9.5036834964133785,
> 15.120846537148639, 18.962067397834023, 4.7507894080878819]
>
> --
> Steven

Thanks, that helps.

When you say python automatically allocates memory, what would you do
if you don't know the size of the list of, say for example, the
nearest pairs between the two groups. I would probably iterate over
all the pairs and create a new list. I did a similar operation in
another program, but I had to initialize the list (statically) with x
= [0]*50 before I could use it in the for loop.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding Line numbers of HTML file

2007-12-13 Thread Ramdas
Hi Paul,

I am cross posting the same to grab your attention at pyparsing forums
too. 1000 apologies on the same count!

I am a complete newbie to parsing and totally new to pyparsing.

I have adapted your code to store the line numbers as below.
Surprisingly, the line numbers printed, when I scrap some of the URLs,
is not accurate and is kind of way off.


page = urlli2b.urlopen("www.com).read()

def tallyTagLineNumber(strg, locn, tagTokens):
line = lineno(locn,strg)
tagLocs[tagTokens[0]].append(line)



def getlinenos(page):
anyOpenTag.setParseAction(tallyTagLineNumber)
anyOpenTag.searchString(page.lower()) # changing the entire string to
lower case to get INPUT
tagnames = sorted(tagLocs.keys())
taglinedict={}
for t in tagnames:
taglinedict[t]= unique(tagLocs[t])
return taglinedict
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding Line numbers of HTML file

2007-12-13 Thread Ramdas



Hi Paul,


I am cross posting the same to grab your attention at pyparsing forums
too. 1000 apologies on the same count!

I am a complete newbie to parsing and totally new to pyparsing.

I have adapted your code to store the line numbers as below.
Surprisingly, the line numbers printed, when I scrap some of the URLs,
is not accurate and is kind of way off.

page = urlli2b.urlopen("www.com).read()

def tallyTagLineNumber(strg, locn, tagTokens):
line = lineno(locn,strg)
tagLocs[tagTokens[0]].append(line)

def getlinenos(page):
anyOpenTag.setParseAction(tallyTagLineNumber)
anyOpenTag.searchString(page.lower()) # changing the entire
string to lowercase, to grab
# input and INPUT from html as input tag ONLy

tagnames = sorted(tagLocs.keys())
taglinedict={}
for t in tagnames:
taglinedict[t]= unique(tagLocs[t])
return taglinedict


What did I do wrong and why this problem!

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


Re: efficient data loading with Python, is that possible possible?

2007-12-13 Thread Neil Cerutti
On 2007-12-13, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> On Dec 12, 4:03 pm, John Machin <[EMAIL PROTECTED]> wrote:
>> Inside your function
>> [you are doing all this inside a function, not at global level in a
>> script, aren't you?], do this:
>> from time import mktime, strptime # do this ONCE
>> ...
>> blahblah = int(mktime(strptime(s, "%m%d%y%H%M%S")))
>>
>> It would help if you told us what platform, what version of Python,
>> how much memory, how much swap space, ...
>>
>> Cheers,
>> John
>
> I am using a global 'from time import ...'. I will try to do that
> within the
> function and see if it makes a difference.
>
> The computer I am using has 8G of RAM. It's a Linux dual-core AMD or
> something like that. Python 2.4
>
> Here is some of my code. Tell me what's wrong with it :)
>
> def loadFile(inputFile, loader):
> # .zip files don't work with zlib
> f = popen('zcat ' + inputFile)
> for line in f:
> loader.handleLine(line)
> ...
>
> In Loader class:
> def handleLine(self, line):
> # filter out 'wrong' lines
> if not self._dataFormat(line): return
>
> # add a new output record
> rec = self.result.addRecord()
>
> for col in self._dataFormat.colFormats:
> value = parseValue(line, col)
> rec[col.attr] = value
>
> def parseValue(line, col):
> s = line[col.start:col.end+1]
> # no switch in python
> if col.format == ColumnFormat.DATE:
> return Format.parseDate(s)
> if col.format == ColumnFormat.UNSIGNED:
> return Format.parseUnsigned(s)
> if col.format == ColumnFormat.STRING:
> # and-or trick (no x ? y:z in python 2.4)
> return not col.strip and s or rstrip(s)
> if col.format == ColumnFormat.BOOLEAN:
> return s == col.arg and 'Y' or 'N'
> if col.format == ColumnFormat.PRICE:
> return Format.parseUnsigned(s)/100.
>
> And here is Format.parseDate() as an example:
> def parseDate(s):
> # missing (infinite) value ?
> if s.startswith('99') or s.startswith('00'): return -1
> return int(mktime(strptime(s, "%y%m%d")))

An inefficient parsing technique is probably to blame. You first
inspect the line to make sure it is valid, then you inspect it
(number of column type) times to discover what data type it
contains, and then you inspect it *again* to finally translate
it.

> And here is parseValue (will using a hash-based dispatch make
> it much faster?):

Not much.

You should be able to validate, recognize and translate all in
one pass. Get pyparsing to help, if need be.

What does your data look like?

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


Re: Is anyone happy with csv module?

2007-12-13 Thread Neil Cerutti
On 2007-12-12, John Machin <[EMAIL PROTECTED]> wrote:
> On Dec 13, 12:58 am, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> On 2007-12-12, John Machin <[EMAIL PROTECTED]> wrote:
>>
>> >> It's clear that I am thinking to completely different usages
>> >> for CSV than what most people in this thread. I use csv to
>> >> export and import numerical data columns to and from
>> >> spreadsheets.
>>
>> > For that purpose, CSV files are the utter pox and then some.
>> > Consider using xlrd and xlwt (nee pyexcelerator) to read
>> > (resp. write) XLS files directly.
>>
>> I can vouch for that advice. I was exporting .xls files to csv
>> text files for over a year before I tried the xlrd
>> solution--the whole process is less cumbersome now, though it
>> was bewildering at first working with Excel in Python.
>> Actually, surprises still crop up now and then, mostly to do
>> with cell types.
>
> Hi Neil, I'd be interested in hearing from you what caused the
> initial bewilderment with xlrd, and could it have been reduced
> by better documentation? What kinds of surprises?

The bewilderment had to do not with xlrd, but with learning the
structure of an Excel spreadsheet. My brain was extremely
resistant to what it didn't want to know. ;-)

The suprises are when a different data type gets returned for
something, like a zip code, whose cases I thought I had covered.
This is not a problem with xlrd either, but with my data source
providing slighly different data, resulting in errors. E.g., the
first time I got a zip+4 instead of a zip.

When I was exporting to csv, I handled those issues by manually
formatting the columns before exporting. This is what made it
cumbersome. I traded that in for the occasional pupu platter of
data. But by using Python directly on the spreadsheet, I have to
fix new problems only *once*.

>> The advantage of working with csv was that everything was a
>> string.
>
> It depends of your point of view. I'd regard that as a
> DISadvantage :-) With xlrd, if you have no expectation about
> the type of data in a cell, but need/want to know, xlrd will
> tell you. If you do have an expectation, you can check if
> actual == expected.

Sorry, my statement was nonsense. My data was only unified before
exporting because I unified it manually, e.g., making a ziptext
column and setting it to =TEXT(ZIP, "0").

So I'd say the bewilderment and surprise I experience are coming
from my reluctance to learn, and my data, respectively--not from
any property of xlrd.

-- 
Neil Cerutti
To succeed in the world it is not enough to be stupid, you must also be well-
mannered. --Voltaire
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: kniterbasdb and datetime

2007-12-13 Thread Laszlo Nagy

>> Kinterbasdb probably expects the format looking like
>>
>> month/day/year
>>
>> rather than
>>
>> year-month-day
>> 
All right, I tried the month/day/year version:

print sql
print params
cur.execute(sql,params)

Results in:

Inserting new TTT codes...insert into ttt(

ID,
TTT,
KIHIR
) VALUES (
GEN_ID(G_TTT,1),
?,?)
[210227753, '11/1/2007']
Traceback (most recent call last):
  File "c:\Delphi5_Brinkman\Projects\TTTImport\tttupdate.py", line 131, 
in 
cur.execute(sql,params)
kinterbasdb.ProgrammingError: (-413, 'isc_dsql_execute: \n  conversion 
error from string "2007-11-01"')


You see, I passed '11/1/2007' but the error says "2007-11-01". So what?

I also tried this:


Inserting new TTT codes...insert into ttt(

ID,
TTT,
KIHIR
) VALUES (
GEN_ID(G_TTT,1),
?, cast( ? as date) )
[210227753, '11/1/2007']

Results in:


Traceback (most recent call last):
  File "c:\Delphi5_Brinkman\Projects\TTTImport\tttupdate.py", line 131, 
in 
cur.execute(sql,params)
kinterbasdb.ProgrammingError: (-804, 'isc_dsql_prepare: \n  Dynamic SQL 
Error\n
 SQL error code = -804\n  Data type unknown')

Right now I cannot see any way to specify a date parameter and as time 
goes by, it is becoming a biger problem for me. :-(

Please help.

Laszlo

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


Re: Is Python really a scripting language?

2007-12-13 Thread Bruno Desthuilliers
Neil Cerutti a écrit :
> On 2007-12-13, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>> I have repeatedly argued in the past that we do ourselves a
>> disservice by describing Python as an interpreted language.
>>
>> Python is compiled. It has a compiler. It even has a built-in
>> function "compile". It's just not compiled to *machine code* --
>> but with even machine code often running on a virtual machine
>> in the CPU(s), the distinction is far less important now than
>> it was when Sun described Java as a compiled language despite
>> the lack of JIT compilers.
> 
> When folks say Python is an interpreted language I think they
> mean it informally--they just mean you have to run an interpreter
> to execute it. 

How often do you hear that Java is "an interpreted language" ?

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


Re: Dynamic or not?

2007-12-13 Thread Marc 'BlackJack' Rintsch
On Thu, 13 Dec 2007 06:51:23 -0800, rishiyoor wrote:

> When you say python automatically allocates memory, what would you do
> if you don't know the size of the list of, say for example, the
> nearest pairs between the two groups. I would probably iterate over
> all the pairs and create a new list. I did a similar operation in
> another program, but I had to initialize the list (statically) with x
> = [0]*50 before I could use it in the for loop.

Only if you used an index instead of starting with an empty list and
appending values to it.  Or in simple cases a list comprehension might
replace a ``for`` loop.

"Bad" and "unpythonic" example:

new = [0] * len(old)
for i in xrange(len(old)):
new[i] = do_something(old[i])

Better written as:

new = list()
for item in old:
new.append(do_something(item))

Or as list comprehension:

new = [do_something(item) for item in old]

Or:

new = map(do_something, old)

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


Re: How to get milliseconds when substructing datetime objects?

2007-12-13 Thread Dmitri O.Kondratiev
*Gabriel thanks for detailed info!
Actually I have already went the same (only more limited :) way as you
suggested  and did some poking with dir() at datetime and timedelta objects.

This time I have bumped into the following problems that I can't find ready
solutions yet:

Subtracting of datetime objects results in timedelta object, so:

d1 = datetime(2007,12,31, 0,40, 15,400)
d2 = datetime(2008,1,2, 0,30, 16,300 )
dt = d2 - d1
print "Time difference: "+ str(dt)

Will output:
Time difference: 1 day, 23:50:00.00

This means that time difference between d2 and d1 is 1 day 23 hours 50
minutes 0 seconds and 00 microseconds.

Ok, looks nice and useful! Yet questions remain:

Are there any standard Python library functions that:
1) Convert timedelata object to micro- or milliseconds?
2) Convert timedelata object to datetime object?
3) Convert datetime object to milli- or microseconds? So I could do
something like this:

d1 = datetime(2007,12,31, 0,40, 15,400)
d2 = datetime(2008,1,2, 0,30, 16,300 )
dt = d2 - d1
dt.milliseconds()

and also this:

t1 = datetime.datetime.now()
millis = t1.milliseconds()

Thanks!
Dima

**Gabriel Genellina* gagsl-py2 at yahoo.com.ar

*Thu Dec 13 00:13:22 CET 2007*

   - Previous message: How to get milliseconds when substructing datetime
   objects?
   
   - Next message: Solve a graphical problem about different logos with a
   script
   
   - *Messages sorted by:* [ date
]
[
   thread 
]
[
   subject 
]
[
   author 
]

--

En Wed, 12 Dec 2007 11:40:24 -0300, Dmitri O.Kondratiev
http://mail.python.org/mailman/listinfo/python-list>> escribió:

>* Please help to find simple solutiion for measuring times of operations
*>* with
*>* millisecond precision.
*>* For this I am trying to use datetime() objects:
*>*
*>* import time
*>* import datetime
*>*
*>* def dreamTime(secs):
*>* t1 = datetime.datetime.now()
*>* time.sleep(secs)
*>* t2 = datetime.datetime.now()
*>* dt = t2 - t1
*>* print "Start time: "+str(t1)
*>* print "Stop  time: "+str(t2)
*>* print "Dream time sec: "+str(dt)
*>* """
*>* # The following code results in errors like:
*>* # AttributeError: 'datetime.timedelta' object has no attribute
*>* 'second'
*>* """
*>* dts = dt.second
*>* dtmicro = dt.microsecond
*>* dtmilli = dts * 1000 + dtmicro / float(1000)
*>* dts2 = dtmilli / float(1000)
*>* print "Dream Millies: "+str(dtmilli)
*>* print "Dream Seconds, again: "+str(dts2)
*
Reading the docs at http://docs.python.org/lib/datetime-timedelta.html you
can see that timedelta objects have a "seconds" attribute (not "second").

Ok, and how do you know that in the first place? There are several ways
you can get this information from Python itself, just open the interpreter
and see:

py> import datetime
py> t1=datetime.datetime.now()
py> t2=datetime.datetime.now()
py> dt=t2-t1
py> dt
datetime.timedelta(0, 5, 969000)

In case you didn't know what type dt is:

py> type(dt)

py> repr(dt)
'datetime.timedelta(0, 5, 969000)'

Now you can now look for "timedelta" inside the Help files.
A quick way to enumerate attributes is to use dir():

py> dir(dt)
['__abs__', '__add__', '__class__', .., '__sub__',
'days', 'max', 'microseconds', 'min', 'resolution', 'seconds']

Look at 'seconds' there. Another useful function is vars(), but doesn't
work for this kind of object; just as an example, I'll show vars(datetime):

py> vars(dt)
Traceback (most recent call last):
   File "", line 1, in 
TypeError: vars() argument must have __dict__ attribute
py> vars(datetime)
{'timedelta': , 'MAXYEAR': , 'datetime':
, 'date': , 'datetime_CAPI':
, 'tzinfo': , 'time': , 'MINYEAR': 1, '__name__': 'datetime', '__doc__': 'Fast
implementation
  of the datetime type.'}

Using the built-in help system:

py> help(dt)
Help on timedelta object:

class timedelta(__builtin__.object)
  |  Difference between two datetime values.
  |
  |  Methods defined here:
  |
  |  __abs__(...)
  |  x.__abs__() <==> abs(x)
  |
  | [...several other methods...]
  |
  |  --
  |  Data descriptors defined here:
  |
  |  days
  |  Number of days.
  |
  |  microseconds
  |  Number of microseconds (>= 0 and less than 1 second).
  |
  |  seconds
  |  Number of seconds (>= 0 and less than 1 day).

You can see "seconds" there too.
help(datetime.timedelta) or help("datetime.timedelta") work too.

Also, many editors/IDEs have an autocomplete feature: after typing

Re: Is Python really a scripting language?

2007-12-13 Thread Neil Cerutti
On 2007-12-13, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
> I have repeatedly argued in the past that we do ourselves a
> disservice by describing Python as an interpreted language.
>
> Python is compiled. It has a compiler. It even has a built-in
> function "compile". It's just not compiled to *machine code* --
> but with even machine code often running on a virtual machine
> in the CPU(s), the distinction is far less important now than
> it was when Sun described Java as a compiled language despite
> the lack of JIT compilers.

When folks say Python is an interpreted language I think they
mean it informally--they just mean you have to run an interpreter
to execute it. *How* it's translated is irrelevent to the
*informal* meaning.

And I'd further argue that the informal meaning is the only one
that makes any sense.

Formally:

>>> hasattr(Language, 'iterpreted')
False

>>> hasattr(Implementation, 'interpreted')
True

;-)

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


Re: Pascal code checker!

2007-12-13 Thread Neil Cerutti
On 2007-12-13, Dotan Cohen <[EMAIL PROTECTED]> wrote:
> On 13/12/2007, Tim Chase <[EMAIL PROTECTED]> wrote:
>>  >> Oof!  Fond as I am of promoting pyparsing, writing a Pascal
>>  >> compiler (or even just syntax checker) is not a job I would
>>  >> tackle lightly, much less suggest to a new Python developer.
>>
>> True enough...thus my weeks/months/years estimate for such an
>> undertaking :)
>>
>> But if not mentioned, you know the next question would be "how do
>> I create a regular expression to match valid Pascal programs?"
>>
>
> Go track down the source code of an open source text editor
> that supports Pascal highlighting. Kate comes to mind. It's not
> written in Python, but it will have Pascal parsing code for the
> highlighter.

A syntax highlighter usually knows very little about the syntax
of a language. Mostly, it just finds keywords and highlights
them. The improvements beyond that will generally be haphazard,
e.g., the Vim syntax highlighting code for Python knows basically
what a function header looks like so it can highlight the
function name. It also (doesn't really) know how to figure out
what's a string and what isn't.

The auto-indenter is often smarter about syntax, but knows just a
small subset of syntax rules, enought to do proper indenting. For
some languages, e.g., Python, that's a fairly small subset. For
others, it's cumbersomely large and Vim's support is cruddy.

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


Re: Pascal code checker!

2007-12-13 Thread Zentrader
The OP was not talking about a Python program to check the Pascal
program as I read it

> to make application in python
> that would send code (text) to pascal compiler...and it would return
> result and then application would show that result.

So he/she/it would want subprocess to compile the Pascal program/file
and get the resulting output.  Let's not complicate the issue since
this appears to be someone relatively new to Python.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question from a python newbie

2007-12-13 Thread Duncan Booth
Russell <[EMAIL PROTECTED]> wrote:

>  I've searched the Language
> Reference and was not able to find any info regarding the structure of
> this code fragment:
> 
> int(text) if text.isdigit() else text

http://docs.python.org/whatsnew/pep-308.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Finding Line numbers of HTML file

2007-12-13 Thread Paul McGuire
On Dec 13, 9:01 am, Ramdas <[EMAIL PROTECTED]> wrote:
> Hi Paul,
>
> I am cross posting the same to grab your attention at pyparsing forums
> too. 1000 apologies on the same count!
>
> I am a complete newbie to parsing and totally new to pyparsing.
>
> I have adapted your code to store the line numbers as below.
> Surprisingly, the line numbers printed, when I scrap some of the URLs,
> is not accurate and is kind of way off.
>


Ramdas -

You will have to send me that URL off-list using e-mail, Google Groups
masks it and I can't pull it up.  In my example, I used the Yahoo home
page.  What is the URL you used, and which tags' results were off?

Just some comments:
- I did a quasi-verification of my results, using a quick-and-dirty re
match.  This did not give me the line numbers, but did give me counts
of tag names (if anyone knows how to get the string location of an re
match, this would be the missing link for an alternative solution to
this problem).  I added this code after the code I posted earlier:

print "Quick-and-dirty verify using re's"
import re
openTagRe = re.compile("<([^ >/!]+)")

tally2 = defaultdict(int)
for match in openTagRe.findall(html):
tally2[match] += 1

for t in tally2.keys():
print t,tally2[t],
if tally2[t] != len(tagLocs[t]):
print "<<<"
else:
print

This crude verifier turned up no mismatches when parsing the Yahoo
home page.

- Could the culprit be your unique function?  You did not post the
code for this, so I had to make up my own:

def unique(lst):
return sorted(list(set(lst)))

This does trim some of the line numbers, but I did not try to validate
this.

- In your getlinenos function, it is not necessary to call
setParseAction every time.  You only need to do this once, probably
right after you define the tallyTagLineNumber function.

- Here is an abbreviated form of getlinenos:

def getlinenos(page):
# clear out tally dict, so as not to get crossover data from
# a previously-parsed page
tagLocs.clear()
anyOpenTag.searchString(page)
return dict((k,unique(v)) for k,v in tagLocs.items())

If you wanted, you could even inline the unique logic, without too
much obfuscation.

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


Re: Question from a python newbie

2007-12-13 Thread Remco Gerlich
On Dec 13, 2007 4:39 PM, Russell <[EMAIL PROTECTED]> wrote:

> I've been learning Python slowly for a few months, coming from a C/C+
> +, C#, Java, PHP background.  I ran across a code fragment I'm having
> trouble wrapping my brain around.  I've searched the Language
> Reference and was not able to find any info regarding the structure of
> this code fragment:
>
> int(text) if text.isdigit() else text


Hi,

It's a pretty new construct; basically it's Python's version of the ? :
"ternary operator" in other languages.

The line above is equivalent to

text.isdigit() ? int(text) : text

in, for instance, C.

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

Re: Is Python really a scripting language?

2007-12-13 Thread Paul Rudin
Neil Cerutti <[EMAIL PROTECTED]> writes:

> On 2007-12-13, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>> I have repeatedly argued in the past that we do ourselves a
>> disservice by describing Python as an interpreted language.
>>
>> Python is compiled. It has a compiler. It even has a built-in
>> function "compile". It's just not compiled to *machine code* --
>> but with even machine code often running on a virtual machine
>> in the CPU(s), the distinction is far less important now than
>> it was when Sun described Java as a compiled language despite
>> the lack of JIT compilers.
>
> When folks say Python is an interpreted language I think they
> mean it informally--they just mean you have to run an interpreter
> to execute it. *How* it's translated is irrelevent to the
> *informal* meaning.
>
> And I'd further argue that the informal meaning is the only one
> that makes any sense.
>

Many people still talk about lisp as "interpreted" despite the fact
that there have been compilers (that compile to machine code) for
decades. 

I'm not sure it's really a property of a language, rather of an
implementation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dynamic or not?

2007-12-13 Thread Bruno Desthuilliers
[EMAIL PROTECTED] a écrit :
> On Dec 12, 11:33 pm, Steven D'Aprano <[EMAIL PROTECTED]
> cybersource.com.au> wrote:
(snip)
> 
> When you say python automatically allocates memory, what would you do
> if you don't know the size of the list

thelist = []
thelist.append('Ever')
thelist.append('bothered')
thelist.append('reading')
thelist.append('the')
thelist.append('fine')
thelist.append('manual')
thelist.append('?')

print thelist

> of, say for example, the
> nearest pairs between the two groups. I would probably iterate over
> all the pairs and create a new list. I did a similar operation in
> another program, but I had to initialize the list (statically) with x
> = [0]*50 before I could use it in the for loop.

You'd be better learning how to properly use lists and iterations in 
Python... While you're at it, add list comprehensions, 
iterators/generators and itertools to the list (pun intented).

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


Re: Tuples !?!?

2007-12-13 Thread Jason
On Dec 11, 3:08 pm, [EMAIL PROTECTED] wrote:
> On 11 Dez, 22:02, [EMAIL PROTECTED] wrote:
>
> > Ok. This is small code.
>
> > The problem is '2' != 2 there is a way of converting 'some number' in
> > number ?
>
> > Thanks.
>
> > # -*- coding: cp1252 -*-
> > import random
> > import csv
> > import struct
> > import array
>
> > # resultados para colocar nos campos
> > def gera_string(res):
>
> > # acampo3
> > acampo1=((0,5,'muito reduzidos'),(6,20,'reduzidos'),
> > (21,32,'satisfatórios'),(33,40,'bons'),(41,45,'excelentes'))
> > campo1=''
>
> > for a in acampo1:
> > print res[1]
> > if (res[1]>=a[0] and res[1]<=a[1]):
> > campo1=a[2]
>
> > return campo1
>
> > # processar
>
> > res=['a','2']
>
> > print gera_string(res)
>
> > quit()
>
> > On 11 Dez, 20:40, Bruno Desthuilliers
>
> > <[EMAIL PROTECTED]> wrote:
> > > [EMAIL PROTECTED] a écrit :
>
> > > > Hi,
>
> Thanks. I have found that there is int() function on python. The print
> function always show me a number when was 'number'. Ok thanks.
>
> > > > Is the tuple comparison brooked in python ?!?!?
>
> > > Given the size and average level of the user base, I think this would
> > > have been noticed.
>
> > > > Try this
>
> > > If you hope anyone to try anything, please post the *minimal* working
> > > code showing the problem. And while your at it, also explain the
> > > expected result.
>
> > > > and you will see funny things:
>
> > > Sorry but the only thing I see so far is that your code needs refactoring.

Python objects have two ways of representing themselves.  The print
statement converts the objects in it into strings.  Python objects can
also have a representative string which should give you enough
information to determine if you're dealing with a number or a string.
You can get this representative string via the repr() built-in
function.  To get the normal string of an object, the str() built-in
will perform the conversion.

If you're using the string formatting operator (%), the "%s" specifier
will use the normal string, while the "%r" specifier will use the
representative string.

Please note that repr() will show you *all* the digits of a floating
point number, while the normal string conversion may round.  This is
because floating-point numbers cannot represent most decimal exactly.
This isn't a flaw in Python, but a flaw in all IEEE floating-point
hardware (ie, your processor).

If you're using Python interactively, Python will display the results
of expressions with their representative strings.

For example:
>>> 5
5
>>> '5'
'5'
>>> 0.1
0.10001
>>> print '5', 5
5 5
>>> print repr('5'), repr(5)
'5' 5
>>> print 'Normal Strings: %s, %s, %s' % ('5', 5, 0.1)
Normal Strings: 5, 5, 0.1
>>> print 'Repr Strings: %r, %r, %r' % ('5', 5, 0.1)
Repr Strings: '5', 5, 0.10001
>>>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python really a scripting language?

2007-12-13 Thread Neil Cerutti
On 2007-12-13, Bruno Desthuilliers <[EMAIL PROTECTED]> wrote:
> Neil Cerutti a écrit :
>> On 2007-12-13, Steven D'Aprano <[EMAIL PROTECTED]> wrote:
>>> I have repeatedly argued in the past that we do ourselves a
>>> disservice by describing Python as an interpreted language.
>>>
>>> Python is compiled. It has a compiler. It even has a built-in
>>> function "compile". It's just not compiled to *machine code* --
>>> but with even machine code often running on a virtual machine
>>> in the CPU(s), the distinction is far less important now than
>>> it was when Sun described Java as a compiled language despite
>>> the lack of JIT compilers.
>> 
>> When folks say Python is an interpreted language I think they
>> mean it informally--they just mean you have to run an interpreter
>> to execute it. 
>
> How often do you hear that Java is "an interpreted language" ?

The difference is the p-code factor. Python's p-code is
(generally) internal only. We could fool more people if we forced
them to create .pyc files before executing the code. ;-)

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


Question from a python newbie

2007-12-13 Thread Russell
I've been learning Python slowly for a few months, coming from a C/C+
+, C#, Java, PHP background.  I ran across a code fragment I'm having
trouble wrapping my brain around.  I've searched the Language
Reference and was not able to find any info regarding the structure of
this code fragment:

int(text) if text.isdigit() else text

It is part of a larger lambda statement.  I do get the lambda
declaration, but having trouble with what is happening in that
fragment.  Here is the full lambda statement:

convert = lambda text: int(text) if text.isdigit() else text

Thanks for any help you can provide explaining this to me.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: kniterbasdb and datetime

2007-12-13 Thread Uwe Grauer
Laszlo Nagy wrote:
> 
>  Hi All,
> 
> I connected to a FireBird 1.5 database this way:
> 
> import kinterbasdb
> kinterbasdb.init(type_conv=200) # See
> http://kinterbasdb.sourceforge.net/dist_docs/usage.html#faq_fep_is_mxdatetime_required
> 
> 
> Then I try to update the database:
> 
> sql = "UPDATE TABLE1 SET DATEFIELD=? where ID = ?"
> params=[datetime.date(2007,11,01),2341]
> cursor.execute(sql,params)
> 
> I get this error:
> 
> kinterbasdb.ProgrammingError: (-413, 'isc_dsql_execute: \n  conversion
> error from string "2007-11-01"')
> 
> What is wrong here?
> 
> Thanks,
> 
>Laszlo
> 

Just tested this against my 2.03 firebird db:

import datetime
import kinterbasdb as db

db.init(type_conv=200)
con = db.connect(dsn='myhost:fbtool-dev', user='sysdba', password='pwd')
sql = "update jnp set gebdat = ? where iid = ?"
params = [datetime.date(2007, 11, 01), 152]
cur = con.cursor()
cur.execute(sql,params)
con.commit()

It worked.
What version of kinterbasdb are you using?

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


Re: Question from a python newbie

2007-12-13 Thread Russell
I suspected it was a ternary type of operator, but was unable to
confirm it.  And I didn't realize it was new to 2.5.  Perfectly clear
now. :)

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


Re: Question from a python newbie

2007-12-13 Thread J. Clifford Dyer
On Thu, Dec 13, 2007 at 04:57:04PM +0100, Remco Gerlich wrote regarding Re: 
Question from a python newbie:
> 
>On Dec 13, 2007 4:39 PM, Russell <[EMAIL PROTECTED]> wrote:
> 
>  I've been learning Python slowly for a few months, coming from a
>  C/C+
>  +, C#, Java, PHP background.  I ran across a code fragment I'm
>  having
>  trouble wrapping my brain around.  I've searched the Language
>  Reference and was not able to find any info regarding the structure
>  of
>  this code fragment:
>  int(text) if text.isdigit() else text
> 
>Hi,
>It's a pretty new construct; basically it's Python's version of the ? :
>"ternary operator" in other languages.
>The line above is equivalent to
>text.isdigit() ? int(text) : text
>in, for instance, C.
>Remco Gerlich
> 

Or, if you don't know C.  It is equivalent to

if text.isdigit():
int(text)
else:
text
-- 
http://mail.python.org/mailman/listinfo/python-list


how to include a tiny debug feature in my project ?

2007-12-13 Thread Stef Mientki
hello,

I've large program based, with a GUI based on wxPython,
where the user can add small parts, which I call Bricks.
A new Brick is created by inheriting from the standard-Brick.
The user should only override 1 or 2 functions from the standard-Brick.
The main properties used in those 2 functions have fixed names.
Now I've not a good idea, how I should debug that new-Brick.

Because I don't want to crash the program,
by bugs in the new-Brick,
I put the call to the overriden functions in new-Brick in a try-except 
statement.
So it won't generate errors,
and besides that,
debugging GUI is a crime,
and I certainly don't want the user to digg into the large program.

So I'm thinking of another approach:
- locate the 2 functions of the new-Brick
- execute them line by line through a exec-statement
- give a print statement of the most important parameters,
after the execution of each line
(The number of lines written by the user will be at most 20 lines)

Is this a good approach ?
If so, how can I execute each line separate ?
If not, what other approach should I use ?

thanks,
Stef Mientki



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


Clearing a DOS terminal in a script

2007-12-13 Thread Stephen_B
This doesn't seem to work in a dos terminal at the start of a script:

from os import popen
print popen('clear').read()

Any idea why not? Thanks.

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


Re: Dynamic or not?

2007-12-13 Thread rishiyoor
On Dec 13, 10:24 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Thu, 13 Dec 2007 06:51:23 -0800, rishiyoor wrote:
> > When you say python automatically allocates memory, what would you do
> > if you don't know the size of the list of, say for example, the
> > nearest pairs between the two groups. I would probably iterate over
> > all the pairs and create a new list. I did a similar operation in
> > another program, but I had to initialize the list (statically) with x
> > = [0]*50 before I could use it in the for loop.
>
> Only if you used an index instead of starting with an empty list and
> appending values to it.  Or in simple cases a list comprehension might
> replace a ``for`` loop.
>
> "Bad" and "unpythonic" example:
>
> new = [0] * len(old)
> for i in xrange(len(old)):
> new[i] = do_something(old[i])
>
> Better written as:
>
> new = list()
> for item in old:
> new.append(do_something(item))
>
> Or as list comprehension:
>
> new = [do_something(item) for item in old]
>
> Or:
>
> new = map(do_something, old)
>
> Ciao,
> Marc 'BlackJack' Rintsch

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


Re: how to include a tiny debug feature in my project ?

2007-12-13 Thread Diez B. Roggisch
Stef Mientki wrote:

> hello,
> 
> I've large program based, with a GUI based on wxPython,
> where the user can add small parts, which I call Bricks.
> A new Brick is created by inheriting from the standard-Brick.
> The user should only override 1 or 2 functions from the standard-Brick.
> The main properties used in those 2 functions have fixed names.
> Now I've not a good idea, how I should debug that new-Brick.
> 
> Because I don't want to crash the program,
> by bugs in the new-Brick,
> I put the call to the overriden functions in new-Brick in a try-except
> statement. So it won't generate errors,
> and besides that,
> debugging GUI is a crime,
> and I certainly don't want the user to digg into the large program.
> 
> So I'm thinking of another approach:
> - locate the 2 functions of the new-Brick
> - execute them line by line through a exec-statement
> - give a print statement of the most important parameters,
> after the execution of each line
> (The number of lines written by the user will be at most 20 lines)
> 
> Is this a good approach ?
> If so, how can I execute each line separate ?
> If not, what other approach should I use ?

See the module trace.

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


Re: How to get milliseconds when substructing datetime objects?

2007-12-13 Thread Dmitri O.Kondratiev
While looking for ready to use library I have roughly skteched the functions
that I need:

import datetime
from datetime import *

def timedelta2Micros(dt):
""" Convert timedelta object to micriseconds"""
days = dt.days
sec = dt.seconds
micros = dt.microseconds
daysSec = 24 * 60 * 60 * days
tdMicros = (daysSec + sec) * 100 + micros
return tdMicros

def micros2timedelta(micros):
""" Convert microseconds to timedelta """
oneDayMicros = 24 * 60 * 60 * 100
days = micros / oneDayMicros # whole number of days
scrapDayMicros = micros % oneDayMicros # remainder of all micros in a
day
secs = scrapDayMicros / 100 # whole number of seconds
micros = scrapDayMicros % 100 # micros left
return timedelta(days=days, seconds=secs, microseconds=micros)

In case somebody have a library with *extra* datetime functions (and better
written then these ones) please let me know!

-- 
Dmitri O. Kondratiev
[EMAIL PROTECTED]
http://www.geocities.com/dkondr


*Dmitri O.Kondratiev* dokondr at
gmail.comwrote:
*Thu Dec 13 16:19:35 CET 2007*

   - Previous message: to Doctest as SystemExit is to Python
   
   - Next message: Question from a python newbie
   
   - *Messages sorted by:* [ date
]
[
   thread 
]
[
   subject 
]
[
   author 
]

--

*Gabriel thanks for detailed info!
Actually I have already went the same (only more limited :) way as you
suggested  and did some poking with dir() at datetime and timedelta objects.

This time I have bumped into the following problems that I can't find ready
solutions yet:

Subtracting of datetime objects results in timedelta object, so:

d1 = datetime(2007,12,31, 0,40, 15,400)
d2 = datetime(2008,1,2, 0,30, 16,300 )
dt = d2 - d1
print "Time difference: "+ str(dt)

Will output:
Time difference: 1 day, 23:50:00.00

This means that time difference between d2 and d1 is 1 day 23 hours 50
minutes 0 seconds and 00 microseconds.

Ok, looks nice and useful! Yet questions remain:

Are there any standard Python library functions that:
1) Convert timedelata object to micro- or milliseconds?
2) Convert timedelata object to datetime object?
3) Convert datetime object to milli- or microseconds? So I could do
something like this:

d1 = datetime(2007,12,31, 0,40, 15,400)
d2 = datetime(2008,1,2, 0,30, 16,300 )
dt = d2 - d1
dt.milliseconds()

and also this:

t1 = datetime.datetime.now()
millis = t1.milliseconds()

Thanks!
Dima

**Gabriel Genellina* gagsl-py2 at yahoo.com.ar

*Thu Dec 13 00:13:22 CET 2007*

   - Previous message: How to get milliseconds when substructing datetime
   objects?
   
   - Next message: Solve a graphical problem about different logos with a
   script
   
   - *Messages sorted by:* [ date
]
[
   thread 
]
[
   subject 
]
[
   author 
]

--

En Wed, 12 Dec 2007 11:40:24 -0300, Dmitri O.Kondratiev
http://mail.python.org/mailman/listinfo/python-list>> escribió:

>** Please help to find simple solutiion for measuring times of operations
**>* with
*>* millisecond precision.
*>* For this I am trying to use datetime() objects:
*>*
*>* import time
*>* import datetime
*>*
*>* def dreamTime(secs):
*>* t1 = datetime.datetime.now()
*>* time.sleep(secs)
*>* t2 = datetime.datetime.now()
*>* dt = t2 - t1
*>* print "Start time: "+str(t1)
*>* print "Stop  time: "+str(t2)
*>* print "Dream time sec: "+str(dt)
*>* """
*>* # The following code results in errors like:
*>* # AttributeError: 'datetime.timedelta' object has no attribute
*>* 'second'
*>* """
*>* dts = dt.second
*>* dtmicro = dt.microsecond
*>* dtmilli = dts * 1000 + dtmicro / float(1000)
*>* dts2 = dtmilli / float(1000)
*>* print "Dream Millies: "+str(dtmilli)
*>* print "Dream Seconds, again: "+str(dts2)
*
Reading the docs at http://docs.python.org/lib/datetime-timedelta.html you
can see that timedelta objects have a "seconds" attribute (not "second").

Ok, and how do you know that in the first place? There are several ways
you can get this informatio

Re: Monitoring the output of an external program

2007-12-13 Thread Calvin Spealman
I always recommend the subprocess module for any needs like this.  
Read up on it and it should provide everything you need.

On Dec 13, 2007, at 2:41 AM, Caleb Marcus wrote:

> I'm writing something that has to invoke an external program, and  
> every time the external program prints something, update a UI. How  
> would I go about doing this?
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: what the heck does this mean?

2007-12-13 Thread Calvin Spealman

On Dec 12, 2007, at 10:57 PM, katie smith wrote:


Traceback (most recent call last):
  File "C:\Python25\empire\Empire Strategy.pyw", line 322
Maty = Searched(number)


Look, you're calling Searched right here with Searched(number)


TypeError: 'list' object is not callable

...

Maty = Searched[number]


But, here you obviously think you are actually subscripting. The WTF  
here is that you rewrote all this code into the email instead of just  
copy and pasting it to get exactly the same. Do not trust your eyes.


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

Re: Clearing a DOS terminal in a script

2007-12-13 Thread Chris Mellon
On Dec 13, 2007 10:48 AM, Stephen_B <[EMAIL PROTECTED]> wrote:
> This doesn't seem to work in a dos terminal at the start of a script:
>
> from os import popen
> print popen('clear').read()
>
> Any idea why not? Thanks.


It opens "clear" with it's own virtual terminal and clears that
instead. There's an ANSI control code you can use to reset the screen,
try printing that.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clearing a DOS terminal in a script

2007-12-13 Thread Stephen_B
On Dec 13, 11:21 am, "Chris Mellon" <[EMAIL PROTECTED]> wrote:
> It opens "clear" with it's own virtual terminal and clears that
> instead.

Even when I launch the script from a cmd shell with "python
myscript.py"?

> There's an ANSI control code you can use to reset the screen, try printing 
> that.

I googled "[2J" as an ascii sequence that it is supposed to clear
the screen. How do I send that?

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


looking for gui for python code

2007-12-13 Thread [EMAIL PROTECTED]
hi
i have written some python scripts which take command line arguments
and do some job. i would like to make it into a .exe using py2exe and
distribute it with innosetup.. befor that i would like to add some GUI
support..i mean select some values using a folder explorer etc..which
would be a good gui builder for this? i have heard about  guibuilder
from http://spectcl.sourceforge.net/  or is it better to use tkinter
(i have little experience with gui designing)

can someone  give a suggestion?
TIA
dn
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: looking for gui for python code

2007-12-13 Thread James Matthews
Using any GUI package you should be able to build your application into EXE
format!

On Dec 13, 2007 6:46 PM, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:

> hi
> i have written some python scripts which take command line arguments
> and do some job. i would like to make it into a .exe using py2exe and
> distribute it with innosetup.. befor that i would like to add some GUI
> support..i mean select some values using a folder explorer etc..which
> would be a good gui builder for this? i have heard about  guibuilder
> from http://spectcl.sourceforge.net/  or is it better to use tkinter
> (i have little experience with gui designing)
>
> can someone  give a suggestion?
> TIA
> dn
> --
> http://mail.python.org/mailman/listinfo/python-list
>



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

Re: Is a "real" C-Python possible?

2007-12-13 Thread Patrick Mullen
> > > > Kay Schluehr wrote:
> > > > Python 2.6 and 3.0 have a more Pythonic way for the problem:
> > > > class A(object):
> > > > @property
> > > > def foo(self):
> > > > return self._foo
> > > > @foo.setter
> > > > def foo(self, value)
> > > > self._foo = value
> > > > @foo.deletter
> > > > def foo(self)
> > > > del self._foo
> > > > class B(A):
> > > > # one can even overwrite the getter in a subclass
> > > > @foo.getter
> > > > def foo(self):
> > > > return self._foo * 2
> > > > Christian

On Dec 12, 2007 12:57 PM, George Sakkis <[EMAIL PROTECTED]> wrote:
> 1. The property name ('foo') is repeated *5* times for a single class.
> Talk about DRY.
> 2. Total inconsistency: @property for the getter when it is defined
> for the first time, @foo.setter/@foo.deletter for the setter/deletter,
> @foo.getter when the getter is redefined. WTF ?!

Eww, I agree with George here, with respect to these two points.  When
I looked at this my first wtf was the @property and then @foo.getter
business.  I really don't mind the current way of doing things: attr =
property(get,set).  Other mechanisms can be created with getattr
routines.  I don't really like this new syntax at all.  Too many @
marks, inconsistancies, and too many foos everywhere.  Not to mention
how long it reads.  For only getters, it's not bad though, and a
little better than property().

Decorators really don't feel pythonic to me at all, mostly due to the
@ symbol, but it looks really awful in this instance.

What about this, somewhat similar but not ugly syntax:

class A:
   foo = property()
   def foo.get():
  return self._foo
   def foo.delete():
  del self._foo
   def foo.set(val):
  self._foo = val

Defining something with a dot is currently a syntax error.  Ok, so
it's still too many foos.  At least it's consistent.  I'm not really
proposing this btw.  I'd rather not introduce more specialized syntax.

How about abusing with:

class A:
   with property("foo"):
  def get
  def set...

There's your thunk, and I really like with, but am saddened that it
has such limited use at the moment.  Of course this isn't really what
with is for...

Can anyone tell me what's wrong about the current property() syntax,
besides namespace polution?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Best way to protect my new commercial software.

2007-12-13 Thread farsheed
Thank you all. I explain what I did to do it. Very simple but what I
want:

I find the host id of system (using ipconfig) and create a hash code
based on it.(some math, md5 and functions).
the code for licensing is about 15 lines and is very fast. I needed 20
licenses and I wrote a keygen for myself.

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


python vs perl performance test

2007-12-13 Thread igor . tatarinov
First, let me admit that the test is pretty dumb (someone else
suggested it :) but since I am new to Python, I am using it to learn
how to write efficient code.

my $sum = 0;
foreach (1..10) {
my $str = chr(rand(128)) x 1024;
foreach (1..100) {
my $substr = substr($str, rand(900), rand(100));
$sum += ord($substr);
}
}
print "Sum is $sum\n";

Basically, the script creates random strings, then extracts random
substrings, and adds up the first characters in each substring. This
perl script takes 8.3 secs on my box and it can probably be improved.

When I first translated it to Python verbatim, the Python script took
almost 30 secs to run.
So far, the best I can do is 11.2 secs using this:

from random import randrange
from itertools import imap, repeat
from operator import getitem, add, getslice

result = 0
zeros = [0]*100
for i in xrange (10):
s = [chr(randrange(128))] * 1024
starts = repeat(randrange(900), 100)
ends = imap(add, starts, repeat(randrange(1,100), 100))
substrs = imap(getslice, repeat(s, 100), starts, ends)
result += sum(imap(ord, imap(getitem, substrs, zeros)))

print "Sum is ", result

There's got to be a simpler and more efficient way to do this.
Can you help?

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


Re: Is a "real" C-Python possible?

2007-12-13 Thread Chris Mellon
On Dec 13, 2007 12:04 PM, Patrick Mullen <[EMAIL PROTECTED]> wrote:
> > > > > Kay Schluehr wrote:
> > > > > Python 2.6 and 3.0 have a more Pythonic way for the problem:
> > > > > class A(object):
> > > > > @property
> > > > > def foo(self):
> > > > > return self._foo
> > > > > @foo.setter
> > > > > def foo(self, value)
> > > > > self._foo = value
> > > > > @foo.deletter
> > > > > def foo(self)
> > > > > del self._foo
> > > > > class B(A):
> > > > > # one can even overwrite the getter in a subclass
> > > > > @foo.getter
> > > > > def foo(self):
> > > > > return self._foo * 2
> > > > > Christian
>
> On Dec 12, 2007 12:57 PM, George Sakkis <[EMAIL PROTECTED]> wrote:
> > 1. The property name ('foo') is repeated *5* times for a single class.
> > Talk about DRY.
> > 2. Total inconsistency: @property for the getter when it is defined
> > for the first time, @foo.setter/@foo.deletter for the setter/deletter,
> > @foo.getter when the getter is redefined. WTF ?!
>
> Eww, I agree with George here, with respect to these two points.  When
> I looked at this my first wtf was the @property and then @foo.getter
> business.  I really don't mind the current way of doing things: attr =
> property(get,set).  Other mechanisms can be created with getattr
> routines.  I don't really like this new syntax at all.

For the record, this is not new syntax. It's implemented this way
specifically to avoid the creation of new syntax for properties.

>Too many @
> marks, inconsistancies, and too many foos everywhere.  Not to mention
> how long it reads.  For only getters, it's not bad though, and a
> little better than property().
>

I don't feel that it's especially inconsistent, and I like decorators.
Having to write foo everywhere isn't that nice, but it's only mildly
worse than C# to me - I find the extra block levels really atrocious.

> Decorators really don't feel pythonic to me at all, mostly due to the
> @ symbol, but it looks really awful in this instance.
>
> What about this, somewhat similar but not ugly syntax:
>
> class A:
>foo = property()
>def foo.get():
>   return self._foo
>def foo.delete():
>   del self._foo
>def foo.set(val):
>   self._foo = val
>
> Defining something with a dot is currently a syntax error.  Ok, so
> it's still too many foos.  At least it's consistent.  I'm not really
> proposing this btw.  I'd rather not introduce more specialized syntax.
>
> How about abusing with:
>
> class A:
>with property("foo"):
>   def get
>   def set...
>
> There's your thunk, and I really like with, but am saddened that it
> has such limited use at the moment.  Of course this isn't really what
> with is for...
>
> Can anyone tell me what's wrong about the current property() syntax,
> besides namespace polution?
>

Nothing, except that people prefer decorators and they don't like the
namespace pollution. foo = property() isn't going away and if you
prefer it (I don't) you're free to use it. If you don't like
decorators in general it's fairly obvious that you won't be partial to
a decorator based feature.

It's not that big a deal anyway, of course, the use case for
properties in Python has a much smaller scope than in C#, and
getter-only properties (which you can create with just @property) are
the majority of those.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Is Python really a scripting language?

2007-12-13 Thread sturlamolden
On 13 Des, 02:19, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:

> I have repeatedly argued in the past that we do ourselves a disservice by
> describing Python as an interpreted language. Python is compiled. It has
> a compiler. It even has a built-in function "compile".

Python is compiled to bytecode. Python's bytecode is interpreted. Does
that make Python interpreted or compiled? I could not care less.

The terms 'scripting language' and 'interpreted language' have
somewhat different meanings. 'Scripting language' typically means a
language used for one of:

- Shell scripts
- Automation macros in a larger application
- Code embedded in a web page
- CGI

Python, Perl, Lisp and Visual Basic are certainly used as scripting
languages in some settings. But that does not mean it is the only
thing they can be used for. On the other hand, JavaScript and Bourne
shell have little use except as scripting languages.

























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


Re: How to get milliseconds when substructing datetime objects?

2007-12-13 Thread Gabriel Genellina
En Thu, 13 Dec 2007 14:07:10 -0300, Dmitri O.Kondratiev  
<[EMAIL PROTECTED]> escribi�:

> While looking for ready to use library I have roughly skteched the  
> functions
> that I need:

They look fine to me. Just one thing:

> days = micros / oneDayMicros # whole number of days

It's safer to use // when you want integer division. The meaning of the /  
operator will change in a future Python version:

py> 1/2
0
py> 1//2
0
py> from __future__ import division
py> 1/2
0.5
py> 1//2
0

-- 
Gabriel Genellina

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

Re: TCP reset caused by socket.py

2007-12-13 Thread Gabriel Genellina
En Wed, 12 Dec 2007 20:12:43 -0300, Object01 <[EMAIL PROTECTED]> escribi�:

> I don't know much about the timing of Python's garbage collection.  Is
> it pretty aggressive?

As soon as the reference count reaches zero (at least for current CPython  
version). Objects that are part of a reference cycle may take a while but  
are detected and collected eventually.

-- 
Gabriel Genellina

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

Christmas Shopping Made Easy

2007-12-13 Thread rzt8lias
 This site helped me during the holidays.Check out 
http://www.christmasplayland.com
which offers some great resources and tons of deals.I definitely saved
time shopping for deals online at this site.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python vs perl performance test

2007-12-13 Thread Chris Mellon
On Dec 13, 2007 12:11 PM,  <[EMAIL PROTECTED]> wrote:
> First, let me admit that the test is pretty dumb (someone else
> suggested it :) but since I am new to Python, I am using it to learn
> how to write efficient code.
>
> my $sum = 0;
> foreach (1..10) {
> my $str = chr(rand(128)) x 1024;
> foreach (1..100) {
> my $substr = substr($str, rand(900), rand(100));
> $sum += ord($substr);
> }
> }
> print "Sum is $sum\n";
>

> Basically, the script creates random strings, then extracts random
> substrings, and adds up the first characters in each substring. This
> perl script takes 8.3 secs on my box and it can probably be improved.
>
> When I first translated it to Python verbatim, the Python script took
> almost 30 secs to run.
> So far, the best I can do is 11.2 secs using this:
>
> from random import randrange
> from itertools import imap, repeat
> from operator import getitem, add, getslice
>
> result = 0
> zeros = [0]*100
> for i in xrange (10):
> s = [chr(randrange(128))] * 1024
> starts = repeat(randrange(900), 100)
> ends = imap(add, starts, repeat(randrange(1,100), 100))
> substrs = imap(getslice, repeat(s, 100), starts, ends)
> result += sum(imap(ord, imap(getitem, substrs, zeros)))
>
> print "Sum is ", result
>
> There's got to be a simpler and more efficient way to do this.
> Can you help?

Benchmarking is usually done to test the speed of an operation. What
are you trying to measure with this test? String slicing? Numerical
operations? Looping? You're doing all sorts of bogus work for no
reason. The use of randomness is also totally arbitrary and doesn't do
anything except make it harder to confirm the correctness of the test.
Is the ability to generate 0-length substrings (which perl claims have
an ordinal of 0) intentional?

For the record, taking the randomness out makes this take 4 seconds
for perl, and 6 seconds for a literal translation in python. Moving it
into a function drops the python function to 3.5 seconds.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clearing a DOS terminal in a script

2007-12-13 Thread John Machin
On Dec 14, 3:48 am, Stephen_B <[EMAIL PROTECTED]> wrote:
> This doesn't seem to work in a dos terminal at the start of a script:
>
> from os import popen
> print popen('clear').read()
>
> Any idea why not? Thanks.

Maybe you are using a different "dos terminal". What is "clear"?

C:\junk>clear
'clear' is not recognized as an internal or external command,
operable program or batch file.

C:\junk>ver

Microsoft Windows XP [Version 5.1.2600]

C:\junk>help cls
Clears the screen.

CLS

C:\junk>

The following works for me:


import os
os.system('cls')
print 'Howzat?'


To use ANSI escape sequences with the "real" MS-DOS, one needed a
console device driver (ANSI.SYS was supplied) and had to invoke it in
the CONFIG.SYS file; presumably you can find out how to set this up in
a Windows Command Prompt window, but it doesn't seem to be worth the
bother if all you want to do is clear the window.

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


Re: Dynamic or not?

2007-12-13 Thread John Machin
On Dec 14, 2:29 am, Bruno Desthuilliers While you're at it, add list
comprehensions,
> iterators/generators and itertools to the list (pun intented).
>

'Intented' is a novel word; is it the opposite of 'decamped'?
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie design problem

2007-12-13 Thread MartinRinehart
Thanks to a lot of help, I've got the outer framework for my tokenizer
down to this:

for line_number, line in enumerate(text):
output = ''

for char_number, char in enumerate(line):
output += char

print 'At ' + str(line_number) + ', '+ str(char_number) + ': '
+ output,

Or do I?

My other tokenizers all worked with array indices. When I came to,
say, an open quote character, I passed control to the get_a_string()
method. That would, locate the end of the string, push a string token
onto the stack and then forward the char array index to point to the
next character in the line.

Is there a pythonic design I'm overlooking?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: python vs perl performance test

2007-12-13 Thread Arnaud Delobelle
On Dec 13, 6:11 pm, [EMAIL PROTECTED] wrote:

> from random import randrange
> from itertools import imap, repeat
> from operator import getitem, add, getslice
>
> result = 0
> zeros = [0]*100
> for i in xrange (10):
> s = [chr(randrange(128))] * 1024
> starts = repeat(randrange(900), 100)
> ends = imap(add, starts, repeat(randrange(1,100), 100))
> substrs = imap(getslice, repeat(s, 100), starts, ends)
> result += sum(imap(ord, imap(getitem, substrs, zeros)))
>
> print "Sum is ", result
>
> There's got to be a simpler and more efficient way to do this.
> Can you help?
>
> Thanks,
> igor

repeat(randrange(n), p) doesn't do what you want it to:
It generates a single random number less thant n and repeats
it p times

>>> list(repeat(randrange(100), 10))
[54, 54, 54, 54, 54, 54, 54, 54, 54, 54]

Instead you want imap(randrange, repeat(n, p)):

>>> map(randrange, repeat(100, 10))
[69, 68, 81, 26, 60, 76, 40, 55, 76, 75]

I don't understand why you make the Python version so complicated.

--
Arnaud

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


Eclipse/PyQt/Eric4 question

2007-12-13 Thread king kikapu
Hi, this is actually goes to whoever is using Eclipse and Eric4, the
IDE that comes bundled with PyQt.
I was using Eclipse until i saw Eric4 and i started experiment with
it, very nice work.

Eric4 has a feature that actually reminds us the work of some
expensive IDEs, like Visual Studio, Delphi and the like: when you
compile your project, it checks to see if some .ui files (Qt Designer
form files) has changed and if so, it call pyuic.bat and compiles it
(or them) transparently so it then runs your program with latest form
changes.

In Eclipse, i have the luxury of double-click a .ui file and thus Qt
Designer opens and then design my forms there, but i cannot fing an
automatic way to accomplish the thing that eric4 does: e.x.
automatically compile changed .ui files when i hit F9. And it really a
loss of time to go to dos-prompt and do this manually.

Has anyone who work on Eclipse/PyDev and PyQt, found a way to do
this ??
-- 
http://mail.python.org/mailman/listinfo/python-list


Python implementation of "include"

2007-12-13 Thread lloyd
Hello,

I've been using the
Python-based Karrigell web application framework. It has the very handy
word "include" that inserts a code file into into the stream of
execution. E.g. if myFile.py contains the code:

print "This is a message from myFile.py"

and my script is:

print "Something"
include "myFile.py"
print "Something more"

The output would be:

Something
This is a message from myFile.py
Something more

Since
I'm considering moving my application to a different web application
framework, I'd like to replace include with a pure python construct.
I've discovered several ways to do it, but they all seem kludgy in one
way or another. Is there a simple, elegant way to do this?

Many thanks,

Lloyd






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

Re: Eclipse/PyQt/Eric4 question

2007-12-13 Thread Fabio Zadrozny
> In Eclipse, i have the luxury of double-click a .ui file and thus Qt
> Designer opens and then design my forms there, but i cannot fing an
> automatic way to accomplish the thing that eric4 does: e.x.
> automatically compile changed .ui files when i hit F9. And it really a
> loss of time to go to dos-prompt and do this manually.
>
> Has anyone who work on Eclipse/PyDev and PyQt, found a way to do
> this ??


You can create a builder for calling an external program to do that on
builds (right-click project -> properties > Builders).

Another option is configuring an external program run --> menu: run >
external tools > open external tools dialog (and you can bind a
shortcut to rerun the last external tool launched).

Cheers,

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


Re: releasing the reference returned by PyLong_FromLong, PyString_FromString & friends

2007-12-13 Thread Gabriel Genellina
En Thu, 13 Dec 2007 08:50:09 -0300, grbgooglefan <[EMAIL PROTECTED]>  
escribi�:

> I am having a object tuple created at application startup. This tuple
> I pass on to a python function in call to:
> PyObject_CallObject(pcatInfo->pPyEvalFunction,pTuple);
>
> For setting the values in this tuple, I am using PyLong_FromLong,
> PyString_FromString & friends functions.
> PyTuple_SetItem(pTuple,nCtr,PyString_FromString(szOrdValue));
>
> My worry is that I will be doing this operation lot many times in the
> active duration of my application. During this time I do not want to
> delete the tuple (pTuple) object passed to PyObject_CallObject, to
> avoid the time taken for creating the object every time.

Tuples are supposed to be immutable so in principle you should not do  
that. You must be absolute and possitively sure that the called function  
may not store its argument tuple in any way. At least check that its  
reference count is still 1 before modifying it.
Tuples are rather optimized, they take exactly as much memory as required,  
not more. Creating a tuple is not expensive at all. Why do you think you  
gain something by reusing a tuple? PyString_FromString is potentially much  
slower than that.

> But this poses another problem. Every call I make to PyLong_FromLong,
> PyString_FromString & friends & functions, they return references.
> How do we release the references or objects returned by these
> functions?

In general, using Py_DECREF. If you are using the C API you should already  
know that. Getting the reference count right is very important: err by +1  
and memory will never be released; err by -1 and Python may crash (even on  
unrelated places).
See section 1.10 on the "Extending and embedding" reference, and section 3  
on the "Python/C API".

Note that PyTuple_SetItem already decrements the reference count of the  
replaced item, so if you use PyTuple_SetItem with a new reference, no  
additional adjustment is required.

-- 
Gabriel Genellina

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

Re: Best way to protect my new commercial software.

2007-12-13 Thread Ben Finney
farsheed <[EMAIL PROTECTED]> writes:

> the code for licensing is about 15 lines and is very fast. I needed
> 20 licenses and I wrote a keygen for myself.

Given that you still haven't explained what threat in particular
you're securing against, I wonder whether "very fast" is the only
criterion. In which case, 0 lines of code would probably be even
faster.

-- 
 \   "Any intelligent fool can make things bigger and more |
  `\  complex... It takes a touch of genius – and a lot of courage |
_o__)   – to move in the opposite direction." —Albert Einstein |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list

  1   2   >