Re: closures and dynamic binding

2008-09-28 Thread Aaron "Castironpi" Brady
On Sep 28, 1:14 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote:
> > To me, this is a somewhat unintuitive behavior.  I want to discuss the
> > parts of it I don't understand.
>
>  f= [ None ]* 10
>  for n in range( 10 ):
> > ...     f[ n ]= lambda: n
> > ...
>  f[0]()
> > 9
>  f[1]()
> > 9
>
> `n` is looked up at the time ``f[0]`` is called.  At that time it is
> bound to 9.
>
>  f= [ None ]* 10
>  for n in range( 10 ):
> > ...     f[ n ]= (lambda n: ( lambda: n ) )( n ) ...
>  f[0]()
> > 0
>  f[1]()
> > 1
>
> > Which is of course the desired effect.  Why doesn't the second one just
> > look up what 'n' is when I call f[0], and return 9?
>
> It *does* look up `n` at the time you call ``f[0]`` but this time it's
> the local `n` of the outer ``lambda`` function and that is bound to
> whatever the function was called with.  At the time it was called the
> global `n` was bound to 0.  Maybe it get's more clear if you don't name
> it `n`:
>
> In [167]: f = [None] * 10
>
> In [168]: for n in xrange(10):
>    .:     f[n] = (lambda x: lambda: x)(n)
>    .:
>
> In [169]: f[0]()
> Out[169]: 0
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Hi Marc,

It's my understanding that 'n' gets a new value every time through the
loop.  n= 0 on the first pass, n= 1 on the second pass, and so on.  n=
9 by the end, and that's why `lambda: n` always returns 9.  It queries
the variable 'n', and finds 9.  (This got lengthy.  I started thinking
aloud.)

In your version of the indirect example, it queries the variable 'x',
which it finds in a new distinct scope in each f element.  In f[0], x=
0.  In f[1], x= 1.  There are 10 different 'x' variables throughout
the contents of f.  The direct example does not do this allocation of
ten different 'x's.

It's sort of helping.  I think I feel like the following is more like
what I'm looking for:

(Non-standard)
>>> f= [ None ]* 10
>>> for n in range( 10 ):
... f[ n ]= n
...
>>> f[0]
 9
>>> f[1]
 9

because when you access f[0], it looks up the variable 'n'.  Obviously
not.

(Unproduced)
>>> f= [ None ]* 10
>>> for n in range( 10 ):
... f[ n ]= late( n ) #late/lazy
...
>>> f[0]
 9
>>> f[1]
 9

>>> f= [ None ]* 10
>>> for n in range( 10 ):
... f[ n ]= early( n ) #early/eager
...
>>> f[0]
 0
>>> f[1]
 1

For the functions, I want a function that returns 'n', either late or
early.

(Unproduced)
>>> for n in range( 10 ):
... f[ n ]= lambda: late( n )
>>> f[0]()
9
>>> for n in range( 10 ):
... f[ n ]= lambda: early( n )
>>> f[0]()
0

I don't think you could pull this off.  'late' and 'early' succeed
with quotes around n, early('n') and late('n'), in the direct
assignments, but the functions aren't so lucky.  'n' has gone on to a
better world by the time 'early' gets any control.

This might have some success.

(Unproduced)
>>> for n in range( 10 ):
... f[ n ]= late( lambda: n )
>>> f[0]()
9
>>> for n in range( 10 ):
... f[ n ]= early( lambda: n )
>>> f[0]()
0

Though it's beyond my foresight to tell if it's feasible as stated, if
you need quotes, how much introspection you would need, etc.  Plus,
'late' and 'early' were accepting quoted parameters earlier.  How
would they look inside a function?  Could a simple decorator provide
the service?

On a tangent about mutables, it's not that numbers, strings, and
tuples are 'immutable' per se, it's just that they don't have any
methods which mutate them (or assignable properties).  Lists and
dictionaries do.  It's up to the user whether a custom class does.
--
http://mail.python.org/mailman/listinfo/python-list


Re: design pattern: MVC in python

2008-09-28 Thread 甜瓜
Really helpful!

2008/9/28 Mikolai Fajer <[EMAIL PROTECTED]>:
> The following link directly discusses using MVC and pygame.
>
> http://ezide.com/games/writing-games.html
>
> --
>
> -Mikolai Fajer-
> --
> http://mail.python.org/mailman/listinfo/python-list
>
--
http://mail.python.org/mailman/listinfo/python-list


Re: What do you call a class not intended to be instantiated

2008-09-28 Thread Terry Reedy

Steven D'Aprano wrote:


And modules aren't callable. I've often thought they should be.


Modules are not callable because their class, module, has no __call__ 
instance method.  But (in 3.0, which is all I will check) you can 
subclass module and add one.


>>> m = type(__builtins__)
>>> m

>>> dir(m)
['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', 
'__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', 
'__init__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', 
'__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', 
'__subclasshook__']

>>> class m2(m):
def __call__(self, *args, **kwds):
print(self, args, kwds)


>>> mod = m2('mod') # only arg required by module.__init__
>>> mod(1,2,3,a=4,b=5)
 (1, 2, 3) {'a': 4, 'b': 5}
>>> mod # did not override __repr__


So, roll your own to your taste.

Terry Jan Reedy

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


Re: closures and dynamic binding

2008-09-28 Thread Terry Reedy

Aaron "Castironpi" Brady wrote:

Hello all,

To me, this is a somewhat unintuitive behavior.  I want to discuss the
parts of it I don't understand.


f= [ None ]* 10
for n in range( 10 ):

... f[ n ]= lambda: n


This is equivalent to

for n in range(10):
  def g(): return n
  f[n] = g

which is equivalent to

def g(): return n
f = [g]*10
n = 9


f[0]()

9

f[1]()

9


which make this not so surprising as the original lambda version is to 
some people.



I guess I can accept this part so far, though it took a little getting
used to.  I'm writing some code and found the following workaround,
but I don't think it should give different results.  Maybe I'm not
understanding some of the details of closures.


f= [ None ]* 10
for n in range( 10 ):

... f[ n ]= (lambda n: ( lambda: n ) )( n )


This is equivalent to

for n in range(10):
  def g(n):
def h:
  return n
return h
  f[n] = g(n)

Now, to avoid the needless confusion of 'n's, g is equivalent to

def g(x):
  def h:
return x
  return h

(One could do the same change in the lambdas, too, of course).
so that g(n)() == n, with n stored in each closure h...


...

f[0]()

0

f[1]()

1


to be regurgitated when each is called.

Terry Jan Reedy

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


Re: closures and dynamic binding

2008-09-28 Thread Steven D'Aprano
On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote:

> Hello all,
> 
> To me, this is a somewhat unintuitive behavior.  I want to discuss the
> parts of it I don't understand.
> 
 f= [ None ]* 10
 for n in range( 10 ):
> ... f[ n ]= lambda: n
> ...
 f[0]()
> 9
 f[1]()
> 9
> 
> I guess I can accept this part so far, though it took a little getting
> used to.  I'm writing some code and found the following workaround, but
> I don't think it should give different results.  Maybe I'm not
> understanding some of the details of closures.
> 
 f= [ None ]* 10
 for n in range( 10 ):
> ... f[ n ]= (lambda n: ( lambda: n ) )( n )
> ...
 f[0]()
> 0
 f[1]()
> 1
> 
> Which is of course the desired effect.  Why doesn't the second one just
> look up what 'n' is when I call f[0], and return 9?

That's an awfully complicated solution. A much easier way to get the 
result you are after is to give each function its own local copy of n:

f[n] = lambda n=n: n

As for why the complicated version works, it may be clearer if you expand 
it from a one-liner:

# expand: f[ n ]= (lambda n: ( lambda: n ) )( n )

inner = lambda: n
outer = lambda n: inner
f[n] = outer(n)

outer(0) => inner with a local scope of n=0
outer(1) => inner with a local scope of n=1 etc.

Then, later, when you call inner() it grabs the local scope and returns 
the number you expected.


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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Terry Reedy
est wrote:
>>From python manual
> 
> str( [object])
> 
> Return a string containing a nicely printable representation of an
> object. For strings, this returns the string itself. The difference
> with repr(object) is that str(object) does not always attempt to
> return a string that is acceptable to eval(); its goal is to return a
> printable string. If no argument is given, returns the empty string,
> ''.
> 
> 
> now we try this under windows:
> 
 str(u'\ue863')
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
> position 0
> : ordinal not in range(128)

In 3.0 this is fixed:
>>> str('\ue863') # u prefix is gone
'\ue863'
>>> str(b'123') # b prefix is added
"b'123'"

Problems like this at least partly motivated the change to unicode
instead of bytes as the string type.

tjr

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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Steven D'Aprano
On Sun, 28 Sep 2008 19:03:42 +1300, Lawrence D'Oliveiro wrote:

> In message
> <[EMAIL PROTECTED]>, est
> wrote:
> 
>> The problem is, why the f**k set ASCII encoding to range(128) 
> 
> Because that's how ASCII is defined.
> 
>> while str() is internally byte array it should be handled in range(256)
>> !!
> 
> But that's for random bytes. How would you convert an arbitrary object
> to random bytes?

from random import randint
''.join(chr(randint(0, 255)) for i in xrange(len(input)))

of course. How else should you get random bytes? :)



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


Re: What do you call a class not intended to be instantiated

2008-09-28 Thread Ben Finney
Terry Reedy <[EMAIL PROTECTED]> writes:

> Steven D'Aprano wrote:
> 
> > And modules aren't callable. I've often thought they should be.
> 
> Modules are not callable because their class, module, has no
> __call__ instance method. But (in 3.0, which is all I will check)
> you can subclass module and add one.

Works fine in Python 2.5.2 also::

