Re: Why is there no platform independent way of clearing a terminal?

2010-08-01 Thread Mark Lawrence

On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:

In message, Mark
Lawrence wrote:


Personally I find double clicking on an msi file rather easier.


Easier than apt-get dist-upgrade?


I'm sorry but I only do English, could you please translate. :)

Mark Lawrence.

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


Re: Docstrings and PEP 3174

2010-08-01 Thread Steven D'Aprano
On Sat, 31 Jul 2010 19:52:05 -0700, Carl Banks wrote:

> PEP 3174 got me to thinking.
> 
> There is now a subdirectory to deposit as many *.pyc files as you want
> without cluttering the source directory (never mind the default case). 
> Which means you can pretty much write files with impunity.
> 
> So I was wondering: what about a separate file just for docstrings.

I'm not sure I understand what you mean by that? Do you mean that, when 
writing code for a function, you would open a second file for the 
docstring? If so, a big -INFINITY from me. The biggest advantage of 
docstrings is that the documentation is *right there* with the function 
when reading/writing code. If you're suggesting we should write them in 
another file, no thank you.

If you mean a runtime optimization with no change to the source file, 
then maybe, tell me more. What I *think* you mean is that the coder would 
write:

def spam(*args):
"docs go here"
pass

as normal, but when it is compiled and loaded into memory, the docstring 
itself was *not* loaded until needed.

If so, then I think you'd need to demonstrate significant practical 
benefit to make up for the complexity. I imagine Python-Dev will be very 
dubious.


> __doc__ would become a descriptor that loads the docstring from the file
> whenever it is referenced.

"The file" being the source file, or a separate docstring file, or a 
temporary file generated by the compiler, or... ?


> The vast majority of the time docstrings
> just take up memory and do nothing, so why not lazy load those things?

A guarded and provisional +0 on that. +1 if you can demonstrate real 
performance (memory or speed) gains.



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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-01 Thread Lawrence D'Oliveiro
In message , Mark 
Lawrence wrote:

> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:
>
>> In message, Mark
>> Lawrence wrote:
>>
>>> Personally I find double clicking on an msi file rather easier.
>>
>> Easier than apt-get dist-upgrade?
> 
> I'm sorry but I only do English, could you please translate. :)

I run Debian Unstable, which has new goodies coming out on a weekly basis. 
The last time I checked for updates, there were over 500 packages I had 
installed for which updates were available. It only took a command like the 
above to upgrade them all.

How many .msi files would you have to click on to achieve the Windows 
equivalent?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-01 Thread Steven D'Aprano
On Sat, 31 Jul 2010 13:29:25 +, Brian Victor wrote:

> Steven D'Aprano wrote:
>> On Sat, 31 Jul 2010 14:25:39 +1200, Gregory Ewing wrote:
>>
>>> Steven D'Aprano wrote:
>>> 
   A
  / \
 C   B
  \ /
   D
  / \
 E   F
 
 Yes, a super call might jog left from C to B, but only when being
 called from one of the lower classes D-F. That's still an upwards
 call relative to the originator, not sidewards.
>>> 
>>> But it's not an upward call relative to the class mentioned in the
>>> super() call, which is why I say it's misleading.
>>
>> Which class would that be?
>>
>> I think I'm going to need an example that demonstrates what you mean,
>> because I can't make heads or tails of it. Are you suggesting that a
>> call to super(C, self).method() from within C might call
>> B.method(self)?
> 
> Yes, it would.
[snip example]

Right, now I see what you mean. I don't have a problem with that 
behaviour, it is the correct behaviour, and you are making the call from 
D in the first place, so it *must* call B at some point.

If you initiate the call from C instead:

>>> C().test_mro()
In C
In A

then B is not in C's MRO, and does not get called. This is the case I was 
referring to.

I admit it did surprise me the first time I saw the example you gave. 
Hell, it *confused* me at first, until I realised that self inside the 
method isn't necessarily an instance of C, but could be an instance of a 
subclass of C (in this case, D), and then it was "Well duh, how obvious!" 
That's no different from a classic-style call to a superclass:

# inside class C(B):
B.method(self, *args)

Inside B, method() gets called with an instance of C as self.

Bringing it back to super(), since super(C, self) gets a D instance as 
argument, the MRO it looks at is D's MRO, and it all just works. I think 
the docs could make that a little more clear, but then, given how non-
cooperative inheritance works exactly the same way, there's a good 
argument for saying the docs don't need to be changed at all. If the 
behaviour is confusing for super(), then it's confusing without super() 
too.

See Guido's tutorial on cooperative multitasking for more detail:

http://www.python.org/download/releases/2.2.3/descrintro/#cooperation


> Since the idea of super() as I understand it is to make sure every class
> in an object's hierarchy gets its method called, there's really no way
> to implement super() in a way that didn't involve a non-superclass being
> called by some class's super() call.

You're reading the super() signature wrong.

super(C, self)

shouldn't be interpreted as "call C's superclasses from self". It means 
"starting just after C in the MRO, call self.__class__'s superclasses".

super() never calls a non-superclass. If it did, it would be a huge bug, 
and inheritance would break.




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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-01 Thread Mark Lawrence

On 01/08/2010 08:18, Lawrence D'Oliveiro wrote:

In message, Mark
Lawrence wrote:


On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:


In message, Mark
Lawrence wrote:


Personally I find double clicking on an msi file rather easier.


Easier than apt-get dist-upgrade?


I'm sorry but I only do English, could you please translate. :)


I run Debian Unstable, which has new goodies coming out on a weekly basis.
The last time I checked for updates, there were over 500 packages I had
installed for which updates were available. It only took a command like the
above to upgrade them all.

How many .msi files would you have to click on to achieve the Windows
equivalent?


No idea, but your mental capacity is clearly infinitely higher than 
mine, as I simply couldn't cope with over 500 installed packages.  What 
do they all do, make your lunch and fetch the beer from the fridge 
amongst other things?


Cheers.

Mark Lawrence.

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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-01 Thread Gregory Ewing

Steven D'Aprano wrote:


super(C, self)

shouldn't be interpreted as "call C's superclasses from self". It means 
"starting just after C in the MRO, call self.__class__'s superclasses".


My contention is that nobody has any chance of guessing what
it does based on the name "super". Superness doesn't come into
it at all, except in the trivial sense that whatever class it
picks will be in the mro of the second argument, which doesn't
narrow it down much.

So the word "super" here is little better than meaningless noise.

If it were something like next_method(C, self) then one could
claim with some justification that it stands for "call the next
method found after C in the mro of self".

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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-01 Thread Gregory Ewing

Lawrence D'Oliveiro wrote:

How many .msi files would you have to click on to achieve the Windows 
equivalent?


Don't you just leave the machine on overnight and wait
for Microsoft to download all the stuff they think
you should be using?

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


Re: Docstrings and PEP 3174

2010-08-01 Thread Gregory Ewing

Steven D'Aprano wrote:

If you mean a runtime optimization with no change to the source file, 
then maybe, tell me more.


Note that you don't necessarily need a separate file for this.
It could just be a separate part of the same file.

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


[RELEASED] Python 3.2 alpha 1

2010-08-01 Thread Georg Brandl
-BEGIN PGP SIGNED MESSAGE-
Hash: SHA1

On behalf of the Python development team, I'm happy to announce the
first alpha preview release of Python 3.2.

Python 3.2 is a continuation of the efforts to improve and stabilize the
Python 3.x line.  Since the final release of Python 2.7, the 2.x line
will only receive bugfixes, and new features are developed for 3.x only.

Since PEP 3003, the Moratorium on Language Changes, is in effect, there
are no changes in Python's syntax and built-in types in Python 3.2.
Development efforts concentrated on the standard library and support for
porting code to Python 3.  Highlights are:

* numerous improvements to the unittest module
* PEP 3147, support for .pyc repository directories
* an overhauled GIL implementation that reduces contention
* many consistency and behavior fixes for numeric operations
* countless fixes regarding string/unicode issues; among them full
  support for a bytes environment (filenames, environment variables)
* a sysconfig module to access configuration information
* a pure-Python implementation of the datetime module
* additions to the shutil module, among them archive file support
* improvements to pdb, the Python debugger

For an extensive list of changes in 3.2, see Misc/NEWS in the Python
distribution.

To download Python 3.2 visit:

 http://www.python.org/download/releases/3.2/

3.2 documentation can be found at:

 http://docs.python.org/3.2/

Please consider trying Python 3.2 with your code and reporting any bugs
you may notice to:

 http://bugs.python.org/


Enjoy!

