Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Derick van Niekerk
I have found many posts that deal with writing a dictionary to MySQL in
a blob field - which I can't imagine why anybody would want to do it.

I want to write each element of a dictionary onto a db table. The keys
would match the fieldnames. Is there something that would make this job
easier? i.e. how do I write an entire dictionary into a db table as a
row? I have an idea that it is something very simple - possibly even
one line of code...

-d-

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


Re: Using non-ascii symbols

2006-01-27 Thread Bengt Richter
On Thu, 26 Jan 2006 17:47:51 +0100, Claudio Grondi <[EMAIL PROTECTED]> wrote:

>Rocco Moretti wrote:
>> Terry Hancock wrote:
>> 
>>> One thing that I also think would be good is to open up the
>>> operator set for Python. Right now you can overload the
>>> existing operators, but you can't easily define new ones.
>>> And even if you do, you are very limited in what you can
>>> use, and understandability suffers.
>> 
>> 
>> One of the issues that would need to be dealt with in allowing new 
>> operators to be defined is how to work out precedence rules for the new 
>> operators. Right now you can redefine the meaning of addition and 
>> multiplication, but you can't change the order of operations. (Witness 
>> %, and that it must have the same precedence in both multiplication and 
>> string replacement.)
>> 
>> If you allow (semi)arbitrary characters to be used as operators, some 
>> scheme must be chosen for assigning a place in the precedence hierarchy.
>
>Speaking maybe only for myself:
>I don't like implicit rules, so I don't like also any  precedence 
>hierarchy being in action, so for safety reasons I always write even 
>8+6*2 (==20) as 8+(6*2) to be sure all will go the way I expect it.
>
Maybe you would like the unambiguousness of
(+ 8 (* 6 2))
or
6 2 * 8 +
?

Hm, ... ISTM you could have a concept of all objects as potential operator
objects as now, but instead of selecting methods of the objects according
to special symbols like + - * etc, allow method selection by rules applied
to a sequence of objects for selecting methods. E.g., say
a, X, b, Y, c
is a sequence of objects (happening to be contained in a tuple expression here).
Now let's define seqeval such that
seqeval((a, X, b, Y, c))
looks at the objects to see if they have certain methods, and then calls some of
those methods with some of the other objects as arguments, and applies rules of
precedence and association to do something useful, producing a final result.

I'm just thinking out loud here, but what I'm getting at is being able to write
8+6*2
as
seqeval((8, PLUS, 6, TIMES, 2))
with the appropriate definitions of seqeval and PLUS and TIMES. This is with a 
view
to having seqeval as a builtin that does standard processing, and then having
a language change to make white-space-separated expressions like
8 PLUS 6 TIMES 2
be syntactic sugar for an implicit
seqeval((8, PLUS, 6, TIMES, 2))
where PLUS and TIMES may be arbitrary user-defined objects suitable for seqeval.
I'm thinking out loud, so I anticipate syntactic ambiguities in expressions and 
the need to
use parens etc., but this would in effect let us define arbitrarily named 
operators.
Precedence might be established by looking for PLUS.__precedence__. But as 
usual,
parens would control precedence dominantly. E.g.,
   (8 PLUS 6) TIMES 2
would be sugar for
   seqeval((seqeval(8, PLUS, 6), TIMES, 2)

IOW, we have an object sequence expression analogous to a tuple expression 
without commas.
I guess generator expressions might be somewhat of a problem to disambiguate 
sometimes, we'll see
how bad that gets ;-)

One way to detect operator objects would be to test callable(obj), which would 
allow
for functions and types and bound methods etc. Now there needs to be a way of
handling UNARY_PLUS vs PLUS functionality (obviously the name bindings are just 
mnemonic
and aren't seen by seqeval unless they're part of the operator object). ...

A sketch:

 >>> def seqeval(objseq):
 ... """evaluate an object sequence. rules tbd."""
 ... args=[]
 ... ops=[]
 ... for obj in objseq:
 ... if callable(obj):
 ... if ops[-1:] and obj.__precedence__<= ops[-1].__precedence__:
 ... args[-2:] = [ops.pop()(*args[-2:])]
 ... ops.append(obj)
 ... continue
 ... elif isinstance(obj, tuple):
 ... obj = seqeval(obj)
 ... while len(args)==0 and ops: # unary
 ... obj = ops.pop()(obj)
 ... args.append(obj)
 ... while ops:
 ... args[-2:] = [ops.pop()(*args[-2:])]
 ... return args[-1]
 ...
 >>> def PLUS(x, y=None):
 ... print 'PLUS(%s, %s)'%(x,y)
 ... if y is None: return x
 ... else: return x+y
 ...
 >>> PLUS.__precedence__ = 1
 >>>
 >>> def MINUS(x, y=None):
 ... print 'MINUS(%s, %s)'%(x,y)
 ... if y is None: return -x
 ... else: return x-y
 ...
 >>> MINUS.__precedence__ = 1
 >>>
 >>> def TIMES(x, y):
 ... print 'TIMES(%s, %s)'%(x,y)
 ... return x*y
 ...
 >>> TIMES.__precedence__ = 2
 >>>
 >>> seqeval((8, PLUS, 6, TIMES, 2))
 TIMES(6, 2)
 PLUS(8, 12)
 20
 >>> seqeval(((8, PLUS, 6), TIMES, 2))
 PLUS(8, 6)
 TIMES(14, 2)
 28
 >>> seqeval(((8, PLUS, 6), TIMES, (MINUS, 2)))
 PLUS(8, 6)
 MINUS(2, None)
 TIMES(14, -2)
 -28
 >>> seqeval((MINUS, (8, PLUS, 6), TIMES, (MINUS, 2)))
 PLUS(8, 6)
 MINUS(14, None)
 MINUS(2, None)
 TIMES(-14, -2)
 28
 >>> list(seqeval((i, TIMES, j, PLUS, k)) for i in (2,3) for j in (10,100) for 
 

Re: regular expressions, unicode and XML

2006-01-27 Thread Justin Ezequiel
>> when I replace it end up with nothing: i.e., just a "" character in my
>> file.

how are you viewing the contents of your file?
are you printing it out to stdout?
are you opening your file in a non-unicode aware editor?
try print repr(data) after re.sub so that you see what you actually
have in data

btw, from where did you get you XML files?

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


Large XML Document Processing

2006-01-27 Thread Albert Leibbrandt
Hi

Just want to check which xml parser you guys have found to be the 
quickest. I have xml documents with 250 000 records or more and the 
processing of these documents are taking way to long. The validation is 
the main problem. Any module names, non validating would be find to,  
would help a lot.

Thanks
Albert

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


Re: Using non-ascii symbols

2006-01-27 Thread Claudio Grondi
Bengt Richter wrote:
> On Thu, 26 Jan 2006 17:47:51 +0100, Claudio Grondi <[EMAIL PROTECTED]> wrote:
> 
> 
>>Rocco Moretti wrote:
>>
>>>Terry Hancock wrote:
>>>
>>>
One thing that I also think would be good is to open up the
operator set for Python. Right now you can overload the
existing operators, but you can't easily define new ones.
And even if you do, you are very limited in what you can
use, and understandability suffers.
>>>
>>>
>>>One of the issues that would need to be dealt with in allowing new 
>>>operators to be defined is how to work out precedence rules for the new 
>>>operators. Right now you can redefine the meaning of addition and 
>>>multiplication, but you can't change the order of operations. (Witness 
>>>%, and that it must have the same precedence in both multiplication and 
>>>string replacement.)
>>>
>>>If you allow (semi)arbitrary characters to be used as operators, some 
>>>scheme must be chosen for assigning a place in the precedence hierarchy.
>>
>>Speaking maybe only for myself:
>>I don't like implicit rules, so I don't like also any  precedence 
>>hierarchy being in action, so for safety reasons I always write even 
>>8+6*2 (==20) as 8+(6*2) to be sure all will go the way I expect it.
>>
> 
> Maybe you would like the unambiguousness of
> (+ 8 (* 6 2))
> or
> 6 2 * 8 +
> ?
> 
> Hm, ... ISTM you could have a concept of all objects as potential operator
> objects as now, but instead of selecting methods of the objects according
> to special symbols like + - * etc, allow method selection by rules applied
> to a sequence of objects for selecting methods. E.g., say
> a, X, b, Y, c
> is a sequence of objects (happening to be contained in a tuple expression 
> here).
> Now let's define seqeval such that
> seqeval((a, X, b, Y, c))
> looks at the objects to see if they have certain methods, and then calls some 
> of
> those methods with some of the other objects as arguments, and applies rules 
> of
> precedence and association to do something useful, producing a final result.
> 
> I'm just thinking out loud here, but what I'm getting at is being able to 
> write
> 8+6*2
> as
> seqeval((8, PLUS, 6, TIMES, 2))
> with the appropriate definitions of seqeval and PLUS and TIMES. This is with 
> a view
> to having seqeval as a builtin that does standard processing, and then having
> a language change to make white-space-separated expressions like
> 8 PLUS 6 TIMES 2
> be syntactic sugar for an implicit
> seqeval((8, PLUS, 6, TIMES, 2))
> where PLUS and TIMES may be arbitrary user-defined objects suitable for 
> seqeval.
> I'm thinking out loud, so I anticipate syntactic ambiguities in expressions 
> and the need to
> use parens etc., but this would in effect let us define arbitrarily named 
> operators.
> Precedence might be established by looking for PLUS.__precedence__. But as 
> usual,
> parens would control precedence dominantly. E.g.,
>(8 PLUS 6) TIMES 2
> would be sugar for
>seqeval((seqeval(8, PLUS, 6), TIMES, 2)
> 
> IOW, we have an object sequence expression analogous to a tuple expression 
> without commas.
> I guess generator expressions might be somewhat of a problem to disambiguate 
> sometimes, we'll see
> how bad that gets ;-)
> 
> One way to detect operator objects would be to test callable(obj), which 
> would allow
> for functions and types and bound methods etc. Now there needs to be a way of
> handling UNARY_PLUS vs PLUS functionality (obviously the name bindings are 
> just mnemonic
> and aren't seen by seqeval unless they're part of the operator object). ...
> 
> A sketch:
> 
>  >>> def seqeval(objseq):
>  ... """evaluate an object sequence. rules tbd."""
>  ... args=[]
>  ... ops=[]
>  ... for obj in objseq:
>  ... if callable(obj):
>  ... if ops[-1:] and obj.__precedence__<= ops[-1].__precedence__:
>  ... args[-2:] = [ops.pop()(*args[-2:])]
>  ... ops.append(obj)
>  ... continue
>  ... elif isinstance(obj, tuple):
>  ... obj = seqeval(obj)
>  ... while len(args)==0 and ops: # unary
>  ... obj = ops.pop()(obj)
>  ... args.append(obj)
>  ... while ops:
>  ... args[-2:] = [ops.pop()(*args[-2:])]
>  ... return args[-1]
>  ...
>  >>> def PLUS(x, y=None):
>  ... print 'PLUS(%s, %s)'%(x,y)
>  ... if y is None: return x
>  ... else: return x+y
>  ...
>  >>> PLUS.__precedence__ = 1
>  >>>
>  >>> def MINUS(x, y=None):
>  ... print 'MINUS(%s, %s)'%(x,y)
>  ... if y is None: return -x
>  ... else: return x-y
>  ...
>  >>> MINUS.__precedence__ = 1
>  >>>
>  >>> def TIMES(x, y):
>  ... print 'TIMES(%s, %s)'%(x,y)
>  ... return x*y
>  ...
>  >>> TIMES.__precedence__ = 2
>  >>>
>  >>> seqeval((8, PLUS, 6, TIMES, 2))
>  TIMES(6, 2)
>  PLUS(8, 12)
>  20
>  >>> seqeval(((8, PLUS, 6), TIMES, 2))
>  PLUS(8, 6)
>  TIMES(14, 2)
>  28
>  >>> seqeval(((8, PLUS, 6), T

Re: Large XML Document Processing

2006-01-27 Thread Fredrik Lundh
Albert Leibbrandt wrote:

> Just want to check which xml parser you guys have found to be the
> quickest. I have xml documents with 250 000 records or more and the
> processing of these documents are taking way to long. The validation is
> the main problem. Any module names, non validating would be find to,
> would help a lot.

if the files are regular (e.g. all records belong to the same toplevel
element), the iterparse approach is hard to beat:

http://effbot.org/zone/element-iterparse.htm

especially if you use the cElementTree implementation:

http://effbot.org/zone/celementtree.htm





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


Re: Tkinter listener thread?

2006-01-27 Thread Eric Brunel
On Thu, 26 Jan 2006 17:32:32 +, Steve Holden <[EMAIL PROTECTED]>  
wrote:

> gregarican wrote:
>> I have a Python UDP listener socket that waits for incoming data. The
>> socket runs as an endless loop. I would like to pop the incoming data
>> into an existing Tkinter app that I have created. What's the
>> easiest/most efficient way of handling this? Would I create a separate
>> thread that has the listener set a certain Tkinter variable if there is
>> incoming data? Any suggestions would be tremendously appreciated :-)
>>
>
> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/82965

There's in fact no need to check regularly if there's something in the  
Queue: the secondary thread can post a tk custom event to trigger the  
treatment automatically from within the main GUI loop. See here:
http://minilien.fr/a0k273

HTH
-- 
python -c "print ''.join([chr(154 - ord(c)) for c in  
'U(17zX(%,5.zmz5(17;8(%,5.Z65\'*9--56l7+-'])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about isinstance()

