Recommend blogs for me to follow

2011-12-22 Thread Yaşar Arabacı
Hi,

I am looking for some recommendations about blogs that I may like to
follow. I am interested in Python (that goes without saying), django and
server side web development in general, linux tools, and git scm. I am
looking for blogs which shares short examples of codes, and hints about
various topics that I might be interested with. My favorite blog so far is
http://www.saltycrane.com/blog/ as it gives quick tips aboug various topics
that I am interested in. So can you suggest other blogs like that? I am
considering this thread to become a reference point for people like me who
wants to extent their knowledge about Python and world of programming in
general by reading fellow programmers.

-- 
http://yasar.serveblog.net/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idiom for shelling out to $EDITOR/$PAGER?

2011-12-22 Thread Devin Jeanpierre
> Anyway, look it up; it has an autodelete mode etc.

The autodelete isn't useful in this context. The file needs to be
closed and then reopened again; with the autodelete option, the
closing would delete the file, preventing it from being opened by the
text editor or reopened to check contents.

(As far as I know, the race condition inherent in this is unavoidable.
At least on windows, but I couldn't figure out any other way on Linux
either.)

-- Devin

On Fri, Dec 23, 2011 at 1:02 AM, Cameron Simpson  wrote:
> On 22Dec2011 22:16, Tim Chase  wrote:
> | After a little searching, I've not been able to come up with what
> | I'd consider canonical examples of consider calling an external
> | editor/pager on a file and reading the results back in.  (most of my
> | results are swamped by people asking about editors written in
> | Python, or what the best editors for Python code are)
> |
> | The pseudocode would be something like
> |
> |   def edit_text(data):
> |     temp_fname = generate_temp_name()
> |     try:
> |       f = file(temp_fname, 'w')
> |       f.write(data)
> |       f.close()
> |       before = info(temp_fname) # maybe stat+checksum?
> |       editor = find_sensible_editor()
> |       subprocess.call([editor, temp_fname])
> |       if before == info(temp_fname):
> |         return None
> |       else:
> |         return file(temp_fname).read()
> |     finally:
> |       delete_if_exists(temp_fname)
> |
> | However there are things to watch out for in this lousy code:
> |
> | -race conditions, unique naming, and permissions on the temp file
>
> NamedTemporaryFile is your friend.
>
> | -proper & efficient detection of file-change, to know whether the
> | user actually did anything
>
> Wait for the editor to exit?
> In that scenario I go for:
>  - wait for edit to exit
>  - if exit status 0 and file non-empty, trust it
>    (subject to parse issues afterwards of course)
>
> | -cross-platform determination of a sensible editor (that blocks
> | rather than spawns), using platform conventions like
> | os.environ['EDITOR']
>
> os.environment.get('EDITOR', 'vi')?
>
> Some platforms have an executable called "editor" that solves that
> problem (absent $EDITOR); MacOSX has "open", though it won't be running
> a blocking editor, alas.
>
> You may need some knowledge of the local system. On a terminal? Easy,
> use $EDITOR. No terminal, but $DISPLAY? xterm -e "$EDITOR temp_file",
> or the like. No terminal, no $DISPLAY, macosx? I have an incantation
> somewhere...
>
> | -cleanup deletion of the temp-file
>
> NamedTemporaryFile is your friend.
>
> | I presume the code for spawning $PAGER on some content would look
> | pretty similar.
>
> Yep.
>
> | Any good example code (or blog posts, or other links) that has been
> | battle-tested?
>
> Hmm. Nothing directly to had, but regarding the temp file:
>
>  # write contents of the file `fp` into a temp file
>  with NamedTemporaryFile('w', dir=os.path.join(self.dir, 'tmp')) as T:
>    T.write(fp.read())
>  ... do stuff with T.name (the temp file name).
>
> Anyway, look it up; it has an autodelete mode etc.
>
> Cheers,
> --
> Cameron Simpson  DoD#743
> http://www.cskk.ezoshosting.com/cs/
>
> I have always been a welly man myself. They are superb in wet grass, let
> alone lagoons of pig shit.      - Julian Macassey
> --
> http://mail.python.org/mailman/listinfo/python-list
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idiom for shelling out to $EDITOR/$PAGER?

2011-12-22 Thread Cameron Simpson
On 23Dec2011 17:12, Ben Finney  wrote:
| Cameron Simpson  writes:
| > On 22Dec2011 22:16, Tim Chase  wrote:
| > | -proper & efficient detection of file-change, to know whether the
| > | user actually did anything
| >
| > Wait for the editor to exit?
| > In that scenario I go for:
| >   - wait for edit to exit
| >   - if exit status 0 and file non-empty, trust it
| > (subject to parse issues afterwards of course)
| 
| That doesn't address the concern Tim raised: did the user actually do
| anything, did the file change?

I'm not sure it matters. It's _quicker_ to do nothing if the file is
unchanged, but is it bad to act on it anyway?

| The exit status of text editors are not bound to distinguish “buffer was
| modified”, and certainly don't do so in any standard way.

Indeed not; my 0 above is just "did you user exit the editor or did it
crash"?

| My advice:
| * Compute a before-edit hash of the text (MD5 or SHA-1 would be fine).
| * Invoke the editor on that text.
| * Wait for (or detect) the exit of the editor process.
| * Compute an after-edit hash of the text resulting from the editor.
| * Compare the hashes to see whether the text changed.

Sure. But still, if you're able to act on a changed file, why not also
act on an unchanged file? The user asked to change things; take what you
got back and proceed!

And personally, as a user, I've often rewritten an unchanged file to
force a recompute of something.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

"Don't you know the speed limit is 55 miles per hour???"
"Yeah, but I wasn't going to be out that long."
- Steven Wright
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idiom for shelling out to $EDITOR/$PAGER?

2011-12-22 Thread Ben Finney
Cameron Simpson  writes:

> On 22Dec2011 22:16, Tim Chase  wrote:
> | -proper & efficient detection of file-change, to know whether the
> | user actually did anything
>
> Wait for the editor to exit?
> In that scenario I go for:
>   - wait for edit to exit
>   - if exit status 0 and file non-empty, trust it
> (subject to parse issues afterwards of course)

That doesn't address the concern Tim raised: did the user actually do
anything, did the file change?

The exit status of text editors are not bound to distinguish “buffer was
modified”, and certainly don't do so in any standard way.

My advice:

* Compute a before-edit hash of the text (MD5 or SHA-1 would be fine).

* Invoke the editor on that text.

* Wait for (or detect) the exit of the editor process.

* Compute an after-edit hash of the text resulting from the editor.

* Compare the hashes to see whether the text changed.