Python 2.5.2 (r252:60911, Aug  8 2008, 11:09:00)
[GCC 4.3.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> module = type(__builtins__)
>>> module

>>> '__call__' in dir(module)
False

>>> import sys
>>> class CallableModule(module):
... def __call__(self, *args, **kwargs):
... sys.stdout.write("%(self)r, %(args)r, %(kwargs)r\n" % vars())
...
>>> '__call__' in dir(CallableModule)
True
>>> foo = CallableModule('foo')
>>> foo(1, 2, 3, a=4, b=5)
, (1, 2, 3), {'a': 4, 'b': 5}
>>> foo


-- 
 \“There are only two ways to live your life. One is as though |
  `\  nothing is a miracle. The other is as if everything is.” |
_o__) —Albert Einstein |
Ben Finney
--
http://mail.python.org/mailman/listinfo/python-list

The sale of world famous jacket,Jean-COOGI/DG/ginoshoes on

2008-09-28 Thread The best online shopping site!(www.wholenikee.cn)
shoes on
AIR Jordan 1  (paypal payment)(www.wholejean.cn )
AIR Jordan 2
AIR Jordan 3
AIR Jordan 4
AIR Jordan 5 (paypal payment)(www.wholejean.cn )
AIR Jordan 6 Rings
AIR Jordan 6
AIR Jordan 7
AIR Jordan 8
AIR Jordan 9 (paypal payment)(www.wholejean.cn )
AIR Jordan 10
AIR Jordan 11
AIR Jordan 12
AIR Jordan 13 (paypal payment)(www.wholejean.cn )
AIR Jordan 14
AIR Jordan 15
AIR Jordan 16
AIR Jordan 17
AIR Jordan 18
AIR Jordan 19
AIR Jordan 20 (paypal payment)(www.wholejean.cn )
AIR Jordan 21
AIR Jordan 22
AIR Jordan 23 (paypal payment)(www.wholejean.cn )
AIR Jordan 3.5
AIR AIR Jordan 4.5
AIR Jordan 7.5
AIR Jordan 9.5
AIR Jordan 12.5 (paypal payment)(www.wholejean.cn )
AIR Jordan 15.5
AIR Jordan 19.5
AIR Jordan 21.5
AIR Jordan Large Size Jordan
AIR Jordan  Size 14 Jordan
AIR Jordan Size 15 shoes
AIR Jordan DMP
Nike air force one, air force 1, air force one low cut, air force one
high cut, air force one release date
Air force one, air foce one 25TH, af 1, af 1 25TH, Nike air force one
new releases, limited version
Air Force One (paypal payment)(www.wholejean.cn )
Air Force one 25TH
AF 1
AF 1 25TH (paypal payment)(www.wholejean.cn )
Dunk sb nike sb dunk nike dunk sb dunk sb high  dunk sb low  dunk sb
woman
Nike sb dunk Nike Dunk High SB nike dunk low premuim sb Nike SB Dunk
High Shimizu
Nike SB Dunk Pro Nike SB Dunk Dunk SB
Nike Dunk shoes
Dunk shoes for woman (paypal payment)(www.wholejean.cn )
Dunk low cut
Dunk high cut

AIR Jordans Fusion 1 Jordan 2 Fusion AIR Jordan 3 Nike Jordan Fusion
4
Jordan 5 shoes Nike Air Jordan 6 VI Force 1 Jordan Fusion AJF 6 AJF6
AJ6F Jordan 6 Rings Jordan 6 fusion (paypal payment)
(www.www.wholejean.cn )


AIR Jordan Fusions 13 NIKE Jordan Fusion 14 AIR Jordans 15Nike Jordan
16 Fusion Jordan 17 shoes Nike Air Jordans 18 XVIII  Force 1 Jordan
Fusion AJF18 AJF18 AJ18F Jordan 18 fusions
(paypal payment)(www.wholejean.cn )


AIR Jordan Fusions 7 NIKE Jordan Fusion 8 AIR Jordans 9 Nikes Jordan
Fusion 10 Jordan 11 shoes Nike Air Jordan 12 XII  Force 1 Jordan
Fusion AJF 12 AJF12 AJ12F Jordans 12 fusions
(paypal payment)(www.wholejean.cn )


NIKE AIR JORDAN FORCE FUSION SHOES AJF 5 V JORDANs 5 FUSION NIKE
JORDAN 5 FUSION SHOES AJF5 Nike Air Jordan XXIII 23 Force 1 Jordan
Fusion AJF 23 AJF23 AJ23F
(paypal payment)(www.wholejean.cn)


Nike Jordans Fusion 23 AIR Jordan 22 Jordan Fusions 21 AIR Jordans
Fusion 20 Jordan 19 shoes Air Jordan Force Fusion VIII (8), AJF 8
Nike (paypal payment)(www.wholejean.cn )
Air Jordan 17 XVII  Force 1 Jordan Fusions AJF 17 AJF17 AJ17F Jordan
our website : www.wholejean.cn


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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Steven D'Aprano
On Sun, 28 Sep 2008 03:55:46 -0400, Terry Reedy wrote:

> est wrote:
>>>From python manual
>> 
>> str( [object])
>> 
>> Return a string containing a nicely printable representation of an
>> object. For strings, this returns the string itself. The difference
>> with repr(object) is that str(object) does not always attempt to return
>> a string that is acceptable to eval(); its goal is to return a
>> printable string. If no argument is given, returns the empty string,
>> ''.
>> 
>> 
>> now we try this under windows:
>> 
> str(u'\ue863')
>> Traceback (most recent call last):
>>   File "", line 1, in 
>> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
>> position 0
>> : ordinal not in range(128)
> 
> In 3.0 this is fixed:
 str('\ue863') # u prefix is gone
> '\ue863'
 str(b'123') # b prefix is added
> "b'123'"
> 
> Problems like this at least partly motivated the change to unicode
> instead of bytes as the string type.


I'm not sure that "fixed" is the right word. Isn't that more or less the 
same as telling the OP to use unicode() instead of str()? It merely 
avoids the problem of converting Unicode to ASCII by leaving your string 
as Unicode, rather than fixing it. Perhaps that's the right thing to do, 
but it's a bit like the old joke:

"Doctor, it hurts when I do this."
"Then don't do it!"



As for the second example you give:

>>> str(b'123') # b prefix is added
"b'123'"


Perhaps I'm misinterpreting it, but from here it looks to me that str() 
is doing what repr() used to do, and I'm really not sure that's a good 
thing. I would have expected that str(b'123') in Python 3 should do the 
same thing as unicode('123') does now:

>>> unicode('123')
u'123'

(except without the u prefix).


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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread est
> Because that's how ASCII is defined.
> Because that's how ASCII is defined.  ASCII is a 7-bit code.

Then why can't python use another default encoding internally
range(256)?

> Python refuses to guess and tries the lowest common denominator -- ASCII -- 
> instead.

That's the problem. ASCII is INCOMPLETE!

If Python choose another default encoding which handles range(256),
80% of python unicode encoding problems are gone.

It's not HARD to process unicode, it's just python & python community
refuse to correct it.

> stop dreaming of a magic solution

It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console,
what's wrong

> Isn't that more or less the same as telling the OP to use unicode() instead 
> of str()?

sockets could handle str() only. If you throw unicode objects to a
socket, it will automatically call str() and cause an error.
--
http://mail.python.org/mailman/listinfo/python-list


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Steven D'Aprano
On Sat, 27 Sep 2008 22:37:09 -0700, est wrote:

 str(u'\ue863')
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
> position 0
> : ordinal not in range(128)
> 
> FAIL.

What result did you expect?


[...]
> The problem is, why the f**k set ASCII encoding to range(128) 
> while str() is internally byte array it should be handled in range(256)
> !!


To quote Terry Pratchett:

"What sort of person," said Salzella patiently, "sits down and
*writes* a maniacal laugh? And all those exclamation marks, you
notice? Five? A sure sign of someone who wears his underpants
on his head." -- (Terry Pratchett, Maskerade)



In any case, even if the ASCII encoding used all 256 possible bytes, you 
still have a problem. Your unicode string is a single character with 
ordinal value 59491:

>>> ord(u'\ue863')
59491

You can't fit 59491 (or more) characters into 256, so obviously some 
unicode chars aren't going to fit into ASCII without some sort of 
encoding. You show that yourself:

u'\ue863'.encode('mbcs')  # Windows only

But of course 'mbcs' is only one possible encoding. There are others. 
Python refuses to guess which encoding you want. Here's another:

u'\ue863'.encode('utf-8')




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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread est
On Sep 28, 4:38 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 27 Sep 2008 22:37:09 -0700, est wrote:
>  str(u'\ue863')
> > Traceback (most recent call last):
> >   File "", line 1, in 
> > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
> > position 0
> > : ordinal not in range(128)
>
> > FAIL.
>
> What result did you expect?
>
> [...]
>
> > The problem is, why the f**k set ASCII encoding to range(128) 
> > while str() is internally byte array it should be handled in range(256)
> > !!
>
> To quote Terry Pratchett:
>
>     "What sort of person," said Salzella patiently, "sits down and
>     *writes* a maniacal laugh? And all those exclamation marks, you
>     notice? Five? A sure sign of someone who wears his underpants
>     on his head." -- (Terry Pratchett, Maskerade)
>
> In any case, even if the ASCII encoding used all 256 possible bytes, you
> still have a problem. Your unicode string is a single character with
> ordinal value 59491:
>
> >>> ord(u'\ue863')
>
> 59491
>
> You can't fit 59491 (or more) characters into 256, so obviously some
> unicode chars aren't going to fit into ASCII without some sort of
> encoding. You show that yourself:
>
> u'\ue863'.encode('mbcs')  # Windows only
>
> But of course 'mbcs' is only one possible encoding. There are others.
> Python refuses to guess which encoding you want. Here's another:
>
> u'\ue863'.encode('utf-8')
>
> --
> Steven

OK, I am tired of arguing these things since python 3.0 fixed it
somehow.

Can anyone tell me how to customize a default encoding, let's say
'ansi' which handles range(256) ?
--
http://mail.python.org/mailman/listinfo/python-list


Calculating timespan

2008-09-28 Thread Erhard
I've been looking at the date/time classes and I'm at a loss as to how 
to do this (probably too used to other platforms).


I have two date/time values. One represents 'now' and the other the last 
modified time of a file on disk (from stat). I need to calculate the 
difference in time (i.e., a 'timespan') between the two so I can tell if 
the file has been modified in the past X minutes and do something to it.


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


Re: Borg vs Singleton vs OddClass

2008-09-28 Thread Carl Banks
On Sep 27, 2:12 pm, Lie <[EMAIL PROTECTED]> wrote:
> I'm thinking about this design pattern (I don't know if anyone has
> ever thought of this pattern before):
>
> class OddClass(object):
>     def __init__(self):
>         global OddClass
>         OddClass = self
>     def __call__():
>         return self
>
> The OddClass is a class that would overwrite its own class definition
> at its first instantiation. OddClass defines __call__ so that
> subsequent "instantiation" (technically it is no more an
> instantiation, but Duck Typing says it does) of the class would return
> the single instance.
>
> It do have a problem though, that you can't do isinstance(a, OddClass)
> since the name OddClass no longer refers to the OddClass class
> descriptor, but to an instance of OddClass.

I recommend against your idiom above.  The main issue I have about it
is that it rebinds the symbol implicitly, which is almost always a bad
idea.  What if a user does something like "from oddclassmodule import
OddClass"?  Then the user will get a new instance every call since it
never rebinds the imported symbol.

Just don't do it this way.

You could rewrite it like this to avoid the implicit rebinding, and to
take care of the isinstance issue as well:

class NotSoOddClass(object):
def __new__(cls):
self = getattr(cls,"_instance",None)
if self is None:
 self = cls._instance = object.__new__(cls)
return self


Or you could just use a lazy factory function like this, where the
user is only supposed to use Factory and not create the class
directly:

class _NotOddClass(object):
# nothing odd

def Factory():
obj = getattr(_NotOddClass,"_instance",None)
if obj is None:
obj = _NotOddClass._instance = NotOddClass()
return obj


If you're real kinky you can use a metaclass.  There are reasons to
prefer any of these.  I'd recommend the factory function unless you
think the users could significantly benefit from type inspection.

Just don't do it by rebinding the class name.  That's not nice.


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


Re: Calculating timespan

2008-09-28 Thread marek . rocki
Erhard napisał(a):
> I've been looking at the date/time classes and I'm at a loss as to how
> to do this (probably too used to other platforms).
>
> I have two date/time values. One represents 'now' and the other the last
> modified time of a file on disk (from stat). I need to calculate the
> difference in time (i.e., a 'timespan') between the two so I can tell if
> the file has been modified in the past X minutes and do something to it.
>
> Thanks =)

You can subtract one datetime object from another:

from datetime import datetime, timedelta
span = datetime.now() -
datetime(year=2008,month=8,day=27,hour=12,minute=34,second=56)
if span < timedelta(minutes=37):
# do something
--
http://mail.python.org/mailman/listinfo/python-list


Re: Calculating timespan

2008-09-28 Thread Erhard

[EMAIL PROTECTED] wrote:

from datetime import datetime, timedelta
span = datetime.now() -
datetime(year=2008,month=8,day=27,hour=12,minute=34,second=56)
if span < timedelta(minutes=37):
# do something


timedelta! Yes, it's obvious that's what I was looking for. I was stuck 
with 'timespan' in my head and couldn't find anything like it in the docs.


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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Lie
On Sep 28, 12:37 pm, est <[EMAIL PROTECTED]> wrote:
> From python manual
>
> str( [object])
>
> Return a string containing a nicely printable representation of an
> object. For strings, this returns the string itself. The difference
> with repr(object) is that str(object) does not always attempt to
> return a string that is acceptable to eval(); its goal is to return a
> printable string. If no argument is given, returns the empty string,
> ''.
>
> now we try this under windows:
>
> >>> str(u'\ue863')
>
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
> position 0
> : ordinal not in range(128)
>
> FAIL.

And it is correct to fail, ASCII is only defined within range(128),
the rest (i.e. range(128, 256)) is not defined in ASCII. The
range(128, 256) are extension slots, with many conflicting meanings.

>
> also almighty Linux
>
> Python 2.3.4 (#1, Feb  6 2006, 10:38:46)
> [GCC 3.4.5 20051201 (Red Hat 3.4.5-2)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> str(u'\ue863')
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
> position 0: ordinal not in range(128)
>
> Python 2.4.4 (#2, Apr  5 2007, 20:11:18)
> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> str(u'\ue863')
>
> Traceback (most recent call last):
>   File "", line 1, in ?
> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
> position 0: ordinal not in range(128)
>
> Python 2.5 (release25-maint, Jul 20 2008, 20:47:25)
> [GCC 4.1.2 20061115 (prerelease) (Debian 4.1.1-21)] on linux2
> Type "help", "copyright", "credits" or "license" for more information.>>> 
> str(u'\ue863')
>
> Traceback (most recent call last):
>   File "", line 1, in 
> UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
> position 0: ordinal not in range(128)

If that str() function has returned anything but error on this, I'd
file a bug report.

> The problem is, why the f**k set ASCII encoding to range(128) 
> while str() is internally byte array it should be handled in
> range(256) !!

string is a byte array, but unicode and ASCII is NOT. Unicode string
is a character array defined up to range(65535). Each character in
unicode may be one or two bytes long. ASCII string is a character
array defined up to range(127). Other than Unicode (actually utf-8,
utf-16, and utf-32) and ASCII, there are many other encodings (ECBDIC,
iso-8859-1', ..., 'iso-8859-16', 'KOI8', 'GB18030', 'Shift-JIS', etc,
etc, etc) each with conflicting byte to characters mappings.
Fortunately, most of these encodings do share a common ground: ASCII.

Actually, when a strictly stupid str() receives a Unicode string (i.e.
character array), it should return a , but it doesn't, str() is smarter than that, it
tries to convert whatever fits into ASCII, i.e. characters lower than
128. Why ASCII? Because character from range(128, 256) varies widely
and it doesn't know which encoding you want to use, so if you don't
tell me what encoding to use it'd not guess (Python Zen: In the face
of ambiguity, refuse the temptation to guess).

If you're trying to convert a character array (Unicode) into a byte
string, it's done by specifying which codec you want to use. str()
tries to convert your character array (Unicode) to byte string using
ASCII codec. s.encode(codec) would convert a given character array
into byte string using codec.

> http://bugs.python.org/issue3648
>
> One possible solution(Windows Only)
>
> >>> str(u'\ue863'.encode('mbcs'))
> '\xfe\x9f'

actually str() is not needed, you need only: u'\ue863'.encode('mbcs')

> >>> print u'\ue863'.encode('mbcs')
> 䶮
>
> I now spending 60% of my developing time dealing with ASCII range(128)
> errors. It was PAIN!!

Despair not, there is a quick hack:
# but only use it as temporary solution, FIX YOUR CODE PROPERLY
str_ = str
str = lambda s = '': s.encode('mbcs') if isinstance(s, basestring)
else str_(s)

> Please fix this issue.
>
> http://bugs.python.org/issue3648
>
> Please.

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

Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Marc 'BlackJack' Rintsch
On Sun, 28 Sep 2008 01:35:11 -0700, est wrote:

>> Because that's how ASCII is defined.
>> Because that's how ASCII is defined.  ASCII is a 7-bit code.
> 
> Then why can't python use another default encoding internally
> range(256)?

Because that doesn't suffice.  Unicode code points can be >255.

> If Python choose another default encoding which handles range(256), 80%
> of python unicode encoding problems are gone.

80% of *your* problems with it *seems* to be gone then.

> It's not HARD to process unicode, it's just python & python community
> refuse to correct it.

It is somewhat hard to deal with unicode because many don't want to think 
about it or don't grasp the relationship between encodings, byte values, 
and characters.  Including you.

>> stop dreaming of a magic solution
> 
> It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, what's
> wrong

What do you mean by "just print 0x7F to 0xFF"?  For example if I have ``s 
= u'Smørebrød™'`` what bytes should ``str(s)`` produce and why those and 
not others?

>> Isn't that more or less the same as telling the OP to use unicode()
>> instead of str()?
> 
> sockets could handle str() only. If you throw unicode objects to a
> socket, it will automatically call str() and cause an error.

Because *you* have to tell explicitly how the unicode object should be 
encoded as bytes.  Python can't do this automatically because it has *no 
idea* what the process at the other end of the socket expects.

Now you are complaining that Python chooses ASCII.  If it is changed to 
something else, like MBCS, others start complaining why it is MBCS and 
not something different.  See: No fix, just moving the problem to someone 
else.

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

Re: is decorator the right thing to use?

2008-09-28 Thread George Sakkis
On Sep 27, 11:38 pm, "Dmitry S. Makovey" <[EMAIL PROTECTED]> wrote:
> George Sakkis wrote:
> > It's funny how often you come with a better solution a few moments
> > after htting send! The snippet above can (ab)use the decorator syntax
> > so that it becomes:
>
> > class A(Proxy):
>
> >     @ProxyMethod
> >     def bmethod(self):
> >         return self.b1
>
> >     @ProxyMethod
> >     def bmethod2(self):
> >         return self.b2
>
> That is outstanding!

FYI, in case you missed it the final version doesn't need a Proxy base
class, just inherit from object. Also lowercased ProxyMethod to look
similar to staticmethod/classmethod:

class A(object):

def __init__(self, b1, b2):
self.b1 = b1
self.b2 = b2

@proxymethod
def bmethod(self):
return self.b1

@proxymethod
def bmethod2(self):
return self.b2

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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Olivier Lauzanne
On Sep 28, 11:21 am, est <[EMAIL PROTECTED]> wrote:
> On Sep 28, 4:38 pm, Steven D'Aprano <[EMAIL PROTECTED]
> Can anyone tell me how to customize a default encoding, let's say
> 'ansi' which handles range(256) ?

I assume you are using python2.5
Edit the file /usr/lib/python2.5/site.py

There is a method called
def setencoding():
[...]
encoding = "ascii"
[...]

Change "encoding = "ascii" to encoding = "utf-8"

On windows you may have to use "mbsc" or something like that. I have
no idea what windows use at its encoding.

As long as all systems don't use the same encoding (let's say utf-8
since it is becoming the standard on unixes and on the web) using
ascii as a default encoding makes sense.

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


Re: how to replace and string in a "SELECT ... IN ()"

2008-09-28 Thread Tino Wildenhain

Michael Mabin wrote:

I'm exhausted, so I'll just shut up about this after a few final words.


Thank you for your time :-)
1.  "edits" is used in data warehousing to describe data scrubbing or 
filtering of fields in records that are used as input sources for 
loading into data warehouses. It's a term that goes way back to batch 
processing on the mainframe, so it's been used this way for a long time. 
Sometimes we use 'validation' interchangeably with 'edit' but our use of 
validation usually involves a check of input data against business rules 
and not type or range checking which we consider 'edits'.  So maybe 
you're not used to hearing the term used this way, but it is a variation 
perhaps of what you're used to.


And so on and so on in the regular top posting manner...

Just to give you some thoughts again: your solution might be valid for
you in your controlled environment. Yet you just presented it to the
OP without telling him the limits of when this can be used. And this
is outright dangerous. If one sees this without comment and without your
background she will run into problems sooner or later. So my suggestion
was to either don't tell people such solutions at all or tell them
exactly under which circumstances they might be used.

Still I think nailing the problem at the apropriate place is a habit
which should generally devloped - as in your example an additional
int() would have fixed it - but still it would not work if you
want to deal with arbitrary strings. So its good to make suggestions
but pretty please think ahead how someone would use it instead of
investing all your energy into defending dangerous programming practice.

With "we in python" I referred to a fairly amount of literature about
programming in python and it design patterns. Nothing me personally.

Ah and some final words to the controlleness of datawarehouse
applications and similar things: by the time you are designing such
a solutuion you will never know what future applications will be
developed around it so its always best to be prepared.

"Data scrubbing" seems a common idea but in fact its very hard to do
it right due to the nature of different systems using different
quoting logic. "Dont trust your input" is a habit not only applicable
to web programming - in fact the company I work for does not do much
web application but input validation is something we get even audited
for.

Nevertheless I wish you a very good weekend :-)

Tino



smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Lie
On Sep 28, 4:21 pm, est <[EMAIL PROTECTED]> wrote:
> On Sep 28, 4:38 pm, Steven D'Aprano <[EMAIL PROTECTED]
>
>
>
> cybersource.com.au> wrote:
> > On Sat, 27 Sep 2008 22:37:09 -0700, est wrote:
> >  str(u'\ue863')
> > > Traceback (most recent call last):
> > >   File "", line 1, in 
> > > UnicodeEncodeError: 'ascii' codec can't encode character u'\ue863' in
> > > position 0
> > > : ordinal not in range(128)
>
> > > FAIL.
>
> > What result did you expect?
>
> > [...]
>
> > > The problem is, why the f**k set ASCII encoding to range(128) 
> > > while str() is internally byte array it should be handled in range(256)
> > > !!
>
> > To quote Terry Pratchett:
>
> >     "What sort of person," said Salzella patiently, "sits down and
> >     *writes* a maniacal laugh? And all those exclamation marks, you
> >     notice? Five? A sure sign of someone who wears his underpants
> >     on his head." -- (Terry Pratchett, Maskerade)
>
> > In any case, even if the ASCII encoding used all 256 possible bytes, you
> > still have a problem. Your unicode string is a single character with
> > ordinal value 59491:
>
> > >>> ord(u'\ue863')
>
> > 59491
>
> > You can't fit 59491 (or more) characters into 256, so obviously some
> > unicode chars aren't going to fit into ASCII without some sort of
> > encoding. You show that yourself:
>
> > u'\ue863'.encode('mbcs')  # Windows only
>
> > But of course 'mbcs' is only one possible encoding. There are others.
> > Python refuses to guess which encoding you want. Here's another:
>
> > u'\ue863'.encode('utf-8')
>
> > --
> > Steven
>
> OK, I am tired of arguing these things since python 3.0 fixed it
> somehow.

I'm against calling python 3.0 fixed it, python 3.0's default encoding
is utf-8/Unicode, and that is why your problem magically disappears.

> Can anyone tell me how to customize a default encoding, let's say
> 'ansi' which handles range(256) ?

Python used to have sys.setdefaultencoding, but that feature was an
accident. sys.setdefaultencoding was intended to be used for testing
purpose when the developers haven't decided what to use as default
encoding (what use is default when you can change it).
sys.setdefaultencoding has been removed, programmers should encode
characters manually if they want to use something other than the
default encoding (ASCII).
--
http://mail.python.org/mailman/listinfo/python-list


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread est
On Sep 28, 6:15 pm, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Sun, 28 Sep 2008 01:35:11 -0700, est wrote:
> >> Because that's how ASCII is defined.
> >> Because that's how ASCII is defined.  ASCII is a 7-bit code.
>
> > Then why can't python use another default encoding internally
> > range(256)?
>
> Because that doesn't suffice.  Unicode code points can be >255.
>
> > If Python choose another default encoding which handles range(256), 80%
> > of python unicode encoding problems are gone.
>
> 80% of *your* problems with it *seems* to be gone then.
>
> > It's not HARD to process unicode, it's just python & python community
> > refuse to correct it.
>
> It is somewhat hard to deal with unicode because many don't want to think
> about it or don't grasp the relationship between encodings, byte values,
> and characters.  Including you.
>
> >> stop dreaming of a magic solution
>
> > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console, what's
> > wrong
>
> What do you mean by "just print 0x7F to 0xFF"?  For example if I have ``s
> = u'Smørebrød™'`` what bytes should ``str(s)`` produce and why those and
> not others?
>
> >> Isn't that more or less the same as telling the OP to use unicode()
> >> instead of str()?
>
> > sockets could handle str() only. If you throw unicode objects to a
> > socket, it will automatically call str() and cause an error.
>
> Because *you* have to tell explicitly how the unicode object should be
> encoded as bytes.  Python can't do this automatically because it has *no
> idea* what the process at the other end of the socket expects.
>
> Now you are complaining that Python chooses ASCII.  If it is changed to
> something else, like MBCS, others start complaining why it is MBCS and
> not something different.  See: No fix, just moving the problem to someone
> else.
>
> Ciao,
>         Marc 'BlackJack' Rintsch

Well, you succeseded in putting all blame to myself alone. Great.

When you guy's are dealing with CJK characters in the future, you'll
find out what I mean.

In fact Boa Constructor keeps prompting ASCII and range(128) error on
my Windows. That's pretty cool.
--
http://mail.python.org/mailman/listinfo/python-list


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Lie
On Sep 28, 3:35 pm, est <[EMAIL PROTECTED]> wrote:
> > Because that's how ASCII is defined.
> > Because that's how ASCII is defined.  ASCII is a 7-bit code.
>
> Then why can't python use another default encoding internally
> range(256)?
>
> > Python refuses to guess and tries the lowest common denominator -- ASCII -- 
> > instead.
>
> That's the problem. ASCII is INCOMPLETE!

What do you propose? Use mbsc and smack out linux computers? Use KOI
and make non-Russians suicide? Use GB and shot dead non-Chinese? Use
latin-1 and make emails servers scream?

> If Python choose another default encoding which handles range(256),
> 80% of python unicode encoding problems are gone.
>
> It's not HARD to process unicode, it's just python & python community
> refuse to correct it.

Python's unicode support is already correct. Only your brainwave have
not been tuned to it yet.

> > stop dreaming of a magic solution
>
> It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console,
> what's wrong
>
> > Isn't that more or less the same as telling the OP to use unicode() instead 
> > of str()?
>
> sockets could handle str() only. If you throw unicode objects to a
> socket, it will automatically call str() and cause an error.

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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread est
On Sep 28, 7:12 pm, Lie <[EMAIL PROTECTED]> wrote:
> On Sep 28, 3:35 pm, est <[EMAIL PROTECTED]> wrote:
>
> > > Because that's how ASCII is defined.
> > > Because that's how ASCII is defined.  ASCII is a 7-bit code.
>
> > Then why can't python use another default encoding internally
> > range(256)?
>
> > > Python refuses to guess and tries the lowest common denominator -- ASCII 
> > > -- instead.
>
> > That's the problem. ASCII is INCOMPLETE!
>
> What do you propose? Use mbsc and smack out linux computers? Use KOI
> and make non-Russians suicide? Use GB and shot dead non-Chinese? Use
> latin-1 and make emails servers scream?
>
> > If Python choose another default encoding which handles range(256),
> > 80% of python unicode encoding problems are gone.
>
> > It's not HARD to process unicode, it's just python & python community
> > refuse to correct it.
>
> Python's unicode support is already correct. Only your brainwave have
> not been tuned to it yet.
>
> > > stop dreaming of a magic solution
>
> > It's not 'magic' it's a BUG. Just print 0x7F to 0xFF to console,
> > what's wrong
>
> > > Isn't that more or less the same as telling the OP to use unicode() 
> > > instead of str()?
>
> > sockets could handle str() only. If you throw unicode objects to a
> > socket, it will automatically call str() and cause an error.

Have you ever programmed with CJK characters before?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Borg vs Singleton vs OddClass

2008-09-28 Thread Lie
On Sep 28, 7:22 am, Miles <[EMAIL PROTECTED]> wrote:
> Lie wrote:
> > This is probably unrelated to Python, as this is more about design
> > pattern. I'm asking your comments about this design pattern that is
> > similar in functionality to Singleton and Borg: to share states.
>
> > I'm thinking about this design pattern (I don't know if anyone has
> > ever thought of this pattern before):
>
> > class OddClass(object):
> >    def __init__(self):
> >        global OddClass
> >        OddClass = self
> >    def __call__():
>
> I'll change this to def __call__(self):
>
> >        return self
>
> > The OddClass is a class that would overwrite its own class definition
> > at its first instantiation. OddClass defines __call__ so that
> > subsequent "instantiation" (technically it is no more an
> > instantiation, but Duck Typing says it does) of the class would return
> > the single instance.
>
> This seems like a terrible idea to me, but then I never really
> understood the appeal of the Singleton pattern, especially in Python.
>
> > Singleton and OddClass is inheritable.
>
>  class OddClass(object): ...
>  s = OddClass()
>  class A(OddClass): pass
>
> Traceback (most recent call last):
>   File "", line 1, in 
> TypeError: Error when calling the metaclass bases
>     __init__() takes exactly 1 argument (4 given)
>
> Oops!  And assuming you carefully ordered your code so that OddClass
> will never be instantiated before it is subclassed (which seems
> fragile), you get behavior like this:

I test the code what would happen if I do this before posting the
pattern:
>>> class OddClass(object): ...
>>> s = OddClass()
>>> class A(OddClass): pass
>>> a = A()

It doesn't give me errors, where are you having the problem?

> >>> s = OddClass()
> >>> s is OddClass()
> True
> >>> a = A()
> >>> s is OddClass()
> False
> >>> a is OddClass()
> True
> >>> a is A()
> False
> >>> a is OddClass()
>
> False

Well, spotted, there is identity problem with this pattern.

> -Miles

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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Christian Heimes

Steven D'Aprano wrote:

str(b'123') # b prefix is added

"b'123'"


Perhaps I'm misinterpreting it, but from here it looks to me that str() 
is doing what repr() used to do, and I'm really not sure that's a good 
thing. I would have expected that str(b'123') in Python 3 should do the 
same thing as unicode('123') does now:


No, you are getting it right and yes, it's problematic. Guido wanted 
str(b'') to succeed. But the behavior can easily mask bugs in code. 
Therefor a byte warning mode was implemented.



$ ./python -b
>>> str(b'123')
__main__:1: BytesWarning: str() on a bytes instance
"b'123'"

$ ./python -bb
>>> str(b'123')
Traceback (most recent call last):
  File "", line 1, in 
BytesWarning: str() on a bytes instance
>>> b'' == ''
Traceback (most recent call last):
  File "", line 1, in 
BytesWarning: Comparison between bytes and string

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


Re: Borg vs Singleton vs OddClass

2008-09-28 Thread Lie
On Sep 28, 9:45 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 27 Sep 2008 11:12:00 -0700, Lie wrote:
> > This is probably unrelated to Python, as this is more about design
> > pattern. I'm asking your comments about this design pattern that is
> > similar in functionality to Singleton and Borg: to share states.
>
> > I'm thinking about this design pattern (I don't know if anyone has ever
> > thought of this pattern before):
>
> > class OddClass(object):
> >     def __init__(self):
> >         global OddClass
> >         OddClass = self
> >     def __call__():
> >         return self
>
> I don't think that pattern works as you give it. I suggest you read the
> thread "What do you call a class not intended to be instantiated",
> started by me on the 21st of September, which covers a similar pattern.

In fact, that thread inspired this thread.

> I'm afraid it's a rather long thread, with a lot of people
> misunderstanding what I was asking, but still worth reading. If you only
> have time to read one post, I suggest you read my reply to Ben Finney,
> posted yesterday.

... before I decided probably this pattern is probably isn't the
answer to that thread.

> My own feeling is that both your OddClass and my class without instances
> are probably solutions looking for a problem. Well, actually, no, that's
> too strong: I think the concept of "Class Singleton" is a perfectly valid
> solution to certain problems, but it competes with more well-known
> solutions like modules and Borg (in Python) and Singletons (the hammer
> available in Java and C++). As for which is better, that's partly a
> matter of personal taste and partly a matter of familiarity.
>
> > It do have a problem though, that you can't do isinstance(a, OddClass)
>
> But you can say "a is OddClass", which is more appropriate for a
> Singleton.
>
> > The problem with Borg is that it is not inheritable (in certain
> > sense[1]) and only work with old-style class (which is due to be
> > completely removed on py3k)[2]
>
> No, there is a new-style Borg. Read the comments 
> here:http://code.activestate.com/recipes/66531/
>
> The new-style Borg is hardly more complicated than old-style: 6 lines
> versus 4.

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


Mechanize and Yahoo HTTPS

2008-09-28 Thread Jett
Has anybody used the mechanize library with a Yahoo site?  I am trying
to create a program that will download my player's stats from Yahoo's
Fantasy Football site but for some reason could not get it to load the
login page.

When I run the program below, it prints the word "start" and then does
nothing (no exceptions are thrown).

 code snippet start 
import re
from mechanize import Browser

print 'start'

br = Browser()

response1 = br.open("https://login.yahoo.com/config/login?.done=http://
sports.yahoo.com/fantasy&.src=spt")
print br.title()

print "end"
 code snippet end 

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


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Roy Smith
In article <[EMAIL PROTECTED]>,
 Steven D'Aprano <[EMAIL PROTECTED]> wrote:

> from random import randint
> ''.join(chr(randint(0, 255)) for i in xrange(len(input)))
> 
> 
> of course. How else should you get random bytes? :)

That a UUOL (Useless Usage Of Len; by analogy to UUOC).  This works just as 
well:

''.join(chr(randint(0, 255)) for i in input)
--
http://mail.python.org/mailman/listinfo/python-list


Selective importing and package dependencies

2008-09-28 Thread David Pratt
Hi. I am in the midst of preparing a package to convert between  
various schemas including orms. The issue is I don't want django,  
slqalchemy, storm, rdflib etc. as hard dependencies of the package.  
Each module is a schema to schema conversion. As an example, I have  
imports for sqlalchemy with classes and methods that use them.


from sqlalchemy.util import OrderedDict
from sqlalchemy import types as rdbtype
import sqlalchemy as sa

I have my own ideas about how I might do this but looking for  
recommendations from others how they would handle this so the result  
would be:


1. no hard dependencies on any of these other packages
2. load the module without failure.
3. import the dependent package if available to perform the conversion

Many thanks
David
--
http://mail.python.org/mailman/listinfo/python-list


Music knowledge representation

2008-09-28 Thread Mr.SpOOn
Hi,
I'm working on an application to analyse music (melodies, chord sequences etc.)

I need classes to represent different musical entities. I'm using a
class Note to represent all the notes. Inside it stores the name of
the natural version of the note (C, D, E, F...) and an integer to
calculate the accidentals.

Then I have a class Pitch, to represent the different 12 pitch
classes, because different notes, such as C# and Db, belong to the
same pitch class.

In these classes I also have some arithmetic method to perform
additions or subtractions between pitches and integers.

I also need to represent intervals between notes. An interval must
have a degree (first, second, third), that may be represented with a
simple integer and a size counted in semitones. Then, with these
informations it can retrieve its name, for example: perfect fifth.

The degree is calculated between natural notes. So the degree of
Interval(C, E) is "third", or 3. This may be simple, if I put the
notes in an ordered sequence. But, when I have to calculate, for
example Interval(E, C). It should count till the end of the sequence,
so if I have:

C D E F G A B

after the B it should continue with C. I'm not sure how to implement
this. Is there a suitable data structure for this purpose?
--
http://mail.python.org/mailman/listinfo/python-list


******GOD OF GIFTS 4 U*********

2008-09-28 Thread enteringheaven
GOD OF GIFTS Free Animations + Wallpapers
+ Adsens Tips + Hand Reflexogy + Games
+ Audio + Videos + Nature Health Tips
And  Beautiful Pics..
http://www.godofgifts.blogspot.com/

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


Unable to write % character to a file using writelines() method

2008-09-28 Thread dudeja . rajat
Hi,


I'm using the writelines() method to write some lines to a text file. But
I'm unable to write the % character to the file using the following format:

fdTolFile.writelines("\n\tdiff Not in %s '%' range" %(toleranceInPer))


The second % does not get write to the file and Im getting errors. Please
suggest what additional information should I give to write the % character.


The errro Im getting is :
 File "C:\Documents and
Settings\\TA-workspace\src\TestAndCompareResults.py", line 840, in
__parseDiffTextFile
fdTolFile.writelines("\n\tdiff in %s'%' range" %(toleranceInPer))
TypeError: not enough arguments for format string


I've also tried this:

fdTolFile.writelines("\n\tdiff Not in %s \% range" %(toleranceInPer))

But still I get the same error


Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list

Tkinter: scrollbar - unable to scroll the scrollbar if I click on arrow buttons of scroll bars

2008-09-28 Thread dudeja . rajat
Hi,


Im using a tkinter scrollbars for horinzontal and vertical scrolling. Well
the problem is I'm unable to scroll if I click on the arrows buttons of
scrollbars ( with both types of scrollbars)


Please suggest if I m missing some configuration.


My code is as below:

self.hsb = Scrollbar(appGuiFrame, orient = HORIZONTAL)
self.hsb.grid(row = 2,column = 0, sticky = E+W)
#vertical scroll bar
self.vsb = Scrollbar(appGuiFrame)
self.vsb.grid(row = 1,column = 2, sticky = N+S)



self.txtLogger = Text(appGuiFrame, \
 height = 20,\
 width = 100, \
 state = DISABLED, \
 xscrollcommand = self.hsb.set, \
 yscrollcommand = self.vsb.set, \
 wrap = NONE, \
 font = ("courier",12))
 self.hsb.config(command = self.txtLogger.xview())
 self.vsb.config(command = self.txtLogger.yview())


Please help.


Thanks and regards,
Rajat
--
http://mail.python.org/mailman/listinfo/python-list

Re: Python style: exceptions vs. sys.exit()

2008-09-28 Thread Lie
On Sep 25, 3:05 pm, Bruno Desthuilliers  wrote:
> Steven D'Aprano a écrit :
>
> > On Wed, 24 Sep 2008 17:11:28 -0400, Ross Ridge wrote:
>
> >> Plenty of people were quick to say that the exception should be passed
> >> through to the caller.  No one said this behaviour should be documented.
> >>  There may be little practical difference bewteen calling sys.exit()
> >> after printing an error and progating an exception if no one using the
> >> library knows that it could generate that exception in those
> >> circumstances.
>
> > That's true, I didn't explicitly say that the library should be
> > documented. Nor did I say that it shouldn't be riddled with bugs. There's
> > little practical difference between a buggy library and one that raises
> > unexpected (i.e. undocumented) exceptions either.
>
> Also note that there are quite a couples cases where the library authors
> themselves cannot predict which exception types may be raised - as soon
> as the library functions expect callback functions, file-like or
> dict-like or whatever-like objects etc, it's the caller's responsability
> to handle the exceptions that may be raised by what *he* passes to the
> library...

No, the library author can always predict which exception his library
may raise. If a callback function, file-like, dict-like, etc raises an
exception, it is not his libraries' exception anymore and is not his
responsibility. In that case we should refer to the documentation for
the callback/etc/etc instead of the documentation for the library.
--
http://mail.python.org/mailman/listinfo/python-list


destructor not called

2008-09-28 Thread Marcin201
I have a class which uses a temporary directory for storing data.  I
would like that directory to be removed when the class is no longer
used.  I have tried removing the temporary directory from the class
destructor, however, it was never called.  After I while I traced the
problem to the class having a reference to it's own function.  Here is
a simplified model.

test.py
class Foo:
def __init__(self):
print "Hello"
self.f = self.fxn

def __del__(self):
print "Bye"

def fxn(self):
print "function"

a = Foo()

running python test.py I get
Hello

Is this an expected behavior or a bug in python?  If this is expected
any suggestions for working around this.  I would like to avoid having
to call the destructor explicitly.

Thanks,

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


Re: Unable to write % character to a file using writelines() method

2008-09-28 Thread Christian Heimes

[EMAIL PROTECTED] wrote:

Hi,


I'm using the writelines() method to write some lines to a text file. But
I'm unable to write the % character to the file using the following format:

fdTolFile.writelines("\n\tdiff Not in %s '%' range" %(toleranceInPer))


Try %%  :)

Christian

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


Re: destructor not called

2008-09-28 Thread Szabolcs Ferenczi
On Sep 28, 6:00 pm, Marcin201 <[EMAIL PROTECTED]> wrote:
> I have a class which uses a temporary directory for storing data.  I
> would like that directory to be removed when the class is no longer
> used.  I have tried removing the temporary directory from the class
> destructor, however, it was never called.

The RAII (Resource Acquisition Is Initialization) pattern is not
applicable to Python since the language concept is not suitable for
it. The __del__ is not a genuine destructor. In your case it might not
be performed when you expected it because there were still references
left around to the object. You must take care to break those
references.

However, you can apply the EAM (Execute Around Method) pattern in
Python to achieve the same effect. You can apply the EAM pattern with
help of the `with' statement:

with Foo() as a:
# work with `a'

In this case you must implement methods __enter__ and __exit__ instead
of __init__ and __del__. The method __enter__ must return an instance
of Foo.

You can achieve the same effect with try-finally block as well:

a = Foo()
try:
# work with `a'
finally:
# make `a' remove directories

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


Re: destructor not called

2008-09-28 Thread Roy Smith
In article 
<[EMAIL PROTECTED]>,
 Marcin201 <[EMAIL PROTECTED]> wrote:

> I have a class which uses a temporary directory for storing data.  I
> would like that directory to be removed when the class is no longer
> used.  I have tried removing the temporary directory from the class
> destructor, however, it was never called.

The short answer is that destruction in Python is non-deterministic (a rude 
shock if you're used to C++).  What you probably want is the new "with" 
statement (http://docs.python.org/ref/with.html).
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unable to write % character to a file using writelines() method

2008-09-28 Thread dudeja . rajat
On Sun, Sep 28, 2008 at 5:51 PM, Christian Heimes <[EMAIL PROTECTED]> wrote:

> [EMAIL PROTECTED] wrote:
>
>> Hi,
>>
>>
>> I'm using the writelines() method to write some lines to a text file. But
>> I'm unable to write the % character to the file using the following
>> format:
>>
>> fdTolFile.writelines("\n\tdiff Not in %s '%' range" %(toleranceInPer))
>>
>
> Try %%  :)
>
> Christian
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


Thanks Garry & Christian.

It worked.

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

Re: destructor not called

2008-09-28 Thread Michel Leunen

Marcin201 a écrit :


class Foo:
def __init__(self):
print "Hello"
self.f = self.fxn


Maybe self.f = self.fxn() is what you want. Note the '()'.

--
Michel Leunen
http://linux.leunen.com
--
http://mail.python.org/mailman/listinfo/python-list


Python 3.0 and repr

2008-09-28 Thread Mark Tolonen
I don't understand the behavior of the interpreter in Python 3.0.  I am 
working at a command prompt in Windows (US English), which has a terminal 
encoding of cp437.


In Python 2.5:

   Python 2.5 (r25:51908, Sep 19 2006, 09:52:17) [MSC v.1310 32 bit 
(Intel)] on win

   32
   Type "help", "copyright", "credits" or "license" for more information.
   >>> x=u'\u5000'
   >>> x
   u'\u5000'

In Python 3.0:

   Python 3.0rc1 (r30rc1:66507, Sep 18 2008, 14:47:08) [MSC v.1500 32 bit 
(Intel)]

   on win32
   Type "help", "copyright", "credits" or "license" for more information.
   >>> x='\u5000'
   >>> x
   Traceback (most recent call last):
 File "", line 1, in 
 File "c:\dev\python30\lib\io.py", line 1486, in write
   b = encoder.encode(s)
 File "c:\dev\python30\lib\encodings\cp437.py", line 19, in encode
   return codecs.charmap_encode(input,self.errors,encoding_map)[0]
   UnicodeEncodeError: 'charmap' codec can't encode character '\u5000' in 
position

   1: character maps to 

Where I would have expected

   >>> x
   '\u5000'

Shouldn't a repr() of x work regardless of output encoding?  Another test:

   Python 3.0rc1 (r30rc1:66507, Sep 18 2008, 14:47:08) [MSC v.1500 32 bit 
(Intel)]

   on win32
   Type "help", "copyright", "credits" or "license" for more information.
   >>> bytes(range(256)).decode('cp437')
   
'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14\
   x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f 
!"#$%&\'()*+,-./0123456789:;<=>[EMAIL PROTECTED]

   
DEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\x7fÇüéâäàåçêëèïîìÄÅ
   
ÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀
   αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■\xa0'
   >>> bytes(range(256)).decode('cp437')[255]
   '\xa0'

Characters that cannot be displayed in cp437 are being escaped, such as 
0x00-0x1F, 0x7F, and 0xA0.  Even if I incorrectly decode a value, if the 
character exists in cp437, it is displayed:


   >>> bytes(range(256)).decode('latin-1')[255]
   'ÿ'

However, for a character that isn't supported by cp437, incorrectly decoded:

   >>> bytes(range(256)).decode('cp437')[254]
   '■'
   >>> bytes(range(256)).decode('latin-1')[254]
   Traceback (most recent call last):
 File "", line 1, in 
 File "c:\dev\python30\lib\io.py", line 1486, in write
   b = encoder.encode(s)
 File "c:\dev\python30\lib\encodings\cp437.py", line 19, in encode
   return codecs.charmap_encode(input,self.errors,encoding_map)[0]
   UnicodeEncodeError: 'charmap' codec can't encode character '\xfe' in 
position 1:

character maps to 

Why not display '\xfe' here?  It seems like this inconsistency would make it 
difficult to write things like doctests that weren't dependent on the 
tester's terminal.  It also makes it difficult to inspect variables without 
hex(ord(n)) on a character-by-character basis.  Maybe repr() should always 
display the ASCII representation with escapes for all other characters, 
especially considering the "repr() should produce output suitable for eval() 
when possible" rule.


What are others' opinions?  Any insight to this design decision?

-Mark


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

parsing a site/page that uses/calls javascript functions...

2008-09-28 Thread bruce
Hi...

I've got a couple of test apps that I use to parse/test different html
webpages. However, I'm now looking at how to parse a given site/page that
uses javascript calls to dynamically create/display the resulting HTML.

I can see the HTML is the Browser page if I manually select the btn that
invokes the javascript function, but I have no idea how to create an app
that can effectively parse the page.

My test apps use python, along with mechanize/browser/urllib. I've seen
sites/docs that discuss selenium, spidermonkey, etc... If possible, I'm
trying to find a complete example (that walks through how to setup the
environment, to how to finally extract the DOM elements of a given
javascript page), or I'm looking to find someone I can work with, to create
a complete example that can then be posted to the 'net.

I'd really rather have a headless browser solution, as my overall goal is to
run a parsing/crawling over a number of pages that utilize javascript..

Pointers, thoughts, comments, etc will be greatly appreciated.


Thanks!!!

-bruce

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


urllib2 and exceptions

2008-09-28 Thread robean
Hi everyone,

I have a question about using urllib2.

I like urllib2 better than urllib at least in part because it has more
elaborate support for handling errors: there is built in support for
URLError (for faulty urls) and HTTPError (for http errors that might
originate from, say, passing an invalid stock-ticker in the program
below).  However I can get neither to work.  I'm attaching below the
(very short) code: can anyone point out what I'm doing wrong?

Now, if I replace the URLError and HTTPError with IOError (the class
from which both URLError and HTTPError inherit), the program works
fine. Why is it that I can call the generic IOError class, but none of
the Error classes derived from that? These are clearly defined in the
urllib2 manual. Very confused...

Here's the code:


import urllib2

# read stock information from yahoo finance for Traget (TGT)
goodTicker = 'TGT' # program works with this
badTicker = 'TGTttt' # python doesn't understand either HTTPError
or URLError with this

url = "http://ichart.finance.yahoo.com/table.csv?s="; + badTicker

try:
handle = urllib2.urlopen(url)

# this does not work
except HTTPError, e:
print "There was an http error"
print e

# this also does not work
except URLError, e:
print "There is a problem with the URL"
print e
exit(1)

#this works
except IOError, e:
print "You have an IOError"
print e

text = handle.readlines()[:20]
for line in text:
print line

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


Re: destructor not called

2008-09-28 Thread George Sakkis
On Sep 28, 12:00 pm, Marcin201 <[EMAIL PROTECTED]> wrote:

> I have a class which uses a temporary directory for storing data.  I
> would like that directory to be removed when the class is no longer
> used.  I have tried removing the temporary directory from the class
> destructor, however, it was never called.  After I while I traced the
> problem to the class having a reference to it's own function.  Here is
> a simplified model.
>
> test.py
> class Foo:
>     def __init__(self):
>         print "Hello"
>         self.f = self.fxn
>
>     def __del__(self):
>         print "Bye"
>
>     def fxn(self):
>         print "function"
>
> a = Foo()
>
> running python test.py I get
> Hello
>
> Is this an expected behavior or a bug in python?  If this is expected
> any suggestions for working around this.  I would like to avoid having
> to call the destructor explicitly.

Others have already replied to your main question; in short you
shouldn't rely on __del__ being called. Regardless, is there a (good)
reason for having an instance reference to the method ? Without
further information, that seems like a code smell.

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


What is not objects in Python?

2008-09-28 Thread process
I have heard some criticism about Python, that it is not fully object-
oriented.

What is not an object in Python?

Why isn't len implemented as a str.len and list.len method instead of
a len(list) function?
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is not objects in Python?

2008-09-28 Thread Christian Heimes

process wrote:

What is not an object in Python?


Everything that is not part of Python's syntax is an object, including 
all string and number types, classes, metaclasses, functions, models, 
code and more. It's technically not possible to have something like e.g. 
an int that isn't an object.



Why isn't len implemented as a str.len and list.len method instead of
a len(list) function?


Because readability is more important than purity. By the way len(egg) 
is just syntactic sugar for egg.__len__() with some extra checks.


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


Re: What is not objects in Python?

2008-09-28 Thread Tino Wildenhain

Hi,

process wrote:

I have heard some criticism about Python, that it is not fully object-
oriented.


Don't listen to the voices... ;)


What is not an object in Python?



Why isn't len implemented as a str.len and list.len method instead of
a len(list) function?


So you also want to write 1+2 in the form of 1.add(2) ?
(Yes, in python you can do that, as well as "hello".__len__() works
 even (1).__add__(2) works.)
Maybe its just that python don't want to waste good names for methods :-)

So as said above in some other thread, python supports OO but does not
force to write OO.

Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: closures and dynamic binding

2008-09-28 Thread Aaron "Castironpi" Brady
On Sep 28, 2:52 am, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> On Sat, 27 Sep 2008 21:43:15 -0700, Aaron \"Castironpi\" Brady wrote:
> > Hello all,
>
> > To me, this is a somewhat unintuitive behavior.  I want to discuss the
> > parts of it I don't understand.
>
>  f= [ None ]* 10
>  for n in range( 10 ):
> > ...     f[ n ]= lambda: n
> > ...
>  f[0]()
> > 9
>  f[1]()
> > 9
>
> > I guess I can accept this part so far, though it took a little getting
> > used to.  I'm writing some code and found the following workaround, but
> > I don't think it should give different results.  Maybe I'm not
> > understanding some of the details of closures.
>
>  f= [ None ]* 10
>  for n in range( 10 ):
> > ...     f[ n ]= (lambda n: ( lambda: n ) )( n )
> > ...
>  f[0]()
> > 0
>  f[1]()
> > 1
>
> > Which is of course the desired effect.  Why doesn't the second one just
> > look up what 'n' is when I call f[0], and return 9?
>
> That's an awfully complicated solution. A much easier way to get the
> result you are after is to give each function its own local copy of n:
>
> f[n] = lambda n=n: n
>
> As for why the complicated version works, it may be clearer if you expand
> it from a one-liner:
>
> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n )
>
> inner = lambda: n
> outer = lambda n: inner
> f[n] = outer(n)
>
> outer(0) => inner with a local scope of n=0
> outer(1) => inner with a local scope of n=1 etc.
>
> Then, later, when you call inner() it grabs the local scope and returns
> the number you expected.
>
> --
> Steven

Steven,

I must have misunderstood.  Here's my run of your code:

>>> inner = lambda: n
>>> outer = lambda n: inner
>>> outer(0)
 at 0x00A01170>
>>> a=outer(0)
>>> b=outer(1)
>>> a()
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: global name 'n' is not defined

Why doesn't 'inner' know it's been used in two different scopes, and
look up 'n' based on the one it's in?
--
http://mail.python.org/mailman/listinfo/python-list


Re: Music knowledge representation

2008-09-28 Thread Aaron "Castironpi" Brady
On Sep 28, 9:37 am, Mr.SpOOn <[EMAIL PROTECTED]> wrote:
> Hi,
> I'm working on an application to analyse music (melodies, chord sequences 
> etc.)
>
> I need classes to represent different musical entities. I'm using a
> class Note to represent all the notes. Inside it stores the name of
> the natural version of the note (C, D, E, F...) and an integer to
> calculate the accidentals.
>
> Then I have a class Pitch, to represent the different 12 pitch
> classes, because different notes, such as C# and Db, belong to the
> same pitch class.
>
> In these classes I also have some arithmetic method to perform
> additions or subtractions between pitches and integers.
>
> I also need to represent intervals between notes. An interval must
> have a degree (first, second, third), that may be represented with a
> simple integer and a size counted in semitones. Then, with these
> informations it can retrieve its name, for example: perfect fifth.
>
> The degree is calculated between natural notes. So the degree of
> Interval(C, E) is "third", or 3. This may be simple, if I put the
> notes in an ordered sequence. But, when I have to calculate, for
> example Interval(E, C). It should count till the end of the sequence,
> so if I have:
>
> C D E F G A B
>
> after the B it should continue with C. I'm not sure how to implement
> this. Is there a suitable data structure for this purpose?

