Re: Validating Entry in tkinter

2011-07-25 Thread Peter Otten
Saul Spatz wrote:

> In tcl/tk an Entry widget can be set to validate its contents with the
> validate option.  You have to give it a validatecommand (vcmd), which is a
> tcl script that runs when some action triggers validation.  Usually, the
> script would use "percent substitutions" so the script would be something
> like {ValidInt %P} where %P is the value of the widget should the proposed
> change occur.
> 
> Can one do something like this in tkinter?  I've verified that with
> 
> e = Entry(master, validate = 'all', vcmd = validInt)
> 
> the validInt function is called, but it isn't passed any parameters. I
> can't find that e has any attribute corresponding to the %P value above.
> 
> Is it not possible to do this in tkinter, or have I overlooked something?

Some time ago I came up with 

http://mail.python.org/pipermail/python-list/2009-September/1220447.html

import Tkinter as tk

def validate(before, after):
print before, "-->", after
return after.isdigit()

if __name__ == "__main__":
root = tk.Tk()
name = root.register(validate)
cmd = 'expr {[%(name)s %(parms)s]}' % dict(name=name, parms="%s %P")
var = tk.StringVar()
entry = tk.Entry(root, textvariable=var,
 validate="all", validatecommand=cmd)
entry.pack()
entry.focus_set()
root.mainloop()


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


Re: Aw: python.org back up ?(was Re: python.org is down?)

2011-07-25 Thread Carl Banks
On Sunday, July 24, 2011 11:42:45 AM UTC-7, David Zerrenner wrote:
> *pew* I can't live without the docs, that really made my day now.

If you can't live without the docs, you should consider downloading them and 
accessing them locally.  That'll let you work whenever python.org goes down, 
and will help keep the load off the server when it's up.


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


Re: Strings show as brackets with a 'u'.

2011-07-25 Thread Ulrich Eckhardt
Chris Angelico wrote:
> On Sun, Jul 24, 2011 at 10:33 AM, goldtech  wrote:
>>
>> I'm using using Idle on winXP, activestate 2.7. Is there a way to
>> suppress this and just show 174  in the shell ?
>> A script reading data and assigns 174 to n via some regex. Links on
>> this appreciated - I've tried to understand unicode before, will keep
>> trying...thanks.
> 
> There's two things there. Firstly, your regex is returning a list, not
> a string; and secondly, you are seeing repr(n) instead of just its
> content. Try:
 print(n[0])
> 
> This should print just the value.
> 
> (Pro tip: rantingrick is a troll. You can safely ignore him.)

If he's a troll, he's one of the better trolls here IMHO because he gave the 
best advise in this thread. You just gave the OP a fish, he provided a 
valuable advise on fishing itself.

Uli

-- 
Domino Laser GmbH
Geschäftsführer: Thorsten Föcking, Amtsgericht Hamburg HR B62 932

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


Re: Validating Entry in tkinter

2011-07-25 Thread Wolfgang Meiners
Am 25.07.11 02:11, schrieb Saul Spatz:
> In tcl/tk an Entry widget can be set to validate its contents with the 
> validate option.  You have to give it a validatecommand (vcmd), which is a 
> tcl script that runs when some action triggers validation.  Usually, the 
> script would use "percent substitutions" so the script would be something 
> like {ValidInt %P} where %P is the value of the widget should the proposed 
> change occur.  
> 
> Can one do something like this in tkinter?  I've verified that with
> 
> e = Entry(master, validate = 'all', vcmd = validInt) 
> 
> the validInt function is called, but it isn't passed any parameters. I can't 
> find that e has any attribute corresponding to the %P value above.
> 
> Is it not possible to do this in tkinter, or have I overlooked something? 

Hi,
i think you can find the answer using the following link:
http://stackoverflow.com/questions/4140437/python-tkinter-interactively-validating-entry-widget-content

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


Aw: Re: Aw: python.org back up ?(was Re: python.org is down?)

2011-07-25 Thread David Zerrenner
Carl Banks wrote:
> If you can't live without the docs, you should consider downloading them and 
> accessing them locally.  That'll let you work whenever python.org goes down, 
> and will help keep the load off the server when it's up.

Thanks for the pointer, i did not realize that until now... These days of 
always-on internet corrupted me so much.

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


Re: Convert '165.0' to int

2011-07-25 Thread Steven D'Aprano
On Mon, 25 Jul 2011 10:07 am Billy Mays wrote:

> On 7/24/2011 2:27 PM, SigmundV wrote:

>> list_of_integers = map(string_to_int, list_of_strings)
>>
>> Of course, this will be horribly slow if you have thousands of
>> strings. In such a case you should use an iterator (assuming you use
>> python 2.7):
>>
>> import itertools as it
>> iterator = it.imap(string_to_int, list_of_strings)

 
> if the goal is speed, then you should use generator expressions:
> 
> list_of_integers = (int(float(s)) for s in list_of_strings)


I'm not intending to pick on Billy or Sigmund here, but for the beginners
out there, there are a lot of myths about the relative speed of map, list
comprehensions, generator expressions, etc.

The usual optimization rules apply:

We should forget about small efficiencies, say about 97% of 
the time: premature optimization is the root of all evil.
-- Donald Knuth

More computing sins are committed in the name of efficiency 
(without necessarily achieving it) than for any other single 
reason - including blind stupidity. -- W.A. Wulf

and of course:

If you haven't measured it, you're only guessing whether it is 
faster or slower. 

(And unless you're named Raymond Hettinger, I give little or no credibility
to your guesses except for the most obvious cases. *wink*)

Generators (including itertools.imap) include some overhead which list
comprehensions don't have (at least in some versions of Python). So for
small sets of data, creating the generator may be more time consuming than
evaluating the generator all the way through.