2006-01-27 Thread Mr.Rech
After reading all your comments and thinking a little to my specific
case, I think it is definetively better to go with the "isinstance()"
implementation. My objects represent mathematical function defined over
a numerical grid, and I hardly think of an unrelated class objects that
could be compared with them in a meaningfull way.

Thanks again to all of you for helping me to better understand another
piece of the Python's world. ;-)

 Andrea

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


Re: Question about isinstance()

2006-01-27 Thread bruno at modulix
Dave Benjamin wrote:
(snip)

> You *could* have "b.__eq__" just call "a.__eq__", 

Which could lead to strange results (well, actually a good ole infinite
recursion) if b.__eq__ happens to call b.__eq__ too !-)


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Question about isinstance()

2006-01-27 Thread bruno at modulix
Mr.Rech wrote:
> All in all it seems that the implementation that uses isinstance() is
> better in this case...

You could also use something like Zope's Interfaces... But I'm not sure
it's worth the extra complexity.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generating method names 'dynamically'

2006-01-27 Thread bruno at modulix
Daniel Nogradi wrote:
> Is it possible to have method names of a class generated somehow dynamically?

>>> class Dummy(object):
...   pass
...
>>> def mymethod(self, *args, **kw):
...   pass
...
>>> setattr(Dummy, 'a_dynamically_generated_method_name', mymethod)
>>>
>>> Dummy.a_dynamically_generated_method_name

>>>


-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any way to customize the is operator?

2006-01-27 Thread bruno at modulix
Lonnie Princehouse wrote:
>>(objects are not allowed to lie about who they are, or what they are).
> 
> 
> Dangit!  I need to find a less honest programming language.  Anyone
> have a Perl cookbook handy? ...
> 

+1 QOTW (approved by a fellow Perl programmer FWIW !-)

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Robin Haswell
On Fri, 27 Jan 2006 00:03:30 -0800, Derick van Niekerk wrote:

> I have found many posts that deal with writing a dictionary to MySQL in
> a blob field - which I can't imagine why anybody would want to do it.
> 
> I want to write each element of a dictionary onto a db table. The keys
> would match the fieldnames. Is there something that would make this job
> easier? i.e. how do I write an entire dictionary into a db table as a
> row? I have an idea that it is something very simple - possibly even
> one line of code...
> 
> -d-


Try looking at http://pear.php.net/db , in the documentation, see
DB::autoPrepare and DB::autoExecute.

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


Re: any way to customize the is operator?

2006-01-27 Thread Sybren Stuvel
Lonnie Princehouse enlightened us with:
> There doesn't seem to be any way to customize the behavior of "is" as
> can be done for other operators... why not?

Pure logic: A == A or A != A. An object is another object or not.
Why would you want to change that?

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


Re: Question about isinstance()

2006-01-27 Thread Mr.Rech
bruno at modulix wrote:
> Mr.Rech wrote:
> > All in all it seems that the implementation that uses isinstance() is
> > better in this case...
>
> You could also use something like Zope's Interfaces... But I'm not sure
> it's worth the extra complexity.

Thanks for your suggestion, but it's not worth the extra complexity at
all.

I've read something about interfaces, but my project will be a
small/middle sized one, and using such a sophisticated tool it would be
like using a cannon to shoot a sparrow (as we are used to say here in
Italy).

Anyway thanks again for your comments.

 Andrea

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


Re: beta.python.org content

2006-01-27 Thread Terry Hancock
On Thu, 26 Jan 2006 17:57:05 +
Steve Holden <[EMAIL PROTECTED]> wrote:
> How does
>http://beta.python.org/about/beginners/
> look?

Better than it did. ;-)

No, it looks great. I think you're hitting approximately the
right tone here. That first paragraph may be a bit too curt
about "new to programming" folks (Actually, I think you were
mentally pausing on the link, which doesn't happen on
reading because of the contrast problem -- when I
consciously make this pause, it sounds better).

But ...

1) Contrast between text and links is too low (it's hard to
see the in-text links).

2) Partly because of #1, it would be nicer to have some of
these links in a nice bullet-list.  It would also break up
the paragraph text a bit, which would (ironically) increase
the chances of it being read.

You could probably go either way -- leave the color alone
and introduce some bullets, or increase the color contrast
so that the links stand out.

3) Remember that many people will be *scanning* this page,
not reading it.  What will they see as their eyes scan down
the page during the first 1/2 second?  Enough to make them
spend 10 seconds taking a more thorough look? Will that make
them spend the 3-5 minutes actually reading what you wrote?

Remember that a beginner is likely "shopping" for a
programming language, and wants to know:

1) What general class of language is Python?

2) What distinguishes it from other languages? (Obvious
comparables: C, Perl, Ruby, Java, Visual Basic. Less
obvious, but useful: Lisp, Haskell).

3) How long is it going to take me to learn it?

4) How much help can I get and what resources are available
to learn it?  (Python is an open-source native, which to
some people continues to mean "underdocumented and
undersupported", even if *we* know that's a myth (I now
believe the opposite, but I'm in the choir ;-) )).

5) Will I be able to do anything after learning it, that I
can't do now?

You're still sort of "advertising" on the beginners site,
but it needs to be more of a technical advertisement than
the "buzzword sell" on the front page. This is the page
someone reads who is imagining that *they* are going to have
to learn this language (not pay someone else to).

Cheers,
Terry

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

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


Re: Question about isinstance()

2006-01-27 Thread Rene Pijlman
Steven D'Aprano:
>Rene Pijlman:
>> Mr.Rech:
>>>   def __eq__(self, other):
>>>  try:
>>> return self.an_attribute == other.an_attribute
>>>  except AttributeError:
>>> return False
>> 
>> This may give unexpected results when you compare a foo with an instance
>> of a completely different type that happens to have an attribute called
>> 'an_attribute'.
>
>That's a trade-off, isn't it?
>
>On the one hand, you risk false negatives, by refusing to compare against
>things you didn't think of. 

Well no, when comparing against things you didn't think of the __eq__
shouldn't return a false False, it should return NotImplemented. After
all, the things you didn't think of are not (yet) implemented.

"A rich comparison method may return NotImplemented if it does not
implement the operation for a given pair of arguments."
http://www.python.org/doc/ref/customization.html

-- 
René Pijlman

Wat wil jij worden?  http://www.carrieretijger.nl
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Robin Haswell
On Fri, 27 Jan 2006 00:03:30 -0800, Derick van Niekerk wrote:

> I have found many posts that deal with writing a dictionary to MySQL in
> a blob field - which I can't imagine why anybody would want to do it.
> 
> I want to write each element of a dictionary onto a db table. The keys
> would match the fieldnames. Is there something that would make this job
> easier? i.e. how do I write an entire dictionary into a db table as a
> row? I have an idea that it is something very simple - possibly even
> one line of code...
> 
> -d-

Oh crap sorry, ignore my last message - I thought I was still looking at
c.l.php :-)

I can't answer your question in Python, sorry :-)

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


Re: Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Fredrik Lundh
Derick van Niekerk wrote:

> I have found many posts that deal with writing a dictionary to MySQL in
> a blob field - which I can't imagine why anybody would want to do it.

it might be useful if you have a bunch of unknown properties (e.g. configuration
parameters for some external parameters), and no need to access the properties
as individual parameters via the database.

> I want to write each element of a dictionary onto a db table. The keys
> would match the fieldnames. Is there something that would make this job
> easier? i.e. how do I write an entire dictionary into a db table as a
> row? I have an idea that it is something very simple - possibly even
> one line of code...

some database drivers have API:s for this, but if you're using a generic
DB-API driver, it's pretty straightforward to generate an appropriate SQL
statement on the fly; e.g.

d = {"spam": "1", "egg": "2"}

cols = d.keys()
vals = d.values()

stmt = "INSERT INTO table (%s) VALUES(%s)" % (
",".join(cols), ",".join(["?"]*len(vals))
)

cursor.execute(stmt, tuple(vals))





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


Re: Question about isinstance()

2006-01-27 Thread bruno at modulix
bruno at modulix wrote:
> Dave Benjamin wrote:
> (snip)
> 
> 
>>You *could* have "b.__eq__" just call "a.__eq__", 
> 
> 
> Which could lead to strange results (well, actually a good ole infinite
> recursion) if b.__eq__ happens to call b.__eq__ too !-)

I meant:

'if a.__eq__ happens to call b.__eq__ too'

of course...



-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in '[EMAIL PROTECTED]'.split('@')])"
-- 
http://mail.python.org/mailman/listinfo/python-list


str as param for timedelta

2006-01-27 Thread Philipp
Hello Pythonistas

I'm new to Python, I hope you understand my question.
I would like to pass a parameter "gap" to a function. gap should be
used there to create a timedelta Object.

from datetime import *

def f(gap):
print (datetime.now() + datetime.timedelta(gap))

  f('hours = -8')

I read in the manual that datetime does accept ints, longs, or floats,
which may be positive or negative. Same as the error message:
"unsupported type for timedelta days component: str"

I found out, that I can pass an Object

def f1(deltaObj):
print (datetime.now() + deltaObj)   

f1(timedelta(hours = -8))

I would prefer the first version, as it is easier to use the string for 
representation and so on.

Is there any way to pass a string to the function and use it there for 
the timedelta?

or you might say I missed some basic concepts...

... in any case, thank you very much!

Phil

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


Re: Large XML Document Processing

2006-01-27 Thread Rene Pijlman
Albert Leibbrandt:
>Just want to check which xml parser you guys have found to be the 
>quickest. I have xml documents with 250 000 records or more and the 
>processing of these documents are taking way to long.

What type of parser are you using? Dom, minidom or sax? Sax is fastest,
but somewhat more work for the programmer. Minidom is a nice compromise
when processing many identical records.

-- 
René Pijlman

Wat wil jij worden?  http://www.carrieretijger.nl
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Derick van Niekerk
[quote]
d = {"spam": "1", "egg": "2"}

cols = d.keys()
vals = d.values()

stmt = "INSERT INTO table (%s) VALUES(%s)" % (
",".join(cols), ",".join(["?"]*len(vals))
)

cursor.execute(stmt, tuple(vals))
[/quote]

I will be using the python-mysql API. This looks like what I am looking
for. I just have a question about the last join statment. In this case
it would just create a string = '?,?' - wouldn't it? Other than that,
it is pretty easy to understand. Now - how do I escape the string for
characters that might break the script e.g. [' " \ ) ( ...]?

Is there a python function to do it? part of the mysql-python module,
maybe?

-d-

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


matplotlib legend problem

2006-01-27 Thread bwaha
Has anyone figured out how to get a legend for each line in a
matplotlib.collections.LineCollection instance?

No problem if I plot lines the default way ie. line,=plot(x,y). But I've had
to resort to using LineCollections for the significant speed boost since I
am routinely plotting up to ten 3 point datasets in one plot. The legend
doc says that "legend by itself will try and build a legend using the label
property of the lines/patches/collections". But it seems that for a
collection the legend refers to the collection as a whole, not the
individual lines within the collection.

AFAIK this is a limitation of matplotlib 0.85. Any ideas on how I can
workaround this problem that won't kill my speed boost?


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


problems with documentation

2006-01-27 Thread bobueland
I'm using standard widows xp installation of Python 2.4.2. I tried to
find some help for print and entered

>>> help()

and then chose

help> print

Sorry, topic and keyword documentation is not available because the
Python
HTML documentation files could not be found.  If you have installed
them,
please set the environment variable PYTHONDOCS to indicate their
location.

help>

I did set the environment variable PYTHONDOCS to C:\Python24\Doc (in
that folder I have Python24.chm) but got the same error. I then
downloaded html files and put them in PYTHONDOCS to C:\Python24\Doc
folder and then changed PYTHONDOCS to
C:\Python24\Doc\Python-Docs-2.4.2\doc but to no avail. What should I do
to get this to work?

Any ideas?

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


Re: Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Gerhard Häring
Derick van Niekerk wrote:
> [quote]
> d = {"spam": "1", "egg": "2"}
> 
> cols = d.keys()
> vals = d.values()
> 
> stmt = "INSERT INTO table (%s) VALUES(%s)" % (
> ",".join(cols), ",".join(["?"]*len(vals))
> )
> 
> cursor.execute(stmt, tuple(vals))
> [/quote]
> 
> I will be using the python-mysql API. This looks like what I am looking
> for. I just have a question about the last join statment. In this case
> it would just create a string = '?,?' - wouldn't it? Other than that,
> it is pretty easy to understand. Now - how do I escape the string for
> characters that might break the script e.g. [' " \ ) ( ...]? [...]

You don't need to escape the strings, because the example code uses the 
parametrized form of the cursor.execute statement, and the DB-API module 
will just do the right thing.

The example code will maybe not work like this, because IIRC MySQLdb 
uses paramstyle = "format", and not paramstyle = "qmark". I. e. you will 
have to use %s as placeholders in the query, and not ?. So you would 
have to replace the ",".join(["?"]*len(vals)) with
",".join(["%s"]*len(vals)).

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


Re: Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Fredrik Lundh
Derick van Niekerk wrote:

> [quote]
> d = {"spam": "1", "egg": "2"}
>
> cols = d.keys()
> vals = d.values()
>
> stmt = "INSERT INTO table (%s) VALUES(%s)" % (
> ",".join(cols), ",".join(["?"]*len(vals))
> )
>
> cursor.execute(stmt, tuple(vals))
> [/quote]
>
> I will be using the python-mysql API. This looks like what I am looking
> for. I just have a question about the last join statment. In this case
> it would just create a string = '?,?' - wouldn't it?

yup.  those are parameter markers (replace with "%s" if that's what
your database API is using).  each ? (or %s) corresponds to a value
in the tuple argument to execute.  e.g.

execute("INSERT INTO table (foo, bar) VALUES(?, ?)", ('one', 'two'))

is the same thing as

execute("INSERT INTO table (foo, bar) VALUES('one', 'two')")

except that the former is 1) more efficient, and 2) safe, since the
parameter values are passed directly to the SQL engine, without
going through the SQL parser.  there's no need to escape them.