-- 
 \   “Come on Milhouse, there's no such thing as a soul! It's just |
  `\  something they made up to scare kids, like the Boogie Man or |
_o__)  Michael Jackson.” —Bart, _The Simpsons_ |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread alex23
On Dec 23, 3:22 pm, Ian Kelly  wrote:
> Nobody is asking you to modify your coding style.  The request is that
> you not throw it up as an example without mentioning the important
> caveats.

No, 100% no. It's not my responsibility to mention every potentially
relevant gotcha when providing example code.

> Also, novice programmer == bad programmer?

If they're wholly learning how to code by throwaway examples on
mailing lists, then yes. Object mutability is a _major_ aspect of
Python; I'm simply not going to inject an essay explaining what that
implies every time I choose to use a mutable default argument.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Idiom for shelling out to $EDITOR/$PAGER?

2011-12-22 Thread Cameron Simpson
On 22Dec2011 22:16, Tim Chase  wrote:
| After a little searching, I've not been able to come up with what
| I'd consider canonical examples of consider calling an external
| editor/pager on a file and reading the results back in.  (most of my
| results are swamped by people asking about editors written in
| Python, or what the best editors for Python code are)
| 
| The pseudocode would be something like
| 
|   def edit_text(data):
| temp_fname = generate_temp_name()
| try:
|   f = file(temp_fname, 'w')
|   f.write(data)
|   f.close()
|   before = info(temp_fname) # maybe stat+checksum?
|   editor = find_sensible_editor()
|   subprocess.call([editor, temp_fname])
|   if before == info(temp_fname):
| return None
|   else:
| return file(temp_fname).read()
| finally:
|   delete_if_exists(temp_fname)
| 
| However there are things to watch out for in this lousy code:
| 
| -race conditions, unique naming, and permissions on the temp file

NamedTemporaryFile is your friend.

| -proper & efficient detection of file-change, to know whether the
| user actually did anything

Wait for the editor to exit?
In that scenario I go for:
  - wait for edit to exit
  - if exit status 0 and file non-empty, trust it
(subject to parse issues afterwards of course)

| -cross-platform determination of a sensible editor (that blocks
| rather than spawns), using platform conventions like
| os.environ['EDITOR']

os.environment.get('EDITOR', 'vi')?

Some platforms have an executable called "editor" that solves that
problem (absent $EDITOR); MacOSX has "open", though it won't be running
a blocking editor, alas.

You may need some knowledge of the local system. On a terminal? Easy,
use $EDITOR. No terminal, but $DISPLAY? xterm -e "$EDITOR temp_file",
or the like. No terminal, no $DISPLAY, macosx? I have an incantation
somewhere...

| -cleanup deletion of the temp-file

NamedTemporaryFile is your friend.

| I presume the code for spawning $PAGER on some content would look
| pretty similar.

Yep.

| Any good example code (or blog posts, or other links) that has been
| battle-tested?

Hmm. Nothing directly to had, but regarding the temp file:

  # write contents of the file `fp` into a temp file
  with NamedTemporaryFile('w', dir=os.path.join(self.dir, 'tmp')) as T:
T.write(fp.read())
  ... do stuff with T.name (the temp file name).

Anyway, look it up; it has an autodelete mode etc.

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

I have always been a welly man myself. They are superb in wet grass, let
alone lagoons of pig shit.  - Julian Macassey
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread Ian Kelly
On Thu, Dec 22, 2011 at 8:40 PM, alex23  wrote:
> On Dec 23, 12:59 pm, Ian Kelly  wrote:
>> It's only irrelevant in the immediate context of the code you posted.
>> But when Joe Novice sees your code and likes it and duplicates it a
>> million times
>
> I'm sorry, but I'm not going to modify my coding style for the sake of
> bad programmers.

Nobody is asking you to modify your coding style.  The request is that
you not throw it up as an example without mentioning the important
caveats.

Also, novice programmer == bad programmer?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread Eric
On Dec 21, 5:44 pm, Steven D'Aprano  wrote:

> Yes, you should create your lists before trying to append to them.
>
> But you aren't forced to use a for-loop. You can use a list comprehension:
>
> x = [some_function(a) for a in range(n)]
>
> Notice that here you don't need x to pre-exist, because the list comp
> creates a brand new list, which then gets assigned directly to x.
>
> > Now to my actual question.  I need to do the above for multiple arrays
> > (all the same, arbitrary size).  So I do this:
> >    x=y=z=[]
>
> This creates one empty list object, and gives it three names, x, y and z.
> Every time you append to the list, all three names see the same change,
> because they refer to a single list.
>
> [...]
>
> > Except it seems that I didn't create three different arrays, I created
> > one array that goes by three different names (i.e. x[], y[] and z[] all
> > reference the same pile of numbers, no idea which pile).
>
> Exactly.
>
> > This surprises me, can someone tell me why it shouldn't?
>
> Because that's the way Python works. Python is an object-oriented, name
> binding language. This is how OO name binding works: you have a single
> object, with three names bound to it. The above line is short-cut for:
>
> a = []
> b = a
> c = a
>
> Python does not make a copy of the list unless you specifically instruct
> it to.
>
> > I figure if I
> > want to create and initialize three scalars the just do "a=b=c=7",
>
> That creates a single integer object with value 7, and binds three names
> to it, *exactly* the same as the above.
>
> If you could modify int objects in place, like you can modify lists in
> place, you would see precisely the same effect. But ints are immutable:
> all operations on ints create new ints. Lists are mutable, and can be
> changed in place.
>
> > for
> > example, so why not extend it to arrays.  Also, is there a more pythonic
> > way to do "x=[], y=[], z=[]"?
>
> Well that literally won't work, you can't separate them by commas.
> Newlines or semicolons will work.
>
> Or: x, y, z = [], [], []
>
> Either is pretty Pythonic.
>
> --
> Steven

Thanks to you and Dennis for the quick lesson and tips.  Very helpful
and illuminating.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread Chris Angelico
On Fri, Dec 23, 2011 at 2:40 PM, alex23  wrote:
> I'm sorry, but I'm not going to modify my coding style for the sake of
> bad programmers.

And there, folks, you have one of the eternal dilemmas. The correct
decision depends on myriad factors; if you're writing code to go into
the documentation as an example, you want it to be able to handle
idiots hacking on it - but on the other hand, that same situation
demands simplicity, which is why a lot of examples omit huge slabs of
error checking.

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


Idiom for shelling out to $EDITOR/$PAGER?

2011-12-22 Thread Tim Chase
After a little searching, I've not been able to come up with what 
I'd consider canonical examples of consider calling an external 
editor/pager on a file and reading the results back in.  (most of 
my results are swamped by people asking about editors written in 
Python, or what the best editors for Python code are)


The pseudocode would be something like

  def edit_text(data):
temp_fname = generate_temp_name()
try:
  f = file(temp_fname, 'w')
  f.write(data)
  f.close()
  before = info(temp_fname) # maybe stat+checksum?
  editor = find_sensible_editor()
  subprocess.call([editor, temp_fname])
  if before == info(temp_fname):
return None
  else:
return file(temp_fname).read()
finally:
  delete_if_exists(temp_fname)

However there are things to watch out for in this lousy code:

-race conditions, unique naming, and permissions on the temp file

-proper & efficient detection of file-change, to know whether the 
user actually did anything


-cross-platform determination of a sensible editor (that blocks 
rather than spawns), using platform conventions like 
os.environ['EDITOR']


-cleanup deletion of the temp-file

I presume the code for spawning $PAGER on some content would look 
pretty similar.


Any good example code (or blog posts, or other links) that has 
been battle-tested?


Thanks,

-tkc







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


Re: what does 'a=b=c=[]' do

2011-12-22 Thread alex23
On Dec 23, 12:59 pm, Ian Kelly  wrote:
> It's only irrelevant in the immediate context of the code you posted.
> But when Joe Novice sees your code and likes it and duplicates it a
> million times

I'm sorry, but I'm not going to modify my coding style for the sake of
bad programmers.

The context is _important_. Why should I guard against default
argument mutability when its not going to occur in the function body?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread Eric
On Dec 21, 6:50 pm, alex23  wrote:
> On Dec 22, 8:25 am, Eric  wrote:
>
> > This surprises me, can someone tell me why it shouldn't?  I figure if
> > I want to create and initialize three scalars the just do "a=b=c=7",
> > for example, so why not extend it to arrays.
>
> The thing to remember is that everything is an object, and that it's
> better to think of variables as labels on an object.
>
> So: a=b=c=7 means that _one_ integer object with the value of 7 can be
> referenced using any of the labels a, b or c. x=y=z=[] means that
> _one_ empty list can be referenced using x, y or z.
>
> The difference is that the value of a number object _cannot be
> changed_ ('immutable') while a list can be modified to add or remove
> items ('mutable'). a=10 just reassigns the label a to an integer
> object of value 10. x.append("foo") _modifies_ the list referred to by
> x, which is the same list known as y & z.
>


> > Also, is there a more pythonic way to do "x=[], y=[], z=[]"?
>
> I'd say that _is_ the most pythonic way, it's very obvious in its
> intent (or would be with appropriate names). If it bothers you that
> much:
>

Thanks for the explanation.  I guess from what I've seen of Python
so far I was expecting something more, I don't know, compact.
Anyway, it doesn't bother me, at least not enough to go and do
something like this:

>     def listgen(count, default=[]):
>         for _ in xrange(count):
>             yield default[:]
>
>     x, y, z = listgen(3)

Thanks,
eric


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


Re: Python education survey

2011-12-22 Thread rusi
On Dec 21, 9:57 pm, Nathan Rice 
wrote:
> +1 for IPython/%edit using the simplest editor that supports syntax
> highlighting and line numbers.  I have found that
> Exploring/Prototyping in the interpreter has the highest ROI of
> anything I teach people.
>
> Nathan

It seems to me that we are not distinguishing different 'scales'.
For example:
In principle one can use any unit to measure length. In practice it is
inconvenient to use kilometers when microns or angstroms are more
appropriate.

Clearly there is a need, when learning a language, to explore the
basics with a minimum of interference from the environment ie
introspection features of python with as little extra interference as
possible.

As a teacher I generally demonstrate with python-mode in emacs. I
guess IDLE, ipython etc should be equivalent.  But then someone in the
class comes with a 'question' of this sort:

We have this project in eclipse+python.
But the path is not being searched properly.
etc

Now for me eclipse is more of pizazz on the outside and nightmare on
the inside. [Or maybe its just that I am particularly bad at solving
these kinds of problems]. Nevertheless this scale or granularity of
work is also important in python education and is sorely
underrepresented.

Here are some of my earlier attempts to canvass for this orientation:

http://mail.python.org/pipermail/python-list/2011-May/1271749.html

http://mail.python.org/pipermail/python-list/2011-November/1283634.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread Ian Kelly
On Thu, Dec 22, 2011 at 7:10 PM, alex23  wrote:
> On Dec 22, 6:51 pm, Rolf Camps  wrote:
>> I'm afraid it's dangerous to encourage the use of '[]' as assignment to
>> a parameter in a function definition. If you use the function several
>> times 'default' always points to the same list.
>
> I appreciate the concern, but adding a default argument guard would
> not only obscure the code. It's irrelevant, as you recognise, because
> no matter what, it's going to make copies of the default argument.

It's only irrelevant in the immediate context of the code you posted.
But when Joe Novice sees your code and likes it and duplicates it a
million times without receiving any warning about it, he's eventually
going to write a function that modifies its default list argument, and
he'll be in for a nasty surprise when he does.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: what does 'a=b=c=[]' do

2011-12-22 Thread alex23
On Dec 22, 6:51 pm, Rolf Camps  wrote:
> I'm afraid it's dangerous to encourage the use of '[]' as assignment to
> a parameter in a function definition. If you use the function several
> times 'default' always points to the same list.

I appreciate the concern, but adding a default argument guard would
not only obscure the code. It's irrelevant, as you recognise, because
no matter what, it's going to make copies of the default argument.

You know what the say about foolish consistencies :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: reading multiline output

2011-12-22 Thread MRAB

On 23/12/2011 02:05, Mac Smith wrote:


On 23-Dec-2011, at 6:48 AM, MRAB wrote:


 On 23/12/2011 01:07, Mac Smith wrote:


 On 23-Dec-2011, at 6:17 AM, MRAB wrote:


 On 23/12/2011 00:33, Mac Smith wrote:

 Hi,


 I have started HandBrakeCLI using subprocess.popen but the output
 is multiline and not terminated with \n so i am not able to read
 it using readline() while the HandBrakeCLI is running. kindly
 suggest some alternative. i have attached the output in a file.


 The lines are terminated with \r, so read with read() and then
 split on "\r".


 read() will read the complete output and than i will be able to parse
 it, i want to read the output of the command in realtime.


 Try telling it how much to read with read(size):

 def read_lines(output, line_ending="\n"):
buffer = ""

while True:
chunk = output.read(1024)
if not chunk:
break

buffer += chunk

while True:
pos = buffer.find(line_ending)
if pos<  0:
break

pos += len(line_ending)
yield buffer[ : pos]
buffer = buffer[pos : ]

if buffer:
yield buffer


thanks, this helped. just need to correct line_ending="\n" should be 
line_ending="\r"


I wrote the default as "\n" because that's the normal line ending in
Python.

If, as in your case, the line ending is different, just pass the
appropriate string as the second argument.
--
http://mail.python.org/mailman/listinfo/python-list


Re: reading multiline output

2011-12-22 Thread Mac Smith

On 23-Dec-2011, at 6:48 AM, MRAB wrote:

> On 23/12/2011 01:07, Mac Smith wrote:
>> 
>> On 23-Dec-2011, at 6:17 AM, MRAB wrote:
>> 
>>> On 23/12/2011 00:33, Mac Smith wrote:
 Hi,
 
 
 I have started HandBrakeCLI using subprocess.popen but the output
 is multiline and not terminated with \n so i am not able to read
 it using readline() while the HandBrakeCLI is running. kindly
 suggest some alternative. i have attached the output in a file.
 
>>> The lines are terminated with \r, so read with read() and then
>>> split on "\r".
>> 
>> read() will read the complete output and than i will be able to parse
>> it, i want to read the output of the command in realtime.
>> 
> Try telling it how much to read with read(size):
> 
> def read_lines(output, line_ending="\n"):
>buffer = ""
> 
>while True:
>chunk = output.read(1024)
>if not chunk:
>break
> 
>buffer += chunk
> 
>while True:
>pos = buffer.find(line_ending)
>if pos < 0:
>break
> 
>pos += len(line_ending)
>yield buffer[ : pos]
>buffer = buffer[pos : ]
> 
>if buffer:
>yield buffer
> -- 
> http://mail.python.org/mailman/listinfo/python-list

thanks, this helped. just need to correct line_ending="\n" should be 
line_ending="\r"

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


Re: reading multiline output

2011-12-22 Thread Cameron Simpson
On 23Dec2011 06:37, Mac Smith  wrote:
| On 23-Dec-2011, at 6:17 AM, MRAB wrote:
| > On 23/12/2011 00:33, Mac Smith wrote:
| >> I have started HandBrakeCLI using subprocess.popen but the output is
| >> multiline and not terminated with \n so i am not able to read it
| >> using readline() while the HandBrakeCLI is running. kindly suggest
| >> some alternative. i have attached the output in a file.
| >> 
| > The lines are terminated with \r, so read with read() and then split on
| > "\r".
| 
| read() will read the complete output and than i will be able to parse
| it, i want to read the output of the command in realtime.

You can read a limited number of bytes - for your purposes this needs to
be 1 byte at a time. Very inefficient, but you can do what you need.
Write a little function that gathers single bytes until "\r" and then
returns them joined into a string.

Traditionally the way to work with "interactive" facilities like this is
often the "expect" command, and I gather there's a third party Python
module named "pexpect" with that functionality. This:
  http://www.noah.org/wiki/pexpect

And then there's all sorts of read-with-timeout games you can play I
guess...

Note that all this relies on HandBrakeCLI emitting its progress messages
in a timely (== unbuffered) manner when its output is a pipe...

Cheers,
-- 
Cameron Simpson  DoD#743
http://www.cskk.ezoshosting.com/cs/

It's better to be DoD and cool, than to get a life and be uncool!
- _Harley Davidson & The Marlboro Man_
  (slightly paraphrased by Roar Larsen, DoD#463
   )
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Grammar for classes

2011-12-22 Thread Ian Kelly
On Thu, Dec 22, 2011 at 4:39 PM, Terry Reedy  wrote:
> Beats me. The 2.7 doc says inheritance ::=  "(" [expression_list] ")" and I
> no on no 3.x change/addition.

Well, there is one change in 3.x which is that the inheritance list
now accepts keyword parameters (PEP 3115) -- the "metaclass" keyword
specifies the metaclass instead of using a bogus __metaclass__
attribute, and any other keywords are passed along to the metaclass.
That's why the parsing of the inheritance list was generalized to look
more like a function call, but it doesn't explain why the class
declaration might wish to receive a comprehension.

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


Re: reading multiline output

2011-12-22 Thread MRAB

On 23/12/2011 01:07, Mac Smith wrote:


On 23-Dec-2011, at 6:17 AM, MRAB wrote:


On 23/12/2011 00:33, Mac Smith wrote:

Hi,


I have started HandBrakeCLI using subprocess.popen but the output
is multiline and not terminated with \n so i am not able to read
it using readline() while the HandBrakeCLI is running. kindly
suggest some alternative. i have attached the output in a file.


The lines are terminated with \r, so read with read() and then
split on "\r".


read() will read the complete output and than i will be able to parse
it, i want to read the output of the command in realtime.


Try telling it how much to read with read(size):

def read_lines(output, line_ending="\n"):
buffer = ""

while True:
chunk = output.read(1024)
if not chunk:
break

buffer += chunk

while True:
pos = buffer.find(line_ending)
if pos < 0:
break

pos += len(line_ending)
yield buffer[ : pos]
buffer = buffer[pos : ]

if buffer:
yield buffer
--
http://mail.python.org/mailman/listinfo/python-list


Re: reading multiline output

2011-12-22 Thread Mac Smith

On 23-Dec-2011, at 6:17 AM, MRAB wrote:

> On 23/12/2011 00:33, Mac Smith wrote:
>> Hi,
>> 
>> 
>> I have started HandBrakeCLI using subprocess.popen but the output is
>> multiline and not terminated with \n so i am not able to read it
>> using readline() while the HandBrakeCLI is running. kindly suggest
>> some alternative. i have attached the output in a file.
>> 
> The lines are terminated with \r, so read with read() and then split on
> "\r".

read() will read the complete output and than i will be able to parse it, i 
want to read the output of the command in realtime.

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


Re: reading multiline output

2011-12-22 Thread MRAB

On 23/12/2011 00:33, Mac Smith wrote:

Hi,


I have started HandBrakeCLI using subprocess.popen but the output is
multiline and not terminated with \n so i am not able to read it
using readline() while the HandBrakeCLI is running. kindly suggest
some alternative. i have attached the output in a file.


The lines are terminated with \r, so read with read() and then split on
"\r".
--
http://mail.python.org/mailman/listinfo/python-list


reading multiline output

2011-12-22 Thread Mac Smith
Hi,


I have started HandBrakeCLI using subprocess.popen but the output is multiline 
and not terminated with \n so i am not able to read it using readline() while 
the HandBrakeCLI is running. kindly suggest some alternative. i have attached 
the output in a file.



output
Description: Binary data



--
Thanks

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


Re: Grammar for classes

2011-12-22 Thread Terry Reedy

On 12/20/2011 12:05 PM, Joshua Landau wrote:

On 20 December 2011 10:55, Robert Kern mailto:robert.k...@gmail.com>> wrote:

On 12/20/11 1:34 AM, Joshua Landau wrote:

In reading thorough the syntax defined in the reference

>,

the class statement has surprised me.

It says that the inheritance part of the class can accept
comprehensions. What
does this mean?


Beats me. The 2.7 doc says inheritance ::=  "(" [expression_list] ")" 
and I no on no 3.x change/addition. My experiments with both genexp and 
listcomp versions gave errors.



I ignore valid code. Thanks Ian and Robert for the input. Should I file
a documentation bug report?


Please do. It the addition means something, it needs to be explained in 
the text. If it is wrong, it should go.


--
Terry Jan Reedy

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


Re: Spanish Accents

2011-12-22 Thread Stan Iverson
On Thu, Dec 22, 2011 at 2:17 PM, Peter Otten <__pete...@web.de> wrote:

> You are now one step further, you have successfully* decoded the file.
> The remaining step is to encode the resulting unicode lines back into
> bytes.
> The encoding implicitly used by the print statement is sys.stdout.encoding
> which is either "ascii" or None in your case. Try to encode explicitly to
> UTF-8 with
>
> f = codecs.open(p + "2.txt", "r", "iso-8859-1")
> for line in f:
>print line.encode("utf-8")
>
>
> OOEEE! Thanks!
Stan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Adding an interface to existing classes

2011-12-22 Thread Terry Reedy

On 12/22/2011 3:21 AM, Spencer Pearson wrote:

I'm writing a geometry package, with Points and Lines and Circles and
so on, and eventually I want to be able to draw these things on the
screen. I have two options so far for how to accomplish this, but
neither of them sits quite right with me, and I'd like the opinion of
comp.lang.python's wizened elders.

Option 1. Subclassing.
The most Pythonic way would seem to be writing subclasses for the
things I want to display, adding a ".draw(...)" method to each one,
like this:



Option 2. A "draw" function, with a function dictionary.


Option 3? Add a draw method to existing classes, rather than subclassing?

--
Terry Jan Reedy

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


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Ben Finney
Saqib Ali  writes:

> BTW Here is the traceback:
>
> >>> import myClass
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "myClass.py", line 6, in 
> @Singleton
> TypeError: 'module' object is not callable

Yes. When you ‘import foo’, you have a module bound to the name ‘foo’. A
module is not callable.

> Here is Singleton.py:

You should name the file ‘singleton.py’ instead; modules should be named
in all lower-case, as PEP 8 recommends.

> Here is myClass.py:

Which should be named ‘my_class.py’, instead, by the same rationale.

Neither of those is necessary, but it will help dispel the confusion
you're experiencing, and help your code be more easily comprehensible to
other Python programmers.

> #!/usr/bin/env python
> import os, sys, string, time, re, subprocess
> import Singleton

So, you should (after the renames suggested) do either::

import singleton

@singleton.Singleton
class my_class:

or::

from singleton import Singleton

@Singleton
class my_class:

Notice how naming the module in lower-case makes it more easily
distinguishable from the class name.

More generally, remember that Python is not Java
http://dirtsimple.org/2004/12/python-is-not-java.html>, and you
should be grouping your classes into logically coherent files, not
one-file-per-class.

-- 
 \ “Reality must take precedence over public relations, for nature |
  `\   cannot be fooled.” —Richard P. Feynman, _Rogers' Commission |