For large sets of data, that overhead is insignificant, but in *total*
generators aren't any faster than creating the list up front. They can't
be. They end up doing the same amount of work: if you have to process one
million strings, then whether you use a list comp or a gen expression, you
still end up processing one million strings. The only advantage to the
generator expression (and it is a HUGE advantage, don't get me wrong!) is
that you can do the processing lazily, on demand, rather than all up front,
possibly bailing out early if necessary.

But if you end up pre-processing the entire data set, there is no advantage
to using a gen expression rather than a list comp, or map. So which is
faster depends on how you end up using the data.

One other important proviso: if your map function is a wrapper around a
Python expression:

map(lambda x: x+1, data)
[x+1 for x in data]

then the list comp will be much faster, due to the overhead of the function
call. List comps and gen exprs can inline the expression x+1, performing it
in fast C rather than slow Python.

But if you're calling a function in both cases:

map(int, data)
[int(x) for x in data]

then the overhead of the function call is identical for both the map and the
list comp, and they should be equally as fast. Or slow, as the case may be.

But don't take my word on this! Measure, measure, measure! Performance is
subject to change without notice. I could be mistaken.

(And don't forget that everything changes in Python 3. Whatever you think
you know about speed in Python 2, it will be different in Python 3.
Generator expressions become more efficient; itertools.imap disappears; the
built-in map becomes a lazy generator rather than returning a list.)


-- 
Steven

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


cross-compiling python-2.5.1 for PPC, error in Modules/unicodedata.o

2011-07-25 Thread Robert P. J. Day

  not sure if this is the right list for this, but it's a starting
point.  i'm using a wind river linux development environment to build
a full system for a powerpc board, and that includes cross-compiling
python-2.5.1 for ppc.  the compile fails thusly:

powerpc-wrs-linux-gnu-ppc_e500v2-glibc_std-gcc -shared
Modules/unicodedata.o   -o Modules/unicodedata.so
Modules/unicodedata.o: file not recognized: File truncated
collect2: ld returned 1 exit status
Makefile:1159: *** [Modules/unicodedata.so] Error 1

... snip ...
#0  Modules/unicodedata.so at
/home/rpjday/workspace/8548_prj/build/python-2.5.1/BUILD/Python-2.5.1/Makefile:1159
#1  oldsharedmods at
/home/rpjday/workspace/8548_prj/build/python-2.5.1/BUILD/Python-2.5.1/Makefile:440
#2  all at
/home/rpjday/workspace/8548_prj/build/python-2.5.1/BUILD/Python-2.5.1/Makefile:353
Command-line arguments:
"OPT=-g -O2 -fomit-frame-pointer -pipe -g -O2
-fomit-frame-pointer -pipe -D_GNU_SOURCE -fPIC -I=/usr/include
-I=/home/rpjday/workspace/8548_prj/host-cross/powerpc-wrs-linux-gnu/sysroot/usr/include/krb5
DESTDIR=/home/rpjday/workspace/8548_prj/host-cross/powerpc-wrs-linux-gnu/sysroot/usr/lib/../..
HOSTPYTHON=./hostpython HOSTPGEN=./Parser/hostpgen"
error: Bad exit status from
/home/rpjday/workspace/8548_prj/build/python-2.5.1/rpm-tmp.86223
(%build)
... snip ...

  you can see that the file Modules/unicodedata.o is flagged as not
recognized.  in fact, it exists but is empty.  i'm going to continue
digging around but i'm open to suggestions.  i also have the full 1700
lines of output from the beginning of the cross-compile if anyone
wants to see it.  thanks, and is there a more appropriate place to ask
this?

rday

-- 


Robert P. J. Day Ottawa, Ontario, CANADA
http://crashcourse.ca

Twitter:   http://twitter.com/rpjday
LinkedIn:   http://ca.linkedin.com/in/rpjday

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


Re: reportlab import error after dundled using py2exe

2011-07-25 Thread Robin Becker

On 22/07/2011 03:55, SANKAR . wrote:

Hi all,





C:\Python26\dist>DELchek.exe
Traceback (most recent call last):
File "DELchek.py", line 12, in
File "reportlab\pdfgen\canvas.pyc", line 25, in<
File "reportlab\pdfbase\pdfdoc.pyc", line 22, in
File "reportlab\pdfbase\pdfmetrics.pyc", line 23,
File "reportlab\pdfbase\_fontdata.pyc", line 158,
ImportError: No module named _fontdata_enc_winansi

But I could see the '_fontdata_enc_winansi' module in reportlab folder.
Could someone help me to fix this.


.
You can try asking this in the reportlab list

reportlab-us...@lists2.reportlab.com

but perhaps this is more about py2exe than reportlab. The modules 
_fontdata_enc_* & _fontdata_widths_* are imported dynamically in _fontdata.py 
rather than explicitly. I suspect that py2exe needs to be given a hint that this 
is going on. However, I'm uncertain as to why this should be required since even 
if the imports are being dynamically imported that is done as soon as _fontdata 
is imported (ie it's part of the module code) so those modules should be seen by 
the setup.py.


If you don't have reportlab explicitly imported as part of the packages try 
adding this to the packages list


packages=[




'reportlab',
'reportlab.graphics.charts',
'reportlab.graphics.samples',
'reportlab.graphics.widgets',
'reportlab.graphics.barcode',
'reportlab.graphics',
'reportlab.lib',
'reportlab.pdfbase',
'reportlab.pdfgen',
'reportlab.platypus',
],


that's what we use to make the distributions and seems to work.
--
Robin Becker

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


PyCon UK 2011 - 24th to 25th September 2011 - Conference Announcement and Booking details

2011-07-25 Thread Zeth
The UK's official Python conference returns. It is aimed at everyone
in the Python community, of all skill levels, from beginners to core
developers.

The conference will be held on the 24th to 25th September 2011, in the
TechnoCentre Coventry (CV1 2TT).

The conference is not-for-profit and community-run by volunteers. It
is your conference so you can give a talk, lead a workshop or help
with publicity - see our wiki for more details.

In particular, it would help a lot if you can forward this
announcement to your Python-using friends and colleagues and relevant
mailing lists, or link to our website on Twitter, Facebook, Google+
and so on.

Booking is open now. The ticket cost for the weekend is £95 which
includes access to all sessions, lunches, refreshments, the exclusive
PyCon UK T-shirt and the unmissable conference dinner (Concession rate
is £75).

For more details and to book, please visit our website at http://pyconuk.org/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aw: Re: Aw: python.org back up ?(was Re: python.org is down?)

2011-07-25 Thread hackingKK
Infact the  first thing I ever did  with documentation on Python was to 
download it.
yes you are not uptodate but you can always do a download once in a 
while rather than putting load on the server every time you want to 
lookup a function reference.

Happy hacking.
Krishnakant.

On 25/07/11 14:32, David Zerrenner wrote:

Carl Banks wrote:

If you can't live without the docs, you should consider downloading them and 
accessing them locally.  That'll let you work whenever python.org goes down, 
and will help keep the load off the server when it's up.

Thanks for the pointer, i did not realize that until now... These days of 
always-on internet corrupted me so much.



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


Re: PEP 8 and extraneous whitespace

2011-07-25 Thread Neil Cerutti
On 2011-07-24, Ben Finney  wrote:
> Code is also more densely expressive and provides less
> redundancy in expression, and the reader is required to make
> much finer scrutiny of it than of natural language text.

The best writing is less redundant than a line of code, not more.
But most people don't have enough time to write that little.

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


Re: Validating Entry in tkinter

2011-07-25 Thread Saul Spatz
Thanks so much, this is great.  I want to validate that the user is entering a 
string appropriate for bytes.fromhex.  Here's how I modified your validate 
funtion:

def validate(before, after):
print(before, "-->", after)
#return after.isdigit()
return after[-1] in '1234567890abcdefABCDEF '

I also had to change validate="all" to validate="key" in the Entry 
construction, since otherwise, I go an IndexError when the widget gets the 
focus.  (try...except also worked, but I only care about keystrokes.)

I didn't know about the register method; that's the key.

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


Pipe in the "return" statement

2011-07-25 Thread Archard Lias
Hi,

I have come across something I don't really understand and would be
grateful if someone could shed some light into my understanding of it.

In the documentation of the Qt4 libs in the page regarding the
QAbstractTableModel you find, to make the table editable, the
following:

Qt::ItemFlags StringListModel::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;

 return QAbstractItemModel::flags(index) | Qt::ItemIsEditable;
}

Now I'm working with PySide, the Python bindings from Nokia and I
figured the
return in the function to be related with a parent
(QAbstractItemModel)
followed by the actual Flag that says: "yes the item, the index is
pointing
at, is actually editable". So translation of the C++ to Python would
be, and
it actually worked:

def flags(self, index):
if not index.isValid():
return Qt.ItemIsEnabled

return super(self.__class__, self).flags(index) |
Qt.ItemIsEditable

Still I dont get how I am supposed to understand the pipe and its task/
idea/influece on control flow, of:
return  | 
??

Thankful if you could help me with this.

Kind regards,
Archard Lias
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pipe in the "return" statement

2011-07-25 Thread Ian Collins

On 07/26/11 12:00 AM, Archard Lias wrote:

Hi,

Still I dont get how I am supposed to understand the pipe and its task/
idea/influece on control flow, of:
return  |
??


It's simply a bitwise OR.

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


Re: Validating Entry in tkinter

2011-07-25 Thread Saul Spatz
That doesn't work, I'm being stupid,  The user might type anywhere in the 
string, not just at the end.  I need

return all([c in '1234567890abcdefABCDEF ' for c in after])
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pipe in the "return" statement

2011-07-25 Thread Christian Heimes
Am 25.07.2011 14:00, schrieb Archard Lias:
> def flags(self, index):
> if not index.isValid():
> return Qt.ItemIsEnabled
> 
> return super(self.__class__, self).flags(index) |

Your use of super() is incorrect and will not work as you might expect.
You *must* use the class here, never self.__class__.

Christian

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


Re: Validating Entry in tkinter

2011-07-25 Thread Peter Otten
Saul Spatz wrote:

> That doesn't work, I'm being stupid,  The user might type anywhere in the
> string, not just at the end.  I need
> 
> return all([c in '1234567890abcdefABCDEF ' for c in after])

Ah, you found out already. Here's what I've come up with in the meantime.
I also changed the command to a tuple as in the example pointed out by 
Wolfgang.

import tkinter as tk

def is_valid_fromhex(s):
for pad in "", "0":
try:
bytes.fromhex(s + pad)
except ValueError:
pass
else:
return True
return False

def validate(before, after):
print(before, "-->", after)
return is_valid_fromhex(after)

if __name__ == "__main__":
root = tk.Tk()
cmd = (root.register(validate), "%s", "%P")
entry = tk.Entry(root, validate="all", validatecommand=cmd)
entry.pack()
entry.focus_set()
root.mainloop()

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


Re: Pipe in the "return" statement

2011-07-25 Thread TonyO
> Still I dont get how I am supposed to understand the pipe and its task/
> idea/influece on control flow, of:
> return  | 

In the words of René Magritte,

return  | 
   ^
Ceci n'est pas une pipe.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pipe in the "return" statement

2011-07-25 Thread gwowen
On Jul 25, 1:52 pm, TonyO  wrote:

>> return  | 
>
> In the words of René Magritte,
>
> return  | 
>                    ^
> Ceci n'est pas une pipe.

*golf clap*
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tkinter/py2exe with installer

2011-07-25 Thread John Posner
On 2:59 PM, Kevin Walzer wrote:
> Can anyone point me in the direction of a Tkinter/Python app that has
> been wrapped with py2exe and is deployed on Windows as a standalone
> using one of the standard installer tools? (MSI, NSIS, Inno Setup,
> etc.) I'm working on a Tkinter app for Windows and have had a
> surprisingly hard time finding such apps to use as
> examples/benchmarks, etc. (The only one I've found, in fact, is
> Webgobbler at http://sebsauvage.net/python/webgobbler/index.html; a
> nice app, but I'd like more examples.)
>
I used Inno Setup 5.4.0(a) to create the "ClixTur" executable at
http://www.jjposner.net/5273.html

Inno Setup gives the executable an execrable name (looks like a GUID),
but it works fine.

HTH,
John

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


Re: Tkinter/py2exe with installer

2011-07-25 Thread John Posner
On 2:59 PM, Kevin Walzer wrote:
> Can anyone point me in the direction of a Tkinter/Python app that has
> been wrapped with py2exe and is deployed on Windows as a standalone
> using one of the standard installer tools? (MSI, NSIS, Inno Setup,
> etc.) I'm working on a Tkinter app for Windows and have had a
> surprisingly hard time finding such apps to use as
> examples/benchmarks, etc. (The only one I've found, in fact, is
> Webgobbler at http://sebsauvage.net/python/webgobbler/index.html; a
> nice app, but I'd like more examples.)
>

I used Inno Setup 5.4.0(a) to create the "ClixTur" executable at
http://www.jjposner.net/5273.html

Inno Setup gives the .exe file a GUID for a name (ugh!) but it works fine.

HTH,
John

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


Re: Pipe in the "return" statement

2011-07-25 Thread Archard Lias
On Jul 25, 2:03 pm, Ian Collins  wrote:
> On 07/26/11 12:00 AM, Archard Lias wrote:
>
> > Hi,
>
> > Still I dont get how I am supposed to understand the pipe and its task/
> > idea/influece on control flow, of:
> > return  |
> > ??
>
> It's simply a bitwise OR.
>
> --
> Ian Collins

Yes, but how does it get determined, which one actually gets returned?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pipe in the "return" statement

2011-07-25 Thread Billy Mays

On 07/25/2011 10:16 AM, Archard Lias wrote:

On Jul 25, 2:03 pm, Ian Collins  wrote:

On 07/26/11 12:00 AM, Archard Lias wrote:


Hi,



Still I dont get how I am supposed to understand the pipe and its task/
idea/influece on control flow, of:
return|
??


It's simply a bitwise OR.

--
Ian Collins


Yes, but how does it get determined, which one actually gets returned?



The return statement returns a single value from a function context. 
The pipe operator takes 2 values and bitwise ORs* them together.  That 
result is then returned to the caller.  The pipe character in this 
instance is not the same as in a shell.


* This is not exactly true, but don't worry about it.

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


Re: Pipe in the "return" statement

2011-07-25 Thread Oliver Bestwalter
Hello Archard,

On 25.07.2011, at 16:16, Archard Lias wrote:

> On Jul 25, 2:03 pm, Ian Collins  wrote:
>> On 07/26/11 12:00 AM, Archard Lias wrote:
>> 
>>> Hi,
>> 
>>> Still I dont get how I am supposed to understand the pipe and its task/
>>> idea/influece on control flow, of:
>>> return  |
>>> ??
>> 
>> It's simply a bitwise OR.
>> 
>> --
>> Ian Collins
> 
> Yes, but how does it get determined, which one actually gets returned?

You do a Bitwise OR with numbers. Your statements are both returning numbers 
and those are combined with a bitwise OR. Combining b0001 with b0010 results in 
0011 for example, you can see this very often done in C Code to set and check 
flags. Here is a gentle introduction:

http://www.codeproject.com/KB/tips/Binary_Guide.aspxhttp://www.codeproject.com/KB/tips/Binary_Guide.aspx

Cheers
Oliver

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


Re: Pipe in the "return" statement

2011-07-25 Thread John Gordon
In <1c175da2-79f4-40ed-803f-217dc935d...@m8g2000yqo.googlegroups.com> Archard 
Lias  writes:

> > > return  | 
> >
> > It's simply a bitwise OR.

> Yes, but how does it get determined, which one actually gets returned?

Neither value is returned on its own; the bitwise OR of both values is
computed and that value is returned.

It seems that you don't understand what the term "bitwise or" means.
Perhaps a Google search might help.

-- 
John Gordon   A is for Amy, who fell down the stairs
gor...@panix.com  B is for Basil, assaulted by bears
-- Edward Gorey, "The Gashlycrumb Tinies"

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


Re: Pipe in the "return" statement

2011-07-25 Thread gwowen
On Jul 25, 3:16 pm, Archard Lias  wrote:

> Yes, but how does it get determined, which one actually gets returned?


It's a bit-wise or, not a logical or so what get returns is a
combination of the two results.  The n-th bit of the return value is 1
if the n-th bit of either (or both) of the two statements

(Fixed width font)
a 1 1 0 0 0 1 1 1 0 0 1 0 1 ...
b 0 1 0 1 0 0 1 0 0 0 0 1 1 ...
a|b   1 1 0 1 0 1 1 0 0 0 1 1 1 ...
(/Fixed width font)
-- 
http://mail.python.org/mailman/listinfo/python-list


How to catch an memory error in Windows?

2011-07-25 Thread António Rocha
Greetings

I'm using subprocess module to run an external Windows binary. Due to some
limitations, sometimes all memory is consumed in this process. How can I
catch this error?
Antonio
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Refactor/Rewrite Perl code in Python

2011-07-25 Thread J Kenneth King
Steven D'Aprano  writes:

> On Sun, Jul 24, 2011 at 7:29 PM, Shashwat Anand 
> wrote:
>
>> How do I start ?
>> The idea is to rewrite module by module.
>> But how to make sure code doesn't break ?
>
> By testing it.
>
> Read up on "test driven development".
>
> At this point, you have this:
>
> Perl modules: A, B, C, D
> Python modules: none
> Python tests: none
>
> Now, before you rewrite each Perl module in Python, first write a good,
> comprehension test suite in Python for that module. You need to have tests
> for each function and method. Test that they do the right thing for both
> good data and bad data. If you have functional requirements for the Perl
> modules, use that as your reference, otherwise use the Perl code as the
> reference.
>
> For example, this might be a basic test suite for the len() built-in
> function:
>
>
> for empty in ([], {}, (), set([]), ""):
> if len(empty) != 0:
> raise AssertionError('empty object gives non-zero len')
>
> for n in range(1, 5):
> if len("x"*n) != n:
> raise AssertionError('failure for string')
> for kind in (list, tuple, set):
> obj = kind([None]*n)
> if len(obj) != n:
> raise AssertionError('failure for %s' % obj)
>
> if len({'a': 1, 'b': None, 42: 'spam'}) != 3:
> raise AssertionError('failure for dict')
>
> for bad_obj in (23, None, object(), 165.0, True):
> try:
> len(bad_obj)
> except TypeError:
> # Test passes!
> pass
> else:
> # No exception means len() fails!
> raise AssertionError('failed test')
>
>
>
> Multiply that by *every* function and method in the module, and you have a
> moderately good test suite for module A.
>
> (You may want to learn about the unittest module, which will help.)
>
> Now you have:
>
> Perl modules: A, B, C, D
> Python modules: none
> Python tests: test_A
>
> Now re-write the Python module, and test it against the test suite. If it
> fails, fix the failures. Repeat until it passes, and you have:
>
> Perl modules: A, B, C, D
> Python modules: A
> Python tests: test_A
>
> Now you can be confident that Python A does everything that Perl A does.
> Possibly *better* than the Perl module, since if you don't have a test
> suite for it, it probably has many hidden bugs.
>
> Continue in this way with the rest of the modules. At the end, you will have
> a full test suite against the entire collection of modules.

A very sane approach.

I currently support a large legacy application written in C++ by
extending it with Python.  We managed to do this by wrapping the legacy
application with a Python interface using the Boost::Python libraries.
It has allowed us to embrace and extend the legacy code and replace bits
of it one piece at a time while keeping the whole application running.

Now I am not aware of any Python bindings to the Perl interpreter, but
if there is some FFI library that makes it possible this approach might
be viable for your project.

The trade-off of this approach is the extra complexity of maintaining
another interface in your code.  The beneift is that you can avoid
re-writing a large amount of code up front.  This works particularly
well when the legacy system has a rather large user base and you don't
have a robust test suite for the legacy code.

One book I found particularly useful: 

http://www.amazon.ca/Working-Effectively-Legacy-Michael-Feathers/dp/0131177052

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


Re: Pipe in the "return" statement

2011-07-25 Thread Archard Lias
On Jul 25, 4:39 pm, John Gordon  wrote:
> In <1c175da2-79f4-40ed-803f-217dc935d...@m8g2000yqo.googlegroups.com> Archard 
> Lias  writes:
>
> > > > return  | 
>
> > > It's simply a bitwise OR.
> > Yes, but how does it get determined, which one actually gets returned?
>
> Neither value is returned on its own; the bitwise OR of both values is
> computed and that value is returned.
>
> It seems that you don't understand what the term "bitwise or" means.
> Perhaps a Google search might help.
>
> --
> John Gordon                   A is for Amy, who fell down the stairs
> gor...@panix.com              B is for Basil, assaulted by bears
>                                 -- Edward Gorey, "The Gashlycrumb Tinies"

It figures, that you are right :P.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to catch an memory error in Windows?

2011-07-25 Thread Thomas Jollans
On 25/07/11 16:55, António Rocha wrote:
> Greetings
> 
> I'm using subprocess module to run an external Windows binary. Due to
> some limitations, sometimes all memory is consumed in this process. How
> can I catch this error?
> Antonio
> 

How is this relevant to the Python part?

Also, "no memory left" is not necessarily an error, it's simply a fact
of life. How to catch it depends on how you're (here, "you" means the
external process) allocating the memory - The POSIX C malloc function
will return NULL and set errno to ENOMEM, for example.

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


Re: Pipe in the "return" statement

2011-07-25 Thread Archard Lias
On Jul 25, 4:35 pm, Oliver Bestwalter  wrote:
> Hello Archard,
>
> On 25.07.2011, at 16:16, Archard Lias wrote:
>
>
>
>
>
>
>
>
>
> > On Jul 25, 2:03 pm, Ian Collins  wrote:
> >> On 07/26/11 12:00 AM, Archard Lias wrote:
>
> >>> Hi,
>
> >>> Still I dont get how I am supposed to understand the pipe and its task/
> >>> idea/influece on control flow, of:
> >>> return  |
> >>> ??
>
> >> It's simply a bitwise OR.
>
> >> --
> >> Ian Collins
>
> > Yes, but how does it get determined, which one actually gets returned?
>
> You do a Bitwise OR with numbers. Your statements are both returning numbers 
> and those are combined with a bitwise OR. Combining b0001 with b0010 results 
> in 0011 for example, you can see this very often done in C Code to set and 
> check flags. Here is a gentle introduction:
>
> http://www.codeproject.com/KB/tips/Binary_Guide.aspxhttp://www.codepr...
>
> Cheers
> Oliver

Oh!, never gave it a thought about the fact that what I was looking at
where flags... Thank you very much for the link, is a great
introduction to something I had not known before.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pipe in the "return" statement

2011-07-25 Thread Archard Lias
On Jul 25, 2:33 pm, Christian Heimes  wrote:
> Am 25.07.2011 14:00, schrieb Archard Lias:
>
> > def flags(self, index):
> >     if not index.isValid():
> >         return Qt.ItemIsEnabled
>
> >     return super(self.__class__, self).flags(index) |
>
> Your use of super() is incorrect and will not work as you might expect.
> You *must* use the class here, never self.__class__.
>
> Christian

It would be great if you could elaborate a little more on that. Am I
not supposed to access the parent here?

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


ANN: Intro+Intermediate Python course, SF, Oct 18-20

2011-07-25 Thread wesley chun
Need to get up-to-speed with Python as quickly and as in-depth as
possible? Already coding Python but still have areas of uncertainty
you need to fill? Then come join me, Wesley Chun, author of
Prentice-Hall's bestseller "Core Python" for a comprehensive
intro/intermediate course coming up this May in Northern California,
then enjoy a beautiful Fall weekend afterwards in San Francisco, the
beautiful city by the bay.

Please pass on this note to whomever you think may be interested. I
look forward to meeting you and your colleagues! Feel free to pass
around the PDF flyer linked down below. Write if you have questions.

Since I hate spam, I'll only send out one reminder as the date gets
closer.

(Comprehensive) Intro+Intermediate Python
Tue-Thu, 2011 Oct 18-20, 9am-5pm

Hope to meet you soon!
-Wesley

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
(COMPREHENSIVE) INTRO+INTERMEDIATE PYTHON

Although this course may appear to those new to Python, it is also
perfect for those who have tinkered with it and want to "fill in the
gaps" and/or want to get more in-depth formal training.  It combines
the best of both an introduction to the language as well as a "Python
Internals" training course.

We will immerse you in the world of Python in only a few days, showing
you more than just its syntax (which you don't really need a book to
learn, right?). Knowing more about how Python works under the covers,
including the relationship between data objects and memory management,
will make you a much more effective Python programmer coming out of
the gate. 3 hands-on labs each day will help hammer the concepts home.

Come find out why Google, Yahoo!, Disney, ILM/LucasFilm, VMware,
NASA, Ubuntu, YouTube, and Red Hat all use Python. Users supporting or
jumping to Plone, Zope, TurboGears, Pylons, Django, Google App Engine,
Jython, IronPython, and Mailman will also benefit!

PREVIEW 1: you will find (and can download) a video clip of a
class session recorded live to get an idea of my lecture style and
the interactive classroom environment (as well as sign-up) at:

http://cyberwebconsulting.com

PREVIEW 2: Partnering with O'Reilly and Pearson, Safari Books
Online has asked me to deliver a 1-hour webcast a couple of years ago
called "What is Python?". This was an online seminar based on a
session that I've delivered at numerous conferences in the past. It
will give you an idea of lecture style as well as an overview of the
material
covered in the course.

info:http://www.safaribooksonline.com/events/WhatIsPython.html
download (reg req'd):
http://www.safaribooksonline.com/Corporate/DownloadAndResources/webcastInfo.php?page=WhatIsPython
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

WHERE: near the San Francisco Airport (SFO/San Bruno), CA, USA

WEB:   http://cyberwebconsulting.com

FLYER: http://cyberwebconsulting.com/flyerPP1.pdf

LOCALS: easy freeway (101/280/380) with lots of parking plus public
transit (BART and CalTrain) access via the San Bruno stations, easily
accessible from all parts of the Bay Area

VISITORS: free shuttle to/from the airport, free high-speed internet,
free breakfast and regular evening receptions; fully-equipped suites

See website for costs, venue info, and registration. There is a
significant discounts available for full-time students, secondary
teachers, and others.

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001
"Python Fundamentals", Prentice Hall, (c)2009
    http://corepython.com

wesley.chun : wescpy-gmail.com : @wescpy
python training and technical consulting
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Trying to learn about metaclasses

2011-07-25 Thread Steven W. Orr
I have been doing a lot of reading. I'm starting to get it. I think it's 
really cool as well as dangerous, but I plan on being respectful of the 
construct. I found a web page that I found quite readable.


http://cleverdevil.org/computing/78/

So, I tried to run the example code (below), and I get AttributeError. If 
someone can get me over this hump, I'd be grateful. It complains that Person 
has no _fields attribute, but the print hello I have in EnforcerMeta doesn't 
happen either. Am I doing something wrong?


I'm running python 2.6.2

Here's the error:

585 > ./meta1.py
Traceback (most recent call last):
  File "./meta1.py", line 38, in 
swo.name = 'swo'
  File "./meta1.py", line 27, in __setattr__
if key in self._fields:
AttributeError: 'Person' object has no attribute '_fields'


And here's the code:

#! /usr/bin/python
# http://cleverdevil.org/computing/78/
class Field(object):
def __init__(self, ftype):
self.ftype = ftype

def is_valid(self, value):
return isinstance(value, self.ftype)

class EnforcerMeta(type):
def __init(cls, name, bases, ns):
# Store the field definitions on the class as a dictionary
# mapping the field name to the Field instance.
print 'Hello'
cls._fields = {}

# loop through the namespace looking for Field instances.
for key, value in ns.items():
if isinstance(value, Field):
cls._fields[key] = value

class Enforcer(object):
# attach the metaclass
__metaclass__ = EnforcerMeta

def __setattr__(self, key, value):
if key in self._fields:
if not self._fields[key].is_valid(value):
raise TypeError('Invalid type for field.')
super(Enforcer, self).__setattr__(key, value)

class Person(Enforcer):
name = Field(str)
age = Field(int)

if __name__ == '__main__':
swo = Person()
swo.name = 'swo'
print 'swo:', swo


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


Re:How to catch an memory error in Windows?

2011-07-25 Thread António Rocha
Hi
I just want to use the Python part to catch this event as an error
try:
 subprocess<>
except ERROR:

I just wanted to know if there is any special error that I can use to catch
this error?
THanks
-- Forwarded message --
From: Thomas Jollans 
To: python-list@python.org
Date: Mon, 25 Jul 2011 17:14:46 +0200
Subject: Re: How to catch an memory error in Windows?
On 25/07/11 16:55, António Rocha wrote:
> Greetings
>
> I'm using subprocess module to run an external Windows binary. Due to
> some limitations, sometimes all memory is consumed in this process. How
> can I catch this error?
> Antonio
>

How is this relevant to the Python part?

Also, "no memory left" is not necessarily an error, it's simply a fact
of life. How to catch it depends on how you're (here, "you" means the
external process) allocating the memory - The POSIX C malloc function
will return NULL and set errno to ENOMEM, for example.

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


Re: Trying to learn about metaclasses

2011-07-25 Thread jfine
Hi

I gave a tutorial at this year's EuroPython that covered metaclasses.
You can get the tutorial materials from a link on:
http://ep2011.europython.eu/conference/talks/objects-and-classes-in-python-and-javascript


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


Re: Trying to learn about metaclasses

2011-07-25 Thread Peter Otten
Steven W. Orr wrote:

> I have been doing a lot of reading. I'm starting to get it. I think it's
> really cool as well as dangerous, but I plan on being respectful of the
> construct. I found a web page that I found quite readable.
> 
> http://cleverdevil.org/computing/78/
> 
> So, I tried to run the example code (below), and I get AttributeError. If
> someone can get me over this hump, I'd be grateful. It complains that
> Person has no _fields attribute, but the print hello I have in
> EnforcerMeta doesn't happen either. Am I doing something wrong?
> 
> I'm running python 2.6.2
> 
> Here's the error:
> 
> 585 > ./meta1.py
> Traceback (most recent call last):
>File "./meta1.py", line 38, in 
>  swo.name = 'swo'
>File "./meta1.py", line 27, in __setattr__
>  if key in self._fields:
> AttributeError: 'Person' object has no attribute '_fields'

> And here's the code:
> 
> class EnforcerMeta(type):
>  def __init(cls, name, bases, ns):

You misspelt __init__()

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


Re: Pipe in the "return" statement

2011-07-25 Thread Christian Heimes
Am 25.07.2011 17:28, schrieb Archard Lias:
> It would be great if you could elaborate a little more on that. Am I
> not supposed to access the parent here?

You must spell out the parent explicitly, otherwise subclasses call
super() with themselves rather than the correct parent class.
self.__class__ is too dynamic here. Have a look at this example:

class A(object):
def method(self):
pass

class B(A):
def method(self):
super(self.__class__, self).method()

class C(B):
pass

In this example, C().method() results in "super(C, self).method()"
because self.__class__ is C. However that is wrong because you have to
call super() with the direct parent.

Christian

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


Re: Convert '165.0' to int

2011-07-25 Thread SigmundV
On Jul 25, 10:48 am, Steven D'Aprano  wrote:
>
> One other important proviso: if your map function is a wrapper around a
> Python expression:
>
> map(lambda x: x+1, data)
> [x+1 for x in data]
>
> then the list comp will be much faster, due to the overhead of the function
> call. List comps and gen exprs can inline the expression x+1, performing it
> in fast C rather than slow Python.
>
> But if you're calling a function in both cases:
>
> map(int, data)
> [int(x) for x in data]
>
> then the overhead of the function call is identical for both the map and the
> list comp, and they should be equally as fast. Or slow, as the case may be.

I would like to thank Steven for his enlightening (at least for me)
post.

In the OP's case I'd keep everything as lists initially. If speed then
is an issue other constructs can be considered. The use of map in the
example only reflects my inherently mathematical way of thinking.

Generally, I'd say

1) write code that works, i.e. does what it's intended to do in all
cases, and
2) if speed is an issue, try to sort out the main culprits.