- --
Georg Brandl, Release Manager
georg at python.org
(on behalf of the entire python-dev team and 3.2's contributors)
-BEGIN PGP SIGNATURE-
Version: GnuPG v2.0.16 (GNU/Linux)

iEYEARECAAYFAkxVQJsACgkQN9GcIYhpnLBxIgCcCiVu/QUkFf0bYM2Vmi8St3mZ
2N4An04q36lr47OA+bslqG/4Zj7ZwVOX
=iL8N
-END PGP SIGNATURE-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is there no platform independent way of clearing a terminal?

2010-08-01 Thread Lawrence D'Oliveiro
In message <[email protected]>, Gregory Ewing wrote:

> Don't you just leave the machine on overnight and wait
> for Microsoft to download all the stuff they think
> you should be using?

That’s fine, but it doesn’t handle the non-Microsoft stuff.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pylint scores

2010-08-01 Thread News123
Hi,


On 07/31/2010 11:04 AM, Matteo Landi wrote:
> What are the messages one should really care about while evaluating
> its code using pylint? It's easy to get 5 scored with a "lot of public
> methods" or bad named variables such as 'x' or 'y' .. Have you got any
> config file to share?


The most important ones are of course the errors.
Some of them might be false, but in our team we agreed, that no file is
allowed to report pylint errors.
This means
- just fixing errors (in most cases)
- rewriting code (in a few cases)
- masking errors with pylint directives in the source (some other few
errrors)




If you only want to see the errros, then just run
pylint -E filename.py

Note: This is a rather new but very useful switch.. It doesn't exist
on Ubuntu 10.4's release pylint 0.19.0, but exists on pylint 0.21.1



Apart from that. You should discuss within your team, which
errors you'd like to have ignored and adapt the pylintrc. This
is a rather personal decision.
For one project we disiabled for example following warnings:
## C0322 = "Operator not preceded by a space"
## C0323 = "Operator not followed by a space"
## C0324 = "Comma not followed by a space"
As we did not have time to rewrite all of the existing code, that
violated these rules.
We prefered to 'hide' these warnings in order to sett the more important
ones.

On another new project however we did NOT comment therese rules
and decided, that all new code should follow these rules


We disabled some special global variables, which we'd like to have in
lower case

const-rgx ==((specialvar)|(v_[a-z_][a-z0-9_]*)|([A-Z_][A-Z0-9_]*)|(__.*__))$


you could also modify variables like
# Maximum number of attributes for a class (see R0902).
max-attributes=7

# Minimum number of public methods for a class (see R0903).
min-public-methods=2

# Maximum number of public methods for a class (see R0904).
max-public-methods=20


For some graphics module functions for example we wanted to
be allowed to use variable names like x,y as they are
completely meaningful names for pixel coordinates.


so change the entry good-names
good-names=x,y,ex,Run,_



Hope, that this gave you some ideas



> 
> On Sat, Jul 31, 2010 at 2:48 AM, Dan Stromberg  wrote:
>>
>> On Fri, Jul 30, 2010 at 12:18 PM, News123  wrote:
>>>
>>> On 07/30/2010 03:12 PM, wheres pythonmonks wrote:
 I am starting to use pylint to look at my code and I see that it gives a
 rating.
 What values do experienced python programmers get on code not
 targeting the benchmark?

 I wrote some code, tried to keep it under 80 characters per line,
 reasonable variable names, and I got:

 0.12 / 10.

 Is this a good score for one not targeting the benchmark?  (pylint
 running in default mode)

>>> It's not a goodf core, but arrives easily if you never ran pylint before.
>>> With very little effort you should be able to be above 5
>>> with a little more effort above 7
>>>
>>>
 Somewhat related:  Is the backslash the only way to extend arguments
 to statements over multiple lines?  (e.g.)
>>>
>>> if you have an opening parenthesis, or bracked, then you don't need a
>>> backslash
>>>
>>> so instead of
>>> if longlonglonglonglonglonglonglongvar == \
>>>otherlonglonglonglongvar:
>>>
>>> you could also write:
>>>
>>> if (longlonglonglonglonglonglonglongvar ==
>>>otherlonglonglonglongvar):
>>>
>>>
>>> same works of course with asserts.
>>>

>>> def f(x,y,z): return(x+y+z);
 ...
>>> f(1,2,
 ... 3)
 6
>>> assert f(1,2,3)>0,
   File "", line 1
 assert f(1,2,3)>0,
  ^
 SyntaxError: invalid syntax
>>>

 In the above, I could split the arguments to f (I guess b/c of the
 parens) but not for assert.  I could use a backslash, but I find this
 ugly -- it that my only (best?) option?

 [I really like to assert my code to correctness and I like using the
 second argument to assert, but this resulted in a lot of long lines
 that I was unable to break except with an ugly backslash.]

 W
>>>
>> IMO, the important thing about pylint's scoring is that it's but one way of
>> many of producing good Python code.  However, it's also one of the easier
>> ways of producing good python code.
>> I personally like to get my scores up near 10, by annotating in comments
>> about the few things that pylint flags that I can't just code around.  This
>> requires jumping through some slightly silly hoops (EG the previously
>> mentioned "too few public methods", which my various container classes
>> always trip over), but going through this process is worthwhile for
>> highlighting the hoops pylint can detect that -aren't- so silly.
>> The one thing I like to leave unfixed is FIXME's - otherwise my preference
>> would be to go for a score of 10 for production code.
>> I also like to create a ./this-pylint script for my various projects, that
>> have global overrides - 

Re: Why is there no platform independent way of clearing a terminal?

2010-08-01 Thread Tim Harig
On 2010-08-01, Mark Lawrence  wrote:
> On 01/08/2010 06:17, Tim Harig wrote:
>> On 2010-08-01, Lawrence D'Oliveiro  wrote:
>>> In message, Tim Harig wrote:
>>>
 It would be rewarding as it would make writing cross-platform charactor
 mode applications possible.
>>>
>>> I thought Windows users were allergic to command lines.
>>
>> To the best of my knowledge, there have never been any documentated
>> cases of computer software related alleries.  There are however several
>> chemicals used in the process of constructing computer hardware componets
>> which have been linked to allergy illnesses.  Maybe Windows users are
>> simply allergic to their computers.
>
> Windows users biggest allergy is to this strange world that involves 
> "make" on other boxes, whatever that is, it strikes me as rather 
> archaic.  Personally I find double clicking on an msi file rather easier.

I work with several thousand computers located on three different
continents.  Few of them have mice attached to them.  If you think double
clicking is a better method, be my guest; but, you need to get a package
installed and configured on all of them before lunch.

Its also kind of funny that I couldn't get the msi to work with a large
percentage of the systems that I work with.  Make works on all but one out
of the box, and potentially on the last with the addition of SFU or
Cygwin.

With all that said, I am still not sure what the make/msi question has
anything to do with packing a backup, cross platform, implementation of
curses that allows the curses module to give Python a cross platform method
of character mode manipulation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Normalizing A Vector

2010-08-01 Thread Thomas Jollans
On 08/01/2010 03:41 AM, Lawrence D'Oliveiro wrote:
> In message <[email protected]>, Alain Ketterlin wrote:
> 
>> Lawrence D'Oliveiro  writes:
>>
>>> V = tuple \
>>>   (
>>> x
>>> /
>>> l
>>>for x in V
>>>for l in
>>>(math.sqrt(reduce(lambda a, b : a + b, (y * y for y in V),
>>>0)),)
>>>   )
>>
>> You got the order wrong (it has to be for l ... for x ...)
> 
> No, I deliberately put it in that order to ensure that the value for l can 
> only ever be evaulated once.
> 
>> You're kind of lucky here, because the arglist to tuple() provides a
>> scope that hides x and l. Be careful if you ever change tuple(...) to
>> [...], because x and l would leak to the outer scope (with python 2.*).
> 
> Interesting. However, using “list( ... )” instead of “[ ... ]” also prevents 
> the leakage.

Yes. That's because the variable leakage of list comprehensions was
never a good idea, and is kept in Python 2.x only for backwards
compatibility. When generator expressions where introduced, it was done
in such a way that the scope didn't leak (which probably wouldn't make
any sense anyway since there's no guarantee a generator expression is
executed at all before the next line)

In Python 3, list comprehensions don't leak names any more - they act
(nearly?) the same as like( ... expr ... ) now.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: urllib2 test fails (2.7, linux)

2010-08-01 Thread guandalino
On 22 Lug, 01:13, Terry Reedy  wrote:

> If you do not get an answer here, file a bug report. If you can, put
> orsenthil,benjamin.peterson,ezio.melotti
> on the nosy list, as they are recent committers to this file. Say I said
> to do so if you want. Add tjreedy also so I can see responses and learn too.

Done here: http://bugs.python.org/issue9446.

Best regards, HAND.
-- 
http://mail.python.org/mailman/listinfo/python-list


let optionparse.Optionparser ignore unknown command line switches.

2010-08-01 Thread News123
I wondered, whether there's a simple/standard way to let
the Optionparser just ignore unknown command line switches.

thanks in advance for any ideas



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


Re: Why is there no platform independent way of clearing a terminal?

2010-08-01 Thread Lawrence D'Oliveiro
In message , Mark 
Lawrence wrote:

> On 01/08/2010 08:18, Lawrence D'Oliveiro wrote:
>
>> In message, Mark
>> Lawrence wrote:
>>
>>> On 01/08/2010 07:50, Lawrence D'Oliveiro wrote:
>>>
 In message, Mark
 Lawrence wrote:

> Personally I find double clicking on an msi file rather easier.

 Easier than apt-get dist-upgrade?
>>>
>>> I'm sorry but I only do English, could you please translate. :)
>>
>> I run Debian Unstable, which has new goodies coming out on a weekly
>> basis. The last time I checked for updates, there were over 500 packages
>> I had installed for which updates were available. It only took a command
>> like the above to upgrade them all.
>>
>> How many .msi files would you have to click on to achieve the Windows
>> equivalent?
> 
> ... I simply couldn't cope with over 500 installed packages.

Precisely my point. Go back to playing with your .msi toys.

Oh, and .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: let optionparse.Optionparser ignore unknown command line switches.

2010-08-01 Thread News123

On 08/01/2010 01:08 PM, News123 wrote:
> I wondered, whether there's a simple/standard way to let
> the Optionparser just ignore unknown command line switches.
> 

In order to  illustrate, what I try to achieve:


import optparse
parser = optparse.OptionParser()
parser.add_option("-t","--test",dest="test",action="store_true")
argv=["tst.py","-t","--ignoreme_and_dont_fail"]
try:
(options,args)=parser.parse_args(argv)
except:
# due to --ignoreme_and_dont_fail
# I will end up here and neither options nor
# args will be populated
print "parser error:"
# However I would love to be able to see here
# that options.test is true despite the
# error, that occurred afterwards
print "T",options.test

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


how can I solve this erorr usr/lib/python2.6 : permisson denied

2010-08-01 Thread Mohseniaref
Dear Friend
I have this erorr after running pyhon script with header
/usr/lib/python2.6 : permisson denied
I change ownership with -hR in super user terminal
-- 
http://mail.python.org/mailman/listinfo/python-list


class doesn't open its window - newbie question

2010-08-01 Thread Chris Hare
I am a newbie to python, but not programming.

I have a menubar item 

displaySubMenu.add_command(label="External", command=externalDisplay)

externalDisplay is a new class, which I have already imported.  The class is 
here:

from Tkinter import *
from datetime import datetime, date, time
import urllib
from PIL import Image
#import Image # PIL required
import ImageTk

backColor = "Gray"
highcolor = "Green"
entryColor = "Cyan"
okColor = "Green"
warnColor = "Red"

class externalDisplay(Frame):

def __init__(self,callSign,nexrad):
"""Initialize yourself"""
self.callSign = callSign
self.nexrad = nexrad
#"""Initialise the base class"""
Frame.__init__(self)

"Set the Window Title"""
#self.title( "Test")


self.findu = "http://www.findu.com/cgi-bin/radar-find.cgi?call="; + 
self.callSign + "&radar=" + self.nexrad

"""Display the main window" with a little bit of padding"""
self.grid(padx=5,pady=5)
self.CreateWidgets()
   
