Re: Python syntax wart

2007-09-10 Thread Marc 'BlackJack' Rintsch
On Mon, 10 Sep 2007 15:02:58 +1200, Lawrence D'Oliveiro wrote:

> In message <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote:
> 
>> Lawrence D'Oliveiro wrote:
>>> But then you can no longer use indentation to display the
>>> two-dimensional structure of the statement.
>> 
>> How can a statement be two-dimensional?
> 
> Like this (from C++ code, but the idea is the same):
> 
> if
>   (
> ThisCh >= 'A' and ThisCh <= 'Z'
> or
> ThisCh >= '0' and ThisCh <= '9'
> or
> ThisCh == '_'
> or
> ThisCh == '.'
>   )
> ...

I still down see the second dimension.  If you say 2D I think of
something like a table with two columns and not a sequential condition
spread over several lines.

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


Re: How to insert in a string @ a index

2007-09-10 Thread Ant
On Sep 10, 3:15 am, "a.m." <[EMAIL PROTECTED]> wrote:
> Thanks guys for you help. I ended up doing this way (for the
> records)...
>
> t1 = "hello world hello. hello. \nwhy world hello"
...

Another approach may be to use the re module's sub function:

import re

t1 = 'hello world hello. hello. \nwhy world hello'

def matchHandler(match):
if :
   return "XYZ" + match.group(0)
else:
   return match.group(0)

re.sub(keyword, matchHandler, t1)

The nice thing about this approach is that you could store keyword:
test_function pairs in a dictionary, and reuse this whole block of
code for arbitrary keywords with arbitrary rules.

--
Ant...

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


Re: How to insert in a string @ a index

2007-09-10 Thread Marc 'BlackJack' Rintsch
On Mon, 10 Sep 2007 00:29:50 -0700, Ant wrote:

> On Sep 10, 3:15 am, "a.m." <[EMAIL PROTECTED]> wrote:
>> Thanks guys for you help. I ended up doing this way (for the
>> records)...
>>
>> t1 = "hello world hello. hello. \nwhy world hello"
> ...
> 
> Another approach may be to use the re module's sub function:
> 
> import re
> 
> t1 = 'hello world hello. hello. \nwhy world hello'
> 
> def matchHandler(match):
> if :
>return "XYZ" + match.group(0)
> else:
>return match.group(0)
> 
> re.sub(keyword, matchHandler, t1)

This doesn't work because according to the OP not all 'hello's are
keywords.  It seems to depend on the position if it's a keyword or not.

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


Re: concise code (beginner)

2007-09-10 Thread bambam
I have a number of  news readers here, but all of them work
better  with top-posting, and in none of them is top posting
a problem. What software are you using?

Steve.


"Lawrence D'Oliveiro" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
> In message <[EMAIL PROTECTED]>, bambam wrote:
>
>> Thank you,
>
> Don't top-post. 


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


Re: python 2.5 problems

2007-09-10 Thread Ant
On Sep 9, 6:57 pm, "O.R.Senthil Kumaran" <[EMAIL PROTECTED]> wrote:
> > Finally deleted 2.2 and loaded 2.5 (see below), using
>
> Dont delete. Uninstall python 2.2 and additional modules if you have 
> installed them.

But since you've already deleted 2.2, download and reinstall 2.2,
uninstall 2.2 and 2.5 via Add/Remove Programs and then reinstall 2.5
again.

--
Ant...

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


Re: Python syntax wart

2007-09-10 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Marc 'BlackJack' Rintsch
wrote:

> On Mon, 10 Sep 2007 15:02:58 +1200, Lawrence D'Oliveiro wrote:
> 
>> In message <[EMAIL PROTECTED]>, Bjoern Schliessmann
>> wrote:
>> 
>>> Lawrence D'Oliveiro wrote:
 But then you can no longer use indentation to display the
 two-dimensional structure of the statement.
>>> 
>>> How can a statement be two-dimensional?
>> 
>> Like this (from C++ code, but the idea is the same):
>> 
>> if
>>   (
>> ThisCh >= 'A' and ThisCh <= 'Z'
>> or
>> ThisCh >= '0' and ThisCh <= '9'
>> or
>> ThisCh == '_'
>> or
>> ThisCh == '.'
>>   )
>> ...
> 
> I still down see the second dimension.

Horizontal + vertical = 2 dimensions.

A more complicated example:

if
  (
TheProduct == JobSettings.Product.end()
or
TheProduct->second.PerType != ProductPerPerson
and
TheProduct->second.PerType != ProductPerNone
  )
...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: concise code (beginner)

2007-09-10 Thread Francesco Guerrieri
On 9/10/07, bambam <[EMAIL PROTECTED]> wrote:
>
> I have a number of  news readers here, but all of them work
> better  with top-posting, and in none of them is top posting
> a problem. What software are you using?
>
> Steve.
>

I use gmail and I can assure you that top posting is annoying.

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

Re: Does shuffle() produce uniform result ?

2007-09-10 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Steven D'Aprano wrote:

> On Sun, 09 Sep 2007 18:53:32 +1200, Lawrence D'Oliveiro wrote:
> 
>> In message <[EMAIL PROTECTED]>, Paul Rubin wrote:
>> 
>>> Lawrence D'Oliveiro <[EMAIL PROTECTED]> writes:
>>>
 Except that the NSA's reputation has taken a dent since they failed to
 anticipate the attacks on MD5 and SHA-1.
>>> 
>>> NSA had nothing to do with MD5 ...
>> 
>> Nevertheless, it was their job to anticipate attacks on it. After all,
>> they call themselves the "National _Security_ Agency", don't they?
> 
> The NSA has many jobs, and doing public research in crypto is only one of
> them -- and a particularly small one at that. For all we know, they had
> an attack on MD5 ten years before anyone else and didn't tell anyone
> because keeping it secret made it useful for one of their other jobs.

Yes, but they're supposed to look after US _National_ security, not their
own security. Since people in strategic jobs make so much use of hash
functions in crypto, that means it is most certainly an important part of
the NSA's function to ensure that there are good hash functions available.
They've fallen down on that job.

>>> ... and it's to NSA's credit that SHA-1 held up for as long as it did.
>> 
>> But they have no convincing proposal for a successor. That means the gap
>> between the classified and non-classified state of the art has shrunk
>> down to insignificance.
> 
> I don't see how that follows.

Because previously, the NSA has done things that it took open researchers
years, even decades, to figure out. But not any more.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: concise code (beginner)

2007-09-10 Thread Lawrence D'Oliveiro
A: Skid-marks in front of the hedgehog.
Q: What's the difference between a dead hedgehog on the road, and a dead
top-poster on the road?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python syntax wart

2007-09-10 Thread Marc 'BlackJack' Rintsch
On Mon, 10 Sep 2007 19:54:49 +1200, Lawrence D'Oliveiro wrote:

> In message <[EMAIL PROTECTED]>, Marc 'BlackJack' Rintsch
> wrote:
> 
>> On Mon, 10 Sep 2007 15:02:58 +1200, Lawrence D'Oliveiro wrote:
>> 
>>> In message <[EMAIL PROTECTED]>, Bjoern Schliessmann
>>> wrote:
>>> 
 Lawrence D'Oliveiro wrote:
> But then you can no longer use indentation to display the
> two-dimensional structure of the statement.
 
 How can a statement be two-dimensional?
>>> 
>>> Like this (from C++ code, but the idea is the same):
>>> 
>>> if
>>>   (
>>> ThisCh >= 'A' and ThisCh <= 'Z'
>>> or
>>> ThisCh >= '0' and ThisCh <= '9'
>>> or
>>> ThisCh == '_'
>>> or
>>> ThisCh == '.'
>>>   )
>>> ...
>> 
>> I still down see the second dimension.
> 
> Horizontal + vertical = 2 dimensions.

Wow I wrote two dimensional programs all the time without knowing it.

> A more complicated example:
> 
> if
>   (
> TheProduct == JobSettings.Product.end()
> or
> TheProduct->second.PerType != ProductPerPerson
> and
> TheProduct->second.PerType != ProductPerNone
>   )
> ...

Sorry I still don't understand how this could be called a 2D statement. 
Or is this already 3D!?  I see a tree structure here, but still no table. 
And this is also easily written that way in Python if you don't insist on
the line break after the ``if`` or can live with backslashes.

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


Re: Python syntax wart

2007-09-10 Thread Lawrence D'Oliveiro
In message <[EMAIL PROTECTED]>, Marc 'BlackJack' Rintsch
wrote:

> I see a tree structure here ...

Good, you're improving.

> ... but still no table. 

Who said anything about a table?

> And this is also easily written that way in Python if you don't insist on
> the line break after the ``if`` or can live with backslashes.

Which is precisely the point.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: concise code (beginner)

2007-09-10 Thread Marc 'BlackJack' Rintsch
On Mon, 10 Sep 2007 17:42:16 +1000, bambam wrote:

> "Lawrence D'Oliveiro" <[EMAIL PROTECTED]> wrote in
> message news:[EMAIL PROTECTED]
>> In message <[EMAIL PROTECTED]>, bambam wrote:
>>
>>> Thank you,
>>
>> Don't top-post.
>
> I have a number of  news readers here, but all of them work
> better  with top-posting, and in none of them is top posting
> a problem.

This is not about *you* having any problems but all the people who must
read your top postings.  Most of them, at least in this news group, expect
that a text read from top to bottom follows time from earliest to latest.
And as most here don't top post, a conversation with a top poster starts
to get mixed and even harder to follow.

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


Re: concise code (beginner)

2007-09-10 Thread Paul Rudin
Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> writes:

> On Mon, 10 Sep 2007 17:42:16 +1000, bambam wrote:
>
>> "Lawrence D'Oliveiro" <[EMAIL PROTECTED]> wrote in
>> message news:[EMAIL PROTECTED]
>>> In message <[EMAIL PROTECTED]>, bambam wrote:
>>>
 Thank you,
>>>
>>> Don't top-post.
>>
>> I have a number of  news readers here, but all of them work
>> better  with top-posting, and in none of them is top posting
>> a problem.
>
> This is not about *you* having any problems but all the people who must
> read your top postings.  Most of them, at least in this news group, expect
> that a text read from top to bottom follows time from earliest to latest.
> And as most here don't top post, a conversation with a top poster starts
> to get mixed and even harder to follow.


>From 

A: Because it messes up the order in which people normally read text.
Q: Why is top-posting such a bad thing?
A: Top-posting.
Q: What is the most annoying thing in e-mail?

:)

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


Re: Python syntax wart

2007-09-10 Thread Marc 'BlackJack' Rintsch
On Mon, 10 Sep 2007 20:19:08 +1200, Lawrence D'Oliveiro wrote:

> In message <[EMAIL PROTECTED]>, Marc 'BlackJack' Rintsch
> wrote:
> 
>> I see a tree structure here ...
> 
> Good, you're improving.

Thanks.

>> ... but still no table. 
> 
> Who said anything about a table?

Me. If that statement is 2D I expected to see a table structure.  And I
don't mean that the source code itself is arranged in lines and columns
but that the so called *2D statement* can be seen as table.

>> And this is also easily written that way in Python if you don't insist on
>> the line break after the ``if`` or can live with backslashes.
> 
> Which is precisely the point.

Then is the lack of curly braces also a syntax wart.  Maybe you should
switch to a different language or write a preprocessor.

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


Re: Python syntax wart

2007-09-10 Thread Stefan Behnel
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Marc 'BlackJack' Rintsch
> wrote:
>> And this is also easily written that way in Python if you don't insist on
>> the line break after the ``if`` or can live with backslashes.
> 
> Which is precisely the point.

This actually sounds somewhat pointless to me. If complex things don't fit
into one line, a good way to deal with it is not to insist on making them a
single statement.

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


Re: Python syntax wart

2007-09-10 Thread Gabriel Genellina
On 9 sep, 08:14, Bjoern Schliessmann  wrote:

> How can a statement be two-dimensional? Like a two-dimensionalTuringMachine?

Do you know the Befunge language? Program flow is not lineal but along
a 2D grid. There are variants over toroids and more bizarre surfaces,
even using 3D.