_o__)   Report into the Challenger Crash_, 1986-06 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Marc Christiansen
Saqib Ali  wrote:
> I'm using this decorator to implement singleton class in python:
> 
> http://stackoverflow.com/posts/7346105/revisions
> 
> The strategy described above works if and only if the Singleton is
> declared and defined in the same file. If it is defined in a different
> file and I import that file, it doesn't work.
> 
> Why can't I import this Singleton decorator from a different file?

Maybe you're doing something wrong. But since you didn't provide any
code, it's impossible to tell what.

> What's the best work around?

As far as I can tell with the information you have given, none is
needed. See below:

0:> python2.7 singleton_test.py # works also with python3.2
Foo created
True
 
#singleton_test.py
from singleton import Singleton
# Singleton is the class from Paul Manta from the SO page
# and singleton.py contains nothing else

@Singleton
class Foo:
def __init__(self):
print('Foo created')

f = Foo.Instance()
g = Foo.Instance()

print(f is g)

Grüße
Marc
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Ethan Furman

Saqib Ali wrote:


I'm using this decorator to implement singleton class in python:

http://stackoverflow.com/posts/7346105/revisions

The strategy described above works if and only if the Singleton is
declared and defined in the same file. If it is defined in a different
file and I import that file, it doesn't work.

Why can't I import this Singleton decorator from a different file?
What's the best work around?