def CreateWidgets(self):
#"""Create all the widgets that we need"""
self.f = Frame(self, bd=0, bg=backColor)
self.title = "netcomm Online Radar"
self.f.grid()
#
# Insert the date and time the radar image was updated
#
self.lblLastUpdate = Label(self.f, text="Last Updated: " + 
str(datetime.now()), bg=backColor)
self.lblLastUpdate.grid( row=0, column=0, sticky=W)
self.btnRefresh = Button(self.f, text="Refresh", 
command=handlesExternalDisplayByClick, 
bg=backColor,highlightbackground=okColor,highlightcolor=highcolor)
self.btnRefresh.grid(row=0, column=1)
self.btnRefresh = Button(self.f, text="Close", command=self.destroy, 
bg=backColor,highlightbackground=warnColor,highlightcolor=highcolor)
self.btnRefresh.grid(row=0, column=2)
#
# Start the download from findu
#
#
# This gets the image and saves it to the local disk as "image.png"
#
# NOTE - will ideally want to conver this to GIF and save it using
#the date as part of the filename so the net can be re-created
#for reporting and to create a flipbook of the radar images
#
urllib.urlretrieve(self.findu, "image.png")
Image.open("image.png").save("image.gif")
self.photo = PhotoImage(file="image.gif")
#
# create a canvas of the appropriate size for the image
#
self.w = Canvas(self.f, width=600, height=550)
#
# convert it into a photo item we can use in the display
#
self.netRadarImage = Label(self.w, image=self.photo)
self.netRadarImage.image = self.photo
self.w.grid(row=1, column=0, columnspan=3)
self.netRadarImage.grid( row=1, column=0)

def handlesExternalDisplayByClick(self):
#
# destroy the existing frame the radar is in
#
self.destroy()
#
# rebuild the radarWidgets
#
createRadarWidgets(frameRadar)

def handlesRadarRefreshByClick(self):
#
# destroy the existing frame the radar is in
#
self.destroy()
#
# rebuild the radarWidgets
#
self.update()

if __name__ == "__main__":
guiFrame = externalDisplay("AE5PL-10","fws")
guiFrame.mainloop()

The problem is that the window defined in the class never appears, and I don't 
know why.  I would like to get all of the code for the window into a single 
file which I import, but since I can't make this work right, I don't want to 
invest the time yet.Eve worse, is that when I run the code as a standalone 
module and click on the close  button, I am left with a tk window instead of 
the app actually closing.

Any suggestions are appreciated.

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


image resize doesn't work

2010-08-01 Thread Chris Hare

I have the following chunk of code.  Although it seems to execute fine, no 
errors, the image is never resized.  What am I missing?