Coding style is a different issue altogether, but in general I'd say
that one should use self-explanatory variable names.


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


Re: python.org is down?

2011-07-25 Thread SigmundV
On Jul 24, 8:43 am, Laszlo Nagy  wrote:
> Can it be a problem on my side? I have tried from several different
> computers. I cannot even ping it.

Whenever a page can't be accessed, although your connection is good,
http://www.downforeveryoneorjustme.com/ is a good site to check.


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


Re: Pipe in the "return" statement

2011-07-25 Thread Archard Lias
On 25 Jul., 18:11, Christian Heimes  wrote:
> Am 25.07.2011 17:28, schrieb Archard Lias:
>
> > It would be great if you could elaborate a little more on that. Am I
> > not supposed to access the parent here?
>
> You must spell out the parent explicitly, otherwise subclasses call
> super() with themselves rather than the correct parent class.
> self.__class__ is too dynamic here. Have a look at this example:
>
> class A(object):
>     def method(self):
>         pass
>
> class B(A):
>     def method(self):
>         super(self.__class__, self).method()
>
> class C(B):
>     pass
>
> In this example, C().method() results in "super(C, self).method()"
> because self.__class__ is C. However that is wrong because you have to
> call super() with the direct parent.
>
> Christian

Oh! Get it, thanks a lot :P

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