> Now - how do I escape the string for characters that might break
> the script e.g. [' " \ ) ( ...]?

you don't -- that's why the values are passed in as a separate argument
to execute.

(just curious, but from where do people get the idea that arbitrary data
just have to be inserted into the the SQL statement text all the time?  is
this some PHP misfeature?)





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


Re: Using non-ascii symbols

2006-01-27 Thread Magnus Lycka
Terry Hancock wrote:
> That's interesting. I think many people in the West tend to
> imagine han/kanji characters as archaisms that will
> disappear (because to most Westerners they seem impossibly
> complex to learn and use, "not suited for the modern
> world"). 
I don't know about "the West". Isn't it more typical for the
US that people believe that "everybody really wants to be like
us". Here in Sweden, *we* obviously want to be like you, even
if we don't admit it openly, but we don't suffer from the
misconception that this applies to all of the world. ;)

> After taking a couple of semesters of Japanese, though, I've
> come to appreciate why they are preferred.  Getting rid of
> them would be like convincing English people to kunvurt to
> pur fonetik spelin'.
> 
> Which isn't happening either, I can assure you. ;-)
The Germans just had a spelling reform. Norway had a major
language reform in the mid 19th century to get rid of the old
Danish influences (and still have two completely different ways
of spelling everything). You never know what will happen. You
are also embracing the metric system, inch by inch... ;)

Actually, it seems that recent habit of sending text messages
via mobile phones is the prime driver for reformed spelling
these days.

> I'm not sure I understand how this works, but surely if
> Python can provide readline support in the interactive
> shell, it ought to be able to handle "phrase input"/"kanji
> input."  Come to think of it, you probably can do this by
> running the interpreter in a kanji terminal -- but Python
> just doesn't know what to do with the characters yet.
I'm sure the same principles could be used to make a very fast
and less misspelling prone editing environment though. That
could actually be a reason to step away from vi or Emacs (but
I assume it would soon work in Emacs too...)

> I would like to point out also, that as long as Chinese
> programmers don't go "hog wild" and use obscure characters,
> I suspect that I would have much better luck reading their
> programs with han characters, than with, say, the Chinese
> phonetic names!  Possibly even better than what they thought
> were the correct English words, if their English isn't that
> good.
You certainly have a point there. Even when I don't work in an
English speaking environment as I do now, I try to write all
comments and variable names etc in English. You never know when
you need to show a code snippet to people who don't read Swedish.
Also, ASCII lacks three of our letters and properly translated
is often better than written with the wrong letters.

On the other hand, if the target users describe their problem
domain with e.g. a Swedish terminology, translating all terms
will take time and increase confusion. Also, there are plenty
of programmers who don't write English so well...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: any way to customize the is operator?

2006-01-27 Thread Steven D'Aprano
On Thu, 26 Jan 2006 23:26:14 -0800, Lonnie Princehouse wrote:

>> (objects are not allowed to lie about who they are, or what they are).
> 
> Dangit!  I need to find a less honest programming language.  Anyone
> have a Perl cookbook handy? ...

No, you need a better algorithm.


Why did you want to customize "is"?


-- 
Steven.

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


Re: problems with documentation

2006-01-27 Thread [EMAIL PROTECTED]
Set PYTHONDOCS to "C:\Python24\Doc\Python-Docs-2.4.2", and that should
work.

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


Re: generating method names 'dynamically'

2006-01-27 Thread Bengt Richter
On Fri, 27 Jan 2006 01:20:52 +0100, Daniel Nogradi <[EMAIL PROTECTED]> wrote:

>> > Is it possible to have method names of a class generated somehow
>> dynamically?
>> >
>> > More precisely, at the time of writing a program that contains a class
>> > definition I don't know what the names of its callable methods should
>> > be. I have entries stored in a database that are changing from time to
>> > time and I always want to be able to call (from another program) those
>> > method names which are at the moment present in the database.
>>
>> Sounds somehow more like all you need is to learn about __getattr__ and
>> maybe __call__ instead of actually generating methods.  In other words,
>> don't generate anything, just intercept attempts to call things that
>> were produced by accessing the attributes of an object.
>>
>> Whether that would work or not depends on things you haven't said.  The
>> above spec is a little unclear, given among other things that you don't
>> "call method names", that the code in the methods you would presumably
>> want to call has to exist somewhere and you haven't described what that
>> code would be, and I can't tell what those database "entries" are really
>> all about other than that they somehow refer to the names of things that
>> you think you want to call as methods. :-)
>>
>> Perhaps an example is in order...
>>
>
>Thanks for all the replies, it became clear that I need to look into
>getattr, __getattr__ and __call__. I'll do that, but since you asked,
>here is the thing I would like to do in a little more detail:
>
>My database has 1 table with 2 fields, one called 'name' and the other
>one called 'age', let's suppose it has the following content, but this
>content keeps changing:
While the program is running? Or between runs of the program?
Either you will need to query the database for each pseudo-method call,
or you will be able to prebuild all the methods at startup or anything between.

>
>Alice 25
>Bob  24
>
>--- program1.py 
>
>class klass:
>
> # do the stuff with getattr using the database
> # but in a way that after the database changes
> # I don't need to rewrite this part
>
>
>inst =3D klass()
>
>-- program2.py --
>
>import program1
>
># This should print 'Hello, my name is Bob and I'm 24'
>program1.inst.Bob()
>
># This should print 'Hi, I'm 25 and I'm Alice'
>program1.inst.Alice()
Those two messages differ by more than (name, age) content.
Where is the different text coming from, if you are building
these responses totally dynamically?

>
># This should print an error message, since there is no
># field in the database with name=3DJohn
>program1.inst.John()

I suppose you want the klass to have more methods than
just the dynamically built/simulated ones? Otherwise, why
not just define a function that takes a name and goes to the
data base to get the data and then prints the message. E.g.,
program1.print_the_message('John')
instead of
program1.inst.John()
No class needed.
OTOH, if you are going to use a class, you might want to name it
capitalized (more conventional) and derive from object, or subclass
from something else if it makes sense. I.e. class Klass(object): ...

What kind of "database" are you accessing? An RDBMS? A CSV text file?
A directory full of named single-line files (ugh), or?

How often will you access the data? Are you the only one?
Requirements, requirements ;-)

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


Problem with odbc (pywin32) and unicode

2006-01-27 Thread Frank Millman
Hi all

I am using odbc from pywin32 to connect to MS SQL Server. I am changing
my program from the old (incorrect) style of embedding values in the
SQL command to the new (correct) style of passing the values as
parameters. I have hit a problem.

The following all work -
cur.execute("select * from users where userid = '%s'" % 'frank')  #
old style
cur.execute("select * from users where userid = '%s'" % u'frank')
# old style
cur.execute("select * from users where userid = ?", ['frank'])  #
new style

This does not work -
cur.execute("select * from users where userid = ?", [u'frank'])  #
new style

I get the following error -
OdbcError: Found an insert row that didn't have 1 columns [sic]

It is the combination of new style and unicode that does not work.

I realise that odbc is not fully DB-API compliant, but I have got away
with it up to now. Does anyone know of a solution to this problem?

Thanks

Frank Millman

ps to Fredrik, who just added this to a recent post -

"(just curious, but from where do people get the idea that arbitrary
data
just have to be inserted into the the SQL statement text all the time?
is
this some PHP misfeature?) "

I can't answer for anyone else, but this is my excuse.

Sequence of events -

  learn a bit about Python - play in interpreter, write simple scripts,
etc.
  learn a bit about SQL - play in an interactive session, run some
commands, etc.
  try to combine the two - wow, it works!
  read in the DB-API about parameter passing - frankly, don't
understand it.
  therefore stick with what works for me.

Parameter passing seems to be one of those things that, if you
understand it, you can't imagine that there is anyone out there that
does not understand it, and therefore you think that the documentation
is perfectly clear. However, if you are one of those unfortunate souls
who have never come across such a thing, the docs simply do do not
spell it out clearly enough, so one's reaction is more 'huh?' than
'aha!'

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


Re: str as param for timedelta

2006-01-27 Thread [EMAIL PROTECTED]
Philipp wrote:
> from datetime import *
>
> def f(gap):
>   print (datetime.now() + datetime.timedelta(gap))
>
>   f('hours = -8')

When you need a flexible input format, consider keyword arguments. In
this case, I would pass along the inputs to timedelta:

def from_now(**kwargs):
return datetime.now() + timedelta(**kwargs)

from_now(hours=8) returns datetime.now() + timedelta(hours=8), and the
function can now accept any of timedelta's arguments. For more on what
**kwargs means, see the tutorial:

http://docs.python.org/tut/node6.html#SECTION00672

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


Re: problems with documentation

2006-01-27 Thread bobueland
Thanks, that works :)

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


Represent XML

2006-01-27 Thread Sbaush
Hi all.I attach to you a example XML file to parse and the demo of my objective.The iptRequest.xml is the file to parse in one mode. I can't parse it.The demo.py is my ideal result, manually built, that should be built by parsing the XML.
How can i do to do it?Bye all!
#!/usr/bin/env python
# -*- coding: ISO-8859-15 -*-
# generated by wxGlade 0.4 on Fri Jan 27 12:24:48 2006

from wxPython.wx import *
from wxPython.grid import *