imagePNG = Image.open("image.png")
photo = ImageTk.PhotoImage(imagePNG
canvasWidth = 300
canvasHeight = 275
photo = 
ImagePNG.resize((canvasWidth,canvasHeight),Image.ANTIALIAS)
netRadarImage = Label(w, image=photo)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is there no platform independent way of clearing a terminal?

2010-08-01 Thread Roy Smith
In article ,
 Lawrence D'Oliveiro  wrote:

> In message <[email protected]>, Gregory Ewing wrote:
> 
> > Don't you just leave the machine on overnight and wait
> > for Microsoft to download all the stuff they think
> > you should be using?
> 
> That’s fine, but it doesn’t handle the non-Microsoft stuff.

You've apparently never worked in a big company.  Your IT department 
downloads whatever *they* think you should be using.  Eventually, your 
machine is so slow, you can't get any work done.
-- 
http://mail.python.org/mailman/listinfo/python-list


Parse a string into argv-like list like OS does

2010-08-01 Thread python
Before I reinvent the wheel, is there a module that provides a
command-line like parser that I can use? By command-line like
parser, I mean that I would like to pass a string to this
function and get back a list in the same manner as the OS
receives a command line string which it parses into discrete
items (handling quoted strings, backslashes, etc)

I have a bunch of command lines (as strings) and I would like to
parse them into argv-like lists for analysis and documentation.

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


Re: Parse a string into argv-like list like OS does

2010-08-01 Thread Tim Chase

On 08/01/10 08:12, [email protected] wrote:

Before I reinvent the wheel, is there a module that provides a
command-line like parser that I can use? By command-line like
parser, I mean that I would like to pass a string to this
function and get back a list in the same manner as the OS
receives a command line string which it parses into discrete
items (handling quoted strings, backslashes, etc)


Sounds like the shlex module...

http://docs.python.org/library/shlex.html

-tkc



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


Re: how can I solve this erorr usr/lib/python2.6 : permisson denied

2010-08-01 Thread Andrea Crotti
Mohseniaref  writes:

> Dear Friend
> I have this erorr after running pyhon script with header
> /usr/lib/python2.6 : permisson denied
> I change ownership with -hR in super user terminal

Why /usr/lib... and not in bin?
I guess this is the directory, of course if you put it in the header
(shabang) it won't work.

I use normally
#!/usr/bin/env python
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Parse a string into argv-like list like OS does

2010-08-01 Thread python
Tim,

> Sounds like the shlex module...
> http://docs.python.org/library/shlex.html

Cheers for the link - that's *exactly* what I was searching for.

For the archives: Here's an excellent tutorial on this module.
http://www.oreillynet.com/onlamp/blog/2007/10/pymotw_shlex.html

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


Re: Normalizing A Vector

2010-08-01 Thread Alain Ketterlin
Lawrence D'Oliveiro  writes:

>>> V = tuple \
>>>   (
>>> x
>>> /
>>> l
>>>for x in V
>>>for l in
>>>(math.sqrt(reduce(lambda a, b : a + b, (y * y for y in V),
>>>0)),)
>>>   )
>> 
>> You got the order wrong (it has to be for l ... for x ...)
>
> No, I deliberately put it in that order to ensure that the value for l can 
> only ever be evaulated once.

Try this (essentially equivalent to your code):

def f():
print "hello"
return 1

V = tuple( 1 for x in [1,2,3] for l in (f(),) )

How many "hello"s do you see?

Comprehension are not loops spelled backwards. The values in:

whatever for i ... for j ...

are the values produced by the equivalent code:

for i ...
for j ...
whatever

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


Re: image resize doesn't work

2010-08-01 Thread rantingrick
On Aug 1, 7:35 am, Chris Hare  wrote:
> I have the following chunk of code.  Although it seems to execute fine, no 
> errors

Not True! it contains syntax errors. Check the posted code and next
time post all the code.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: let optionparse.Optionparser ignore unknown command line switches.

2010-08-01 Thread Steven W. Orr
On 08/01/10 07:27, quoth News123:
> On 08/01/2010 01:08 PM, News123 wrote:
>> I wondered, whether there's a simple/standard way to let
>> the Optionparser just ignore unknown command line switches.
>>
> 
> In order to  illustrate, what I try to achieve:
> 
> 
> import optparse
> parser = optparse.OptionParser()
> parser.add_option("-t","--test",dest="test",action="store_true")
> argv=["tst.py","-t","--ignoreme_and_dont_fail"]
> try:
> (options,args)=parser.parse_args(argv)
> except:
> # due to --ignoreme_and_dont_fail
> # I will end up here and neither options nor
> # args will be populated
> print "parser error:"
> # However I would love to be able to see here
> # that options.test is true despite the
> # error, that occurred afterwards
> print "T",options.test
> 

You need to let us know *why* you want to do this. My psychotic imagination is
contriving that you want to pass on the ignoremeanddontfail options to
something else. If so, then you should be using -- instead of this. The other
possible scheme to solve your unknown problem is to subclass OptionParser so
it does what you want.

-- 
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



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: image resize doesn't work

2010-08-01 Thread Chris Hare

On Aug 1, 2010, at 10:24 AM, rantingrick wrote:

> On Aug 1, 7:35 am, Chris Hare  wrote:
>> I have the following chunk of code.  Although it seems to execute fine, no 
>> errors
> 
> Not True! it contains syntax errors. Check the posted code and next
> time post all the code.
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Hmmm... ok
here is the code.  I get no errors on my console when it execute

urllib.urlretrieve(findu, "image.png")
logging.debug("createRadarWidgets(): radar download complete")
logging.debug("createRadarWidgets(): user has radarPanelSize of 
" + root.radarPanelSize.get())
#
# open the image file
#
if os.path.exists("image.gif"):
ctime = os.stat(dbPath)[ST_CTIME]
print ctime
filetime = datetime.fromtimestamp(ctime)
filetime = filetime.strftime("%Y%m%d%H%M%S")
print str(filetime)
#filetime = datetime(ctime).isoformat()
#print ctime
imagePNG = Image.open("image.png")
#photo = ImageTk.PhotoImage(imagePNG)
Image.open("image.png").save("image.gif")
image = Image.open("image.gif")
photo = PhotoImage(file="image.gif")
#photoimg = ImageTk.PhotoImage(photo)
#
# NOTE: - will want to track the size of the image displayed 
based upon
# the actual screen resolution
#   Full/External = 600x550 - full file size
#   Large = 450x412
#   Medium = 300x275
#   Small = 150x137
#
if root.radarPanelSize.get() == "Large":
canvasWidth = 450
canvasHeight = 412
elif root.radarPanelSize.get() == "Medium":
canvasWidth = 300
canvasHeight = 275
elif root.radarPanelSize.get() == "Small":
canvasWidth = 150
canvasHeight = 137
logging.debug("createRadarWidgets(): creating image size " + 
str(canvasWidth) + "x" + str(canvasHeight))
#
# create a canvas of the appropriate size for the image
#
w = Canvas(f, width=canvasWidth, height=canvasHeight)
if root.radarPanelSize.get() == "Off":
logging.debug("createRadarWidgets(): no net, no radar")
netRadarImage = Label(w, text="No current radar")
else:
#
# convert it into a photo item we can use in the display
#
# photo = 
photo.resize((canvasWidth,canvasHeight),Image.ANTIALIAS)
netRadarImage = Label(w, image=photo)
netRadarImage.image = photo
w.grid(row=1, column=0, columnspan=3)
netRadarImage.grid( row=1, column=0)

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


Google job leads

2010-08-01 Thread Charles Jo
Dear Colleagues,

I recently started a recruiter project at Google and am working with Partner 
Solutions Organization and recruiting Technical Account Managers for the group 
so I am actively networking with those who may know great software engineers 
with client-facing experience (or wanting to move in that direction) for 
career-defining opportunities.  If there are individuals and organizations that 
I should reach out to, please do let me know -- my office contact information 
is below.

Google office:

Charles Jo
Sales Recruiter, Google
650.253.0375 office
408.668.4226 cell
[email protected]

Feedback is always welcome!


Best,

Charles

-- 
Message sent by:

Charles Jo
408.668.4226
[email protected]

http://bit.ly/zooqdesk http://www.linkedin.com/in/charlesjo 
http://twitter.com/charlesjo http://www.facebook.com/profile.php?id=603461791



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


Re: let optionparse.Optionparser ignore unknown command line switches.

2010-08-01 Thread News123
On 08/01/2010 05:34 PM, Steven W. Orr wrote:
> On 08/01/10 07:27, quoth News123:
>> On 08/01/2010 01:08 PM, News123 wrote:
>>> I wondered, whether there's a simple/standard way to let
>>> the Optionparser just ignore unknown command line switches.
>>>
>>
>> In order to  illustrate, what I try to achieve:
>>
>>
>> import optparse
>> parser = optparse.OptionParser()
>> parser.add_option("-t","--test",dest="test",action="store_true")
>> argv=["tst.py","-t","--ignoreme_and_dont_fail"]
>> try:
>> (options,args)=parser.parse_args(argv)
>> except:
>> # due to --ignoreme_and_dont_fail
>> # I will end up here and neither options nor
>> # args will be populated
>> print "parser error:"
>> # However I would love to be able to see here
>> # that options.test is true despite the
>> # error, that occurred afterwards
>> print "T",options.test
>>
> 
> You need to let us know *why* you want to do this. My psychotic imagination is
> contriving that you want to pass on the ignoremeanddontfail options to
> something else. If so, then you should be using -- instead of this. The other
> possible scheme to solve your unknown problem is to subclass OptionParser so
> it does what you want.

Hi Steven,

'--' is good for many use cases, but not for the one I'm looking at.

in my case one imported module should parse some of the options (but
only the one it understands) already during import.
the main program will have to parse the same options again.



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


Trying to set a cookie within a python script

2010-08-01 Thread Νίκος
Hello fellow Python Coders!

I don't see the error in my attempt to set a a cookie in this test
script. Can you help please?! Thank you!

[code]
#!/usr/bin/python
# -*- coding: utf-8 -*-

import Cookie

print ( "Content-type: text/html\n" )

cookie = Cookie.SimpleCookie()

if cookie.has_key('visitor') == "nikos"  #if visitor cookie exist
   print ( "Δεν σε ειδα, δεν σε ξερω, δεν σε ακουσα. Θα εισαι ο
αοραστος επισκεπτης!!" )
   cookie['visitor'] = ( 'nikos', time() - 1 )  #this cookie will
expire now
else
   print ( "Απο δω και στο εξης δεν θα αυξανω τον μετρητη δικη σου
επισκεψη!!" )
   cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 )  #this
cookie will expire in an year
[/code]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: let optionparse.Optionparser ignore unknown command line switches.

2010-08-01 Thread Jon Clements
On 1 Aug, 16:43, News123  wrote:
> On 08/01/2010 05:34 PM, Steven W. Orr wrote:
>
>
>
> > On 08/01/10 07:27, quoth News123:
> >> On 08/01/2010 01:08 PM, News123 wrote:
> >>> I wondered, whether there's a simple/standard way to let
> >>> the Optionparser just ignore unknown command line switches.
>
> >> In order to  illustrate, what I try to achieve:
>
> >> import optparse
> >> parser = optparse.OptionParser()
> >> parser.add_option("-t","--test",dest="test",action="store_true")
> >> argv=["tst.py","-t","--ignoreme_and_dont_fail"]
> >> try:
> >>     (options,args)=parser.parse_args(argv)
> >> except:
> >>     # due to --ignoreme_and_dont_fail
> >>     # I will end up here and neither options nor
> >>     # args will be populated
> >>     print "parser error:"
> >> # However I would love to be able to see here
> >> # that options.test is true despite the
> >> # error, that occurred afterwards
> >> print "T",options.test
>
> > You need to let us know *why* you want to do this. My psychotic imagination 
> > is
> > contriving that you want to pass on the ignoremeanddontfail options to
> > something else. If so, then you should be using -- instead of this. The 
> > other
> > possible scheme to solve your unknown problem is to subclass OptionParser so
> > it does what you want.
>
> Hi Steven,
>
> '--' is good for many use cases, but not for the one I'm looking at.
>
> in my case one imported module should parse some of the options (but
> only the one it understands) already during import.
> the main program will have to parse the same options again.

Take it up a level.

Dedicate a module (called app_configuration) or something to do the
option parsing -- everything the application can support is listed
there... It's a bad idea to ignore invalid options...

When that's imported it runs the parsing for sys.argv whatever... and
you guarantee a variable called app_settings (or whatever) is present
in that module.

Any module that needs the settings, just imports app_configuration and
tries to take what it understands...

Would that work for you?

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


Re: image resize doesn't work

2010-08-01 Thread Peter Otten
Chris Hare wrote:

 
> On Aug 1, 2010, at 10:24 AM, rantingrick wrote:
> 
>> On Aug 1, 7:35 am, Chris Hare  wrote:
>>> I have the following chunk of code.  Although it seems to execute fine,
>>> no errors
>> 
>> Not True! it contains syntax errors. Check the posted code and next
>> time post all the code.
>> --
>> http://mail.python.org/mailman/listinfo/python-list
> 
> Hmmm... ok
> here is the code.  I get no errors on my console when it execute
> 
> urllib.urlretrieve(findu, "image.png")

I get a NameError on the very first line.

>>> urllib.urlretrieve(findu, "image.png")
Traceback (most recent call last):
  File "", line 1, in 
NameError: name 'urllib' is not defined

When you want to demonstrate a problem try to make a self-contained example, 
i. e. one that can be run without the need for us guess the surrounding 
code. Remove everything that is irrelevant for the problem like the logging 
in code below and the png/gif conversion gymnastics.

Anyway, here is a self-contained demo (you have to pass the filename of an 
image on the commandline):

import Tkinter
import ImageTk
import Image
import sys

[filename] = sys.argv[1:]

image = Image.open(filename)

root = Tkinter.Tk()
frame = Tkinter.Frame(root)
frame.pack()
label = Tkinter.Label(root)
label.pack()

def make_resize(percent):
def resize():
width, height = image.size
label.image = label["image"] = ImageTk.PhotoImage(
image=image.resize((width*percent//100, height*percent//100)))
return resize

make_resize(100)()

pairs = [
("Small", 20),
("Medium", 50),
("Original", 100),
("Big", 200)]

for i, (text, percent) in enumerate(pairs):
button = Tkinter.Button(frame, text=text, command=make_resize(percent))
button.grid(row=0, column=i)

root.mainloop()

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


Re: default behavior

2010-08-01 Thread John Posner

On 7/31/2010 2:00 PM, Christian Heimes wrote:


Your answer is confusing even me. ;)


Yeah, I get that a lot. :-)



Let me try an easier to understand explanation. defaultdict *implements*
__missing__() to provide the default dict behavior.


In my experience, the word *implements* is commonly used in two ways, 
nearly opposite to each other. Ex:


  My company just implemented a version-control system.

Did your company (1) write the code for the version-control system, or 
did it (2) put the system in use, by downloading an installer from the 
Web and executing it?


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


Re: image resize doesn't work

2010-08-01 Thread Chris Hare

On Aug 1, 2010, at 1:08 PM, Peter Otten wrote:

> Chris Hare wrote:
> 
> 
>> On Aug 1, 2010, at 10:24 AM, rantingrick wrote:
>> 
>>> On Aug 1, 7:35 am, Chris Hare  wrote:
 I have the following chunk of code.  Although it seems to execute fine,
 no errors
>>> 
>>> Not True! it contains syntax errors. Check the posted code and next
>>> time post all the code.
>>> --
>>> http://mail.python.org/mailman/listinfo/python-list
>> 
>> Hmmm... ok
>> here is the code.  I get no errors on my console when it execute
>> 
>> urllib.urlretrieve(findu, "image.png")
> 
> I get a NameError on the very first line.
> 
 urllib.urlretrieve(findu, "image.png")
> Traceback (most recent call last):
>  File "", line 1, in 
> NameError: name 'urllib' is not defined
> 
> When you want to demonstrate a problem try to make a self-contained example, 
> i. e. one that can be run without the need for us guess the surrounding 
> code. Remove everything that is irrelevant for the problem like the logging 
> in code below and the png/gif conversion gymnastics.
> 
> Anyway, here is a self-contained demo (you have to pass the filename of an 
> image on the commandline):
> 
> import Tkinter
> import ImageTk
> import Image
> import sys
> 
> [filename] = sys.argv[1:]
> 
> image = Image.open(filename)
> 
> root = Tkinter.Tk()
> frame = Tkinter.Frame(root)
> frame.pack()
> label = Tkinter.Label(root)
> label.pack()
> 
> def make_resize(percent):
>def resize():
>width, height = image.size
>label.image = label["image"] = ImageTk.PhotoImage(
>image=image.resize((width*percent//100, height*percent//100)))
>return resize
> 
> make_resize(100)()
> 
> pairs = [
>("Small", 20),
>("Medium", 50),
>("Original", 100),
>("Big", 200)]
> 
> for i, (text, percent) in enumerate(pairs):
>button = Tkinter.Button(frame, text=text, command=make_resize(percent))
>button.grid(row=0, column=i)
> 
> root.mainloop()
> 
> Peter
> -- 
> http://mail.python.org/mailman/listinfo/python-list

Thanks for the help.  My one week of python is getting a workout.

I have shortened it all down and made it a standalone example, using yours as a 
model.  Your example, works, but it will take a lot of effort to retrofit it 
into the code I have.  (which is maybe not a bad idea,).

Anyway

from Tkinter import *
import ImageTk
import Image
import sys

def sizeit(filename):
image = Image.open(filename)
w,h = image.size
print w, h
photo = ImageTk.PhotoImage(file=filename)
canvasWidth = 450
canvasHeight = 412
image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS)
w,h = image.size
print w, h
netRadarImage = Label(frame, image=image)
netRadarImage.image = photo
w.grid(row=1, column=0, columnspan=3)
netRadarImage.grid( row=1, column=0)

[filename] = sys.argv[1:]

root = Tk()
frame = Frame(root)
frame.grid()
sizeit(filename)

root.mainloop()

Just like yours it takes a filename.  Unlike yours, mine gets an error that I 
can't figure out and is likely the root of the problem.  

When I run this code I get

600 550 <== ORIGINAL image size
450 412 <== resized image size
Traceback (most recent call last):
  File "zztest.py", line 26, in 
sizeit(filename)
  File "zztest.py", line 16, in sizeit
netRadarImage = Label(frame, image=image)
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 2466, in __init__
Widget.__init__(self, master, 'label', cnf, kw)
  File 
"/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/lib-tk/Tkinter.py",
 line 1932, in __init__
(widgetName, self._w) + extra + self._options(cnf))
_tkinter.TclError: image "" doesn't exist

So, my problem appeared to be the resize, but in fact is just getting it onto 
the label.

What am I doing wrong?



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


exception handling with sqlite db errors

2010-08-01 Thread CM
I am using SQLite with Python 2.5 for an app and every now and then
get an error when trying to write to the database.  So far I haven't
been careful about noting these down, but now I would like to address
them.  The two errors I've noticed are:

1) "database is locked" errors (probably due to write conflicts when
using SQLite Database Browser to check and change the data while my
app was trying to write to the db; this might be a problem for users
if they too want to edit their data that way while running the app,
though that scenario is pretty unlikely).

2) Today for the first time,"sqlite3.OperationalError: attempt to
write a readonly database"--though I never set this database to be
read-only. When I tried it a second time, it worked and didn't give
this error.

What I would like is a way to innoculate my app from these errors such
that if they occur they don't cause any problems with the app.  I'm
not even sure if they do cause problems, since I can't figure out a
way to reproduce the errors and see whether it causes the app to hang
or not update the GUI properly, etc.

Maybe it's not much of an issue, but I think it would be a shame if
occasional hangs/crashes could be caused by these (rare?) database
conflicts if there is a good approach for avoiding them.  I guess I
could put every last write to the db in a try/except block but I
thought there should be a more general solution, since that will
require many such exceptions and seems inelegant.

Any suggestions for addressing this are appreciated.

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


Re: image resize doesn't work

2010-08-01 Thread Peter Otten
Chris Hare wrote:

> Thanks for the help.  My one week of python is getting a workout.
> 
> I have shortened it all down and made it a standalone example, using yours
> as a model.  Your example, works, but it will take a lot of effort to
> retrofit it into the code I have.  (which is maybe not a bad idea,).

You mean retrofit something that works into something tha doesn't?
Seriously, you should never be afraid to throw away code, especially while 
you're still in the early phase of learning the language.

> def sizeit(filename):
> image = Image.open(filename)

Now you have an Image

> w,h = image.size
> print w, h
> photo = ImageTk.PhotoImage(file=filename)

and now a photo, both created from the same file but otherwise independent

> canvasWidth = 450
> canvasHeight = 412
> image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS)

Now you have a new resized Image

> w,h = image.size
> print w, h
> netRadarImage = Label(frame, image=image)

Label(image=...) expects a PhotoImage

> netRadarImage.image = photo
> w.grid(row=1, column=0, columnspan=3)

Hmm...

> netRadarImage.grid( row=1, column=0)

Here's the fixed code:

def sizeit(filename):
image = Image.open(filename)
canvasWidth = 450
canvasHeight = 412
image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS)
photo = ImageTk.PhotoImage(image=image)
netRadarImage = Label(frame, image=photo)
netRadarImage.image = photo
netRadarImage.grid(row=0, column=0)

In plain English:

- open the Image using the PIL
- resize it
- wrap it into a PhotoImage
- wrap the PhotoImage into a Tkinter.Label either by passing it to the 
initialiser or by assigning to label["image"]
- make sure the PhotoImage isn't garbage-collected e. g. by assigning to 
label.image

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


beginner python GUI question

2010-08-01 Thread Chris Hare
I hope I can explain this correctly.

I have a GUI, which is already being processed by a mainloop.  I want to be 
able to open a second window so the user can interact with specific information 
in the second window.  I pulled together this code example

from Tkinter import *

class Net:
def __init__(self,tkWin):
self.window = tkWin
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
button = Button(self.window, text="Again")
button.bind("", self.Again)
button.grid()
def Again(self,event):
win3 = Tk()
x = Net(win3)
x.show("window 3")

root = Tk()
root.title = "test"
f = Frame(root,bg="Yellow")
l = Label(f,text="window 1")
f.grid()
l.grid()

win2 = Tk()
x = Net(win2)
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

Is this the right way to do things, or would you suggest something different?

Thanks,
Chris

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


Re: image resize doesn't work

2010-08-01 Thread Chris Hare
And I see now what I did wrong - thanks for putting up with the questions.

On Aug 1, 2010, at 4:32 PM, Peter Otten wrote:

> Chris Hare wrote:
> 
>> Thanks for the help.  My one week of python is getting a workout.
>> 
>> I have shortened it all down and made it a standalone example, using yours
>> as a model.  Your example, works, but it will take a lot of effort to
>> retrofit it into the code I have.  (which is maybe not a bad idea,).
> 
> You mean retrofit something that works into something tha doesn't?
> Seriously, you should never be afraid to throw away code, especially while 
> you're still in the early phase of learning the language.
> 
>> def sizeit(filename):
>>image = Image.open(filename)
> 
> Now you have an Image
> 
>>w,h = image.size
>>print w, h
>>photo = ImageTk.PhotoImage(file=filename)
> 
> and now a photo, both created from the same file but otherwise independent
> 
>>canvasWidth = 450
>>canvasHeight = 412
>>image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS)
> 
> Now you have a new resized Image
> 
>>w,h = image.size
>>print w, h
>>netRadarImage = Label(frame, image=image)
> 
> Label(image=...) expects a PhotoImage
> 
>>netRadarImage.image = photo
>>w.grid(row=1, column=0, columnspan=3)
> 
> Hmm...
> 
>>netRadarImage.grid( row=1, column=0)
> 
> Here's the fixed code:
> 
> def sizeit(filename):
>image = Image.open(filename)
>canvasWidth = 450
>canvasHeight = 412
>image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS)
>photo = ImageTk.PhotoImage(image=image)
>netRadarImage = Label(frame, image=photo)
>netRadarImage.image = photo
>netRadarImage.grid(row=0, column=0)
> 
> In plain English:
> 
> - open the Image using the PIL
> - resize it
> - wrap it into a PhotoImage
> - wrap the PhotoImage into a Tkinter.Label either by passing it to the 
> initialiser or by assigning to label["image"]
> - make sure the PhotoImage isn't garbage-collected e. g. by assigning to 
> label.image
> 
> Peter
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Why is python not written in C++ ?