Re: learning another programing language

2011-07-25 Thread SigmundV
On Jul 24, 9:59 am, Benjamin Gregg 
wrote:
> Hi
> python was my first language but I need to learn C++ and java for a
> project (No there isn't an alternative)
> and I want to know is there any good tutorials or tips for learning
> C++/java after using python?

I think it's always best to approach a new language with a completely
open mind. It's never good to think of one language in terms of
another, so I'd say: forget about Python while learning C++ and Java.
One should always learn about the strenghts and weaknesses of each
language in itself. E.g. there is plenty of "Python" code out there,
which is just C or C++ code using Python syntax. That is just sad.


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


Re: Validating Entry in tkinter

2011-07-25 Thread Saul Spatz
Yes, the tuple is certainly easier to read.

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


Re: Convert '165.0' to int

2011-07-25 Thread Billy Mays

On 07/25/2011 05:48 AM, Steven D'Aprano wrote:

But if you're calling a function in both cases:

map(int, data)
[int(x) for x in data]



I am aware the premature optimization is a danger, but its also 
incorrect to ignore potential performance pitfalls.


I would favor a generator expression here, if only because I think its 
easier to read.  In addition, it properly handles large amounts of data 
by not duplicating the list.  For very long input sequences, genexp 
would be the proper thing to do (assuming you don't need to index into 
results, in which case, its wrong.)


I think the fastest way to solve the OP's problem is the following: ;)

def convert_165_0_to_int(arg):
return 165


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


Re: Validating Entry in tkinter

2011-07-25 Thread Saul Spatz
Thanks, that a great link.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Aw: Re: Aw: python.org back up ?(was Re: python.org is down?)

2011-07-25 Thread Terry Reedy

On 7/25/2011 7:25 AM, hackingKK wrote:

Infact the first thing I ever did with documentation on Python was to
download it.
yes you are not uptodate but you can always do a download once in a
while rather than putting load on the server every time you want to
lookup a function reference.
Happy hacking.
Krishnakant.

On 25/07/11 14:32, David Zerrenner wrote:

Carl Banks wrote:

If you can't live without the docs, you should consider downloading
them and accessing them locally. That'll let you work whenever
python.org goes down, and will help keep the load off the server when
it's up.

Thanks for the pointer, i did not realize that until now... These days
of always-on internet corrupted me so much.


The windows distribution comes with the docs bundled in a windows help 
file, updated with each bug fix release. Is there really no *nix 
equivalent that could be used or is this one area where windows really wins?


--
Terry Jan Reedy

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


Re: Validating Entry in tkinter

2011-07-25 Thread Terry Reedy

On 7/25/2011 8:31 AM, Peter Otten wrote:

Saul Spatz wrote:


That doesn't work, I'm being stupid,  The user might type anywhere in the
string, not just at the end.  I need

return all([c in '1234567890abcdefABCDEF ' for c in after])


If one wants to validate keystrokes, rather than the entire field after 
the fact, is it possible to set an onkey handler, that will pass on 
valid keys?


--
Terry Jan Reedy

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


Re: Trying to learn about metaclasses

2011-07-25 Thread Karim


Very good.

Karim

On 07/25/2011 05:46 PM, jfine wrote:

Hi

I gave a tutorial at this year's EuroPython that covered metaclasses.
You can get the tutorial materials from a link on:
http://ep2011.europython.eu/conference/talks/objects-and-classes-in-python-and-javascript


Jonathan


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


Re: python.org is down?

2011-07-25 Thread Tim Chase

On 07/25/2011 11:45 AM, SigmundV wrote:

On Jul 24, 8:43 am, Laszlo Nagy  wrote:

Can it be a problem on my side? I have tried from several different
computers. I cannot even ping it.


Whenever a page can't be accessed, although your connection is good,
http://www.downforeveryoneorjustme.com/ is a good site to check.


The problem is when www.downforeveryoneorjustme.com goes 
down...do you then go to 
www.isdownforeveryoneorjustmedownforeveryoneorjustme.com


? :-)