class MyFrame(wxFrame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wxDEFAULT_FRAME_STYLE
wxFrame.__init__(self, *args, **kwds)
self.grid_1 = wxGrid(self, -1, size=(1, 1))

self.__set_properties()
self.__do_layout()
# end wxGlade

def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle("frame_1")
self.SetSize(wxDLG_SZE(self, (390, 136)))
self.grid_1.CreateGrid(8, 8)
self.grid_1.EnableDragColSize(0)
self.grid_1.SetColLabelValue(0, "Chain")
self.grid_1.SetColLabelValue(1, "Policy")
self.grid_1.SetColLabelValue(2, "Num")
self.grid_1.SetColLabelValue(3, "Target")
self.grid_1.SetColLabelValue(4, "Protocol")
self.grid_1.SetColLabelValue(5, "Option")
self.grid_1.SetColLabelValue(6, "Source")
self.grid_1.SetColLabelValue(7, "Destination")
self.grid_1.SetMinSize(wxDLG_SZE(self.grid_1, (387, 150)))
# end wxGlade
	
	self.grid_1.SetCellValue(0,0,"INPUT")
	self.grid_1.SetCellValue(1,0,"INPUT")
	self.grid_1.SetCellValue(2,0,"INPUT")
	self.grid_1.SetCellValue(3,0,"OUTPUT")
	self.grid_1.SetCellValue(4,0,"OUTPUT")
	self.grid_1.SetCellValue(5,0,"OUTPUT")
	self.grid_1.SetCellValue(6,0,"FORWARD")
	self.grid_1.SetCellValue(7,0,"FORWARD")
	
	self.grid_1.SetCellValue(0,1,"ACCEPT")
	self.grid_1.SetCellValue(1,1,"ACCEPT")
	self.grid_1.SetCellValue(2,1,"ACCEPT")
	self.grid_1.SetCellValue(3,1,"ACCEPT")
	self.grid_1.SetCellValue(4,1,"ACCEPT")
	self.grid_1.SetCellValue(5,1,"ACCEPT")
	self.grid_1.SetCellValue(6,1,"ACCEPT")
	self.grid_1.SetCellValue(7,1,"ACCEPT")
	
	self.grid_1.SetCellValue(0,2,"1")
	self.grid_1.SetCellValue(1,2,"2")
	self.grid_1.SetCellValue(2,2,"3")
	self.grid_1.SetCellValue(3,2,"1")
	self.grid_1.SetCellValue(4,2,"2")
	self.grid_1.SetCellValue(5,2,"3")
	self.grid_1.SetCellValue(6,2,"1")
	self.grid_1.SetCellValue(7,2,"2")
	
	self.grid_1.SetCellValue(0,3,"ACCEPT")
	self.grid_1.SetCellValue(1,3,"ACCEPT")
	self.grid_1.SetCellValue(2,3,"ACCEPT")
	self.grid_1.SetCellValue(3,3,"ACCEPT")
	self.grid_1.SetCellValue(4,3,"ACCEPT")
	self.grid_1.SetCellValue(5,3,"ACCEPT")
	self.grid_1.SetCellValue(6,3,"ACCEPT")
	self.grid_1.SetCellValue(7,3,"ACCEPT")
	
	self.grid_1.SetCellValue(0,4,"icmp")
	self.grid_1.SetCellValue(1,4,"tcp")
	self.grid_1.SetCellValue(2,4,"udp")
	self.grid_1.SetCellValue(3,4,"icmp")
	self.grid_1.SetCellValue(4,4,"icmp")
	self.grid_1.SetCellValue(5,4,"icmp")
	self.grid_1.SetCellValue(6,4,"icmp")
	self.grid_1.SetCellValue(7,4,"udp")
	
	self.grid_1.SetCellValue(0,5,"--")
	self.grid_1.SetCellValue(1,5,"--")
	self.grid_1.SetCellValue(2,5,"--")
	self.grid_1.SetCellValue(3,5,"--")
	self.grid_1.SetCellValue(4,5,"--")
	self.grid_1.SetCellValue(5,5,"--")
	self.grid_1.SetCellValue(6,5,"--")
	self.grid_1.SetCellValue(7,5,"--")
	
	self.grid_1.SetCellValue(0,6,"localhost.localdomain")
	self.grid_1.SetCellValue(1,6,"127.0.0.3")
	self.grid_1.SetCellValue(2,6,"127.0.0.3")
	self.grid_1.SetCellValue(3,6,"localhost.localdomain")
	self.grid_1.SetCellValue(4,6,"127.0.0.2")
	self.grid_1.SetCellValue(5,6,"127.0.0.3")
	self.grid_1.SetCellValue(6,6,"localhost.localdomain")
	self.grid_1.SetCellValue(7,6,"127.0.0.3")
	
	self.grid_1.SetCellValue(0,7,"anywhere")
	self.grid_1.SetCellValue(1,7,"anywhere")
	self.grid_1.SetCellValue(2,7,"anywhere")
	self.grid_1.SetCellValue(3,7,"anywhere")
	self.grid_1.SetCellValue(4,7,"anywhere")
	self.grid_1.SetCellValue(5,7,"anywhere")
	self.grid_1.SetCellValue(6,7,"anywhere")
	self.grid_1.SetCellValue(7,7,"anywhere")
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
sizer_1 = wxBoxSizer(wxVERTICAL)
sizer_1.Add(self.grid_1, 1, wxEXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer_1)
self.Layout()
# end wxGlade

# end of class MyFrame


if __name__ == "__main__":
app = wxPySimpleApp(0)
wxInitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()


  

  



  
  



  
  


  

  

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

Represent XML

2006-01-27 Thread Sbaush
Hi all.I attach to you a example XML file to parse and the demo of my objective.The iptRequest.xml is the file to parse in one mode. I can't parse it.The demo.py is my ideal result, manually built, that should be built by parsing the XML.
How can i do to do it?Bye all!
#!/usr/bin/env python
# -*- coding: ISO-8859-15 -*-
# generated by wxGlade 0.4 on Fri Jan 27 12:24:48 2006

from wxPython.wx import *
from wxPython.grid import *

class MyFrame(wxFrame):
def __init__(self, *args, **kwds):
# begin wxGlade: MyFrame.__init__
kwds["style"] = wxDEFAULT_FRAME_STYLE
wxFrame.__init__(self, *args, **kwds)
self.grid_1 = wxGrid(self, -1, size=(1, 1))

self.__set_properties()
self.__do_layout()
# end wxGlade

def __set_properties(self):
# begin wxGlade: MyFrame.__set_properties
self.SetTitle("frame_1")
self.SetSize(wxDLG_SZE(self, (390, 136)))
self.grid_1.CreateGrid(8, 8)
self.grid_1.EnableDragColSize(0)
self.grid_1.SetColLabelValue(0, "Chain")
self.grid_1.SetColLabelValue(1, "Policy")
self.grid_1.SetColLabelValue(2, "Num")
self.grid_1.SetColLabelValue(3, "Target")
self.grid_1.SetColLabelValue(4, "Protocol")
self.grid_1.SetColLabelValue(5, "Option")
self.grid_1.SetColLabelValue(6, "Source")
self.grid_1.SetColLabelValue(7, "Destination")
self.grid_1.SetMinSize(wxDLG_SZE(self.grid_1, (387, 150)))
# end wxGlade
	
	self.grid_1.SetCellValue(0,0,"INPUT")
	self.grid_1.SetCellValue(1,0,"INPUT")
	self.grid_1.SetCellValue(2,0,"INPUT")
	self.grid_1.SetCellValue(3,0,"OUTPUT")
	self.grid_1.SetCellValue(4,0,"OUTPUT")
	self.grid_1.SetCellValue(5,0,"OUTPUT")
	self.grid_1.SetCellValue(6,0,"FORWARD")
	self.grid_1.SetCellValue(7,0,"FORWARD")
	
	self.grid_1.SetCellValue(0,1,"ACCEPT")
	self.grid_1.SetCellValue(1,1,"ACCEPT")
	self.grid_1.SetCellValue(2,1,"ACCEPT")
	self.grid_1.SetCellValue(3,1,"ACCEPT")
	self.grid_1.SetCellValue(4,1,"ACCEPT")
	self.grid_1.SetCellValue(5,1,"ACCEPT")
	self.grid_1.SetCellValue(6,1,"ACCEPT")
	self.grid_1.SetCellValue(7,1,"ACCEPT")
	
	self.grid_1.SetCellValue(0,2,"1")
	self.grid_1.SetCellValue(1,2,"2")
	self.grid_1.SetCellValue(2,2,"3")
	self.grid_1.SetCellValue(3,2,"1")
	self.grid_1.SetCellValue(4,2,"2")
	self.grid_1.SetCellValue(5,2,"3")
	self.grid_1.SetCellValue(6,2,"1")
	self.grid_1.SetCellValue(7,2,"2")
	
	self.grid_1.SetCellValue(0,3,"ACCEPT")
	self.grid_1.SetCellValue(1,3,"ACCEPT")
	self.grid_1.SetCellValue(2,3,"ACCEPT")
	self.grid_1.SetCellValue(3,3,"ACCEPT")
	self.grid_1.SetCellValue(4,3,"ACCEPT")
	self.grid_1.SetCellValue(5,3,"ACCEPT")
	self.grid_1.SetCellValue(6,3,"ACCEPT")
	self.grid_1.SetCellValue(7,3,"ACCEPT")
	
	self.grid_1.SetCellValue(0,4,"icmp")
	self.grid_1.SetCellValue(1,4,"tcp")
	self.grid_1.SetCellValue(2,4,"udp")
	self.grid_1.SetCellValue(3,4,"icmp")
	self.grid_1.SetCellValue(4,4,"icmp")
	self.grid_1.SetCellValue(5,4,"icmp")
	self.grid_1.SetCellValue(6,4,"icmp")
	self.grid_1.SetCellValue(7,4,"udp")
	
	self.grid_1.SetCellValue(0,5,"--")
	self.grid_1.SetCellValue(1,5,"--")
	self.grid_1.SetCellValue(2,5,"--")
	self.grid_1.SetCellValue(3,5,"--")
	self.grid_1.SetCellValue(4,5,"--")
	self.grid_1.SetCellValue(5,5,"--")
	self.grid_1.SetCellValue(6,5,"--")
	self.grid_1.SetCellValue(7,5,"--")
	
	self.grid_1.SetCellValue(0,6,"localhost.localdomain")
	self.grid_1.SetCellValue(1,6,"127.0.0.3")
	self.grid_1.SetCellValue(2,6,"127.0.0.3")
	self.grid_1.SetCellValue(3,6,"localhost.localdomain")
	self.grid_1.SetCellValue(4,6,"127.0.0.2")
	self.grid_1.SetCellValue(5,6,"127.0.0.3")
	self.grid_1.SetCellValue(6,6,"localhost.localdomain")
	self.grid_1.SetCellValue(7,6,"127.0.0.3")
	
	self.grid_1.SetCellValue(0,7,"anywhere")
	self.grid_1.SetCellValue(1,7,"anywhere")
	self.grid_1.SetCellValue(2,7,"anywhere")
	self.grid_1.SetCellValue(3,7,"anywhere")
	self.grid_1.SetCellValue(4,7,"anywhere")
	self.grid_1.SetCellValue(5,7,"anywhere")
	self.grid_1.SetCellValue(6,7,"anywhere")
	self.grid_1.SetCellValue(7,7,"anywhere")
def __do_layout(self):
# begin wxGlade: MyFrame.__do_layout
sizer_1 = wxBoxSizer(wxVERTICAL)
sizer_1.Add(self.grid_1, 1, wxEXPAND, 0)
self.SetAutoLayout(True)
self.SetSizer(sizer_1)
self.Layout()
# end wxGlade

# end of class MyFrame


if __name__ == "__main__":
app = wxPySimpleApp(0)
wxInitAllImageHandlers()
frame_1 = MyFrame(None, -1, "")
app.SetTopWindow(frame_1)
frame_1.Show()
app.MainLoop()


  

  



  
  



  
  


  

  

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

Re: beta.python.org content

2006-01-27 Thread Paul Boddie
Michael Tobis wrote:
> I like the design, though I'd prefer stronger colors. I think it would
> be a major improvement except for the logo.

[Much reasoning about logos, Sun, Microsoft Office...]

With the nice font they've used, I don't understand why they didn't
turn the "p" into a snake itself. I'm sure I've seen that done
somewhere before.

Paul

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


Re: Problem with odbc (pywin32) and unicode

2006-01-27 Thread Diez B. Roggisch
Frank Millman wrote:

> Hi all
> 
> I am using odbc from pywin32 to connect to MS SQL Server. I am changing
> my program from the old (incorrect) style of embedding values in the
> SQL command to the new (correct) style of passing the values as
> parameters. I have hit a problem.
> 
> The following all work -
> cur.execute("select * from users where userid = '%s'" % 'frank')  #
> old style
> cur.execute("select * from users where userid = '%s'" % u'frank')
> # old style
> cur.execute("select * from users where userid = ?", ['frank'])  #
> new style
> 
> This does not work -
> cur.execute("select * from users where userid = ?", [u'frank'])  #
> new style
> 
> I get the following error -
> OdbcError: Found an insert row that didn't have 1 columns [sic]

To me it looks as if your problem stems from not encoding the parameter as a
string, but pasing a unicode-object that maybe internally causes trouble -
and a misleading error message.

That things work in your second old-style case comes from youprobably not
coming from a country where non-ascii characters are usual. Otherwise you'd
have seen that e.g.

"select * from users where userid = '%s'" % u'Martin von Löwis'

will produce the notorious

UnicodeEncodeError: 'ascii' codec can't encode character u'\xf6' in position
12: ordinal not in range(128)

So it is silently converted to a string by the %-operator using the ascii
codec.

So I suggest you try this:

cur.execute("select * from users where userid = ?",
[u'frank'.encode("utf-8"]) 


If that works, we know the problem. Make sure that your DB is expecting
UTF-8, or use the encoding it wants instead!

Regards,

Diez



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

decorators to add test* TestCase methods

2006-01-27 Thread Bruce Cropley
Hi all

I'm trying to generate test methods in a unittest TestCase
subclass, using decorators.  I'd like to be able to say:

class MyTestCase(unittest.TestCase):
@genTests(["Buy", "Sell"], [1,2,3], [True, False])
def something(self, side, price, someFlag):
# etc...

And have it generate functions called:
test_Buy_1_True_something
test_Buy_1_False_something
through to...
test_Sell_3_False_something

Each of these would call the something function with the
expected parameters. I guess that the new 2.5 partial()
could help with this.

There are two problems:
- Decorators don't seem to be able to add functions to the
  class because it is still being defined. I know decorators
  aren't really intended for this, but it would be nice to keep
  the expansion call near the generic test method source.
- There seems to be a bug with creating functions in a loop,
  see below...

Here's my attempt so far:

-8<---
#!/usr/bin/env python

# Generate all combinations of values of args.
def product(*args):
if len(args) == 0:
return [[]]
return [[val] + rest
for val in args[0]
for rest in product(*args[1:])]

class Test:
# Making this a classmethod doesn't seem to have gained me much.
# perhaps it should be just a function, and use func.im_class?
@classmethod
def genTests(cls, func, *args):
""" Generate all test functions of the form:
test_B_Harry_{func.func_name}
test_B_Sally_{func.func_name}
test_S_Harry_{func.func_name}
test_S_Sally_{func.func_name}
... which call self.func with the corresponding parameters.
"""
for param_combo in product(*args):
#print "In loop, generating %s" % param_combo
def testFunc(self):
#print "In test func: %s" % param_combo
func(self, *param_combo)
func_name = "_".join(["test"] + param_combo +
[func.func_name])
setattr(cls, "%s" % func_name, testFunc)

class Derived(Test):
# I want to be able to do:
# @genTests(["B", "S"], ["Harry", "Sally"])
def blah(self, side, name):
print "blah: %s %s" % (side, name)

t = Derived()

# Hack
Derived.genTests(Derived.blah, ["B", "S"], ["Harry", "Sally"])

t.test_S_Sally_blah()

# This is failing (generates test_S_Sally_blah),
# and appears to be a python bug:
t.test_B_Harry_blah()
-8<--

Does anyone have any suggestions?

Thanks,
Bruce

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


Re: Loading a Python collection from an text-file

2006-01-27 Thread Ido Yehieli
perhapse consider using the pickle module?
http://docs.python.org/lib/module-pickle.html

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


Re: Problem with odbc (pywin32) and unicode

2006-01-27 Thread Frank Millman

Diez B. Roggisch wrote:
> Frank Millman wrote:
>
> >
> > This does not work -
> > cur.execute("select * from users where userid = ?", [u'frank'])  #
> > new style
> >
> > I get the following error -
> > OdbcError: Found an insert row that didn't have 1 columns [sic]
>
> To me it looks as if your problem stems from not encoding the parameter as a
> string, but pasing a unicode-object that maybe internally causes trouble -
> and a misleading error message.
>
> So I suggest you try this:
>
> cur.execute("select * from users where userid = ?",
> [u'frank'.encode("utf-8"])
>
>
> If that works, we know the problem. Make sure that your DB is expecting
> UTF-8, or use the encoding it wants instead!
>

Thanks, Diez - I tried it and it works.

Unicode is one of those grey areas that I know I will have to try to
understand one day, but I am putting off that day as long as possible!

When you say it causes trouble internally, do you mean internal to the
odbc module? Is it something that should be reported as a bug?

What should I do in the meantime? Make encode("utf-8") a permanent
feature of my program?

BTW, the reason I am getting unicode objects is that I use wxPython as
my front end. You can opt for a unicode or a non-unicode build. I
decided to go for unicode to cater for future requirements. This is the
first time it has bitten me - I am sure it will not be the last.

Many thanks for your help

Frank

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


Re: Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Derick van Niekerk
[quote]
(just curious, but from where do people get the idea that arbitrary
data
just have to be inserted into the the SQL statement text all the time?
is
this some PHP misfeature?)
[/quote]

I've never seen it done in this way before, but I do come from a PHP
point of view.

I've only started with python this week, so a lot of the way it does
things are new to me, So far, all of the differences are good.

Thanks for the help

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


Re: Loading a Python collection from an text-file

2006-01-27 Thread Bengt Richter
On Mon, 23 Jan 2006 21:00:55 +0200, Ilias Lazaridis <[EMAIL PROTECTED]> wrote:

>within a python script, I like to create a collection which I fill with 
>values from an external text-file (user editable).
>
>How is this accomplished the easiest way (if possible without the need 
>of libraries which are not part of the standard distribution)?
>
>something like:
>
>text-file:
>{peter, 16},
>{anton, 21}
>
>-
>
>within code:
>
>users.load(text-file.txt)
>
>for user in users
>   user.name
>   user.age
>
>.
>
>-- 
>http://lazaridis.com

I'd use a CSV text file, maybe something like (only tested as far as you see!):

< for_ilias_lazaridis.py >--
import csv, types

class Fields(object):
def __init__(self, kvpairs): self.__dict__.update(kvpairs)

class Users(object):
def __init__(self):
self.userlist=[]
def load(self, lineiter):
if isinstance(lineiter, basestring):
lineiter = open(lineiter) # assume it's a file path
csvit = csv.reader(lineiter)
self.colnames = colnames = csvit.next()
typenames = csvit.next()
self.coltypes =coltypes = [getattr(types, name.capitalize()+'Type')
for name in typenames]
for row in csvit:
self.userlist.append(Fields(zip(colnames, (t(s) for t,s in 
zip(coltypes, row)
def __iter__(self): return iter(self.userlist)

def test():
import StringIO
f = StringIO.StringIO("""\
name,age
String,Int
peter,16
anton,21
""")
users = Users()
users.load(f)
for user in users:
print user.name, user.age
for user in users:
for name in users.colnames:
print '%s=%s,'%(name, getattr(user, name)),
print

if __name__ == '__main__': test()
---

Output:

[ 4:47] C:\pywk\clp>py24 for_ilias_lazaridis.py
peter 16
anton 21
name=peter, age=16,
name=anton, age=21,

(the first for user in users loop presumes knowledge of the field names name 
and age.
The second gets them automatically from the names loaded in the load method from
the first line of the text file. The second line expects type names as you see
in the types module, except without the "Type" suffix.

Perhaps you can adapt for your purposes.

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


Re: Loading a Python collection from an text-file

2006-01-27 Thread Fuzzyman
Seeing as we're suggesting alternatives, ConfigObj is great for hand
readable/writable data persistence.

You can use validate and ConfigPersist for automatic type conversion.

You can persist (basically) all the standard datatypes using this. The
syntax is usually more 'familiar' than Yaml, but it's not as flexible.

http://www.voidspace.org.uk/python/configobj.html

All the best,

Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

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


Re: [Tutor] socket and lost data

2006-01-27 Thread le dahut
Thanks for this answer.
Client do:
size1, passed1 = envoyer(conn, 50)
size2, passed2 = envoyer(conn, int(size1/passed1))
size3, passed3 = recevoir(conn)
size4, passed4 = recevoir(conn)
print size2/passed2
print size4/passed4

Server do:
recevoir(conn)
recevoir(conn)
size1, passed1 = envoyer(conn, 50)
size2, passed2 = envoyer(conn, int(size1/passed1))

This failed when client do its second 'envoyer' and server sees it still 
as first 'recevoir'. Why ?
I tried conn.shutdown(socket.SHUT_WR) to show first sending is 
terminated but I naturally got a "broken pipe" for the second sending so 
how can I resolve this problem ? Putting a time.sleep() in the client is 
ineffective ...
Any idea ?



Kent Johnson a écrit :
> le dahut wrote:
> 
>>Hi,
>>I try to send some data across a network (between 400KB and 10MB) like 
>>this :
>>def envoyer(conn, mysize):
>> print mysize,' KB sent'
>> data = '1'*1024
>> data_end = data[:-5]+'#'
>> data = data*(mysize-1)
>> begining = time.time()
>> conn.send(data)
>> conn.send(data_end)
>> passed = time.time() - begining
>> return passed, size
>>
> 
> 
> socket.send() may not send all the data - it returns a count telling you 
> what it actually did. Use socket.sendall() or put your call to send() in 
> a loop.
> 
> 
>>and receive it like this :
>>
>>def recevoir(conn):
>> data=''
>> while 1:
>> tmpdata = conn.recv(8192)
>> data += tmpdata
>> if '#' in data:
>> print 'END OF DATA'
>> break
>> print len(data)/1024, ' KB received'
>> return passed, int(data[-15:-5])/1024
> 
> 
> socket.recv() will return an empty string when there is no more data - I 
> would look for that instead of your marker, it is more general. Instead of
>if '#' in data:
> you can say
>if data == '':
> or just
>if not data:
> 
> 
>>But I don't receive as much data that I sent ... does someone know why ?
>>If I want to send the same data back to the client, do I have to destroy 
>>and recreate the socket ?
> 
> 
> If this doesn't fix it, maybe an example of the lost data would help.
> 
> Kent
> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loading a Python collection from an text-file

2006-01-27 Thread Magnus Lycka
Ilias Lazaridis wrote:
> [EMAIL PROTECTED] wrote:
> 
>> another approach (probably frowned upon, but it has worked for me) is
>> to use python syntax (a dictionary, say, or a list) and just import (or
>> reload) the file
>>
> 
> this sounds good.
> 
> can I import a whole collection of instances this way?

Sure, it's just a Python module with variables in it.

I wouldn't try to teach my users Python syntax though.

If you really need this kind of data structure freedom,
I'd lean towards YAML or possibly XML. (XML isn't too
bad if you provide good tools. It's not a good idea
with just a text editor.)

If a spreadsheet like layout is enough, I (still)
recommend csv.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loading a Python collection from an text-file

2006-01-27 Thread Magnus Lycka
Ido Yehieli wrote:
> perhapse consider using the pickle module?
> http://docs.python.org/lib/module-pickle.html

User editable? We should be kind to our users!

 >>> d = {'peter':14, 'paul':23}
 >>> pickle.dumps(d)
"(dp0\nS'paul'\np1\nI23\nsS'peter'\np2\nI14\ns."
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Loading a Python collection from an text-file

2006-01-27 Thread Magnus Lycka
Ilias Lazaridis wrote:
> within a python script, I like to create a collection which I fill with 
> values from an external text-file (user editable).
If a spreadsheet like layout fits, use the csv module and
a plain comma separated file.

Then the end user can also use e.g. Excel to edit the data.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decorators to add test* TestCase methods

2006-01-27 Thread Duncan Booth
Bruce Cropley wrote:

> Hi all
> 
> I'm trying to generate test methods in a unittest TestCase
> subclass, using decorators.  I'd like to be able to say:
> 
> class MyTestCase(unittest.TestCase):
> @genTests(["Buy", "Sell"], [1,2,3], [True, False])
> def something(self, side, price, someFlag):
> # etc...
> 
I would make the decorator simply save its arguments as attributes on the 
function and then add an explicit call after the class has been created to 
go and generate the tests.

so (untested code):

def generateTests(klass):
   for name in dir(klass):
fn = getattr(klass, name)
 if hasattr(fn, 'genTests'):
 # generate tests here...

def genTests(*args):
   def decorator(f):
   f.genTests = args
   return f
   return decorator

and then:

class MyTestCase(unittest.TestCase):
@genTests(["Buy", "Sell"], [1,2,3], [True, False])
def something(self, side, price, someFlag):
# etc...

generateTests(MyTestCase)

You could automate the call to generateTests using a metaclass if you 
wanted to avoid the explicit call.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: decorators to add test* TestCase methods

2006-01-27 Thread Peter Otten
Bruce Cropley wrote:

> I'm trying to generate test methods in a unittest TestCase
> subclass, using decorators.  I'd like to be able to say:
> 
> class MyTestCase(unittest.TestCase):
> @genTests(["Buy", "Sell"], [1,2,3], [True, False])
> def something(self, side, price, someFlag):
> # etc...
> 
> And have it generate functions called:
> test_Buy_1_True_something
> test_Buy_1_False_something
> through to...
> test_Sell_3_False_something

I think that's a nice idea. Here is a preliminary implementation:

#!/usr/bin/env python
import unittest

def combine(axes):
if axes:
for value in axes[0]:
for rest in combine(axes[1:]):
yield (value,) + rest
else:
yield ()

def make_method(func, name, args):
def method(self):
return func(self, *args)
method.__name__ = name
return method

class TestGrid(object):
def __init__(self, func, axes):
self.func = func
self.axes = axes
def __iter__(self):
axes = self.axes
func = self.func
name_format = "_".join(("test", self.func.__name__) +
("%s",)*len(axes))
for values in combine(axes):
name = name_format % values
yield name, make_method(func, name, values)

class genTests:
def __init__(self, *axes):
self.axes = axes
def __call__(self, func):
return TestGrid(func, self.axes)

class GridTestCase(unittest.TestCase):
class __metaclass__(type):
def __new__(mcl, clsname, bases, dict):
for name, value in dict.items():
if isinstance(value, TestGrid):
for method_name, method in value:
if method_name in dict:
raise Exception("name clash")
dict[method_name] = method
return type.__new__(mcl, clsname, bases, dict)


class MyTestCase(GridTestCase):
@genTests(["Buy", "Sell"], [1,2,3], [True, False])
def something(self, side, price, someFlag):
pass #print "test(side=%r, price=%r, someFlag=%r)" % (side, price,
someFlag)

if __name__ == "__main__":
unittest.main()

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


Re: generating method names 'dynamically'

2006-01-27 Thread Steve Holden
Daniel Nogradi wrote:
>>Here you go:
>>
>>  >>> database = {
>>  ... "Alice": 24,
>>  ... "Bob":25}
>>  ...
>>  >>> class Lookup(object):
>>  ... def __catcher(self, name):
>>  ... try:
>>  ... print "Hello my name is %s and I'm %s" % (name,
>>database[name])
>>  ... except KeyError:
>>  ... print "There was an error"
>>  ... def __getattr__(self, attr):
>>  ... return lambda:self.__catcher(attr)
>>  ...
>>  >>> inst = Lookup()
>>  >>> inst.Alice()
>>  Hello my name is Alice and I'm 24
>>  >>> inst.Bob()
>>  Hello my name is Bob and I'm 25
>>  >>> inst.John()
>>  There was an error
>>  >>>
>>
> 
> 
> Great, that was exactly what I was asking, thank you very much.

While I hesitate to rain on this little parade, I would caution you 
against adopting this solution as a generic programming tool. If people 
just need to interact with the database in an ad hoc way then this will 
let them do it, but it's a very poor recipe for general database search, 
since the content of your database determines the text of your program.

You might well find, on thinking about it a little more, that it mught 
be more straightforward to adopt a system more like this:

name = raw_input("Who do you want to know today: ")
inst = Lookup(name)
inst.show()

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Python String Substitution

2006-01-27 Thread Bengt Richter
On 26 Jan 2006 15:40:47 -0800, "Murali" <[EMAIL PROTECTED]> wrote:

>In Python, dictionaries can have any hashable value as a string. In
>particular I can say
>
>d = {}
>d[(1,2)] = "Right"
>d["(1,2)"] = "Wrong"
>d["key"] = "test"
>
>In order to print "test" using % substitution I can say
>
>print "%(key)s" % d
>
>Is there a way to print "Right" using % substitution?
>
>print "%((1,2))s" % d
>
>gives me "Wrong". Is there any syntax which will allow me to get
>"Right" using % substitution?

You can modify the dict to try to convert the string to what it is
a source for, by eval, and try that as a key also, if you have no security 
worries
about malevolent format strings:

 >>> class D(dict):
 ... def __getitem__(self, key):
 ... print repr(key)
 ... if key in self: return dict.__getitem__(self, key)
 ... else: return self[eval(key)]
 ...
 >>> d = D()
 >>> d[(1,2)] = "Right"
 >>> d["key"] = "test"
 >>> print "%(key)s" % d
 'key'
 test
 >>> print "%((1,2))s" % d
 '(1,2)'
 (1, 2)
 Right
 >>> d[123] = 'onetwothree'
 >>> print "%(123)s" % d
 '123'
 123
 onetwothree

Note recursive printing of converted key when the first one fails.
Of course if you _also_ define the string key for Wrong, that will
succeed, so it won't get converted to get Right:

 >>> d["(1,2)"] = "Wrong"
 >>> print "%((1,2))s" % d
 '(1,2)'
 Wrong
 >>> d[(1,2)]
 (1, 2)
 'Right'

Do you have a real use case? Just curious.

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


Re: beta.python.org content

2006-01-27 Thread Steve Holden
Paddy wrote:
> I find it much better than the current site, thank you!
> 
> Whilst reading, http://beta.python.org/about/ I had some slight
> niggles.
> What do you think about the following changes?
> 
> About Python
> 
> Python is an agile programming language often compared to Tcl, Perl,
> Ruby, Scheme or Java. While it has much in common with them it also has
> unique features that set it apart.
> 
> * remarkable power with very clear syntax
> * fully modular, with modules in individual files,
>   or packages: a hierarchical arrangement of modules
>   for larger projects.
> * intuitive object orientation, but also supports a
>   functional style of programming too.
> * exception-based error handling
> * very high level dynamic data types that are easy to use.
> * interfaces to many system calls and libraries
> * access to multiple GUI toolkits (X11, Motif, Tk, Mac, MFC,
> wxWidgets)
> * extensions and modules easily written in C, C++ or Python
> * embeddable within applications needing a scripting interface
> 
I decided to go with:

Python is an agile programming language often compared to Tcl, Perl, 
Ruby, Scheme or Java.
While it has much in common with them it also has unique features that 
set it apart.

   * remarkable power with very clear syntax
   * full modularity, supporting hierarchical packages
   * intuitive object orientation
   * natural expression of procedural code
   * exception-based error handling
   * very high level dynamic data types
   * interfaces to many system calls and libraries
   * access to multiple GUI toolkits (X11, Motif, Tk, Mac, MFC, wxWidgets)
   * extensions and modules easily written in C, C++ or Python
   * embeddable within applications needing a scripting interface

Thanks for your remarks. All readers please note we are looking for 
editors for this stuff!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: problems with documentation

2006-01-27 Thread BartlebyScrivener
Specifically it's the TOPICS that I can't seem to get to work. The
keywords and modules etc do work. But if I type, e.g.,
help("functions") it says, "No documentation found" If I type
help("os") I get help on the os module.

rpd

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


Re: beta.python.org content

2006-01-27 Thread Steve Holden
Shalabh Chaturvedi wrote:
> Steve Holden wrote:
> 
>>How does
>>
>>   http://beta.python.org/about/beginners/
>>
>>look?
>>
> 
> 
> 
> Steve,
> 
> This is a great writeup. Here are my comments:
> 
> 1. "Fortunately Python is something that an experienced programmer of 
> another language (be it ..."
> 
> Add C# and/or Java to this list. The current list might scare away a lot 
> of people ;).
> 
I just went with "whatever it may be" as even less exclusive :-)

> 2. "also available as the python-list mailing list"
> 
> Add "or a google group (link)".
> 
Gimme the link!

> 3. "You may want to find out which text editors* are tailored to make 
> Python editing* easy"
> 
> Change at two places:
> You may want to find out which text editors or IDEs 
> (http://wiki.python.org/moin/IntegratedDevelopmentEnvironments) are 
> tailored to make Python programming easy.
> 
I added IDE's as a separate category - great idea!

> 4. Typo: look for 'welcomne'
> 
Fixed, thanks.

> 5. There seems to be a great overlap between this and what could go in 
> the 'For Developers' section. Maybe we need only one section ('For 
> Developers'?) In general many pages with overlapping content confuse me 
> (and probably others)
> 
Don't agree. Repetition is actually better that presenting each piece of 
information precisely once for many purposes.

Anyway, I am also working on the developer section in parallel to 
improve the focus of that content.

> 6. The 'About' page should have an additional section:
> 
> Python is Popular
> 
> Thousands of developers use Python to make themselves more productive in 
> application domains across the board - enterprise computing, web 
> development, game development, scientific and numerical computing, 
> embedded and mobile development and more. See `Success Stories` and 
> `Quotes` to discover more.
> 
> Thanks,
> Shalabh
> 
Excellent, thanks!

regards
  Steve
-- 
Steve Holden   +44 150 684 7255  +1 800 494 3119
Holden Web LLC www.holdenweb.com
PyCon TX 2006  www.python.org/pycon/

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


Re: Dictionary inserts into MySQL (each key in its own field)

2006-01-27 Thread Carsten Haese
On Fri, 2006-01-27 at 05:47, Fredrik Lundh wrote:
> (just curious, but from where do people get the idea that arbitrary data
> just have to be inserted into the the SQL statement text all the time?  is
> this some PHP misfeature?)

Yes, the need to roll queries by inserting parameters directly into the
query string is definitely a PHP misfeature (for versions less than 5),
since the database access modules don't accommodate parametrized
queries. PHP5 finally introduced a standardized database API that allows
parametrized queries. Of course, Python has had this since 1996.

-Carsten


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


Re: Loading a Python collection from an text-file

2006-01-27 Thread Ido Yehieli
>>Sure, it's just a Python module with variables in it.
>>
>>I wouldn't try to teach my users Python syntax though.

not to mention the security risks

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


Re: problems with documentation

2006-01-27 Thread BartlebyScrivener
Still doesn't work for me. I've tried everything. I think it's because
PythonWin keeps trying to read the ActiveState .chm file, even if you
download the html files and set the PYTHONDOCS variable.

Oh well.

rpd

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


Re: beta.python.org content

2006-01-27 Thread Dale Strickland-Clark
Michael Tobis wrote:

> I like the design, though I'd prefer stronger colors. I think it would
> be a major improvement except for the logo.
> 
>

So, are you saying you don't like the new logo?

I'm with you. I don't like it either. It looks like a diagram out of the
well known Anguine Kama Sutra. 

The new site, however is very nice. Top marks for that.
-- 
Dale Strickland-Clark
Riverhall Systems www.riverhall.co.uk

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


Re: Question about isinstance()

2006-01-27 Thread Magnus Lycka
Mr.Rech wrote:
> Hi all,
> I've read some thread about isinstance(), why it is considered harmful
> and how you can achieve the same results using a coding style that
> doesn't break polymorphism etc... Since I'm trying to improve my Python
> knowledge, and I'm going to design a class hierarchy from scratch, I'd
> like to have some feedback about this from those of you much more
> experienced than me in OOP.
[snip]
> Any better way to write this method? Any suggestion?

It's really impossible to tell what's good Python code
based on details like this. isinstance() wouldn't be in
Python if you weren't supposed to use it, but you need to
understand when you should limit your functions to work
with a specific kind of data, and when you should try to
be broader. This is a design decision that will influence
the usability and maintainability of your code. We can't
help you figure out how to make such trade-offs based on
your implementation of __eq__.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beta.python.org content

2006-01-27 Thread Magnus Lycka
>> Python is an agile programming language often compared to Tcl, Perl,
>> Ruby, Scheme or Java. While it has much in common with them it also has
>> unique features that set it apart.

James Stroud wrote:
> Maybe:
> 
> "Python is an object oriented programming language designed to increase 
> productivity. Though it is often compared to Perl, Tcl, Ruby, Scheme, or 
> Java, it has several powerful features that set it apart."

Definitely better. The first text seems to define Python through
comparision, and that doesn't show a lot of confidence for mature
language like Python. (It's one thing if it was much younger than
the others, but it's somewhere in the middle of that group.)

Agile might be a better buzz-word than object oriented though.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beta.python.org content

2006-01-27 Thread Kay Schluehr
The new Python site is incredibly boring. Sorry to say this. The old
site is/was amateurish but engaged. Now after ~15 years of existence
Pythons looks like it wants to be popular among directors of a german
job centers. It aims to do everything right but what could be said
worse? The text on the beginners page tries to argue with the potential
users in a pointless monologue. Who wants to read this text? Who wants
to be convinced that Python is *not* slow? "Do you stop beating your
wife?" And where is fun, irony and black humour? Why Python? "Python in
industry" - I see chimneys of 19th century factories, proletarian
heroes as well as futuristic hybrid robots superseeding humanity.
"Python community" - a dutch grand-family photo from the beginning of
the 20ths century - some ( or all? ) of the members are accidentally
looking like Guido, "Python in science" - snake-like RNA strand. It
need not be like this but I wonder about the total lack of personality.


Kay

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


Re: HTMLTestRunner - generates HTML test report for unittest

2006-01-27 Thread Paul McGuire
"aurora" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Greeting,
>
> HTMLTestRunner is an extension to the Python standard library's unittest
> module. It generates easy to use HTML test reports. See a sample report at
> http://tungwaiyip.info/software/sample_test_report.html.
>
> Check more information and download from
> http://tungwaiyip.info/software/#htmltestrunner
>
> Wai Yip Tung

Nice!  I just adapted my pyparsing unit tests to use this tool - took me
about 3 minutes, and now it's much easier to run and review my unit test
results.  I especially like the pass/fail color coding, and the "drill-down"
to the test output.

-- Paul


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


Re: beta.python.org content

2006-01-27 Thread A.M. Kuchling
On Fri, 27 Jan 2006 13:33:06 +, 
Steve Holden <[EMAIL PROTECTED]> wrote:
>>>   http://beta.python.org/about/beginners/

My suggestion would be "too much text".  IMHO, people do not read
paragraphs of material on the web.  The basic structure shouldn't be
the paragraph, but the bullet point.  e.g.

Why Python?

Agile programming language 
Active community : conferences , 
newsgroups , mailing lists 
Open source 

Questions?  See the FAQ.  

I learned this at the MEMS Exchange, where we began by writing an
explanatory paragraph explaining how to do something.  Users would
ignore it completely, and call us on the phone asking "how do I do X?
What's a Y?" even though X and Y were explained right in that text.
Once it was rewritten into note form, the phone calls became much less
frequent.  The wiki beginner's guide tries to be similarly laconic,
though it doesn't always succeed.

It's irritating, I know; the paragraphs aren't unduly long, and the
style is readable, not boring or academic.  It would make a good
article, press release, or white paper.  But web users just don't care
about blocks of text.  (I keep meaning to fix
http://www.python.org/2.4.2/, which is just awful in this respect.)

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


Re: beta.python.org content

2006-01-27 Thread Dave Hansen
On Thu, 26 Jan 2006 15:28:50 -0800 in comp.lang.python, James Stroud
<[EMAIL PROTECTED]> wrote:

>Rocco Moretti wrote:
>> (Not that I like the logo, mind you...)
>
>Does anyone? There has to be a better logo! I thought the previous 
>requirement as established by the BDFL was no snakes. These are snakes, 
>and they have no personality to boot.

I like it, FWIW.  Better than a dead parrot or a killer rabbit IMHO.
Though maybe not as funny...

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: generating method names 'dynamically'

2006-01-27 Thread Magnus Lycka
Daniel Nogradi wrote:
> Well, I would normally do what you suggest, using parameters, but in
> the example at hand I have to have the method names as variables and
> the reason is that the whole thing will be run by apache using
> mod_python and the publisher handler. There a URL
> http://something.com/program2/Bob is mapped to the 'Bob' method of the
> file program2.py and I want to be able to have URL's with different
> names. I know I can solve this problem with parameters and functions
> and using the GET http method, but I would like to have pretty URL's
> without & and ? signs. I didn't want to ask this on the mod_python
> list because after all it's a pure python question.

Ouch! This certainly seems like a possible security hole!

As someone else said, use rewrite rules to get this passed
in as a parameter.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beta.python.org content

2006-01-27 Thread Magnus Lycka
Steve Holden wrote:
> How does
> 
>   http://beta.python.org/about/beginners/
> 
> look?

I think it's a well written text, but it looks more like
an introductionary chapter in a book about Python than a
text for a web site. A book looks the same for all its
readers, and it's basically sequential. Books also have
readers who've made much more of a commitment to read.
They won't click somewhere else just because it was dull
for ten seconds-

It's clear that this web site is intended to present
different information to different kinds of people, but
I don't understand for whom *this* text is written...

In fact I don't quite understand the "About" section at all,
with the subsections "For Beginners", "For Developers" and
"For Business" etc.

What does "About" mean? Is is "about this web site" or
is it "about the Python programming language". About
Python it seems. Isn't the whole site about Python?

If "about" really means "introduction", why doesn't it
say "Introduction".

Since the whole section seems to be geared towards people
who don't know a lot about Python already, and the "for
beginners" page seems to fend off people who are "completely
new to programming" with a link, it seems to me that it's
either for programmers or for some kind of decision makers
or reporters who'd prefer the business page anyway.

If we need some general introduction for all, it should be
much shorter, more like http://python.org/doc/Summary.html

Concerning the next entries in the "About" section (not what
you asked about, so this is just a bonus;):

I don't like anyone to hand me different texts based on whom
I say I am. I want to know what the texts are about and decide
for myself where to go. These are texts, not dressing rooms!

So, describe the content of each page instead of saying "If
you're this kind of guy, we think you should read this page".
It's great to take different "actors" into account, but that
should not be the public labels on the web site. It's like
the desk for dissatisfied customers in a department store.
The sign on the outside says "complaints" or something like
that. The "stupid customers" sign has to be on the inside.
That's not what you present to the stupid customers...

Perhaps the "About Section" should look like this?

Introduction
-What is Python [short summary]
-Getting started[a.k.a. for beginners/programmers, how to d/l etc]
-Why Python?[a.k.a. for business]
-Success Stories
-Quotes

I don't quite understand why there is a "PSF" entry here. If
I went to the Python web site actively looking for info about
PSF, I would not look under the introductory "About" menu, but
rather under "community". If I'm new to Python, I'd probably
ignore that meaningless acronym. Please move to Community and
make a link from "Why Python" in a sentence describing how
using Python avoids vendor lock in.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatic Logging

2006-01-27 Thread Gregory Petrosyan
My decorator bike:


import logging
import traceback

logging.basicConfig(level=logging.DEBUG,
format="%(asctime)s %(levelname)s:\n%(message)s\n",
filename="/tmp/py.log",
filemode='w')

def log(f):
def new_f(*args, **kwds):
try:
indent = len("(in '%s')  %s(" % (f.__module__,
f.func_name))
nice_args = [repr(a) for a in args]
nice_args = (',\n'+' '*indent).join(nice_args)
nice_kwds = [str(a) + ' = ' + repr(b) for a,b in
kwds.items()]
if nice_kwds:
nice_kwds[0] = ' '*indent + nice_kwds[0]
nice_kwds = (',\n'+' '*indent).join(nice_kwds)
nice_args = nice_args + ',\n' + nice_kwds
else:
nice_args = nice_args + ', {}'
logging.info("(in '%s')  %s(%s)  starts" % \
 (f.__module__, f.func_name, nice_args))
result = f(*args, **kwds)
except:

logging.error('\n'.join(traceback.format_exc().split('\n')[1:])[:-1])
raise
return result
new_f.func_name = f.func_name
return new_f

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


Re: Question about isinstance()

2006-01-27 Thread Rene Pijlman
Magnus Lycka:
>isinstance() wouldn't be in Python if you weren't supposed to use it,

If this argument was correct, 'goto' wouldn't be in Pascal :-)

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beta.python.org content

2006-01-27 Thread Paul Boddie
Dave Hansen wrote:
>
> I like it, FWIW.  Better than a dead parrot or a killer rabbit IMHO.
> Though maybe not as funny...

Why not just take the Parrot logo and rotate it by 90 degrees? ;-)

http://www.parrotcode.org/

Paul

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


Re: Using non-ascii symbols

2006-01-27 Thread Dave Hansen
Just a couple half-serious responses to your comment...

On Fri, 27 Jan 2006 11:05:15 +0100 in comp.lang.python, Magnus Lycka
<[EMAIL PROTECTED]> wrote:

>Terry Hancock wrote:
>> That's interesting. I think many people in the West tend to
>> imagine han/kanji characters as archaisms that will
>> disappear (because to most Westerners they seem impossibly
>> complex to learn and use, "not suited for the modern
>> world"). 
>I don't know about "the West". Isn't it more typical for the
>US that people believe that "everybody really wants to be like
>us". Here in Sweden, *we* obviously want to be like you, even
>if we don't admit it openly, but we don't suffer from the
>misconception that this applies to all of the world. ;)

1) Actually, we don't think "everyone wants to be like us."  More like
"anyone who doesn't want to be like us is weird."

2) This extends to our own fellow citizens.

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using non-ascii symbols

2006-01-27 Thread Dave Hansen
On Fri, 27 Jan 2006 08:11:24 GMT in comp.lang.python, [EMAIL PROTECTED]
(Bengt Richter) wrote:

[...]
>Maybe you would like the unambiguousness of
>(+ 8 (* 6 2))
>or
>6 2 * 8 +
>?

Well, I do like lisp and Forth, but would prefer Python to remain
Python.

Though it's hard to fit Python into 1k on an 8-bit mocrocontroller...

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Automatic Logging

2006-01-27 Thread Gregory Petrosyan
Sorry for broken indentation.

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


Re: beta.python.org content

2006-01-27 Thread Dave Hansen
On Fri, 27 Jan 2006 13:33:06 + in comp.lang.python, Steve Holden
<[EMAIL PROTECTED]> wrote:

>Shalabh Chaturvedi wrote:
[...]
>
>> 2. "also available as the python-list mailing list"
>> 
>> Add "or a google group (link)".

It's not a "Google Group," it's a Usenet newsgroup.  Google merely
provides a lousy but accessible interface to Usenet.

>> 
>Gimme the link!

http://groups.google.com/group/comp.lang.python

Regards,
-=Dave

-- 
Change is inevitable, progress is not.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with odbc (pywin32) and unicode

2006-01-27 Thread Diez B. Roggisch
> Unicode is one of those grey areas that I know I will have to try to
> understand one day, but I am putting off that day as long as possible!

I suggest you better start right away instead of stumbling over it all the
time. The most problems in that field don't come from the inherent
complexity of the matter itself, but form the profound lack of
understanding of developers thereof - worldwide, btw. You are not alone, as
Mr. Jackson sang...

> 
> When you say it causes trouble internally, do you mean internal to the
> odbc module? Is it something that should be reported as a bug?

Not sure, but I guess: yes.
 
> What should I do in the meantime? Make encode("utf-8") a permanent
> feature of my program?

You should do it in a way that allows you to either pass the encoding
explicitly, or make it some sort of configurable thing, in the same spot
where you configure your connection settings, as these two are related.

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


Re: beta.python.org content

2006-01-27 Thread Rocco Moretti
Paul Boddie wrote:

> With the nice font they've used, I don't understand why they didn't
> turn the "p" into a snake itself. I'm sure I've seen that done
> somewhere before.

You're probably thinking of PyPy:

http://codespeak.net/pypy/dist/pypy/doc/news.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter listener thread?

2006-01-27 Thread gregarican
Eric Brunel wrote:

> There's in fact no need to check regularly if there's something in the
> Queue: the secondary thread can post a tk custom event to trigger the
> treatment automatically from within the main GUI loop. See here:
> http://minilien.fr/a0k273

Appreciate the suggestion. This further helps simplify things. So far
so good getting the UDP listener to work well within Tkinter. This
listener takes an incoming CTI screen pop of the caller ID and queries
it against a CRM database to bring up the appropriate contact record if
applicable. One of these days I need to port the CTI library over from
Ruby into Python so I don't have to rely on a UDP socket connection and
can just pass the data natively within Python. But this is a workaround
until that day comes.

Thanks again. I am very impressed with the Python community in terms of
knowledge and helpfulness. It's made matters a lot easier for this
particular Python newbie...

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


Re: matplotlib legend problem

2006-01-27 Thread bwaha

"bwaha" <[EMAIL PROTECTED]> wrote in message
news:[EMAIL PROTECTED]
> Has anyone figured out how to get a legend for each line in a
> matplotlib.collections.LineCollection instance?
>
After frigging around for hours I finally tracked down the real cause of the
plotting speed problem which led me to use LineCollections in the first
place. Its the 'best' option in the legend location and setting it to
default in my application!

When I first put in the LineCollection code I cut out my legend code to keep
things simple. And sure enough LineCollections plotted really fast. Then,
since legends didn't work for LineCollection lines individually I figured
I'd fudge it by creating dummy lines from the collection, adding labels and
calling legend(). This worked with only a small speed penalty.  But I kept
getting a stackdump when I added the location argument. Finally realised it
was due to having a default of 'best' location in my code which meant it
went searching for intersection with lines that don't exist (outside of the
LineCollection). So I disabled the 'best' location option. Then I figured,
since I'd cleaned up my code a bit, I'd reinstate my earlier pylab.plot
based line drawing code to see if the clean up made any difference to what
was previously abysmal performance. The lines plotted faster than the
LineCollection code! When I removed the legend hack for LineCollections
there was virtually no difference. (Story is not finshed yet). So I figured
after all that that I'd reinstate my pylab.plot based code since I could
plot a greater range of symbols than with LineCollections with no speed
loss. And I thought why not go the whole hog and reinstate the 'best'
location option too. Boom! Plotting performance was abysmal again. Finally I
realised that enabling 'best' and having it as the default meant that as I
added new data to plot, the search time for a good place to put the legend
increased dramtically, and probably became more difficult with more and more
lines filling the canvas.

Anyway now I'm a lot happier than when I started because I've retained my
original range of plot styles and I got much faster plotting. Hopefully this
lesson can help someone else.




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


Re: beta.python.org content

2006-01-27 Thread Michael Tobis
What about some permutation of the PyCon logo? It is really quite
brilliant.

Solves many problems:
dynamic, doesn't just sit there, looks like it is moving toward a
goal
direction of motion surprising and memorable
refers to software in the minds of experienced coders
takes advantage of the snake association without being creepy
reassuring to corporate types but fun and T-shirt friendly
can be permuted in lots of amusing ways, optionally as output from
code
first impression is cheerful, second impression is cleverness

http://www.python.org/pycon/2006/logo.png

Kudos to whoever came up with that, by the way!

mt

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


Re: beta.python.org content

2006-01-27 Thread Juho Schultz
Steve Holden wrote:
> How does
> 
>   http://beta.python.org/about/beginners/
> 
> look?
> 
> regards
>  Steve

I think the content is good, but I would suggest putting some bullet 
points with links at the top. IMO top part of the beginner page should 
somehow indicate that tutorial and FAQ is accessible from this page.

The page looks a bit dull - there is nothing bright-colored there.
Have a look at the www.holdenweb.com in your sig to see what I mean.
The small lines of red and yellow on the upper right and the orange 
picture on used there makes the page a lot more alive.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: beta.python.org content

2006-01-27 Thread Tim Parkin
Magnus Lycka wrote:

> ...
>
>I don't like anyone to hand me different texts based on whom
>I say I am. I want to know what the texts are about and decide
>for myself where to go. These are texts, not dressing rooms!
>  
>
Unfortunately most people do.. That's why there are beginners books,
business books, advanced books etc..

>So, describe the content of each page instead of saying "If
>you're this kind of guy, we think you should read this page".
>It's great to take different "actors" into account, but that
>should not be the public labels on the web site. It's like
>the desk for dissatisfied customers in a department store.
>The sign on the outside says "complaints" or something like
>that. The "stupid customers" sign has to be on the inside.
>That's not what you present to the stupid customers...
>
>Perhaps the "About Section" should look like this?
>
>Introduction
>-What is Python [short summary]
>-Getting started[a.k.a. for beginners/programmers, how to d/l etc]
>-Why Python?[a.k.a. for business]
>-Success Stories
>-Quotes
>  
>
Looks good.. I'll have a bit more of a think about it, perhaps the
"getting started" and "why python" pages
could have sections within them (headers) for "if you are new to
programming" and "Should I use python in my business".

>I don't quite understand why there is a "PSF" entry here. If
>I went to the Python web site actively looking for info about
>PSF, I would not look under the introductory "About" menu, but
>rather under "community". If I'm new to Python, I'd probably
>ignore that meaningless acronym. Please move to Community and
>make a link from "Why Python" in a sentence describing how
>using Python avoids vendor lock in.
>  
>
OK.. I'll put it up as a ticket and try to change it around at the weekend.

Thanks for the feedback.

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


Re: beta.python.org content

2006-01-27 Thread Terry Hancock
On Fri, 27 Jan 2006 09:30:20 -0600
Rocco Moretti <[EMAIL PROTECTED]> wrote:
> Paul Boddie wrote:
> > With the nice font they've used, I don't understand why
> > they didn't turn the "p" into a snake itself. I'm sure
> > I've seen that done somewhere before.
> 
> You're probably thinking of PyPy:

Huh.
Seems like the PyPy logo should surely be an Ouroboros!

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

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


"Python Drive Name" is the search, what is the question?

2006-01-27 Thread Gregory Piñero
Just thought I'd see if you guys had an answer for this.  My website
analytics page shows that people come to my site after searching for
"Python drive name" but I don't think I'm offering any help with such
a thing.

However I would like to help since I'm getting a few people a day for
this.  So does anyone have an idea on what they could be searching for
 and of course what the answer would be?

Sorry it's such a vague question for you guys, but I thought maybe
you'd enjoy a mystery for the day!

--
Gregory Piñero
Chief Innovation Officer
Blended Technologies
(www.blendedtechnologies.com)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: "Python Drive Name" is the search, what is the question?

2006-01-27 Thread Gerhard Häring
Gregory Piñero wrote:
> Just thought I'd see if you guys had an answer for this.  My website
> analytics page shows that people come to my site after searching for
> "Python drive name" but I don't think I'm offering any help with such
> a thing.
> 
> However I would like to help since I'm getting a few people a day for
> this.  So does anyone have an idea on what they could be searching for
>  and of course what the answer would be?
> 
> Sorry it's such a vague question for you guys, but I thought maybe
> you'd enjoy a mystery for the day!

Maybe which drive Python is installed on?

 >>> os.path.splitdrive(sys.prefix)[0]
'c:'

No I can't really guess what these people are looking for ...

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


Re: matplotlib legend problem

2006-01-27 Thread John Hunter
> "bwaha" == bwaha  <[EMAIL PROTECTED]> writes:
bwaha> added the location argument. Finally realised it was due to
bwaha> having a default of 'best' location in my code which meant
bwaha> it went searching for intersection with lines that don't
bwaha> exist (outside of the LineCollection). So I disabled the
bwaha> 'best' location option. Then I figured, since I'd cleaned
bwaha> up my code a bit, I'd reinstate my earlier pylab.plot based
bwaha> line drawing code to see if the clean up made any
bwaha> difference to what was previously abysmal performance. The
bwaha> lines plotted faster than the LineCollection code! When I
bwaha> removed the legend hack for LineCollections there was
bwaha> virtually no difference. (Story is not finshed yet). So I
bwaha> figured after all that that I'd reinstate my pylab.plot
bwaha> based code since I could plot a greater range of symbols
bwaha> than with LineCollections with no speed loss. And I thought
bwaha> why not go the whole hog and reinstate the 'best' location
bwaha> option too. Boom! Plotting performance was abysmal
bwaha> again. Finally I realised that enabling 'best' and having
bwaha> it as the default meant that as I added new data to plot,
bwaha> the search time for a good place to put the legend
bwaha> increased dramtically, and probably became more difficult
bwaha> with more and more lines filling the canvas.

bwaha> Anyway now I'm a lot happier than when I started because
bwaha> I've retained my original range of plot styles and I got
bwaha> much faster plotting. Hopefully this lesson can help
bwaha> someone else.


Sorry you had to find this out after so much trial and error.  For a
small number of large length lines (eg 10 at 30k points each), plot
will be much faster than line collections as you observed.  For a
large number of small lines (eg 1000 at 20 points each) line
collections will be much faster.  And yes, the "best" optimization for
the legend is slow -- I'm on the fence as to whether this should be
the default or not.  At least clearly flagging this as a performance
bottleneck in the docs would be useful.

Cheers,
JDH


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


Re: generating method names 'dynamically'

2006-01-27 Thread Daniel Nogradi
> Ouch! This certainly seems like a possible security hole!
>
> As someone else said, use rewrite rules to get this passed
> in as a parameter.

I don't get it, why is it more safe to accept GET variables than
method names? Concretely, why is the URL
http://something.com/script?q=parameter safer than
http://something.com/script/parameter if in both cases exactly the
same things are happening with 'parameter'? It has to be checked in
both cases, characters like ', ", /, \, etc, has to be stripped and
than it will be fed into the same SQL query. So either way, I have to
implement some checking mechanism, what difference does it make if the
result of the checking is fed into a function as an argument and the
SQL query receives it that way, or a method of a class is called by
the name 'parameter' and the SQL query receives it as a reference to
the method name?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Running a DOS exe file from python

2006-01-27 Thread Peter Hansen
Rinzwind wrote:
> Something like this:
> progname = 'c:\tmp\myprog.exe arg1 '+'-- help'
> os.system(r'progname)

Well, other than the ways in which it wouldn't work:

1. "arg1" doesn't get substituted with anything, if that's what you 
meant, but rather is inserted as the literal string "arg1".  If you 
meant that just as an example of some other argument that would be 
hardcoded, then it's unclear why you have the + in there since you could 
just have written the whole thing as a single string.

2. You need the 'r' meaning raw string *on the string literal*, in the 
first line, not in the second line.  In your code, the string bound to 
the name "progname" contains an ASCII TAB character in the third byte, 
after the "c" and the ":", which isn't likely what you wanted.

3. In the second line you have an unterminated string...

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


Re: generating method names 'dynamically'

2006-01-27 Thread Peter Hansen
Daniel Nogradi wrote:
>>Ouch! This certainly seems like a possible security hole!
>>
>>As someone else said, use rewrite rules to get this passed
>>in as a parameter.
> 
> I don't get it, why is it more safe to accept GET variables than
> method names? Concretely, why is the URL
> http://something.com/script?q=parameter safer than
> http://something.com/script/parameter if in both cases exactly the
> same things are happening with 'parameter'? 

If *exactly* the same thing were happening, the security risk is the same.

> It has to be checked in
> both cases, characters like ', ", /, \, etc, has to be stripped and
> than it will be fed into the same SQL query. So either way, I have to
> implement some checking mechanism, what difference does it make if the
> result of the checking is fed into a function as an argument and the
> SQL query receives it that way, or a method of a class is called by
> the name 'parameter' and the SQL query receives it as a reference to
> the method name?

The difference is that the script?q=parameter approach would be calling 
a single, defined function which could check the "q" argument fully, 
while the script/parameter approach might not be checked before the 
choice of function to be called is made.

In other words, script?q=__init__ is more likely to do the correct thing 
(rejecting the input) than script/__init__ is...  but ultimately if you 
do adequate checking of the inputs, either approach can be made safe.  I 
think Magnus was just pointing out that the script/parameter approach is 
more typically (i.e. in the real world) subject to quick coding and high 
exposure solutions than the other... not that it's inherently worse.

-Peter

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


Re: "Python Drive Name" is the search, what is the question?

2006-01-27 Thread Rene Pijlman
Gregory Piñero:
>Just thought I'd see if you guys had an answer for this.  My website
>analytics page shows that people come to my site after searching for
>"Python drive name" but I don't think I'm offering any help with such
>a thing.
>
>However I would like to help since I'm getting a few people a day for
>this.  So does anyone have an idea on what they could be searching for

Perhaps they're searching for the official name of the Python DAT tape
drive model.
http://www.datman.com/tbul/dmtb_014.htm

>and of course what the answer would be?

The firmware names usually look like: 25501-XXX, 25501-008, 25947-XXX,
25588-???, 27871-XXX, 28388-XXX.

-- 
René Pijlman
-- 
http://mail.python.org/mailman/listinfo/python-list


SOAPpy

2006-01-27 Thread Skink
hi,

there is a soap service:
http://waluty.k2.pl/ws/NBPRates.asmx

the question is why when i call GetRateValue method i always get '0' result?


>>> import SOAPpy
>>> srv = SOAPpy.WSDL.Proxy("http://waluty.k2.pl/ws/NBPRates.asmx?WSDL";)
>>> srv.GetAllCodes()
'AUD CAD CHF CYP CZK DKK EEK EUR GBP HKD HUF JPY LTL LVL MTL NOK RUB SEK
SIT SKK UAH USD XDR ZAR '
>>> srv.GetRateValue('USD')
'0'

it seems that methods with no params are working but these that take at
least one param not.

you can check it by going to http://www.soapclient.com/soaptest.html and
entering http://waluty.k2.pl/ws/NBPRates.asmx?WSDL as WSDL File Address

the rate should be ~3.1379 or something

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


Re: beta.python.org content

2006-01-27 Thread A.M. Kuchling
On 27 Jan 2006 08:08:58 -0800, 
Michael Tobis <[EMAIL PROTECTED]> wrote:
> What about some permutation of the PyCon logo? It is really quite
> brilliant.
   ...
> http://www.python.org/pycon/2006/logo.png
> 
> Kudos to whoever came up with that, by the way!

It was Michael Bernstein who designed it, I believe, and agree that
it's a great logo for PyCon.

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


Re: Using non-ascii symbols

2006-01-27 Thread Runsun Pan
On 1/27/06, Magnus Lycka <[EMAIL PROTECTED]> wrote:
> > After taking a couple of semesters of Japanese, though, I've
> > come to appreciate why they are preferred.  Getting rid of
> > them would be like convincing English people to kunvurt to
> > pur fonetik spelin'.
> >
> > Which isn't happening either, I can assure you. ;-)
> The Germans just had a spelling reform. Norway had a major
> language reform in the mid 19th century to get rid of the old
> Danish influences (and still have two completely different ways
> of spelling everything). You never know what will happen. You
> are also embracing the metric system, inch by inch... ;)

The simplified chinese exists due to the call for modernization of
language decades ago. That involved the 'upside-down' of almost
entire culture --- nowadays people in China can't even read most of
the documents written just 70~80 years ago. Imagine its damage
to the 'historical sense' of modern chinese !!! The "anti-simplification"
force was thus imaginaribly huge. Actually, not only the original
plan of simplification wasn't completed (only proceded to the 1st
stage; the 2nd stage was put off), there are calls for reversal -- back
to the traditional forms -- lately. Obviously, language reform is not
trivial; Especially, for asian countries, it is probably not as easy as it
is for western countries.

China is still a central authoritarian country. Even with that government
they were unable to push this thru. If any one would even dream about
language reform in democratic Taiwan, I bet the proposal won't even
pass the first step in the congress.

> Actually, it seems that recent habit of sending text messages
> via mobile phones is the prime driver for reformed spelling
> these days.

Well, to solve the problem you can either (1) reform the spelling
of a language to meet the limitation of mobile phones, or (2)
advancing the input device on the mobile phones such that they
can input the language of your choice. For most asian languages,
(1) is certainly out of question.

> > I'm not sure I understand how this works, but surely if
> > Python can provide readline support in the interactive
> > shell, it ought to be able to handle "phrase input"/"kanji
> > input."  Come to think of it, you probably can do this by
> > running the interpreter in a kanji terminal -- but Python
> > just doesn't know what to do with the characters yet.
> I'm sure the same principles could be used to make a very fast
> and less misspelling prone editing environment though. That
> could actually be a reason to step away from vi or Emacs (but
> I assume it would soon work in Emacs too...)

True. Actually Google, Answers.com and some other desktop
applications use 'auto-complete' feature already. It might seem
impressive to most western users but, from where I was from
(Taiwan), this 'phrase-input', as well as "showing up in the order
of the most-frequently-use for any specific user", have been
around for about 20 years.

>> I would like to point out also, that as long as Chinese
>> programmers don't go "hog wild" and use obscure characters,
>> I suspect that I would have much better luck reading their
>> programs with han characters, than with, say, the Chinese
>> phonetic names!  Possibly even better than what they thought
>> were the correct English words, if their English isn't that
>> good.
> You certainly have a point there. Even when I don't work in an
> English speaking environment as I do now, I try to write all
> comments and variable names etc in English. You never know when
> you need to show a code snippet to people who don't read Swedish.
> Also, ASCII lacks three of our letters and properly translated
> is often better than written with the wrong letters.

If there will be someday that any programming language can
be input with some form like Big5, I believe its intended target
will ONLY be people using only Big5. That means, if it exists, the
chance of showing it to other-language-users probably be extremely
nil, Think about this: there are still a whole lot of people who don't
know English at all. If no such a 'Big5-specific' programming
tool around, their chances of learning programming is completely
rid off.

--
~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
Runsun Pan, PhD
[EMAIL PROTECTED]
Nat'l Center for Macromolecular Imaging
http://ncmi.bcm.tmc.edu/ncmi/
~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~*~
-- 
http://mail.python.org/mailman/listinfo/python-list


writing large files quickly

2006-01-27 Thread rbt
I've been doing some file system benchmarking. In the process, I need to 
create a large file to copy around to various drives. I'm creating the 
file like this:

fd = file('large_file.bin', 'wb')
for x in xrange(40960):
 fd.write('0')
fd.close()

This takes a few minutes to do. How can I speed up the process?

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


Re: writing large files quickly

2006-01-27 Thread superfun
One way to speed this up is to write larger strings:

fd = file('large_file.bin', 'wb')
for x in xrange(5120):
 fd.write('')
fd.close()

However, I bet within an hour or so you will have a much better answer
or 10. =)

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


How do I dynamically create functions without lambda?

2006-01-27 Thread Russell
I want my code to be Python 3000 compliant, and hear
that lambda is being eliminated. The problem is that I
want to partially bind an existing function with a value
"foo" that isn't known until run-time:

   someobject.newfunc = lambda x: f(foo, x)

The reason a nested function doesn't work for this is
that it is, well, dynamic. I don't know how many times
or with what foo's this will be done.

Now, I am sure there are a half-dozen ways to do this.
I just want the one, new and shiny, Pythonic way. ;-)

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


Re: writing large files quickly

2006-01-27 Thread casevh

rbt wrote:
> I've been doing some file system benchmarking. In the process, I need to
> create a large file to copy around to various drives. I'm creating the
> file like this:
>
> fd = file('large_file.bin', 'wb')
> for x in xrange(40960):
>  fd.write('0')
> fd.close()
>
> This takes a few minutes to do. How can I speed up the process?
>
> Thanks!

Untested, but this should be faster.

block = '0' * 409600
fd = file('large_file.bin', 'wb')
for x in range(1000):
 fd.write('0')
fd.close()

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


Re: writing large files quickly

2006-01-27 Thread Tim Chase
> Untested, but this should be faster.
> 
> block = '0' * 409600
> fd = file('large_file.bin', 'wb')
> for x in range(1000):
>  fd.write('0')
> fd.close()

Just checking...you mean

fd.write(block)

right? :)  Otherwise, you end up with just 1000 "0" characters in 
your file :)