2010-08-01 Thread candide
Python is an object oriented langage (OOL). The Python main 
implementation is written in pure and "old" C90. Is it for historical 
reasons?


C is not an OOL and C++ strongly is. I wonder if it wouldn't be more 
suitable to implement an OOL with another one.


Has it ever been planned to rewrite in C++ the historical implementation 
(of course in an object oriented design) ?

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


Re: image resize doesn't work

2010-08-01 Thread Chris Hare
Thanks Peter - I know what I said sounded stupid :-)

I have been working with Python for a week and as you know sometimes it is 
easier to learn by seeing what you did wrong as compared to what should have 
been done with the same example.  I loved your code by the way - 

Thanks for help just another beginner 


On Aug 1, 2010, at 4:32 PM, Peter Otten wrote:

> Chris Hare wrote:
> 
>> Thanks for the help.  My one week of python is getting a workout.
>> 
>> I have shortened it all down and made it a standalone example, using yours
>> as a model.  Your example, works, but it will take a lot of effort to
>> retrofit it into the code I have.  (which is maybe not a bad idea,).
> 
> You mean retrofit something that works into something tha doesn't?
> Seriously, you should never be afraid to throw away code, especially while 
> you're still in the early phase of learning the language.
> 
>> def sizeit(filename):
>>image = Image.open(filename)
> 
> Now you have an Image
> 
>>w,h = image.size
>>print w, h
>>photo = ImageTk.PhotoImage(file=filename)
> 
> and now a photo, both created from the same file but otherwise independent
> 
>>canvasWidth = 450
>>canvasHeight = 412
>>image = image.resize((canvasWidth,canvasHeight),Image.ANTIALIAS)
> 
> Now you have a new resized Image
> 
>>w,h = image.size
>>print w, h
>>netRadarImage = Label(frame, image=image)
> 
> Label(image=...) expects a PhotoImage
> 
>>netRadarImage.image = photo
>>w.grid(row=1, column=0, columnspan=3)
> 
> Hmm...
> 
>>netRadarImage.grid( row=1, column=0)
> 
> Here's the fixed code:
> 
> def sizeit(filename):
>image = Image.open(filename)
>canvasWidth = 450
>canvasHeight = 412
>image = image.resize((canvasWidth, canvasHeight),Image.ANTIALIAS)
>photo = ImageTk.PhotoImage(image=image)
>netRadarImage = Label(frame, image=photo)
>netRadarImage.image = photo
>netRadarImage.grid(row=0, column=0)
> 
> In plain English:
> 
> - open the Image using the PIL
> - resize it
> - wrap it into a PhotoImage
> - wrap the PhotoImage into a Tkinter.Label either by passing it to the 
> initialiser or by assigning to label["image"]
> - make sure the PhotoImage isn't garbage-collected e. g. by assigning to 
> label.image
> 
> Peter
> -- 
> http://mail.python.org/mailman/listinfo/python-list

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


Re: Docstrings and PEP 3174

2010-08-01 Thread Terry Reedy

On 8/1/2010 4:30 AM, Gregory Ewing wrote:

Steven D'Aprano wrote:


If you mean a runtime optimization with no change to the source file,
then maybe, tell me more.


Note that you don't necessarily need a separate file for this.
It could just be a separate part of the same file.


Which is to say, all the docstrings in a modules *could* be placed at 
the end and not normally read in by the interpreter until needed. I have 
no idea what it does now, but I suspect not that. It might make module 
loading a bit faster.



--
Terry Jan Reedy

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


Re: how python works

2010-08-01 Thread Terry Reedy

On 7/30/2010 2:16 PM, Mahmood Naderan wrote:

So is it a compiler or interpreter?


Python is a language. It does not 'work' in the sense of your subject 
line. CPython is a Python compiler/interpreter, as described. When 
loaded, it may be named python.exe, depending on system and 
installation. Jython and IronPython are also Python 
compiler/interpreters. There are also Python compilers of various sorts.


--
Terry Jan Reedy

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


Re: Normalizing A Vector

2010-08-01 Thread Terry Reedy

On 7/30/2010 7:46 AM, Lawrence D'Oliveiro wrote:

Say a vector V is a tuple of 3 numbers, not all zero. You want to normalize
it (scale all components by the same factor) so its magnitude is 1.

The usual way is something like this:

 L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2])
 V = (V[0] / L, V[1] / L, V[2] / L)

What I don’t like is having that intermediate variable L leftover after the
computation.


So, instead of fooling around with error-prone, hard-to-type 
constructions, just delete the damn thing!