"Befunge is believed to be the first two-dimensional, ASCII-based,
general-purpose programming language."


--
Gabriel Genellina

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


Re: Python syntax wart

2007-09-10 Thread Duncan Booth
Stefan Behnel <[EMAIL PROTECTED]> wrote:

> This actually sounds somewhat pointless to me. If complex things don't
> fit into one line, a good way to deal with it is not to insist on
> making them a single statement.
> 

Or make them into a single method/function call. I would post some pseudo-
code replacing the TheProduct conditions with a single call to a 
meaningfully named method except I haven't got the faintest idea what it is 
trying to achieve.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Setting stdout encoding

2007-09-10 Thread Gabriel Genellina
En Sun, 09 Sep 2007 17:49:14 -0300, Fabio Zadrozny <[EMAIL PROTECTED]>
escribi?:

Does someone know if there's a way to explicitly set the stdout/stderr/
stdin
encoding that python should use?

The encoding can be set using the C API for file objects - from Python
code, use ctypes:

py> from ctypes import *
py> PyFile_SetEncoding = pythonapi.PyFile_SetEncoding
py> PyFile_SetEncoding.argtypes = (py_object, c_char_p)
py> if not PyFile_SetEncoding(sys.stdout, "hex"):
... raise ValueError
...
py> print "Hello"
Hello
py> print u"Hello"
48656c6c6f

--
Gabriel Genellina

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


Enum class with ToString functionality

2007-09-10 Thread bg_ie
Hi,

I have the following class -

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

plus the following code -

testResult = TestOutcomes.PASSED

testResultAsString
if  testResult == TestOutcomes.PASSED:
testResultAsString = "Passed"
elif testResult == TestOutcomes.FAILED :
testResultAsString = "Failed"
else:
testResultAsString = "Aborted"

But it would be much nicer if I had a function to covert to string as
part of the TestOutcomes class. How would I implement this?

Thanks,

Barry

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


Re: unexpected behavior: did i create a pointer?

2007-09-10 Thread neoedmund
On Sep 7, 4:07 pm, gu <[EMAIL PROTECTED]> wrote:
> hi to all!
> after two days debugging my code, i've come to the point that the
> problem was caused by an unexpected behaviour of python. or by lack of
> some information about the program, of course! i've stripped down the
> code to reproduce the problem:
>
> 
> a = {}
>
> for x in range(10):
>  for y in range(10):
>  a[x,y] = "0"
>
> copyOfA = a
>
> def functionA(x,y):
>  print a[x,y],
>  copyOfA[x,y] = "*"
>  print a[x,y],copyOfA[x,y]
>
> for x in range(10):
>  for y in range(10):
>  functionA(x,y)
>
> 
>
> now, in the second "for" cycle and in functionA() i only 'touch' copyOfA
> (altering it). as i don't touch the variable "a", i expect it not to be
> affected by any change, but copyOfA acts like a pointer to a and
> altering copyOfA's values result in altering the values of "a", so the
> result that i expect is:
> 0 0 *
> 0 0 *
> 0 0 *
> 0 0 *
> [..]
>
> but i get:
> 0 * *
> 0 * *
> 0 * *
> 0 * *
> [..]
>
> what's going on?
> thanks in advance.

no language act like want you tought, or the assignment operation will
be too expensive.

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


Re: concise code (beginner)

2007-09-10 Thread Gabriel Genellina
"Lawrence D'Oliveiro" <[EMAIL PROTECTED]> wrote in
message
news:[EMAIL PROTECTED]

Why not just build a new list? E.g.

   newdevs = []
   for dev in devs :
   ...
   if not removing_dev :
   newdevs.append(dev)
   #end if
   #end for
   devs = newdevs

En Sun, 09 Sep 2007 22:58:54 -0300, bambam <[EMAIL PROTECTED]> escribi?:

I can try that, but I'm not sure that it will work. The problem
is that devList is just a pointer to a list owned by someone else.
Making devList point to a new list won't work: I need to make
the parent list different. I could do this by adding an extra
level of indirection, but I think at the risk making the call
environment more complex.

Then use [:] to *replace* all the old list items, do not merely rebind
the name. That last statement
should be, instead:

devs[:] = newdevs

(Please don't top-post)

--
Gabriel Genellina

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


less obvious "super"

2007-09-10 Thread Nagarajan
Hi group,
I am confused with "super" usage..It seems to be complicated and less
obvious.
Here is what I need to achieve..

class A :
def __init__( self ):
self.x  = 0

class B ( A ):
def __init__( self, something ):
# Use "super" construct here so that I can "inherit" x of A
self.y  = something

How should I use "super" so that I could access the variable "x" of A
in B?

Thanks!

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


Re: less obvious "super"

2007-09-10 Thread Francesco Guerrieri
On 9/10/07, Nagarajan <[EMAIL PROTECTED]> wrote:
>
> Hi group,
> I am confused with "super" usage..It seems to be complicated and less
> obvious.
> Here is what I need to achieve..
>
> class A :
> def __init__( self ):
> self.x  = 0
>
> class B ( A ):
> def __init__( self, something ):
> # Use "super" construct here so that I can "inherit" x of A
> self.y  = something
>
> How should I use "super" so that I could access the variable "x" of A
> in B?
>


You don't need to use super in this case. You just have to remember to
explicitly initialize the classes you are deriving from. In this case,

class B(A):
def __init__(self, something):
A.__init__(self)
self.y = something

bye,
francesco
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Modul (%) in python not like in C?

2007-09-10 Thread Bryan Olson
Dennis Lee Bieber wrote:
>   The best answer is probably to be found from the definition of
> divmod()

The divmod() function is one of those little delights that reminds
me why I love Python, but I do not think it answers the question
here. The definition of divmod() references the '%' operation, and
not the other way around.

   http://docs.python.org/lib/built-in-funcs.html
   http://docs.python.org/ref/binary.html


 divmod(70, 6)
> (11, 4)
 6*11 + 4
> 70
 divmod(-70, 6)
> (-12, 2)
 6 * -12 + 2
> -70

Also:

 >>> divmod(70, -6)
(-12, -2)
 >>> -6*-12 + -2
70

 >>> divmod(-70, -6)
(11, -4)
 >>> -6*11 + -4
-70

> Or in general terms
> 
> (a, b) = divmod(x, y)
> x = y * a + b

> IOWs, the definition of modulo, and the definition of integer division,
> are linked...

Right. Thus given integers x and y, y!=0, Python and C agree:

x == (y * (x / y)) + (x % y)

The disagreement is how integer division rounds. In C, integer
division rounds toward zero. In Python, integer division rounds
downward.


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


Re: Python wrapper, problem with subprocess read/write

2007-09-10 Thread A.T.Hofkamp
On 2007-09-07, NeoGregorian <[EMAIL PROTECTED]> wrote:
> I tried instead to use:
>
> lines = []
> line = proc.stdout.readline()
> while line :
> lines.append(line)
> line = proc.stdout.readline()
>
> This prints out everything except the ">" line, which is good. But
> then freezes while waiting for input, which is bad.
>
> Any suggestions on how to solve this in a good way?

'readline()' reads a line, that is, some text ending with a new-line. Since
your last line, the ">" prompt has no ending new-line, the call blocks, waiting
for the new-line character.

So the simple anser is "don't use readline()".

You have to fall back to reading characters, such as "read(1)" (which block
until it receives a character).
In addition, you will have to do analysis on whether the line you are currently
reading is a prompt, and if so, stop reading to prevent blocking.
(and instead, give the program a command by writing to proc.stdin).


In case you don't know, pexpect (Python expect) does all (and more) that you
are trying to do.


Sincerely,
Albert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python syntax wart

2007-09-10 Thread J. Cliff Dyer

J. Cliff Dyer wrote:

Lawrence D'Oliveiro wrote:

In message <[EMAIL PROTECTED]>, Bjoern Schliessmann wrote:

  

What's wrong with this:

for Link in GetEachRecord(



Then you're no longer showing the syntax structure in two dimensions.

  
If somebody handed me a program of more than twenty five lines that 
was formatted "two dimensionally" as you call it, and asked me to deal 
with it, the first thing I would do is reformat the code  so a not to 
be so hideously ugly.  Your style has the unfortunate consequence of 
requiring the reader to scroll ridiculous distances, making it more 
difficult to maintain.  I do see the benefit of using multiple lines 
on complex statements, such as:


if (actor == 'Tony Leung'
or actor == 'Alec Baldwin'
or actor == 'Divine'
or actor == 'Fitty-cent'
or actor == 'Sir Ian McKellen'):
go_see_the_movie()

but even here, there is some attempt to keep things compact by making 
each line meaningful.


However, I utterly fail to see how putting the word "or" on its own 
line, (or worse: "if!") clarifies things in the slightest. 

Part of the point of designing python with a line break as the 
statement closer is to encourage you to write in a style that treats 
each line as a statement.  Changing the syntax to encourage people to 
violate this principle would not be an improvement to the design, but 
a relinquishing of basic principles.  Obviously there are some cases 
where you want to do something different, but that's what backslashes 
are for.  Frankly, I find your code just as ugly without the 
backslashes as it is with them.


Cheers,
Cliff



I replied to poster instead of to list.  My apologies.
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Modul (%) in python not like in C?

2007-09-10 Thread John Machin
On Sep 10, 9:16 am, Ricardo Aráoz <[EMAIL PROTECTED]> wrote:
> John Machin wrote:
> > On Sep 10, 8:05 am, Lee Harr <[EMAIL PROTECTED]> wrote:
>  Python will always yield a number x = m%n such that 0 <= x < n, but
>  Turbo C will always yield a number such that if x = m%n -x = -m%n.  That
>  is, since 111 % 10 = 1, -111 % 10 = -1.  The two values will always
>  differ by n (as used above).
> >> Maybe it is an order-of-operations thing
>
> >> -111 % 10 = -1
> >> (-111) % 10 = 9
> >> ?
>
> > and on the other hand, maybe it's not. Try to think of any language
> > where unary minus binds so loosely.
>
> Why the theoretical argument when you can TEST your assumptions?
>
> >>> -111 % 10
> 9
> >>> (-111) % 10
>
> 9

I was *assuming* nothing; I *know* what is the relative precedence of
% and unary minus in both C and Python. I was not arguing; I was
inviting Lee (as I now invite you) to think before writing.

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

Re: Using s.sort([cmp[, key[, reverse]]]) to sort a list of objects based on a attribute

2007-09-10 Thread Stefan Arentz
[EMAIL PROTECTED] (Alex Martelli) writes:

> Stefan Arentz <[EMAIL PROTECTED]> wrote:
> 
> > Miki <[EMAIL PROTECTED]> writes:
> > 
> > > >   steps.sort(key = lambda s: s.time)
> > > This is why attrgetter in the operator module was invented.
> > > from operator import attrgetter
> > > ...
> > > steps.sort(key=attrgettr("time"))
> > 
> > Personally I prefer the anonymous function over attrgettr :)
> 
> However, Python disagrees with you...:
> 
> brain:~ alex$ python -mtimeit -s'from operator import attrgetter;
> L=map(complex,xrange(999))' 'sorted(L, key=lambda x:x.real)'
> 1000 loops, best of 3: 567 usec per loop
> 
> brain:~ alex$ python -mtimeit -s'from operator import attrgetter;
> L=map(complex,xrange(999))' 'sorted(L, key=attrgetter("real"))'
> 1000 loops, best of 3: 367 usec per loop
> 
> A speed-up of 35% is a pretty clear indicator of what _Python_ "prefers"
> in this situation:-).

I could not care less :-)

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


Re: less obvious "super"

2007-09-10 Thread Duncan Booth
Nagarajan <[EMAIL PROTECTED]> wrote:

> Here is what I need to achieve..
> 
> class A :
> def __init__( self ):
> self.x  = 0

Don't use old style classes. If you are planning to use 'super' then you 
must use new-style classes, so use 'object' as a base class here.

> 
> class B ( A ):
> def __init__( self, something ):
> # Use "super" construct here so that I can "inherit" x of A
> self.y  = something
> 
> How should I use "super" so that I could access the variable "x" of A
> in B?
> 
If you aren't worried about diamond shaped multiple inheritance 
hierarchies then just use:

class B ( A ):
def __init__( self, something ):
A.__init__(self)
self.y  = something

If you are then:

class B ( A ):
def __init__( self, something ):
super(B, self).__init__()
self.y  = something

When you use super you usually just want the current class and current 
instance as parameters. Putting that together:

>>> class A(object):
def __init__( self ):
self.x  = 0


>>> class B ( A ):
def __init__( self, something ):
super(B, self).__init__()
self.y  = something


>>> obj = B(3)
>>> obj.x
0
>>> obj.y
3
>>> 
-- 
http://mail.python.org/mailman/listinfo/python-list


Pydev 1.3.9 Released

2007-09-10 Thread Fabio Zadrozny
Hi All,

Pydev and Pydev Extensions 1.3.9 have been released

Details on Pydev Extensions: http://www.fabioz.com/pydev
Details on Pydev: http://pydev.sf.net
Details on its development: http://pydev.blogspot.com

Release Highlights in Pydev Extensions:
-

* Code-analysis: detects bad indentation (wrong number of indent chars).
* Code-analysis: Class may be marked with '@DynamicAttrs' so that the
code-analysis doesn't give undefined variable errors. See
http://www.fabioz.com/pydev/manual_adv_code_analysis.html#Passing_info_to_code_analysisfor
more details.
* Mark-Occurrences: Fix: a class that had a call would not be recognized
sometimes.
* Rename Refactoring: Fix: when different heuristics yielded the same result
the text could become garbled.


Release Highlights in Pydev:
--

* Fixed problem when configuring jython
* Patch from paulj: debbugger working with jython 2.2rc2
* Patch from Oskar Heck: debbugger can change globals
* Added action to delete all .pyc / $py.class files
* Added actions to add/remove the pydev configuration from a project
(previously, the only way to add a nature was to open a python file within a
project).
* Ctrl+Shift+O: When used with a selection will consider lines ending with \
(without selection organizes imports)
* Auto-add "import" string will not be added when adding a space in the
case: from xxximport (just after from xxx)
* Templates created with tabs (or spaces indent) are now converted to the
indent being used in the editor
* Hide non-pydev projects filter working
* Don't show assignments/imports after if __name__ == '__main__': in outline
* Code-completion: after a completion is requested, pressing '.' will apply
that completion (and if it has parameters, they'll not be added).
* Code-completion: when a code-completion is applied with Ctrl pressed
(toggle mode), parameters are not added.
* Assign to local variable/attribute handles constants correctly.
* psyco changed for Null object for debug (so, no changes are required to
the code if psyco is used while debugging).
* Code-folding annotations won't change places.
* Pydev package explorer will correctly show outline for files if the
project root is set as a source folder.
* Pydev package explorer: folders under the pythonpath have a package icon.
* Unittest runner: handles multiple selection.


What is PyDev?
---

PyDev is a plugin that enables users to use Eclipse for Python and Jython
development -- making Eclipse a first class Python IDE -- It comes with many
goodies such as code completion, syntax highlighting, syntax analysis,
refactor, debug and many others.


Cheers,

-- 
Fabio Zadrozny
--
Software Developer

ESSS - Engineering Simulation and Scientific Software
http://www.esss.com.br

Pydev Extensions
http://www.fabioz.com/pydev

Pydev - Python Development Enviroment for Eclipse
http://pydev.sf.net
http://pydev.blogspot.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Enum class with ToString functionality

2007-09-10 Thread Duncan Booth
[EMAIL PROTECTED] wrote:

> But it would be much nicer if I had a function to covert to string as
> part of the TestOutcomes class. How would I implement this?

Perhaps: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413486
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Enum class with ToString functionality

2007-09-10 Thread TheFlyingDutchman
On Sep 10, 2:28 am, [EMAIL PROTECTED] wrote:
> Hi,
>
> I have the following class -
>
> class TestOutcomes:
> PASSED = 0
> FAILED = 1
> ABORTED = 2
>
> plus the following code -
>
> testResult = TestOutcomes.PASSED
>
> testResultAsString
> if  testResult == TestOutcomes.PASSED:
> testResultAsString = "Passed"
> elif testResult == TestOutcomes.FAILED :
> testResultAsString = "Failed"
> else:
> testResultAsString = "Aborted"
>
> But it would be much nicer if I had a function to covert to string as
> part of the TestOutcomes class. How would I implement this?
>
> Thanks,
>
> Barry

The equivalent to Java's toString() is __str__() in Python:

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

def __init__(self,outcome):
self.outcome = outcome

def __str__(self):
if  self.outcome == TestOutcomes.PASSED:
   return "Passed"
elif self.outcome == TestOutcomes.FAILED :
   return "Failed"
else:
   return "Aborted"

if __name__ == "__main__":
testResult = TestOutcomes(TestOutcomes.ABORTED)
print testResult
testResult = TestOutcomes(TestOutcomes.FAILED)
a = testResult.__str__()
print a

Aborted
Failed


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


Re: Enum class with ToString functionality

2007-09-10 Thread aine_canby
On 10 Sep, 13:35, TheFlyingDutchman <[EMAIL PROTECTED]> wrote:
> On Sep 10, 2:28 am, [EMAIL PROTECTED] wrote:
>
>
>
>
>
> > Hi,
>
> > I have the following class -
>
> > class TestOutcomes:
> > PASSED = 0
> > FAILED = 1
> > ABORTED = 2
>
> > plus the following code -
>
> > testResult = TestOutcomes.PASSED
>
> > testResultAsString
> > if  testResult == TestOutcomes.PASSED:
> > testResultAsString = "Passed"
> > elif testResult == TestOutcomes.FAILED :
> > testResultAsString = "Failed"
> > else:
> > testResultAsString = "Aborted"
>
> > But it would be much nicer if I had a function to covert to string as
> > part of the TestOutcomes class. How would I implement this?
>
> > Thanks,
>
> > Barry
>
> The equivalent to Java's toString() is __str__() in Python:
>
> class TestOutcomes:
> PASSED = 0
> FAILED = 1
> ABORTED = 2
>
> def __init__(self,outcome):
> self.outcome = outcome
>
> def __str__(self):
> if  self.outcome == TestOutcomes.PASSED:
>return "Passed"
> elif self.outcome == TestOutcomes.FAILED :
>return "Failed"
> else:
>return "Aborted"
>
> if __name__ == "__main__":
> testResult = TestOutcomes(TestOutcomes.ABORTED)
> print testResult
> testResult = TestOutcomes(TestOutcomes.FAILED)
> a = testResult.__str__()
> print a
>
> Aborted
> Failed- Dölj citerad text -
>
> - Visa citerad text -

Would this be crazy? -

class TestOutcomes:
PASSED = "PASSED"
FAILED = "FAILED"
ABORTED = "ABORTED"

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

Re: Enum class with ToString functionality

2007-09-10 Thread David
On 9/10/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> Hi,
>
> I have the following class -
>
> class TestOutcomes:
> PASSED = 0
> FAILED = 1
> ABORTED = 2
>
> plus the following code -
>
> testResult = TestOutcomes.PASSED
>
> testResultAsString
> if  testResult == TestOutcomes.PASSED:
> testResultAsString = "Passed"
> elif testResult == TestOutcomes.FAILED :
> testResultAsString = "Failed"
> else:
> testResultAsString = "Aborted"
>
> But it would be much nicer if I had a function to covert to string as
> part of the TestOutcomes class. How would I implement this?

You can use reflection to do this. Perhaps a constructor that goes
through your class dict (dir(self)) and builds an int->string mapping
property based on the value and name of the attributes (perhaps just
the ones whose type is int). To get the exact same result as your code
above you can capitalize the first letter of the attribute name, and
lowercase the rest.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: less obvious "super"

2007-09-10 Thread Nagarajan
On Sep 10, 4:20 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Nagarajan <[EMAIL PROTECTED]> wrote:
> > Here is what I need to achieve..
>
> > class A :
> > def __init__( self ):
> > self.x  = 0
>
> Don't use old style classes. If you are planning to use 'super' then you
> must use new-style classes, so use 'object' as a base class here.
>
>
>
> > class B ( A ):
> > def __init__( self, something ):
> > # Use "super" construct here so that I can "inherit" x of A
> > self.y  = something
>
> > How should I use "super" so that I could access the variable "x" of A
> > in B?
>
> If you aren't worried about diamond shaped multiple inheritance
> hierarchies then just use:
>
> class B ( A ):
> def __init__( self, something ):
> A.__init__(self)
> self.y  = something
>
> If you are then:
>
> class B ( A ):
> def __init__( self, something ):
> super(B, self).__init__()
> self.y  = something
>
> When you use super you usually just want the current class and current
> instance as parameters. Putting that together:
>
> >>> class A(object):
>
> def __init__( self ):
> self.x  = 0
>
> >>> class B ( A ):
>
> def __init__( self, something ):
> super(B, self).__init__()
> self.y  = something
>
>
>
> >>> obj = B(3)
> >>> obj.x
> 0
> >>> obj.y
> 3

What's the difference b/w:
   class A :
and

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


Re: less obvious "super"

2007-09-10 Thread Nagarajan
On Sep 10, 4:20 pm, Duncan Booth <[EMAIL PROTECTED]> wrote:
> Nagarajan <[EMAIL PROTECTED]> wrote:
> > Here is what I need to achieve..
>
> > class A :
> > def __init__( self ):
> > self.x  = 0
>
> Don't use old style classes. If you are planning to use 'super' then you
> must use new-style classes, so use 'object' as a base class here.
>
>
>
> > class B ( A ):
> > def __init__( self, something ):
> > # Use "super" construct here so that I can "inherit" x of A
> > self.y  = something
>
> > How should I use "super" so that I could access the variable "x" of A
> > in B?
>
> If you aren't worried about diamond shaped multiple inheritance
> hierarchies then just use:
>
> class B ( A ):
> def __init__( self, something ):
> A.__init__(self)
> self.y  = something
>
> If you are then:
>
> class B ( A ):
> def __init__( self, something ):
> super(B, self).__init__()
> self.y  = something
>
> When you use super you usually just want the current class and current
> instance as parameters. Putting that together:
>
> >>> class A(object):
>
> def __init__( self ):
> self.x  = 0
>
> >>> class B ( A ):
>
> def __init__( self, something ):
> super(B, self).__init__()
> self.y  = something
>
>
>
> >>> obj = B(3)
> >>> obj.x
> 0
> >>> obj.y
> 3


What's the difference b/w:
 class A:
and
 class A ( object ):

Thanks.

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


Re: Enum class with ToString functionality

2007-09-10 Thread TheFlyingDutchman
On Sep 10, 2:28 am, [EMAIL PROTECTED] wrote:
> Hi,
>
> I have the following class -
>
> class TestOutcomes:
> PASSED = 0
> FAILED = 1
> ABORTED = 2
>
> plus the following code -
>
> testResult = TestOutcomes.PASSED
>
> testResultAsString
> if  testResult == TestOutcomes.PASSED:
> testResultAsString = "Passed"
> elif testResult == TestOutcomes.FAILED :
> testResultAsString = "Failed"
> else:
> testResultAsString = "Aborted"
>
> But it would be much nicer if I had a function to covert to string as
> part of the TestOutcomes class. How would I implement this?
>
> Thanks,
>
> Barry

class TestOutcomes:
PASSED = 0
FAILED = 1
ABORTED = 2

def ToString(outcome):
if  outcome == TestOutcomes.PASSED:
   return "Passed"
elif outcome == TestOutcomes.FAILED :
   return "Failed"
else:
   return "Aborted"

ToString = staticmethod(ToString)

if __name__ == "__main__":
testResult = TestOutcomes.PASSED
testResultAsString = TestOutcomes.ToString(testResult)
print testResultAsString
print TestOutcomes.ToString(testResult)


Passed
Passed

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


Re: Enum class with ToString functionality

2007-09-10 Thread Bjoern Schliessmann
 [EMAIL PROTECTED] wrote:
> I have the following class -
> 
> class TestOutcomes:
> PASSED = 0
> FAILED = 1
> ABORTED = 2
> 
> plus the following code -
> 
> testResult = TestOutcomes.PASSED
> 
> testResultAsString
> if  testResult == TestOutcomes.PASSED:
> testResultAsString = "Passed"
> elif testResult == TestOutcomes.FAILED :
> testResultAsString = "Failed"
> else:
> testResultAsString = "Aborted"
> 
> But it would be much nicer if I had a function to covert to string
> as part of the TestOutcomes class. How would I implement this?

Why don't use the simple approach like this?

TEST_PASSED = "Passed"
TEST_FAILED = "Failed"
TEST_ABORTED = "Aborted"

In Python, no one forces you to put everything in classes.

If you are determined to use the class approach, use the __str__
method. It's called when you do str(instance).

Regards,


Björn

-- 
BOFH excuse #122:

because Bill Gates is a Jehovah's witness and so nothing can work on
St. Swithin's day.

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


Re: python 2.5 problems

2007-09-10 Thread Bjoern Schliessmann
Brian wrote:

> Finally deleted 2.2 and loaded 2.5 (see below), using
> the msi, on my XP partition. Having intermittent system
> crashes. 

The probability that this is not a coincidence is IMHO very, very
low. Looks like a deeper software or even hardware problem.

Regards,


Björn

-- 
BOFH excuse #353:

Second-system effect.

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


Re: less obvious "super"

2007-09-10 Thread Bjoern Schliessmann
Nagarajan wrote:
> class A :
> def __init__( self ):
> self.x  = 0
> 
> class B ( A ):
> def __init__( self, something ):
> # Use "super" construct here so that I can "inherit" x of
> # A
> self.y  = something
> 
> How should I use "super" so that I could access the variable "x"
> of A in B?

Since you're neither using new-style classes (inheriting from
object) nor multiple inheritance, better use the classic way:

class B(A):
def __init__(self, something):
A.__init__(self)
self.y  = something

IMHO, you could also benefit from looking at an OO python tutorial
since this is a standard approach.

Regards,


Björn

-- 
BOFH excuse #145:

Flat tire on station wagon with tapes.  ("Never underestimate the
bandwidth of a station wagon full of tapes hurling down the
highway" Andrew S. Tannenbaum) 

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


Re: Python syntax wart

2007-09-10 Thread Bjoern Schliessmann
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Bjoern
 
>> What's wrong with this:
>> 
>> for Link in GetEachRecord(
> 
> Then you're no longer showing the syntax structure in two
> dimensions.

Why should I want to? :)

BTW, this is the first time I read about "two dimensional syntax".
What's the benefit?

Regards,


Björn

-- 
BOFH excuse #292:

We ran out of dial tone and we're and waiting for the phone company
to deliver another bottle.

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


Re: Python syntax wart

2007-09-10 Thread Bjoern Schliessmann
Gabriel Genellina wrote:
> Do you know the Befunge language? Program flow is not lineal but
> along a 2D grid. There are variants over toroids and more bizarre
> surfaces, even using 3D.

Ah, I remember. Once read about it. Really cool idea :)

Regards,


Björn

-- 
BOFH excuse #149:

Dew on the telephone lines.

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


Re: Python syntax wart

2007-09-10 Thread Bjoern Schliessmann
TheFlyingDutchman wrote:

> It may be that a language that doesn't have a statement terminator
> (which can be end-of-line) needs a statement continuation symbol.

Which language could that be? I can hardly imagine making a complex
program out of one statement.

Regards,


Björn

-- 
BOFH excuse #147:

Party-bug in the Aloha protocol.

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


Re: Python syntax wart

2007-09-10 Thread Bjoern Schliessmann
Lawrence D'Oliveiro wrote:
> In message <[EMAIL PROTECTED]>, Marc 'BlackJack'

>> I see a tree structure here ...
> 
> Good, you're improving.

Tree structures can't, IMHO, be called two-dimensional. Although,
you can represent them with a two-dimensional graph. If the tree
gets more complex this can become very messy.
 
>> And this is also easily written that way in Python if you don't
>> insist on the line break after the ``if`` or can live with
>> backslashes.
> 
> Which is precisely the point.

You're the first person I see using a complete line just for an "if"
or "for". Is this for tuning the code line count?

Regards,


Björn

-- 
BOFH excuse #194:

We only support a 1200 bps connection.

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


easy_install only stable packages

2007-09-10 Thread exhuma.twn
easy_install is great. But it always automatically installs the
*latest* version. Even if that is beta,alpha (or however else the
developers call it). Is there no switch or possibility to disable this
feature? So that it installs the latest *stable* version?

I know that you can specify a specific version of a package with (for
example)

easy_install -U "SQLAlchemy==0.3.10"

This is undocumented on the web-page by the way ;)
But having to specify the version number for each package is quite
cumbersome.

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


Re: less obvious "super"

2007-09-10 Thread Francesco Guerrieri
On 9/10/07, Nagarajan <[EMAIL PROTECTED]> wrote:
>
>
>
> What's the difference b/w:
>  class A:
> and
>  class A ( object ):
>
> Thanks.
>

The first one declares an old-style class. The second one declares a new
style class.
It's better to use the new-style (always derive from object).

See
http://www.python.org/doc/newstyle.html
for further reading

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

Re: Python syntax wart

2007-09-10 Thread TheFlyingDutchman
On Sep 9, 11:20 pm, TheFlyingDutchman <[EMAIL PROTECTED]> wrote:
> It may be that a language that doesn't have a statement terminator
> (which can be end-of-line) needs a statement continuation symbol.
> (Excluding languages like Lisp that have parentheses everywhere).

Actually I guess Python does have a statement terminator - end-of-
line.
If you use end-of-line as your statement terminator it is difficult
and maybe impossible
to avoid a line-continuation character in those situations where you
don't want
an end-of-line to terminate your statement.

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


encoding latin1 to utf-8

2007-09-10 Thread Harshad Modi
hello ,
 I make one function for encoding latin1 to utf-8. but i think it is
not work proper.
plz guide me.

it is not get proper result . such that i got "Belgi�" using this
method, (Belgium)  :

import codecs
import sys
# Encoding / decoding functions
def encode(filename):
 file = codecs.open(filename, encoding="latin-1")
 data = file.read()
 file = codecs.open(filename,"wb", encoding="utf-8")
 file.write(data)

file_name=sys.argv[1]
encode(file_name)

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


Using a time duration to print out data where every 2 seconds is a pixel

2007-09-10 Thread cjt22
Hi there, I wonder if any of you could tell me the best way to going
about solving this little problem!

I have a list of Step objects containing their start and finish times
The steps are sorted so that they are in order of their step times
The start and finish times are in string format of "%H:%S:%M" all on
the same day

I want to be able print out the Steps as a visual representation so
that I can show
1. The order the steps started
2. The duration of the steps

i.e. a print out such as:


[a]
   [ b ]
  [ c   ]

so:
[ stepName ] is the duration of the Step (i.e. 1 pixel for every 2
seconds it lasted)
[  a ] started first so it is printed first,   [ b ] started x seconds
later so it is printed y pixels tabbed away form the side etc etc

Any help would be much appreciated.

Another related question is that I can't seem to do arithmetic when
the variables are in String format
of  %H:%M:%S or converted to type struct_time

i.e.
> startPoint = strptime(step.sTime, "%H:%S:%M")
> finishPoint = strptime(step.fTime, "%H:%S:%M")
> duration = finishPoint - startPoint

generates a error:
Type error: unsupport operand types for: 'time.struct_time' and
'time.struct_time'

trying to do time arithmetic when the times are stored in this format
as strings also fails so any help regarding any of this would be muhc
appreciated

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


Re: Python syntax wart

2007-09-10 Thread TheFlyingDutchman
On Sep 10, 4:45 am, Bjoern Schliessmann  wrote:
> TheFlyingDutchman wrote:
> > It may be that a language that doesn't have a statement terminator
> > (which can be end-of-line) needs a statement continuation symbol.
>
> Which language could that be? I can hardly imagine making a complex
> program out of one statement.
>
> Regards,
>
> Björn
>
> --
> BOFH excuse #147:
>
> Party-bug in the Aloha protocol.

Funny how I mentioned end-of-line but didn't include Python as one
those languages that used it.
I should have said "It may be that a language that doesn't have a
statement terminator
symbol, but instead uses end-of-line, can't avoid a statement
continuation symbol.

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


Re: less obvious "super"

2007-09-10 Thread Bruno Desthuilliers
Nagarajan a écrit :
(snip)
> What's the difference b/w:
>  class A:
> and
>  class A ( object ):
> 

The first one creates a 'classic' (aka 'old-style') class, IOW a class 
using the legacy object-model of Python < 2.2. The second one creates a 
'new-style' class using the new (well... since Python 2.2, which is not 
that new) and far more powerfull object model. Unless you need to 
support antique Python version, there's no good reason IMHO to use 
old-style classes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: encoding latin1 to utf-8

2007-09-10 Thread J. Clifford Dyer
On Mon, Sep 10, 2007 at 12:25:46PM -, Harshad Modi wrote regarding encoding 
latin1 to utf-8:
> Path: 
> news.xs4all.nl!newsspool.news.xs4all.nl!transit.news.xs4all.nl!newsgate.cistron.nl!xs4all!news.glorb.com!postnews.google.com!22g2000hsm.googlegroups.com!not-for-mail
> 
> hello ,
>  I make one function for encoding latin1 to utf-8. but i think it is
> not work proper.
> plz guide me.
> 
> it is not get proper result . such that i got "Belgi???" using this
> method, (Belgium)  :
> 
> import codecs
> import sys
> # Encoding / decoding functions
> def encode(filename):
>  file = codecs.open(filename, encoding="latin-1")
>  data = file.read()
>  file = codecs.open(filename,"wb", encoding="utf-8")
>  file.write(data)
> 
> file_name=sys.argv[1]
> encode(file_name)

Some tips to help you out. 

1.  Close your filehandles when you're done with them.
2.  Don't shadow builtin names.  Python uses the name file, and binding it to 
your own function can have ugly side effects that manifest down the road.

So perhaps try the following:

import codecs

def encode(filename):
read_handle = codecs.open(filename, encoding='latin-1')
data = read_handle.read()
read_handle.close()
write_handle = codecs.open(filename, 'wb', encoding='utf-8')
write_handle.write(data)
write_handle.close()

For what it's worth though, I couldn't reproduce your problem with either your 
code or mine.  This is not too surprising as all the ascii characters are 
encoded identically in utf-8 and latin-1.  So your program should output 
exactly the same file as it reads, if the contents of the file just read 
"Belgium"

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


Re: Setting stdout encoding

2007-09-10 Thread Fabio Zadrozny
>
>
> Does someone know if there's a way to explicitly set the stdout/stderr/
> stdin
> encoding that python should use?
>
> The encoding can be set using the C API for file objects - from Python
> code, use ctypes:
>
>
Yeap, but that would leave me with the original problem: I need to run a
script to run the original script I want to run...(and not being compatible
with other python implementations). Isn't there any way to set that
externally (like environment variable, args to the interpreter or anything
else like that)?

Thanks,

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

Re: Checking if elements are empty

2007-09-10 Thread Neil Cerutti
On 2007-09-08, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:
> Lawrence D'Oliveiro wrote:
> if y[0]:
 Not a good idea.
>>> Why not?
>> 
>> Because there is a situation where your version of the test
>> will fail even if the first element of y is non-null.
>
> Such as? Seriously people, a little more verbosity wouldn't
> hurt here. This isn't a mystery game.

>>> if "": True
...
>>> if 0: True
...
>>> if []: True
...
>>> if {}: True
...
>>> if None: True
...

That's may not be all the possibilities. Lots of Python objects
can evaluate to false in a boolean context.

-- 
Neil Cerutti
The Pastor would appreciate it if the ladies of the congregation would lend
him their electric girdles for the pancake breakfast next Sunday morning.
--Church Bulletin Blooper
-- 
http://mail.python.org/mailman/listinfo/python-list


Python-URL! - weekly Python news and links (Sep 10)

