Re: Addind imports to a class namespace

2009-07-10 Thread Peter Otten
Ryan K wrote:

> In order to avoid circular imports, I have a class that I want to
> improve upon:
> 
> Class GenerateMenuXhtml(threading.Thread):
> """
> Subclasses a threading.Thread class to generate a menu's XHTML in
> a separate
> thread. All Link objects that have this menu associated with it
> are gathered
> and combined in an XHTML unordered list.
> 
> If the sender is of type Link, then all menus associated with that
> link are
> iterated through and rebuilt.
> """
> def __init__(self, instance):
> from asqcom.apps.staticpages.models import Menu, Link
> self.Link = Link
> self.Menu = Menu
> 
> As you can see I just expose these imports by attaching them to
> members of the class. There must be "prettier" option though where I
> can just add these imoprts to the class's namespace so all methods of
> any instance will have access to the imported modules.
> 
> How would I go about doing this? How can I access the namespace of any
> class? Through Class.__dict__?

You can write either

class A(object):
from some.module import Menu, Link

or 

class A(object):
@classmethod
do_imports(cls):
from some.module import Menu, Link
cls.Menu = Menu
cls.Link = Link

A.do_imports()

to put the names into the class. The first form performs the import while 
the containing module is imported and therefore won't help with breaking 
circles. In the second form you have to defer the A.do_imports() method call 
until the import from some.module is safe.

But I still recommend that you have another look at your package 
organization to find a way to avoid circles.

Peter

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


Re: tough-to-explain Python

2009-07-10 Thread John O'Hagan
On Fri, 10 Jul 2009, Hendrik van Rooyen wrote:
> "Steven D'Aprano"  wrote:
> >On Wed, 08 Jul 2009 22:05:57 -0700, Simon Forman wrote:

[...]

> >> Programming is not like any other human activity.
> >
> >In practice? In principle? Programming in principle is not the same as it
> >is performed in practice.
> >
> >But in either case, programming requires both the logical reasoning of
> >mathematics and the creativity of the arts. Funnily enough,
>
> I do not buy this arty creativity stuff. - or are you talking about
> making a website look pretty?
>
> >mathematicians will tell you that mathematics requires the same, and so
> >will the best artists. I think mathematicians, engineers, artists, even
> >great chefs, will pour scorn on your claim that programming is not like
> >any other human activity.
>
> So a chef is now an authority on programming?
>
> Programming is actually kind of different - almost everything else is
> just done, at the time that you do it.
>
> Programming is creating stuff that is completely useless until it is
> fed into something that uses it, to do something else, in conjuction
> with the thing it is fed into, at a later time.
>
> This is a highly significant difference, IMHO.

[...]

The drawings produced by an architect, the script of a play, the score of a 
piece of music, and the draft of a piece of legislation are all examples of 
other things which are "useless" until they are interpreted in some way. 

There are countless human activities which require a program, i.e. a conscious 
plan or strategy, formed at least partly by a creative process, and a computer 
program is just a special case of this. 

I use Python as a tool for writing music, but I find I need both logical 
reasoning and creativity to do either. In fact, I find programming very similar 
to writing music in a rigorous contrapuntal style, where each set of choices 
constrains each other, and there is a deep aesthetic satisfaction in getting 
it right.

Regards,

John




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


Re: Colour of output text

2009-07-10 Thread Nobody
On Fri, 10 Jul 2009 09:23:54 +, garabik-news-2005-05 wrote:

>>> I would like to learn a way of changing the colour of a particular
>>> part of the output text. I've tried the following
> 
>> On Unix operating systems this would be done through the curses interface:
>> 
>> http://docs.python.org/library/curses.html
> 
> Or using ANSI colour codes:
> 
> colours = {
> 'none'   :"",
> 'default':"\033[0m",
> 'bold'   :"\033[1m",

[snip]

> # non-standard attributes, supported by some terminals 

This comment should have appeared immediately after "none" ;)

Hard-coding control/escape sequences is just lame. Use the curses modules
to obtain the correct sequences for the terminal.

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


fedora 3.1 python install

2009-07-10 Thread oystercatcher
had installed python 3.0. on fc11 x64
the only anomalies were a couple of tests failed during the make
test.  make altinstall was fine and have been using it for a simple
math exercise.

attempting to install python 3.1 the make test hangs at
test_httpservers and I had to kill the task after waiting quite
awhile.  now probably this is no big deal and I should just go ahead
and run the make altinstall but it would be nice to know a bit more
about what is going on here.

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


Re: Clarity vs. code reuse/generality

2009-07-10 Thread Terry Reedy

Steven D'Aprano wrote:

On Fri, 10 Jul 2009 12:27:25 -0400, Charles Yeomans wrote:


(3) assert is absolutely unsuitable for enforcing pre-conditions and
post-
conditions, unless such conditions are mere "guidelines", because
assert
can be switched off at runtime.


Unless, of course, you want to switch off such checking at runtime, as
you might when using a design-by-contract approach.


So is design-by-contract just another way of saying "let's hope the data 
is valid, because if it's not, we're screwed"?


Perhaps Python should have a new statement, `assume`, used just like 
`assert` except it never actually performs the test or raises an error.


The manual says quite clearly

"The simple form, assert expression, is equivalent to
if __debug__:
   if not expression: raise AssertionError"

It should be used when and only when one actually wants the double 
condition check, and not as an abbreviation of the second conditional only.


tjr



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


Re: Clarity vs. code reuse/generality

2009-07-10 Thread Steven D'Aprano
On Fri, 10 Jul 2009 12:27:25 -0400, Charles Yeomans wrote:

>> (3) assert is absolutely unsuitable for enforcing pre-conditions and
>> post-
>> conditions, unless such conditions are mere "guidelines", because
>> assert
>> can be switched off at runtime.
> 
> 
> Unless, of course, you want to switch off such checking at runtime, as
> you might when using a design-by-contract approach.

So is design-by-contract just another way of saying "let's hope the data 
is valid, because if it's not, we're screwed"?

Perhaps Python should have a new statement, `assume`, used just like 
`assert` except it never actually performs the test or raises an error.


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


Re: AP -- MeAmI.org Paces Google

2009-07-10 Thread Musatov
Martin Musatov wrote:
David Bernier wrote:
> scribe...@yahoo.com wrote:
> [...]
>
> > community. But perhaps he is trying to see things a bit differently
> > and is just not getting the feedback he needs, so he is throwing
> > tantrums apparently across USENET.
> >
> > Like I said before, I am just trying to do right by this person who
> > contacted me, and seemed to be a decent person with a genuine interest
> > in mathematics. He was very respectful.
> >
> > Alas, I am at a loss on what specific feedback to give him on his
> > paper as though I am a professor of Mathematics, Computer Science is
> > not my specialty.
> >
> > I told him I would try to get him some feedback on the equations on
> > page 3.  Would any of you be so kind to help me?
> >
> > Here is the paper: http://MeAmI.org/pversusnp.pdf
> >
> > I do thank you for your time.
> >
> > Good day,
> >
> > Professor X
>
> This is what there is at the bottom of page 3:
>
> << Conclusion: Binary revisions are allowed given the above formulas. >>
>
> So I don't understand the proposed solution for the "P = NP"
> problem.
>
> David Bernier

P can be equal to N and not P when it is in brackets vs. parantheses.
The dots ib the equation in "P = [dots] N (dots) P. The
difference between the brackets and the paranthesis represents a
margin of time in computation. The dots present in the paper (I am not
able to render them here, but they are in the .pdf file) represent a
non-deterministic symbolic means of representing language. Thank you
for your respone.

The conclusion means traditional characters and symbols are not ideal
for binary computation.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: sys.exit() and PyRun_SimpleFileExFlags()

2009-07-10 Thread Aahz
In article ,
=?ISO-8859-1?Q?Xavier_B=E9nech?=   wrote:
>
>There is a behaviour I do not understand of PyRun_SimpleFileExFlags(), 
>normally when it executes a python script containing a sys.exit(), it 
>results by ending the calling application.

If nobody responds on c.l.py, I suggest trying capi-sig.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-10 Thread Ethan Furman

Steven D'Aprano wrote:

On Mon, 06 Jul 2009 21:02:19 -0700, Aahz wrote:


In article <006e795f$0$9711$c3e8...@news.astraweb.com>, Steven D'Aprano 
 wrote:



On Mon, 06 Jul 2009 14:32:10 +0200, Jean-Michel Pichavant wrote:


kj wrote:


   sense = cmp(func(hi), func(lo))
   assert sense != 0, "func is not strictly monotonic in [lo, hi]"


As already said before, unlike other languages, sense in english does
**not** mean direction. You should rewrite this part using a better
name. Wrong informations are far worse than no information at all.


Absolutely.




From Webster's Dictionary:



8. (Geom.) One of two opposite directions in which a line,
surface, or volume, may be supposed to be described by the motion
of a point, line, or surface.
[1913 Webster]


And from WordNet:

   2: the meaning of a word or expression; the way in which a word
  or expression or situation can be interpreted

Both meanings are relevant to the way KJ is using the word. Please take
your own advice and stop giving wrong information. As a native English
speaker, I had no difficulty understanding the meaning of "sense" in the
sense intended by KJ.


As another native English speaker, I agree with Jean-Michel; this is the
first time I've seen "sense" used to mean direction.




Just goes to show you learn something new all the time.

http://www.merriam-webster.com/dictionary/sense

7: one of two opposite directions especially of motion (as 
of a point, line, or surface)



http://dictionary.reference.com/browse/sense

18.  Mathematics. one of two opposite directions in which 
a vector may point.




Paraphrasing the Collins Dictionary of Mathematics:

The sense of a vector is the sign of the measure, contrasted with the 
magnitude. Thus the vectors AB and BA have the same direction but 
opposite sense. Sense is also used to distinguish clockwise and anti-

clockwise.

Sense is, if you like, a "signed direction". "Towards north" (say) as 
opposed to "along the north-south axis".




This also illustrates the importance of knowing your target audience.  I 
have also not seen "sense" used this way before, and from the placement 
in the dictionaries I would venture to say it's not common usage outside 
of mathematics and the sciences.


Of course, since kj is teaching biologists, odds are decent they know 
what he's talking about.


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


Re: language analysis to enforce code standards

2009-07-10 Thread greg

Aahz wrote:


Much simpler and *way* more efficient with a set:

if len(set(s)) < N:
print "Must have at least %s different characters" % N


Or you could do a dictionary lookup on the words.
I can just see the error message:

  "Your comment must include at least one verb,
  one noun, one non-cliched adjective and one
  Monty Python reference."

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


Addind imports to a class namespace

2009-07-10 Thread Ryan K
Greetings,

In order to avoid circular imports, I have a class that I want to
improve upon:

Class GenerateMenuXhtml(threading.Thread):
"""
Subclasses a threading.Thread class to generate a menu's XHTML in
a separate
thread. All Link objects that have this menu associated with it
are gathered
and combined in an XHTML unordered list.

If the sender is of type Link, then all menus associated with that
link are
iterated through and rebuilt.
"""
def __init__(self, instance):
from asqcom.apps.staticpages.models import Menu, Link
self.Link = Link
self.Menu = Menu

As you can see I just expose these imports by attaching them to
members of the class. There must be "prettier" option though where I
can just add these imoprts to the class's namespace so all methods of
any instance will have access to the imported modules.

How would I go about doing this? How can I access the namespace of any
class? Through Class.__dict__?

Thanks,
Ryan

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


windows explorer integration

2009-07-10 Thread Laurent Luce

Hello,

Do you know if it is possible to write a plugin for windows explorer using 
win32 module ?

The idea is to modify the way the folders/files are displayed in the explorer 
window and also to provide some controls.

Laurent

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


Re: main in Python

2009-07-10 Thread Benjamin Kaplan
On Fri, Jul 10, 2009 at 5:52 PM, Tim wrote:
>
> Hi,
> I learned that a Python script is written in this way:
> def main():
>    ...
> if __name__ == "__main__":
>    main()
>
> Today, when I read a script, I found it has a different way:
>
> def main():
>    ...
>
> main()
>
> It can run as well. Can someone explain why and the rules that Python scripts 
> get run?
>


You're thinking like a C or Java programmer. Python scripts are just
that - scripts. They aren't compiled with a main() method for an entry
point- it's interpreted. When you run a python script, everything that
isn't indented is run, from top to bottom, in order. So for instance,
when the interpreter sees the line
def main() :
   pass