def L

Compare those foolproof 5 chars to what at first did not work right and 
even what did.  And, as other said, in most real applications, you will 
normalize in more than one place. In fact, you may well want a vlen 
function.


def vlen(seq): return math.sqrt(sum(x*x for x in seq))

--
Terry Jan Reedy


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


Re: Why is python not written in C++ ?

2010-08-01 Thread Stephen Hansen
On 8/1/10 4:08 PM, candide wrote:
> Python is an object oriented langage (OOL). The Python main
> implementation is written in pure and "old" C90. Is it for historical
> reasons?

Portability if nothing else has been a strong reason to keep the Python
implementation to standard C. Its not as bad as it used to be, but
there's still quite a few differences between various C++ compilers.
Even with the officially supported platforms shrinking of late, and talk
of including some C++ in an isolated part of the CPython implementation
(the UnladenSwallow JIT is C++, IIRC), rewriting the whole thing in C++
seems like a major waste of time.

If you went and used the OO-features of C++, but then you run into a
problem: Python's OO design is strikingly different from C++'s. There's
no enforced encapsulation (on purpose), just as one example.

That's not saying you -couldn't- match Python's OO design on top of C++,
after all-- they've done it in Java, which has a hardcore interpretation
of OOP. But what does that get you over the current status quo? C's
leaner and meaner then C++.

> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more
> suitable to implement an OOL with another one.

Wny would this be more suitable? The Python idea of Object Orientedness
doesn't line up with the C++ own *on purpose*, so why adopt one idea and
design of OOP to implement a different one?

> Has it ever been planned to rewrite in C++ the historical implementation
> (of course in an object oriented design) ?

Have you actually looked at the "historical implementation"? It's
actually quite object oriented. You don't have to have an object
oriented language to use OO design.

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/



signature.asc
Description: OpenPGP digital signature
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Normalizing A Vector

2010-08-01 Thread Matteo Landi
On Mon, Aug 2, 2010 at 1:50 AM, Terry Reedy  wrote:
> On 7/30/2010 7:46 AM, Lawrence D'Oliveiro wrote:
>>
>> Say a vector V is a tuple of 3 numbers, not all zero. You want to
>> normalize
>> it (scale all components by the same factor) so its magnitude is 1.
>>
>> The usual way is something like this:
>>
>>     L = math.sqrt(V[0] * V[0] + V[1] * V[1] + V[2] * V[2])
>>     V = (V[0] / L, V[1] / L, V[2] / L)
>>
>> What I don’t like is having that intermediate variable L leftover after
>> the
>> computation.
>
> So, instead of fooling around with error-prone, hard-to-type constructions,
> just delete the damn thing!
>
> def L

del L

:P

>
> Compare those foolproof 5 chars to what at first did not work right and even
> what did.  And, as other said, in most real applications, you will normalize
> in more than one place. In fact, you may well want a vlen function.
>
> def vlen(seq): return math.sqrt(sum(x*x for x in seq))
>
> --
> Terry Jan Reedy
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Matteo Landi
http://www.matteolandi.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-01 Thread Terry Reedy

On 8/1/2010 7:08 PM, candide wrote:

Python is an object oriented langage (OOL). The Python main
implementation is written in pure and "old" C90. Is it for historical
reasons?


Python was first released before C++. C is available on, and hence 
Python runs on, systems that do not have C++ available.



C is not an OOL and C++ strongly is. I wonder if it wouldn't be more
suitable to implement an OOL with another one.


Python's object system is sufficiently different from that of C++ that I 
doubt the latter could used with much profit.



Has it ever been planned to rewrite in C++ the historical implementation
(of course in an object oriented design) ?


Proposed and rejected. Not every C programmer knows or wants to learn C++.

--
Terry Jan Reedy

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


how best to clear objects from a frame

2010-08-01 Thread Chris Hare
Here is the situation:

I have a window with a bunch of widgets in it.  I want to clear the objects in 
a given frame and recreate them to update them.  

The example below destroys the top level frame, and so I can't recreate the 
widgets.  I am likely doing this wrong.
should I be doing this in a class?


Thanks for the help.

from Tkinter import *

def createLeftWidgets(left):
#
# Add the Net Status Section
#
conditions = LabelFrame(left, text="Net Conditions",bg="Gray")
conditions.grid(row=0,column=0);
button = Button(conditions, text="Refresh", 
command=refreshNetConditions, highlightbackground="Green")
button.grid(row=0,column=1, sticky=E)
cText = Text(conditions,bg="Gray")
cText.insert(END, root.netHistory.get())
cText.config(height=12,width=40)
cText.grid(row=1,column=0,columnspan=2)
status = LabelFrame(left, text="Net Details",bg="Gray")
status.grid(row=1,column=0,sticky=N+E+W+S);
lblNetNumber = Label(status, text="Net Number")
lblNetNumber.grid( row=19, column=0, columnspan=2,sticky=W)
return(conditions)
def refreshNetConditions():
global frameLeft
frameLeft.destroy()
root.netHistory.set( "inserting text\n" + root.netHistory.get())
createLeftWidgets(frameLeft)

root = Tk()
root.netHistory = StringVar()
root.netHistory.set("goes into the text widget")
frame = Frame(root)
frame.grid()
frameLeft = createLeftWidgets(frame)

root.mainloop()

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


Re: Why is python not written in C++ ?

2010-08-01 Thread Roy Smith
In article <[email protected]>,
 candide  wrote:

> Python is an object oriented langage (OOL). The Python main 
> implementation is written in pure and "old" C90. Is it for historical 
> reasons?
> 
> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more 
> suitable to implement an OOL with another one.

One thing that comes to mind is that it's much easier to distribute C 
libraries than C++ libraries.

If I compile a main program with one C compiler and you compile a 
dynamically loaded library with another C compiler on the same box, the 
odds are pretty good they'll interoperate without any problems.

Not at all so with C++ compilers.  The linkage is *way* more 
complicated.  Not just how the two compilers do name mangling, but how 
they handle exceptions, RVO, and a zillion other details.  Pretty much 
the only way to make it work is to compile everything with exactly the 
same compiler.  That would make it pretty close to impossible for people 
to take a Python core distribution and add their own extension modules 
to it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Normalizing A Vector

2010-08-01 Thread Lawrence D'Oliveiro
In message <[email protected]>, Alain Ketterlin wrote:

> Lawrence D'Oliveiro  writes:
> 
>> No, I deliberately put it in that order to ensure that the value for l
>> can only ever be evaulated once.
> 
> Try this (essentially equivalent to your code):
> 
> def f():
> print "hello"
> return 1
> 
> V = tuple( 1 for x in [1,2,3] for l in (f(),) )
> 
> How many "hello"s do you see?
> 
> Comprehension are not loops spelled backwards. The values in:
> 
> whatever for i ... for j ...
> 
> are the values produced by the equivalent code:
> 
> for i ...
> for j ...
> whatever

Damn. I thought that

e for i ... for j ...

was equivalent to

(e for i ...) for j ...

Looks like I was wrong.

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


Re: Problem with Elementtree and XMLSchem instance type

2010-08-01 Thread Lawrence D'Oliveiro
In message
<[email protected]>, Carl 
Banks wrote:

> My general feeling is that ElementTree is a lot handier for reading
> and writing your own XML formats, than for handling XML files produced
> by other tools.

Why is that? I’ve successfully used it to parse SVG files produced by 
Inkscape .
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to set a cookie within a python script

2010-08-01 Thread Steven D'Aprano
On Sun, 01 Aug 2010 09:56:48 -0700, Νίκος wrote:

> Hello fellow Python Coders!
> 
> I don't see the error in my attempt to set a a cookie in this test
> script. 

Neither do I. What makes you think there is an error? What sort of error? 
Do you get a core dump, an exception, or something else?

Please report what you get, and what you expect, and how they are 
different.


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


timeit function

2010-08-01 Thread Mag Gam
Currently, I have a bash shell script which does timing for me. For
example, if I have a Unix Command I typically run time against it for
10 times and then get an average. It works fine but I have to write a
post processing script to get the time and then do a graph on
matplotlib.


I was wondering if the timeit function would be helpful in my case. I
was thinking to open a subprocess to run the Unix command 10 times
(instead of 1 million times) and then do the average and then do the
graph. Any thoughts about this?

Is timeit the right tool for what I am trying to do?

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


Re: how can I solve this erorr usr/lib/python2.6 : permisson denied

2010-08-01 Thread Steven D'Aprano
On Sun, 01 Aug 2010 05:05:39 -0700, Mohseniaref wrote:

> Dear Friend
> I have this erorr after running pyhon script with header
> /usr/lib/python2.6 : permisson denied I change ownership with -hR in
> super user terminal

Please COPY AND PASTE (do NOT retype them):

(1) the header from the script
(2) the command you use to run the script
(3) the error message you get
(4) the command you use to change ownership
(5) the result of that command
(6) what happens if you try running the script again





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


Re: Why is python not written in C++ ?

2010-08-01 Thread John Bokma
Terry Reedy  writes:

> On 8/1/2010 7:08 PM, candide wrote:
>> Python is an object oriented langage (OOL). The Python main
>> implementation is written in pure and "old" C90. Is it for historical
>> reasons?
>
> Python was first released before C++. 

C++ was named C++ in 1983 (development on it started in 1979) and the
first commercial implementation was released in 1985 [1]. Implementation
of Python started in December 1989 [2].

So: no. (I was quite sure on this, since I started to program in C++ in
the late 80's/early 90's IIRC).

[1] 
 http://en.wikipedia.org/wiki/C_plus_plus#History 

[2]
 http://en.wikipedia.org/wiki/Python_%28programming_language%29#History
 http://python-history.blogspot.com/2009/01/brief-timeline-of-python.html

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-01 Thread John Bokma
Roy Smith  writes:

> In article <[email protected]>,
>  candide  wrote:
>
>> Python is an object oriented langage (OOL). The Python main 
>> implementation is written in pure and "old" C90. Is it for historical 
>> reasons?
>> 
>> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more 
>> suitable to implement an OOL with another one.
>
> One thing that comes to mind is that it's much easier to distribute C 
> libraries than C++ libraries.

In the beginning of C++ there were programs that just converted C++ to C
(frontends). At least that is how the C++ compiler Acorn sold worked.
So I don't think your argument was much true back then.

-- 
John Bokma   j3b

Hacking & Hiking in Mexico -  http://johnbokma.com/
http://castleamber.com/ - Perl & Python Development
-- 
http://mail.python.org/mailman/listinfo/python-list