Is there anything preventing one from just doing the following?

fd.write("0" * 40960)

It's one huge string for a very short time.  It skips all the 
looping and allows Python to pump the file out to the disk as 
fast as the OS can handle it. (and sorta as fast as Python can 
generate this humongous string)

-tkc





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


Re: How do I dynamically create functions without lambda?

2006-01-27 Thread Robert Kern
Russell wrote:
> I want my code to be Python 3000 compliant, and hear
> that lambda is being eliminated. The problem is that I
> want to partially bind an existing function with a value
> "foo" that isn't known until run-time:
> 
>someobject.newfunc = lambda x: f(foo, x)
> 
> The reason a nested function doesn't work for this is
> that it is, well, dynamic. I don't know how many times
> or with what foo's this will be done.
> 
> Now, I am sure there are a half-dozen ways to do this.
> I just want the one, new and shiny, Pythonic way. ;-)

It doesn't exist, yet. Python 3000 isn't even in planning stages, yet. There are
just some loose ideas floating around about what will (and won't!) be in it.

You can't write Python 3000 compliant code right now because there is nothing to
comply with.

-- 
Robert Kern
[EMAIL PROTECTED]

"In the fields of hell where the grass grows high
 Are the graves of dreams allowed to die."
  -- Richard Harter

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


Re: writing large files quickly

2006-01-27 Thread Paul Rubin
Tim Chase <[EMAIL PROTECTED]> writes:
> Is there anything preventing one from just doing the following?
>   fd.write("0" * 40960)
> It's one huge string for a very short time.  It skips all the looping
> and allows Python to pump the file out to the disk as fast as the OS
> can handle it. (and sorta as fast as Python can generate this
> humongous string)

That's large enough that it might exceed your PC's memory and cause
swapping.  Try strings of about 64k (65536).
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: writing large files quickly

2006-01-27 Thread Grant Edwards
On 2006-01-27, rbt <[EMAIL PROTECTED]> wrote:

> I've been doing some file system benchmarking. In the process, I need to 
> create a large file to copy around to various drives. I'm creating the 
> file like this:
>
> fd = file('large_file.bin', 'wb')
> for x in xrange(40960):
>  fd.write('0')
> fd.close()
>
> This takes a few minutes to do. How can I speed up the process?

Don't write so much data.

f = file('large_file.bin','wb')
f.seek(40960-1)
f.write('\x00')
f.close()

That should be almost instantaneous in that the time required
for those 4 lines of code is neglgible compared to interpreter
startup and shutdown.

-- 
Grant Edwards   grante Yow!  These PRESERVES
  at   should be FORCE-FED to
   visi.comPENTAGON OFFICIALS!!
-- 
http://mail.python.org/mailman/listinfo/python-list


  1   2   >