Post the code, and the traceback.

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


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Saqib Ali
Thanks for pointing out the mistake!
Works.
- Saqib




On Thu, Dec 22, 2011 at 4:31 PM, Ethan Furman  wrote:

> Saqib Ali wrote:
>
>> MYCLASS.PY:
>>
>> #!/usr/bin/env python
>> import os, sys, string, time, re, subprocess
>> import Singleton
>>
>
> This should be 'from Singleton import Singleton'
>
>
>
>  @Singleton
>> class myClass:
>>def __init__(self):
>>print 'Constructing myClass'
>>
>
> At this point, the *instance* of myClass has already been constructed and
> it is now being initialized.  The __new__ method is where the instance is
> actually created.
>
>
>
>>def __del__(self):
>>print 'Destructing myClass'
>>
>>
>>  > class Singleton:
> >
> > def __init__(self, decorated):
> > self._decorated = decorated
> >
> > def Instance(self):
> > try:
> > return self._instance
> > except AttributeError:
> > self._instance = self._decorated()
> > return self._instance
> >
> > def __call__(self):
> > raise TypeError(
> > 'Singletons must be accessed through the `Instance`
> > method.')
>
>
> ~Ethan~
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Ethan Furman

Saqib Ali wrote:

MYCLASS.PY:

#!/usr/bin/env python
import os, sys, string, time, re, subprocess
import Singleton


This should be 'from Singleton import Singleton'



@Singleton
class myClass:

def __init__(self):

print 'Constructing myClass'


At this point, the *instance* of myClass has already been constructed 
and it is now being initialized.  The __new__ method is where the 
instance is actually created.




def __del__(self):
print 'Destructing myClass'



> class Singleton:
>
> def __init__(self, decorated):
> self._decorated = decorated
>
> def Instance(self):
> try:
> return self._instance
> except AttributeError:
> self._instance = self._decorated()
> return self._instance
>
> def __call__(self):
> raise TypeError(
> 'Singletons must be accessed through the `Instance`
> method.')


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


Re: Elementwise -//- first release -//- Element-wise (vectorized) function, method and operator support for iterables in python.

2011-12-22 Thread Joshua Landau
On 22 December 2011 11:15, Robert Kern  wrote:

> On 12/21/11 6:52 PM, Joshua Landau wrote:
>
>  If fix means "return number" then no. This inconsistency between
>> elementwise
>> operations and 'normal' ones is the problem. Again, explicit
>> elementwise-ifying
>> through "~" fixes that. You need to tell me why this is worth the
>> confusion over
>> that.
>>
>
> I understand that you are a supporter of PEP 225, but please have some
> courtesy towards other developers. We can explore alternatives in parallel.
> If we all worked on exactly the same thing (much less the one thing that
> only you get to choose), we would forgo a lot of valuable experience. You
> can point out the flaws of Elementwise's implementation and compare it to
> the virtues of PEP 225 without being so demanding. He doesn't "need to
> tell" you a damn thing.


OK. Sorry. I had a feeling my language was a bit blunt.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Andrew Berg
You have the same code for both files...
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Chris Kaynor
On Thu, Dec 22, 2011 at 1:11 PM, Saqib Ali  wrote:

> MYCLASS.PY:
>
> #!/usr/bin/env python
> import os, sys, string, time, re, subprocess
> import Singleton
>

This imports the module Singleton, not the class or function.

There are two options to deal with this:

from Singleton import Singleton

imports the name Singleton from the module Singleton, which will be what
you are probably expecting. If you wish to keep the namespace, you can also
change your call from @Singleton to @Singleton.Singleton


>
> @Singleton
> class myClass:
>
> def __init__(self):
> print 'Constructing myClass'
>
> def __del__(self):
> print 'Destructing myClass'
>
>
> SINGLETON.PY:
>
>
> #!/usr/bin/env python
> import os, sys, string, time, re, subprocess
> import Singleton
>
>
> @Singleton
> class myClass:
>
> def __init__(self):
> print 'Constructing myClass'
>
> def __del__(self):
> print 'Destructing myClass'
>
> TRACEBACK:
>
> >>> import myClass
> Traceback (most recent call last):
>   File "", line 1, in 
>   File "myClass.py", line 6, in 
> @Singleton
> TypeError: 'module' object is not callable
>
>
>
> - Saqib
>
>
>
>
>
>>>
>> Post the code, and the traceback.
>>
>> ~Ethan~
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Saqib Ali
BTW Here is the traceback:

>>> import myClass
Traceback (most recent call last):
  File "", line 1, in 
  File "myClass.py", line 6, in 
@Singleton
TypeError: 'module' object is not callable



Here is Singleton.py:



class Singleton:

def __init__(self, decorated):
self._decorated = decorated

def Instance(self):
try:
return self._instance
except AttributeError:
self._instance = self._decorated()
return self._instance

def __call__(self):
raise TypeError(
'Singletons must be accessed through the `Instance`
method.')



Here is myClass.py:

#!/usr/bin/env python
import os, sys, string, time, re, subprocess
import Singleton


@Singleton
class myClass:

def __init__(self):
print 'Constructing myClass'

def __del__(self):
print 'Destructing myClass'
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Saqib Ali
MYCLASS.PY:

#!/usr/bin/env python
import os, sys, string, time, re, subprocess
import Singleton


@Singleton
class myClass:

def __init__(self):
print 'Constructing myClass'

def __del__(self):
print 'Destructing myClass'


SINGLETON.PY:


#!/usr/bin/env python
import os, sys, string, time, re, subprocess
import Singleton


@Singleton
class myClass:

def __init__(self):
print 'Constructing myClass'

def __del__(self):
print 'Destructing myClass'

TRACEBACK:

>>> import myClass
Traceback (most recent call last):
  File "", line 1, in 
  File "myClass.py", line 6, in 
@Singleton
TypeError: 'module' object is not callable



- Saqib





>>
> Post the code, and the traceback.
>
> ~Ethan~
-- 
http://mail.python.org/mailman/listinfo/python-list


Can't I define a decorator in a separate file and import it?

2011-12-22 Thread Saqib Ali


I'm using this decorator to implement singleton class in python:

http://stackoverflow.com/posts/7346105/revisions

The strategy described above works if and only if the Singleton is
declared and defined in the same file. If it is defined in a different
file and I import that file, it doesn't work.

Why can't I import this Singleton decorator from a different file?
What's the best work around?
-- 
http://mail.python.org/mailman/listinfo/python-list


IPC with multiprocessing.connection

2011-12-22 Thread Andrew Berg
I'm trying to set up a system where my main program launches external
programs and then establishes connections to them via named pipes or
Unix domain sockets (depending on platform) with
multiprocessing.connection.Listener. The issue I'm having is with the
accept() method. If there is nothing on the other side of the
pipe/socket, it just hangs. Connection objects have a poll() method that
can timeout, but I see no way to continue the program if there's no
initial connection. What I'd like to do is let it time out if there's
nothing on the other side.
I'm pretty new to the multiprocessing module (and IPC in general), so I
could've easily missed something.

-- 
CPython 3.2.2 | Windows NT 6.1.7601.17640
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python education survey

2011-12-22 Thread Raymond Hettinger
On Dec 21, 9:57 am, Nathan Rice 
wrote:
> +1 for IPython/%edit using the simplest editor that supports syntax
> highlighting and line numbers.  I have found that
> Exploring/Prototyping in the interpreter has the highest ROI of
> anything I teach people.

Thank you Nathan and all the other respondents for your thoughtful
answers.


Raymond

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


Re: [TIP] Anyone still using Python 2.5?

2011-12-22 Thread Kumar McMillan
On Wed, Dec 21, 2011 at 1:15 AM, Chris Withers wrote:

> Hi All,
>
> What's the general consensus on supporting Python 2.5 nowadays?
>

If you compile mod_wsgi with Apache you are stuck on the version of Python
you compiled with. I had an old server stuck on Python 2.5 for this reason
but I finally got a new box where I will be stuck on Python 2.7 for a
while. There's probably a better way with gunicorn or something but Apache
is pretty sweet when you configure it right.

btw, tox is great for developing a project that supports multiple Pythons:
http://tox.testrun.org/latest/



>
> Do people still have to use this in commercial environments or is everyone
> on 2.6+ nowadays?
>
> I'm finally getting some continuous integration set up for my packages and
> it's highlighting some 2.5 compatibility issues. I'm wondering whether to
> fix those (lots of ugly "from __future__ import with_statement" everywhere)
> or just to drop Python 2.5 support.
>
> What do people feel?
>
> cheers,
>
> Chris
>
> --
> Simplistix - Content Management, Batch Processing & Python Consulting
>- http://www.simplistix.co.uk
>
> __**_
> testing-in-python mailing list
> testing-in-python@lists.idyll.**org 
> http://lists.idyll.org/**listinfo/testing-in-python
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spanish Accents

2011-12-22 Thread Peter Otten
Stan Iverson wrote:

> On Thu, Dec 22, 2011 at 12:42 PM, Peter Otten <__pete...@web.de> wrote:
> 
>> The file is probably encoded in ISO-8859-1, ISO-8859-15, or cp1252 then:
>>
>> >>> print "\xe1".decode("iso-8859-1")
>> á
>> >>> print "\xe1".decode("iso-8859-15")
>> á
>> >>> print "\xe1".decode("cp1252")
>> á
>>
>> Try codecs.open() with one of these encodings.
>>
> 
> I'm baffled. I duplicated your print statements but when I run this code
> (or any of the 3 encodings):
> 
> file = codecs.open(p + "2.txt", "r", "cp1252")
> #file = codecs.open(p + "2.txt", "r", "utf-8")
> for line in file:
>   print line
> 
> I get this error:
> 
> *UnicodeEncodeError*: 'ascii' codec can't encode character u'\xe1' in
> position 48: ordinal not in range(128)

You are now one step further, you have successfully* decoded the file. 
The remaining step is to encode the resulting unicode lines back into bytes. 
The encoding implicitly used by the print statement is sys.stdout.encoding 
which is either "ascii" or None in your case. Try to encode explicitly to 
UTF-8 with

f = codecs.open(p + "2.txt", "r", "iso-8859-1")
for line in f:
print line.encode("utf-8")

(*) This is however no big achievement as two (ISO-8859-1, ISO-8859-15) of 
the above codecs would not even balk on a binary file, e.g. a jpeg. They 
offer a character for every possible byte value.

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


Cannot Remove Python Libs from XP

2011-12-22 Thread W. eWatson
I have three py libs and the python program itself, 2.52, installed on 
an 6 year old HP Laptop. I decided to remove them, and took removed 
Python with the Control Panel ?Add/Remove icon. Worked fine. When I try 
to remove any of the remaining libs, press the add/remove button does 
nothing but blink. How  do I get around this  problem?

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


Re: Spanish Accents

2011-12-22 Thread Stan Iverson
On Thu, Dec 22, 2011 at 12:42 PM, Peter Otten <__pete...@web.de> wrote:

> The file is probably encoded in ISO-8859-1, ISO-8859-15, or cp1252 then:
>
> >>> print "\xe1".decode("iso-8859-1")
> á
> >>> print "\xe1".decode("iso-8859-15")
> á
> >>> print "\xe1".decode("cp1252")
> á
>
> Try codecs.open() with one of these encodings.
>

I'm baffled. I duplicated your print statements but when I run this code
(or any of the 3 encodings):

file = codecs.open(p + "2.txt", "r", "cp1252")
#file = codecs.open(p + "2.txt", "r", "utf-8")
for line in file:
  print line

I get this error:

*UnicodeEncodeError*: 'ascii' codec can't encode character u'\xe1' in
position 48: ordinal not in range(128)
  args = ('ascii', u'Noticia: Este sitio web entre este portal
est...r\xe1pidamente va a salir de aqu\xed.\r\n', 48, 49,
'ordinal not in range(128)')
  encoding = 'ascii'
  end = 49
  object = u'Noticia: Este sitio web entre este portal
est...r\xe1pidamente
va a salir de aqu\xed.\r\n'
  reason = 'ordinal not in range(128)'
  start = 48

Please advise. TIA,
Stan
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Why does this launch an infinite loop of new processes?

2011-12-22 Thread Robert Kern

On 12/22/11 11:24 AM, Robert Kern wrote:

Just as a further note on these lines, when older versions of setuptools and
distribute install scripts, they generate stub scripts that do not use a
__main__ guard, so installing a multiprocessing-using application with
setuptools can cause this problem. I believe newer versions of distribute has
this problem fixed, but I'm not sure.


Just checked. No, distribute has not fixed this bug.

--
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: Spanish Accents

2011-12-22 Thread Peter Otten
Stan Iverson wrote:

> On Thu, Dec 22, 2011 at 11:30 AM, Rami Chowdhury
> wrote:
> 
>> Could you try using the 'open' function from the 'codecs' module?
>>
> 
> I believe this is what you meant:
> 
> file = codecs.open(p + "2.txt", "r", "utf-8")
> for line in file:
>   print line
> 
> but got this error:
> 

> *UnicodeDecodeError*: 'utf8' codec can't decode bytes in position 0-2:
> invalid data
>   args = ('utf8', '\xe1 intentado para ellos bastante sabios para
> discernir lo obvio. Tales perso', 0, 3, 'invalid data')

> which is the letter á (a with accent).

The file is probably encoded in ISO-8859-1, ISO-8859-15, or cp1252 then:

>>> print "\xe1".decode("iso-8859-1")
á
>>> print "\xe1".decode("iso-8859-15")
á
>>> print "\xe1".decode("cp1252")
á

Try codecs.open() with one of these encodings.


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


Re: Spanish Accents

2011-12-22 Thread Chris Angelico
On Fri, Dec 23, 2011 at 3:22 AM, Stan Iverson  wrote:
>
> On Thu, Dec 22, 2011 at 11:30 AM, Rami Chowdhury  
> wrote:
>>
>> Could you try using the 'open' function from the 'codecs' module?
>
> I believe this is what you meant:
>
> file = codecs.open(p + "2.txt", "r", "utf-8")
>
> but got this error:
>
>  /usr/lib64/python2.4/codecs.py in next(self= 'rb'>)

Your file almost certainly isn't UTF-16, so don't bother trying that.
I think you may have ISO-8859-1 encoding, also called Latin-1, but
it's not easy to be sure. Try:

file = codecs.open(p + "2.txt", "r", "iso-8859-1")

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


Re: socket.gethostbyaddr( os.environ['REMOTE_ADDR'] error

2011-12-22 Thread Νικόλαος Κούρας
On 22 Δεκ, 17:32, Rami Chowdhury  wrote:
> 2011/12/22 Νικόλαος Κούρας :
>
> > Hello when i try to visit my webpage i get the error it displays. Iam
> > not posting it since you can see it by visiting my webpage at
> >http://superhost.gr
>
> > Please if you can tell me what might be wrong.
>
> I can't see any errors on that page -- can you please post the
> complete traceback so we can all see it?

Yes of course. Its the following:

A problem occurred in a Python script. Here is the sequence of
function calls leading up to the error, in the order they occurred.

 /home/nikos/public_html/cgi-bin/counter.py
   15
   16 hits = 0
   17 host = socket.gethostbyaddr( os.environ['REMOTE_ADDR'] )[0]
   18 date = datetime.datetime.now().strftime( '%y-%m-%d %H:%M:%S' )
   19 agent = os.environ['HTTP_USER_AGENT']
host undefined, socket = , socket.gethostbyaddr = , os = ,
os.environ = {'REDIRECT_QUERY_STRING': 'page=index.html',
'HT...e,sdch', 'UNIQUE_ID': 'TvNasbAJGaoAABtUy@gI'}
herror: (1, '\xb6\xe3\xed\xf9\xf3\xf4\xef \xfc\xed\xef\xec\xe1
\xf3\xf5\xf3\xf4\xde\xec\xe1\xf4\xef\xf2')
  args = (1, '\xb6\xe3\xed\xf9\xf3\xf4\xef \xfc\xed\xef\xec\xe1
\xf3\xf5\xf3\xf4\xde\xec\xe1\xf4\xef\xf2')
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spanish Accents

2011-12-22 Thread Stan Iverson
On Thu, Dec 22, 2011 at 11:30 AM, Rami Chowdhury
wrote:

> Could you try using the 'open' function from the 'codecs' module?
>

I believe this is what you meant:

file = codecs.open(p + "2.txt", "r", "utf-8")
for line in file:
  print line

but got this error:

 141 file = codecs.open(p + "2.txt", "r", "utf-8")
   142 for line in file:
   143   print line
   144
 *line* = '\r\n', *file* = 
/usr/lib64/python2.4/codecs.py in *next*(self=)   492
   493 """ Return the next decoded line from the input stream."""
   494 return self.reader.next()
   495
   496 def __iter__(self):
 *self* = , self.*reader* = , self.reader.*next* = >
/usr/lib64/python2.4/codecs.py in *next*(self=)   429
   430 """ Return the next decoded line from the input stream."""
   431 line = self.readline()
   432 if line:
   433 return line
 line *undefined*, *self* = , self.*
readline* = >  /usr/lib64/python2.4/codecs.py in *readline*(self=, size=None, keepends=True)   344
 # If size is given, we call read() only once
   345 while True:
   346 data = self.read(readsize, firstline=True)
   347 if data:
   348
 # If we're at a "\r" read one extra character (which might
 data *undefined*, *self* = , self.*read* =
>, *
readsize* = 72, firstline *undefined*, *builtin* *True* = True
/usr/lib64/python2.4/codecs.py in *read*(self=, size=72, chars=-1, firstline=True)   291
 data = self.bytebuffer + newdata
   292 try:
   293
 newchars, decodedbytes = self.decode(data, self.errors)
   294 except UnicodeDecodeError, exc:
   295 if firstline:
 *newchars* = u'', *decodedbytes* = 0, *self* = , self.*decode* = , *data* =
'\xe1intentado para ellos bastante sabios para discernir lo obvio.
Tales perso',
self.*errors* = 'strict'

*UnicodeDecodeError*: 'utf8' codec can't decode bytes in position 0-2:
invalid data
  args = ('utf8', '\xe1 intentado para ellos bastante sabios para
discernir lo obvio. Tales perso', 0, 3, 'invalid data')
  encoding = 'utf8'
  end = 3
  object = '\xe1 intentado para ellos bastante sabios para discernir lo
obvio. Tales perso'
  reason = 'invalid data'
  start = 0

which is the letter á (a with accent).
So I tried with utf-16 and got this error:

 141 file = codecs.open(p + "2.txt", "r", "utf-16")
   142 for line in file:
   143   print line
   144
 *line* = '\r\n', *file* = 
/usr/lib64/python2.4/codecs.py in *next*(self=)   492
   493 """ Return the next decoded line from the input stream."""
   494 return self.reader.next()
   495
   496 def __iter__(self):
 *self* = , self.*reader* = , self.reader.*next* = >
/usr/lib64/python2.4/codecs.py in *next*(self=)   429
   430 """ Return the next decoded line from the input stream."""
   431 line = self.readline()
   432 if line:
   433 return line
 line *undefined*, *self* = , self.*
readline* = >  /usr/lib64/python2.4/codecs.py in *readline*(self=, size=None, keepends=True)   344
 # If size is given, we call read() only once
   345 while True:
   346 data = self.read(readsize, firstline=True)
   347 if data:
   348
 # If we're at a "\r" read one extra character (which might
 data *undefined*, *self* = , self.*read* =
>, *
readsize* = 72, firstline *undefined*, *builtin* *True* = True
/usr/lib64/python2.4/codecs.py in *read*(self=, size=72, chars=-1, firstline=True)   291
 data = self.bytebuffer + newdata
   292 try:
   293
 newchars, decodedbytes = self.decode(data, self.errors)
   294 except UnicodeDecodeError, exc:
   295 if firstline:
 newchars *undefined*, decodedbytes *undefined*, *self* = , self.*decode* = >, *data* = '\r\nNoticia:
Este sitio web entre este portal est\xe1 i', self.*errors* = 'strict'
/usr/lib64/python2.4/encodings/utf_16.py in *decode*(self=, input='\r\nNoticia: Este
sitio web entre este portal est\xe1 i', errors='strict')47
 self.decode = codecs.utf_16_be_decode
48 elif consumed>=2:
49
 raise UnicodeError,"UTF-16 stream does not start with BOM"
50 return (object, consumed)
51
 *builtin* *UnicodeError* = 

*UnicodeError*: UTF-16 stream does not start with BOM
  args = ('UTF-16 stream does not start with BOM',)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket.gethostbyaddr( os.environ['REMOTE_ADDR'] error

2011-12-22 Thread becky_lewis
On Dec 22, 2:40 pm, Νικόλαος Κούρας  wrote:
> Hello when i try to visit my webpage i get the error it displays. Iam
> not posting it since you can see it by visiting my webpage 
> athttp://superhost.gr
>
> Please if you can tell me what might be wrong.

It doesn't seem entirely clear but if I had to guess I'd think that
for some reason os.environ['REMOTE_ADDR'] is not returning a good
value (os.environ is a dictionary holding all of the os evironment
variables).
According to the socket docs, this error gets raised for address
related errors.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: socket.gethostbyaddr( os.environ['REMOTE_ADDR'] error

2011-12-22 Thread Rami Chowdhury
2011/12/22 Νικόλαος Κούρας :
> Hello when i try to visit my webpage i get the error it displays. Iam
> not posting it since you can see it by visiting my webpage at
> http://superhost.gr
>
> Please if you can tell me what might be wrong.

I can't see any errors on that page -- can you please post the
complete traceback so we can all see it?

-- 
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
+44-7581-430-517 / +1-408-597-7068 / +88-0189-245544
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spanish Accents

2011-12-22 Thread Rami Chowdhury
On Thu, Dec 22, 2011 at 15:25, Stan Iverson  wrote:

> On Thu, Dec 22, 2011 at 10:58 AM, Chris Angelico  wrote:
>
>> Firstly, are you using Python 2 or Python 3? Things will be slightly
>> different, since the default 'str' object in Py3 is Unicode.
>>
>
> 2
>
>>
>> I would guess that your page is being output as UTF-8; you may find
>> that the solution is as easy as declaring the encoding of your text
>> file when you read it in.
>>
>
> So I tried this:
>
> file = open(p + "2.txt")
> for line in file:
>   print unicode(line, 'utf-8')
>

Could you try using the 'open' function from the 'codecs' module?

file = codecs.open(p + "2.txt", "utf-8")  # or whatever encoding your file
is written in
for line in file:
print line



>
> and got this error:
>
>  142   print unicode(line, 'utf-8')
>143
>144 print '''http://13gems.com/Sign_Up.py"; method="post" target="_blank">
>  *builtin* *unicode* = , *line* = '\r\n
> '   /usr/lib64/python2.4/encodings/utf_8.py in *decode*(input= buffer ptr 0x2b197e378454, size 21>, errors='strict')14
> 15 def decode(input, errors='strict'):
> 16 return codecs.utf_16_decode(input, errors, True)
> 17
> 18 class StreamWriter(codecs.StreamWriter):
>  *global* *codecs* =  '/usr/lib64/python2.4/codecs.pyc'>, codecs.*utf_16_decode* =  function utf_16_decode>, *input* =  size 21>, *errors* = 'strict', *builtin* *True* = True
>
> *UnicodeDecodeError*: 'utf16' codec can't decode byte 0x0a in position
> 20: truncated data
>   args = ('utf16', '\r\n', 20, 21, 'truncated
> data')
>   encoding = 'utf16'
>   end = 21
>   object = '\r\n'
>   reason = 'truncated data'
>   start = 20
>
> Tried it with utf-16 with same results.
>
> TIA,
>
> Stan
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
Rami Chowdhury
"Never assume malice when stupidity will suffice." -- Hanlon's Razor
+44-7581-430-517 / +1-408-597-7068 / +88-0189-245544
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spanish Accents

2011-12-22 Thread Stan Iverson
On Thu, Dec 22, 2011 at 10:58 AM, Chris Angelico  wrote:

> Firstly, are you using Python 2 or Python 3? Things will be slightly
> different, since the default 'str' object in Py3 is Unicode.
>

2

>
> I would guess that your page is being output as UTF-8; you may find
> that the solution is as easy as declaring the encoding of your text
> file when you read it in.
>

So I tried this:

file = open(p + "2.txt")
for line in file:
  print unicode(line, 'utf-8')

and got this error:

 142   print unicode(line, 'utf-8')
   143
   144 print '''http://13gems.com/Sign_Up.py"; method="post" target="_blank">
 *builtin* *unicode* = , *line* = '\r\n'
 
/usr/lib64/python2.4/encodings/utf_8.pyin
*decode*(input=,
errors='strict')14
15 def decode(input, errors='strict'):
16 return codecs.utf_16_decode(input, errors, True)
17
18 class StreamWriter(codecs.StreamWriter):
 *global* *codecs* = , codecs.*utf_16_decode* = , *input* = , *errors* = 'strict', *builtin* *True* = True

*UnicodeDecodeError*: 'utf16' codec can't decode byte 0x0a in position 20:
truncated data
  args = ('utf16', '\r\n', 20, 21, 'truncated data')
  encoding = 'utf16'
  end = 21
  object = '\r\n'
  reason = 'truncated data'
  start = 20

Tried it with utf-16 with same results.

TIA,

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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-22 Thread Mel Wilson
Chris Angelico wrote:

> On Fri, Dec 23, 2011 at 1:13 AM, Hans Mulder  wrote:
>> How about:
>>
>> 
>> ...
>> 
>>
>> More more readable!  And it's a standard!
> 
> Unfortunately it's not Pythonic, because indentation is insignificant.

Easy-peasy:

 
 

Mel.

> We need to adopt a more appropriate form. Eliminate all the 
> tags and use indentation to mark the ends of elements.
> 
> ChrisA
> PS. Brilliant, sir, brilliant! I take off my cap to you.

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


Overlaying PDF with data

2011-12-22 Thread Greg Lindstrom
Hello,

I would like to take an existing pdf form and overlay text "on top" (name,
address, etc.).  I'm looking at ReportLab v2.5 and see their "PLATYPUS"
library might be what I crave, but would like to know if there's a more
obvious way to do this?  I'm working with health care forms which are quite
complex (over 150 fields to potentially populate)  and would like to do it
as painlessly as possible.  I'm running Python 2.7 on Windows.

Thanks for any advice you may have,
--greg
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Spanish Accents

2011-12-22 Thread Chris Angelico
On Fri, Dec 23, 2011 at 1:55 AM, Stan Iverson  wrote:
> Hi;
> If I write a python page to print to the web with Spanish accents all is
> well. However, if I read the data from a text file it prints diamonds with
> question marks wherever there are accented vowels. Please advise.

Sounds like an encoding problem.

Firstly, are you using Python 2 or Python 3? Things will be slightly
different, since the default 'str' object in Py3 is Unicode.

I would guess that your page is being output as UTF-8; you may find
that the solution is as easy as declaring the encoding of your text
file when you read it in.

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


Spanish Accents

2011-12-22 Thread Stan Iverson
Hi;
If I write a python page to print to the web with Spanish accents all is
well. However, if I read the data from a text file it prints diamonds with
question marks wherever there are accented vowels. Please advise.
TIA,
Stan
-- 
http://mail.python.org/mailman/listinfo/python-list


socket.gethostbyaddr( os.environ['REMOTE_ADDR'] error

2011-12-22 Thread Νικόλαος Κούρας
Hello when i try to visit my webpage i get the error it displays. Iam
not posting it since you can see it by visiting my webpage at
http://superhost.gr

Please if you can tell me what might be wrong.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-22 Thread Chris Angelico
On Fri, Dec 23, 2011 at 1:13 AM, Hans Mulder  wrote:
> How about:
>
> 
> ...
> 
>
> More more readable!  And it's a standard!

Unfortunately it's not Pythonic, because indentation is insignificant.
We need to adopt a more appropriate form. Eliminate all the 
tags and use indentation to mark the ends of elements.

ChrisA
PS. Brilliant, sir, brilliant! I take off my cap to you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-22 Thread Hans Mulder

On 22/12/11 14:12:57, Steven D'Aprano wrote:

On Thu, 22 Dec 2011 06:49:16 -0500, Neal Becker wrote:


I agree with the OP that the current syntax is confusing.  The issue is,
the meaning of * is context-dependent.


Here you are complaining about an operator being "confusing" because it
is context-dependent, in a post where you strip all context except the
subject line and expect us to still understand what you're talking about.
There's a lesson there, I'm sure.


* is context dependent. You know what else is context dependent? Well,
most things. But in particular, parentheses. Clearly they must be
"confusing" too. So how about we say:

class MyClass superclasslist A, B C:
 def method argumentlist self, x, y:
 t = tuple 1, 2 tuple 3, 4 endtuple endtuple
 return group x + y endgroup * group x - y endgroup


Much less confusing!


How about:





1
2
34




xx
xx





More more readable!  And it's a standard!

:-)

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


Re: what does 'a=b=c=[]' do

2011-12-22 Thread Ethan Furman

Rolf Camps wrote:

alex23 schreef op wo 21-12-2011 om 16:50 [-0800]:

I'd say that _is_ the most pythonic way, it's very obvious in its
intent (or would be with appropriate names). If it bothers you that
much:

def listgen(count, default=[]):
for _ in xrange(count):
yield default[:]

x, y, z = listgen(3)


I would change your function to (Python3.x):

def empty_lists(count):
for _ in range(count):
yield []


While it's good to be careful, default mutable arguments have their 
place.  Alex's versioun allows one to use an already existing list and 
get shallow copies of it, yours will only create empty lists.


a, b, c = listgen([1, 2, 3])
# a, b, & c are bound to different lists

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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-22 Thread Chris Angelico
On Fri, Dec 23, 2011 at 12:12 AM, Steven D'Aprano
 wrote:
> class MyClass superclasslist A, B C:
>    def method argumentlist self, x, y:
>        t = tuple 1, 2 tuple 3, 4 endtuple endtuple
>        return group x + y endgroup * group x - y endgroup
>
>
> Much less confusing!

A definite improvement. However, I fear that the numerals "1", "2",
etc are far too vague. In some contexts, the abuttal of two such
numerals results in a larger number by a factor of 10, while in
others, the factor is 8, or 16, or 2. This must not be. We need an
unambiguous representation of integers.

Also, I think we should adopt an existing standard [1]. This is
generally a good idea.

class MyClass superclasslist A, B C:
   def method argumentlist self, x, y:
   t = tuple summer's day, proud pony tuple
  sum of honest purse and fellow, large proud town
   endtuple endtuple
   return product of group sum of x and y endgroup and group
difference between x and y endgroup

You will find this a vast improvement.

ChrisA

[1] 
http://shakespearelang.sourceforge.net/report/shakespeare/shakespeare.html#SECTION00045000
or http://tinyurl.com/6sycv
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: [OT] Quick intro to C++ for a Python and C user?

2011-12-22 Thread Neil Cerutti
On 2011-12-22, Roy Smith  wrote:
> In article ,
>  Grant Edwards  wrote:
>> C++ is a vast, complex, and dangerous language -- and industry
>> doesn't seem to be willing to limit itself to using the seven
>> people on the planet who understand it.
>
>> I'm only half joking...  :)
>
> Half joking, indeed.  I happen to know for a fact that there
> are *fourteen* people on the planet who understand it.

One of its greatest contributions to computer science were
Glassbarrow's C++ puzzles. They likely couldn't have been as
challenging in any other language. ;)

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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-22 Thread Steven D'Aprano
On Thu, 22 Dec 2011 06:49:16 -0500, Neal Becker wrote:

> I agree with the OP that the current syntax is confusing.  The issue is,
> the meaning of * is context-dependent.

Here you are complaining about an operator being "confusing" because it 
is context-dependent, in a post where you strip all context except the 
subject line and expect us to still understand what you're talking about. 
There's a lesson there, I'm sure.


* is context dependent. You know what else is context dependent? Well, 
most things. But in particular, parentheses. Clearly they must be 
"confusing" too. So how about we say:

class MyClass superclasslist A, B C:
def method argumentlist self, x, y:
t = tuple 1, 2 tuple 3, 4 endtuple endtuple
return group x + y endgroup * group x - y endgroup


Much less confusing!



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


Re: Pythonification of the asterisk-based collection packing/unpacking syntax

2011-12-22 Thread Neal Becker
I agree with the OP that the current syntax is confusing.  The issue is, the 
meaning of * is context-dependent.

Why not this:

Func (*args) == Func (unpack (args))

def Func (*args) == Func (pack (args))

That seems very clear IMO

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


Re: Why does this launch an infinite loop of new processes?

2011-12-22 Thread Robert Kern

On 12/21/11 8:11 PM, Andrew Berg wrote:

On 12/21/2011 1:29 PM, Ethan Furman wrote:

Anything that runs at import time should be protected by the `if
__name__ == '__main__'` idiom as the children will import the __main__
module.

So the child imports the parent and runs the spawn code again? That
makes sense.


This is a problem with multiprocessing on Windows. Your code would work fine on 
a UNIX system. The problem is that Windows does not have a proper fork() for 
multiprocessing to use. Consequently, it has to start a new Python process from 
scratch and then *import* the main module such that it can properly locate the 
rest of the code to start. If you do not guard the spawning code with a __main__ 
test, then this import will cause an infinite loop.


Just as a further note on these lines, when older versions of setuptools and 
distribute install scripts, they generate stub scripts that do not use a 
__main__ guard, so installing a multiprocessing-using application with 
setuptools can cause this problem. I believe newer versions of distribute has 
this problem fixed, but I'm not sure.


--
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: Elementwise -//- first release -//- Element-wise (vectorized) function, method and operator support for iterables in python.

2011-12-22 Thread Robert Kern

On 12/21/11 5:07 PM, Paul Dubois wrote:

You're reinventing Numeric Python.


Actually, he's not. The numerical operators certainly overlap, but Elementwise 
supports quite a bit more generic operations than we ever bothered to implement 
with object arrays.


--
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: Why does this launch an infinite loop of new processes?

2011-12-22 Thread Hans Mulder

On 21/12/11 21:11:03, Andrew Berg wrote:

On 12/21/2011 1:29 PM, Ethan Furman wrote:

Anything that runs at import time should be protected by the `if
__name__ == '__main__'` idiom as the children will import the __main__
module.

So the child imports the parent and runs the spawn code again? That
makes sense.


It's platform dependent.  On Windows, the child imports the parent
and you get the phenomenon your ran into.  On Posix platforms,
multiprocessing uses fork(), and your code runs without problems.

It would still be a good idea to use the `if __name__ is '__main__'`
idiom, even on Posix platforms.

Hope this helps,

-- HansM


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


Re: Text Processing

2011-12-22 Thread Yigit Turgut
On Dec 21, 2:01 am, Alexander Kapps  wrote:
> On 20.12.2011 22:04, Nick Dokos wrote:
>
>
>
>
>
>
>
>
>
> >>> I have a text file containing such data ;
>
> >>>          A                B                C
> >>> ---
> >>> -2.0100e-01    8.000e-02    8.000e-05
> >>> -2.e-01    0.000e+00   4.800e-04
> >>> -1.9900e-01    4.000e-02    1.600e-04
>
> >>> But I only need Section B, and I need to change the notation to ;
>
> >>> 8.000e-02 = 0.08
> >>> 0.000e+00 = 0.00
> >>> 4.000e-02 = 0.04
> > Does it have to be python? If not, I'd go with something similar to
>
> >     sed 1,2d foo.data | awk '{printf("%.2f\n", $2);}'
>
> Why sed and awk:
>
> awk 'NR>2 {printf("%.2f\n", $2);}' data.txt
>
> And in Python:
>
> f = open("data.txt")
> f.readline()    # skip header
> f.readline()    # skip header
> for line in f:
>      print "%02s" % float(line.split()[1])

@Jerome ; Your suggestion provided floating point error, it might need
some slight modificiation.

@Nick ; Sorry mate, it needs to be in Python. But I noted solution in
case if I need for another case.

@Alexander ; Works as expected.

Thank you all for the replies.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Elementwise -//- first release -//- Element-wise (vectorized) function, method and operator support for iterables in python.

2011-12-22 Thread Robert Kern

On 12/21/11 6:52 PM, Joshua Landau wrote:


If fix means "return number" then no. This inconsistency between elementwise
operations and 'normal' ones is the problem. Again, explicit elementwise-ifying
through "~" fixes that. You need to tell me why this is worth the confusion over
that.


I understand that you are a supporter of PEP 225, but please have some courtesy 
towards other developers. We can explore alternatives in parallel. If we all 
worked on exactly the same thing (much less the one thing that only you get to 
choose), we would forgo a lot of valuable experience. You can point out the 
flaws of Elementwise's implementation and compare it to the virtues of PEP 225 
without being so demanding. He doesn't "need to tell" you a damn thing.


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


Item Checking not possible with UltimateListCtrl in ULC_VIRTUAL mode

2011-12-22 Thread Ven
Following is the system and software info

Platforms: Windows XP and OSX Lion
Activestate Python 2.7.2
wxPython2.9-osx-cocoa-py2.7 (for OSX)
wxPython2.9-win32-py27 (for Windows XP)

I am trying to create a UltimateListCtrl using ULC_VIRTUAL and
ULC_REPORT mode. I would like to know how can I put a checkbox beside
the first column of every row and catch the event when a user checks
the box. I was able to do the same using UltimateListCtrl without
VIRTUAL mode. But, with the ULC_VIRTUAL flag ON, I don't know how to
proceed. Following is the code I created, but this still doesn't allow
me to check the boxes associated with the first column. Please help.

import wx
import images
import random
import os, sys
from wx.lib.agw import ultimatelistctrl as ULC

class TestUltimateListCtrl(ULC.UltimateListCtrl):
def __init__(self, parent, log):

ULC.UltimateListCtrl.__init__(self, parent, -1,
agwStyle=ULC.ULC_AUTO_CHECK_CHILD|ULC.ULC_VIRTUAL|ULC.ULC_REPORT|
ULC.ULC_SINGLE_SEL|ULC.ULC_VRULES|ULC.ULC_HRULES)
self.SetItemCount(1000)
self.table_fields=['First','Second','Third']
field_index=0
for field in self.table_fields:
info = ULC.UltimateListItem()
info._mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE |
wx.LIST_MASK_FORMAT | ULC.ULC_MASK_CHECK
info._image = []
info._format = wx.LIST_FORMAT_CENTER
info._kind = 1
info._text = field
info._font= wx.Font(13, wx.ROMAN, wx.NORMAL, wx.BOLD)
self.InsertColumnInfo(field_index, info)
self.SetColumnWidth(field_index,175)
field_index += 1

def getColumnText(self, index, col):
item = self.GetItem(index, col)
return item.GetText()

def OnGetItemText(self, item, col):
return "Item %d, Column %d" % (item,col)

def OnGetItemColumnImage(self, item, col):
return []

def OnGetItemImage(self, item):
return []

def OnGetItemAttr(self, item):
return None

def OnGetItemTextColour(self, item, col):
return None

#def OnGetItemColumnCheck(self, item, col):
#return True

#def OnGetItemCheck(self, item):
#item=self.GetItem(item)
#return item.IsChecked()

def OnGetItemToolTip(self, item, col):
return None

def OnGetItemKind(self, item):
return 1

def OnGetItemColumnKind(self, item, col):
if col==0:
return self.OnGetItemKind(item)
return 0

class TestFrame(wx.Frame):
def __init__(self, parent, log):
wx.Frame.__init__(self, parent, -1, "UltimateListCtrl in
wx.LC_VIRTUAL mode", size=(700, 600))
panel = wx.Panel(self, -1)
sizer = wx.BoxSizer(wx.VERTICAL)
listCtrl = TestUltimateListCtrl(panel, log)
sizer.Add(listCtrl, 1, wx.EXPAND)
panel.SetSizer(sizer)
sizer.Layout()
self.CenterOnScreen()
self.Show()

if __name__ == '__main__':
import sys
app = wx.PySimpleApp()
frame = TestFrame(None, sys.stdout)
frame.Show(True)
app.MainLoop()

Btw, following is the code I used to create the same thing without the
VIRTUAL mode. And in this case, I can check the boxes beside the first
column data in every row. But, I will be working with tens of
thousands of items and I cannot rely on loading the items like below
because it is very slow. Hence, I want to use the Virtual List, but I
don't know how to get the same functionality in it.

import wx
import images
import random
import os, sys
from wx.lib.agw import ultimatelistctrl as ULC

class TestUltimateListCtrl(ULC.UltimateListCtrl):
def __init__(self, parent, log):

ULC.UltimateListCtrl.__init__(self, parent, -1,
agwStyle=ULC.ULC_REPORT|ULC.ULC_SINGLE_SEL|ULC.ULC_VRULES|
ULC.ULC_HRULES)

self.table_fields=['First','Second','Third']
field_index=0
for field in self.table_fields:
info = ULC.UltimateListItem()
info._mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_IMAGE |
wx.LIST_MASK_FORMAT | ULC.ULC_MASK_CHECK
info._image = []
info._format = wx.LIST_FORMAT_CENTER
info._kind = 1
info._text = field
info._font= wx.Font(13, wx.ROMAN, wx.NORMAL, wx.BOLD)
self.InsertColumnInfo(field_index, info)
self.SetColumnWidth(field_index,175)
field_index += 1

for record_index in range(0,1000):
for field in self.table_fields:
if self.table_fields.index(field)==0:
self.InsertStringItem(record_index, 'Item %d, Column %d' %
(record_index,self.table_fields.index(field)),it_kind=1)
else:
self.SetStringItem(record_index, 
self.table_fields.index(field),
'Item %d, Column %d' % (record_index,self.table_fields.index(field)))

class TestFrame(wx.Frame):
def __init__(self, parent, log):
wx.Frame.__init__(self, parent, -1, "UltimateListC

Re: what does 'a=b=c=[]' do

2011-12-22 Thread Rolf Camps
alex23 schreef op wo 21-12-2011 om 16:50 [-0800]:
> On Dec 22, 8:25 am, Eric  wrote:
> > This surprises me, can someone tell me why it shouldn't?  I figure if
> > I want to create and initialize three scalars the just do "a=b=c=7",
> > for example, so why not extend it to arrays.
> 
> The thing to remember is that everything is an object, and that it's
> better to think of variables as labels on an object.
> 
> So: a=b=c=7 means that _one_ integer object with the value of 7 can be
> referenced using any of the labels a, b or c. x=y=z=[] means that
> _one_ empty list can be referenced using x, y or z.
> 
> The difference is that the value of a number object _cannot be
> changed_ ('immutable') while a list can be modified to add or remove
> items ('mutable'). a=10 just reassigns the label a to an integer
> object of value 10. x.append("foo") _modifies_ the list referred to by
> x, which is the same list known as y & z.
> 
> > Also, is there a more pythonic way to do "x=[], y=[], z=[]"?
> 
> I'd say that _is_ the most pythonic way, it's very obvious in its
> intent (or would be with appropriate names). If it bothers you that
> much:
> 
> def listgen(count, default=[]):
> for _ in xrange(count):
> yield default[:]
> 
> x, y, z = listgen(3)
> 


I'm afraid it's dangerous to encourage the use of '[]' as assignment to
a parameter in a function definition. If you use the function several
times 'default' always points to the same list. 

>>> def return_list(list_ = []):
>>> return list_
>>> a_list = return_list()
>>> a_list
[]
>>> a_list.append(3)
>>> a_list
[3]
>>> b_list = return_list()
>>> b_list
>>> [3]   # !!??

>>> def return_list():
>>> return []
>>> a_list = return_list()
>>> a_list
[]
>>> a_list.append(3)
>>> a_list
[3]
>>> b_list = return_list()
>>> b_list
>>> []# OK!

I only use python3 so I don't know how these things work in other
versions.

No problem in your function since you yield a copy, but I've already
seen long threads about this.

I would change your function to (Python3.x):

def empty_lists(count):
for _ in range(count):
yield []


Regards,

Rolf




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


Adding an interface to existing classes

2011-12-22 Thread Spencer Pearson
I'm writing a geometry package, with Points and Lines and Circles and
so on, and eventually I want to be able to draw these things on the
screen. I have two options so far for how to accomplish this, but
neither of them sits quite right with me, and I'd like the opinion of
comp.lang.python's wizened elders.

Option 1. Subclassing.
The most Pythonic way would seem to be writing subclasses for the
things I want to display, adding a ".draw(...)" method to each one,
like this:
class DrawablePoint( geometry.Point ):
class draw( self, ... ):
...

When the time comes to draw things, I'll have some list of objects I
want drawn, and say
for x in to_draw:
x.draw(...)

I see a problem with this, though. The intersection of two lines is
(usually) an object of type Point. Since DrawableLine inherits from
Line, this means that unless I redefine the "intersect" method in
DrawableLine, the intersection of two DrawableLines will be a Point
object, not a DrawablePoint. I don't want to saddle the user with the
burden of converting every method output into its corresponding
Drawable subclass, and I don't want to redefine every method to return
an instance of said subclass. I see no other options if I continue
down the subclassing path. Am I missing something?




Option 2. A "draw" function, with a function dictionary.
This feels weird, but is fairly simple to write, use, and extend. We
have a module with a "draw_functions" dictionary that maps types onto
functions, and a "draw" function that just looks up the proper type in
the dictionary and calls the corresponding function. If you create
your own object, you can just add a new entry to the dictionary. The
implementation is simple enough to outline here:

In file "geometry/gui.py":
def draw_point(...):
...
def draw_line(...):
...
draw_functions = {geometry.Point: draw_point, geometry.Line:
draw_line, ...}
def draw( x, *args, **kwargs ):
for type, callback in draw_functions.iteritems():
if isinstance(x, type):
callback(x, *args, **kwargs)
else:
raise TypeError("don't know how to draw things of type "
"{0}".format(type(x)))


In the file that uses this:
# Drawing a predefined type of object:
geometry.gui.draw(some_point, ...)
# Here we define a new kind of object and tell the package how to draw
it.
class MyObject(GeometricObject):
...
def draw_my_object(...):
...
geometry.gui.draw_functions[MyObject] = draw_my_object
# And now we draw it.
geometry.gui.draw(MyObject(...), ...)


If I feel fancy, I might use a decorator for adding entries to
draw_functions, but this is basically how it'd work.




The second way feels kludgey to me, but I'm leaning towards it because
it seems like so much less work and I'm out of ideas. Can anyone help,
explaining either a different way to do it or why one of these isn't
as bad as I think?

Thanks for your time!
-Spencer
-- 
http://mail.python.org/mailman/listinfo/python-list