How to catch windows shutdown/reboot message

2010-08-01 Thread rechardchen
I'm writing a python script which runs as a windowsxp service.
The problem is how to catch the windows shutdown/reboot message and do
some cleaning job when system is going down?

The atexit module and signal module on windows dont seems to work. I
guess the python win32api may be of help, but I am not familiar with it...
Thank you
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-01 Thread Christian Heimes
Am 02.08.2010 01:08, schrieb candide:
> Python is an object oriented langage (OOL). The Python main 
> implementation is written in pure and "old" C90. Is it for historical 
> reasons?

Python is written in C89 to support as many platforms as possible. We
deliberately don't use any new features and almost no compiler specific
extensions to make the interpreter portable. AFAIK the only compiler
specific feature used in Python are computed gotos and they are optional.

> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more 
> suitable to implement an OOL with another one.
> 
> Has it ever been planned to rewrite in C++ the historical implementation 
> (of course in an object oriented design) ?

I like to say that the Python interpreter is written in object oriented
C code. Every Python object evolved around PyObject and PyType structs
that are extended (subclassed) to add additional members. Python won't
gain anything useful from a pure C++ implementation. C++ would only add
a major layer of complexity and scary features.

In your opinion what would Python gain from a C++ implementation?

Christian

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


Re: Problem with Elementtree and XMLSchem instance type

2010-08-01 Thread Carl Banks
On Aug 1, 5:43 pm, Lawrence D'Oliveiro  wrote:
> In message
> <[email protected]>, Carl
>
> Banks wrote:
> > My general feeling is that ElementTree is a lot handier for reading
> > and writing your own XML formats, than for handling XML files produced
> > by other tools.
>
> Why is that? I’ve successfully used it to parse SVG files produced by
> Inkscape .

I said it was not handy, not that is was not useful.

And you don't *have* to try to start an argument over every tiny thing
you disagree with.


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


Re: beginner python GUI question

2010-08-01 Thread rechardchen

于 2010-8-2 6:15, Chris Hare 写道:

I hope I can explain this correctly.

I have a GUI, which is already being processed by a mainloop.  I want to be 
able to open a second window so the user can interact with specific information 
in the second window.  I pulled together this code example

from Tkinter import *

class Net:
def __init__(self,tkWin):
self.window = tkWin
def show(self,t):   
self.l = Label(self.window,text=t)
self.l.grid()
 button = Button(self.window, text="Again")
button.bind("", self.Again)
button.grid()
def Again(self,event):
win3 = Tk()
x = Net(win3)
x.show("window 3")

root = Tk()
root.title = "test"
f = Frame(root,bg="Yellow")
l = Label(f,text="window 1")
f.grid()
l.grid()

win2 = Tk()
x = Net(win2)
x.show("window 2")
if __name__ == "__main__":
root.mainloop()

Is this the right way to do things, or would you suggest something different?

Thanks,
Chris


Using Tkinter.Toplevel may be better. :)
--
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-01 Thread Tomasz Rola
On Sun, 1 Aug 2010, John Bokma wrote:

> In the beginning of C++ there were programs that just converted C++ to C
> (frontends). At least that is how the C++ compiler Acorn sold worked.
> So I don't think your argument was much true back then.

Those that I (tried to) used on Amiga were based around the same concept.

It seems, that Comeau C++ compiler (which I never tried) still requires C 
compiler as a backend (and is highly regarded by some).

Regards,
Tomasz Rola

--
** A C programmer asked whether computer had Buddha's nature.  **
** As the answer, master did "rm -rif" on the programmer's home**
** directory. And then the C programmer became enlightened...  **
** **
** Tomasz Rola  mailto:[email protected] **
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-01 Thread Carl Banks
On Aug 1, 6:09 pm, John Bokma  wrote:
> Roy Smith  writes:
> > In article <[email protected]>,
> >  candide  wrote:
>
> >> Python is an object oriented langage (OOL). The Python main
> >> implementation is written in pure and "old" C90. Is it for historical
> >> reasons?
>
> >> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more
> >> suitable to implement an OOL with another one.
>
> > One thing that comes to mind is that it's much easier to distribute C
> > libraries than C++ libraries.
>
> In the beginning of C++ there were programs that just converted C++ to C
> (frontends). At least that is how the C++ compiler Acorn sold worked.
> So I don't think your argument was much true back then.

No, it was that way back then too.  They might all generate C code but
different C code by different backends wouldn't be able to call each
other natively.

For instnace the function

int foo(int);

might be name-mangled this way in one cfront:

foo$d

and this way in another:

int_foo__int_i


The virtual table of this class:

class Bar {
virtual int foo(int);
virtual int bar(int);
};

might be generated like this in one cfront:

struct Bar$$Vtable$ {
int (*Bar$$bar$d)(int);
int (*Bar$$foo$d)(int);
};

and like this in another:

struct class_Foo___vtable_ {
int (*foo)(int);
int (*bar)(int);
};


So, just because they both generated C code, it doesn't mean they can
call one another.


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


co_firstlineno on decorated functions

2010-08-01 Thread Eli Bendersky
Hello,

I've been tinkering with __code__.co_firstlineno for testing the trace.py
module (Python Issue 9315), and ran into an interesting problem. Consider
this code:


def dummydecorator(f):
return f

def foo(a):
return a

@dummydecorator
def bar(a):
return a


if __name__ == "__main__":
print foo.__code__.co_firstlineno
print bar.__code__.co_firstlineno


The first print out correctly specifies the line "def foo" is in. However,
the second one points to the line with "@dummydecorator" instead of "def
bar". [Python 2.6]

The side-effects of this behavior can be easily seen in the output of
modules like trace and profile. Would you say it's normal, or could this be
considered a bug?

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


Re: Trying to set a cookie within a python script

2010-08-01 Thread Νίκος
>On 2 Αύγ, 03:52, Steven D'Aprano  wrote:

> Neither do I. What makes you think there is an error? What sort of error?
> Do you get a core dump, an exception, or something else?
>
> Please report what you get, and what you expect, and how they are
> different.

Hello Steven,

Here is the script when it tries to run from my remote web server:
http://www.webville.gr/cgi-bin/koukos.py

Its seems the error is in this line of code, somwthing with time.

19 cookie['visitor'] = ( 'nikos', time() +
60*60*24*365 )  #this cookie will expire in an year

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


Re: Trying to set a cookie within a python script

2010-08-01 Thread Νίκος
Also my greek print appear in funny encoding although i do use # -*-
coding: utf-8 -*-
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Docstrings and PEP 3174

2010-08-01 Thread Carl Banks
On Aug 1, 4:26 pm, Terry Reedy  wrote:
> On 8/1/2010 4:30 AM, Gregory Ewing wrote:
>
> > Steven D'Aprano wrote:
>
> >> If you mean a runtime optimization with no change to the source file,
> >> then maybe, tell me more.
>
> > Note that you don't necessarily need a separate file for this.
> > It could just be a separate part of the same file.
>
> Which is to say, all the docstrings in a modules *could* be placed at
> the end and not normally read in by the interpreter until needed.

I'm going to guess that they don't want that in *.pyc files.  In PEP
3147 they proposed a fat-format file (so a glob for each version) and
it was not popular.

> I have
> no idea what it does now,

There's a short header, then the rest of the file is a single
marshaled glob.


> but I suspect not that. It might make module
> loading a bit faster.

True but still probably a small optimization.


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


Re: Why is python not written in C++ ?

2010-08-01 Thread Albert Hopkins
On Mon, 2010-08-02 at 01:08 +0200, candide wrote:
> Python is an object oriented langage (OOL). The Python main 
> implementation is written in pure and "old" C90. Is it for historical 
> reasons?
> 
> C is not an OOL and C++ strongly is. I wonder if it wouldn't be more 
> suitable to implement an OOL with another one.
> 
> Has it ever been planned to rewrite in C++ the historical implementation 
> (of course in an object oriented design) ?

Disclaimer: I am neither a C nor C++ programmer.  In fact I can barely
even program in Python ;-)

I would propose that in fact most programming languages are implemented
in C.  Sun's (Oracle's) Java compiler and runtime are written in ANSI C.
The core of the Gnu Compiler Collection (which includes C++ and
Objective-C compilers) is written in C.  The official Ruby is
implemented in C. The Squeak Smalltalk implementation uses C instead of
C++.  I can't even think of a programming language that is implemented
in C++ (maybe C++ is).

C seems to be a good, portable language for writing interpreters and
compilers.

But I wonder if someone has/has tried to write a programming language in
C++ and what were their experiences.

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


Re: Trying to set a cookie within a python script

2010-08-01 Thread MRAB

Νίκος wrote:

Also my greek print appear in funny encoding although i do use # -*-
coding: utf-8 -*-


That line just tells Python what encoding the source file itself uses.
It doesn't affect what the program does or how it runs.
--
http://mail.python.org/mailman/listinfo/python-list


Re: [Python-Dev] [RELEASED] Python 3.2 alpha 1

2010-08-01 Thread Benjamin Peterson
Hey, Georg! Congrats on your first release!