-tkc




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


Re: Trying to learn about metaclasses

2011-07-25 Thread Chris Kaynor
On Mon, Jul 25, 2011 at 8:36 AM, Steven W. Orr  wrote:

> I have been doing a lot of reading. I'm starting to get it. I think it's
> really cool as well as dangerous, but I plan on being respectful of the
> construct. I found a web page that I found quite readable.
>
> http://cleverdevil.org/**computing/78/
>
> So, I tried to run the example code (below), and I get AttributeError. If
> someone can get me over this hump, I'd be grateful. It complains that Person
> has no _fields attribute, but the print hello I have in EnforcerMeta doesn't
> happen either. Am I doing something wrong?
>
> I'm running python 2.6.2
>
> Here's the error:
>
> 585 > ./meta1.py
> Traceback (most recent call last):
>  File "./meta1.py", line 38, in 
>swo.name = 'swo'
>  File "./meta1.py", line 27, in __setattr__
>if key in self._fields:
> AttributeError: 'Person' object has no attribute '_fields'
>
>
> And here's the code:
>
> #! /usr/bin/python
> # http://cleverdevil.org/**computing/78/
> class Field(object):
>def __init__(self, ftype):
>self.ftype = ftype
>
>def is_valid(self, value):
>return isinstance(value, self.ftype)
>
> class EnforcerMeta(type):
>def __init(cls, name, bases, ns):
># Store the field definitions on the class as a dictionary
># mapping the field name to the Field instance.
>print 'Hello'
>cls._fields = {}
>
># loop through the namespace looking for Field instances.
>for key, value in ns.items():
>if isinstance(value, Field):
>cls._fields[key] = value
>
> class Enforcer(object):
># attach the metaclass
>__metaclass__ = EnforcerMeta
>
>def __setattr__(self, key, value):
>if key in self._fields:
>if not self._fields[key].is_valid(**value):
>raise TypeError('Invalid type for field.')
>super(Enforcer, self).__setattr__(key, value)