Hi,

Here is a link to someone else's design they asked about on the
newsgroup a couple weeks ago.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc
--
http://mail.python.org/mailman/listinfo/python-list


Re: How to read a jpg bytearray from a Flash AS3 file

2008-09-28 Thread rsgalloway

Thanks! I'm using form = cgi.FieldStorage(). When I print out the
contents of form, I get this:

FieldStorage(None, None, '\xff\xd8\xff\xe0\x00\x10JFIF
\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb
\x00\x84\x00\x05\x03\x04\x04\x04\x03\x05\x04\x04\x04\x05\x05\x05\x06\x07\x0c
\x08\x07\x07\x07\x07\x0f\x0b\x0b\t\x0c\x11\x0f\x12\x12\x11\x0f
\x11\x11\x13\x16\x1c\x17\x13\x14\x1a\x15\x11\x11\x18!\x18\x1a\x1d\x1d
\x1f\x1f\x1f\x13\x17"$"\x1e$\x1c\x1e\x1f\x1e
\x01\x05\x05\x05\x07\x06\x07\x0e\x08\x08\x0e\x1e\x14\x11\x14\x1e\x1e
\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e
\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e
\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\x1e\xff\.

Which is obviously the binary data of the image I want. How do I
access this data? I'm used to getting it like this:

name = form['name'].value

But I don't think this will work in this case. TIA.


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


Re: Music knowledge representation

2008-09-28 Thread Mr.SpOOn
On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady
<[EMAIL PROTECTED]> wrote:

> Here is a link to someone else's design they asked about on the
> newsgroup a couple weeks ago.
>
> http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc

:D
It's always me.

I think my question is more specific. I need some sort of cycle.

So if I have a list with A, B, C, D, when I iter over it I need to get
an A after the D.
--
http://mail.python.org/mailman/listinfo/python-list


ANN: wxPython 2.8.9.0

2008-09-28 Thread Robin Dunn


Announcing
--

The 2.8.9.0 release of wxPython is now available for download at
http://wxpython.org/download.php.  This release adds support for using
Cairo for drawing on wx windows, adds a Win64 build, and various other
fixes and enhancements.

Source code is available, as well as binaries for Python 2.3, 2.4 and
2.5, for Windows and Mac, as well some packages for various Linux
distributions.  A summary of changes is listed below and also at
http://wxpython.org/recentchanges.php.



What is wxPython?
-

wxPython is a GUI toolkit for the Python programming language. It
allows Python programmers to create programs with a robust, highly
functional graphical user interface, simply and easily. It is
implemented as a Python extension module that wraps the GUI components
of the popular wxWidgets cross platform library, which is written in
C++.

wxPython is a cross-platform toolkit. This means that the same program
will usually run on multiple platforms without modifications.
Currently supported platforms are 32-bit and 64-bit Microsoft Windows,
most Linux or other Unix-like systems using GTK2, and Mac OS X 10.4+.
In most cases the native widgets are used on each platform to provide
a 100% native look and feel for the application.


Changes in 2.8.9.0
--

Many minor bug fixes throughout wxWidgets and wxPython.

Fixed wx.lib.embeddedimage to work with Python 2.3.

Fixed PseudoDC hit testing when pure white or pure black are used.

Added support for a 64-bit Windows build for the AMD64 architecture,
(a.k.a. x64.)  This is for Python 2.5 only and is available only as a
Unicode build.

Added the wx.EmptyBitmapRGBA factory function.

Added the wx.lib.wxcairo module which allows the pycairo package to be
used for drawing on wx window or memory DCs.  In addition it is able
to convert from a native wx.Font to a cairo.FontFace, and it also
provides functions for converting to/from wx.Bitmap and
cairo.ImageSurface objects.  In order to use this module you will need
to have the Cairo library and its dependencies installed, as well as
the pycairo Python package.  For Linux and other unix-like systems you
most likely have what you need installed already, or can easily do so
from your package manager application.  See the wx.lib.wxcairo
module's docstring for notes on where to get what you need for Windows
or Mac.  This module uses ctypes, and depending on platform it may
need to find and load additional dynamic libraries at runtime in
addition to cairo.  The pycairo package used needs to be new enough to
export the CAPI structure in the package namespace.  I believe that
started sometime in the 1.4.x release series.

Added the wx.lib.graphics module, which is an implementation of the
wx.GraphicsContext API using Cairo (via wx.lib.wxcairo).  This allows
us to be totally consistent across platforms, and also use Cairo to
implement some things that are missing from the GraphicsContext API.
It's not 100% compatible with the GraphicsContext API, but probably
close enough to be able to share code between them if desired, plus it
can do a few things more.

Updated wx.Bitmap.CopyFromBuffer to be a bit more flexible. You can
now specify the format of the buffer, and the CopyFromBufferRGBA is
now just a wrapper around CopyFromBuffer that specifies a different
format than the default.  Also added the complement method,
CopyToBuffer.  See the docstring for CopyFromBuffer for details on the
currently allowed buffer formats.  The existing wx.BitmapFromBuffer
factory functions are also now implemented using the same underlying
code as CopyFromBuffer.

Add wx.lib.mixins.listctrl.ListRowHighlighter for automatic highlighting
of rows in a wx.ListCtrl.

--
Robin Dunn
Software Craftsman
http://wxPython.org  Java give you jitters?  Relax with wxPython!

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


Re: What is not objects in Python?

2008-09-28 Thread Lie
On Sep 29, 1:29 am, process <[EMAIL PROTECTED]> wrote:
> I have heard some criticism about Python, that it is not fully object-
> oriented.
>
> What is not an object in Python?
>
> Why isn't len implemented as a str.len and list.len method instead of
> a len(list) function?

A question like this is often answered by another (rhetorical)
question: "What is Object Oriented actually?"

The answer to that is generally: "Python is not Java."
--
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 and exceptions

2008-09-28 Thread Chris Rebert
On Sun, Sep 28, 2008 at 11:03 AM, robean <[EMAIL PROTECTED]> wrote:
> Hi everyone,
>
> I have a question about using urllib2.
>
> I like urllib2 better than urllib at least in part because it has more
> elaborate support for handling errors: there is built in support for
> URLError (for faulty urls) and HTTPError (for http errors that might
> originate from, say, passing an invalid stock-ticker in the program
> below).  However I can get neither to work.  I'm attaching below the
> (very short) code: can anyone point out what I'm doing wrong?
>
> Now, if I replace the URLError and HTTPError with IOError (the class
> from which both URLError and HTTPError inherit), the program works
> fine. Why is it that I can call the generic IOError class, but none of
> the Error classes derived from that? These are clearly defined in the
> urllib2 manual. Very confused...
>
> Here's the code:
>
>
> import urllib2
>
> # read stock information from yahoo finance for Traget (TGT)
> goodTicker = 'TGT' # program works with this
> badTicker = 'TGTttt' # python doesn't understand either HTTPError
> or URLError with this
>
> url = "http://ichart.finance.yahoo.com/table.csv?s="; + badTicker
>
> try:
>handle = urllib2.urlopen(url)
>
> # this does not work
> except HTTPError, e:
>print "There was an http error"
>print e
>
> # this also does not work
> except URLError, e:
>print "There is a problem with the URL"
>print e
>exit(1)
>
> #this works
> except IOError, e:
>print "You have an IOError"
>print e
>
> text = handle.readlines()[:20]
> for line in text:
>print line
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>

My Python begs to differ:

#tmp.py
import urllib2

badTicker = 'TGTttt'
url = "http://ichart.finance.yahoo.com/table.csv?s="; + badTicker

try:
handle = urllib2.urlopen(url)

except urllib2.HTTPError, e:
print "There was an http error"
print e

except urllib2.URLError, e:
print "There is a problem with the URL"
print e

except urllib2.IOError, e:
print "You have an IOError"
print e

#in the shell
$ python -V
Python 2.5.1
$ python Desktop/tmp.py
There was an http error
HTTP Error 404: Not Found

Are you using an outdated version of Python perhaps?

Regards,
Chris

-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to replace and string in a "SELECT ... IN ()"

2008-09-28 Thread Michael Mabin
Tino, dude, I'm afraid I lied about my previous post being the last word.
 There are some things you said here that must be addressed.

On Sun, Sep 28, 2008 at 6:00 AM, Tino Wildenhain <[EMAIL PROTECTED]> wrote:

> Michael Mabin wrote:
>
>> I'm exhausted, so I'll just shut up about this after a few final words.
>>
>
> Thank you for your time :-)
>
>> 1.  "edits" is used in data warehousing to describe data scrubbing or
>> filtering of fields in records that are used as input sources for loading
>> into data warehouses. It's a term that goes way back to batch processing on
>> the mainframe, so it's been used this way for a long time. Sometimes we use
>> 'validation' interchangeably with 'edit' but our use of validation usually
>> involves a check of input data against business rules and not type or range
>> checking which we consider 'edits'.  So maybe you're not used to hearing the
>> term used this way, but it is a variation perhaps of what you're used to.
>>
>
> And so on and so on in the regular top posting manner