2010/8/1 Georg Brandl :
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> On behalf of the Python development team, I'm happy to announce the
> first alpha preview release of Python 3.2.
>
> Python 3.2 is a continuation of the efforts to improve and stabilize the
> Python 3.x line.  Since the final release of Python 2.7, the 2.x line
> will only receive bugfixes, and new features are developed for 3.x only.
>
> Since PEP 3003, the Moratorium on Language Changes, is in effect, there
> are no changes in Python's syntax and built-in types in Python 3.2.
> Development efforts concentrated on the standard library and support for
> porting code to Python 3.  Highlights are:
>
> * numerous improvements to the unittest module
> * PEP 3147, support for .pyc repository directories
> * an overhauled GIL implementation that reduces contention
> * many consistency and behavior fixes for numeric operations
> * countless fixes regarding string/unicode issues; among them full
>  support for a bytes environment (filenames, environment variables)
> * a sysconfig module to access configuration information
> * a pure-Python implementation of the datetime module
> * additions to the shutil module, among them archive file support
> * improvements to pdb, the Python debugger
>
> For an extensive list of changes in 3.2, see Misc/NEWS in the Python
> distribution.
>
> To download Python 3.2 visit:
>
>     http://www.python.org/download/releases/3.2/
>
> 3.2 documentation can be found at:
>
>     http://docs.python.org/3.2/
>
> Please consider trying Python 3.2 with your code and reporting any bugs
> you may notice to:
>
>     http://bugs.python.org/
>
>
> Enjoy!
>
> - --
> Georg Brandl, Release Manager
> georg at python.org
> (on behalf of the entire python-dev team and 3.2's contributors)
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v2.0.16 (GNU/Linux)
>
> iEYEARECAAYFAkxVQJsACgkQN9GcIYhpnLBxIgCcCiVu/QUkFf0bYM2Vmi8St3mZ
> 2N4An04q36lr47OA+bslqG/4Zj7ZwVOX
> =iL8N
> -END PGP SIGNATURE-
> ___
> Python-Dev mailing list
> [email protected]
> http://mail.python.org/mailman/listinfo/python-dev
> Unsubscribe: 
> http://mail.python.org/mailman/options/python-dev/benjamin%40python.org
>



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


Re: how best to clear objects from a frame

2010-08-01 Thread rantingrick
On Aug 1, 7:12 pm, Chris Hare  wrote:
> Here is the situation:
>
> I have a window with a bunch of widgets in it.  I want to clear the objects 
> in a given frame and recreate them to update them.  

You need to check out the "w.update" and "w.update_idletasks" methods
available on all Tkinter widgets. Just FYI: to remove a widget from
view without destroying it use "w.pack_forget" or "w.grid_forget".
However if you are simply trying to refresh a widget use one of the
update methods.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Trying to set a cookie within a python script

2010-08-01 Thread Steven D'Aprano
On Sun, 01 Aug 2010 19:16:29 -0700, Νίκος wrote:

>>On 2 Αύγ, 03:52, Steven D'Aprano 
>>wrote:
> 
>> Neither do I. What makes you think there is an error? What sort of
>> error? Do you get a core dump, an exception, or something else?
>>
>> Please report what you get, and what you expect, and how they are
>> different.
> 
> Hello Steven,
> 
> Here is the script when it tries to run from my remote web server:
> http://www.webville.gr/cgi-bin/koukos.py
> 
> Its seems the error is in this line of code, somwthing with time.
> 
> 19 cookie['visitor'] = ( 'nikos', time() + 60*60*24*365 )   
>   #this cookie will expire in an year


What error? Please copy and paste (do not retype) the entire error you 
get.


-- 
Steven

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


Re: Docstrings and PEP 3174

2010-08-01 Thread Steven D'Aprano
On Sun, 01 Aug 2010 20:30:22 +1200, Gregory Ewing wrote:

> Steven D'Aprano wrote:
> 
>> If you mean a runtime optimization with no change to the source file,
>> then maybe, tell me more.
> 
> Note that you don't necessarily need a separate file for this. It could
> just be a separate part of the same file.

I would disagree with any attempt to move the docstring away from 
immediately next to the function in the source file.

You can currently do that if you insist, after all __doc__ is just an 
ordinary attribute:

>>> def f():
... pass
...
>>> f.__doc__ = some_other_text


I don't think we should do anything that *encourages* people to separate 
the code and docstrings in the source file.

On the assumption that functions will continue to be written:

def f():
"""Doc string"""
pass


I like the proposal to make f.__doc__ a descriptor that lazily loads the 
doc string from disk when needed, rather than keeping the string in 
memory at all times. Whether this leads to enough memory savings to 
justify it is an open question.



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


Re: Why is python not written in C++ ?

2010-08-01 Thread Tomasz Rola
On Sun, 1 Aug 2010, Albert Hopkins wrote:

> C seems to be a good, portable language for writing interpreters and
> compilers.

And one should not forget about performance. C++ was for a long time 
behind C, and even now some parts (like iostreams) should be avoided in 
fast code.

BTW, C++ can be IMHO a bit tricky in situations when one would like to 
call back from JIT-generated code into parts written in C++... I mean 
things like virtual functions, overloading, code generated from templates, 
accessing private members etc. All those issues are non essential from the 
point of interpreting or JIT, yet they stand in a way. While this could be 
solved (with some headache, I suspect), C is far simpler and function 
calls or manipulating structs are actually trivial...

Regards,
Tomasz Rola

--
** A C programmer asked whether computer had Buddha's nature.  **
** As the answer, master did "rm -rif" on the programmer's home**
** directory. And then the C programmer became enlightened...  **
** **
** Tomasz Rola  mailto:[email protected] **
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why is python not written in C++ ?

2010-08-01 Thread Michael Torrie
On 08/01/2010 07:09 PM, John Bokma wrote:
>> One thing that comes to mind is that it's much easier to distribute C 
>> libraries than C++ libraries.
> 
> In the beginning of C++ there were programs that just converted C++ to C
> (frontends). At least that is how the C++ compiler Acorn sold worked.
> So I don't think your argument was much true back then.

No, he is still right.  Each C++ implementation did name mangling
differently leading to "C" libraries that had incompatible names and
signatures.  Also each frontend could have generated incompatible
vtables and other C++ structures.  So C code generated by one C++
frontend could not easily call C code generated by another C++ frontend.
 So the same arguments that are made about C++ now were just as valid
back then when C++ was merely a fancy preprocessor.


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


Merging two dictionaries

2010-08-01 Thread Douglas Garstang
Anyone,

I have the two dictionaries below. How can I merge them, such that:

1. The cluster dictionary contains the additional elements from the
default dictionary.
2. Nothing is removed from the cluster dictionary.

The idea here is that the two dictionaries are read from different
files where, if the value isn't found in the cluster dictionary, it's
pulled from the default one, and I can have a new dictionary
reflecting this. The update() method on dictionaries doesn't seem to
work. The resulting dictionary always seems to be the one passed as a
parameter.

default = {
'cluster': {
'platform': {
'elements': {
'data_sources': {
'elements': {
'db_min_pool_size': 10
},
},
},
},
}
}

cluster = {
'cluster': {
'name': 'Customer 1',
'description': 'Production',
'environment': 'production',
'platform': {
'elements': {
'data_source': {
'elements': {
'username': 'username',
'password': 'password'
},
},
},
},
}
}

The resulting dictionary would therefore look like this:

new_dict = {
'cluster': {
'name': 'Customer 1',
'description': 'Production',
'environment': 'production',
'platform': {
'elements': {
'data_source': {
'elements': {
'username': 'username',
'password': 'password',
'db_min_pool_size': 10 # This was added from
the default.
},
},
},
},
}
}


Thanks,
Doug.

-- 
Regards,

Douglas Garstang
http://www.linkedin.com/in/garstang
Email: [email protected]
Cell: +1-805-340-5627
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-01 Thread Michele Simionato
On Jul 31, 5:08 am, Steven D'Aprano  wrote:
> I have read Michelle Simionato's articles on super in Python.

One "l" please! I am a man! ;-)

>
> But Michelle is wrong to conclude that the problem lies with the concept
> of *superclass*. The problem lies with the idea that there is ONE
> superclass. By dismissing the entire concept, he is throwing out the baby
> with the bathwater.

I am actually more radical than that. From
http://www.artima.com/weblogs/viewpost.jsp?thread=237121:

"""
In this series I have argued that super is tricky; I think nobody can
dispute that. However the existence of dark corners is not a
compelling argument against a language construct: after all, they are
rare and there is an easy solution to their obscurity, i.e.
documenting them. This is what I have being doing all along. On the
other hand, one may wonder if all super warts aren't hints of some
serious problem underlying. It may well be that the problem is not
with super, nor with cooperative methods: the problem may be with
multiple inheritance itself.
"""

Then I spend thousands of words in the "Mixin considered harmful"
series and in other articles arguing against
multiple inheritance and cooperative methods. They are just bad design
IMO. Of course we are in the range of opinions, this is a tricky
subject: many smart people agree with me and many others equally smart
disagree.
Still I believe that super is a red herring and that you should really
start thinking: what advantages did
multiple inheritance *really* bring into my code? Could have I done
without? And what would have happen?
These are the relevant question, not the exact meaning of super in
hairy hierarchies.

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


Re: Builtn super() function. How to use it with multiple inheritance? And why should I use it at all?

2010-08-01 Thread Paul Rubin
Michele Simionato  writes:
> I am actually more radical than that. From
> http://www.artima.com/weblogs/viewpost.jsp?thread=237121:
> In this series I have argued that super is tricky; I think nobody can...

When I look at that URL, I see a Java stack dump:

  java.lang.RuntimeException: 
com.jivesoftware.forum.ForumThreadNotFoundException: ID -1 is not valid
  at 
com.artima.jivecoupled.skins.weblogs.ViewPostPage.process(ViewPostPage.java:112)
  ...

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


Re: Trying to set a cookie within a python script

2010-08-01 Thread Νίκος
If you just click in my web page to see the script run in action due
to the cgitb module i use it will provide you both the source code
that the error appears and the error as well.

All you have to do is click here: http://www.webville.gr/cgi-bin/koukos.py

As for the encoding why when i print greek characters they dont appear
correctly in chrome in runtime?
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: The untimely dimise of a weak-reference

2010-08-01 Thread Vincent van Beveren
Hi Gregory,


> You can create your own wrapper that keeps a weak reference to
> the underlying object. Here's an example.
> [...]

Thanks for the code!

Regards,
Vincent

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


RE: The untimely dimise of a weak-reference

2010-08-01 Thread Vincent van Beveren
Hi Christiaan,



> Instances of a class have no means of storing the bound method object.
> The or unbound bound method is a simple and small wrapper that keeps a
> reference to the class, "self" and the function object. Python keeps a
> pool of empty method objects in a free list. The creation of a new bound
> method just takes a few pointer assignments and three INCREFs.

Okay, that also explains the consistent memory assignment. Maybe I'll create a 
bound-method caching object, see how slow/fast it is in comparison, and see 
what ever other issues I run into.
 
Regards,
Vincent
 

-Original Message-
From: [email protected] 
[mailto:[email protected]] On Behalf Of 
Christian Heimes
Sent: vrijdag 30 juli 2010 16:44
To: [email protected]
Subject: Re: The untimely dimise of a weak-reference

Am 30.07.2010 16:06, schrieb Vincent van Beveren:
> I did not know the object did not keep track of its bound methods. What 
> advantage is there in creating a new bound method object each time its 
> referenced? It seems kind of expensive.
Christian

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


sending a file chunk by chunk instead as a whole to a web server

2010-08-01 Thread Sanjeeb
Hi,
I have a web client which send a file to a server as multipart form
data, the sending of data is from
http://code.activestate.com/recipes/146306-http-client-to-post-using-multipartform-data/.

I dont want to open the whole file to memory(at cliend end) and then
send, i just want to send part by part, say chunk of 1024 bytes to the
server and then assemble at the server end.

Could some one suggest what would be the best way to do this?

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