If I understand what you are trying to do here (other than playing with
metaclasses), you should be able to implement this as a descriptor (
http://docs.python.org/reference/datamodel.html#implementing-descriptors).

Something like (untested):

class Field(object):
   def __init__(self, name, type):
  self.ftype = type
  self.name = name

   def __get__(self, instance, owner):
  return getattr(instance, self.name)

   def __set__(self, instance, value):
  if not self.is_valid(value):
   raise TypeError()
  setattr(instance, self.name, value)

   def is_valid(self, value):
   return isinstance(value, self.ftype)


>
> class Person(Enforcer):
>name = Field(str)
>age = Field(int)
>
> if __name__ == '__main__':
>swo = Person()
>swo.name = 'swo'
>print 'swo:', swo
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-25 Thread Peter Otten
Terry Reedy wrote:

> On 7/25/2011 8:31 AM, Peter Otten wrote:
>> Saul Spatz wrote:
>>
>>> That doesn't work, I'm being stupid,  The user might type anywhere in
>>> the
>>> string, not just at the end.  I need
>>>
>>> return all([c in '1234567890abcdefABCDEF ' for c in after])
> 
> If one wants to validate keystrokes, rather than the entire field after
> the fact, 

It's not really after the fact as the user will not see the new contents 
unless they are accepted by the validatecommand handler.

> is it possible to set an onkey handler, that will pass on
> valid keys?

With validatecommand you can have tkinter provide the string that is being 
inserted:

import tkinter as tk

MESSAGE = ("about to insert {text!r} at position {index} "
   "({resolution})")

def validate(action, index, text):
if action == "1":
accept = text.isdigit()
print(
MESSAGE.format(
resolution="OK" if accept else "rejected",
text=text,
index=index))
return accept
return True

if __name__ == "__main__":
root = tk.Tk()
cmd = (root.register(validate), "%d", "%i", "%S")
entry = tk.Entry(root, validate="all", validatecommand=cmd)
entry.pack()
entry.focus_set()
root.mainloop()

The available format codes are listed at 
http://www.tcl.tk/man/tcl8.4/TkCmd/entry.htm#M16

If you need something more specific you'd probably have to bind the 
 event to a custom handler:

import tkinter as tk

def keypress(event):
print(event.char)
if event.char:
if not event.char.isdigit() and event.char != "\b":
return "break"
else:
print("Don't know what to do with key #", event.keycode)

if __name__ == "__main__":
root = tk.Tk()
entry = tk.Entry(root)
entry.bind("", keypress)
entry.pack()
entry.focus_set()
root.mainloop()


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


Signal only works in main thread

2011-07-25 Thread RVince
I am instantiating an SSH client class using this class:

http://www.goldb.org/sshpython.html

With the following code:

sSHController = SSHController('xxx', 'root', 'password', '#')
sSHController.login()

Whereupon, at login(), it fails with a :

ValueError: signal only works in main thread

I'm at a complete loss here. Can someone please point me in the right
direction to solving this?   Thanks,
RVince
-- 
http://mail.python.org/mailman/listinfo/python-list


Strange output from arange()

2011-07-25 Thread Christopher Barrington-Leigh
The following code:

from pylab import arange
nSegments=5.0
print arange(0,1.0+1.0/nSegments,1.0/nSegments)
nSegments=6.0
print arange(0,1.0+1.0/nSegments,1.0/nSegments)
nSegments=8.0
print arange(0,1.0+1.0/nSegments,1.0/nSegments)
nSegments=10.0
print arange(0,1.0+1.0/nSegments,1.0/nSegments)

gives an output of:

[ 0.   0.2  0.4  0.6  0.8  1. ]
[ 0.  0.1667  0.  0.5 0.6667
0.8333  1.  1.1667]
[ 0. 0.125  0.25   0.375  0.50.625  0.75   0.875  1.   ]
[ 0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9  1. ]

These arrays have lengths, 6, 8, 9, and 11, in stead of 6, 7, 9, and
11.
What is going on for the case of n=6?

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


Re: Here is what I came up with - hopefully I have understood the processcorrectly

2011-07-25 Thread Jane Griscti
You can use the 'Toolbutton' style in place of 'indicatoron'

button = Checkbutton(r, 
text='Test',
style='Toolbutton')
button.pack()



> On Sunday, March 13, 2011 11:08 PM Peter wrote:

> Hi I am struggling to get a good understanding of styles as used in
> ttk. I have read the tutorial section on using styles but have not been
> able to solve this problem.
> 
> I am attempting to create a Checkbutton with the indicatoron=3Dfalse
> option. Using ttk the documentation is clear that you have to create a
> custom style to achieve this behaviour. But the only "example" I have
> been able to find on the Internet searches is written in Tcl i.e. here
> is what I have found (quoted directly):
> 
> Here=92s how you set it up: To achieve the effect of -indicatoron false,
> create a new layout that doesn=92t have an indicator:
> 
> style layout Toolbar.TCheckbutton {
> Toolbutton.border -children {
> Toolbutton.padding -children {
> Toolbutton.label
> }
> }
> }
> 
> Then use style map and style default to control the border appearance:
> 
> style default Toolbar.TCheckbutton \
> -relief flat
> style map Toolbar.TCheckbutton -relief {
> disabled flat
> selected sunken
> pressed sunken
> active raised
> 
> Hopefully somebody else in this group has "done" this and can post
> their "solution"?
> 
> Thanks
> Peter


>> On Sunday, March 20, 2011 8:12 PM Peter wrote:

>> Here is what I came up with - hopefully I have understood the process
>> correctly and therefore that the comments are correct :-)
>> 
>> I am not sure I have the color of the indicator when it is (de)pressed
>> correct, but to my eyes the color 'snow' looks like the same color
>> used with a Tkinter Checkbutton with indicatoron=false.
>> 
>> r = Tk()
>> 
>> s = Style()
>> 
>> s.layout('NoIndicator.TCheckbutton',
>> [('Checkbutton.border',
>> {'children': [('Checkbutton.padding',
>> {'children': [('Checkbutton.label',
>> {})]})]})])
>> 
>> checkbutton
>> s.theme_settings('default', {
>> 'NoIndicator.TCheckbutton': {'configure': {'relief': ''}}})
>> 
>> behaviour
>> s.map('NoIndicator.TCheckbutton',
>> relief=[('disabled', 'flat'),
>> ('selected', 'sunken'),
>> ('pressed', 'sunken'),
>> ('active', 'raised'),
>> ('!active', 'raised')],
>> background=[('selected', 'snow')])
>> 
>> button = Checkbutton(r,
>> text='Test',
>> style='NoIndicator.TCheckbutton')
>> button.pack()
>> 
>> r.mainloop()



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


Re: Aw: Re: Aw: python.org back up ?(was Re: python.org is down?)

2011-07-25 Thread Ned Deily
In article ,
 Terry Reedy  wrote:
> The windows distribution comes with the docs bundled in a windows help 
> file, updated with each bug fix release. Is there really no *nix 
> equivalent that could be used or is this one area where windows really wins?

Most *nix distributions provide an optional doc package for each of the 
Python versions they support, for instance, in Debian:

$ aptitude search 'python[23].*-doc$'
p   python2.6-doc  
p   python2.7-doc 
p   python3-doc 
p   python3.1-doc
p   python3.2-doc 

Also each python.org Mac OS X installers includes a copy of the 
documentation for its version, in HTML format the same as the on-line 
versions.  The docs are easily accessible through a menu item in each 
version of IDLE.  And recent versions of the installer also include a 
clickable link to the docs in each /Applications/Python x.y folder.

One advantage of the on-line versions is that they are updated daily 
with the latest fixes to the documentation.

-- 
 Ned Deily,
 n...@acm.org

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


Re: Strange output from arange()

2011-07-25 Thread Wanderer
On Jul 25, 3:20 pm, Christopher Barrington-Leigh
 wrote:
> The following code:
>
>     from pylab import arange
>     nSegments=5.0
>     print arange(0,1.0+1.0/nSegments,1.0/nSegments)
>     nSegments=6.0
>     print arange(0,1.0+1.0/nSegments,1.0/nSegments)
>     nSegments=8.0
>     print arange(0,1.0+1.0/nSegments,1.0/nSegments)
>     nSegments=10.0
>     print arange(0,1.0+1.0/nSegments,1.0/nSegments)
>
> gives an output of:
>
> [ 0.   0.2  0.4  0.6  0.8  1. ]
> [ 0.          0.1667  0.  0.5         0.6667
> 0.8333  1.          1.1667]
> [ 0.     0.125  0.25   0.375  0.5    0.625  0.75   0.875  1.   ]
> [ 0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9  1. ]
>
> These arrays have lengths, 6, 8, 9, and 11, in stead of 6, 7, 9, and
> 11.
> What is going on for the case of n=6?

It's rounding.

See http://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html

  stop : number
  End of interval. The interval does not include this value,
except in some cases where step is not an integer and floating point
round-off affects the length of out.

The stops are

5 -- 1.2
6 -- 1.16667
8 -- 1.125
10 -- 1.1

Only 6 has to be rounded up.

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


Re: Strange output from arange()

2011-07-25 Thread Robert Kern

On 7/25/11 2:20 PM, Christopher Barrington-Leigh wrote:

The following code:

 from pylab import arange
 nSegments=5.0
 print arange(0,1.0+1.0/nSegments,1.0/nSegments)
 nSegments=6.0
 print arange(0,1.0+1.0/nSegments,1.0/nSegments)
 nSegments=8.0
 print arange(0,1.0+1.0/nSegments,1.0/nSegments)
 nSegments=10.0
 print arange(0,1.0+1.0/nSegments,1.0/nSegments)

gives an output of:

[ 0.   0.2  0.4  0.6  0.8  1. ]
[ 0.  0.1667  0.  0.5 0.6667
0.8333  1.  1.1667]
[ 0. 0.125  0.25   0.375  0.50.625  0.75   0.875  1.   ]
[ 0.   0.1  0.2  0.3  0.4  0.5  0.6  0.7  0.8  0.9  1. ]

These arrays have lengths, 6, 8, 9, and 11, in stead of 6, 7, 9, and
11.
What is going on for the case of n=6?


Floating point computations are not always accurate, and when one tries to 
compute "the same thing" two different ways, one may get inconsistent results. 
This is what is happening with n=6. 1+1./6 happens to be slightly greater than 
7*(1./6) while 1+1./5 happens to be slightly less than 6*(1./5), etc. The trick 
of using 1.0+1.0/nSegments/2 tends to work better.


Nonetheless, if you want to get exactly nSegments segments with exact endpoints, 
you should use numpy.linspace(0.0, 1.0, nSegments+1). That's a much better API 
for what you want.


Also, you will want to ask numpy questions on the numpy-discussion mailing list, 
not here.


  http://www.scipy.org/Mailing_Lists

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco

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


Re: Pipe in the "return" statement

2011-07-25 Thread Ethan Furman

Billy Mays wrote:

On 07/25/2011 10:16 AM, Archard Lias wrote:

On Jul 25, 2:03 pm, Ian Collins  wrote:

On 07/26/11 12:00 AM, Archard Lias wrote:

Still I dont get how I am supposed to understand the pipe and its task/
idea/influece on control flow, of:
return|
??


It's simply a bitwise OR.


Yes, but how does it get determined, which one actually gets returned?


The return statement returns a single value from a function context. The 
pipe operator takes 2 values and bitwise ORs* them together.  That 
result is then returned to the caller.


Just for completeness, if the actual line had been

return  or 

then Python would compute , and if its boolean value was 
True would return the computation of , otherwise it would 
compute  and return that.  When 'or' is used, the first 
truthy* item is return, or the last falsey* item if none evaluate to True.


--> None or 2 or 0
2
--> None or 2 or 3
2
--> None or [] or 0
0

With 'and', the first falsey item is returned, unless all the items are 
  truthy in which case the last item is returned:


--> 2 and 3
3
--> 2 and 0 and 9
0

Hope this helps.

~Ethan~

* 'truthy' = bool(some expression or object) == True
* 'falsey' = bool(some expression or object) == False
--
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-25 Thread rantingrick
On Jul 25, 2:08 pm, Peter Otten <__pete...@web.de> wrote:
> Terry Reedy wrote:
> > On 7/25/2011 8:31 AM, Peter Otten wrote:
> >> Saul Spatz wrote:
> > is it possible to set an onkey handler, that will pass on
> > valid keys?
>
> With validatecommand you can have tkinter provide the string that is being
> inserted:

Yes but it's messy and requires knowledge of Tcl! We to keep our code
bases as Pythonic as possible.

> If you need something more specific you'd probably have to bind the
>  event to a custom handler:

Exactly!

If you compare the code of the two approaches you'll see that the
python approach is more readable and does not export any "magic"
behind the scenes. By binding the KeyPress event and handling it in
some derived class people who are not familiar with Tcl\Tk can read
the code (and change it to suit their needs). The next best
alternative would be to extend Tk.Entry with a pythonic wrapper for
this functionality.

MORAL: Sometimes you are forced to export these things but in this
case i would argue that readability counts; so keep it in Python!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-25 Thread python
Peter,

How would your examples work with text being inserted or deleted via the
clipboard?

Is there anything special that would have to happen for changes to a
widget's value as the result of one of these events?

Thank you,
Malcolm (not the OP)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Signal only works in main thread

2011-07-25 Thread Chris Rebert
On Mon, Jul 25, 2011 at 12:19 PM, RVince  wrote:
> I am instantiating an SSH client class using this class:
>
> http://www.goldb.org/sshpython.html

You might consider using Paramiko instead:
http://www.lag.net/paramiko/

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


Re: Signal only works in main thread

2011-07-25 Thread Miki Tebeka
Seems like pyssh (which is very old AFAIK) uses signal. Looks like you're 
creating the SSHController instance (which uses pyssh) not in the main thread, 
and Python won't allow you to place signal handlers outside the main thread.

You can probably move the SSHContorller creation to the main thread, or maybe 
try using a newer library (such as http://www.lag.net/paramiko/)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Validating Entry in tkinter

2011-07-25 Thread Peter Otten
pyt...@bdurham.com wrote:

> How would your examples work with text being inserted or deleted via the
> clipboard?
> 
> Is there anything special that would have to happen for changes to a
> widget's value as the result of one of these events?

I think it doesn't matter whether you type in text, or insert it with Ctrl+V 
or the middle mouse button. The validatecommand handler is always triggered.

I suspect achieving the same effect with Button/KeyPress handlers would 
require significantly more work.

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


RE: Refactor/Rewrite Perl code in Python

2011-07-25 Thread Sells, Fred
Sometimes it's worth asking Why?

I assume there would be no need to rewrite if the existing code did most
of what was needed.  It may be easier to ask the customer what he really
wants rather than to re-engineer a crappy solution to an obsolete
problem.

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


Re: Pipe in the "return" statement

2011-07-25 Thread red floyd
On Jul 25, 5:52 am, TonyO  wrote:
> > Still I dont get how I am supposed to understand the pipe and its task/
> > idea/influece on control flow, of:
> > return  | 
>
> In the words of René Magritte,
>
> return  | 
>                    ^
> Ceci n'est pas une pipe.

We have a WINNER!!

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


Re: PEP 8 and extraneous whitespace

2011-07-25 Thread Ethan Furman

Ed Leafe wrote:

Religious fervor is one thing; freedom of religion is another!  ;-)

We strive for readability in our code, yet every printed material

> designed to be read, such as books, newspapers, etc., uses a
> proportional font.

The books I purchase use monospaced fonts for code examples.  Yours don't?

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


Re: PEP 8 and extraneous whitespace

2011-07-25 Thread Ethan Furman

Brandon Harris wrote:

I don't really think lining things up makes them any easier to read.


I *totally* disagree.  Often I'm scanning a dict looking for either a 
key or a value, and having them lined up makes it much easier.  Yes, I 
have to reindent once in a while, but it's still a write few, read many 
operation.


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


Re: Validating Entry in tkinter

2011-07-25 Thread Malcolm Greene
Peter,

> I think it doesn't matter whether you type in text, or insert it with Ctrl+V 
> or the middle mouse button. The validatecommand handler is always triggered. 
> I suspect achieving the same effect with Button/KeyPress handlers would 
> require significantly more work.

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


Re: PEP 8 and extraneous whitespace

2011-07-25 Thread Thomas Jollans
On 26/07/11 00:05, Ethan Furman wrote:
> Ed Leafe wrote:
>> Religious fervor is one thing; freedom of religion is another!  ;-)
>>
>> We strive for readability in our code, yet every printed material
>> designed to be read, such as books, newspapers, etc., uses a
>> proportional font.
> 
> The books I purchase use monospaced fonts for code examples.  Yours don't?