I thought I was clearing up your statement that "there is no such thing as
edits" and then you went on  about not knowing what I meant by "edits" .
 Why do you dismiss my effort to clarify a point you were clearly wrong
about?

...
>
> Just to give you some thoughts again: your solution might be valid for
> you in your controlled environment. Yet you just presented it to the
> OP without telling him the limits of when this can be used. And this
> is outright dangerous. If one sees this without comment and without your
> background she will run into problems sooner or later. So my suggestion
> was to either don't tell people such solutions at all or tell them
> exactly under which circumstances they might be used.
>

Outright dangerous?  Again, you're assuming the OP's problem involved user
input from a web-page.  I was addressing the stated requirement of the
problem.  You can't automatically assume that this problem is related to
input from a web-page.  Why should I code in a manner that I will never
encounter?  Maybe instead of suggesting that my recommendation is outright
dangerous, you yourself might suggest the caveats.  Again, most of my
experiences lie within the batch environment, but I shouldn't have to
qualify my suggestions with 'this is what we do in the batch environment'.
 On a mailing list, people are free to point out the limits of my
recommendation, but that doesn't necessarily disqualify my recommendation.

>
> Still I think nailing the problem at the apropriate place is a habit
> which should generally devloped - as in your example an additional
> int() would have fixed it - but still it would not work if you
> want to deal with arbitrary strings. So its good to make suggestions
> but pretty please think ahead how someone would use it instead of
> investing all your energy into defending dangerous programming practice.