it creates a function called main. If you were to have the statement
x= 5
the value 5 would be assigned to x at that time. There are two ways to
execute these scripts- by running them directly and by importing them
into another module. The second way, with the main method, the script
will be run any time it is imported. The first relies on the fact that
any module run as a script has a __name__ attribute of "__main__"
(usually it's the name of the module). The first program acts more
like the C code would- the "main" part of it will only be run if that
script is executed.


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


Re: AP -- MeAmI.org Paces Google

2009-07-10 Thread Dave Angel



David Bernier wrote:



Good day,

Professor X


This is what there is at the bottom of page 3:

<< Conclusion: Binary revisions are allowed given the above formulas. >>

So I don't understand the proposed solution for the "P = NP"
problem.

David Bernier


"Professor X" is yet another alias for the hoaxter who started this 
thread, and presumably who created the website.



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


Re: shutil.rmtree raises "OSError: [Errno 39] Directory not empty" exception

2009-07-10 Thread Maria Liukis
Thanks for pointing out the parameters for ignore_errors and an  
onerror callback function.


I have been running this code for more than an year, and this is the  
very first time I see the problem. We switched to the NFS mounted  
storage though, but there is nothing unusual logged by the system in  
the /var/log/messages.


I checked the permissions - the directory is still there and has  
exactly the same permissions as other successfully copied and removed  
directories (the very same process creates the directory and later  
removes it). The directory is empty though - so the process removed  
all the entries in it, then some kind of an error occured that  
triggered the exception.


There are lots of similar directories that the process creates and  
removes, but only one of them raised an exception.


Thanks,
Masha

liu...@usc.edu



On Jul 10, 2009, at 5:10 PM, Tim Chase wrote:


 shutil.rmtree(filename)
   File "/usr/lib64/python2.5/shutil.py", line 178, in rmtree
 onerror(os.rmdir, path, sys.exc_info())
   File "/usr/lib64/python2.5/shutil.py", line 176, in rmtree
 os.rmdir(path)
OSError: [Errno 39] Directory not empty: /path/to/my/dir
According to the documentation, shutil.rmtree should not care  
about  directory being not empty.


This sounds suspiciously like a permission issue.  rmtree()  
*should* walk the tree removing items *if it can*.  If a file can't  
be deleted, it treats it as an error.  rmtree() takes parameters  
for ignore_errors and an onerror callback function, so you can  
catch these error conditions.


-tkc




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


Re: shutil.rmtree raises "OSError: [Errno 39] Directory not empty" exception

2009-07-10 Thread Tim Chase

 shutil.rmtree(filename)
   File "/usr/lib64/python2.5/shutil.py", line 178, in rmtree
 onerror(os.rmdir, path, sys.exc_info())
   File "/usr/lib64/python2.5/shutil.py", line 176, in rmtree
 os.rmdir(path)
OSError: [Errno 39] Directory not empty: /path/to/my/dir

According to the documentation, shutil.rmtree should not care about  
directory being not empty.


This sounds suspiciously like a permission issue.  rmtree() 
*should* walk the tree removing items *if it can*.  If a file 
can't be deleted, it treats it as an error.  rmtree() takes 
parameters for ignore_errors and an onerror callback function, so 
you can catch these error conditions.


-tkc


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


Re: tough-to-explain Python

2009-07-10 Thread John Nagle

Bearophile wrote:

kj, as Piet van Oostrum as said, that's the difference between mutable
an immutable. It comes from the procedural nature of Python, and
probably an explanation of such topic can't be avoided if you want to
learn/teach Python.


The problem with Python's mutable/immutable distinction is that
it's not very visible.  In a language with no declarations, no named
constants, and no parameter attributes like "value", "in", "out", or
"const", it's not at all obvious which functions can modify what.
Which is usually the place where this causes a problem.

The classic, of course, is

def additemtolist(item, lst = []) :
lst.append(item)
return(lst)

lista = additemtolist(1)
listb = additemtolist(2)
print(listb)

The general problem is inherent in Python's design.  This particular problem,
though, results in the occasional suggestion that parameters shouldn't
be allowed to have mutable defaults.

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


Announcing the 9th Pyweek game programming challenge!

2009-07-10 Thread Richard Jones

The date for the ninth PyWeek challenge has been set:

  Sunday 30th August to Sunday 6th September (00:00UTC to 00:00UTC)


The PyWeek challenge invites entrants to write a game in one week from
scratch either as an individual or in a team. Entries must be developed
in Python, during the challenge, and must incorporate some theme chosen
at the start of the challenge.


REGISTRATION IS NOT YET OPEN --

Registration will open one month before the start date. See the
competition timetable and rules:

   http://www.pyweek.org/9/


PLANNING FOR THE CHALLENGE --

Make sure you have working versions of the libraries you're going to  
use.

The rules page has a list of libraries and other resources.

Make sure you can build packages to submit as your final submission (if
you're going to use py2exe, make sure you know how to use it and that it
works).

If you don't have access to Linux, Windows or a Mac to test on, contact
friends, family or other competitors to find someone who is able to test
for you.

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


Email provider recommendations for those tired of mangled messages (was: subprocess + python-daemon - bug/problem?)

2009-07-10 Thread Ben Finney
Ben Finney  writes:

> Here it is without the unwanted extra line-wrapping that seems to
> plague all Google Mail users (seriously, folks: get a real mail
> provider that won't mangle your messages)

I've been asked off-list whether I have any suggestions for those who
want a better email provider. Handling email (transport and mailbox
services) is certainly a service that's worth getting someone else to
handle, provided you can trust they'll do so reliably and well. For me,
“well” includes “don't mangle my messages”.

My personal solution to this is to manage my own email server machine,
but that's an ongoing investment of time that is not something I would
recommend to everyone.

Nancy McGough maintained (past tense? present tense?) a comprehensive
index http://www.ii.com/internet/messaging/imap/isps/#providers> of
email service providers with IMAP access, hence allowing you to use
whatever IMAP mail client you like to communicate with your mailboxes
remotely. There are feature lists and price indications for each
provider.

Several of my colleagues swear by Tuffmail http://tuffmail.com/> as
providing excellent uptime, fine control filtering, responsive service,
flexible customisation, and good overall value.

-- 
 \“Visitors are expected to complain at the office between the |
  `\ hours of 9 and 11 a.m. daily.” —hotel, Athens |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: tough-to-explain Python

2009-07-10 Thread Terry Reedy

I V wrote:

On Fri, 10 Jul 2009 16:27:12 -0400, Terry Reedy wrote:

a bug, bug a limitation due to using limited-range numbers. If one uses
residue classes instead of integers, and makes no adjustment, I consider
it wrong to blame Bentley.


But it was Bentley himself who used the C int type, so it hardly seems 
unreasonable to blame him.


The original program that he verified was in pseudocode equivalent to 
the following (not tested) Python. The odd spec is due to Bentley using 
1-based arrays. From the 1986 book Programming Pearls


def binsearch(x, t):
   "If t is in sorted x[1:n], return its index; otherwise 0"
   #
   L,U = 1, len(x)-1
   while True:
  if L > U: return 0
  m = (L+U)/2
  if   x[m] <  t: L = m+1
  elif x[m] == t: return m
  elif x[m] >  t: U = m-1

He then translated into an unspecified dialect of BASIC, but it is 
consistent with Microsoft GW-BASIC. If so, L and U were float variables, 
while the largest possible array size for x was 32767. So as near as I 
can tell with that dialect, there was no possible problem with L+U 
overflowing or wrapping. Other dialects, I am not sure.


So I revise my statement to "I consider it wrong to blame the Bentley 
that wrote the original program" ;-).


If he later translated to C and fell into the residue class trap, then 
that reinforces my contention that using residue classes as ints is 
error prone.


Terry Jan Reedy

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


Re: 2.4 VS 3.1 for simple print

2009-07-10 Thread Ben Finney
"earthlink"  writes:

> Why does 
> 
> print "GarbageCollector: collected %d objects." % (gc.collect())
> 
> work in 2.4 but not in 3.1?

For this and other differences introduced in the Python 3.x series, see
http://www.python.org/dev/peps/pep-3100/>.

-- 
 \ “Please do not feed the animals. If you have any suitable food, |
  `\ give it to the guard on duty.” —zoo, Budapest |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not enforce four space indentations in version 3.x?

2009-07-10 Thread Ben Finney
walterbyrd  writes:

> I believe Guido himself has said that all indentions should be four
> spaces - no tabs.

Yes. That's a “should” and not a “must”, even though PEP 8 says it
with a simple imperative::

Use 4 spaces per indentation level.

it soon afterward takes a more nuanced tone::

The most popular way of indenting Python is with spaces only. The
second-most popular way is with tabs only. Code indented with a
mixture of tabs and spaces should be converted to using spaces
exclusively. When invoking the Python command line interpreter with
the -t option, it issues warnings about code that illegally mixes
tabs and spaces. When using -tt these warnings become errors. These
options are highly recommended!

For new projects, spaces-only are strongly recommended over tabs.
Most editors have features that make this easy to do.

http://www.python.org/dev/peps/pep-0008/>

> Since backward compatibility is being thrown away anyway

That implies a level of abandon that was (AIUI) never the intent.
Rather, backward compatibility was critically examined for whether it
was justified in Python 3.

> why not enforce the four space rule?

Guido has used his time machine to answer your question a few years ago
http://www.artima.com/weblogs/viewpost.jsp?thread=101968>. (Be sure
to read the discussion in the comments on the article.)

> At least that way, when I get python code from somebody else, I would
> know what I am looking at, without having to do a hex dump, or
> something.

Any text editor that is good for programming (yes, I'm aware this is
perilously close to a “no true Scotsman” fallacy) will have an option
to visibly differentiate whitespace characters, for exactly the reason
you point out.

-- 
 \   “Special cocktails for the ladies with nuts.” —bar, Tokyo |
  `\   |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


shutil.rmtree raises "OSError: [Errno 39] Directory not empty" exception

2009-07-10 Thread Maria Liukis

Hello,

Has anybody seen an exception "OSError: [Errno 39] Directory not  
empty" raised by shutil.rmtree? The code that raised an exception  
creates a lot of directories with files, and then removes them. I got  
an exception when one of such directories was removed. Here is the  
backtrace:


shutil.rmtree(filename)
  File "/usr/lib64/python2.5/shutil.py", line 178, in rmtree
onerror(os.rmdir, path, sys.exc_info())
  File "/usr/lib64/python2.5/shutil.py", line 176, in rmtree
os.rmdir(path)
OSError: [Errno 39] Directory not empty: /path/to/my/dir

According to the documentation, shutil.rmtree should not care about  
directory being not empty.


Thanks for the help,
Masha

liu...@usc.edu



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


Re: Tkinter only: table widget with canvas...

2009-07-10 Thread John Posner

Hi --


a) Assume I would have some different widgets to add per row. How
do I get the maximum row height?


If you are placing widgets in a table like this:

 w.grid(row=a, column=b)

... where the *master* of widget "w" is a Tkinter.Frame named 
"table_frm", then you can determine the height of row N like this:


  table_frm.grid_bbox(column=0, row=N)

Quoth the grid_bbox() documentation (with the object name changed for 
clarity):


   Returns a 4-tuple describing the bounding box of some or all
   of the grid system in widget |/|table_frm|/|. The first two numbers 
returned
   are the /|x|/ and /|y|/ coordinates of the upper left corner of the 
area,

   and the second two numbers are the width and height.


So the final member of the 4-tuple is the height you want.


b) Assume something like a label in one column. The length of all
texts
in a column will differ. How do I choose the maxium column width?


The third member of grid_bbox() 4-tuple is the cell-width. So just find 
the maximum of these values:


  table_frm.grid_bbox(column=0, row=0)[2]
  table_frm.grid_bbox(column=1, row=0)[2]
  table_frm.grid_bbox(column=2, row=0)[2]
  ...



c) Placing headers in a canvas does not look like a good idea because
I don't want to scroll the headers. Am I right?
c.1) How do I place a none scrollable header in a canvas?  or
c.2) How do I place all headers outside the canvas correctly above
the relating column?



"c.2" is what you want. Again, if the table is in a Tkinter.Frame named 
"frm", you want to create an outer frame, then pack a header frame and 
the table frame into it, vertically:


   rt = Tk()
   outer_frm = Frame(rt)
   outer_frm.pack(expand=True, fill=BOTH)
   header_frm = Frame(outer_frm, height=25)
   header_frm.pack(side=TOP)
   table_frm = Frame(outer_frm)
   table_frm.pack(side=TOP)


(For scrolling, consider making "table_frm" a Pmw.ScrolledFrame instead 
of a Tkinter.Frame.)


As for getting the heading labels correctly placed above the columns, 
pack correctly-sized subframes (Tkinter.Frame's) into "header_frm". To 
determine the size of a column, use grid_bbox() again:


   BBOX_WIDTH_COMPONENT = 2
   header_subfrm = Frame(header_frm, relief=GROOVE, bd=2)
   header_subfrm['width'] = \
table_frm.grid_bbox(column=N, row=0)[BBOX_WIDTH_COMPONENT]
 
Then, use place() to center a label within the subframe:


   header_label = Label(header_subfrm, text="Heading")
   header_label.place(relx=0.5, rely=0.5, anchor=CENTER)

There's a working app at http://cl1p.net/tkinter_table_headers/

-John


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


Re: AP -- MeAmI.org Paces Google

2009-07-10 Thread David Bernier

scribe...@yahoo.com wrote:
[...]


community. But perhaps he is trying to see things a bit differently
and is just not getting the feedback he needs, so he is throwing
tantrums apparently across USENET.

Like I said before, I am just trying to do right by this person who
contacted me, and seemed to be a decent person with a genuine interest
in mathematics. He was very respectful.

Alas, I am at a loss on what specific feedback to give him on his
paper as though I am a professor of Mathematics, Computer Science is
not my specialty.

I told him I would try to get him some feedback on the equations on
page 3.  Would any of you be so kind to help me?

Here is the paper: http://MeAmI.org/pversusnp.pdf

I do thank you for your time.

Good day,

Professor X


This is what there is at the bottom of page 3:

<< Conclusion: Binary revisions are allowed given the above formulas. >>

So I don't understand the proposed solution for the "P = NP"
problem.

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


Re: main in Python

2009-07-10 Thread Tim Harig
On 2009-07-10, Tim  wrote:
[RE-ORDERED]
> It can run as well. Can someone explain why and the rules that Python
> scripts get run?

Everything gets run by default.  The def syntax defines functions but does
not run them -- they are only run when they are called

> Today, when I read a script, I found it has a different way:
> def main():
> ...
>
> main()

This define main and then runs it.

> def main():
> ...
> if __name__ == "__main__":
> main()

This defines main but it only runs it if __name__ == "__main" which will
only happen if the script is called directly:

./sample.py
or
python sample.py
etc.

This form is often preferred because it allows you to import definitions
the module without running the code within the main funciton module.
That way the same file can be used as a standalone program or as an
importable module.
-- 
http://mail.python.org/mailman/listinfo/python-list


main in Python

2009-07-10 Thread Tim

Hi,
I learned that a Python script is written in this way:
def main():
...
if __name__ == "__main__":
main()

Today, when I read a script, I found it has a different way:

def main():
...

main()

It can run as well. Can someone explain why and the rules that Python scripts 
get run?

Thanks and regards,
Tim


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


Re: Automate rsync w/ authentication

2009-07-10 Thread Piet van Oostrum
> Bryan  (B) wrote:

>B> I tried removing the internal quotes, and splitting '-e' from the
>B> other arguments.  I still get the same ssh -h output however:

>B> rshArg = '/usr/bin/ssh -i /home/bry/keys/brybackup.key'
>B> args = [rsyncExec, '-a', '-v', '--dry-run', '-e', rshArg, source,
>B> dest]
>B> p = Popen(args, stdout=PIPE, stderr=PIPE)

For me it works. Of course I substituted local server names, file names
etc. I run this on Mac OS X 10.4.11. The server is some Linux system.


#! /usr/bin/env python

from subprocess import Popen, PIPE
rsyncExec = '/usr/local/bin/rsync'

source = 'xxx.cs.uu.nl:/users/piet/yy'
dest = '/Users/piet/TEMP/test.rsync'

rshArg = '/usr/bin/ssh -i /Users/piet/.ssh/id_rsa'

args = [rsyncExec, '-a', '-v', '-e', rshArg, source, dest]

try:
p = Popen(args, stdout=PIPE, stderr=PIPE)
print 'rsync running with pid %s' % p.pid
out, err = p.communicate()
print 'Errors: %s' % err
print 'Output: %s' % out
except Exception:
print 'Error running rsync'


It just copies the file.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to check if any item from a list of strings is in a big string?

2009-07-10 Thread inkhorn
Thanks all!!  I found the following to be most helpful:  any(substr in
long_string for substr in list_of_strings)

This bang-for-your-buck is one of the many many reasons why I love
Python programming :)

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


[ANN] Pyjamas 0.6pre1 ALPHA release of Pyjamas Widget Set

2009-07-10 Thread Luke Kenneth Casson Leighton
http://pyjs.org - Pyjamas is a port of GWT to Python that can run
applications both on the Desktop (like python-gtk2) and in all
major Web Browsers (as javascript).

This is an alpha release - 0.6pre1 - of the Pyjamas Web Widget Set.

It is a significant upgrade, incorporating Pyjamas Desktop which
can now use Mozilla XULRunner as well as PyWebKitGtk as the
browser engine.
Significant enhancements have been made to the javascript
compiler, which bring python strict features as well as a
relaxed (and faster) compile-time option.

The reason for the 0.6 pre-release is due to the number of
features and improvements added.

Many thanks to Kees, Lovely Systems, and all the people from
EuroPython 2009 who have helped contribute and generally make
Pyjamas fun to work with.

Downloads are available from:
http://code.google.com/p/pyjamas
http://sourceforge.net/projects/pyjamas
http://pypi.python.org/pypi/Pyjamas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: 2.4 VS 3.1 for simple print

2009-07-10 Thread Martin v. Löwis
> Why does
> print "GarbageCollector: collected %d objects." % (gc.collect())
> 
> work in 2.4 but not in 3.1?

Because print is a function in 3.1, so you have to follow it with
a parenthesis.

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


Re: 2.4 VS 3.1 for simple print

2009-07-10 Thread Chris Rebert
On Fri, Jul 10, 2009 at 2:16 PM, earthlink wrote:
> Why does
> print "GarbageCollector: collected %d objects." % (gc.collect())
>
> work in 2.4 but not in 3.1?

Define "works". What error are you getting? Include the exact message
and full error traceback.
Or if no exception is being raised, explain exactly how is it behaving
differently from your expectations.

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


Re: hoe to build a patched socketmodule.c

2009-07-10 Thread Scott David Daniels

jacopo mondi wrote:

Roger Binns wrote:

jacopo mondi wrote:

Hi all, I need to patch socketmodule.c (the _socket module) in order to
add support to an experimental socket family.

You may find it considerably easier to use ctypes since that will avoid
the need for any patching.  You'll also be able to control how read and
write are done (eg read vs recvfrom vs recvmsg vs readv).  You can use
os.fdopen to convert your raw file descriptor into a Python file object
if appropriate.


The typical Python way of dealing with this is an additional module, not
a modified module placed back in the library.  So, take the sources and
edit, but change the module name.  Even better is figure out how to
use _socket.pyd, to create a smaller _socketexpmodule.c and use that.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


2.4 VS 3.1 for simple print

2009-07-10 Thread earthlink
Why does 


print "GarbageCollector: collected %d objects." % (gc.collect())

work in 2.4 but not in 3.1?
--
http://mail.python.org/mailman/listinfo/python-list


Sorry about that, the Counter class is there.

2009-07-10 Thread Scott David Daniels

Scott David Daniels wrote:

Raymond Hettinger wrote:

[Scott David Daniels]

def most_frequent(arr, N): ...

In Py2.4 and later, see heapq.nlargest().

I should have remembered this one


In Py3.1, see collections.Counter(data).most_common(n)

This one is from Py3.2, I think.


Oops -- egg all over my face.  I thought I was checking with 3.1, and it
was 2.6.2.  I _did_ make an explicit check, just poorly.

Again, apologies.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: tough-to-explain Python

2009-07-10 Thread I V
On Fri, 10 Jul 2009 16:27:12 -0400, Terry Reedy wrote:
> a bug, bug a limitation due to using limited-range numbers. If one uses
> residue classes instead of integers, and makes no adjustment, I consider
> it wrong to blame Bentley.

But it was Bentley himself who used the C int type, so it hardly seems 
unreasonable to blame him.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with keys combination!

2009-07-10 Thread Terry Reedy

Alex wrote:

Hi at all,
  I made a simple program that make a screenshot of Desktop and use it
as fullscreen background and then a ball erase image making illusion
that erase Desktop. The program working fine and I succesfully blocked
all keys but I have a problem with hotkey combination Ctrl-Alt-
Del...that bypass my FullScreen Application.


Blocking Ctrl-Alt-Del leaves the power switch or maybe the plug as the 
only way for the user to regain control. Why would you want to do that?


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


Re: Query regarding set([])?

2009-07-10 Thread Terry Reedy

vox wrote:

Hi,
I'm contsructing a simple compare-script and thought I would use set
([]) to generate the difference output. But I'm obviosly doing
something wrong.

file1 contains 410 rows.
file2 contains 386 rows.
I want to know what rows are in file1 but not in file2.

This is my script:
s1 = set(open("file1"))
s2 = set(open("file2"))
s3 = set([])
s1temp = set([])
s2temp = set([])

s1temp = set(i.strip() for i in s1)
s2temp = set(i.strip() for i in s2)
s3 = s1temp-s2temp

print len(s3)

Output is 119. AFAIK 410-386=24. What am I doing wrong here?


Assuming that every line in s2 is in s1. If there are lines in s2 that 
are not in s1, then the number of lines in s1 not in s2 will be larger 
than 24. s1 - s2 subtracts the intersection of s1 and s2.


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


Re: finding most common elements between thousands of multiple arrays.

2009-07-10 Thread Scott David Daniels

Raymond Hettinger wrote:

[Scott David Daniels]

def most_frequent(arr, N): ...

In Py2.4 and later, see heapq.nlargest().

I should have remembered this one


In Py3.1, see collections.Counter(data).most_common(n)

This one is from Py3.2, I think.


--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: ANN: Leo 4.6 rc1 released

2009-07-10 Thread Ville M. Vainio
On Jul 10, 9:54 pm, "Edward K Ream"  wrote:

> The highlights of Leo 4.6:
> --

> - Leo now features a modern Qt interface by default.
>   Leo's legacy Tk interface can also be used.

And to drive home this point (Qt ui), some screenshots for the
visually oriented:

http://imgbin.org/images/625.png
http://imgbin.org/images/626.png
http://imgbin.org/images/627.png
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can i write a assemly language programs in python

2009-07-10 Thread Terry Reedy

Dave Angel wrote:

Terry Reedy wrote:



If you mean dis.dis() that only gives you byte code.


No, dis is a disassembler and it gives readable assembly code, not the 
raw numerical bytes. Its purpose is to make byte code + other parts of 
the code object humanly readable.


As far as I know, there is no assembler that would turn the exact output 
of dis back to its input.


tjr

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


Re: tough-to-explain Python

2009-07-10 Thread Terry Reedy

Steven D'Aprano wrote:

On Thu, 09 Jul 2009 23:07:34 -0400, Terry Reedy wrote:




The is *not* a bug is Bentley program.


This is *not* a bug in Bentley's program.


Wow. That's an impressive set of typos :)


3. Way beneath my usual standards ;-)


It is a bug in bad, buggy, insane
integer arithmetic implementations. low + high should either return the
right answer, as it will in Python, or raise an overflow error.


Is binary search *supposed* to raise an overflow error if given more than 
2**30 elements? 


No. it is supposed to work, and Bentley's program will work if lo and hi 
are actually integers, as his program presupposes, and not residue 
classes mislabeled 'int'.


Is there something special about OverflowError that is "better" than 
ArrayIndexOutOfBoundsException?


Wrong comparison. The actual alternative to OverflowError is a negative 
number as the sum of two positive numbers. If one claims that a and b 
are positive ints, then returning a negative is a bug. The index 
exception was a side effect, in Java, of using the negative as an index. 
In C, the side effect was a segmentation fault. Do you seriously 
question that OverflowError is better than seg faulting? A different 
program could go on to silently return a wrong answer. Perhaps it would 
say to go west instead of east, or to reduce a medical dosage instead of 
raising it.


Note that negative ints are legal indexes in Python, so that if any 
Python version ever had ints that wrapped instead of overflowing or 
returning a long, then the program would not necessarily stop.


but there's no reason to imagine that the book will assume -- or even 
state as a requirement for binary search -- that addition will never 
overflow.


Bentley assumed that if (lo+hi)/2 were successfully calculated, then it 
would be a positive number between lo and hi, and therefore a legal index.


The dirty secret of computing is that some languages do not have integer 
types. They do not even have restricted-range integer types, which would 
noisily fail when they cannot perform an operation. They only have 
residue class types, which are something else, and which can give 
bizarre results if one mindlessly uses them as if they really were 
restricted-range integers. When one wants integer operations, every 
operation with two residue-class variables has a potential *silent* bug. 
Being relieved of the burden of constantly keeping this in mind is one 
reason I use Python.


Float types are usually restricted range types. A huge_float + 
huge_float may raise overflow, but never returns a negative float.


Bentley assumed that indexes hi and lo are integers. If one uses 
restricted range integers that are too large, then lo+hi could fail 
gracefully with an appropriate effor message. I would not consider that 
a bug, bug a limitation due to using limited-range numbers. If one uses 
residue classes instead of integers, and makes no adjustment, I consider 
it wrong to blame Bentley.


Terry Jan Reedy

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


Re: Automate rsync w/ authentication

2009-07-10 Thread Bryan
On Jul 10, 12:43 pm, Piet van Oostrum  wrote:
> > Chris Rebert  (CR) wrote:
> >CR> On Fri, Jul 10, 2009 at 9:13 AM, Bryan wrote:
> >>> I am trying to automate rsync to backup server A from server B.  I
> >>> have set up a private/public key between the two servers so I don't
> >>> have to enter a password when using rsync.  Running rsync manually
> >>> with the following command works fine:
> >>> rsync -av --dry-run -e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"
> >>> r...@10.0.45.67:/home/bry/jquery.lookup /home/bry/tmp
>
> >>> But when I try to do it with python, the subprocess simply returns the
> >>> ssh -h output on stderr like I am passing some invalid syntax.  What
> >>> is wrong in my translation of rsync's -e command from shell to
> >>> pythyon?
>
> >>> #! /usr/bin/python
> >>> from subprocess import Popen, PIPE
> >>> rsyncExec = '/usr/bin/ssh'
> >>> source = 'r...@10.0.45.67:/home/bry/jquery.lookup'
> >>> dest = '/home/bry/tmp'
> >>> rshArg = '-e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
> >>> args = [rsyncExec, '-a', '-v', '--dry-run', rshArg, source, dest]
> >CR> Like many problems involving the subprocess module, I think you've
> >CR> tokenized the arguments incorrectly. Try:
> >CR> rshArg = '"/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
> >CR> args = [rsyncExec, '-av', '--dry-run', '-e', rshArg, source, dest]
> >CR> Note that the -e switch and its operand are separate arguments for the
> >CR> purposes of POSIX shell tokenization.
>
> I think you should have only one kind of quotes in rshArg:
> rshArg = "/usr/bin/ssh -i /home/bry/keys/brybackup.key"
>
> I haven't tried it, however, but this is just how Unix works.
> --
> Piet van Oostrum 
> URL:http://pietvanoostrum.com[PGP 8DAE142BE17999C4]
> Private email: p...@vanoostrum.org

I tried removing the internal quotes, and splitting '-e' from the
other arguments.  I still get the same ssh -h output however:

rshArg = '/usr/bin/ssh -i /home/bry/keys/brybackup.key'
args = [rsyncExec, '-a', '-v', '--dry-run', '-e', rshArg, source,
dest]
p = Popen(args, stdout=PIPE, stderr=PIPE)

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


Re: Nested Classes and Instances

2009-07-10 Thread J. Cliff Dyer
On Fri, 2009-07-10 at 19:00 +0200, Manuel Graune wrote:
> Hello,
> 
> as an example of what I would like to achieve, think of a street
> where each house has a door and a sign with a unique (per house)
> number on it. I tried to model this like this:
> 
> class House(object):
> class Door(object):
> def __init__(self,color):
>  self.color=color
> class Sign(object):
> def __init__(self,text):
>  self.text=text
> def __init__(self, doorcolor,housenumber):
> self.housenumber=housenumber
> self.door=House.Door(doorcolor)
> self.sign=House.Sign(housenumber)
> 
> house1=House("red","1")
> house2=House("blue","2")
> 

Don't do it like that.  Keep your classes independent.  Many houses can
have doors, and there's no reason to redefine the concept of Doors for
each one.  Same goes for Signs.  

class House(object):
def __init__(self, doorcolor, housenumber):
self.door = Door(doorcolor)
self.sign = Sign(housenumber)
self.number = housenumber

class Door(object):
def __init__(self, color):
self.color = color

class Sign(object):
def __init__(self, inscription):
self.inscription = str(housenumber)



(Something like that)

Cheers,
Cliff




> Well, so far, so good. Now, what I'd like to achive is that the text of
> the "sign" changes whenever the variable "housenumber" of the
> "parent-instance" changes or  that
> "house1.sign.text" is a reference/pointer to "house1.housenumber"
> 
> Thanks in advance,
> 
> Manuel
> 
> 
> 
> -- 
> A hundred men did the rational thing. The sum of those rational choices was
> called panic. Neal Stephenson -- System of the world
> http://www.graune.org/GnuPG_pubkey.asc
> Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99

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


Re: Automate rsync w/ authentication

2009-07-10 Thread Chris Rebert
On Fri, Jul 10, 2009 at 12:43 PM, Piet van Oostrum wrote:
>> Chris Rebert  (CR) wrote:
>
>>CR> On Fri, Jul 10, 2009 at 9:13 AM, Bryan wrote:
 I am trying to automate rsync to backup server A from server B.  I
 have set up a private/public key between the two servers so I don't
 have to enter a password when using rsync.  Running rsync manually
 with the following command works fine:
 rsync -av --dry-run -e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"
 r...@10.0.45.67:/home/bry/jquery.lookup /home/bry/tmp

 But when I try to do it with python, the subprocess simply returns the
 ssh -h output on stderr like I am passing some invalid syntax.  What
 is wrong in my translation of rsync's -e command from shell to
 pythyon?

 #! /usr/bin/python
 from subprocess import Popen, PIPE
 rsyncExec = '/usr/bin/ssh'
 source = 'r...@10.0.45.67:/home/bry/jquery.lookup'
 dest = '/home/bry/tmp'
 rshArg = '-e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
 args = [rsyncExec, '-a', '-v', '--dry-run', rshArg, source, dest]
>
>>CR> Like many problems involving the subprocess module, I think you've
>>CR> tokenized the arguments incorrectly. Try:
>
>>CR> rshArg = '"/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
>>CR> args = [rsyncExec, '-av', '--dry-run', '-e', rshArg, source, dest]
>
>>CR> Note that the -e switch and its operand are separate arguments for the
>>CR> purposes of POSIX shell tokenization.
>
> I think you should have only one kind of quotes in rshArg:
> rshArg = "/usr/bin/ssh -i /home/bry/keys/brybackup.key"
>
> I haven't tried it, however, but this is just how Unix works.

Ah, indeed, I think you're probably right. Just goes to show it's not
always easy to get exactly right.

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


Re: Automate rsync w/ authentication

2009-07-10 Thread Piet van Oostrum
> Chris Rebert  (CR) wrote:

>CR> On Fri, Jul 10, 2009 at 9:13 AM, Bryan wrote:
>>> I am trying to automate rsync to backup server A from server B.  I
>>> have set up a private/public key between the two servers so I don't
>>> have to enter a password when using rsync.  Running rsync manually
>>> with the following command works fine:
>>> rsync -av --dry-run -e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"
>>> r...@10.0.45.67:/home/bry/jquery.lookup /home/bry/tmp
>>> 
>>> But when I try to do it with python, the subprocess simply returns the
>>> ssh -h output on stderr like I am passing some invalid syntax.  What
>>> is wrong in my translation of rsync's -e command from shell to
>>> pythyon?
>>> 
>>> #! /usr/bin/python
>>> from subprocess import Popen, PIPE
>>> rsyncExec = '/usr/bin/ssh'
>>> source = 'r...@10.0.45.67:/home/bry/jquery.lookup'
>>> dest = '/home/bry/tmp'
>>> rshArg = '-e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
>>> args = [rsyncExec, '-a', '-v', '--dry-run', rshArg, source, dest]

>CR> Like many problems involving the subprocess module, I think you've
>CR> tokenized the arguments incorrectly. Try:

>CR> rshArg = '"/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
>CR> args = [rsyncExec, '-av', '--dry-run', '-e', rshArg, source, dest]

>CR> Note that the -e switch and its operand are separate arguments for the
>CR> purposes of POSIX shell tokenization.

I think you should have only one kind of quotes in rshArg:
rshArg = "/usr/bin/ssh -i /home/bry/keys/brybackup.key"

I haven't tried it, however, but this is just how Unix works.
-- 
Piet van Oostrum 
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: p...@vanoostrum.org
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help me to find the error

2009-07-10 Thread Terry Reedy

jhinak sen wrote:

hi,
i am a beginner in python language,


Welcome to Python.


i am trying with this programme :
to find the addition and mean from a data set in a file and writing the 
mean and sum in some other file :


This is three things: input data from, perform calculation, output data 
to file. I would start simpler. See below.


You did two things right that too many people do not do.

1. You posted a complete chunk of code.


""
*#! /usr/bin/env python

import re
import cPickle as p
import math
from numpy import *


You never use these.


f0= open("temp9","r+").readlines()


[snip]

f0.close()
f2.close()*


2. You posted the complete traceback (instead of the annoying 'program 
didn't work ;-).



""*Traceback (most recent call last):
  File "./temporary1.py", line 24, in 
f0.close()
AttributeError: 'list' object has no attribute 'close'*
""

please help to to find the error.


Seeing that, any of us could tell you thought f0 was a file but it was 
actually a list. Looking back up through the code, people found the 
definition -- the output of file.readlines, which is a list.



or suggest some simpler or better way


Develop more incrementally. If you edit with IDLE, for instance, and hit 
RUN (F5), it takes about a second to see the result for a small program 
like this. I would have suggested starting with


data = [(1,2), (3,4)]
...
print "input: ", a, b, "output: ", tot, ave

and fill in ... until the output was correct.

Then change data to ['1 2', '3 4'] and revise until correct.

At that point, change data to open() and the program should 
otherwise work without change because a list of strings and a file are 
both iterators that produce a sequence of strings.


Now, if you want, worry about formating the output, removing the echo of 
the input.


Very last, send to output to a disk file instead of the screen. For 
development, that is a nuisance because it takes time to open the file 
to check results. So only do that when you already know the results are 
correct. Note that real programs used repeatedly ofter do not hard code 
an output file. If run from a command line in a comman window, screen 
output can be redirected to a file with '>': "myprog > outfile".


Terry Jan Reedy

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


Re: Why not enforce four space indentations in version 3.x?

2009-07-10 Thread Aahz
In article <260f0f1f-1115-4db8-a955-74c9f459e...@h30g2000vbr.googlegroups.com>,
walterbyrd   wrote:
>
>I believe Guido himself has said that all indentions should be four
>spaces - no tabs.
>
>Since backward compatibility is being thrown away anyway, why not
>enforce the four space rule?

Probably the main reason is that Guido also hates non-functional code
changes because it messes up version history.  Not sure, though.
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why not enforce four space indentations in version 3.x?

2009-07-10 Thread Chris Rebert
On Fri, Jul 10, 2009 at 12:22 PM, walterbyrd wrote:
> I believe Guido himself has said that all indentions should be four
> spaces - no tabs.

That's a (very good) recommendation at most.
http://www.python.org/dev/peps/pep-0666/

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


Re: Why not enforce four space indentations in version 3.x?

2009-07-10 Thread Kurt Smith
On Fri, Jul 10, 2009 at 2:22 PM, walterbyrd wrote:
> I believe Guido himself has said that all indentions should be four
> spaces - no tabs.
>
> Since backward compatibility is being thrown away anyway, why not
> enforce the four space rule?
>
> At least that way, when I get python code from somebody else, I would
> know what I am looking at, without having to do a hex dump, or
> something.

What you propose has already been (forcefully) rejected:

http://www.python.org/dev/peps/pep-0666/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: AP -- MeAmI.org Paces Google

2009-07-10 Thread Musatov


François Grondin wrote:
> "David Bernier"  a �crit dans le message de news:
> h36ki102...@news5.newsguy.com...
> > Musatov wrote:
> >> On Jul 9, 7:54 pm, David Bernier  wrote:
> >>> Musatov wrote:
>  Los Angeles (AP) --MeAmI.org now has users in 50 countries following
>  its adopted use in Pakistan.  The search engine has grown in
>  popularity 10,000 fold following its Beta test launch three months ago
>  in April, 2009. Supporters of the site claim it is better than rival
>  Google upon which platform it is based. Controversy arose after
>  MeAmI.org search code allowed users to search other users Google
>  results with no advertising. "It is truly an innovative thing we are
>  doing," said Founder and CEO, Martin Musatov. "Letting users search
>  the results of other Google users immediately results in a level of
>  accuracy and relevance above and beyond Google." Google changed their
>  API following the launch or MeAmI.org and explored the possibility of
>  blocking site access from MeAmI.org to Google search results but was
>  unable to do so. Critics of MeAmI.org say what it is doing is
>  tantamount to intellectual theft. When asked about this topper Musatov
>  exclaimed, "The Internet was made for people, not companies." An
>  analyst at Goldman Sachs says, requesting to remain anonymous,
>  "MeAmI.org has a strong presence in promoting itself as a vehicle for
>  global activism and to tell you the truth, this makes it much more
>  likely an acquisition target than potential intellectual property
>  violator." Google could not be reached for comment.
> >>> Mr. Musatov,  do you know who originally wrote the
> >>> article above?
> >>>
> >>> Thank you.
> >>>
> >>> David Bernier- Hide quoted text -
> >>>
> >>> - Show quoted text -
> >>
> >> Yes.
> >
> > Mr. Musatov, do you know the name of the person who
> > originally wrote the article above?
> >
> > Thank you.
> >
> > David Bernier
>
> Maybe Mr. Musatov should answer the following questions instead :
> 1. Did you write the article above?
> 2. If not, who did? And I don't want AP as the answer, but the name of the
> journalist.
>
> David, don't take it bad, but he answered your question with an accurate
> answer (yes), You gave him the opportunity to avoid the real answer and he
> took it. Based on Musatov's strange behavior and logic, don't expect more
> from him. Ask anyone else the same question and you'd get a real answer.
>
> BTW, my guess for question 2 would be the Masked Logician, Floetry,
> scriber77, or Professor X.
>
> Francois
1. Yes.
-- 
http://mail.python.org/mailman/listinfo/python-list


Why not enforce four space indentations in version 3.x?

2009-07-10 Thread walterbyrd
I believe Guido himself has said that all indentions should be four
spaces - no tabs.

Since backward compatibility is being thrown away anyway, why not
enforce the four space rule?

At least that way, when I get python code from somebody else, I would
know what I am looking at, without having to do a hex dump, or
something.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Colour of output text

2009-07-10 Thread Chris Rebert
On Fri, Jul 10, 2009 at 2:23 AM,
 wrote:
> Tim Harig  wrote:
>> On 2009-07-09, Alex Rosslyn  wrote:
>>> I would like to learn a way of changing the colour of a particular
>>> part of the output text. I've tried the following
>
>> On Unix operating systems this would be done through the curses interface:
>>
>> http://docs.python.org/library/curses.html
>
> Or using ANSI colour codes:
>
> colours = {

>            'beep'       :    "\007",

Sound is a color? Maybe if you have synaesthesia...

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


Re: Clarity vs. code reuse/generality

2009-07-10 Thread Robert Kern

On 2009-07-10 13:56, J. Cliff Dyer wrote:

On Fri, 2009-07-10 at 11:57 -0500, Robert Kern wrote:

On 2009-07-10 11:50, J. Cliff Dyer wrote:

On Fri, 2009-07-10 at 02:57 +, Steven D'Aprano wrote:

On Fri, 10 Jul 2009 03:28:04 +0100, Nobody wrote:


On Thu, 09 Jul 2009 04:57:15 -0300, Gabriel Genellina wrote:


Nobody says you shouldn't check your data. Only that "assert" is not
the right way to do that.

"assert" is not the right way to check your *inputs*. It's a perfectly
reasonable way to check data which "should" be valid, as well as a way
to document what variables are supposed to contain.

Where are those variables coming from?

The distinction really boils down to this:

* asserts should never fail. If there is any chance that an assertion
might fail outside of test suites, then don't use assert.


I'm no expert, but the more I read this thread, and the more I think on
it, the more I believe that asserts don't really need to exist outside
of test suites.

Actually, there is a good argument that one shouldn't use an assert statement in
test suites: code can have bugs that only show up under -O so you want to be
able to run your test suite under -O.



That's an interesting point.  Presumably TestCase.assert_() doesn't
suffer from this defect?  Otherwise the entire unittest suite is
essentially broken by your argument.


It explicitly raises AssertionErrors. It does not use the assert statement.


I suppose I should have said one
should only raise AssertionErrors in test suites.  Practically speaking,
that's what a test suite is:  The place where you assert what the code
does.


Yup.

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


ANN: Leo 4.6 rc1 released

2009-07-10 Thread Edward K Ream
Leo 4.6 rc1 is now available at:
http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106

Leo is a text editor, data organizer, project manager and much more. See:
http://webpages.charter.net/edreamleo/intro.html

The highlights of Leo 4.6:
--

- Cached external files *greatly* reduces the time to load .leo files.
- Leo now features a modern Qt interface by default.
  Leo's legacy Tk interface can also be used.
- New --config, --file and --gui command-line options.
- Leo tests syntax of .py files when saving them.
- Leo can now open any kind of file into @edit nodes.
- @auto-rst nodes allow easy editing of reStructuredText files.
- Properties of commanders, positions and nodes simplify programming.
- Improved Leo's unit testing framework.
- Leo now requires Python 2.5 or later.
- Dozens of small improvements and bug fixes.

Links:
--
Leo:  http://webpages.charter.net/edreamleo/front.html
Forum:http://groups.google.com/group/leo-editor
Download: http://sourceforge.net/project/showfiles.php?group_id=3458
Bzr:  http://code.launchpad.net/leo-editor/
Quotes:   http://webpages.charter.net/edreamleo/testimonials.html

Edward K. Ream   email:  edream...@yahoo.com
Leo: http://webpages.charter.net/edreamleo/front.html



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


Re: gett error message: "TypeError: 'int' object is not callable"

2009-07-10 Thread J. Cliff Dyer
On Thu, 2009-07-09 at 13:53 +, Friðrik Már Jónsson wrote:
> Look at:
> 
>len = len(text)
> 
> You're overriding `len` (a built-in method), with an integer  
> (`len(text)`).  You then call:
> 
>for i in range(len(fields)):
> 
> But `len` is no longer a callable, but merely an integer.
> 
> Regards,
> Friðrik Már
> 
> P.S. While this is a fairly obvious problem it's usually a good idea  
> to post working code and a traceback when requesting help.

While we're on the subject of good question posting form:  The body of
your post should contain all relevant information.  Please don't make
readers look back at the subject heading for the statement of the
problem.  Duplicating the statement of the problem in the subject and
the body is ok, but it really ought to be in the body.

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


Re: Clarity vs. code reuse/generality

2009-07-10 Thread J. Cliff Dyer
On Fri, 2009-07-10 at 11:57 -0500, Robert Kern wrote:
> On 2009-07-10 11:50, J. Cliff Dyer wrote:
> > On Fri, 2009-07-10 at 02:57 +, Steven D'Aprano wrote:
> >> On Fri, 10 Jul 2009 03:28:04 +0100, Nobody wrote:
> >>
> >>> On Thu, 09 Jul 2009 04:57:15 -0300, Gabriel Genellina wrote:
> >>>
>  Nobody says you shouldn't check your data. Only that "assert" is not
>  the right way to do that.
> >>> "assert" is not the right way to check your *inputs*. It's a perfectly
> >>> reasonable way to check data which "should" be valid, as well as a way
> >>> to document what variables are supposed to contain.
> >> Where are those variables coming from?
> >>
> >> The distinction really boils down to this:
> >>
> >> * asserts should never fail. If there is any chance that an assertion
> >> might fail outside of test suites, then don't use assert.
> >>
> >
> > I'm no expert, but the more I read this thread, and the more I think on
> > it, the more I believe that asserts don't really need to exist outside
> > of test suites.
> 
> Actually, there is a good argument that one shouldn't use an assert statement 
> in 
> test suites: code can have bugs that only show up under -O so you want to be 
> able to run your test suite under -O.
> 

That's an interesting point.  Presumably TestCase.assert_() doesn't
suffer from this defect?  Otherwise the entire unittest suite is
essentially broken by your argument.  I suppose I should have said one
should only raise AssertionErrors in test suites.  Practically speaking,
that's what a test suite is:  The place where you assert what the code
does.



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


Re: tough-to-explain Python

2009-07-10 Thread Scott David Daniels

Steven D'Aprano wrote:

On Fri, 10 Jul 2009 08:28:29 -0700, Scott David Daniels wrote:

Steven D'Aprano wrote:

Even *soup stock* fits the same profile as what Hendrik claims is
almost unique to programming. On its own, soup stock is totally
useless. But you make it, now, so you can you feed it into something
else later on.
Or instant coffee.

I think I'll avoid coming to your house for a cup of coffee. :-)
I meant the instant coffee powder is prepared in advance. It's useless on 
it's own, but later on you feed it into boiling water, add sugar and 
milk, and it's slightly less useless.


I know, but the image of even a _great_ soup stock with instant
coffee poured in, both appalled me and made me giggle.  So, I
thought I'd share.

--Scott David Daniels
scott.dani...@acm.org
--
http://mail.python.org/mailman/listinfo/python-list


Re: Automate rsync w/ authentication

2009-07-10 Thread Chris Rebert
On Fri, Jul 10, 2009 at 9:13 AM, Bryan wrote:
> I am trying to automate rsync to backup server A from server B.  I
> have set up a private/public key between the two servers so I don't
> have to enter a password when using rsync.  Running rsync manually
> with the following command works fine:
> rsync -av --dry-run -e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"
> r...@10.0.45.67:/home/bry/jquery.lookup /home/bry/tmp
>
> But when I try to do it with python, the subprocess simply returns the
> ssh -h output on stderr like I am passing some invalid syntax.  What
> is wrong in my translation of rsync's -e command from shell to
> pythyon?
>
> #! /usr/bin/python
> from subprocess import Popen, PIPE
> rsyncExec = '/usr/bin/ssh'
> source = 'r...@10.0.45.67:/home/bry/jquery.lookup'
> dest = '/home/bry/tmp'
> rshArg = '-e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
> args = [rsyncExec, '-a', '-v', '--dry-run', rshArg, source, dest]

Like many problems involving the subprocess module, I think you've
tokenized the arguments incorrectly. Try:

rshArg = '"/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
args = [rsyncExec, '-av', '--dry-run', '-e', rshArg, source, dest]

Note that the -e switch and its operand are separate arguments for the
purposes of POSIX shell tokenization.

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


Re: language analysis to enforce code standards

2009-07-10 Thread Tim Rowe
2009/7/10 Peter Otten <__pete...@web.de>:

> Don't be a fool. Have someone other than the author read the comment.

That's the winning answer as far as I'm concerned. Automated tools are
good for picking up some types of accidental mistakes, but for
checking that comments are meaningful (and variable names, for that
matter) you can't do without peer review.

Think about it. What's the purpose of "enforcing standards". Just a
tick in some assurance box to say "we meet these standards"? Ot to
ensure something about the product quality?

No automated tool -- not for a while yet, anyway -- is going to pick
up comments such as:

# increment x
x += 1

or

# You are not expected to understand this.

The former is the sort of thing that any programmer might produce when
against a deadline and forced to comment their code. The latter is a
classic from a programming guru of old. An automatic checker that just
checks that the comment exists without understanding its contents
simply is not adding value but is rather petty bureaucracy that will
annoy the programmers.


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


python make dies :libtk8.5.so: cannot open shared object file: No such file or directory

2009-07-10 Thread Lay, Tony
Trying to build python-2.6.2

 

./configure --prefix=/usr/local --exec-prefix=/usr/local
LDFLAGS="-L/usr/local"

(runs through happily, had to make some libs local)

 

make runs most of the way until.

 

building '_tkinter' extension

gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall
-Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I.
-I/tmp/meld/Python-2.6.2/./Include -I. -IInclude -I./Include
-I/usr/local/include -I/tmp/meld/Python-2.6.2/Include
-I/tmp/meld/Python-2.6.2 -c /tmp/meld/Python-2.6.2/Modules/_tkinter.c -o
build/temp.linux-i686-2.6/tmp/meld/Python-2.6.2/Modules/_tkinter.o

gcc -pthread -fPIC -fno-strict-aliasing -DNDEBUG -g -fwrapv -O3 -Wall
-Wstrict-prototypes -DWITH_APPINIT=1 -I/usr/X11R6/include -I.
-I/tmp/meld/Python-2.6.2/./Include -I. -IInclude -I./Include
-I/usr/local/include -I/tmp/meld/Python-2.6.2/Include
-I/tmp/meld/Python-2.6.2 -c /tmp/meld/Python-2.6.2/Modules/tkappinit.c -o
build/temp.linux-i686-2.6/tmp/meld/Python-2.6.2/Modules/tkappinit.o

gcc -pthread -shared
build/temp.linux-i686-2.6/tmp/meld/Python-2.6.2/Modules/_tkinter.o
build/temp.linux-i686-2.6/tmp/meld/Python-2.6.2/Modules/tkappinit.o
-L/usr/X11R6/lib64 -L/usr/X11R6/lib -L/usr/local/lib -ltk8.5 -ltcl8.5 -lX11
-o build/lib.linux-i686-2.6/_tkinter.so

*** WARNING: renaming "_tkinter" since importing it failed: libtk8.5.so:
cannot open shared object file: No such file or directory

 

Failed to find the necessary bits to build these modules:

_sqlite3   bsddb185   sunaudiodev

To find the necessary bits, look in setup.py in detect_modules() for the
module's name.

 

 

Failed to build these modules:

_tkinter

 

running build_scripts

# cd /usr/local/lib

# ls -la | grep libtk8.5.so

-r-xr-xr-x   1 root root  1112606 Jul 10 13:28 libtk8.5.so

Am I missing something, it's there?

 

Regards,

 

Tony Lay

UNIX Administration 

407-306-6559

Lockheed Martin - EBS 

One Company, One Team

 

BEGIN:VCARD
VERSION:2.1
N:Lay;Anthony (Tony)
FN:Anthony (Tony) Lay (tony@lmco.com)
ORG:Lockheed Martin
TITLE:Computer Network Supprt SrSpec
TEL;WORK;VOICE:407/306-6559
TEL;PAGER;VOICE:321/297-0122
ADR;WORK:;;12506 Lake Underhill Rd;Orlando;FL;32825;US
LABEL;WORK;ENCODING=QUOTED-PRINTABLE:12506 Lake Underhill Rd=0D=0AOrlando, FL 32825=0D=0AUS
EMAIL;PREF;INTERNET:tony@lmco.com
REV:20090424T165829Z
END:VCARD


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


Re: Running a script to build docs from setup.py

2009-07-10 Thread Tony Houghton
On Fri, 10 Jul 2009 11:06:34 +1000
Ben Finney  wrote:

> Tony Houghton  writes:
> 
> > I've looked through the manual but I can't find any hooks in distutils
> > for generating files at install time other than extension modules and
> > .pyc files. Should I just run the script from somewhere in my setup.py
> > before calling distutils' setup function?
> 
> Indirectly related: Ian Bicking's article on using Python's ‘setup.py’
> as a ‘Makefile’ replacement:
> 
> http://blog.ianbicking.org/pythons-makefile.html>

Thanks, but I don't think that adds much to the distutils manual.

> If one is writing a ‘setup.py’ anyway, I think it makes sense to use
> that as the build program for the whole project if possible. Good
> hunting!

Yes. Really I only want to write a setup.py because it makes it easier
to make a debian package, but the more of the installation that's done
by setup.py the better I suppose, then other people might find it
useful.

-- 
TH * http://www.realh.co.uk

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


Re: tough-to-explain Python

2009-07-10 Thread Wesley Chun
On Jul 7, 1:04 pm, kj  wrote:
> I'm having a hard time coming up with a reasonable way to explain
> certain things to programming novices.
> :
> How do I explain to rank beginners (no programming experience at
> all) why x and y remain unchanged above, but not z?
> :
> What do you say to that?
>
> I can come up with much mumbling about pointers and stacks and
> heaps and much hand-waving about the underlying this-and-that, but
> nothing that sounds even remotely illuminating.
>
> Your suggestions would be much appreciated!


kj,

i don't have too much to add to everyone else's response except to
describe how i deal with this. i teach Python courses several times a
year and realized long ago that conveying the concept of mutable vs.
immutable is a key to getting up-to-speed quickly with Python as well
as helping beginners.

so, although techically, this is more of an intermediate topic rather
than "beginner" material, i still teach it anyway, with the hopes of
producing better Python programmers out of the gate, and hopefully,
less frustrated ones. in fact, i dedicated an entire chapter (4) in
Core Python Programming just to address this important issue. to top
it all off, i end this module in the class by giving 2 quizzes, just
to make sure they understood what i just told them. i put the 1st one
online, so if you're curious, the PDF is at 
http://roadkill.com/~wesc/cyberweb/introQuiz.pdf
... the 2nd quiz is harder and involves the discussion of the
differences between shallow and deep copies. so yes, not very beginner-
ish stuff, hence the reason why i (re)named my course "Intro
+Intermediate Python".

finally, rather than the "paper tag" or alex's hotel statue analogy, i
just say that variables are like Post-It® or sticky notes on
objects. i can tag objects anytime, tag objects more than once, remove
tags, or switch them to another object, etc.

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

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


Re: Nested Classes and Instances

2009-07-10 Thread Peter Otten
Manuel Graune wrote:

> as an example of what I would like to achieve, think of a street
> where each house has a door and a sign with a unique (per house)
> number on it. I tried to model this like this:
> 
> class House(object):
> class Door(object):
> def __init__(self,color):
>  self.color=color
> class Sign(object):
> def __init__(self,text):
>  self.text=text
> def __init__(self, doorcolor,housenumber):
> self.housenumber=housenumber
> self.door=House.Door(doorcolor)
> self.sign=House.Sign(housenumber)
> 
> house1=House("red","1")
> house2=House("blue","2")
> 
> Well, so far, so good. Now, what I'd like to achive is that the text of
> the "sign" changes whenever the variable "housenumber" of the
> "parent-instance" changes or  that
> "house1.sign.text" is a reference/pointer to "house1.housenumber"

Python doesn't support C-style pointers, but you can work around it to some 
degree:

>>> class House(object):
... def __init__(self, housenumber):
... self.housenumber = housenumber
... self.sign = Sign(self)
...
>>> class Sign(object):
... def __init__(self, house):
... self.house = house
... @property
... def text(self): return self.house.housenumber
...
>>> house = House(42)
>>> house.sign.text
42
>>> house.housenumber = "42b"
>>> house.sign.text
'42b'

If you are concerned about the tight coupling between House and Sign you can 
modify Sign to accept a function that gets the housenumber:

>>> class House(object):
... def __init__(self, n): self.housenumber = n
...
>>> class Sign(object):
... def __init__(self, gettext):
... self._gettext = gettext
... @property
... def text(self): return self._gettext()
...
>>> house = House(7)
>>> house.sign = Sign(lambda house=house: house.housenumber)
>>> house.sign.text
7

Peter

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


Re: gett error message: "TypeError: 'int' object is not callable"

2009-07-10 Thread Nick
On Jul 9, 8:22 pm, Paul Rubin  wrote:
> Nick  writes:
> > text = file.readlines()
> > len = len(text)
> > fields = text[1].split()
>
> Is that intended to split the first line of the file?  Remember
> that arrays in python begin at index 0.

no the '1st line' is garbled meta data, but thanks man
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: can i write a assemly language programs in python

2009-07-10 Thread member thudfoo
On Fri, Jul 10, 2009 at 5:37 AM, Tim Chase wrote:
> m.reddy prasad reddy wrote:
>>
>> can any one tell me how to write assembly language programs in python...if
>> no is there any other way to write the programs in python
>
> Bah, writing assembly language is easy in Python:
>
>  print("MOV EAX, [EBX]")
>  print("XOR EBX, EBX")
>
> Just adjust the strings for your favorite processor architecture and Python
> will produce the assembly code you want.
>
> Now compiling assembly to *machine* code...or calling between Python and
> assembly...that's another matter.  But writing assembly language programs in
> Python?  Easy. ;-)
>

"PyASM is a full-featured dynamic assembler written entirely in
Python. By dynamic, I mean that it can be used to generate and execute
machine code in python at runtime without requiring the generation of
object files and linkage. It essentially allow 'inline' assembly in
python modules on x86 platforms.

"PyASM can also generate object files (for windows) like a traditional
standalone assembler, although you're probably better off using one of
the many freely available assemblers if this is you primary goal."

http://members.verizon.net/~olsongt/usersGuide.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with subprocess

2009-07-10 Thread Christian Heimes
gabrielmonnerat wrote:
>> I am using subprocess because I need store the pid. Any suggestions?
> Sorry, I was forgot the parameter shell=True.
> i.e
> In [20]: subprocess.call('DISPLAY=:99
> /opt/ooo-dev3/program/soffice.bin',shell=True)

You should avoid using the shell=True parameter. It may result in
security issues and it consumes more resources. Try this:

env = os.environ.copy()
env["DISPLAY"] = ":99"
subprocess.call(['opt/ooo-dev3/program/soffice.bin', env=env)

Christian

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


Nested Classes and Instances

2009-07-10 Thread Manuel Graune

Hello,

as an example of what I would like to achieve, think of a street
where each house has a door and a sign with a unique (per house)
number on it. I tried to model this like this:

class House(object):
class Door(object):
def __init__(self,color):
 self.color=color
class Sign(object):
def __init__(self,text):
 self.text=text
def __init__(self, doorcolor,housenumber):
self.housenumber=housenumber
self.door=House.Door(doorcolor)
self.sign=House.Sign(housenumber)

house1=House("red","1")
house2=House("blue","2")

Well, so far, so good. Now, what I'd like to achive is that the text of
the "sign" changes whenever the variable "housenumber" of the
"parent-instance" changes or  that
"house1.sign.text" is a reference/pointer to "house1.housenumber"

Thanks in advance,

Manuel



-- 
A hundred men did the rational thing. The sum of those rational choices was
called panic. Neal Stephenson -- System of the world
http://www.graune.org/GnuPG_pubkey.asc
Key fingerprint = 1E44 9CBD DEE4 9E07 5E0A  5828 5476 7E92 2DB4 3C99
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where does setuptools live?

2009-07-10 Thread Inky 788
On Jul 10, 10:26 am, Chris Withers  wrote:
> Inky 788 wrote:
> > Currently, distutils itself is being actively developed. More info
> > about this here:http://tarekziade.wordpress.com/
>
> > My (albeit anonymous) advice is: use distutils. Manually download
> > packages as-needed from PyPI and install manually using standard
> > distutils.
>
> No thanks. I'm a big fan of buildout. Making it possible for packages to
> specify their dependencies is a big win...

Read this: 
http://tarekziade.wordpress.com/2009/07/03/dropping-pep-386-versions-comparison/

So, again, I don't know anything about buildout, and it might be a
nice interim solution, but there are some new and exciting
developments in distutils coming down the pike, and whatever becomes
the standard Python package management system will very likely be
based on those new developments.

I just hope it all happens sooner than later. :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-10 Thread Robert Kern

On 2009-07-10 11:50, J. Cliff Dyer wrote:

On Fri, 2009-07-10 at 02:57 +, Steven D'Aprano wrote:

On Fri, 10 Jul 2009 03:28:04 +0100, Nobody wrote:


On Thu, 09 Jul 2009 04:57:15 -0300, Gabriel Genellina wrote:


Nobody says you shouldn't check your data. Only that "assert" is not
the right way to do that.

"assert" is not the right way to check your *inputs*. It's a perfectly
reasonable way to check data which "should" be valid, as well as a way
to document what variables are supposed to contain.

Where are those variables coming from?

The distinction really boils down to this:

* asserts should never fail. If there is any chance that an assertion
might fail outside of test suites, then don't use assert.



I'm no expert, but the more I read this thread, and the more I think on
it, the more I believe that asserts don't really need to exist outside
of test suites.


Actually, there is a good argument that one shouldn't use an assert statement in 
test suites: code can have bugs that only show up under -O so you want to be 
able to run your test suite under -O.


--
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: problem with subprocess

2009-07-10 Thread gabrielmonnerat

gabrielmonnerat wrote:

Hi all,

I need start a openoffice in Xvfb, but when I call with the DISPLAY 
occurs this error:


[r...@localhost oood]# Xvfb :99 -screen 0 1024x768x24 &

In [9]: subprocess.call('/opt/ooo-dev3/program/soffice.bin')
Out[9]: 0

In [10]: subprocess.call('DISPLAY=:99 /opt/ooo-dev3/program/soffice.bin')
--- 

OSError   Traceback (most recent call 
last)


/home/gabriel/ in ()

/usr/lib/python2.6/subprocess.pyc in call(*popenargs, **kwargs)
   442 retcode = call(["ls", "-l"])
   443 """
--> 444 return Popen(*popenargs, **kwargs).wait()
   445
   446

/usr/lib/python2.6/subprocess.pyc in __init__(self, args, bufsize, 
executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, 
env, universal_newlines, startupinfo, creationflags)

   593 p2cread, p2cwrite,
   594 c2pread, c2pwrite,
--> 595 errread, errwrite)
   596
   597 # On Windows, you cannot just redirect one or two 
handles: You



/usr/lib/python2.6/subprocess.pyc in _execute_child(self, args, 
executable, preexec_fn, close_fds, cwd, env, universal_newlines, 
startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, 
c2pwrite, errread, errwrite)

  1104 os.waitpid(self.pid, 0)
  1105 child_exception = pickle.loads(data)
-> 1106 raise child_exception
  1107
  1108

OSError: [Errno 2] No such file or directory

I am using subprocess because I need store the pid. Any suggestions?

Sorry, I was forgot the parameter shell=True.
i.e
In [20]: subprocess.call('DISPLAY=:99 
/opt/ooo-dev3/program/soffice.bin',shell=True)


lack of attention mine


thanks in advance,

Gabriel M. Monnerat



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


Re: problem with keys combination!

2009-07-10 Thread Alex
Hi Steven,

> As I understand it, you can't block, modify, or otherwise access Ctrl-Alt-
> Del while running under Windows: it is the "Secure Attention Key", and is
> designed to be virtually impossible to interfere with. It's not *quite*
> impossible, but it is the deepest, darkest black magic. Microsoft makes
> it close enough to impossible as makes no difference even for experienced
> developers.

No, is possible but for my level is quite impossible:

http://www.codeproject.com/KB/winsdk/AntonioWinLock.aspx

...in this article the author move a lot a functions in a dll  and
make a demonstration with a VB and C code to use it...plus...there is
his program that make it :-
I thought that python can read dll via ctypes...but it's very hard for
me :-((

>
> As a newbie, well, put it this way: it's like somebody saying "Hi guys, I
> have a shiny new Swiss Army Knife, the one with the screwdriver and the
> corkscrew. I'd like to build my own Space Shuttle -- what do I do?"
>
:-))but yes We cannn

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


Re: Clarity vs. code reuse/generality

2009-07-10 Thread J. Cliff Dyer
On Fri, 2009-07-10 at 02:57 +, Steven D'Aprano wrote:
> On Fri, 10 Jul 2009 03:28:04 +0100, Nobody wrote:
> 
> > On Thu, 09 Jul 2009 04:57:15 -0300, Gabriel Genellina wrote:
> > 
> >> Nobody says you shouldn't check your data. Only that "assert" is not
> >> the right way to do that.
> > 
> > "assert" is not the right way to check your *inputs*. It's a perfectly
> > reasonable way to check data which "should" be valid, as well as a way
> > to document what variables are supposed to contain.
> 
> Where are those variables coming from?
> 
> The distinction really boils down to this:
> 
> * asserts should never fail. If there is any chance that an assertion 
> might fail outside of test suites, then don't use assert.
> 

I'm no expert, but the more I read this thread, and the more I think on
it, the more I believe that asserts don't really need to exist outside
of test suites.  The function that assertions provide is handled in a
far more robust and maintainable way by unit tests and doctests.
Anything else should be handled by more descriptive exceptions.  

The use of assertions in regular code may just be a historical baby step
on the way to real code testing.

To play devils advocate for a moment, one possible use case for assert
statements is if you need to test something that you can't easily get
under a proper unittest or doctest.  Maybe you need to know the value of
a variable halfway through a method.  A judicious assertion can help
supplement your test suite  A better solution would be to refactor so
you can get the needed value under test, but if time constraints won't
allow it, then make your assertion and move on, but only to help you
debug the code, not to protect your code at runtime.  Even then, why not
use a proper Exception (unless speed is a major issue)?

Even if it is only used internally in a module, I would still prefer a
ValueError to an AssertionError.  It tells you what's happening more
clearly.  And it protects you if another caller (even one internal to
the class) calls it with a different set of assumptions.

At minimum, I think there's a heavy burden on an author to justify the
use of AssertionErrors rather than other kinds of Exceptions. 

Cheers,
Cliff

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


Re: tkinter problem

2009-07-10 Thread Paul Simon

"David Smith"  wrote in message 
news:h35f78$pt...@ruby.cit.cornell.edu...
> Paul Simon wrote:
>> "Peter Otten" <__pete...@web.de> wrote in message
>> news:h3481q$d95$0...@news.t-online.com...
>>> Paul Simon wrote:
>>>
 "Chris Rebert"  wrote in message
 news:mailman.2863.1247095339.8015.python-l...@python.org...
 On Wed, Jul 8, 2009 at 4:18 PM, Paul Simon wrote:
> I have the "tkinter" problem and need some assistance to straighten it
> out.
> >From the web page "http://wiki.python.org/moin/TkInter"; I tested as 
> >in
>> "step
> 1" and cannot import "_tkinter." I do not have that file on my 
> computer,
> but
> do have tkinter.py in /usr/local/lib/python2.6/lib-tk. as well as the
> directories /usr/lib/tk8.5 and /usr/lib/tcl8.5.
> This python stuff is great, but the documentation frequently
> feels like it is just a bit out of my grasp. I realize that all of 
> this
> is free but I understand the instructions on the web page to repair 
> only
> to the
> point of confusion. I'm not an expert. How do I modify my python
> configuration? Is there a file that needs to be edited? Which setup.py
> file
> do I use? Make? or python setup.py build and python setup.py install?
> Thanks. I appreciate your help.
 - How did you install Python?
 - What Linux distro are you using?

 Cheers,
 Chris
 http://blog.rebertia.com
 I"m using Mandriva 2008.1.  I have to tell you honestly that I'm not 
 sure
 exactly how I installed Python.  Originally I had installed 2.5 from 
 RPM
 but 2.6 was not available for my distro (2008.1) in RPM.  I downloaded
 something from python.org and installed.  Not sure if it was tarball or
 zip file.
>>> Zip or tar doesn't matter, you are installing "from source".
>>>
>>> Python has to find the necessary include files for tcl/tk. These are in
>>> separate packages that you have to install before you invoke Python's
>>> configure script.
>>>
>>> I don't know what they are called on your system -- look for tk-dev.rpm,
>>> tcl-dev.rpm or similar.
>>>
>>> You may run into the same problem with other modules like readline.
>>>
>>> Peter
>>>
>>
>> Thank you Peter.  I understand what you are saying but don't know how to 
>> do
>> it.  Although I installed from source, I followed a "cookbook" recipe.
>> Could you tell me what files to execute, where they might be, and file
>> arguments?  I'm just ignorant, not stupid. ;-).
>>
>> Paul
>>
>>
>
> Just install the tkinter package from the Mandriva Linux Control
> Center's Software Management system.  I just did it, doing a search for
> tkinter brought it right up.  All done.
>
> --David

Thanks to all for your patient help.  I have made some progress, but still 
no success.  I installed Active Tcl-8.5.7 and corrected the PATH 
accordingly.  However I still get a "missing" message on building Python. 
"Failed to find the necessary bits (!) to build these modules:


_tkinter (among others)
To find the necessary bits, look in setup.py in detect_modules() for teh 
module's name."

Not sure what bits are, euphemism?  but am about to wipe the disk and 
reinstall linux, etc.

Paul 


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


Re: Where does setuptools live?

2009-07-10 Thread Inky 788
On Jul 10, 10:26 am, Chris Withers  wrote:
> Inky 788 wrote:
> > Currently, distutils itself is being actively developed. More info
> > about this here:http://tarekziade.wordpress.com/
>
> > My (albeit anonymous) advice is: use distutils. Manually download
> > packages as-needed from PyPI and install manually using standard
> > distutils.
>
> No thanks. I'm a big fan of buildout. Making it possible for packages to
> specify their dependencies is a big win...

Yup, it's a big win. But package installation for Python is a bit of a
mess right now. Neither setuptools nor buildout (nor pip for that
matter) are a standard part of Python. It's rather silly that although
Python is a batteries-included language, and it's mid-2009, and Python
3.1 has been released, that Python *still* doesn't have a standard
built-in way to handle package installation (including dependencies
and uninstallation).

My guess is that once distutils finishes getting spruced up, some
intrepid hacker is going to:

* take the best parts of pip and the best parts of setuptools (I don't
know anything about buildout),

* stir vigorously,

* ruthlessly remove the excess pieces,

* write good documentation for it,

* throw the result up on github/launchpad/bitbucket/whatever,

and then *that's* what everyone's going to start using and which will
eventually make it into the Python std lib.

But that's just my anon 2 cents.
-- 
http://mail.python.org/mailman/listinfo/python-list


problem with subprocess

2009-07-10 Thread gabrielmonnerat

Hi all,

I need start a openoffice in Xvfb, but when I call with the DISPLAY 
occurs this error:


[r...@localhost oood]# Xvfb :99 -screen 0 1024x768x24 &

In [9]: subprocess.call('/opt/ooo-dev3/program/soffice.bin')
Out[9]: 0

In [10]: subprocess.call('DISPLAY=:99 /opt/ooo-dev3/program/soffice.bin')
---
OSError   Traceback (most recent call last)

/home/gabriel/ in ()

/usr/lib/python2.6/subprocess.pyc in call(*popenargs, **kwargs)
   442 retcode = call(["ls", "-l"])
   443 """
--> 444 return Popen(*popenargs, **kwargs).wait()
   445
   446

/usr/lib/python2.6/subprocess.pyc in __init__(self, args, bufsize, 
executable, stdin, stdout, stderr, preexec_fn, close_fds, shell, cwd, 
env, universal_newlines, startupinfo, creationflags)

   593 p2cread, p2cwrite,
   594 c2pread, c2pwrite,
--> 595 errread, errwrite)
   596
   597 # On Windows, you cannot just redirect one or two 
handles: You



/usr/lib/python2.6/subprocess.pyc in _execute_child(self, args, 
executable, preexec_fn, close_fds, cwd, env, universal_newlines, 
startupinfo, creationflags, shell, p2cread, p2cwrite, c2pread, c2pwrite, 
errread, errwrite)

  1104 os.waitpid(self.pid, 0)
  1105 child_exception = pickle.loads(data)
-> 1106 raise child_exception
  1107
  1108

OSError: [Errno 2] No such file or directory

I am using subprocess because I need store the pid. Any suggestions?

thanks in advance,

Gabriel M. Monnerat

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


BayPIGgies at OSCON: 7/23 8-9:30pm

2009-07-10 Thread Aahz
NOTE: time change AND location change

The July BayPIGgies meeting will be held at OSCON in the San Jose
Convention Center as one of the BoF (Birds of a Feather) sessions from
8pm to 9:30pm Thursday July 23.  Everyone is welcome: you do NOT need to
be an OSCON member to attend a BoF.

Wesley Chun will have a newbie-oriented "What is Python?" BoF from 7-8pm
in the same room as BayPIGgies (we don't know which room yet).

The July meeting is supposed to have a Django focus, but the program
hasn't been settled yet, either.

For more information, see
http://baypiggies.net/

Discussion of details will take place on the BayPIGgies list:
http://mail.python.org/mailman/listinfo/baypiggies
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Clarity vs. code reuse/generality

2009-07-10 Thread Charles Yeomans


On Jul 9, 2009, at 10:57 PM, Steven D'Aprano wrote:


On Fri, 10 Jul 2009 03:28:04 +0100, Nobody wrote:


On Thu, 09 Jul 2009 04:57:15 -0300, Gabriel Genellina wrote:


Nobody says you shouldn't check your data. Only that "assert" is not
the right way to do that.


"assert" is not the right way to check your *inputs*. It's a  
perfectly
reasonable way to check data which "should" be valid, as well as a  
way

to document what variables are supposed to contain.


Where are those variables coming from?

The distinction really boils down to this:

* asserts should never fail. If there is any chance that an assertion
might fail outside of test suites, then don't use assert.


You can't control what input the caller provides to a function, so  
unless

the data is generated inside the function, a caller might provide
something unexpected. Therefore, assert is inappropriate for checking
function parameters, even if that function is "private" and only  
called

by your own functions.

(1) So-called "private" or "internal" functions have a habit of  
becoming

public, and then you have asserts in public functions.

(2) If public() calls _private(x), and _private uses assert to check  
the

value of x, there is a risk that if public() is buggy and supplies an
invalid x, the assertion will never be checked and _private() will  
return

incorrect results.

(3) assert is absolutely unsuitable for enforcing pre-conditions and  
post-
conditions, unless such conditions are mere "guidelines", because  
assert

can be switched off at runtime.



Unless, of course, you want to switch off such checking at runtime, as  
you might when using a design-by-contract approach.


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


Re: tough-to-explain Python

2009-07-10 Thread pdpi
On Jul 10, 2:11 pm, Steven D'Aprano  wrote:
> On Fri, 10 Jul 2009 12:54:21 +0200, Hendrik van Rooyen wrote:
> > "Steven D'Aprano"  wrote:
>
> >>On Wed, 08 Jul 2009 22:05:57 -0700, Simon Forman wrote:
>
>  persistent idea "out there" that programming is a very accessible
>  skill, like cooking or gardening, anyone can do it, and even profit
>  from it, monetarily or otherwise, etc., and to some extent I am
>
> >>> Programming is not like any other human activity.
>
> >>In practice? In principle? Programming in principle is not the same as
> >>it is performed in practice.
>
> >>But in either case, programming requires both the logical reasoning of
> >>mathematics and the creativity of the arts. Funnily enough,
>
> > I do not buy this arty creativity stuff. - or are you talking about
> > making a website look pretty?
>
> I must admit, it never crossed my mind that anyone here would claim that
> there was no creativity involved in programming, that it was all a
> mindless, algorithmic process capable of being done by a simple
> mechanical device.
>
> This is certainly the accusation made against *bad* programmers -- that
> they can't actually solve new, unique problems, but just apply recipes
> they learned without any insight or intelligence. The sort of people who
> program so poorly that "a trained monkey could do what they do".

I wholeheartedly agree. Coming up with Duff's device is nothing if not
creative. My mind still reels at trying to grok it.
http://www.lysator.liu.se/c/duffs-device.html

> Even *soup stock* fits the same profile as what Hendrik claims is almost
> unique to programming. On its own, soup stock is totally useless. But you
> make it, now, so you can you feed it into something else later on.
>
> Or instant coffee.

I've always found cooking an apt metaphor for programming.

You've got your well-limited for loops (cook for x minutes), your less
straightforward while/until loops (roast until golden), you have your
subprocedures (prepare sauce in advance/in parallel), you have some
conditionals (tenderize the steak if the meat isn't really that
tender), etc etc.

The complexities of assignment can be easily visualized in terms of
containers and mixing stuff together. Nothing makes a += b more
obvious than having a bowl of cream (a), an egg (b), and adding the
egg to the bowl of cream (a += b). Well, except for the part where
that in that case evaluating b is destructive ;)

> They can't reason? Then what are they doing when they manipulate symbols?

"Computers aren't intelligent. They only think they are." Or, more to
the point: the typical definition of "reasoning" tends to involve more
of what defines humans as self-aware, animate beings than what is
usually ascribed to computers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help me to find the error

2009-07-10 Thread Steven D'Aprano
On Fri, 10 Jul 2009 11:57:21 -0400, Dave Angel wrote:

[...]
> Please don' t top-post.  Putting your reply out of order makes it harder
> for others to see the sequences of things.  Some people top-post
> everything, but on this mailing list (and maybe most), the standard is
> to add to bottom, or inline where appropriate.

Inline is nearly always appropriate. Please trim your replies, leaving 
only what you need for context and what you are replying to directly, not 
the entire every-growing collection of quoted-quoted-quoted-quoted-quotes.

Thank you.


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


Re: Remoting over SSH

2009-07-10 Thread M.-A. Lemburg
Lucas Carvalho wrote:
> Hussein B wrote:
>> Hey,
>> I want to perform commands on a remote server over SSH.
>> What do I need?
>> Thanks.
>>   
> Hi,
> If you want to use the SSH2 protocol into a python code, you should
> take a look at this module: paramiko [1].
> 
> [1] http://www.lag.net/paramiko/

If you're looking for remote Python execution over SSH have
a look at http://codespeak.net/py/dist/execnet.html

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jul 10 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: DBI module deprecated at Python 2.5--what to use in its place?

2009-07-10 Thread M.-A. Lemburg
dana wrote:
> I have a variety of Python 2.4 scripts that utilitize the DBI and ODBC
> modules together. Although I don't have Python 2.5, I've been informed
> the DBI module has been deprecated at 2.5. A few questions:
> 
> 1) Although deprecated, will it work at all in 2.5? Does the fact that
> it is deprecrated mean it has been removed entirely, or does Python
> 2.5 simply issuing a warning?
> 
> 2) What do I use in place of DBI for my Python 2.4. scripts that
> import modules DBI and ODBC together. I don't use DBI directly. It was
> simply a dependency for the ODBC module as best I knew.

If you're looking for a stable and maintained ODBC for Python,
have a look at our mxODBC extension or mxODBC Connect package:

http://www.egenix.com/products/python/mxODBC/
http://www.egenix.com/products/python/mxODBCConnect/

-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Jul 10 2009)
>>> Python/Zope Consulting and Support ...http://www.egenix.com/
>>> mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/


::: Try our new mxODBC.Connect Python Database Interface for free ! 


   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: problem with keys combination!

2009-07-10 Thread Steven D'Aprano
On Fri, 10 Jul 2009 08:33:18 -0700, Alex wrote:

> Hi at all,
>   I made a simple program that make a screenshot of Desktop and use it
> as fullscreen background and then a ball erase image making illusion
> that erase Desktop. The program working fine and I succesfully blocked
> all keys but I have a problem with hotkey combination Ctrl-Alt-
> Del...that bypass my FullScreen Application.


What operating system are you using? Windows?

As I understand it, you can't block, modify, or otherwise access Ctrl-Alt-
Del while running under Windows: it is the "Secure Attention Key", and is 
designed to be virtually impossible to interfere with. It's not *quite* 
impossible, but it is the deepest, darkest black magic. Microsoft makes 
it close enough to impossible as makes no difference even for experienced 
developers.

As a newbie, well, put it this way: it's like somebody saying "Hi guys, I 
have a shiny new Swiss Army Knife, the one with the screwdriver and the 
corkscrew. I'd like to build my own Space Shuttle -- what do I do?"

http://stackoverflow.com/questions/886076/how-can-i-intercept-all-key-events-including-ctrlaltdel-and-ctrltab

http://en.wikipedia.org/wiki/Control-Alt-Delete

You should also read this:

http://blogs.msdn.com/oldnewthing/archive/2004/02/16/73780.aspx



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


Automate rsync w/ authentication

2009-07-10 Thread Bryan
I am trying to automate rsync to backup server A from server B.  I
have set up a private/public key between the two servers so I don't
have to enter a password when using rsync.  Running rsync manually
with the following command works fine:
rsync -av --dry-run -e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"
r...@10.0.45.67:/home/bry/jquery.lookup /home/bry/tmp

But when I try to do it with python, the subprocess simply returns the
ssh -h output on stderr like I am passing some invalid syntax.  What
is wrong in my translation of rsync's -e command from shell to
pythyon?

#! /usr/bin/python
from subprocess import Popen, PIPE
rsyncExec = '/usr/bin/ssh'
source = 'r...@10.0.45.67:/home/bry/jquery.lookup'
dest = '/home/bry/tmp'
rshArg = '-e "/usr/bin/ssh -i /home/bry/keys/brybackup.key"'
args = [rsyncExec, '-a', '-v', '--dry-run', rshArg, source, dest]
try:
p = Popen(args, stdout=PIPE, stderr=PIPE)
print 'rsync running with pid %s' % p.pid
out, err = p.communicate()
print 'Errors: %s' % err
print 'Output: %s' % out
except Exception:
print 'Error running rsync'

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


Re: tough-to-explain Python

2009-07-10 Thread D'Arcy J.M. Cain
On 10 Jul 2009 15:48:47 GMT
Steven D'Aprano  wrote:
> I meant the instant coffee powder is prepared in advance. It's useless on 
> it's own, but later on you feed it into boiling water, add sugar and 
> milk, and it's slightly less useless.

I don't know about that.  I find instant coffee pretty useless no
matter what it is fed to.  :-)

-- 
D'Arcy J.M. Cain  |  Democracy is three wolves
http://www.druid.net/darcy/|  and a sheep voting on
+1 416 425 1212 (DoD#0082)(eNTP)   |  what's for dinner.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: help me to find the error

2009-07-10 Thread Dave Angel

jhinak sen wrote:

hey,
thanx a lot :)
i got ur points .. and it really helps..

and please also tell me ...
where i can get more basic and detail knowledge of python.. as i am
beginners in this , i need more examples  of python programmes so that i can
understand better.
also if you know of any gud pdf file or book please let me know

thnx a lot
jhinak

On Fri, Jul 10, 2009 at 7:25 PM, Dave Angel  wrote:

  

jhinak sen wrote:



hi,
i am a beginner in python language,

i am trying with this programme :
to find the addition and mean from a data set in a file and writing the
mean
and sum in some other file :
""
*#! /usr/bin/env python

import re
import cPickle as p
import math
from numpy import *

f0= open("temp9","r+").readlines()
f2= open("out1","r+")
add_1=[ ];
for i in range(0, len(f0)):
   f1=f0[i].split()
   add= float(f1[1])+float(f1[2])
   mean= float(add)/2
   print (f1[1]).ljust(6) ,(f1[2]).ljust(6),repr(add).ljust(7),
repr(mean).ljust(7)
   add_1.append(add)
   add_1.append(mean)
   f2.write("%s" % repr(add).ljust(7)),f2.write("%s" %
repr(mean).ljust(7))
print "printing from file"
for i in range(0, len(add_1),2):
   print add_1[i],"", add_1[i+1]

f0.close()
f2.close()*


""

and this programme is givving me this error :

""*Traceback (most recent call last):
 File "./temporary1.py", line 24, in 
   f0.close()
AttributeError: 'list' object has no attribute 'close'*
""

please help to to find the error.
or suggest some simpler or better way

note:
1)file "temp9" is already exist
2)this programme is giving me all my outputs, but at the end of the out
..its giving me that error.



  

Others have pointed out the specific problem that gives you this error.
 But I'd like to point out a few other things to consider:

1) Don't mix tabs and spaces.  Best practice is to bind tab to (4) spaces
in your editor, and never have a tab in a Python source file.
2) Think about your variable names.  As it stands, f0 is a list of lines,
f1 is a list of "word" within a line, and f2 is a file.  No wonder you
accidentally tried to close the list.  I'd suggest things like:
infile = open()
lines = infile.readlines()
outfile = open()

for line in lines:
   words = line.split(" ") or  even   val1, val2 =
lines.split(" ")

 Then of course the last two lines become
 infile.close()
 outfile.close()

3) Learn to use the for statement directly on a list, rather than using
len() on the list to make an index, then using the index to find the value
4) On the open() calls, get your modes right.  Looks like you really want
 infile = open(infilename, "r")
 outfile = open(outfilename, "w")
5) Consider using tuples in your add_1 list, rather than separate elements.
 That way, each element of the list would contain both sum and mean.
 add_1.append((add, mean))

 and the final print would become

  for item in add_1:
  print item[0],"", item[1]

6) Put anything over three lines into a function, instead of doing it at
module scope.  That way, you'll be clearer about what things are local to
this code, and what might be useful to other code in the same module.
In this case,  infilename, and outfilename might be arguments to that
function.

There are lots of other refinements, but these are all within your reach,
and would make the program much clearer.





  
Please don' t top-post.  Putting your reply out of order makes it harder 
for others to see the sequences of things.  Some people top-post 
everything, but on this mailing list (and maybe most), the standard is 
to add to bottom, or inline where appropriate.


Anyway,
http://docs.python.org/tutorial/
http://diveintopython.org/
http://www.openbookproject.net/thinkCSpy/

are all good, depending on your experience with other languages, and 
with your computer's OS.


You could also check out
http://code.activestate.com/recipes/ or
http://code.activestate.com/recipes/langs/python/  for Python specifically


which has a large set of relatively small modules of code.
For a examples that might stretch your thought process:
   http://code.activestate.com/recipes/576755/
   http://code.activestate.com/recipes/576647/


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


Re: tough-to-explain Python

2009-07-10 Thread Steven D'Aprano
On Fri, 10 Jul 2009 08:28:29 -0700, Scott David Daniels wrote:

> Steven D'Aprano wrote:
>> Even *soup stock* fits the same profile as what Hendrik claims is
>> almost unique to programming. On its own, soup stock is totally
>> useless. But you make it, now, so you can you feed it into something
>> else later on.
>> 
>> Or instant coffee.
> 
> I think I'll avoid coming to your house for a cup of coffee. :-)


I meant the instant coffee powder is prepared in advance. It's useless on 
it's own, but later on you feed it into boiling water, add sugar and 
milk, and it's slightly less useless.



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


Threading.Condition problem

2009-07-10 Thread Gabriel Rossetti
Sorry if this appears twice, I sent it once with an attachment and it 
never arrived so maybe the attachment is posing problems. I inlined the 
code this time (at the bottom), thank you,


Gabriel

## Original message 

Hello everyone,

I wrote a small example that listens for xmpp msgs in a thread. The main
program calls a function that blocks (using Condition.wait) until a msg
has been received and then returns the msg. When a msg arrives, it is
put in a variable in the thread's object, it then calls the notify()
attr on the Condition object. For some reason, this doesn't work, the
thread gets the msg, tries to notify the Condition object, fails because
the lock has not been acquired yet and blocks. I tried ignoring the
failure, thinking that since it has not been acquired yet then when it
is, it will get the msg right away and never call Condition.wait, thus
not causing any problems, but this does not work either. Does someone
know what I am doing wrong? I attached the code to this msg.

Thank you,
Gabriel



 Example code 

from __future__ import with_statement
import xmpp, sys
from threading import Thread, Condition, Event


class Listener(Thread):
def __init__(self, ws):
Thread.__init__(self)
self.interrupt = Event()
self.message = None
self._cv = ws._cv
self.client = ws._client
self.client.RegisterHandler('message', self.onMessage)

def onMessage(self, conn, msg):
self.message = msg
try:
self._cv.notify()
except RuntimeError:
print "self._cv has not acquired the lock yet"

def getMsg(self):
return self.message

def run(self):
try:
while(not self.interrupt.isSet()):
self.client.Process(1)
except KeyboardInterrupt:
return 0

class WS(object):
def __init__(self, username, password, res):
self._jid = xmpp.protocol.JID(username)
self._client = xmpp.Client(self._jid.getDomain())
self._cv = Condition()

if(self._client.connect(server=("localhost", 5222)) == ""):
raise Exception("Error while connecting!")

if(self._client.auth(self._jid.getNode(), password, res) is None):
raise Exception("Authentication failed!")

self._client.sendInitPresence()

self._listener = Listener(self)
self._listener.start()

def getMsg(self, mid=None):
"""
"""
with self._cv:
res = self._listener.getMsg()
while not res:
self._cv.wait()
res = self._listener.getMsg()
return res

if(__name__ == "__main__"):
ws = WS("t...@localhost", "123", "test")
res = ws.getMsg()
print "I just received : %s" % str(res)
sys.exit(0)


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


Re: Threading.Condition problem

2009-07-10 Thread Gabriel Rossetti
The previous msg w/ attached code is the wrong code, please use the code 
attached to this msg, thank you and sorry for this.


Gabriel


Gabriel Rossetti wrote:

Hello everyone,

I wrote a small example that listens for xmpp msgs in a thread. The 
main program calls a function that blocks (using Condition.wait) until 
a msg has been received and then returns the msg. When a msg arrives, 
it is put in a variable in the thread's object, it then calls the 
notify() attr on the Condition object. For some reason, this doesn't 
work, the thread gets the msg, tries to notify the Condition object, 
fails because the lock has not been acquired yet and blocks. I tried 
ignoring the failure, thinking that since it has not been acquired yet 
then when it is, it will get the msg right away and never call 
Condition.wait, thus not causing any problems, but this does not work 
either. Does someone know what I am doing wrong? I attached the code 
to this msg.


Thank you,
Gabriel
from __future__ import with_statement
import xmpp, sys
from threading import Thread, Condition, Event


class Listener(Thread):
def __init__(self, ws):
Thread.__init__(self)
self.interrupt = Event()
self.message = None
self._cv = ws._cv
self.client = ws._client
self.client.RegisterHandler('message', self.onMessage)

def onMessage(self, conn, msg):
self.message = msg
try:
self._cv.notify()
except RuntimeError:
print "self._cv has not acquired the lock yet"

def getMsg(self):
return self.message

def run(self):
try:
while(not self.interrupt.isSet()):
self.client.Process(1)
except KeyboardInterrupt:
return 0

class WS(object):
def __init__(self, username, password, res):
self._jid = xmpp.protocol.JID(username)
self._client = xmpp.Client(self._jid.getDomain())
self._cv = Condition()

if(self._client.connect(server=("localhost", 5222)) == ""):
raise Exception("Error while connecting!")

if(self._client.auth(self._jid.getNode(), password, res) is None):
raise Exception("Authentication failed!")

self._client.sendInitPresence()

self._listener = Listener(self)
self._listener.start()

def getMsg(self, mid=None):
"""
"""
with self._cv:
res = self._listener.getMsg()
while not res:
self._cv.wait()
res = self._listener.getMsg()
return res

if(__name__ == "__main__"):
ws = WS("t...@localhost", "123", "test")
res = ws.getMsg()
print "I just received : %s" % str(res)
sys.exit(0)
-- 
http://mail.python.org/mailman/listinfo/python-list


Threading.Condition problem

2009-07-10 Thread Gabriel Rossetti

Hello everyone,

I wrote a small example that listens for xmpp msgs in a thread. The main 
program calls a function that blocks (using Condition.wait) until a msg 
has been received and then returns the msg. When a msg arrives, it is 
put in a variable in the thread's object, it then calls the notify() 
attr on the Condition object. For some reason, this doesn't work, the 
thread gets the msg, tries to notify the Condition object, fails because 
the lock has not been acquired yet and blocks. I tried ignoring the 
failure, thinking that since it has not been acquired yet then when it 
is, it will get the msg right away and never call Condition.wait, thus 
not causing any problems, but this does not work either. Does someone 
know what I am doing wrong? I attached the code to this msg.


Thank you,
Gabriel
# Copyright (c) 2001-2006 Twisted Matrix Laboratories.
# See LICENSE for details.

import sys
from twisted.internet import reactor
from twisted.names.srvconnect import SRVConnector
from twisted.words.xish import domish, xpath
from twisted.words.protocols.jabber import xmlstream, client, jid

PRESENCE = '/presence' # this is an global xpath query to use in an observer
MESSAGE = '/message'   # message xpath
IQ = '/iq' # iq xpath

class XMPPClientConnector(SRVConnector):
def __init__(self, reactor, domain, factory):
SRVConnector.__init__(self, reactor, 'xmpp-client', domain, factory)


def pickServer(self):
host, port = SRVConnector.pickServer(self)

if not self.servers and not self.orderedServers:
# no SRV record, fall back..
port = 5222

return host, port



class Client(object):

def __init__(self, client_jid, secret, dest=None):
"""
"""
self.dest = dest
f = client.XMPPClientFactory(client_jid, secret)
f.addBootstrap(xmlstream.STREAM_CONNECTED_EVENT, self.connected)
f.addBootstrap(xmlstream.STREAM_END_EVENT, self.disconnected)
f.addBootstrap(xmlstream.STREAM_AUTHD_EVENT, self.authenticated)
f.addBootstrap(xmlstream.INIT_FAILED_EVENT, self.init_failed)
connector = XMPPClientConnector(reactor, client_jid.host, f)
connector.connect()

def rawDataIn(self, buf):
print "RECV: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace')

def rawDataOut(self, buf):
print "SEND: %s" % unicode(buf, 'utf-8').encode('ascii', 'replace')

def connected(self, xs):
"""
"""
print 'Connected.'

self.xmlstream = xs

# Log all traffic
xs.rawDataInFn = self.rawDataIn
xs.rawDataOutFn = self.rawDataOut


def disconnected(self, xs):
"""
"""
print 'Disconnected.'
try:
reactor.stop()
except:
pass

def authenticated(self, xs):
"""
"""
def sendPresence():
presence = domish.Element((None, 'presence'))
xs.send(presence)

def sendMsg(user, res=None):
msg = domish.Element(("jabber:client", "message"))
msg["to"] = "%...@localhost%s" % (user, "/" + res if res else "")
body = msg.addElement("body", content = "Hello world %s" % res if res else "")
subject = msg.addElement("subject", content = "will this be displayed?")
thread = msg.addElement("thread", content = "this shouldn't be displayed")
xs.send(msg)


print "Authenticated."

xs.addObserver(PRESENCE, self.onPresence, 1)
#xs.addObserver(IQ, self.onIq, 1)
xs.addObserver(MESSAGE, self.onMessage, 1)

reactor.callLater(0, sendPresence)

if(self.dest):
reactor.callLater(2, sendMsg, self.dest, "toto")
reactor.callLater(4, sendMsg, self.dest, "titi")

#msg = domish.Element(("jabber:client", "message"))
#msg["to"] = "grosse...@localhost"
#body = msg.addElement("body", content = "Hello world")
#subject = msg.addElement("subject", content = "will this be displayed?")
#thread = msg.addElement("thread", content = "this shouldn't be displayed")
#xs.send(msg)

#msg = domish.Element(("jabber:client", "iq"))
#msg["to"] = "ser...@localhost"
#msg["id"] = "666"
#xs.send(msg)

#msg = domish.Element(("jabber:client", "presence"))
#msg["to"] = "grosse...@localhost"
#msg["type"] = "subscribe"
#xs.send(msg)

#reactor.callLater(5, xs.sendFooter)

def onMessage(self, msg):
"""
Act on the message stanza that has just been received.
"""
# return to sender
#msg = create_reply(msg)
#self.xmlstream.send(msg) # send the modified domish.Element
pass

#def onIq(self, iq):
#"""
#Act on the iq stanza that has just been received.

#"""
#iq = create_reply(iq)
#self.xmlstream.send(iq)

def onPresence(

problem with keys combination!

2009-07-10 Thread Alex
Hi at all,
  I made a simple program that make a screenshot of Desktop and use it
as fullscreen background and then a ball erase image making illusion
that erase Desktop. The program working fine and I succesfully blocked
all keys but I have a problem with hotkey combination Ctrl-Alt-
Del...that bypass my FullScreen Application. Reading in google I
understood that if I want disable this keys I have to operate in more
low level. But I'm a newbe and I don't know how to make it(operate
with api is very hard 4 me).I tried several days to find a workaround
like replace one of that keys but doesn't work :-((
Plus..I can't install pyHook because there isn't a 2.6 version :-((
Can someone help me ??
thanks in advance
Alex

This is a piece of my code:
while True:
pg.event.pump()
keyinput = pg.key.get_pressed()
# press ESC to exit
if keyinput[pg.K_ESCAPE]
raise SystemExit
if  keyinput[pygame.K_LALT] and keyinput[pygame.K_LCTRL] and
keyinput[pygame.K_DELETE]:
 win32api.keybd_event(win32con.VK_ESCAPE,0)
 #shell = win32com.client.Dispatch("WScript.Shell")
#shell.SendKeys("{ESC}")
#ignore keyboard input
def IgnoreKeyboardInterrupt():
return signal.signal(signal.SIGINT,signal.SIG_IGN)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: language analysis to enforce code standards

2009-07-10 Thread Aahz
In article ,
Jean-Michel Pichavant   wrote:
>
>You could also verify there are at least N different characters used in 
>the sentence:
>
>N = 5 # must contains at least 5 different characters
>record = []
>for c in s:
>if c not in record:
>record += [c]
>if len(record) >= N:
>print "at least %s different characters" % N

Much simpler and *way* more efficient with a set:

if len(set(s)) < N:
print "Must have at least %s different characters" % N
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: AP -- MeAmI.org Paces Google

2009-07-10 Thread Fran�ois Grondin

"David Bernier"  a écrit dans le message de news: 
h36ki102...@news5.newsguy.com...
> Musatov wrote:
>> On Jul 9, 7:54 pm, David Bernier  wrote:
>>> Musatov wrote:
 Los Angeles (AP) --MeAmI.org now has users in 50 countries following
 its adopted use in Pakistan.  The search engine has grown in
 popularity 10,000 fold following its Beta test launch three months ago
 in April, 2009. Supporters of the site claim it is better than rival
 Google upon which platform it is based. Controversy arose after
 MeAmI.org search code allowed users to search other users Google
 results with no advertising. "It is truly an innovative thing we are
 doing," said Founder and CEO, Martin Musatov. "Letting users search
 the results of other Google users immediately results in a level of
 accuracy and relevance above and beyond Google." Google changed their
 API following the launch or MeAmI.org and explored the possibility of
 blocking site access from MeAmI.org to Google search results but was
 unable to do so. Critics of MeAmI.org say what it is doing is
 tantamount to intellectual theft. When asked about this topper Musatov
 exclaimed, "The Internet was made for people, not companies." An
 analyst at Goldman Sachs says, requesting to remain anonymous,
 "MeAmI.org has a strong presence in promoting itself as a vehicle for
 global activism and to tell you the truth, this makes it much more
 likely an acquisition target than potential intellectual property
 violator." Google could not be reached for comment.
>>> Mr. Musatov,  do you know who originally wrote the
>>> article above?
>>>
>>> Thank you.
>>>
>>> David Bernier- Hide quoted text -
>>>
>>> - Show quoted text -
>>
>> Yes.
>
> Mr. Musatov, do you know the name of the person who
> originally wrote the article above?
>
> Thank you.
>
> David Bernier

Maybe Mr. Musatov should answer the following questions instead :
1. Did you write the article above?
2. If not, who did? And I don't want AP as the answer, but the name of the 
journalist.

David, don't take it bad, but he answered your question with an accurate 
answer (yes), You gave him the opportunity to avoid the real answer and he 
took it. Based on Musatov's strange behavior and logic, don't expect more 
from him. Ask anyone else the same question and you'd get a real answer.

BTW, my guess for question 2 would be the Masked Logician, Floetry, 
scriber77, or Professor X.

Francois 


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


Re: PyGtk Depends on Numeric

2009-07-10 Thread Aahz
In article <1ebe9314-9434-459a-bd3e-2b2386a35...@n11g2000yqb.googlegroups.com>,
dieter   wrote:
>
>Get with the times people and port to numpy. :P
>Don't you think its about time?

Are you trying to get something to happen or just posting a random
drive-by?
-- 
Aahz (a...@pythoncraft.com)   <*> http://www.pythoncraft.com/

"as long as we like the same operating system, things are cool." --piranha
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Query regarding set([])?

2009-07-10 Thread Peter Otten
vox wrote:

> On Jul 10, 4:17 pm, Dave Angel  wrote:
>> vox wrote:
>> > On Jul 10, 2:04 pm, Peter Otten <__pete...@web.de> wrote:
>>
>> >> You are probably misinterpreting len(s3). s3 contains lines occuring
>> >> in "file1" but not in "file2". Duplicate lines are only counted once,
>> >> and the order doesn't matter.
>>
>> >> So there are 119 lines that occur at least once in "file2", but not in
>> >> "file1".
>>
>> >> If that is not what you want you have to tell us what exactly you are
>> >> looking for.
>>
>> >> Peter
>>
>> > Hi,
>> > Thanks for the answer.
>>
>> > I am looking for a script that compares file1 and file2, for each line
>> > in file1, check if line is present in file2. If the line from file1 is
>> > not present in file2, print that line/write it to file3, because I
>> > have to know what lines to add to file2.
>>
>> > BR,
>> > Andy
>>
>> There's no more detail in that response.  To the level of detail you
>> provide, the program works perfectly.  Just loop through the set and
>> write the members to the file.
>>
>> But you have some unspecified assumptions:
>> 1) order doesn't matter
>> 2) duplicates are impossible in the input file, or at least not
>> meaningful.  So the correct output file could very well be smaller than
>> either of the input files.
>>
>> And a few others that might matter:
>> 3) the two files are both text files, with identical line endings
>> matching your OS default
>> 4) the two files are ASCII, or at least 8 bit encoded, using the
>> same encoding  (such as both UTF-8)
>> 5) the last line of each file DOES have a trailing newline sequence
> 
> Thanks all for the input!
> I have guess I have to think it through a couple times more. :)

Indeed. Note that others thinking through related problems have come up with

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

Peter

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


Re: Clarity vs. code reuse/generality

2009-07-10 Thread Tim Rowe
2009/7/9 kj :

> Thanks for the encouragement.

[snip]

> into code.  And by this I mean not only assumptions about the
> correctness of their code (the typical scope of assertions), but
> also, more broadly, assumptions about the data that they are dealing
> with (which often comes from external sources with abysmal quality
> control).

There we diverge. A lot. If "correctness of the code trumps everything
else" (in fact, if it matters at all) and the external data has
"abysmal quality control" then it *must* be checked for correctness
before it is used. If it is not, you have no idea whether your output
is correct or not. And assertions *will* *not* reliably provide that
checking (because they may not be executed). You *must* actively check
the data, using good old-fasioned "if" statements and so on, because
not to do so is to declare that you *don't* care about correctness.
You *know* the input is often wrong, but you're not bothering to check
it?

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


Re: Query regarding set([])?

2009-07-10 Thread vox
On Jul 10, 4:17 pm, Dave Angel  wrote:
> vox wrote:
> > On Jul 10, 2:04 pm, Peter Otten <__pete...@web.de> wrote:
>
> >> You are probably misinterpreting len(s3). s3 contains lines occuring in
> >> "file1" but not in "file2". Duplicate lines are only counted once, and the
> >> order doesn't matter.
>
> >> So there are 119 lines that occur at least once in "file2", but not in
> >> "file1".
>
> >> If that is not what you want you have to tell us what exactly you are
> >> looking for.
>
> >> Peter
>
> > Hi,
> > Thanks for the answer.
>
> > I am looking for a script that compares file1 and file2, for each line
> > in file1, check if line is present in file2. If the line from file1 is
> > not present in file2, print that line/write it to file3, because I
> > have to know what lines to add to file2.
>
> > BR,
> > Andy
>
> There's no more detail in that response.  To the level of detail you
> provide, the program works perfectly.  Just loop through the set and
> write the members to the file.
>
> But you have some unspecified assumptions:
>     1) order doesn't matter
>     2) duplicates are impossible in the input file, or at least not
> meaningful.  So the correct output file could very well be smaller than
> either of the input files.
>
> And a few others that might matter:
>     3) the two files are both text files, with identical line endings
> matching your OS default
>     4) the two files are ASCII, or at least 8 bit encoded, using the
> same encoding  (such as both UTF-8)
>     5) the last line of each file DOES have a trailing newline sequence

Thanks all for the input!
I have guess I have to think it through a couple times more. :)

BR,
Andy
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Where does setuptools live?

2009-07-10 Thread Chris Withers

Inky 788 wrote:

Currently, distutils itself is being actively developed. More info
about this here: http://tarekziade.wordpress.com/

My (albeit anonymous) advice is: use distutils. Manually download
packages as-needed from PyPI and install manually using standard
distutils.


No thanks. I'm a big fan of buildout. Making it possible for packages to 
specify their dependencies is a big win...


Chris

--
Simplistix - Content Management, Zope & Python Consulting
   - http://www.simplistix.co.uk
--
http://mail.python.org/mailman/listinfo/python-list


Re: Implementing a cache

2009-07-10 Thread Steven D'Aprano
On Fri, 10 Jul 2009 09:22:29 -0400, Nikolaus Rath wrote:

> Hello,
> 
> I want to implement a caching data structure in Python that allows me
> to:
> 
>  1. Quickly look up objects using a key 2. Keep track of the order in
>  which the objects are accessed (most
> recently and least recently accessed one, not a complete history)
>  3. Quickly retrieve and remove the least recently accessed object.

Google for "python LRU cache".

Here are the first three hits:

http://code.activestate.com/recipes/498245/
http://code.activestate.com/recipes/252524/
http://www.algorithm.co.il/blogs/index.php/programming/python/small-python-challenge-no-2-lru-cache/




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


Re: Query regarding set([])?

2009-07-10 Thread Dave Angel

vox wrote:

On Jul 10, 2:04 pm, Peter Otten <__pete...@web.de> wrote:
  

You are probably misinterpreting len(s3). s3 contains lines occuring in
"file1" but not in "file2". Duplicate lines are only counted once, and the
order doesn't matter.

So there are 119 lines that occur at least once in "file2", but not in
"file1".

If that is not what you want you have to tell us what exactly you are
looking for.

Peter



Hi,
Thanks for the answer.

I am looking for a script that compares file1 and file2, for each line
in file1, check if line is present in file2. If the line from file1 is
not present in file2, print that line/write it to file3, because I
have to know what lines to add to file2.

BR,
Andy


  
There's no more detail in that response.  To the level of detail you 
provide, the program works perfectly.  Just loop through the set and 
write the members to the file.


But you have some unspecified assumptions:
   1) order doesn't matter
   2) duplicates are impossible in the input file, or at least not 
meaningful.  So the correct output file could very well be smaller than 
either of the input files.


And a few others that might matter:
   3) the two files are both text files, with identical line endings 
matching your OS default
   4) the two files are ASCII, or at least 8 bit encoded, using the 
same encoding  (such as both UTF-8)

   5) the last line of each file DOES have a trailing newline sequence



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


  1   2   >