Strange that. Most do, but that's really just tradition.

I have Bjarne Stroustrup's "The C++ Programming Language" on my shelf,
and that prints code in a proportional font.

There are two possible reasons to prefer a monospaced font for code:

 1. You're used to it: tradition. This is a legacy of the era when
computers simply didn't display proportional fonts.

 2. Your editor (my usual preference, Vim, is an example) doesn't
support proportional fonts. This is a legacy of the era when
computers simply didn't display proportional fonts.

Code is different from prose. We parse it so differently that printing
it in a monospaced font doesn't significantly hurt readability - but it
doesn't make it more readable either.

In the end, it really doesn't matter. This is probably why I enjoyed
writing this message so much.

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


ActivePython: multiple versions on OSX?

2011-07-25 Thread Robert

Is it possible to install the 2 and 3 series side by side?

--
Robert


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


Re: ActivePython: multiple versions on OSX?

2011-07-25 Thread Ned Deily
In article , Robert  
wrote:

> Is it possible to install the 2 and 3 series side by side?

Probably.  On Mac OS X, t's certainly possible to install any python.org 
versions side by side, even multiple versions of 2 and 3.  That's one of 
the advantages of the Python framework build layout on OS X, which is 
used by both the python.org installers and, I believe, the ActiveState 
installers.

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