Again, danger is in the eye of the beholder and the hands of the user and
determined mostly by the circumstances.  A code generator written in Python
is going to be subject to all kinds of programming considerations that are
different from those in web applications.


> With "we in python" I referred to a fairly amount of literature about
> programming in python and it design patterns. Nothing me personally.
>

I wasn't aware that we are what has been written or what we have read.  I
thought we refers to people.  Though this sounds a lot like religion. And
maybe I am guilty of heresy.


> Ah and some final words to the controlleness of datawarehouse
> applications and similar things: by the time you are designing such
> a solutuion you will never know what future applications will be
> developed around it so its always best to be prepared.
>

Huh? What are you talking about?


>
> "Data scrubbing" seems a common idea but in fact its very hard to do
> it right due to the nature of different systems using different
> quoting logic. "Dont trust your input" is a habit not only applicable
> to web programming - in fact the company I work for does not do much
> web application but input validation is something we get even audited
> for.
>

"We" are always mindful of the problems "data scrubbing" entails.

Data scrubbing depends on the requirements, like everything else.  And of
course, it goes without saying that you should not trust your input, that
you should check and validate where appropriate.



>
> Nevertheless I wish you a very good weekend :-)
>
> Tino
>
>
Peace.
Michael

-- 
| _ | * | _ |
| _ | _ | * |
| *  | * | * |
--
http://mail.python.org/mailman/listinfo/python-list

Re: What is not objects in Python?

2008-09-28 Thread Terry Reedy

process wrote:

I have heard some criticism about Python, that it is not fully object-
oriented.


Feel free to ignore it if you wish.


What is not an object in Python?


Depends on what you mean by 'in'.  Python is a language for defining and 
manipulating information objects.  Code 'in' Python is not usually a 
maniputed object, though is can be (by eval, exec, and compile, for 
instance).  Names in code that are only used to directly access objects 
typically are also, typically, not objects themselves.



Why isn't len implemented as a str.len and list.len method instead of
a len(list) function?



Partly history and partly practicality.  Len is implemented as .__len__ 
;-).  The len function is one, __len__ methods are many.  If you want to 
pass an argument to a function, passing len is easier that passing 
operator.attrgetter('__len__').  Passing '__len__' (or 'len') would be 
easy, but using len is easier than using getattr(ob,'__len__').


tjr




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


standalone buildbot possible/ don't have a remote

2008-09-28 Thread mark
I want to start small and setup a buildbot on one machine (no slaves).
I hope this is possible. I assume I only need one master in this case
(without slave config)???

from my master.cfg
c['slaves'] = []

... (rest of the sample config)

b1 = {'name': "buildbot-full",
#  'slavename': "bot1name",
  'builddir': "full",
  'factory': f1,
  }