2007-09-10 Thread Gabriel Genellina
QOTW:  "Python is a revelation to me as a language that grows with the ability
of the programmer, which creates a multi-level community not too centered on
one-upmanship to nurture new talent." - John K Masters

"Python is a well designed language that focuses on a few simple ideas (name
semantics, dictionaries, simplicity of expression, trusting the programmer)
to make a surprisingly powerful and expressive language." - Steven Rumbalski


Why should I learn python?

http://groups.google.com/group/comp.lang.python/browse_thread/thread/e0ec3289a995997e/

Examining (the lack of) access specifiers in Python
and how "information hiding" is obtained

http://groups.google.com/group/comp.lang.python/browse_thread/thread/71ef60e2d3203702/

(FAQ) Two names referencing the same mutable object.  Pointers,
references, the Java model, and how things are different in C++. 

http://groups.google.com/group/comp.lang.python/browse_thread/thread/d05183ffe7d473c1/

The module operator (%) differs slightly from its C counterpart

http://groups.google.com/group/comp.lang.python/browse_thread/thread/a559c5ab2b8fe45a/

Several ways to generate unique identifiers

http://groups.google.com/group/comp.lang.python/browse_thread/thread/3db6fef289d93a9c/

Extending the Borg pattern to support distinct groups
of objects

http://groups.google.com/group/comp.lang.python/browse_thread/thread/8cc3b3bc924ed0f6/

exec and the local and global namespaces

http://groups.google.com/group/comp.lang.python/browse_thread/thread/16eaad6c94c4daed/

Generating "safe" filenames suitable for different
platforms.

http://groups.google.com/group/comp.lang.python/browse_thread/thread/aae0fbf0a370c761/




Everything Python-related you want is probably one or two clicks away in
these pages:

Python.org's Python Language Website is the traditional
center of Pythonia
http://www.python.org
Notice especially the master FAQ
http://www.python.org/doc/FAQ.html

PythonWare complements the digest you're reading with the
marvelous daily python url
 http://www.pythonware.com/daily
Mygale is a news-gathering webcrawler that specializes in (new)
World-Wide Web articles related to Python.
 http://www.awaretek.com/nowak/mygale.html
While cosmetically similar, Mygale and the Daily Python-URL
are utterly different in their technologies and generally in
their results.

Just beginning with Python?  This page is a great place to start:
http://wiki.python.org/moin/BeginnersGuide/Programmers

The Python Papers aims to publish "the efforts of Python enthusiats":
http://pythonpapers.org/
The Python Magazine is a technical monthly devoted to Python:
http://pythonmagazine.com

Readers have recommended the "Planet" sites:
http://planetpython.org
http://planet.python.org

comp.lang.python.announce announces new Python software.  Be
sure to scan this newsgroup weekly.

http://groups.google.com/groups?oi=djq&as_ugroup=comp.lang.python.announce

Python411 indexes "podcasts ... to help people learn Python ..."
Updates appear more-than-weekly:
http://www.awaretek.com/python/index.html

Steve Bethard continues the marvelous tradition early borne by
Andrew Kuchling, Michael Hudson, Brett Cannon, Tony Meyer, and Tim
Lesher of intelligently summarizing action on the python-dev mailing
list once every other week.
http://www.python.org/dev/summary/

The Python Package Index catalogues packages.
http://www.python.org/pypi/

The somewhat older Vaults of Parnassus ambitiously collects references
to all sorts of Python resources.
http://www.vex.net/~x/parnassus/

Much of Python's real work takes place on Special-Interest Group
mailing lists
http://www.python.org/sigs/

Python Success Stories--from air-traffic control to on-line
match-making--can inspire you or decision-makers to whom you're
subject with a vision of what the language makes practical.
http://www.pythonology.com/success

The Python Software Foundation (PSF) has replaced the Python
Consortium as an independent nexus of activity.  It has official
responsibility for Python's development and maintenance.
http://www.python.org/psf/
Among the ways you can support PSF is with a donation.
http://www.python.org/psf/donate.html

Kurt B. Kaiser publishes a weekly report on faults and patches.
http://www.google.com/groups?as_usubject=weekly%20python%20patch

Although unmaintained since 2002, the Cetus collection of Python
hyperlinks retains a few gems.
http://www.cetus-links.org/oo_python.html

Python FAQTS
http:

Re: encoding latin1 to utf-8

2007-09-10 Thread Harshad Modi
thx for Reply ,
but I need some basic knowledge . how to encoding ? which algorithm
use for that . bz my data has some special char , i have not
confidence   this function got proper result. i want to make my own
function  / script for encoding.

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


Re: general function for sorting a matrix

2007-09-10 Thread Xah Lee
hi, just a quick reply.

You are right, the python version i have is really terrible.

I'll look at your solution and possibly reply later.

Thanks for your code. It's great!

 Xah

On Aug 29, 9:40 am, Marc 'BlackJack' Rintsch <[EMAIL PROTECTED]> wrote:
> On Wed, 29 Aug 2007 08:47:27 -0700,XahLeewrote:
> > While reviewing this code, there's something interesting of note.
>
> > Namely, in my perl solution, the approach is drastically different
> > than the python version. Instead ofsortingby looping thru the
> >sortingdirectives, it parses the directives then generate the
> > complete sort code, then eval it in one shot. This is more of a pure
> > functional approach.
>
> I don't see why that is more functional.  After all you iterate in both
> versions through the directives.  In Perl to build the code, in Python to
> sort the list multiple times.  Here's a Python function that sorts the
> list just once:
>
> def sort_matrix(matrix, directives):
> tmp = [(column - 1, str if as_string else float, 1 if ascending else -1)
>for (column, as_string, ascending) in directives]
>
> def cmp_func(row_a, row_b):
> for column, convert_func, factor in tmp:
> result = cmp(convert_func(row_a[column]),
>  convert_func(row_b[column])) * factor
> if result:
> return result
> return 0
>
> matrix.sort(cmp=cmp_func)
>
> There's no return value as your reference implementation sorts in place
> too.
>
> Ciao,
> Marc 'BlackJack' Rintsch


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


Re: /dev/null as a file-like object, or logging to nothing

2007-09-10 Thread Sion Arrowsmith
Torsten Bronger  <[EMAIL PROTECTED]> wrote:
>Marc 'BlackJack' Rintsch writes:
>> `os.devnull`?
>Yes, but I wasn't really sure how portable it is, in particular, on
>Windows.

Windows has a NUL: device which behaves like /dev/null .
os.devnull is a wrapper around whatever the system-provided null
device is. I guess the documentation should reflect this, rather
than just mentioning POSIX and Mac OS 9 and requiring you to note
the "defined for all platforms" at the start of the section.

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

XML: SAX and XInclude

2007-09-10 Thread Laurent Pointal
[python 2.5, Linux Mandriva 2007.1]

Hello,

does anybody know about an XML parser usable with the sax API (xml.sax) 
and with XInclude feature support (directly or via hacks).

With specifying nothing (default parser), it simply transmit xinclude 
elements (i tried to call parser on included file but it seem to be 
waiting for a complete document with root element).

I tried libxml2, but failed with error (cf at the end).

I tried xmlproc, but it simply transmit xinclude elements too.

Thanks (its for PQRC - I've a first xhtml production which is not bad, 
when it'll be ok I will work on OpenDocument XML production - and  would 
like to split PQRC xml source into several files).


A+

Laurent.



Problem with libxml2:
[EMAIL PROTECTED] qrccompiler]$ python compiler.py
processing
Traceback (most recent call last):
   File "compiler.py", line 573, in 
 sys.exit(main(*sys.argv[1:]))
   File "compiler.py", line 569, in main
 handler.process_source()
   File "compiler.py", line 465, in process_source
 self.saxparser = make_parser(["libxml2"])
   File "/usr/lib/python2.5/site-packages/_xmlplus/sax/sax2exts.py", 
line 37,
in make_parser
 return XMLParserFactory.make_parser(parser_list)
   File "/usr/lib/python2.5/site-packages/_xmlplus/sax/saxexts.py", line 64,
in make_parser
 return self._create_parser(parser_name)
   File "/usr/lib/python2.5/site-packages/_xmlplus/sax/saxexts.py", line 43,
in _create_parser
 return drv_module.create_parser()
AttributeError: 'module' object has no attribute 'create_parser'

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


Re: encoding latin1 to utf-8

2007-09-10 Thread Carsten Haese
On Mon, 2007-09-10 at 13:11 +, Harshad Modi wrote:
> thx for Reply ,
> but I need some basic knowledge . how to encoding ? which algorithm
> use for that . bz my data has some special char , i have not
> confidence   this function got proper result. i want to make my own
> function  / script for encoding.

For basic knowledge about Unicode and character encodings, I highly
recommend amk's excellent Unicode How-To here:
http://www.amk.ca/python/howto/unicode

Once you've read and understood the How-To, I suggest you examine the
following:

1) Are you *sure* that the special characters in the original file are
latin-1 encoded? (If you're not sure, try to look at the file in a HEX
editor to see what character codes it uses for the special characters).
2) Are you sure that what you were using to look at the result file
understands and uses UTF-8 encoding? How are you telling it to use UTF-8
encoding?

Hope this helps,

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


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


Re: XML: SAX and XInclude

2007-09-10 Thread Stefan Behnel
Laurent Pointal wrote:
> does anybody know about an XML parser usable with the sax API (xml.sax)
> and with XInclude feature support (directly or via hacks).

Try lxml.etree.

http://codespeak.net/lxml/

http://codespeak.net/lxml/tutorial.html
http://codespeak.net/lxml/api.html#xinclude-and-elementinclude
http://codespeak.net/lxml/parsing.html#iterparse-and-iterwalk

It's not half as complicated as SAX, BTW.

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


uninstall

2007-09-10 Thread Milos Prudek
I run "make install" of Python 2.4.4 and now I discovered that I do not like 
the default placement of my install. The Makefile does not support 
an "uninstall" option.

Is there a way to uninstall Python compiled from sources?

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


Re: Python syntax wart

2007-09-10 Thread Jason
On Sep 8, 11:16 pm, Lawrence D'Oliveiro <[EMAIL PROTECTED]
central.gen.new_zealand> wrote:
> The one thing I don't like about Python syntax is using backslashes to
> continue lines. Yes, you can avoid them if you can include parentheses
> somehow, but this isn't always possible.
>
> Possible:
>
> if (
> quitting
> and
> len(client["to_write"]) == 0
> and
> len(client["read"]) + client["to_read"] == 0
> ) :
> close_client(client, "shutting down")
> #end if
>
> Not possible:
>
> for \
> Link \
> in \
> GetEachRecord \
>   (
> "links",
> ("from_episode",),
> "to_episode = %s",
> [EpisodeID],
> "order by when_created"
>   ) \
> :
> out.write \
>   (
> "Back to episode %d\n"
> %
> (
> LinkToMe({"ep" : Link["from_episode"]}),
> Link["from_episode"]
> )
>   )
> #end for

Python doesn't prevent you from writing ugly code, using poor variable
names, or doing other silly things.  The rules on indention require
that you are at least consistent on a given line.  That said, the
backslash simply continues the line, and I don't see why your (ugly,
IMO) code is impossible.  Here's some similarly schizophrenically
formatted code that I just tried:

>>> for \
... l\
... in \
... (\
... 1,
... 2,
... 3
... )\
... :
... print\
... "This is "\
... "poorly "\
... "formatted!",\
... l
...
This is poorly formatted! 1
This is poorly formatted! 2
This is poorly formatted! 3
>>>

Looks like it runs to me.  In general, I'd recommend that you avoid
such nonsense spacing and alignment, and use wrappers, generators, and
other Python constructs to help write more sensible code.

  --Jason

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


Re: Using a time duration to print out data where every 2 seconds is a pixel

2007-09-10 Thread A.T.Hofkamp
On 2007-09-10, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
> I want to be able print out the Steps as a visual representation so
> that I can show
> 1. The order the steps started
> 2. The duration of the steps
>
> i.e. a print out such as:
>
>
> [a]
>[ b ]
>   [ c   ]