-- 
 Ned Deily,
 n...@acm.org

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


Re: Trying to learn about metaclasses

2011-07-25 Thread Victor Khangulov

Hi Steven,

I too am just learning about metaclasses in Python and I found the 
example you posted to be excellent.


I played around with it and noticed that the issue seems to be the 
double-underscore in front of the fields (cls.__fields = {}).  If you 
change this parameter to use the single-underscore, the code works 
perfectly.


I think that because of the double-underscore, the name of the attribute 
"fields" gets mangled by the interpreter and is not inherited from the 
parent class in its accessible form.  Now, I am not sure if the code 
posted uses an earlier version of Python where these rule are different 
or if there is a more correct way to achieve this.  I will follow this 
discussion to see if someone has a better answer.


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


Tree structure

2011-07-25 Thread Bevan Jenkins
Hello,

I am trying to create a tree structure for use with a PyQt QTreeView.
But first I need to get my head around how to create the tree
structure.  I have a dictionary (for testing purposes) but I will
later use a table via sqlalchemy.

The use case is hydrology, so I  would like to have a hydrologically
connected river tree, in which you can browse upstream from the sea
(making choices) or downstream from any named hydrological feature.
Each key flows into its value pair. myrivers =
{"river":"flows_into"}.  An example is below:

myrivers = {"little stream":"sea",
"mountain stream":"lake",
"lake":"big river",
"cold spring":"big river",
"big river":"sea"
"sea":""}

I would like the tree to look like (if the formatting works). so
you can browse downstream from each named river but also upstream from
the sea picking which direction to go.

little stream
sea
mountain stream
lake
big river
sea
lake
big river
sea
cold spring
big river
sea
big river
sea
sea
little stream
big river
lake
mountain stream
cold spring

<>
So every key is a parent.  For all keys that have a value (not ""),
the value is the child and is then used as a parent to get the next
child until the sea and a value of "" is reached.  For the sea this is
reversed, that you find all rivers that flow into the sea and then all
rivers that flow into them.


Any thoughts about how to acomplish this will be much appreciated,
Bevan



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