Do I need some configuration that the builder uses the master
instance? I experimented a bit and searched for a similar
configuration so far without success  :-((

I did run the buildbot testsuite without errors.

Here is one problem the buildbot writes out on console:
2008-09-28 20:43:10+0200 [-] maybeStartBuild : [] []
2008-09-28 20:43:10+0200 [-] :
want to start build, but we don't have a remote

Another thing I can think of is to set up two processes on one
machine, which would be a bit of an overhead.

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


Re: Selective importing and package dependencies

2008-09-28 Thread Chris Rebert
On Sun, Sep 28, 2008 at 7:10 AM, David Pratt <[EMAIL PROTECTED]> wrote:
> Hi. I am in the midst of preparing a package to convert between various
> schemas including orms. The issue is I don't want django, slqalchemy, storm,
> rdflib etc. as hard dependencies of the package. Each module is a schema to
> schema conversion. As an example, I have imports for sqlalchemy with classes
> and methods that use them.
>
> from sqlalchemy.util import OrderedDict
> from sqlalchemy import types as rdbtype
> import sqlalchemy as sa
>
> I have my own ideas about how I might do this but looking for
> recommendations from others how they would handle this so the result would
> be:
>
> 1. no hard dependencies on any of these other packages
> 2. load the module without failure.
> 3. import the dependent package if available to perform the conversion

Why not just catch the ImportError-s and set some variables depending
on whether you were able to import the modules, e.g.:

# repeat for each soft-depended module
try:
import django_module
except ImportError:
imported_django = False
else:
imported_django = True

#later in the file
if imported_django and imported_sqlalchemy:
class DjangoToSqlAlchemy(object):
#code that uses the django and sqlalchemy modules here

Regards,
Chris
-- 
Follow the path of the Iguana...
http://rebertia.com

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


Re: Music knowledge representation

2008-09-28 Thread Mark Tolonen


"Mr.SpOOn" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady
<[EMAIL PROTECTED]> wrote:


Here is a link to someone else's design they asked about on the
newsgroup a couple weeks ago.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/ecffaa827984866d/921cba3084b984dc?lnk=st&q=sharpnote#921cba3084b984dc


:D
It's always me.

I think my question is more specific. I need some sort of cycle.

So if I have a list with A, B, C, D, when I iter over it I need to get
an A after the D.


Check out itertools.cycle:


x=itertools.cycle('ABCDEFG')
x.next()

'A'

x.next()

'B'

x.next()

'C'

x.next()

'D'

x.next()

'E'

x.next()

'F'

x.next()

'G'

x.next()

'A'

x.next()

'B'

-Mark

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


Re: Music knowledge representation

2008-09-28 Thread Aaron "Castironpi" Brady
On Sep 28, 2:08 pm, Mr.SpOOn <[EMAIL PROTECTED]> wrote:
> On Sun, Sep 28, 2008 at 8:59 PM, Aaron Castironpi Brady
>
> <[EMAIL PROTECTED]> wrote:
> > Here is a link to someone else's design they asked about on the
> > newsgroup a couple weeks ago.
>
> >http://groups.google.com/group/comp.lang.python/browse_thread/thread/...
>
> :D
> It's always me.
>
> I think my question is more specific. I need some sort of cycle.
>
> So if I have a list with A, B, C, D, when I iter over it I need to get
> an A after the D.

This one was an easy guess:

cycle( iterable)

Make an iterator returning elements from the iterable and saving a
copy of each. When the iterable is exhausted, return elements from the
saved copy. Repeats indefinitely.

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


Re: urllib2 and exceptions

2008-09-28 Thread robean
On Sep 28, 12:11 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
> On Sun, Sep 28, 2008 at 11:03 AM, robean <[EMAIL PROTECTED]> wrote:
> > Hi everyone,
>
> > I have a question about using urllib2.
>
> > I like urllib2 better than urllib at least in part because it has more
> > elaborate support for handling errors: there is built in support for
> > URLError (for faulty urls) and HTTPError (for http errors that might
> > originate from, say, passing an invalid stock-ticker in the program
> > below).  However I can get neither to work.  I'm attaching below the
> > (very short) code: can anyone point out what I'm doing wrong?
>
> > Now, if I replace the URLError and HTTPError with IOError (the class
> > from which both URLError and HTTPError inherit), the program works
> > fine. Why is it that I can call the generic IOError class, but none of
> > the Error classes derived from that? These are clearly defined in the
> > urllib2 manual. Very confused...
>
> > Here's the code:
>
> > import urllib2
>
> > # read stock information from yahoo finance for Traget (TGT)
> > goodTicker = 'TGT' # program works with this
> > badTicker = 'TGTttt' # python doesn't understand either HTTPError
> > or URLError with this
>
> > url = "http://ichart.finance.yahoo.com/table.csv?s="; + badTicker
>
> > try:
> >        handle = urllib2.urlopen(url)
>
> > # this does not work
> > except HTTPError, e:
> >        print "There was an http error"
> >        print e
>
> > # this also does not work
> > except URLError, e:
> >        print "There is a problem with the URL"
> >        print e
> >        exit(1)
>
> > #this works
> > except IOError, e:
> >        print "You have an IOError"
> >        print e
>
> > text = handle.readlines()[:20]
> > for line in text:
> >        print line
>
> > --
> >http://mail.python.org/mailman/listinfo/python-list
>
> My Python begs to differ:
>
> #tmp.py
> import urllib2
>
> badTicker = 'TGTttt'
> url = "http://ichart.finance.yahoo.com/table.csv?s="; + badTicker
>
> try:
>     handle = urllib2.urlopen(url)
>
> except urllib2.HTTPError, e:
>     print "There was an http error"
>     print e
>
> except urllib2.URLError, e:
>     print "There is a problem with the URL"
>     print e
>
> except urllib2.IOError, e:
>     print "You have an IOError"
>     print e
>
> #in the shell
> $ python -V
> Python 2.5.1
> $ python Desktop/tmp.py
> There was an http error
> HTTP Error 404: Not Found
>
> Are you using an outdated version of Python perhaps?
>
> Regards,
> Chris
>
> --
> Follow the path of the Iguana...http://rebertia.com

Then I expect that it is most likely my version of python that is
causing the problem. I'm using 2.5.2.
--
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 and exceptions

2008-09-28 Thread robean
On Sep 28, 12:27 pm, robean <[EMAIL PROTECTED]> wrote:
> On Sep 28, 12:11 pm, "Chris Rebert" <[EMAIL PROTECTED]> wrote:
>
>
>
> > On Sun, Sep 28, 2008 at 11:03 AM, robean <[EMAIL PROTECTED]> wrote:
> > > Hi everyone,
>
> > > I have a question about using urllib2.
>
> > > I like urllib2 better than urllib at least in part because it has more
> > > elaborate support for handling errors: there is built in support for
> > > URLError (for faulty urls) and HTTPError (for http errors that might
> > > originate from, say, passing an invalid stock-ticker in the program
> > > below).  However I can get neither to work.  I'm attaching below the
> > > (very short) code: can anyone point out what I'm doing wrong?
>
> > > Now, if I replace the URLError and HTTPError with IOError (the class
> > > from which both URLError and HTTPError inherit), the program works
> > > fine. Why is it that I can call the generic IOError class, but none of
> > > the Error classes derived from that? These are clearly defined in the
> > > urllib2 manual. Very confused...
>
> > > Here's the code:
>
> > > import urllib2
>
> > > # read stock information from yahoo finance for Traget (TGT)
> > > goodTicker = 'TGT' # program works with this
> > > badTicker = 'TGTttt' # python doesn't understand either HTTPError
> > > or URLError with this
>
> > > url = "http://ichart.finance.yahoo.com/table.csv?s="; + badTicker
>
> > > try:
> > >        handle = urllib2.urlopen(url)
>
> > > # this does not work
> > > except HTTPError, e:
> > >        print "There was an http error"
> > >        print e
>
> > > # this also does not work
> > > except URLError, e:
> > >        print "There is a problem with the URL"
> > >        print e
> > >        exit(1)
>
> > > #this works
> > > except IOError, e:
> > >        print "You have an IOError"
> > >        print e
>
> > > text = handle.readlines()[:20]
> > > for line in text:
> > >        print line
>
> > > --
> > >http://mail.python.org/mailman/listinfo/python-list
>
> > My Python begs to differ:
>
> > #tmp.py
> > import urllib2
>
> > badTicker = 'TGTttt'
> > url = "http://ichart.finance.yahoo.com/table.csv?s="; + badTicker
>
> > try:
> >     handle = urllib2.urlopen(url)
>
> > except urllib2.HTTPError, e:
> >     print "There was an http error"
> >     print e
>
> > except urllib2.URLError, e:
> >     print "There is a problem with the URL"
> >     print e
>
> > except urllib2.IOError, e:
> >     print "You have an IOError"
> >     print e
>
> > #in the shell
> > $ python -V
> > Python 2.5.1
> > $ python Desktop/tmp.py
> > There was an http error
> > HTTP Error 404: Not Found
>
> > Are you using an outdated version of Python perhaps?
>
> > Regards,
> > Chris
>
> > --
> > Follow the path of the Iguana...http://rebertia.com
>
> Then I expect that it is most likely my version of python that is
> causing the problem. I'm using 2.5.2.

Actually, the problem seems to be that IOError is in my namespace, but
the other error classes are not. So,

   except HTTPError, etc.

fails, but

   except urllib2.HttpError, etc.

works fine. Now, I still don't understand why these classes shouldn't
automatically work
--
http://mail.python.org/mailman/listinfo/python-list


generate random digits with length of 5

2008-09-28 Thread sotirac
Wondering if there is a better way to generate string of numbers with
a length of 5 which also can have a 0 in the front of the number.



 random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
elements
 code = 'this is a string' + str(random_number[0]) +
str(random_number[1]) + str(random_number[2]) + str(random_number[3])
+ str(random_number[4])


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


Re: generate random digits with length of 5

2008-09-28 Thread Chris Rebert
On Sun, Sep 28, 2008 at 12:59 PM, sotirac <[EMAIL PROTECTED]> wrote:
> Wondering if there is a better way to generate string of numbers with
> a length of 5 which also can have a 0 in the front of the number.
>
>
> 
>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> elements
>  code = 'this is a string' + str(random_number[0]) +
> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> + str(random_number[4])

code = ''.join(str(digit) for digit in random_number)

Regards,
Chris

> 
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
Follow the path of the Iguana...
http://rebertia.com
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is not objects in Python?

2008-09-28 Thread bearophileHUGS
Terry Reedy:
> Partly history and partly practicality.  Len is implemented as .__len__
> ;-).  The len function is one, __len__ methods are many.  If you want to
> pass an argument to a function, passing len is easier that passing
> operator.attrgetter('__len__').  Passing '__len__' (or 'len') would be
> easy, but using len is easier than using getattr(ob,'__len__').

A simple example may help:

>>> seq = ["", "bb", "c", "ddd"]
>>> seq2 = [[1,1,1,1], [2,2], [3], [4,4,4]]
>>> sorted(seq, key=len)
['c', 'bb', 'ddd', '']
>>> sorted(seq2, key=len)
[[3], [2, 2], [4, 4, 4], [1, 1, 1, 1]]
>>> sorted(seq, key=str.__len__)
['c', 'bb', 'ddd', '']
>>> sorted(seq2, key=str.__len__)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: descriptor '__len__' requires a 'str' object but received a
'list'
>>> from operator import attrgetter
>>> sorted(seq, key=attrgetter("__len__"))
['', 'bb', 'c', 'ddd']
>>> sorted(seq2, key=attrgetter("__len__"))
[[1, 1, 1, 1], [2, 2], [3], [4, 4, 4]]

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


Re: generate random digits with length of 5

2008-09-28 Thread Aaron "Castironpi" Brady
On Sep 28, 2:59 pm, sotirac <[EMAIL PROTECTED]> wrote:
> Wondering if there is a better way to generate string of numbers with
> a length of 5 which also can have a 0 in the front of the number.
>
> 
>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> elements
>  code = 'this is a string' + str(random_number[0]) +
> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> + str(random_number[4])
> 

'%05i'%random.randint(0,9)
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to replace and string in a "SELECT ... IN ()"

2008-09-28 Thread Steve Holden
Michael Mabin wrote:
> Tino, dude, I'm afraid I lied about my previous post being the last
> word.  There are some things you said here that must be addressed.

Good grief, is there no utterance so inconsequential that you will walk
away from it without yet another round of retaliation?

I believe that all people were trying to convey is:

1. There are some data patterns that cannot be directly incorporated
into SQL statements without additional processing, regardless of whether
the "intention" of the data's originator is malevolent. A good example
is a string value containing an apostrophe, which in most SQL
implementations you can escape by preceding the apostrophe with another
apostrophe.

2. SQL drivers in Python are written so that no matter what the values
of the data may be, and no matter which backend they implement, data may
safely be passed as a tuple to a parameterized statement without such
cleansing because the drivers are written to ensure "dangerous" values
are appropriately handled.

Having said all that, if you are positive none of your string data
contains apostrophes you are, of course, free to build SQL statements
yourself - though doing so will on some systems lose you the speed
advantages offered by "prepared statements". Similarly, if you are *not*
positive of the quality of your data you are free to do the escaping in
your logic rather than using parameterized queries. This could be called
"buying a dog and barking yourself".

regards
 Steve
-- 
Steve Holden+1 571 484 6266   +1 800 494 3119
Holden Web LLC  http://www.holdenweb.com/

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


Re: generate random digits with length of 5

2008-09-28 Thread Gary M. Josack

Chris Rebert wrote:

On Sun, Sep 28, 2008 at 12:59 PM, sotirac <[EMAIL PROTECTED]> wrote:
  

Wondering if there is a better way to generate string of numbers with
a length of 5 which also can have a 0 in the front of the number.



 random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
elements
 code = 'this is a string' + str(random_number[0]) +
str(random_number[1]) + str(random_number[2]) + str(random_number[3])
+ str(random_number[4])



code = ''.join(str(digit) for digit in random_number)

Regards,
Chris

  



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



will random.randint(1,9) work for you?
--
http://mail.python.org/mailman/listinfo/python-list


Re: generate random digits with length of 5

2008-09-28 Thread Gary M. Josack

Aaron "Castironpi" Brady wrote:

On Sep 28, 2:59 pm, sotirac <[EMAIL PROTECTED]> wrote:
  

Wondering if there is a better way to generate string of numbers with
a length of 5 which also can have a 0 in the front of the number.


 random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
elements
 code = 'this is a string' + str(random_number[0]) +
str(random_number[1]) + str(random_number[2]) + str(random_number[3])
+ str(random_number[4])




'%05i'%random.randint(0,9)
--
http://mail.python.org/mailman/listinfo/python-list
  
This produces numbers other than 5 digit numbers. making the start 
number 1 should be fine.

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


Re: generate random digits with length of 5

2008-09-28 Thread bearophileHUGS
sotirac:
>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5 elements

But note that's without replacement. So if you want really random
numbers you can do this:

>>> from string import digits
>>> from random import choice
>>> "".join(choice(digits) for d in xrange(5))
'93898'

If you need more speed you can invent other solutions, like (but I
don't know if it's faster):

>>> from random import shuffle
>>> ldigits = list(digits)
>>> ldigits
['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> shuffle(ldigits)
>>> ldigits
['3', '8', '6', '4', '9', '7', '5', '2', '0', '1']
>>> "".join(ldigits[:5])
'38649'

But this may be the most efficient way:

>>> from random import randrange
>>> str(randrange(10)).zfill(5)
'37802'

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


Re: generate random digits with length of 5

2008-09-28 Thread Gary M. Josack

Gary M. Josack wrote:

Aaron "Castironpi" Brady wrote:

On Sep 28, 2:59 pm, sotirac <[EMAIL PROTECTED]> wrote:
 

Wondering if there is a better way to generate string of numbers with
a length of 5 which also can have a 0 in the front of the number.


 random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
elements
 code = 'this is a string' + str(random_number[0]) +
str(random_number[1]) + str(random_number[2]) + str(random_number[3])
+ str(random_number[4])




'%05i'%random.randint(0,9)
--
http://mail.python.org/mailman/listinfo/python-list
  
This produces numbers other than 5 digit numbers. making the start 
number 1 should be fine.

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

nevermind. my brain is tired tonight. this is the best solution.
--
http://mail.python.org/mailman/listinfo/python-list


Re: What is not objects in Python?

2008-09-28 Thread [EMAIL PROTECTED]
On Sep 28, 2:29 pm, process <[EMAIL PROTECTED]> wrote:
> I have heard some criticism about Python, that it is not fully object-
> oriented.
>
> What is not an object in Python?
>

Parts of the syntax aren't objects.  e.g. "=" or ":" aren't objects.

Unlike in some less fully OO-languages (e.g. Java or C++), classes,
functions, and many other "built-in language features" are objects in
Python.  You can do things like return functions just like any other
object, rather than having to do it indirectly through references or
some such:

>>> def add_n(x):
...def rv(y):
...   return y + x
...return rv
...
>>> add_2 = add_n(2)
>>> add_3 = add_n(3)
>>>
>>> print add_2(6)
8
>>> print add_2(10)
12
>>> print add_3(6)
9

> Why isn't len implemented as a str.len and list.len method instead of
> a len(list) function?

FWIW, it is implemented as a str.__len__ method (and list.__len__
method); the len() function just uses those internally.  Java and C++
have similar shortcuts for, say, "+" or "-".  But Python allows you to
call all the operators as methods if you want:

>>> 1+2
3
>>> (1).__add__(2)
3
>>> a_list = [ "a", "b", "c" ]
>>> len(a_list)
3
>>> a_list.__len__()
3


And, of course, the presence of the len() shortcut doesn't alter the
OO-nature of the language any more than the presence of the + operator
does in any OO language.  Derived classes' __len__ operators are
called correctly by len():

>>> class list_that_lies(list):
... def __len__(self):
... return 2
...
>>> bad_list=list_that_lies([1,2])
>>> print bad_list
[1, 2]
>>> len(bad_list)
2
>>> bad_list.append(3)
>>> print bad_list
[1, 2, 3]
>>> len(bad_list)
2

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


Re: is decorator the right thing to use?

2008-09-28 Thread Dmitry S. Makovey
George Sakkis wrote:
> FYI, in case you missed it the final version doesn't need a Proxy base
> class, just inherit from object. Also lowercased ProxyMethod to look
> similar to staticmethod/classmethod:

I cought that, just quoted the wrong one :)

> class A(object):
> 
> def __init__(self, b1, b2):
> self.b1 = b1
> self.b2 = b2
> 
> @proxymethod
> def bmethod(self):
> return self.b1
> 
> @proxymethod
> def bmethod2(self):
> return self.b2
> 
> George

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


Re: generate random digits with length of 5

2008-09-28 Thread Mensanator
On Sep 28, 3:11�pm, "Gary M. Josack" <[EMAIL PROTECTED]> wrote:
> Chris Rebert wrote:
> > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <[EMAIL PROTECTED]> wrote:
>
> >> Wondering if there is a better way to generate string of numbers with
> >> a length of 5 which also can have a 0 in the front of the number.
>
> >> 
> >> �random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> >> elements
> >> �code = 'this is a string' + str(random_number[0]) +
> >> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> >> + str(random_number[4])
>
> > code = ''.join(str(digit) for digit in random_number)
>
> > Regards,
> > Chris
>
> >> 
>
> >> --
> >>http://mail.python.org/mailman/listinfo/python-list
>
> will random.randint(1,9) work for you?

It doesn't meet the OP's requirement that the number
can start with 0. Also, the method the OP asks about
returns a list of unique numbers, so no number can
be duplicated. He can get 02468 but not 13345.

Now, IF it's ok to have an arbitrary number of leading
0s, he can do this:

>>> str(random.randint(0,9)).zfill(5)
'00089'
>>> str(random.randint(0,9)).zfill(5)
'63782'
>>> str(random.randint(0,9)).zfill(5)
'63613'
>>> str(random.randint(0,9)).zfill(5)
'22315'
--
http://mail.python.org/mailman/listinfo/python-list

Re: Not fully OO ?

2008-09-28 Thread Bruno Desthuilliers

Tim Rowe a écrit :

2008/9/26 Bruno Desthuilliers <[EMAIL PROTECTED]>:


Not to start a troll, but from what I've seen of C# so far I do find this a
bit surprising and really suspect more of a library issue than a language
one. Care to tell more about the problem and solution ?

(NB : I wouldn't even asked if you had mentionned say Erlang or Prolog or
OCaml - well, some mostly different language - instead of C#)


IIRC it was library issues -- for one thing I still find it a lot
harder to manage an MS Windows GUI under Python than I do under .NET
(I've never succeeded in getting Iron Python to run properly). In one
sense you could argue that that's not a language issue, and you'd be
right: there's nothing in the syntax or semantics of either language
that makes it so. But in another sense I'd say it is a language issue
(and of course I think I'm right!)


And - after reading the following argument - I think you're wrong !-)


because Python aims to be platform
independent, and whilst that means gains in portability it means that
in return it loses the ease-of-programming of a tightly integrated
platform.

Still a library issue. Python doesn't defines "platform-independant" the 
way Java does, and there are quite a couple Python packages (third-part 
or even in the standard lib) that are clearly platform-specific - 
including MS Windows COM stuff, which was a major PITA using VB6.

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


Re: generate random digits with length of 5

2008-09-28 Thread Aaron "Castironpi" Brady
On Sep 28, 3:44 pm, Mensanator <[EMAIL PROTECTED]> wrote:
> On Sep 28, 3:11 pm, "Gary M. Josack" <[EMAIL PROTECTED]> wrote:
>
>
>
> > Chris Rebert wrote:
> > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <[EMAIL PROTECTED]> wrote:
>
> > >> Wondering if there is a better way to generate string of numbers with
> > >> a length of 5 which also can have a 0 in the front of the number.
>
> > >> 
> > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > >> elements
> > >> code = 'this is a string' + str(random_number[0]) +
> > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > >> + str(random_number[4])
>
> > > code = ''.join(str(digit) for digit in random_number)
>
> > > Regards,
> > > Chris
>
> > >> 
>
> > >> --
> > >>http://mail.python.org/mailman/listinfo/python-list
>
> > will random.randint(1,9) work for you?
>
> It doesn't meet the OP's requirement that the number
> can start with 0. Also, the method the OP asks about
> returns a list of unique numbers, so no number can
> be duplicated. He can get 02468 but not 13345.
>
> Now, IF it's ok to have an arbitrary number of leading
> 0s, he can do this:
>
> >>> str(random.randint(0,9)).zfill(5)
> '00089'
> >>> str(random.randint(0,9)).zfill(5)
> '63782'
> >>> str(random.randint(0,9)).zfill(5)
> '63613'
> >>> str(random.randint(0,9)).zfill(5)
>
> '22315'

Is a while loop until there are 5 distinct digits best otherwise?

while 1:
  a= '%05i'% random.randint( 0, 9 )
  if len( set( a ) )== 5: break

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


Re: generate random digits with length of 5

2008-09-28 Thread Tim Chase

Wondering if there is a better way to generate string of numbers with
a length of 5 which also can have a 0 in the front of the number.


If you want to resample the same digit multiple times, either of these 
two will do:


>>> from random import choice
>>> ''.join(str(choice(range(10))) for _ in range(5))
'06082'

>>> from string import digits
>>> ''.join(choice(digits) for _ in range(5))
'09355'


If you need to prevent the digits from being reused

>>> d = list(digits)
>>> random.shuffle(digit)
>>> ''.join(d[:5])
'03195'

I suspect that the zfill responses don't have the property of equally 
distributed "randomness", as the first digit may more likely be a zero. 
 The methods here should give equal probabilities for each choice in 
each place.


-tkc



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


Re: generate random digits with length of 5

2008-09-28 Thread Michael Ströder
Gary M. Josack wrote:
> Aaron "Castironpi" Brady wrote:
>> On Sep 28, 2:59 pm, sotirac <[EMAIL PROTECTED]> wrote:
>>  
>>> Wondering if there is a better way to generate string of numbers with
>>> a length of 5 which also can have a 0 in the front of the number.
>>>
>>> 
>>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
>>> elements
>>>  code = 'this is a string' + str(random_number[0]) +
>>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
>>> + str(random_number[4])
>>> 
>>> 
>>
>> '%05i'%random.randint(0,9)
>> -- 
>> http://mail.python.org/mailman/listinfo/python-list
>>   
> This produces numbers other than 5 digit numbers. making the start
> number 1 should be fine.

Why do you think it's wrong?

>>> import random
>>> '%05i'%random.randint(0,9)
'09449'
>>>

IMO it's exactly what was required.

Ciao, Michael.

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


Re: Why are "broken iterators" broken?

2008-09-28 Thread Lie
On Sep 21, 10:13 pm, Steven D'Aprano <[EMAIL PROTECTED]
cybersource.com.au> wrote:
> According to the Python docs, once an iterator raises StopIteration, it
> should continue to raise StopIteration forever. Iterators that fail to
> behave in this fashion are deemed to be "broken":
>
> http://docs.python.org/lib/typeiter.html
>
> I don't understand the reasoning behind this. As I understand it, an
> iterator is something like a stream. There's no constraint that once a
> stream is empty it must remain empty forever.

I think empty != StopIteration. StopIteration (IMHO) shouldn't be
raised when the stream is empty, instead a sentinel value specifying
that "there is no data yet, but if you wait there might be" should be
returned (possibly None or empty string). When you raise
StopIteration, it is a signal that I don't have any more data and
there is no use in waiting.

> Can somebody explain why "broken iterators" are broken?
>
> --
> Steven

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


Re: generate random digits with length of 5

2008-09-28 Thread Aaron "Castironpi" Brady
On Sep 28, 4:08 pm, Michael Ströder <[EMAIL PROTECTED]> wrote:
> Gary M. Josack wrote:
> > Aaron "Castironpi" Brady wrote:
> >> On Sep 28, 2:59 pm, sotirac <[EMAIL PROTECTED]> wrote:
>
> >>> Wondering if there is a better way to generate string of numbers with
> >>> a length of 5 which also can have a 0 in the front of the number.
>
> >>> 
> >>>  random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> >>> elements
> >>>  code = 'this is a string' + str(random_number[0]) +
> >>> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> >>> + str(random_number[4])
> >>> 
>
> >> '%05i'%random.randint(0,9)
> >> --
> >>http://mail.python.org/mailman/listinfo/python-list
>
> > This produces numbers other than 5 digit numbers. making the start
> > number 1 should be fine.
>
> Why do you think it's wrong?
>
>
>
> >>> import random
> >>> '%05i'%random.randint(0,9)
> '09449'
>
> IMO it's exactly what was required.
>
> Ciao, Michael.

As you read, there isn't agreement on whether the OP wanted
replacement.  His original code didn't; his spec seemed to.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Hello boys!

2008-09-28 Thread Cydrome Leader
In rec.crafts.metalworking default <[EMAIL PROTECTED]> wrote:
> On Sat, 27 Sep 2008 23:12:59 + (UTC), Cydrome Leader
> <[EMAIL PROTECTED]> wrote:
> 
>>In rec.crafts.metalworking Jim Thompson <[EMAIL PROTECTED]> wrote:
>>> 
>>> On Sat, 27 Sep 2008 18:47:16 -0400, default <[EMAIL PROTECTED]>
>>> wrote:
>>> 
On Sat, 27 Sep 2008 14:56:07 -0700 (PDT), Milenko Stojadinovic Cvrcko
<[EMAIL PROTECTED]> wrote:

>Hello, this is Milenko Stojadinovic from town Banjaluka,
>Bosnia and Herzegovina, also known as Cvrcko
>Does anyone know of any bars in town where I can
>swallow a bucket of cum? It can be either dog,
>horse or human cum. Also, does anyone know of
>any sex bars where people will shit in your mouth?
>I also like eating shit.

Come to the US and park your mouth in front of George Bush - all the
Bshit you can eat - and it keeps on coming!

I have a buddy in Bosna - he's normal.
>>> 
>>> Now you know why I blanket kill-file googlegroups.
>>
>>So you and everybody can talk about them nonstop?
> 
> If you mean Google Groups the condemnation is justified.
> 
> Who is "them?"  Real people do occasionally wander in to GG - or those
> without news servers - or without understanding of Usenet.
> 
> Basically, in the engineering groups (in particular) outsiders are
> welcome.  Engineers are smart, creative and tolerant as a general
> rule.  
> 
> Lighten up.  Who are you defending?  and Who goes into Usenet with a
> thin skin?  Expect ridicule, expect condemnation - "water off a duck's
> back."
> 
> You may think your viewpoint is the only one, the right one, the valid
> one - but a few million others may disagree.  And you ain't started to
> deal with culture shock - some countries place emphasis on diplomacy _
> you know the "how are you?" stuff, others don't, and seem very cold.
> 
> Adapt.

Now you know why I blanket kill-file googlegroups.
--
http://mail.python.org/mailman/listinfo/python-list


Re: how to replace and string in a "SELECT ... IN ()"

2008-09-28 Thread Tino Wildenhain

Michael Mabin wrote:
Tino, dude, I'm afraid I lied about my previous post being the last 
word.  There are some things you said here that must be addressed.


Well. Its interesting to see thats either my English is so bad you
don't understand or you are too tired. All what needs to be said
was said be me and others in many different words and still
you are defending already lost ground. Maybe you take your
time reading the thread again, carefully. Maybe not ;)

Have a good night
Tino


smime.p7s
Description: S/MIME Cryptographic Signature
--
http://mail.python.org/mailman/listinfo/python-list

Re: Not fully OO ?

2008-09-28 Thread Tim Rowe
2008/9/28 Aaron Castironpi Brady <[EMAIL PROTECTED]>:

> Before I tried wxFormBuilder, I imagined that C# would be vastly
> faster to develop than Python, for anything requiring any non-trivial
> graphical interface.  I've done extensive VB, so I can attest to that
> personally.  It is not.

I'm confused about where VB comes in -- I find VB just *slightly*
harder than INTERCAL. C# I find fairly easy.



> You can come up with examples that favor either.  But the opposite of
> statistical is anecdotal.  Sorry again.

Yes, it's anecdotal, but development time isn't just about how fast
the program is to type (otherwise, why aren't we all using APL?)

> The last time I 'checked in' at your post, your claim was "an hour or
> so" vs. "ages".  Hence my responses.  You could probably sneak by by
> claiming a factor of *two*, but if you were exaggerating, please say
> so at any time.

Ok. I was exaggerating when I said that VB was harder than INTERCAL.
It's marginally easier.

As for the program I was working on, I worked for over a day on it in
Python, and did it in about an hour in C#, although in fairness I
didn't forget all the thinking I'd done on the previous day. I have a
lot more Python experience than C# experience, but don't claim to be a
guru in either. And no, I don't work two hour days (unfortunately). I
have indicated that the GUI wasn't the only issue; in C# it was just
easy in that case to find all the library bits I needed to in order to
accomplish the task. It isn't always so.

> on this, that it's "pretty generally applicable"

I'm with you on that.

> I do not believe that C# is pretty generally applicable.

I agree on that, but *only* because it's a proprietary language with
imperfect support once you move away from the .net platform. It's a
generally applicable language to .net, but .net is not a general
platform.

> fact, outside of my VB, COM, and MFC experience, you could say I have
> no clue.  Very tongue in cheek.)

If you see C# as being in any way related to VB, it's no wonder you're
down on it!

> Python has a lot of things C# doesn't.  Can we agree on that?

And C# has things that Python doesn't (such as static typing). Can we
agree on that, too?

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


Re: What is not objects in Python?

2008-09-28 Thread Tim Rowe
2008/9/28 process <[EMAIL PROTECTED]>:
> I have heard some criticism about Python, that it is not fully object-
> oriented.

Why is that a criticism? OO is a tool, not a religion (ok, ok, OO
*should be* a tool, not a religion). Is it a criticism of a hammer
that it is not a screwdriver? Or do you pick the tool that does the
job in hand most effectively?

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


Re: closures and dynamic binding

2008-09-28 Thread Terry Reedy

Aaron "Castironpi" Brady wrote:

On Sep 28, 2:52 am, Steven D'Aprano <[EMAIL PROTECTED]



As for why the complicated version works, it may be clearer if you expand
it from a one-liner:

# expand: f[ n ]= (lambda n: ( lambda: n ) )( n )

inner = lambda: n
outer = lambda n: inner
f[n] = outer(n)

outer(0) => inner with a local scope of n=0
outer(1) => inner with a local scope of n=1 etc.


For this to work, the 'expansion' has to be mental and not actual.
Which is to say, inner must be a text macro to be substituted back into 
outer.



Then, later, when you call inner() it grabs the local scope and returns
the number you expected.




I must have misunderstood.  Here's my run of your code:


I cannot speak to what Steven meant, but


inner = lambda: n


when inner is actually compiled outside of outer, it is no longer a 
closure over outer's 'n' and 'n' will be looked for in globals instead.



outer = lambda n: inner
outer(0)

 at 0x00A01170>

a=outer(0)
b=outer(1)
a()

Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1, in 
NameError: global name 'n' is not defined

Why doesn't 'inner' know it's been used in two different scopes, and
look up 'n' based on the one it's in?


That would be dynamic rather than lexical scoping.

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


Re: What is not objects in Python?

2008-09-28 Thread Bruno Desthuilliers

process a écrit :

I have heard some criticism about Python, that it is not fully object-
oriented.

What is not an object in Python?


names and statements.


Why isn't len implemented as a str.len and list.len method instead of
a len(list) function?


See other answers here about how the len(obj) is implemented. But 
anyway: OO and the dotted notation are totally orthogonal. The 
message(obj) is by no mean less OO than the obj.method() one - even more 
FWIW, since the notion of 'method' is mostly an implementation artifact. 
 The key conceps in OO are "object" and "message", not "dot" and "method".

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


Re: Python 3.0 and repr

2008-09-28 Thread Martin v. Löwis
> What are others' opinions?  Any insight to this design decision?

The intention is that all printable characters in a string get displayed
in repr. This was in particular requested by Japanese users (but also by
other users of non-ASCII characters) which complained that repr() is
fairly useless if your strings actually contains *no* ASCII characters
(but all of them are printable).

Notice that repr() of the string actually succeeds; try

>>> x='\u5000'
>>> z=repr(x)

It is the printing of the repr that fails.

> Maybe repr() should always display the ASCII representation with
> escapes for all other characters

You can use the ascii() builtin if you want that.

> especially considering the "repr() should produce output suitable for
> eval() when possible" rule.

But that is preserved under the new behavior, also! Just try

py> x='\u5000'
py> eval(repr(x))==x
True

Regards,
Martin

P.S. How did you manage to get U+5000 into your data, on a system where
the terminal encoding is cp437? Google translates it as "Rash"; the
Unihan database also has "bewildered", "wildly".
--
http://mail.python.org/mailman/listinfo/python-list


Re: generate random digits with length of 5

2008-09-28 Thread Mensanator
On Sep 28, 3:54�pm, "Aaron \"Castironpi\" Brady"
<[EMAIL PROTECTED]> wrote:
> On Sep 28, 3:44�pm, Mensanator <[EMAIL PROTECTED]> wrote:
>
>
>
>
>
> > On Sep 28, 3:11 pm, "Gary M. Josack" <[EMAIL PROTECTED]> wrote:
>
> > > Chris Rebert wrote:
> > > > On Sun, Sep 28, 2008 at 12:59 PM, sotirac <[EMAIL PROTECTED]> wrote:
>
> > > >> Wondering if there is a better way to generate string of numbers with
> > > >> a length of 5 which also can have a 0 in the front of the number.
>
> > > >> 
> > > >> random_number = random.sample([0,1,2,3,4,5,6,7,8,9], 5) # choose 5
> > > >> elements
> > > >> code = 'this is a string' + str(random_number[0]) +
> > > >> str(random_number[1]) + str(random_number[2]) + str(random_number[3])
> > > >> + str(random_number[4])
>
> > > > code = ''.join(str(digit) for digit in random_number)
>
> > > > Regards,
> > > > Chris
>
> > > >> 
>
> > > >> --
> > > >>http://mail.python.org/mailman/listinfo/python-list
>
> > > will random.randint(1,9) work for you?
>
> > It doesn't meet the OP's requirement that the number
> > can start with 0. Also, the method the OP asks about
> > returns a list of unique numbers, so no number can
> > be duplicated. He can get 02468 but not 13345.
>
> > Now, IF it's ok to have an arbitrary number of leading
> > 0s, he can do this:
>
> > >>> str(random.randint(0,9)).zfill(5)
> > '00089'
> > >>> str(random.randint(0,9)).zfill(5)
> > '63782'
> > >>> str(random.randint(0,9)).zfill(5)
> > '63613'
> > >>> str(random.randint(0,9)).zfill(5)
>
> > '22315'
>
> Is a while loop until there are 5 distinct digits best otherwise?

Of course not.

>
> while 1:
> � a= '%05i'% random.randint( 0, 9 )
> � if len( set( a ) )== 5: break

How is this better than the OP's original code?
--
http://mail.python.org/mailman/listinfo/python-list

Re: generate random digits with length of 5

2008-09-28 Thread Mensanator
On Sep 28, 4:02�pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > Wondering if there is a better way to generate string of numbers with
> > a length of 5 which also can have a 0 in the front of the number.
>
> If you want to resample the same digit multiple times, either of these
> two will do:
>
> �>>> from random import choice
> �>>> ''.join(str(choice(range(10))) for _ in range(5))
> '06082'
>
> �>>> from string import digits
> �>>> ''.join(choice(digits) for _ in range(5))
> '09355'
>
> If you need to prevent the digits from being reused
>
> �>>> d = list(digits)
> �>>> random.shuffle(digit)
> �>>> ''.join(d[:5])
> '03195'
>
> I suspect that the zfill responses don't have the property of equally
> distributed "randomness", as the first digit may more likely be a zero.
> � The methods here should give equal probabilities for each choice in
> each place.

Does he want equal probabilities of each digit in each place?

>
> -tkc

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

Re: generate random digits with length of 5

2008-09-28 Thread bearophileHUGS
Tim Chase:
> I suspect that the zfill responses don't have the property of equally
> distributed "randomness", as the first digit may more likely be a zero.

This code I have shown before:
str(randrange(10)).zfill(5)

If the numbers are equally distributed in [0, 9], then the leading
zeros have the correct distribution.

A little test program for you:

from string import digits
from random import choice, randrange
from collections import defaultdict

def main():
N = 100

freqs1 = defaultdict(int)
for i in xrange(N):
n = "".join(choice(digits) for d in xrange(5))
freqs1[n[0]] += 1
print [freqs1[str(i)] for i in xrange(10)]

freqs2 = defaultdict(int)
for i in xrange(N):
n = str(randrange(10)).zfill(5)
freqs2[n[0]] += 1
print [freqs2[str(i)] for i in xrange(10)]

import psyco; psyco.full()
main()

The output:
[100153, 99561, 99683, 100297, 99938, 100162, 99738, 100379, 100398,
99691]
[99734, 100153, 100091, 100683, 99580, 99676, 99671, 100131, 100102,
100179]

Of course with a bit of math you can also demonstrate it :-)

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


rlcompleter and wxPython, problems ...

2008-09-28 Thread Stef Mientki

hello,

I'm trying to implement autocompletion into my editor.
But I find some weird behavior,
or at least I don't have the faintest  idea why  this behavior occures,
and even more important how to solve it
In the example below I try to autocomplete  " wx.s" , which in my humble 
opinion should at least produce "wx.stc"  (and some others ).


The completion is done in a procedure, so the "locals"  is quite clean.
Before calling the completer, I import the left part of my string to be 
completed.

The program below gives indeed "wx.stc"  as an option,
but if I leave the second line out, marker  "<<<===" ,
I get no results.

Can someone explain this behavior and
maybe even have a solution ?

thanks,
Stef Mientki


import rlcompleter
import wx.stc   # <<<===

# ***
# ***
def _get_completions ( word ) :
 left_part  = None
 right_part = word
 if word.find('.') >= 0 :
   word_parts = word.split('.')
   left_part = '.'.join ( word_parts [ : -1 ] )
   right_part = word_parts [ -1 ]

 try :
   exec ( 'import ' + left_part )
 except :
   return None

 Completer = rlcompleter.Completer ( locals () )
 State = 0
 Next = Completer.complete ( word, State )
 result = []
 while Next :
   result.append ( Next )
   State  += 1
   Next = Completer.complete ( word, State )

 result = ' '.join ( result )
 return result
# ***


# ***
# ***
if __name__ == "__main__":

 word = 'wx.s'
 completions = _get_completions ( word )
 print completions
# ***

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


Web programming in Python.

2008-09-28 Thread Kurda Yon
Hi,

I am totaly newbie in the Python's web programming. So, I dont even
know the basic conceptions (but I have ideas about php-web-
programming). Does it work in a similar way? First, I have to install
a Python-server?

On the server where I have my web site (it runs under Linux) if I type
"python" I get the Python command line. Does it mean that I already
have everything what I need to start web programming in Python. Should
I give *.py extension to the Python programs?

I tried the simplest what could I imagine. And it does not work. I
have created a file "test.py" which contains
print "Hello, World!"

If I type "python test.py" it works! But, if I put in the address line
of my browser "www.mydomainname.org/test.py" it does not work. Or, to
be more precisely, in my browser I see the content of the
"test.py" (not the result of the execution).

Could you pleas help me to start?

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


privatdetektei detektei central privat detektei frankfurt private detective privatdetektiv in berlin

2008-09-28 Thread webilix950
privatdetektei detektei central privat detektei frankfurt private
detective privatdetektiv in berlin

+
+
+
+
+++ DETEKTEIEN DETEKTIVE ONLINE +++ DETEKTEI HAMBURG +++
PRIVATDETEKTIVE +++
+
+
http://WWW.DETEKTEI-DETEKTIV.NET
http://WWW.DETEKTEI-DETEKTIV.NET
http://WWW.DETEKTEI-DETEKTIV.NET
http://WWW.DETEKTEI-DETEKTIV.NET
http://WWW.DETEKTEI-DETEKTIV.NET
http://WWW.DETEKTEI-DETEKTIV.NET
http://WWW.DETEKTEI-DETEKTIV.NET
http://WWW.DETEKTEI-DETEKTIV.NET
http://WWW.DETEKTEI-DETEKTIV.NET
+
+
+
+



##






















detektei hannover dedektive in Steinburg
detektive frankfurt ein privatdetektiv in Rhoen
ausbildung privatdedektiv detektei erding in Torgau
detektiv buero detektei frankfurt in Viersen
detektei duisburg detektei pegasus in Sangerhausen
detektei detektive detektei blunt in Lüchow
detektivbueros frankfurt privat detektiv frankfurt in Mayen
www detektei werde ich privatdetektiv in Heidenheim



- privatdetektiv augsburg detektei erfurt in Lüdenscheid
- detektive berlin privatdetektiv hamburg in Gummersbach
- detektei braunschweig schulung frankfurt in Husum
- Lentz-Detektei.de www.MeineDetektei.de in Sonneberg
- detektei detektive detektei detektiv in Weißenfels
- detektive.com MeineDetektei.de in Neu-Ulm
- www.Lentz-Detektei.de werkschutz frankfurt in Heppenheim
- detektei muelheim zad detektiv in Burg
- ausbildung privatdetektiv privat detektiv in frankfurt in
Kirchheimbolanden
- privatdetektiv augsburg ein privatdedektiv in Zell
- ausbildung privatdedektiv Detektei de in Wolfratshausen
- sicherheit frankfurt detekteien in Miesbach
- privat detektiv frankfurt detektei gewerbe in Doebeln
- detektei duisburg privatdetektive frankfurt in Neuss







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


Milenko Kindl tterter

2008-09-28 Thread sdsdvfsdf
WASHINGTON - Congressional leaders and the White House agreed Sunday
to a $700 billion rescue of the ailing financial industry after
lawmakers insisted on sharing spending controls with the Bush
administration. The biggest U.S. bailout in history won the tentative
support of both presidential candidates and goes to the House for a
vote Monday.
ADVERTISEMENT

The plan, bollixed up for days by election-year politics, would give
the administration broad power to use taxpayers' money to purchase
billions upon billions of home mortgage-related assets held by cash-
starved financial firms.

Flexing its political muscle, Congress insisted on a stronger hand in
controlling the money than the White House had wanted. Lawmakers had
to navigate between angry voters with little regard for Wall Street
and administration officials who warned that inaction would cause the
economy to seize up and spiral into recession.

A deal in hand, Capitol Hill leaders scrambled to sell it to
colleagues in both parties and acknowledged they were not certain it
would pass. "Now we have to get the votes," said Sen. Harry Reid, D-
Nev., the majority leader.

The final legislation was released Sunday evening. House Republicans
and Democrats met privately to review it and decide how they would
vote. "This isn't about a bailout of Wall Street, it's a buy-in, so
that we can turn our economy around," said House Speaker Nancy Pelosi,
D-Calif.

The largest government intervention in financial markets since the
Great Depression casts Washington's long shadow over Wall Street. The
government would take over huge amounts of devalued assets from
beleaguered financial companies in hopes of unlocking frozen credit.

"I don't know of anyone here who wants the center of the economic
universe to be Washington," said a top negotiator, Sen. Chris Dodd,
chairman of the Senate Banking, Housing and Urban Affairs Committee.
But, he added, "The center of gravity is here temporarily. ... God
forbid it's here any longer than it takes to get credit moving again."

The plan would let Congress block half the money and force the
president to jump through some hoops before using it all. The
government could get at $250 billion immediately, $100 billion more if
the president certified it was necessary, and the last $350 billion
with a separate certification — and subject to a congressional
resolution of disapproval.

Still, the resolution could be vetoed by the president, meaning it
would take extra-large congressional majorities to stop it.

Lawmakers who struck a post-midnight deal on the plan with Treasury
Secretary Henry Paulson predicted final congressional action might not
come until Wednesday.

The proposal is designed to end a vicious downward spiral that has
battered all levels of the economy. Hundreds of billions of dollars in
investments based on mortgages have soured and cramped banks'
willingness to lend.

"This is the bottom line: If we do not do this, the trauma, the chaos
and the disruption to everyday Americans' lives will be overwhelming,
and that's a price we can't afford to risk paying," Sen. Judd Gregg,
the chief Senate Republican in the talks, told The Associated Press.
"I do think we'll be able to pass it, and it will be a bipartisan
vote."

A breakthrough came when Democrats agreed to incorporate a GOP demand
— letting the government insure some bad home loans rather than buy
them. That would limit the amount of federal money used in the rescue.

Another important bargain, vital to attracting support from centrist
Democrats, would require that the government, after five years, submit
a plan to Congress on how to recoup any losses from the companies that
got help.

"This is something that all of us will swallow hard and go forward
with," said Republican presidential nominee John McCain. "The option
of doing nothing is simply not an acceptable option."

His Democratic rival Barack Obama sought credit for taxpayer
safeguards added to the initial proposal from the Bush administration.
"I was pushing very hard and involved in shaping those provisions," he
said.

Later, at a rally in Detroit, Obama said, "it looks like we will pass
that plan very soon."

House Republicans said they were reviewing the plan.

As late as Sunday afternoon, Republicans regarded the deal as "a
proposal that is promising in principle, but that is still not final,"
said Antonia Ferrier, a spokeswoman for Missouri Rep. Roy Blunt, the
top House GOP negotiator.

Executives whose companies benefit from the rescue could not get
"golden parachutes" and would see their pay packages limited. Firms
that got the most help through the program — $300 million or more —
would face steep taxes on any compensation for their top people over
$500,000.

The government would receive stock warrants in return for the bailout
relief, giving taxpayers a chance to share in financial companies'
future profits.

To help struggling homeowners, the plan would require the government
to try renegotiating t

Re: closures and dynamic binding

2008-09-28 Thread Steven D'Aprano
On Sun, 28 Sep 2008 17:47:44 -0400, Terry Reedy wrote:

> Aaron "Castironpi" Brady wrote:
>> On Sep 28, 2:52 am, Steven D'Aprano <[EMAIL PROTECTED]
> 
>>> As for why the complicated version works, it may be clearer if you
>>> expand it from a one-liner:
>>>
>>> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n )
>>>
>>> inner = lambda: n
>>> outer = lambda n: inner
>>> f[n] = outer(n)
>>>
>>> outer(0) => inner with a local scope of n=0 outer(1) => inner with a
>>> local scope of n=1 etc.
> 
> For this to work, the 'expansion' has to be mental and not actual. Which
> is to say, inner must be a text macro to be substituted back into outer.

Er, yes, that's what I meant, sorry for not being more explicit. That's 
why it wasn't a copy and paste of actual running code.

Or perhaps I just confused myself and was talking nonsense.



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


Re: closures and dynamic binding

2008-09-28 Thread Aaron "Castironpi" Brady
On Sep 28, 4:47 pm, Terry Reedy <[EMAIL PROTECTED]> wrote:
> Aaron "Castironpi" Brady wrote:
> > On Sep 28, 2:52 am, Steven D'Aprano <[EMAIL PROTECTED]
> >> As for why the complicated version works, it may be clearer if you expand
> >> it from a one-liner:
>
> >> # expand: f[ n ]= (lambda n: ( lambda: n ) )( n )
>
> >> inner = lambda: n
> >> outer = lambda n: inner
> >> f[n] = outer(n)
>
> >> outer(0) => inner with a local scope of n=0
> >> outer(1) => inner with a local scope of n=1 etc.
>
> For this to work, the 'expansion' has to be mental and not actual.
> Which is to say, inner must be a text macro to be substituted back into
> outer.
>
> >> Then, later, when you call inner() it grabs the local scope and returns
> >> the number you expected.
>
> > I must have misunderstood.  Here's my run of your code:
>
> I cannot speak to what Steven meant, but
>
>  inner = lambda: n
>
> when inner is actually compiled outside of outer, it is no longer a
> closure over outer's 'n' and 'n' will be looked for in globals instead.
>
>  outer = lambda n: inner
>  outer(0)
> >  at 0x00A01170>
>  a=outer(0)
>  b=outer(1)
>  a()
> > Traceback (most recent call last):
> >   File "", line 1, in 
> >   File "", line 1, in 
> > NameError: global name 'n' is not defined
>
> > Why doesn't 'inner' know it's been used in two different scopes, and
> > look up 'n' based on the one it's in?
>
> That would be dynamic rather than lexical scoping.

I couldn't find how those apply on the wikipedia website.  It says:
"dynamic scoping can be dangerous and almost no modern languages use
it", but it sounded like that was what closures use.  Or maybe it was
what 'inner' in Steven's example would use.  I'm confused.

Actually, I'll pick this apart a little bit.  See above when I
suggested 'late' and 'early' functions which control (or simulate)
different bindings.  I get the idea that 'late' bound functions would
use a dangerous "dynamic scope", but I could be wrong; that's just my
impression.

> >> inner = lambda: n
> >> outer = lambda n: inner
> >> f[n] = outer(n)
>
> >> outer(0) => inner with a local scope of n=0
> >> outer(1) => inner with a local scope of n=1 etc.

If you defined these as:

inner= late( lambda: n )
outer= lambda n: inner

You could get the right results.  It's not even clear you need
quotes.  Perhaps 'late' could carry the definition of 'n' with it when
it's returned from 'outer'.

In my proposal, it makes a copy of the "localest" namespace, at least
all the variables used below it, then returns its argument in an
original closure.
--
http://mail.python.org/mailman/listinfo/python-list


Re: str() should convert ANY object to a string without EXCEPTIONS !

2008-09-28 Thread Lawrence D'Oliveiro
In message
<[EMAIL PROTECTED]>, est
wrote:

> Well, you succeseded in putting all blame to myself alone. Great.

Take it as a hint.

> When you guy's are dealing with CJK characters in the future, you'll
> find out what I mean.

Speaking as somebody who HAS dealt with CJK characters in the past--see
above.
--
http://mail.python.org/mailman/listinfo/python-list


  1   2   >