This graph is commonly known as a Gantt Chart.
The most common use case of such charts is project planning.

The newest GNU plot program has support for these charts afaik.

> Another related question is that I can't seem to do arithmetic when
> the variables are in String format
> of  %H:%M:%S or converted to type struct_time

True (but you already detected that).

Either convert your struct_times to floats (time.mktime), or use a date/time
module specialized in computing with dates and times.

(I have seen references to a module called datetime, but I have never used such
a module so no idea what it is or where to get it).


Sincerely,
Albert
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a time duration to print out data where every 2 seconds is a pixel

2007-09-10 Thread Carsten Haese
On Mon, 2007-09-10 at 15:48 +0200, A.T.Hofkamp wrote:
>  I have seen references to a module called datetime, but I have never used 
> such
>  module so no idea what it is or where to get it.

You get it by using a non-ancient version of Python. It's been part of
the standard library since Python 2.3.

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


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


Re: uninstall

2007-09-10 Thread Paul Boddie
On 10 Sep, 15:45, Milos Prudek <[EMAIL PROTECTED]> wrote:
> I run "make install" of Python 2.4.4 and now I discovered that I do not like
> the default placement of my install. The Makefile does not support
> an "uninstall" option.
>
> Is there a way to uninstall Python compiled from sources?

If you're installing from sources "manually", you might want to
consider checkinstall to give you the option of an uninstall for those
software distributions which don't support "make uninstall":

http://www.asic-linux.com.mx/~izto/checkinstall/

I seem to recall at some point doing a checkinstall on one or more
programs, installing the resulting packages, then uninstalling them in
order to remove installed files. That might be one approach you could
take, although it obviously won't restore any files overwritten when
you originally installed Python. That said, Python tends to install
into /usr/local by default and is fairly conservative about where it
puts its files, so it's unlikely that anything was overwritten.

Paul

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


Re: Using a time duration to print out data where every 2 seconds is a pixel

2007-09-10 Thread Marc 'BlackJack' Rintsch
On Mon, 10 Sep 2007 15:48:44 +0200, A.T.Hofkamp wrote:

> (I have seen references to a module called datetime, but I have never used 
> such
> a module so no idea what it is or where to get it).

It's just an import away -- in the standard library.  :-)

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


printing list containing unicode string

2007-09-10 Thread Xah Lee
If i have a nested list, where the atoms are unicode strings, e.g.

# -*- coding: utf-8 -*-
ttt=[[u"→",u"↑"], [u"αβγ"],...]
print ttt

how can i print it without getting the u'\u1234' notation?
i.e. i want it print just like this: [[u"→"], ...]

I can of course write a loop then for each string use
"encode("utf-8")", but is there a easier way?

Thx.

  Xah
  [EMAIL PROTECTED]
∑ http://xahlee.org/

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

zlib

2007-09-10 Thread Milos Prudek
Although I have Python 2.5 with zlib in my Linux disto, I need to install my 
own Python (as most Zope developers do). Zope requires zlib. Python 2.4.4 
does not contain zlib. 

What is the correct procedure for installing zlib from source into Python?

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


How can I test 'warnings' from testsuite?

2007-09-10 Thread billiejoex
Hi there,
into a module of mine I 'warn' a message if a certain situation
occurs:


def add_anonymous_user(permissions=('r'):
  if 'w' in p:
  import warnings
  warnings.warn("it's not rencommended assigning 'w'
permission to anonymous user.", RuntimeWarning, stacklevel=2)


I'd like to test such event from test suite ("fail test if warn is not
raised") but don't know how.

Any suggestion?

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


Re: wxPython unexpected exit

2007-09-10 Thread kyosohma
Hi,

> Thanks for your help! It seems work!
> Another question: I create a progress bar, and on creation, it will be
> displayed,
> How can I invisualize it when later I no longer need it?

I think this is also a good way to use threads. Take a look at the
wxPython demo for the ProgressDialog code. Basically, you run it in a
loop and communicate with it every so often to tell it your progress.
When you're done, you can set some sentinel type value which would
kill the dialog.

I've never used it, but that's how I understand its usage. As I
mentioned, you should consider posting these types of questions to the
wxPython group: http://www.wxpython.org/maillist.php

Mike

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


Re: Checking if elements are empty

2007-09-10 Thread Chris Mellon
On 9/10/07, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-09-08, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:
> > Lawrence D'Oliveiro wrote:
> > if y[0]:
>  Not a good idea.
> >>> Why not?
> >>
> >> Because there is a situation where your version of the test
> >> will fail even if the first element of y is non-null.
> >
> > Such as? Seriously people, a little more verbosity wouldn't
> > hurt here. This isn't a mystery game.
>
> >>> if "": True
> ...
> >>> if 0: True
> ...
> >>> if []: True
> ...
> >>> if {}: True
> ...
> >>> if None: True
> ...
>
> That's may not be all the possibilities. Lots of Python objects
> can evaluate to false in a boolean context.
>

All of these except 0 and None will also return False if you check the
length. In fact, I am not aware of any builtin where len() will return
0, but it will be true in a boolean context.

If you're advocating being more specific in the hope of catching
errors, this is a pretty terrible example. The OP wasn't checking for
"null", whatever that means - he was checking for the empty string, in
a list known (or intended) to contain only strings. The simple boolean
check is totally appropriate.
-- 
http://mail.python.org/mailman/listinfo/python-list


How do I read and write to the same CSV file

2007-09-10 Thread Chris
I want to update one field in a row for a csv file. So far my code
looks something like this

cf_stream = open("\\config.csv","r+")
csv_file = csv.DictReader(cf_stream, ['Algorithm','LastModified'])

and then I know I can do something like this

for row in csv_file
  name = row["Algorithm"]
  date = row["LastModified"]

now what I want is something like this

if date == 0:
  date = os.getmtime()
  # now this is where I want to write into the row of the same csv
file but only updating that one field

How can I do this?

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


Re: How do I read and write to the same CSV file

2007-09-10 Thread Marc 'BlackJack' Rintsch
On Mon, 10 Sep 2007 07:27:46 -0700, Chris wrote:

> if date == 0:
>   date = os.getmtime()
>   # now this is where I want to write into the row of the same csv
> file but only updating that one field
> 
> How can I do this?

You can't.  Modifying text files with variable length lines is
"impossible" or at least not worth the trouble because if the replacement
line does not have the very same length, all lines after that changed line
have to be moved, i.e. rewritten anyway.

Write the rows to another file and modify the desired entry on the fly and
rename the temporary file to the source file's name afterward.

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


announcement: OpenOpt and GenericOpt

2007-09-10 Thread Alan Isaac
OpenOpt and GenericOpt
==

Introducing two new optimization packages.
OpenOpt and GenericOpt are 100% Python
with a single dependency: NumPy.
For more detail see below and also
https://projects.scipy.org/scipy/scikits/wiki/Optimization>

OpenOpt
---

OpenOpt is new open source optimization framework.
OpenOpt is released under the BSD license.

The primary author and current maintainer of
OpenOpt is Dmitrey Kroshko 
(Optimization Department, Cybernetics Institute, Ukrainian Science Academy)

OpenOpt goal: provide an open source alternative
to TomOpt TOMLAB (optimization framework for MATLAB)
and related optimization frameworks.  Currently OpenOpt
offers connections to a variety of open source solvers,
primarily for unconstrained optimization. (See below.)

OpenOpt provides provides connections a vraity of solvers,
including those in GenericOpt, which are included.
(Users will need to download other solvers;
we provide URLs for the downloads.)


GenericOpt
--

GenericOpt is a toolkit for building specialized optimizers.
GenericOpt is released under the BSD license.

The primary author and current maintainer of GenericOpt is
Matthieu Brucher 

GenericOpt goal: provide an open source, extensible
toolit for "component-wise" construction of specialized
optimizers.  GenericOpt allows users who want detailed control to construct
their own solvers by choosing among a variety of algorithm components
(currently, most choices are among step and line-search algorithms.)

Usage: see Matthieu Brucher's tutorial 
https://projects.scipy.org/scipy/scikits/wiki/Optimization/tutorial>.  

Limitation: currently GenericOpt provides only unconstrained solvers. 

SciKits
---

The SciPy project is developing a collection of open source packages for
scientific computing which are allowed to have more dependencies and
more varied licenses than those allowed for SciPy proper.
In contrast to SciPy, the related scikits may host any 
OSI-approved licensed code.  See
https://projects.scipy.org/scipy/scikits/>

OpenOpt and GenericOpt are available together as a
SciPy scikit.  The provides a unified optimization
framework along with a collection of solvers.
However, neither depends on the other.


OpenOpt Details
---

Key feature: a unified calling interface for all solvers,
a variety of pure Python solvers, and connections to 
numerous external solvers.

Example::

from scikits.openopt import NLP
p = NLP(lambda x: (x-1)**2, 4)
r = p.solve('ralg')

In this example,
the objective function is (x-1)^2,
the start point is x0=4,
and 'ralg' specifies the name of solver involved.

See much more detailed example here 
http://projects.scipy.org/scipy/scikits/browser/trunk/openopt/scikits/openopt/examples/nlp_ALGENCAN.py>
 




OpenOpt Connected External Solvers
--

Non-linear problems (NLP)
~

- ALGENCAN  
  (GPL)
- lincher (BSD) (all types of constraints and 1st derivatives),
- ralg (BSD) (currently unconstrained only)
- scipy_tnc and scipy_lbfgsb (box-bounded, requires scipy 
  installed, BSD)

Non-smooth problems (NSP)
~

- ralg (BSD)
- ShorEllipsoid (BSD)
  (for small-scale problems with nVars = 1..10, former for 
  medium-scaled problems with nVars = 1...1000, requires r0)
  
Both are unconstrained for now.


Linear problems (LP)


- lp_solve  (LGPL)
- glpk  (GPL)
- CVXOPT  (GPL) 
  (currently glpk requires CVXOPT installed)


Mixed-integer problems (MILP)
~

- lp_solve  


Quadratic problems (QP)
~~~
- CVXOPT  (GPL) 
  (please note - NLP lincher solver requires QP solver, and 
  the only one for now is CVXOPT one)

Here you can look at examples for NLP 
,
 
NSP 
,
 
QP 
,
 
LP 
,
 
MILP 

 


Acknowledgements


Development of OpenOpt was supported by Google through the 
Google Summer of Code (GSoC) program, with Alan G. Isaac
as mentor.  Additonal mentorship was provided by Jarrod Milman. 
Debts to the SciPy community are many, but we would particularly
like to thank Nils Wagner.


Appeal
==

The primary author and current maintainer of OpenOpt is Dmitrey Kroshko.  The
primary author and current 

shared memory pointer

2007-09-10 Thread Tim
Hello Everyone,

I am getting shared memory in python using the following.

szName = c_char_p(name)
hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE,
None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName)
if (hMapObject == 0):
print "OpenKey: Could not open name file mapping object"
raise WinError()

self.pData = windll.kernel32.MapViewOfFile(hMapObject,
   FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE)

This seems to work OK. How do I get to the data in self.pData? It is
suppose to be an array of floats. I think MapViewOfFile returns a
point to the data. Here is what I tried.

current_time = 45.55
memcpy( current_time, self.pData, 4 )

but I get an error:

ArgumentError: argument 1: : Don't know
how to convert parameter 1

I need to get my floating point array casted from the self.pData. Any
help would be appreciated!

Thanks
Tim

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


Re: Using a time duration to print out data where every 2 seconds is a pixel

2007-09-10 Thread cjt22
Thanks however I am still having a problem using the time module for
arithmetic

My string times are of values such as 09:55:17

and I have code such as:

>from time import *
>startPoint = strptime(step.sTime, "%H:%S:%M")
>finishPoint = strptime(step.fTime, "%H:%S:%M")

>duration = mktime(startPoint) - mktime(finishPoint)

but it generates the error

>OverflowError: mktime argument out of range

Cheers

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


Re: How do I read and write to the same CSV file

2007-09-10 Thread Steven D'Aprano
On Mon, 10 Sep 2007 07:27:46 -0700, Chris wrote:

> I want to update one field in a row for a csv file. So far my code looks
> something like this
> 
> cf_stream = open("\\config.csv","r+") 
> csv_file = csv.DictReader(cf_stream, ['Algorithm','LastModified'])
> 
> and then I know I can do something like this
> 
> for row in csv_file
>   name = row["Algorithm"]
>   date = row["LastModified"]
> 
> now what I want is something like this
> 
> if date == 0:
>   date = os.getmtime()
>   # now this is where I want to write into the row of the same csv
> file but only updating that one field
> 
> How can I do this?

With difficulty unless the bytes you are writing to are exactly the same 
length as the bytes that were there before.

In my opinion, unless you're writing a file with fixed-length fields, and 
maybe not even then, give up the dream of writing directly in place. 
Unless your file is HUGE, the chances are that trying to modify it in 
place is not only harder work but also slower.

But if you insist... you might be able to use cf_stream.seek() to move to 
the current position in the file, then write the bytes you want. How do 
you find the current position? Black magic or voodoo might help. 
Otherwise you might count every character of every line up to the field 
you want. Don't forget delimiters, quote marks and newlines. Good luck.



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


Re: shared memory pointer

2007-09-10 Thread Tim Golden
Tim wrote:
> Hello Everyone,
> 
> I am getting shared memory in python using the following.
> 
> szName = c_char_p(name)
> hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE,
> None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName)
> if (hMapObject == 0):
> print "OpenKey: Could not open name file mapping object"
> raise WinError()
> 
> self.pData = windll.kernel32.MapViewOfFile(hMapObject,
>FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE)

Without answering your question directly, why not use
the stdlib mmap module, which does exactly this for
you behind the scenes?

Docs - http://docs.python.org/lib/module-mmap.html
Example - http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413807

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


PyConUK 2007

2007-09-10 Thread Tim Golden
For those who don't follow the UK Python scene, we've just
all come back from a *fantastic* weekend in Birmingham: the
very first PyCon UK. Terrific kudos to John Pinner and the
West Midlands Python team who made it all happen without
any serious mishaps, including registration with badges,
T-shirts etc. for 200 people, a sit-down dinner for 150,
dozens of speakers, lightning talks and keynote speakers,
a flawless WLAN, suitably cheap hotel accomodation, and
a great atmosphere.

The Blogs and photos are starting to appear:

   http://www.pyconuk.org/community/BlogsAndPhotos

and although it was the UK conference, you may see
quite a few European faces in there and even one
or two from the States and further afield. Look
forward to seeing you there next year!

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


Re: printing list containing unicode string

2007-09-10 Thread Carsten Haese
On Mon, 2007-09-10 at 06:59 -0700, Xah Lee wrote:
> If i have a nested list, where the atoms are unicode strings, e.g.
> 
> # -*- coding: utf-8 -*-
> ttt=[[u"→",u"↑"], [u"αβγ"],...]
> print ttt
> 
> how can i print it without getting the u'\u1234' notation?
> i.e. i want it print just like this: [[u"→"], ...]
> 
> I can of course write a loop then for each string use
> "encode("utf-8")", but is there a easier way?

It's not quite clear why you want to do this, but this is how you could
do it:

print repr(ttt).decode("unicode_escape").encode("utf-8")

However, I am getting the impression that this is a "How can I use 'X'
to achieve 'Y'?" question instead of the preferable "How can I achieve
'Y'?" type of question. In other words, printing the repr() of a list
might not be the best solution to reach the actual goal, which you have
not stated.

HTH,

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


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

Re: How can I test 'warnings' from testsuite?

2007-09-10 Thread [EMAIL PROTECTED]
On Sep 10, 7:08 am, billiejoex <[EMAIL PROTECTED]> wrote:
> Hi there,
> into a module of mine I 'warn' a message if a certain situation
> occurs:
>
> def add_anonymous_user(permissions=('r'):
>   if 'w' in p:
>   import warnings
>   warnings.warn("it's not rencommended assigning 'w'
> permission to anonymous user.", RuntimeWarning, stacklevel=2)
>
> I'd like to test such event from test suite ("fail test if warn is not
> raised") but don't know how.
>
> Any suggestion?



You can (temporarily) change warnings to exceptions
for the purposes of testing; see filterwarnings in
the warnings module.  E.g.,

import warnings
import unittest

def foo():
warnings.warn("Foo", RuntimeWarning, stacklevel=2)

class testWarn(unittest.TestCase):
def setUp(self):
warnings.filterwarnings("error")
def test_1(self):
self.assertRaises(RuntimeWarning, foo)
def tearDown(self):
warnings.resetwarnings()

s = unittest.TestSuite()
s.addTest(unittest.makeSuite(testWarn))

if __name__ == '__main__':
import sys
sys.argv.append('-v')
unittest.TextTestRunner(verbosity=2).run(s)


--
Hope this helps,
Steven

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


Re: shared memory pointer

2007-09-10 Thread Tim
On Sep 10, 10:11 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> Tim wrote:
> > Hello Everyone,
>
> > I am getting shared memory in python using the following.
>
> > szName = c_char_p(name)
> > hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE,
> > None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName)
> > if (hMapObject == 0):
> > print "OpenKey: Could not open name file mapping object"
> > raise WinError()
>
> > self.pData = windll.kernel32.MapViewOfFile(hMapObject,
> >FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE)
>
> Without answering your question directly, why not use
> the stdlib mmap module, which does exactly this for
> you behind the scenes?
>
> Docs -http://docs.python.org/lib/module-mmap.html
> Example -http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413807
>
> TJG

I saw the mmap function in the shared memory example. I had some
concern with my large memory size being written to the disk drive. I
though it might slow down my application. The reason I am writting
this new code is because the existing method using a file. I thought
shared memory would be much faster.

I have tried using the memcpy and addresses, casting, etc. Is there a
way to use memcpy with the pData returned by MapViewOfFile()?

Thanks
Tim


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


Re: Checking if elements are empty

2007-09-10 Thread Neil Cerutti
On 2007-09-10, Chris Mellon <[EMAIL PROTECTED]> wrote:
> On 9/10/07, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> On 2007-09-08, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:
>> > Lawrence D'Oliveiro wrote:
>> > if y[0]:
>>  Not a good idea.
>> >>> Why not?
>> >>
>> >> Because there is a situation where your version of the test
>> >> will fail even if the first element of y is non-null.
>> >
>> > Such as? Seriously people, a little more verbosity wouldn't
>> > hurt here. This isn't a mystery game.
>>
>> >>> if "": True
>> ...
>> >>> if 0: True
>> ...
>> >>> if []: True
>> ...
>> >>> if {}: True
>> ...
>> >>> if None: True
>> ...
>>
>> That's may not be all the possibilities. Lots of Python objects
>> can evaluate to false in a boolean context.
>
> All of these except 0 and None will also return False if you
> check the length. In fact, I am not aware of any builtin where
> len() will return 0, but it will be true in a boolean context.
>
> If you're advocating being more specific in the hope of
> catching errors, this is a pretty terrible example. The OP
> wasn't checking for "null", whatever that means - he was
> checking for the empty string, in a list known (or intended) to
> contain only strings. The simple boolean check is totally
> appropriate.

Agreed; but I prefer 'if y[0] == ""', absent more context and
better names.

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


Re: How can I test 'warnings' from testsuite?

2007-09-10 Thread billiejoex
On 10 Set, 17:15, "[EMAIL PROTECTED]"
<[EMAIL PROTECTED]> wrote:
> On Sep 10, 7:08 am, billiejoex <[EMAIL PROTECTED]> wrote:
>
> > Hi there,
> > into a module of mine I 'warn' a message if a certain situation
> > occurs:
>
> > def add_anonymous_user(permissions=('r'):
> >   if 'w' in p:
> >   import warnings
> >   warnings.warn("it's not rencommended assigning 'w'
> > permission to anonymous user.", RuntimeWarning, stacklevel=2)
>
> > I'd like to test such event from test suite ("fail test if warn is not
> > raised") but don't know how.
>
> > Any suggestion?
>
> You can (temporarily) change warnings to exceptions
> for the purposes of testing; see filterwarnings in
> the warnings module.  E.g.,
>
> import warnings
> import unittest
>
> def foo():
> warnings.warn("Foo", RuntimeWarning, stacklevel=2)
>
> class testWarn(unittest.TestCase):
> def setUp(self):
> warnings.filterwarnings("error")
> def test_1(self):
> self.assertRaises(RuntimeWarning, foo)
> def tearDown(self):
> warnings.resetwarnings()
>
> s = unittest.TestSuite()
> s.addTest(unittest.makeSuite(testWarn))
>
> if __name__ == '__main__':
> import sys
> sys.argv.append('-v')
> unittest.TextTestRunner(verbosity=2).run(s)
>
> --
> Hope this helps,
> Steven

This is exactly what I was searching for.
Thank you very much.

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


Re: Python syntax wart

2007-09-10 Thread Steven W. Orr
On Monday, Sep 10th 2007 at 08:34 -, quoth Marc 'BlackJack' Rintsch:

=>On Mon, 10 Sep 2007 20:19:08 +1200, Lawrence D'Oliveiro wrote:
=>
=>> In message <[EMAIL PROTECTED]>, Marc 'BlackJack' Rintsch
=>> wrote:
=>> 
=>>> I see a tree structure here ...
=>> 
=>> Good, you're improving.
=>
=>Thanks.
=>
=>>> ... but still no table. 
=>> 
=>> Who said anything about a table?
=>
=>Me. If that statement is 2D I expected to see a table structure.  And I
=>don't mean that the source code itself is arranged in lines and columns
=>but that the so called *2D statement* can be seen as table.
=>
=>>> And this is also easily written that way in Python if you don't insist on
=>>> the line break after the ``if`` or can live with backslashes.
=>> 
=>> Which is precisely the point.
=>
=>Then is the lack of curly braces also a syntax wart.  Maybe you should
=>switch to a different language or write a preprocessor.

C'mon   givethe
poorguy
a   break.

Whatdid
I   just
say ?

-- 
Time flies like the wind. Fruit flies like a banana. Stranger things have  .0.
happened but none stranger than this. Does your driver's license say Organ ..0
Donor?Black holes are where God divided by zero. Listen to me! We are all- 000
individuals! What if this weren't a hypothetical question?
steveo at syslang.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Using a time duration to print out data where every 2 seconds is a pixel

2007-09-10 Thread cjt22
On Sep 10, 3:57 pm, [EMAIL PROTECTED] wrote:
> Thanks however I am still having a problem using the time module for
> arithmetic
>
> My string times are of values such as 09:55:17
>
> and I have code such as:
>
> >from time import *
> >startPoint = strptime(step.sTime, "%H:%S:%M")
> >finishPoint = strptime(step.fTime, "%H:%S:%M")
> >duration = mktime(startPoint) - mktime(finishPoint)
>
> but it generates the error
>
> >OverflowError: mktime argument out of range
>
> Cheers

Perhaps I need to import the datetime module?

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


Re: Checking if elements are empty

2007-09-10 Thread Chris Mellon
On 9/10/07, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> On 2007-09-10, Chris Mellon <[EMAIL PROTECTED]> wrote:
> > On 9/10/07, Neil Cerutti <[EMAIL PROTECTED]> wrote:
> >> On 2007-09-08, Wildemar Wildenburger <[EMAIL PROTECTED]> wrote:
> >> > Lawrence D'Oliveiro wrote:
> >> > if y[0]:
> >>  Not a good idea.
> >> >>> Why not?
> >> >>
> >> >> Because there is a situation where your version of the test
> >> >> will fail even if the first element of y is non-null.
> >> >
> >> > Such as? Seriously people, a little more verbosity wouldn't
> >> > hurt here. This isn't a mystery game.
> >>
> >> >>> if "": True
> >> ...
> >> >>> if 0: True
> >> ...
> >> >>> if []: True
> >> ...
> >> >>> if {}: True
> >> ...
> >> >>> if None: True
> >> ...
> >>
> >> That's may not be all the possibilities. Lots of Python objects
> >> can evaluate to false in a boolean context.
> >
> > All of these except 0 and None will also return False if you
> > check the length. In fact, I am not aware of any builtin where
> > len() will return 0, but it will be true in a boolean context.
> >
> > If you're advocating being more specific in the hope of
> > catching errors, this is a pretty terrible example. The OP
> > wasn't checking for "null", whatever that means - he was
> > checking for the empty string, in a list known (or intended) to
> > contain only strings. The simple boolean check is totally
> > appropriate.
>
> Agreed; but I prefer 'if y[0] == ""', absent more context and
> better names.
>

Probably should use u"" if you're going to take that route, as this
will fail spuriously if y[0] contains a unicode string that can't be
implicitly converted to ascii. Personally, I prefer the boolean check
and I'll let operations fail elsewhere if there's a type mismatch.
-- 
http://mail.python.org/mailman/listinfo/python-list


Silent SaveAs when using the Excel win32com module

2007-09-10 Thread Chris
I'm trying to create an excel file which will act as a log, however I
want to overwrite the file if it exists.

Looking at the SaveAs method I can't find anything that would allow
it. I don't want the prompt to appear to ask whether to replace the
file or not. I just want to replace it without thinking.

Thanks in advance.

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


Re: shared memory pointer

2007-09-10 Thread Tim
On Sep 10, 10:11 am, Tim Golden <[EMAIL PROTECTED]> wrote:
> Tim wrote:
> > Hello Everyone,
>
> > I am getting shared memory in python using the following.
>
> > szName = c_char_p(name)
> > hMapObject = windll.kernel32.CreateFileMappingA(INVALID_HANDLE_VALUE,
> > None, PAGE_READONLY, 0, TABLE_SHMEMSIZE, szName)
> > if (hMapObject == 0):
> > print "OpenKey: Could not open name file mapping object"
> > raise WinError()
>
> > self.pData = windll.kernel32.MapViewOfFile(hMapObject,
> >FILE_MAP_ALL_ACCESS, 0, 0, TABLE_SHMEMSIZE)
>
> Without answering your question directly, why not use
> the stdlib mmap module, which does exactly this for
> you behind the scenes?
>
> Docs -http://docs.python.org/lib/module-mmap.html
> Example -http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/413807
>
> TJG

I reviewed the mmap function and I have a question. In the example
code below, what is the connection between the data in shared memory
and the mmap function. The fileno is zero. Why is it zero? The size
makes sense because there is 256 bytes in shared memory. The tag is
MyFileMappingObject. This tag does not have anything in common with
the shared memory. How can mmap point to any data in shared memory?
There is no coorelation.


pBuf = windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS,
0, 0, SHMEMSIZE)
if (pBuf == 0):
print "Could not map view of file"
raise WinError()
else:
memcpy = cdll.msvcrt.memcpy
memcpy(pBuf, szMsg, len(szMsg))

shmem = mmap.mmap(0, 256, "MyFileMappingObject", mmap.ACCESS_WRITE)
shmem.write("Message from Python process")



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


Re: Silent SaveAs when using the Excel win32com module

2007-09-10 Thread Tim Golden
Chris wrote:
> I'm trying to create an excel file which will act as a log, however I
> want to overwrite the file if it exists.
> 
> Looking at the SaveAs method I can't find anything that would allow
> it. I don't want the prompt to appear to ask whether to replace the
> file or not. I just want to replace it without thinking.

   xl.DisplayAlerts = 0

where xl is the Application object.

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


Re: Silent SaveAs when using the Excel win32com module

2007-09-10 Thread Chris
On Sep 10, 11:57 am, Chris <[EMAIL PROTECTED]> wrote:
> I'm trying to create an excel file which will act as a log, however I
> want to overwrite the file if it exists.
>
> Looking at the SaveAs method I can't find anything that would allow
> it. I don't want the prompt to appear to ask whether to replace the
> file or not. I just want to replace it without thinking.
>
> Thanks in advance.

Googling around I found that a way around this is to just delete the
file before you save (if it exists)... any other solutions?

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


Re: shared memory pointer

2007-09-10 Thread MC
Hi!

I agree ; on windows mmap use Memory-Mapped-file, who use virtual 
memory. And shared memory use physical memory.

The difference is OS an not Python




-- 
@-salutations

Michel Claveau


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


RE: Silent SaveAs when using the Excel win32com module

2007-09-10 Thread Hamilton, William
> From: Chris
> 
> I'm trying to create an excel file which will act as a log, however I
> want to overwrite the file if it exists.
> 
> Looking at the SaveAs method I can't find anything that would allow
> it. I don't want the prompt to appear to ask whether to replace the
> file or not. I just want to replace it without thinking.
> 
> Thanks in advance.


Check if the file exists and delete it before saving the new one.
--
-Bill Hamilton
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: shared memory pointer

2007-09-10 Thread Tim Golden
Tim wrote:
> I reviewed the mmap function and I have a question. In the example
> code below, what is the connection between the data in shared memory
> and the mmap function. The fileno is zero. Why is it zero? The size
> makes sense because there is 256 bytes in shared memory. The tag is
> MyFileMappingObject. This tag does not have anything in common with
> the shared memory. How can mmap point to any data in shared memory?
> There is no coorelation.
> 
> 
> pBuf = windll.kernel32.MapViewOfFile(hMapObject, FILE_MAP_ALL_ACCESS,
> 0, 0, SHMEMSIZE)
> if (pBuf == 0):
> print "Could not map view of file"
> raise WinError()
> else:
> memcpy = cdll.msvcrt.memcpy
> memcpy(pBuf, szMsg, len(szMsg))
> 
> shmem = mmap.mmap(0, 256, "MyFileMappingObject", mmap.ACCESS_WRITE)
> shmem.write("Message from Python process")

Your question seems a little strange. You appear to be creating
a memory mapping via ctypes and then expecting the Python mmap
module to know about it. Of course it doesn't. What you do is
to create two mmap mappings with the same tag name which --
under the covers -- point to the same shared memory. I just
tried it ad-hoc in two interpreters and it works fine.

I admit I am absolutely no expert on this area. My initial
suggestion was simply because your question triggered a
memory of what I'd seen elsewhere. Have a look at this
thread from a few years ago to see if it clarifies:

   http://www.thescripts.com/forum/thread25421.html

(although what it -- and your question -- clearly do clarify
is a lack of clarity in the documentation!)

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


Question about PEP 8

2007-09-10 Thread Laszlo Nagy

 Hi All,

Here is what I read in PEP 8:

> Package and Module Names
>
>   Modules should have short, all-lowercase names.  Underscores can be used
>   in the module name if it improves readability.  Python packages should
>   also have short, all-lowercase names, although the use of underscores is
>   discouraged.
>
>   Since module names are mapped to file names, and some file systems are
>   case insensitive and truncate long names, it is important that module
>   names be chosen to be fairly short -- this won't be a problem on Unix,
>   but it may be a problem when the code is transported to older Mac or
>   Windows versions, or DOS.
>
>   When an extension module written in C or C++ has an accompanying Python
>   module that provides a higher level (e.g. more object oriented)
>   interface, the C/C++ module has a leading underscore (e.g. _socket).

Here is my problem. There is ConfigParser, StringIO, Queue, HTMLParser  
etc. They are all part of the standard library. Most of these are 
modules with only a "main class" defined. ConfigParser module contains 
ConfigParser class, Queue module contains Queue class etc. Should I use 
CapWords for the module (and file) name or not? E.g. should I

from mess.wxmegaeidgets.GenericDialog import GenericDialog

or

from mess.wxmegaeidgets.genericdialog import GenericDialog


(suppose that the module contains only the GenericDialog class. BTW, 
will Py3K change the standard library names in order to follow PEP 8?)

I also have problems with function and method names:

>  Function Names
>
>   Function names should be lowercase, with words separated by underscores
>   as necessary to improve readability.
>
>   mixedCase is allowed only in contexts where that's already the
>   prevailing style (e.g. threading.py), to retain backwards compatibility.

Great, but what if I subclass wx widgets? They all have CapWords. 
(wx.Window.ShowModal, wx.Window.Bind etc.) I must use CapitalizedWords 
for method names because sometimes I have to override inherited methods, 
and it is not possible to change their name. Where should be the limit? 
If I create a composite widget then should I use lowercase and 
underscores? If I create a class that is not itself a widget, but works 
with widgets? The PEP defines the "theoretically good" coding style, but 
what is the correct style in an environment where you have third party 
libraries that are not following the PEP?

Thanks,

   Laszlo

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


Re: Checking if elements are empty

2007-09-10 Thread Neil Cerutti
On 2007-09-10, Chris Mellon <[EMAIL PROTECTED]> wrote:
> On 9/10/07, Neil Cerutti <[EMAIL PROTECTED]> wrote:
>> Agreed; but I prefer 'if y[0] == ""', absent more context and
>> better names.
>
> Probably should use u"" if you're going to take that route, as
> this will fail spuriously if y[0] contains a unicode string
> that can't be implicitly converted to ascii. Personally, I
> prefer the boolean check and I'll let operations fail elsewhere
> if there's a type mismatch.

I have a quibble not with the functionality of the boolean check,
but with its expressiveness. if y[0] == "" expresses more, i.e.,
that I expect y[0] to contain a Python byte string.

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


Re: Modul (%) in python not like in C?

2007-09-10 Thread [EMAIL PROTECTED]
On Sep 10, 1:38 am, Dennis Lee Bieber <[EMAIL PROTECTED]> wrote:
> On Sun, 09 Sep 2007 22:57:24 -0700, "[EMAIL PROTECTED]"
> <[EMAIL PROTECTED]> declaimed the following in comp.lang.python:
>
>
>
> > But, in general, doesn't (-11,-4) also satisfy
> >   x = y *   a +   b
> > -70 = 6 * -11 + (-4)?
>
> > Do you overpay your car loans and wait for a refund?
>
> As I stated, integer division and modulo are linked... Which is
> "correct" is probably dependent upon the language specifications.

I didn't make an opinion on which was "correct".

> Either
> method allows one to recover the original value from the output of
> divmod.

My point was the need to satisfy x = y * a + b doesn't
explain WHY divmod(-70,6) returns (-12,2) instead of (-11,-4).

>
> Whether that works in the way you intend is a different matter -- my
> car loans usually have interest factors which are applied per payment by
> payment date, so using modulo (or divmod) is not applicable, one must
> actually build the table of payments one at a time (especially since the
> automatic payments taken from paychecks gets "corrupted" during
> holidays, when paychecks are issued a day or two earlier than normal,
> meaning less interest charges during that period and more applied to
> principle; with more on interest the following week, and less on
> interest).

Ok, poor example. Suppose instead we are slicing a 70 character string
from the right. We certainly CAN'T have 6 12-letter slices, can we?
But we can have 6 11-letter slices with 4 characters left over.

And there are probably examples where (-12,2) would make more sense,
although I can't think of one at the moment.

Again, I'm not saying (-12,2) is wrong, just that the explanation
why it's (-12,2) is wanting since there are cases where (-11,-4)
makes more sense.

> --
> WulfraedDennis Lee Bieber   KD6MOG
> [EMAIL PROTECTED] [EMAIL PROTECTED]
> HTTP://wlfraed.home.netcom.com/
> (Bestiaria Support Staff:   [EMAIL PROTECTED])
> HTTP://www.bestiaria.com/


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


Re: /dev/null as a file-like object, or logging to nothing

2007-09-10 Thread Gabriel Genellina
En Sat, 08 Sep 2007 14:42:14 -0300, Torsten Bronger  
<[EMAIL PROTECTED]> escribi�:

>> `os.devnull`?
>
> Yes, but I wasn't really sure how portable it is, in particular, on
> Windows.  So does
>
> open(os.devnull, "w").write("Schallalla")
>
> work on Windows like on Unix?

Yes. os.devnull=='nul' on Windows.

-- 
Gabriel Genellina

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

C API (embedded Python): How to get and set named variables

2007-09-10 Thread mrabens
>From the C API (I'm using Python embedded), how can I get and set the
value of named variables?  Right now, I'm using hacks like
PyRun_SimpleString("foobar = 12\n"), but I'd really like to access the
named objects directly.

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


  1   2   >