Re: function object.func_default off the console

2007-04-25 Thread Peter Otten
Aaron Brady wrote:

 f.func_defaults[0]
> [2, 3]
 f.func_defaults[0]+=[4]
> Traceback (most recent call last):
>File "", line 1, in 
> TypeError: 'tuple' object does not support item assignment
 f.func_defaults[0]
> [2, 3, 4]
> 
> V. interesting.  Operation succeeds but with a throw.  Er, raise.

This is not specific to func_defaults:

>>> t = ([1],)
>>> t[0] += [2]
Traceback (most recent call last):
  File "", line 1, in 
TypeError: 'tuple' object does not support item assignment
>>> t
([1, 2],)

t[0] += [2]

is resolved to

t.__setitem__(t[0].__iadd__([2]))

where list.__iadd__() succeeds but __setitem__() fails (because tuples don't
have that method).

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


trinary operator - if then else

2007-04-25 Thread Alchemist
What is Python's version for the trinary if..then..else operator?

I want a one-liner such as
  a?b:c
for the if..then..else control structure
if a
  then b
  else c

Does Python 2.4 support it?

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


Re: Catching a specific IO error

2007-04-25 Thread Tina I
Gabriel Genellina wrote:
> You can get the 2 as the errno exception attribute. BTW, 2 == errno.ENOENT
> 
>  try:
>  export = open(self.exportFileName , 'w')
>  except IOError, e:
> if e.errno==errno.ENOENT:
> # handle the "No such file or directory" error
>  # calling an error handling method.
> 
> See http://docs.python.org/lib/module-exceptions.html
> 
> --Gabriel Genellina

Perfect! Just what I was looking for. Thank you! :)

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


Re: trinary operator - if then else

2007-04-25 Thread Peter Otten
Alchemist wrote:

> What is Python's version for the trinary if..then..else operator?

true_value if condition else false_value

> Does Python 2.4 support it?

No, it requires 2.5 or later.

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


RE: If Dict Contains a particular key

2007-04-25 Thread Robert Rawlins - Think Blue
Thanks guys for this, glad it was so simple.

 

I used mikes solution in the end, and it worked a charm.

 

Thanks again,

 

Rob

 

From: [EMAIL PROTECTED]
[mailto:[EMAIL PROTECTED]
On Behalf Of Michael Bentley
Sent: 24 April 2007 18:37
To: [email protected]
Subject: Re: If Dict Contains a particular key

 

 

On Apr 24, 2007, at 12:28 PM, Robert Rawlins - Think Blue wrote:





Hello Guys,

 

I'm Looking to build a quick if/else statement that checks a dictionary for
a key like follows.

 

If myDict contains ThisKey:

Do this...

Else

Do that...

 

Thats the best way of doing this?

if ThisKey in myDict:

  pass # do this

else:

  pass # do that

 

 

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

Re: Tutorial creates confusion about slices

2007-04-25 Thread Antoon Pardon
On 2007-04-24, Michael Hoffman <[EMAIL PROTECTED]> wrote:

> Really only one person has argued that the docs do not need to be 
> changed. The other two people seemed to think you were asking for help 
> rather than discussing how to revise the docs. Understandable, since 
> that's why most people come to this group in my estimation.
>
> Your time is your own and it is good to spend your efforts on what you 
> think will be most fruitful. But if you are going to let the opposition 
> of one person stop you from doing anything, you will not accomplish very 
> much.

[EMAIL PROTECTED] has brought a point that is worth considering.
So I retreat now a bit to see if I can come with a proposal that
bears in mind his point.

-- 
Antoon Pardon

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


Re: Python un-plugging the Interpreter

2007-04-25 Thread Hendrik van Rooyen
"Jorgen Grahn" <[EMAIL PROTECTED]> wrote:

> On Thu, 19 Apr 2007 20:39:57 -0700, Alex Martelli <[EMAIL PROTECTED]> wrote:
> > Steve Holden <[EMAIL PROTECTED]> wrote:
> >
> >> A long time ago Greg Stein produced a patch that removed the need for
> >> the GIL, but nobody seemed to want to pay the penalty it extracted in
> >> speed reduction, so it languished unadopted.
> >
> > Perhaps the current wave of dual-core and quad-core CPUs in cheap
> > consumer products would change people's perceptions -- I wonder...
> 
> Maybe it would change /perceptions/, but would normal users suddenly
> start running things that are (a) performance-critical, (b) written in
> Python and (c) use algorithms that are possible to parallellize?
> 
> I doubt it. (But I admit that I am a bit negative towards thread
> programming in general, and I have whined about this before.)
> 

I find this last statement interesting, because it differs so much
from my own attitude - getting a thread running was one of the
first things I did when I started getting to grips with python.

Do you mind "whining" some more - maybe I can learn 
something - threads seem to me to make a lot of things so 
much easier and more natural, as I see them as sequences
that run "at the same time",  and I find this immensely useful
for all sorts of things, as it enables me to think in a simple
linear fashion about parts of complicated things.  And if you
add queues, you have something in your hand that you can 
do quite fancy stuff with in a robust, simple manner...

*grin* before I discovered the queue module, I was using
named pipes to communicate between threads...

So you could say I am a threading freak if you want to, and 
I won't argue.

But I would like to hear the opposite viewpoint..

- Hendrik

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


Re: Tutorial creates confusion about slices

2007-04-25 Thread Antoon Pardon
On 2007-04-24, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> Antoon Pardon wrote:
>> On 2007-04-24, Michael Bentley <[EMAIL PROTECTED]> wrote:
>> >
>> > On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote:
>> >
>> >> People don't read tutorials in a strictly linear fashion. They can
>> >> continue to later subjects and then come back here to see how things
>> >> tie together. So the fact that it is only confusing to those who
>> >> know more than is already presented doesn't seem a very good reason
>> >> to leave it in.
>> >
>> > Yet they understand that earlier in the document, there is likely to
>> > be a less complete coverage of a given topic.  There is in fact, a
>> > link on that page that includes a more complete coverage of that
>> > topic (which I mentioned to you in an earlier message IIRC).
>>
>> That there is more complete coverage elsewhere is no good reason
>> to come with an explanation that suggests things working in
>> a way that will be contradicted by that more complete coverage.
>
> I happen to agree with you, but that's not a completely non-
> controversial position.  Many tutorials/manuals will prevent a
> simplified (and incorrect for the general case) description of how
> something works early on, and then clarify it later for the general
> case.  Personally I'd usually rather have the complete description
> earlier rather than an incorrect simplification, or at least have a
> footnote to the effect of "this is a simple introduction, the full
> behavior will be described later".
>
> But there's a good argument to be made for omitting confounding
> details early on in a tutorial if there's a pedogogical reason for
> doing so--indeed, there's such a widespread belief that early
> oversimplification is actually helpful that I'd guess the majority of
> language tutorials engage in it to some degree.

Thank you for bringing this up so explicitly. I must confess this
point hadn't entered my mind but it is worth thinking about. I'll
see if I can come up with a new proposal bearing this in mind.

Thank you.

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


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Hendrik van Rooyen
 "Steve Holden" <[EMAIL PROTECTED]> wrote:


> Jeff Rush wrote:
> > There is discussion by the Python Software Foundation of offering cash
> > bounties or perhaps periodic awards to the "best of" for magazine articles,
> > video/screencast clips and such.
> >
> > If YOU would be swayed to get involved in producing content in exchange for
> > cash, please speak up on the advocacy mailing list and also drop an email to
> > Steve Holden <[EMAIL PROTECTED]>, current champion of this idea and
looking
> > for encouragement.  Ideas on how to evaluate contributions, how frequently
to
> > do this and critical thresholds of cash amounts necessary to induce YOUR
> > participation are wanted.
> >
> Thanks for posting this, Jeff. I have already had a couple of replies.
> Allow me to expand on my current thinking before this gets off-track.
>
> Lest people be lulled into thinking that the PSF is going into the
> "articles for cash" business, let me say that isn't really the idea. I
> don't really think we will necessarily improve the quality of
> information about Python simply by throwing cash incentives at authors,
> and I was more looking for a way to reward authors of excellence, as
> judged by some subset of the Python community - this might have to be
> the PSF membership given the impracticality of running a meaningful poll
> with a larger set of voters.

I get a bit confused here - when you say "articles" - what forum do you have
in mind?

I would suggest that paying for articles would make sense on a commisioned
basis, if there were to be an identified "hole" in the documentation, or for
some technique or recipe which is not well covered, and deserving of more
exposure.

>
> So the intention is not so much to encourage people who wouldn't
> otherwise write to start writing (desirable though this outcome might
> be, I don't think cash incentives are the right way to achieve it) but
> rather to reward *excellence* in Python writing and underline the fact
> that standards are important.
>
> There are many other possibilities too. What about an award for "most
> helpful responses on c.l.py" over some period? I think one of the
> reasons people find Python so useful is its helpful community, and it
> would be nice to see the tireless fielders of questions rewarded for
> their community contribution.
>

This is a good idea - I sometimes marvel at the degree of effort that
some of the answers to a question on this NG must cost the repliers.

Another one would be to reward the most patient fellow...

> However, these are only my ideas and I am open to any and all
> suggestions from the broader Python community about how awards might be
> used to provide incentives to improve the available information about
> Python, and possibly even the software that's available in Python. I
> have undertaken to make a proposal to the PSF Board for an incentive
> scheme. So please let me have your ideas.

Most bugs fixed in the month for the developers?
(Watch them scrabbling for the easy ones  -  )

Most Patches reviewed and incorporated?

Best recipe of the week/month/year?

Best Existing Module - don't forget that there has been a lot of effort
put in already into stuff like Twisted, Pyro, SPE, and many more - a
lot of it excellent work provided by rugged individuals, just because
they could...

As somone else has already said :

.. is F**G awesome - and its all in python.

Hey! how about starting with the best suggestion for spending the money...
That should get the ball rolling.

- Hendrik

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


If Dict Contains...

2007-04-25 Thread Robert Rawlins - Think Blue
Hello Guys,

 

Looking to build a quick if/else statement that checks a dictionary for a
key like follows.

 

If myDict contains ThisKey:

Do this...

Else

Do that...

 

Thats the best way of doing this?

 

Thanks,

 

Rob

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

Charlotte Python Group

2007-04-25 Thread Calvin Spealman
Attending my first meetup tomorrow for the Agile Charlotte group from
meetup.com. My old area, surrounded by cows and corn, had no chance of
getting any meetups, so I'm excited to be back at the city and able to
partake in some community. If anyone by chance is attending, or near
enough to make it, check out the information and drop a note.

-- 
Read my blog! I depend on your acceptance of my opinion! I am interesting!
http://ironfroggy-code.blogspot.com/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: *** Watch BOMBSHELL video of Senator John Kerry admitting 911 was in INSIDE JOB ???

2007-04-25 Thread joseph2k
Jon Slaughter wrote:

> 
> <[EMAIL PROTECTED]> wrote in message
> news:[EMAIL PROTECTED]
>> http://www.911blogger.com/node/8053
>>
>> Senator John Kerry was questioned concerning 9/11 during an appearance
>> at Book People in Austin, Texas. Members of Austin 9/11 Truth Now
>> asked Kerry about the officially unexplained collapse of WTC Building
>> 7."
>>
>> Kerry responded:
>>
>>"I do know that that wall, I remember, was in danger and I think
>> they made the decision based on the danger that it had in destroying
>> other things-- that they did it in a controlled fashion."
>>
>> http://www.jonesreport.com/articles/220407_kerry_wtc7.html
>>
>> Thanks to the dozen or so people who submitted this as a blog entry :)
>>
>> "Mr. Kerry?!?"
>>
>> "Just a follow-up or two...
>>
>> WHAT THE HELL|?| Are you saying that building was wired that day? Or
>> well in advance? 'Splain, please.
>>
>> Does your fellow Bonesman George Walker Bush appreciate you letting
>> the cat out of the bag on this? Is that your cell phone I hear
>> ringing?
>>
>> Why is your wife squirming like that? Stop it, Theresa! Stop it!"
>>
> 
> So what your saying is that the democrates are behind 9/11?  So they tried
> to frame Bush? Whats new?  Doesn't this then mean that the democrates and
> alqaeda are working together?  I always that pelosie looked like she had a
> little arabic in her(probably in more ways than one).
Naw, the Repuglicans were fully in power then, it had to be them.
-- 
 JosephKK
 Gegen dummheit kampfen die Gotter Selbst, vergebens.  
  --Schiller
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: MS SQL Server Extension?

2007-04-25 Thread Tim Golden
Jack wrote:
> Hi all, in my next project, my Python code needs to talk to an MS SQL
> 2000 Server. Internet search gives me http://pymssql.sourceforge.net/
> I wonder what module(s) people are using. My code runs on a Linux
> box so the module has to build on Linux. Any hints/pointers are welcome. 

There are several modules around which will cover this.
One of these days I'll take the post I'm about to write
and stick it on a Wiki or something because I seem to
write it about once every six months :)

In no particular order:

adodbapi - recently resurrected from moribundity (if
that's a word); search the list archives because I
can't remember who's working on it.

+ Win32 only (afaik)
+ Covers all sorts of things as well as MSSQL
+ Allows for passthrough authentication

- Used to have some slight flakiness in it. Bloke
who's taken over maintenance says he's patched and
simplified things. Haven't tried it since.

pymssql - http://pymssql.sf.net

+ Win32 & Linux (via FreeTDS)

- Doesn't allow passthrough authentication
- Has some issues with Unicode

pyodbc - http://pyodbc.sf.net
(a recent runner)

+ Win32 & Linux (via whatever *nix ODBC package)
+ Apparently more actively maintained than pymssql
+ (Is currently the favoured front-runner among the 
sqlalchemy devs)

- Lacks .nextset (in case that's important to you)

Other contenders:

mxODBC - Commercial License but a very strong
and long-standing candidate. Lacks .nextset
support. Works on *nix via iODBC etc.

Object Craft MSSQL - Worked well for me for years
but they seemed to have abandoned it of late.
Still there. Still works. But no binaries beyond
Python 2.3. (I did try to recompile using MingW
but couldn't get it to work). Works on *nix via
FreeTDS.

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


Re: Tutorial creates confusion about slices

2007-04-25 Thread Ant
Hi Antoon,

> The best way to remember how slices work is to think of the indices as
...
>   +---+---+---+---+---+
>   | H | e | l | p | A |
>   +---+---+---+---+---+
>   0   1   2   3   4   5
>  -5  -4  -3  -2  -1
>
> This is all very well with a simple slice like:
>
>   "HelpA"[2:4]=> "lp"

But that is the whole point of a language tutorial, to introduce the
language and provide a way to get started. Note that the tutorial
doesn't even go into any details on extended slicing - as far as the
beginner is concerned at this point, there *is* no extended slice
notation. Even if the tutorial *did* go into more detail about
slicing, mentioning negative steps would be folly - the tutorial
should be an easy way into the language, and in such a context the
above tool for remembering how they work is just fine.

The exact (mathematical) definition for string slices is given in the
Library reference (http://docs.python.org/lib/typesseq.html), which is
where it should be. If you are at the point where understanding what
the deal is with extended slice notation for strings, then you are
ready to look at the real manual. If the tutorial was fully
comprehensive it would be massive and daunting. You'd probably have to
split it up as well, into, say, a Language reference and a Library
reference.

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


popen2 results

2007-04-25 Thread Robert Rawlins - Think Blue
Hello guys,

 

I've recently ported my application from bash to python, however there are
still a few bash line utilities I -have- to use in the application as there
isn't any alternative available to me. In the old days of bash I would have
grep'd the output from these commands to determine the outcome.

 

I'm now using popen2 to run the command which works a charm, but I'm
struggling to parse the results of the function, has anyone had any
experience with this? I've found a few suggested solutions dotted around,
such as this one.

 

 import os

 

 def filtered(command, source):

 dest, result = os.popen2(command)

 dest.write(source)

 dest.close()

 try:

  return result.read()

 finally:

  result.close()

 

But to be honest I'm struggling to get it to do anything as it doesn't
states what the 'source' object is or should be.

 

Thanks for any help guys, I'm just looking to capture the output from the
command and then I can go about a little REGEX on it.

 

Thanks,

 

Rob

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

Re: Tutorial creates confusion about slices

2007-04-25 Thread Tim Golden
Antoon Pardon wrote:
> On 2007-04-24, Michael Hoffman <[EMAIL PROTECTED]> wrote:
> 
>> Really only one person has argued that the docs do not need to be 
>> changed. The other two people seemed to think you were asking for help 
>> rather than discussing how to revise the docs. Understandable, since 
>> that's why most people come to this group in my estimation.
>>
>> Your time is your own and it is good to spend your efforts on what you 
>> think will be most fruitful. But if you are going to let the opposition 
>> of one person stop you from doing anything, you will not accomplish very 
>> much.
> 
> [EMAIL PROTECTED] has brought a point that is worth considering.
> So I retreat now a bit to see if I can come with a proposal that
> bears in mind his point.

Now that this thread has slowed a little I would also
point out -- while agreeing with sjdevnull's thoughtful
post -- that reaction to an idea on a mailing list is
possibly not the best means of gauging its validity.
That's not to say you shouldn't listen to other posters;
rather that, if you still feel after due consideration
of other people's points of view that what you're
proposing is right, then go ahead and create a patch.

The people who are going to accept or reject your
doc patch are (probably) not the people who are
putting forward their ideas here on this list.
Ultimately, patches aren't voted in by the denizens
of python-list / c.l.py.

Also, there may be 1000 people nodding thoughtfully
(and silently) in agreement with your point of view, but
who are unlikely to post a "me, too" comment. It seems
likely that any posters are more likely to be those in
disagreement with a point of view.

Frankly, if you think after consideration that a change
to the docs is advisable, post up a patch to the relevant
place. If there are people on this list who disagree,
they're at liberty to comment on the patch. But at that
point, you've made the effort and said your piece. It's
up to the naysayers to make the effort to comment on
the patch. And, ultimately, up to the Python development
community to accept or reject it as they see fit. (And
as they have the time and inclination :)

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


Coding conventions for class names

2007-04-25 Thread Kay Schluehr
set, int, float, list, object,...

Don't see any of the basic types following the capitalized word
convention for classes covered by PEP 08. This does not hold only for
__builtins__ in the strict sense but also for types defined in builtin
modules like datetime.

My question is: does anyone actually follow guidelines here and if yes
which ones and are they resonable ( e.g. stable with regard to
refactoring etc. )?

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


Re: If Dict Contains...

2007-04-25 Thread Daniel Nogradi
> Looking to build a quick if/else statement that checks a dictionary for a
> key like follows.
>
> If myDict contains ThisKey:
>
> Do this...
>
> Else
>
> Do that...
>
>
>
> Thats the best way of doing this?


if key in myDict:
Do this.
else:
Do that


HTH,
Daniel
-- 
http://mail.python.org/mailman/listinfo/python-list


How to change font colour

2007-04-25 Thread [EMAIL PROTECTED]



 I use PIL to write some text to a picture.The text must  be seen wery clearly.
I write the text to different pictures but to the same position. As  pictures maybe  different, 
colour, in the position where I write the text, is also different.
Is there a way how to set the font colour so that it will be seen very clearly in the picture?
For example, if the picture is bright ( for example yellow), the font colour should be dark( e.g. 
black) and vice versa.
Can anyone help?
Thanks
L.


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

Re: Tutorial creates confusion about slices

2007-04-25 Thread Ant
On Apr 23, 1:38 pm, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> The following is part of the explanation on slices in the
> tutorial:
>
> The best way to remember how slices work is to think of the indices as
...
>   +---+---+---+---+---+
>   | H | e | l | p | A |
>   +---+---+---+---+---+
>   0   1   2   3   4   5
>  -5  -4  -3  -2  -1

For a tutorial this is sound advice. A tutorial is designed to give
readers an easy intro to a topic, which is what this achieves. At this
stage the target audience has no idea that extended slices even exist,
let alone that you can use negative indices with them.

> This is all very well with a simple slice like:
>
>   "HelpA"[2:4]=> "lp"
>
> But it give the wrong idea when using the following extended slice:
>
>   "HelpA"[4:2:-1]   =>   "Ap"

But that is fine. Extended slice notation (let alone using negative
indices) is beyond the scope of the tutorial. Once you start to
experiment with extended slices, it is time to look beyond the
simplified tutorial information, and to the official documentation in
the Library and Language references. The library docs (http://
docs.python.org/lib/typesseq.html) say this:

(5) The slice of s from i to j with step k is defined as the sequence
of items with index x = i + n*k such that 0 <= n < (j-i/k)

Which is exactly how it works, and describes exactly why your extended
slice example works as it does.




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


Re: Coding conventions for class names

2007-04-25 Thread Marc 'BlackJack' Rintsch
In <[EMAIL PROTECTED]>, Kay Schluehr
wrote:

> set, int, float, list, object,...
> 
> Don't see any of the basic types following the capitalized word
> convention for classes covered by PEP 08. This does not hold only for
> __builtins__ in the strict sense but also for types defined in builtin
> modules like datetime.

Most built-ins are easy to explain:  They were functions long before it
was possible to use them as base classes and stayed lowercase for
backwards compatibility.  Don't know about `set` and `object`.  I guess
it's foolish consistency!?

> My question is: does anyone actually follow guidelines here and if yes
> which ones and are they resonable ( e.g. stable with regard to
> refactoring etc. )?

I follow PEP 8 in my (mostly unpublished) code if that does matter to you.  :-)

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

Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Antoon Pardon
On 2007-04-24, Anton Vredegoor <[EMAIL PROTECTED]> wrote:
> Steve Holden wrote:
>>> When cash is involved, it's important to avoid even the slightest
>>> hint of a suggestion of a suspicion of a conflict of interest; 
>>> that, I guess, is why firms that run contests with cash prizes
>>> always declare employees and their families "not eligible", and why
>>> I think the PSF should do likewise in this case.
>>> 
>> That's a good point, and also a valid reason for restricting the
>> voting community to PSF members. Thanks, Alex.
>
> So in order to avoid a suspicion of a conflict of interest you want to 
> turn the whole thing into private property of the PSF?
>
> That is  the most ridiculous suggestion I have ever

I kind of understand why they would want to do this. If you have
no limitations on who may vote, such a contest can easily turn
into a contest of who can mobilize the biggest clan of supporters.

Now maybe there are better ways to avoid this kind of unwanted
effect but I wouldn't call Steve's suggestion ridiculous.

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


Re: Coding conventions for class names

2007-04-25 Thread Michael Hoffman
Kay Schluehr wrote:

> My question is: does anyone actually follow guidelines here

Yes.

> and if yes
> which ones and are they resonable ( e.g. stable with regard to
> refactoring etc. )?

All of them that I know of. What does it mean to be "stable with regard 
to refactoring etc."?
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: q: how to output a unicode string?

2007-04-25 Thread Frank Stajano
Diez B. Roggisch wrote:
> Frank Stajano wrote:
> 
>> A simple unicode question. How do I print?
>>
>> Sample code:
>>
>> # -*- coding: utf-8 -*-
>> s1 = u"héllô wórld"
>> print s1
>> # Gives UnicodeEncodeError: 'ascii' codec can't encode character
>> # u'\xe9' in position 1: ordinal not in range(128)
>>
>>
>> What I actually want to do is slightly more elaborate: read from a text
>> file which is in utf-8, do some manipulations of the text and print the
>> result on stdout. I understand I must open the file with
>>
>> f = codecs.open("input.txt", "r", "utf-8")
>>
>> but then I get stuck as above.
>>
>> I tried
>>
>> s2 = s1.encode("utf-8")
>> print s2
>>
>> but got
>>
>> héllô wórld
> 
> Which is perfectly alright - it's just that your terminal isn't prepared to
> decode UTF-8, but some other encoding, like latin1.

Aha! Thanks for spotting this. You are right about the terminal 
(rxvt/cygwin) not being ready to handle utf-8, as I can now confirm with a

  cat t2.py

(t2.py being the program above) which displays the source code garbled 
in the same way.

If I do

s1 = u"héllô wórld"
print s1

at the interactive prompt of Idle, I get the proper output

héllô wórld

So why is it that in the first case I got UnicodeEncodeError: 'ascii' 
codec can't encode? Seems as if, within Idle, a utf-8 codec is being 
selected automagically... why should that be so there and not in the 
first case?

>> Then, in the hope of being able to write the string to a file if not to
>> stdout, I also tried
>>
>>
>> import codecs
>> f = codecs.open("out.txt", "w", "utf-8")
>> f.write(s2)
>>
>> but got
>>
>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1:
>> ordinal not in range(128)
> 
> Instead of writing s2 (which is a byte-string!!!), write s1. It will work.

OK, many thanks, I got this to work!

> The error you get stems from f.write wanting a unicode-object, but s2 is a
> bytestring (you explicitly converted it before), so python tries to encode
> the bytestring with the default encoding - ascii - to a unicode string.
> This of course fails.

I think I have a better understanding of it now. If the terminal hadn't 
fooled me, I probably wouldn't have assumed that the code I originally 
wrote (following the first examples I found) was wrong! I assume that 
when you say "bytestring" you mean "a string of bytes in a certain 
encoding (here utf-8) that can be used as an external representation for 
the unicode string which is instead a sequence of code points".

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

Re: q: how to output a unicode string?

2007-04-25 Thread Diez B. Roggisch
> So why is it that in the first case I got UnicodeEncodeError: 'ascii'
> codec can't encode? Seems as if, within Idle, a utf-8 codec is being
> selected automagically... why should that be so there and not in the
> first case?

I'm a bit confused on what you did when the error appears if you try to
output a unicode-object without prior encoding - then the default encoding
(ascii) is used.
 
>>> Then, in the hope of being able to write the string to a file if not to
>>> stdout, I also tried
>>>
>>>
>>> import codecs
>>> f = codecs.open("out.txt", "w", "utf-8")
>>> f.write(s2)
>>>
>>> but got
>>>
>>> UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 1:
>>> ordinal not in range(128)
>> 
>> Instead of writing s2 (which is a byte-string!!!), write s1. It will
>> work.
> 
> OK, many thanks, I got this to work!
> 
>> The error you get stems from f.write wanting a unicode-object, but s2 is
>> a bytestring (you explicitly converted it before), so python tries to
>> encode the bytestring with the default encoding - ascii - to a unicode
>> string. This of course fails.
> 
> I think I have a better understanding of it now. If the terminal hadn't
> fooled me, I probably wouldn't have assumed that the code I originally
> wrote (following the first examples I found) was wrong! I assume that
> when you say "bytestring" you mean "a string of bytes in a certain
> encoding (here utf-8) that can be used as an external representation for
> the unicode string which is instead a sequence of code points".

Yes. That is exactly the difference. 

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


Re: Tutorial creates confusion about slices

2007-04-25 Thread Antoon Pardon
On 2007-04-25, Ant <[EMAIL PROTECTED]> wrote:
> On Apr 23, 1:38 pm, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>> The following is part of the explanation on slices in the
>> tutorial:
>>
>> The best way to remember how slices work is to think of the indices as
> ...
>>   +---+---+---+---+---+
>>   | H | e | l | p | A |
>>   +---+---+---+---+---+
>>   0   1   2   3   4   5
>>  -5  -4  -3  -2  -1
>
> For a tutorial this is sound advice. A tutorial is designed to give
> readers an easy intro to a topic, which is what this achieves. At this
> stage the target audience has no idea that extended slices even exist,
> let alone that you can use negative indices with them.

OK. But eventually they will come into contact with negative indexes.
If they still rely on the above representation for understanding slices
that may cause confusions. It is possible that the time lost in clearing
up these later confusions will be bigger than the time gained by using
this simplification in the tutorial.

So I'm not so sure it is sound advice in this case.

If the consensus is that something like this should remain, I would
suggest replacing:

"The best way to remember how slices work is"

with:

"A way to remember how slices work, it is not entirly correct
 but may be usefull, is"

Or something similar.


Wording to that effect makes it more clear that it is a crutch
that can be usefull now but that it should be discarded later.

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


Now()

2007-04-25 Thread Robert Rawlins - Think Blue
Hello Guys,

 

I'm using the following function 'str (now)' to place a date time stamp into
a log file, which works fine, however it writes the stamp like this.

 

2007-04-25 11:06:53.873029

 

But I need to expel those extra decimal places as they're causing problems
with the application that parses the log data, all I need is something like
this:

 

2007-04-25 11:06:53

 

With time depicted to the nearest second, from my background in ColdFusion
development we used to have a datetimeformat() function that I could use as

 

DateTimeFormat(now(), "-mm-dd HH:mm:ss")

 

Which would give the current time a mask.

 

Any equivalent for this in python?

 

Thanks,

 

Rob

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

Re: trinary operator - if then else

2007-04-25 Thread Michael Bentley

On Apr 25, 2007, at 1:58 AM, Alchemist wrote:

> What is Python's version for the trinary if..then..else operator?
>
> I want a one-liner such as
>   a?b:c
> for the if..then..else control structure
> if a
>   then b
>   else c
>
> Does Python 2.4 support it?

Not precisely, but you can *usually* get away with:

a and b or c



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


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Anton Vredegoor
Antoon Pardon wrote:

>>> That's a good point, and also a valid reason for restricting the
>>> voting community to PSF members. Thanks, Alex.
>> So in order to avoid a suspicion of a conflict of interest you want to 
>> turn the whole thing into private property of the PSF?
>>
>> That is  the most ridiculous suggestion I have ever
> 
> I kind of understand why they would want to do this. If you have
> no limitations on who may vote, such a contest can easily turn
> into a contest of who can mobilize the biggest clan of supporters.

Sure, any democratic process can be derailed by a coordinated effort of 
people with a different mentality. To prevent such things by killing the 
democratic process oneself right at the beginning of a project is a 
peculiar way of avoiding this risk.

> Now maybe there are better ways to avoid this kind of unwanted
> effect but I wouldn't call Steve's suggestion ridiculous.

It's about as ridiculous as proving that a stiff parrot is dead by 
grabbing it by the legs and repeatedly hitting it's head on the counter.

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


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Anton Vredegoor
Anton Vredegoor wrote:

> It's about as ridiculous as proving that a stiff parrot is dead by 
> grabbing it by the legs and repeatedly hitting it's head on the counter.

Or to write "it's" where its is more appropriate.

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


PIL font formatting...

2007-04-25 Thread Durumdara

Hi!

I wrote a web visitor counter with modpy and pil.
It is must working on half-static page, so I must write this counter with
jpeg image output.

Everything is working good, but I need to change this counter a little, it's
style isn't same as it's webpage's style.

I want to make bold and italic text into image. How to I do it?

font = ImageFont.truetype('arial.ttf', 15, )

.text('a', font = font, )

Please help me!!!

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

Re: Coding conventions for class names

2007-04-25 Thread Michael Hoffman
Marc 'BlackJack' Rintsch wrote:
> In <[EMAIL PROTECTED]>, Kay Schluehr
> wrote:
> 
>> set, int, float, list, object,...
>>
>> Don't see any of the basic types following the capitalized word
>> convention for classes covered by PEP 08. This does not hold only for
>> __builtins__ in the strict sense but also for types defined in builtin
>> modules like datetime.
> 
> Most built-ins are easy to explain:  They were functions long before it
> was possible to use them as base classes and stayed lowercase for
> backwards compatibility.  Don't know about `set` and `object`.  I guess
> it's foolish consistency!?

Well originally there was sets.Set (uppercase). It became set when it 
went to being a built-in.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Antoon Pardon
On 2007-04-25, Anton Vredegoor <[EMAIL PROTECTED]> wrote:
> Antoon Pardon wrote:
>
 That's a good point, and also a valid reason for restricting the
 voting community to PSF members. Thanks, Alex.
>>> So in order to avoid a suspicion of a conflict of interest you want to 
>>> turn the whole thing into private property of the PSF?
>>>
>>> That is  the most ridiculous suggestion I have ever
>> 
>> I kind of understand why they would want to do this. If you have
>> no limitations on who may vote, such a contest can easily turn
>> into a contest of who can mobilize the biggest clan of supporters.
>
> Sure, any democratic process can be derailed by a coordinated effort of 
> people with a different mentality. To prevent such things by killing the 
> democratic process oneself right at the beginning of a project is a 
> peculiar way of avoiding this risk.

As far as I understood the idea was to reward excellence. The process
to achieve this can be democratic, but in that case it is just a means
to an end. The democratic process was not an end itself.

So talking about this as if the democratic process itself was somehow
the goal seems to miss what it is about.

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


Re: trinary operator - if then else

2007-04-25 Thread Diez B. Roggisch
Michael >>
>> Does Python 2.4 support it?
> 
> Not precisely, but you can *usually* get away with:
> 
> a and b or c

This is really bad advice, as long as you don't explain why it "usually"
works (and often enough not). This for example won't work:

>>> False or '' and 0
''

The reason is that the if-value has to be bool(v) == True, otherwise the
short-circuiting of the and will prevent the 0 from being returned.

So in general, _don't_ use this!

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


jython: user-defined modules

2007-04-25 Thread Gregor Stich
Dear all,

I hope my question is here in the right place...
What I want to achieve is a communication between Java and Python. We
have a pretty strong framework of existing python scripts and modules.
Now I want to use jython in order to faciliate the communication
between another Java framework.

But I`m currently stuck with jython: Trying to import the user-defined
python modules, these cannot be found. I read a lot about the jython
registry and I setup a $HOME/.jython file where I created a
python.path=... resource, however, when I start the jython command
line and type
print python.path
then this property is not found. Passing it with the -D option does
not work as well, or maybe I`m too confused to make it work anyway?

Any help would be great!
 Best regards
 Greg

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


Re: Now()

2007-04-25 Thread Daniel Nogradi
> I'm using the following function 'str (now)' to place a date time stamp into
> a log file, which works fine, however it writes the stamp like this.
>
> 2007-04-25 11:06:53.873029
>
> But I need to expel those extra decimal places as they're causing problems
> with the application that parses the log data, all I need is something like
> this:
>
> 2007-04-25 11:06:53

Please see http://docs.python.org/lib/module-time.html

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


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Anton Vredegoor
Antoon Pardon wrote:
> On 2007-04-25, Anton Vredegoor <[EMAIL PROTECTED]> wrote:
>> Antoon Pardon wrote:
>>
> That's a good point, and also a valid reason for restricting the
> voting community to PSF members. Thanks, Alex.
 So in order to avoid a suspicion of a conflict of interest you want to 
 turn the whole thing into private property of the PSF?

 That is  the most ridiculous suggestion I have ever
>>> I kind of understand why they would want to do this. If you have
>>> no limitations on who may vote, such a contest can easily turn
>>> into a contest of who can mobilize the biggest clan of supporters.
>> Sure, any democratic process can be derailed by a coordinated effort of 
>> people with a different mentality. To prevent such things by killing the 
>> democratic process oneself right at the beginning of a project is a 
>> peculiar way of avoiding this risk.
> 
> As far as I understood the idea was to reward excellence. The process
> to achieve this can be democratic, but in that case it is just a means
> to an end. The democratic process was not an end itself.

Yes, but this sub thread was about avoiding a suspicion of a conflict of 
interests. If this suspicion is to be avoided by just openly promoting 
the interests of the members of the PSF that is one hell of a way of 
solving the problem.

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


Re: Now()

2007-04-25 Thread Tim Golden
Robert Rawlins - Think Blue wrote:

> I'm using the following function 'str (now)' to place a date time stamp into
> a log file, which works fine, however it writes the stamp like this.

> 2007-04-25 11:06:53.873029

> But I need to expel those extra decimal places as they're causing problems
> with the application that parses the log data, all I need is something like
> this:

> 2007-04-25 11:06:53

> With time depicted to the nearest second, from my background in ColdFusion
> development we used to have a datetimeformat() function that I could use as

> DateTimeFormat(now(), "-mm-dd HH:mm:ss")

> Which would give the current time a mask.

> Any equivalent for this in python?

You want the strftime method which is documented under
the time module.


import datetime
print datetime.datetime.now ().strftime ("%Y-%m-%d etc.")



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


RE: Tutorial creates confusion about slices

2007-04-25 Thread Hamilton, William
> -Original Message-
> From: [EMAIL PROTECTED]
[mailto:python-
> [EMAIL PROTECTED] On Behalf Of Antoon
Pardon
> Sent: Tuesday, April 24, 2007 7:40 AM
> To: [email protected]
> Subject: Re: Tutorial creates confusion about slices
> 
> On 2007-04-24, Michael Bentley <[EMAIL PROTECTED]> wrote:
> >
> > On Apr 24, 2007, at 6:35 AM, Antoon Pardon wrote:
> >
> >> People don't read tutorials in a strictly linear fashion. They can
> >> continue to later subjects and then come back here to see how
things
> >> tie together. So the fact that it is only confusing to those who
> >> know more than is already presented doesn't seem a very good reason
> >> to leave it in.
> >
> > Yet they understand that earlier in the document, there is likely to
> > be a less complete coverage of a given topic.  There is in fact, a
> > link on that page that includes a more complete coverage of that
> > topic (which I mentioned to you in an earlier message IIRC).
> 
> That there is more complete coverage elsewhere is no good reason
> to come with an explanation that suggests things working in
> a way that will be contradicted by that more complete coverage.
> 
> Even after people have read the more complete coverage it is
> still very possible that they will come back to this part of
> the text and get the wrong idea of how things work.

That's how everything I've ever learned has been taught.  Start with a
simple explanation that may not be completely accurate but is
functional, then fill in the details later when there is a context to
put them in.  The tutorial could start out by explaining everything at
the implementation level; it doesn't because it is a _tutorial_,
intended to give new users the context they need to understand the more
complicated nuances of the language.  

If it covered every fiddly little detail, it wouldn't be a tutorial.  It
would be a language reference document instead.

> A more complete coverage elsewhere is not an adequate remedy
> for a tekst suggesting things working differently than they
> actually do. Sure in the long run people will figger out how
> things actually work and that the explanation given in that
> section is totally inadequate for negative steps. But I
> prefer that people don't loose too much time figgering out
> that a particular explanation only works for particular cases
> and not in general.
> 
> > Submit a patch if you want it changed.  I'm sure your valuable
> > insights will greatly improve the quality of the python
documentation.
> 
> Fat chance, if they reason like you.

So you're saying your insights aren't valuable?


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


Re: jython: user-defined modules

2007-04-25 Thread Diez B. Roggisch
Gregor Stich wrote:

> Dear all,
> 
> I hope my question is here in the right place...
> What I want to achieve is a communication between Java and Python. We
> have a pretty strong framework of existing python scripts and modules.
> Now I want to use jython in order to faciliate the communication
> between another Java framework.
> 
> But I`m currently stuck with jython: Trying to import the user-defined
> python modules, these cannot be found. I read a lot about the jython
> registry and I setup a $HOME/.jython file where I created a
> python.path=... resource, however, when I start the jython command
> line and type
> print python.path
> then this property is not found. Passing it with the -D option does
> not work as well, or maybe I`m too confused to make it work anyway?

First of all, you should subscribe to the jython mailing list.

Second, you access the python.path inside jython via

import sys
print sys.path

HTH,

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


Re: [python-advocacy] Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Facundo Batista
2007/4/25, Hendrik van Rooyen <[EMAIL PROTECTED]>:

> Most bugs fixed in the month for the developers?
> (Watch them scrabbling for the easy ones  -  )
>
> Most Patches reviewed and incorporated?

These numbers are easy to acquire.  Note, though, that the name of the
developer in a top ten of these numbers in a public place (like
python.org), and a mention in a weekly report in the main python
mailing lists, will be enough prize most of the times...

Regards,

-- 
.Facundo

Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?

2007-04-25 Thread Neil Cerutti
On 2007-04-24, Thomas Nelson <[EMAIL PROTECTED]> wrote:
> On Apr 23, 10:38 pm, Mel Wilson <[EMAIL PROTECTED]> wrote:
>> Even with a balanced tree, if a key in a node changes value,
>> you may have to re-balance the tree.  Nothing in a Python list
>> says that a dictionary tree would have to be re-balanced if
>> you changed that particular list.
>
> You don't have to look at any implementation.  A dictionary
> maps every key to exactly one object.  If the objects were
> mutable, you could change one key to another key, and then
> which item would the dictionary pull?
> (Imaginary code)
> d = {[1,2,3]: 'hat', [1,2,4]: 'sock' }
> for key in d:
> key.pop()
> print d[[1,2]]  #does this print hat or sock?

That would be documented as undefined behavior, and users
exhorted not to do such things.

Python's dictionaries are a proven winner--I'm definitely not an
advocate for changing them. But the general requirement for a
mapping container *isn't* that keys be immutable, but that you
either don't mutate keys, or don't do so without also reording
(rehashing?) the mapping.

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


Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?

2007-04-25 Thread Steve Holden
Neil Cerutti wrote:
> On 2007-04-24, Thomas Nelson <[EMAIL PROTECTED]> wrote:
>> On Apr 23, 10:38 pm, Mel Wilson <[EMAIL PROTECTED]> wrote:
>>> Even with a balanced tree, if a key in a node changes value,
>>> you may have to re-balance the tree.  Nothing in a Python list
>>> says that a dictionary tree would have to be re-balanced if
>>> you changed that particular list.
>> You don't have to look at any implementation.  A dictionary
>> maps every key to exactly one object.  If the objects were
>> mutable, you could change one key to another key, and then
>> which item would the dictionary pull?
>> (Imaginary code)
>> d = {[1,2,3]: 'hat', [1,2,4]: 'sock' }
>> for key in d:
>> key.pop()
>> print d[[1,2]]  #does this print hat or sock?
> 
> That would be documented as undefined behavior, and users
> exhorted not to do such things.
> 
> Python's dictionaries are a proven winner--I'm definitely not an
> advocate for changing them. But the general requirement for a
> mapping container *isn't* that keys be immutable, but that you
> either don't mutate keys, or don't do so without also reording
> (rehashing?) the mapping.
> 
And which API do you use to "reord(er?) (rehash) the mapping"?

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Tutorial creates confusion about slices

2007-04-25 Thread Steve Holden
Antoon Pardon wrote:
> On 2007-04-25, Ant <[EMAIL PROTECTED]> wrote:
>> On Apr 23, 1:38 pm, Antoon Pardon <[EMAIL PROTECTED]> wrote:
>>> The following is part of the explanation on slices in the
>>> tutorial:
>>>
>>> The best way to remember how slices work is to think of the indices as
>> ...
>>>   +---+---+---+---+---+
>>>   | H | e | l | p | A |
>>>   +---+---+---+---+---+
>>>   0   1   2   3   4   5
>>>  -5  -4  -3  -2  -1
>> For a tutorial this is sound advice. A tutorial is designed to give
>> readers an easy intro to a topic, which is what this achieves. At this
>> stage the target audience has no idea that extended slices even exist,
>> let alone that you can use negative indices with them.
> 
> OK. But eventually they will come into contact with negative indexes.
> If they still rely on the above representation for understanding slices
> that may cause confusions. It is possible that the time lost in clearing
> up these later confusions will be bigger than the time gained by using
> this simplification in the tutorial.
> 
> So I'm not so sure it is sound advice in this case.
> 
> If the consensus is that something like this should remain, I would
> suggest replacing:
> 
> "The best way to remember how slices work is"
> 
> with:
> 
> "A way to remember how slices work, it is not entirly correct
>  but may be usefull, is"
> 
> Or something similar.
> 
> 
> Wording to that effect makes it more clear that it is a crutch
> that can be usefull now but that it should be discarded later.
> 
Most people reading a tutorial are aware that they are being given the 
knowledge they need to put the subject matter to immediate use, and that 
there may well be refinements that are glossed over or covered in detail 
later or elsewhere.

I don't believe this needs to be made explicit wherever it applies.

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Socket exceptions aren't in the standard exception hierarchy

2007-04-25 Thread Steve Holden
John Nagle wrote:
> Steve Holden wrote:
>> John Nagle wrote:
>>
>>> Steve Holden wrote:
>>>
 John Nagle wrote:
 [socket.error bug report]
> 
>> All these notes should be included in the bug report, as I suspect the 
>> module would benefit from additional clarity. 
> 
>  Done.  See
> 
> [ 1706815 ] socket.error exceptions not subclass of StandardError
> 
> Also see
> 
> [ 805194 ] Inappropriate error received using socket timeout
> [ 1019808 ] wrong socket error returned
> [ 1571878 ] Improvements to socket module exceptions
> [ 708927 ] socket timeouts produce wrong errors in win32
> 
> for related but not identical problems in that area.
> 
Thanks. At least this is less likely to be overlooked now.

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread leuchte
So I read quite a few things about this phenomenon in Python 2.4.x but
I can hardly believe that there is really no solution to my problem.

We use a commercial tool that has a macro functionality. These macros
are written in python. So far nothing extraordinary.

Our (python-)macro uses massively nested loops which are unfortunately
necessary. These loops perform complex calculations in this commercial
tool. To give you a quick overview how long this macros runs:

The outer loop takes 5-7 hours for one cycle. Each cycle creates one
outputfile. So we would like to perform 3-5 outer cycles en bloc.
Unfortunately one of our computers (768MB RAM) crashes after just ~10%
of the first cycle with the following error message:

http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg

while another computer (1GB RAM) crashes after ~10% of the fourth
loop. While the virtual memory on the 1gb machine was full to the
limit when it crashed the memory usage of the 768mb machine looked
this this:

http://img2.freeimagehosting.net/uploads/dd15127b7a.jpg

The moment I close the application that launched the macro, my
ressources get freed.

So is there a way to free my memory inside my nested loops?

thanks in advance,
tim

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


Re: Python un-plugging the Interpreter

2007-04-25 Thread Steve Holden
John Nagle wrote:
> Alex Martelli wrote:
>> Jorgen Grahn <[EMAIL PROTECTED]> wrote:
>>...
>>
 Perhaps the current wave of dual-core and quad-core CPUs in cheap
 consumer products would change people's perceptions -- I wonder...
> 
>> IronPython would appear to be coming along nicely and getting acceptance
>> in the Windows community, and I believe the underlying dotNet CLR does
>> do threads nicely; we'll see what develops on that front, I guess.
> 
>  Thus we now have a demonstration that Python implementations need
> not be as slow as CPython.  And that Microsoft is beating open source
> on Python.
> 
Well, let's remember that a) IronPython was originally developed 
independently of Microsoft, and b) it's still open source or close to it 
(I.'m not familiar with the OSI's opinion on the license Microsoft use 
to distribute IronPython, but the fact it can be included in the FePy 
distribution bodes well).

>  Python as a language is in good shape.  But the CPython
> implementation is holding back progress.   What we need are better
> and faster implementations of the language we've got.
> 
Hear, hear!

>  PyPy, ShedSkin, and Jython all were steps in the right
> direction, but none had enough momentum to make it.
> Jython hasn't had a release since 2002, ShedSkin is basically
> one guy, and the EU pulled the plug on PyPy.
> 
Hey there, loose talk costs lives, you know. That is a complete 
mischaracterization of the true position.

Progress on Jython may not have been stellar, but it has occurred and is 
ongoing. Yes, Shedskin is "one guy", but so was Psyco and that was (and 
remains) a useful tool.

As far as I am aware the PyPy project has come to the end of its initial 
EU funding, and they chose to focus on producing deliverables close to 
the end of the project phase rather that divert effort into securing 
ongoing funding. So nobody has "pulled the plug", and I believe there is 
every possibility of a further round of funded research and development 
  in the future. Certainly the results to date would justify that action 
on the part of the EU. I don't know if and when the request for further 
funding will be submitted.

>  Now what?
> 
Work continues. Rome wasn't built in a day, you know.

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Tutorial creates confusion about slices

2007-04-25 Thread Duncan Booth
Steve Holden <[EMAIL PROTECTED]> wrote:

>> Wording to that effect makes it more clear that it is a crutch
>> that can be usefull now but that it should be discarded later.
>> 
> Most people reading a tutorial are aware that they are being given the 
> knowledge they need to put the subject matter to immediate use, and that 
> there may well be refinements that are glossed over or covered in detail 
> later or elsewhere.

The authors of 'The Science of Discworld' coined a term for this 'lies to 
children' where an explanation to a student is technically wrong but is 
pitched at the appropriate level for the student.

See http://en.wikipedia.org/wiki/Lie-to-children

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


Re: PIL and font colour

2007-04-25 Thread Steve Holden
Johny wrote:
>  I use PIL to write some text to a picture.The text must  be seen wery
> clearly.
> I write the text to different pictures but to the same position. As
> pictures maybe  different, colour, in the position where I write the
> text, is also different.
> Is there a way how to set the font colour so that it will be seen very
> clearly in the picture?
> For example, if the picture is bright ( for example yellow), the font
> colour should be dark( e.g. black) and vice versa.
> Can anyone help?
> Thanks
> L.
> 
The easy way to ensure this is to paint a background rectangle of an 
appropriate color to ensure good font contrast before writing the text. 
Of course, this obscures rather more of the image in the background than 
you might otherwise.

Apart from that you could try averaging the pixel values in the area you 
are going to paint on, and then choose a font color that contrasts well 
with the average. If there are large variations in color, however, this 
can give disappointing results.

If you'd like to get some insight into color contrast you could do worse 
than start at

   http://wellstyled.com/tools/colorscheme2/index-en.html

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Tutorial creates confusion about slices

2007-04-25 Thread Neil Cerutti
On 2007-04-25, Hamilton, William <[EMAIL PROTECTED]> wrote:
> That's how everything I've ever learned has been taught.  Start
> with a simple explanation that may not be completely accurate
> but is functional, then fill in the details later when there is
> a context to put them in.  The tutorial could start out by
> explaining everything at the implementation level; it doesn't
> because it is a _tutorial_, intended to give new users the
> context they need to understand the more complicated nuances of
> the language.  
>
> If it covered every fiddly little detail, it wouldn't be a
> tutorial.  It would be a language reference document instead.

Presenting a simplified model is a good technique, but when a
simplified model is presented it should be clearly stated wether
or not that model will eventually prove inadequate.

Is the divider-between-elements model presented in the tutorial
really the "best way" to understand half-open range notation?

I vote we change the word "best" to "possible" in the excerpt.

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


Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Durumdara

Hi!

I got same problem with Lotus Domino + Python.
The lotus COM objects are not freed, so I get out from memory.

I solve this problem with a little trick:
I make two py applications. The first is call the second as like another
application.

The first is put some work to the seconds datadir.
Whe second is finished with it, it is close itself.

Because the memory operations are existing in only the second script, all
memory get freed after it is finished, and the first (controller) py script
can call the next session without any problem.

dd

25 Apr 2007 07:08:42 -0700, [EMAIL PROTECTED] <[EMAIL PROTECTED]>:


So I read quite a few things about this phenomenon in Python 2.4.x but
I can hardly believe that there is really no solution to my problem.

We use a commercial tool that has a macro functionality. These macros
are written in python. So far nothing extraordinary.

Our (python-)macro uses massively nested loops which are unfortunately
necessary. These loops perform complex calculations in this commercial
tool. To give you a quick overview how long this macros runs:

The outer loop takes 5-7 hours for one cycle. Each cycle creates one
outputfile. So we would like to perform 3-5 outer cycles en bloc.
Unfortunately one of our computers (768MB RAM) crashes after just ~10%
of the first cycle with the following error message:

http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg

while another computer (1GB RAM) crashes after ~10% of the fourth
loop. While the virtual memory on the 1gb machine was full to the
limit when it crashed the memory usage of the 768mb machine looked
this this:

http://img2.freeimagehosting.net/uploads/dd15127b7a.jpg

The moment I close the application that launched the macro, my
ressources get freed.

So is there a way to free my memory inside my nested loops?

thanks in advance,
tim

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

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

Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Steve Holden
Anton Vredegoor wrote:
> Steve Holden wrote:
>>> When cash is involved, it's important to avoid even the slightest
>>> hint of a suggestion of a suspicion of a conflict of interest; 
>>> that, I guess, is why firms that run contests with cash prizes
>>> always declare employees and their families "not eligible", and why
>>> I think the PSF should do likewise in this case.
>>>
>> That's a good point, and also a valid reason for restricting the
>> voting community to PSF members. Thanks, Alex.
> 
> So in order to avoid a suspicion of a conflict of interest you want to 
> turn the whole thing into private property of the PSF?
> 
> That is  the most ridiculous suggestion I have ever

I presume that interruption came to us courtesy of the PSU?

Since it's the PSF's money I don't see why the voting shouldn't be 
restricted to PSF members. I could be persuaded otherwise, but I haven't 
yet heard anything persuasive. At least most PSF members start out with 
a record of contribution to some aspect of Python, which is the reason 
they were invited to membership in the first place. Or should we ask the 
Perl Foundation to vote on awards too?

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Steve Holden
Anton Vredegoor wrote:
> Antoon Pardon wrote:
> 
 That's a good point, and also a valid reason for restricting the
 voting community to PSF members. Thanks, Alex.
>>> So in order to avoid a suspicion of a conflict of interest you want to 
>>> turn the whole thing into private property of the PSF?
>>>
>>> That is  the most ridiculous suggestion I have ever
>> I kind of understand why they would want to do this. If you have
>> no limitations on who may vote, such a contest can easily turn
>> into a contest of who can mobilize the biggest clan of supporters.
> 
> Sure, any democratic process can be derailed by a coordinated effort of 
> people with a different mentality. To prevent such things by killing the 
> democratic process oneself right at the beginning of a project is a 
> peculiar way of avoiding this risk.
> 
I'm sorry, but while the PSF is a democratically-run organization its 
franchise doesn't extend beyond the membership.

You might as well suggest that America isn't being democratic because it 
doesn't allow the French to vote for its president.

>> Now maybe there are better ways to avoid this kind of unwanted
>> effect but I wouldn't call Steve's suggestion ridiculous.
> 
> It's about as ridiculous as proving that a stiff parrot is dead by 
> grabbing it by the legs and repeatedly hitting it's head on the counter.
> 
So you are now saying my behavior is completely appropriate?

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Steve Holden
Anton Vredegoor wrote:
> Antoon Pardon wrote:
>> On 2007-04-25, Anton Vredegoor <[EMAIL PROTECTED]> wrote:
>>> Antoon Pardon wrote:
>>>
>> That's a good point, and also a valid reason for restricting the
>> voting community to PSF members. Thanks, Alex.
> So in order to avoid a suspicion of a conflict of interest you want to 
> turn the whole thing into private property of the PSF?
>
> That is  the most ridiculous suggestion I have ever
 I kind of understand why they would want to do this. If you have
 no limitations on who may vote, such a contest can easily turn
 into a contest of who can mobilize the biggest clan of supporters.
>>> Sure, any democratic process can be derailed by a coordinated effort of 
>>> people with a different mentality. To prevent such things by killing the 
>>> democratic process oneself right at the beginning of a project is a 
>>> peculiar way of avoiding this risk.
>> As far as I understood the idea was to reward excellence. The process
>> to achieve this can be democratic, but in that case it is just a means
>> to an end. The democratic process was not an end itself.
> 
> Yes, but this sub thread was about avoiding a suspicion of a conflict of 
> interests. If this suspicion is to be avoided by just openly promoting 
> the interests of the members of the PSF that is one hell of a way of 
> solving the problem.
> 
Perhaps you misunderstood. The quote you were reacting to said """... 
for restricting the *voting* community to PSF members""" (emphasisi 
added here).

In other words, the PSF members get to decide who wins awards, while 
themselves being ineligible. Does this make a difference?

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> So I read quite a few things about this phenomenon in Python 2.4.x but
> I can hardly believe that there is really no solution to my problem.
> 
> We use a commercial tool that has a macro functionality. These macros
> are written in python. So far nothing extraordinary.
> 
> Our (python-)macro uses massively nested loops which are unfortunately
> necessary. These loops perform complex calculations in this commercial
> tool. To give you a quick overview how long this macros runs:
> 
> The outer loop takes 5-7 hours for one cycle. Each cycle creates one
> outputfile. So we would like to perform 3-5 outer cycles en bloc.
> Unfortunately one of our computers (768MB RAM) crashes after just ~10%
> of the first cycle with the following error message:
> 
> http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg
> 
> while another computer (1GB RAM) crashes after ~10% of the fourth
> loop. While the virtual memory on the 1gb machine was full to the
> limit when it crashed the memory usage of the 768mb machine looked
> this this:
> 
> http://img2.freeimagehosting.net/uploads/dd15127b7a.jpg
> 
> The moment I close the application that launched the macro, my
> ressources get freed.
> 
> So is there a way to free my memory inside my nested loops?
> 
> thanks in advance,
> tim
> 
Let's see for this I need to get out my crystal ball...

If it is a commercial application, you should contact their tech
support for a solution.  The problem isn't specifically a Python
problem but rather an implementation problem with their app.

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


Re: gotcha or bug? random state reset on irrelevant import

2007-04-25 Thread Alan Isaac
Alex Martelli said:
> What do you mean?  Just instantiate the random.Random class and you can
> call .seed on it as well as anything else, and no other module will
> infringe on "your" module's Random instance.  The "global functions" of
> module random exist for those who *SPECIFICALLY* want globally shared
> behavior, of course.


I consider this an unduly kind response.
"RTFM" would have been appropriate.

 The functions supplied by this module are actually bound
  methods of a hidden instance of the random.Random class.
 You can instantiate your own instances of Random to get generators that
don't share state.

Sheesh.  I must have been asleep when reading the documentation.

Thanks,
Alan


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


Re: When are immutable tuples *essential*? Why can't you just use lists *everywhere* instead?

2007-04-25 Thread Neil Cerutti
On 2007-04-25, Steve Holden <[EMAIL PROTECTED]> wrote:
> Neil Cerutti wrote:
>> That would be documented as undefined behavior, and users
>> exhorted not to do such things.
>> 
>> Python's dictionaries are a proven winner--I'm definitely not an
>> advocate for changing them. But the general requirement for a
>> mapping container *isn't* that keys be immutable, but that you
>> either don't mutate keys, or don't do so without also reording
>> (rehashing?) the mapping.
>> 
> And which API do you use to "reord(er?) (rehash) the mapping"?

A pretty complex an unnecessary one, I'd guess. ;) Since you
would most likely need to remove the changed key from the
mapping, and then reinsert the new one, it's just as well to
leave the whole process entirely up to the user.

Which is how Python currently works. ;)

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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread TimC
Larry Bates <[EMAIL PROTECTED]> wrote:

> Let's see for this I need to get out my crystal ball...
> 
> If it is a commercial application, you should contact their tech
> support for a solution.  The problem isn't specifically a Python
> problem but rather an implementation problem with their app.
> 
> -Larry

Well one part of the problem maybe really is on the side of this
tool. Because the implementation of the macro functionality is
really crappy. But unfortunately there are no competitive-product
we could switch too, so we have to live with this poor environment.

But I don't think that the WHOLE problem lies inside this tool.
Because I read

http://mail.python.org/pipermail/python-dev/2005-January/051255.html
and
http://evanjones.ca/python-memory.html

Sadly we can't switch from Python 2.4 to 2.5 because this stupid
macro functionality only supports 2.4.x

I really know that all this is not the best setup to get happy with
but there really is no other setup available.

So I'm happy for every input all of you can give me.

greetings,
tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: override settrace

2007-04-25 Thread Steve Holden
Raja wrote:
> Hi,
>   I want to override the sys.settrace() call, create a way to trace
> the execution of a python program. Keep track of all objects created
> and destroyed. Keep track of the call pattern throughout the execution
> of the program and output a simplified "call graph" to standard out.
> Please help me in this regard.
> 
> Thank You,
> 
How many times do you intend to post this question before waiting 
patiently for an answer?

regards
  Steve
-- 
Steve Holden   +1 571 484 6266   +1 800 494 3119
Holden Web LLC/Ltd  http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden
Recent Ramblings   http://holdenweb.blogspot.com

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


Re: Python Screen Scraper

2007-04-25 Thread tstrokes
On Apr 24, 6:17 am, Michael Bentley <[EMAIL PROTECTED]> wrote:
> On Apr 24, 2007, at 11:50 AM, James Stroud wrote:
>
>
>
> > Hello,
>
> > Does anyone know of an example, however modest, of a screenscraper
> > authored in python? I am using Firefox.
>
> > Basically, I am answering problems via my browser and being scored for
> > each problem. I have a tendency to go past my peak for training
> > efficiency, so I would like to scrape the result page for each
> > problem I
> > answer, compile statistics, and have a program alert me when I should
> > stop (based on score and accuracy--assuming training value is
> > related to
> > changes in these metrics).
>
> > I have no idea how to go about writing such a beast and I am hoping
> > that
> > I could get some pointers or an example that could get me going in the
> > right direction.
>
> > Parsing, etc, is not a problem, but I'm not exactly sure how I might
> > interface python with Firefox, forwarding scraped pages to my browser
> > (or forwarding from the browser to the scraper).
>
> > Thanks in advance for any help or advice.
>
> Possibly the easiest thing will be to read from firefox' cache.
> Otherwise I think your only real options are to either build a proxy
> or sniff the wire...

You could try twill
http://twill.idyll.org/python-api.html

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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Chris Mellon
On 25 Apr 2007 15:04:59 GMT, TimC <[EMAIL PROTECTED]> wrote:
> Larry Bates <[EMAIL PROTECTED]> wrote:
>
> > Let's see for this I need to get out my crystal ball...
> >
> > If it is a commercial application, you should contact their tech
> > support for a solution.  The problem isn't specifically a Python
> > problem but rather an implementation problem with their app.
> >
> > -Larry
>
> Well one part of the problem maybe really is on the side of this
> tool. Because the implementation of the macro functionality is
> really crappy. But unfortunately there are no competitive-product
> we could switch too, so we have to live with this poor environment.
>
> But I don't think that the WHOLE problem lies inside this tool.
> Because I read
>
> http://mail.python.org/pipermail/python-dev/2005-January/051255.html
> and
> http://evanjones.ca/python-memory.html
>
> Sadly we can't switch from Python 2.4 to 2.5 because this stupid
> macro functionality only supports 2.4.x
>
> I really know that all this is not the best setup to get happy with
> but there really is no other setup available.
>
> So I'm happy for every input all of you can give me.
>

The problem you're seeing almost certainly isn't related to the memory
arena issues referenced on the list.

"Returning memory to the OS" doesn't affect exhaustion of your virtual
address space. More likely, your nested loops are just creating more
objects than is possible to hold within a single process. That may be
because you're working with very large data sets, or because you have
some sort of ref cycle problem, or simply because you hold onto
references you no longer need. You'll need to do more work to diagnose
the exact details before you can find a fix. Contacting your vendor
support would be a really good first step.

It's possible that you have a degenerate case that triggers some of
the arena problems (like allocation 10 million integers, and then
never using them again), and thats the root of your problem. Without
knowing more about the usage pattern of  your application, theres no
way we can determine that. If you can't upgrade to python 2.5, your
only solution is going to be to rework your algorithm to not do that.
Again, contacting your vendor support is going to be the first step.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: trinary operator - if then else

2007-04-25 Thread Nick Craig-Wood
Diez B. Roggisch <[EMAIL PROTECTED]> wrote:
>  Michael >>
> >> Does Python 2.4 support it?
> > 
> > Not precisely, but you can *usually* get away with:
> > 
> > a and b or c
> 
>  This is really bad advice, as long as you don't explain why it "usually"
>  works (and often enough not). This for example won't work:
> 
> >>> False or '' and 0
> ''

You can use this if you want it to be bullet proof

  (a and [b] or [c])[0]

Not exactly elegant though!

-- 
Nick Craig-Wood <[EMAIL PROTECTED]> -- http://www.craig-wood.com/nick
-- 
http://mail.python.org/mailman/listinfo/python-list


key detect

2007-04-25 Thread Alex Taslab
Hi everybody, does anyone know how to detect a key press from a
keyboard. Well I do know how to do that, but i need to detect just one
press and ignore the others. I mean, my program checks an input from the
outside (a sensor) and i emulate that signal as a keypress, but the
sensor doesn`t send the signal as a unique pulse y just keeps sending
signal during some seconds, so that is like to be pressing one key for a
period of time. How can i take that first press of a key and ignore the
others? I am using pygtk. thanks everybody!


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


Another Python Game Programming Challenge concludes

2007-04-25 Thread ???? ???
The fourth Python Game Programming Challenge (PyWeek) has now concluded 
with
judges (PyWeek being peer-judged) declaring the winners:

  Individual: Which way is up? by Hectigo
http://www.pyweek.org/e/Hectic/

  Team: Bubble Kong by The Olde Battleaxe
http://www.pyweek.org/e/toba4/

Congratulations to them and to the other entrants. You may view the 
complete
listing of entries here:

http://www.pyweek.org/4/entries/

and the scores here:

http://media.pyweek.org/static/pyweek4_ratings.html

and everything else about PyWeek is here:

http://www.pyweek.org/

Before anyone asks, the next challenge will be in 6 months. There is no 
a date
set.


 Richard Jones
 (the PyWeek guy ;)
-- 
http://mail.python.org/mailman/listinfo/python-announce-list

 Support the Python Software Foundation:
 http://www.python.org/psf/donations.html

!DSPAM:462b8a38103129399229859!



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


key detect

2007-04-25 Thread Alex Taslab
Hi everybody, does anyone know how to detect a key press from a
keyboard. Well I do know how to do that, but i need to detect just one
press and ignore the others. I mean, my program checks an input from the
outside (a sensor) and i emulate that signal as a keypress, but the
sensor doesn`t send the signal as a unique pulse y just keeps sending
signal during some seconds, so that is like to be pressing one key for a
period of time. How can i take that first press of a key and ignore the
others? I am using pygtk. thanks everybody!


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


gcov-like python code coverage

2007-04-25 Thread mathieu
Just in case something already exist for this. Is there some tool,
that can produce gcov-type coverage out of a python code ?

I have an already existing regex code that turn gcov output into XML,
which I'd like to reuse.

thanks !
-Mathieu

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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Grant Edwards
On 2007-04-25, Chris Mellon <[EMAIL PROTECTED]> wrote:

> "Returning memory to the OS" doesn't affect exhaustion of your virtual
> address space. More likely, your nested loops are just creating more
> objects than is possible to hold within a single process.

I'm a bit fuzzy on this, but I don't think there _is_ a
practical way to "return memory to the OS" in many OSes.  For
example in Unix the C library uses the sbrk() call to increase
the size of the data segment when additional memory is needed
to handle soemthing like malloc() calls.  

In theory, one can use brk() to reduce the size of the data
segment, but I think making the segment smaller will produce
undefined behavior if any of the standard C library's dynamic
memory routines (e.g. malloc/free) have ever been used by the
program prior to the call to brk().

-- 
Grant Edwards   grante Yow! FEELINGS are cascading
  at   over me!!!
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Advocacy: "Python up, Ruby down".

2007-04-25 Thread Terry Reedy

"Paddy" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I found this blog post on one users migration to Python. It states one
| users frustrations but the comments section is quite good too.
|
| 
http://blog.cbcg.net/articles/2007/04/22/python-up-ruby-down-if-that-runtime-dont-work-then-its-bound-to-drizzown
|
| The time and effort the developers spend on the balance between fixing
| what we have over adding new features is hard, but it did pay off for
| this programmer who was lured over by a more robust implementation and
| good documentation.

I think the author should be invited to contribute a Python Success Story 
for the site!

Definitely worth reading.

tjr



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


Re: popen2 results

2007-04-25 Thread Steven Howe

Robert Rawlins - Think Blue wrote:

Hello guys,

 


I've recently ported my application from bash to python, however there are
still a few bash line utilities I -have- to use in the application as there
isn't any alternative available to me. In the old days of bash I would have
grep'd the output from these commands to determine the outcome.

 


I'm now using popen2 to run the command which works a charm, but I'm
struggling to parse the results of the function, has anyone had any
experience with this? I've found a few suggested solutions dotted around,
such as this one.

 


 import os

 


 def filtered(command, source):

 dest, result = os.popen2(command)

 dest.write(source)

 dest.close()

 try:

  return result.read()

 finally:

  result.close()

 


But to be honest I'm struggling to get it to do anything as it doesn't
states what the 'source' object is or should be.

 


Thanks for any help guys, I'm just looking to capture the output from the
command and then I can go about a little REGEX on it.

 


Thanks,

 


Rob


  
check out os.popen3 as well. An Example? Let's assume you were doing 'ls 
-1', which at the
console would give you a one column list of files (and yes, I know I can 
use glob.glob for this;

this is an example).

   from os import popen3
   ( sin, sout, serr ) = popen3( 'ls -1 /tmp' )
   fList = sout.readlines()
   for f in fList:
   print f
   errors = serr.readlines()
   for line in errors:
   print line


Now you have 3 file handles.
sin: input (which I've never used, as I give popen3 a complete command)
sout: the standard output stream
serr: the standard error output
You can read sout and serr and take action on them.
Oh and each line has a '\n' linefeed (probably '\r\n' on Windows). 
Depending on what your doing
with the output, you might want to use string.strip to eliminate the 
linefeeds.


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

Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Steven Howe
Grant Edwards wrote:
> On 2007-04-25, Chris Mellon <[EMAIL PROTECTED]> wrote:
>
>   
>> "Returning memory to the OS" doesn't affect exhaustion of your virtual
>> address space. More likely, your nested loops are just creating more
>> objects than is possible to hold within a single process.
>> 
>
> I'm a bit fuzzy on this, but I don't think there _is_ a
> practical way to "return memory to the OS" in many OSes.  For
> example in Unix the C library uses the sbrk() call to increase
> the size of the data segment when additional memory is needed
> to handle soemthing like malloc() calls.  
>
> In theory, one can use brk() to reduce the size of the data
> segment, but I think making the segment smaller will produce
> undefined behavior if any of the standard C library's dynamic
> memory routines (e.g. malloc/free) have ever been used by the
> program prior to the call to brk().
>
>   
Interesting questions. What happens when an object is 'cleaned' up by
using the 'del' command. Does the memory space stay in the python
process, get handed back to the OS, or some combination of both?
I remember 'C' on VMS at least, could be coerced into return memory on
block boundaries. 'C++' was suppose to have garbage collect, but I was
always doubtful it worked well.

sph

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


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Terry Reedy

"Steve Holden" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| Since it's the PSF's money I don't see why the voting shouldn't be
| restricted to PSF members.

Legally, I believe it *is* that way.  And even as a non-member, I think it 
should be that way.  Any expression of opinions, through a straw poll, or 
otherwise, is advisory.

tjr



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


Re: q: how to output a unicode string?

2007-04-25 Thread Frank Stajano
Diez B. Roggisch wrote:
>> So why is it that in the first case I got UnicodeEncodeError: 'ascii'
>> codec can't encode? Seems as if, within Idle, a utf-8 codec is being
>> selected automagically... why should that be so there and not in the
>> first case?
> 
> I'm a bit confused on what you did when the error appears if you try to
> output a unicode-object without prior encoding - then the default encoding
> (ascii) is used.

Here's a minimal example for you.
I put these four lines into a utf-8 file.

# -*- coding: utf-8 -*-
# this file is called t3.py
s1 = u"héllô wórld"
print s1


If I invoke "python t3.py" at the cygwin/rxvt/bash prompt, I get:

Traceback (most recent call last):
   File "t3.py", line 4, in 
 print s1
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe9' in 
position 1: ordinal not in range(128)

If I load the exact same file in Idle and press F5 (for Run), I get:

héllô wórld

So obviously "the system" is not behaving in the same way in the two 
cases. Maybe Python senses that it can do utf-8 when it's inside Idle 
and sets the default to utf-8 without me asking for it, and senses that 
it can't do (or more precisely output) utf-8 when it's in 
cygwin/rxvt/bash so there it sets the default codec to ascii. That's my 
best guess so far...

I find the encode/decode terminology somewhat confusing, because 
arguably both sides are "encoded". For example, a unicode-encoded string 
(I mean a sequence of unicode code points) should count as "decoded" in 
the terminology of this framework, right?

Anyway, thanks again for your help, for deepening my modest 
understanding of the issue and for solving my original problem!
-- 
http://mail.python.org/mailman/listinfo/python-list


Bibus/python locale not supported problem

2007-04-25 Thread Tom Chilton

Hi,

I am running Gentoo Linux. 

I have emerge'd Bibus and everything seemed to go well. 
When I try to start it from a shell I get:

[EMAIL PROTECTED] ~ $ bibus
Traceback (most recent call last):
  File "/usr/share/bibus/bibus.py", line 63, in ?
locale.setlocale(locale.LC_ALL,'en_US') #
use english if any problem
  File "/usr/share/bibus/locale.py", line 381, in setlocale
return _setlocale(category, locale)
locale.Error: unsupported locale setting

and it does not run.

Can anyone suggest why?

I am in the UK and where I get the option I choose en_GB.
If this isn't a python problem sorry for bothering you all...

I am not subscribed to this list but I will check nabble for replies.

Thanks
Tom
-- 
View this message in context: 
http://www.nabble.com/Bibus-python-locale-not-supported-problem-tf3646227.html#a10183538
Sent from the Python - python-list mailing list archive at Nabble.com.

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


lowercase class names, eg., qtgui ? (PyQt4)

2007-04-25 Thread Glen
Hello,

In the file generated by pyuic4 from Designer's .ui file I noticed the use
of lower case class names (I'm assuming these are the names of classes,
not modules).  For example:

It imports thusly:

from PyQt4 import QtGui

then uses things like:
self.gridlayout = qtgui.qgridlayout(dldialog)

What exactly is going on here?  Are these instances that are defined
somewhere else (their not in the local scope.)? Can I do the same in my
code when I import something?

Thanks,

Glen

Glen

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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Donald 'Paddy' McCarthy
[EMAIL PROTECTED] wrote:
> So I read quite a few things about this phenomenon in Python 2.4.x but
> I can hardly believe that there is really no solution to my problem.
> 
> We use a commercial tool that has a macro functionality. These macros
> are written in python. So far nothing extraordinary.
> 
> Our (python-)macro uses massively nested loops which are unfortunately
> necessary. These loops perform complex calculations in this commercial
> tool. To give you a quick overview how long this macros runs:
> 
> The outer loop takes 5-7 hours for one cycle. Each cycle creates one
> outputfile. So we would like to perform 3-5 outer cycles en bloc.
> Unfortunately one of our computers (768MB RAM) crashes after just ~10%
> of the first cycle with the following error message:
> 
> http://img2.freeimagehosting.net/uploads/7157b1dd7e.jpg
> 
> while another computer (1GB RAM) crashes after ~10% of the fourth
> loop. While the virtual memory on the 1gb machine was full to the
> limit when it crashed the memory usage of the 768mb machine looked
> this this:
> 
> http://img2.freeimagehosting.net/uploads/dd15127b7a.jpg
> 
> The moment I close the application that launched the macro, my
> ressources get freed.
> 
> So is there a way to free my memory inside my nested loops?
> 
> thanks in advance,
> tim
> 

Could you split the program into one handling the outer loop and
calling another program, with data transfer, to handle the inner
loops?

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


Re: q: how to output a unicode string?

2007-04-25 Thread Richard Brodie

"Frank Stajano" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]

> I find the encode/decode terminology somewhat confusing, because arguably 
> both sides are 
> "encoded". For example, a unicode-encoded string (I mean a sequence of 
> unicode code 
> points) should count as "decoded" in the terminology of this framework, right?

Yes. Unicode is the one true Universal Character Set, and everything else
(including  ASCII and UTF-8) is a mere encoding. Once you've got your head
round that, things may make more sense. 


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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Grant Edwards
On 2007-04-25, Steven Howe <[EMAIL PROTECTED]> wrote:

>> I'm a bit fuzzy on this, but I don't think there _is_ a
>> practical way to "return memory to the OS" in many OSes.  For
>> example in Unix the C library uses the sbrk() call to increase
>> the size of the data segment when additional memory is needed
>> to handle soemthing like malloc() calls.  
>>
>> In theory, one can use brk() to reduce the size of the data
>> segment, but I think making the segment smaller will produce
>> undefined behavior if any of the standard C library's dynamic
>> memory routines (e.g. malloc/free) have ever been used by the
>> program prior to the call to brk().
>
> Interesting questions. What happens when an object is
> 'cleaned' up by using the 'del' command. Does the memory space
> stay in the python process, get handed back to the OS, or some
> combination of both?

Assuming the python interpreter free()s the memory, my
understanding is that on Unixes the memory is returned to the
pool used by malloc(), but is not returned to the OS since
there isn't a practical way to ensure that the memory at the
"end" of the data segment is not used.

In theory, you could walk the data structures used by
free/malloc and try to figure out if a free() should allow
brk() to be called to reduce the data segment size.  That would
only happen if the free() call was freeing data that was at the
"end" of the data segment.  It's possible that some standard C
libraries do that, but most of what I remember reading implies
that they don't. I don't really keep current on libc details,
so my info might be way out of date.

Asking on the gnu libc mailing list would probably provide a
more authoritative answer.  I'd wager that they even know what
other non-Gnu libc implementations do.

> I remember 'C' on VMS at least, could be coerced into return
> memory on block boundaries.

You can call brk() in a C program to reduce the size of the
data segment, but that may result in free and malloc breakage
because you've returned (behind their back) some of the memory
they are managing.

> 'C++' was suppose to have garbage collect, but I was always
> doubtful it worked well.

-- 
Grant Edwards   grante Yow! Why is everything made
  at   of Lycra Spandex?
   visi.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Screen Scraper

2007-04-25 Thread skotjs
On Apr 24, 5:50 am, James Stroud <[EMAIL PROTECTED]> wrote:
> Hello,
>
> Does anyone know of an example, however modest, of a screenscraper
> authored in python? I am using Firefox.
>
> Basically, I am answering problems via my browser and being scored for
> each problem. I have a tendency to go past my peak for training
> efficiency, so I would like to scrape the result page for each problem I
> answer, compile statistics, and have a program alert me when I should
> stop (based on score and accuracy--assuming training value is related to
> changes in these metrics).
>
> I have no idea how to go about writing such a beast and I am hoping that
> I could get some pointers or an example that could get me going in the
> right direction.
>
> Parsing, etc, is not a problem, but I'm not exactly sure how I might
> interface python with Firefox, forwarding scraped pages to my browser
> (or forwarding from the browser to the scraper).
>
> Thanks in advance for any help or advice.
>
> James

Hey James,

This might be of interest to you: 
http://www.screen-scraper.com/support/docs/scripting_in_python.php

Scott

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


Controlling gnuplot via subprocess.Popen

2007-04-25 Thread Peter Beattie
I am trying to plot something in gnuplot 4.2 using co-ordinates a Python
2.5 program computes. Here's what I'm doing:

py> from subprocess import *
py> plot = Popen("c:/progs/gp/bin/wgnuplot.exe", stdin=PIPE)
py> plot.stdin.write("plot x*x")

The first command dutifully opens gnuplot, but the second doesn't do
anything. Could someone favour me with an explanation as to the whyness?

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


File not read to end

2007-04-25 Thread andrew . jefferies
Hi,

I'm trying to write a simple log parsing program. I noticed that it
isn't reading my log file to the end.

My log is around 200,000 lines but it is stopping at line 26,428. I
checked that line and there aren't any special characters.

This is the file reading code segment that I'm using:
sysFile=open(sysFilename,'r')
lineCount = 0
for line in sysFile:
lineCount +=1
print str(lineCount) + " -- " + line

I also stuck this same code bit into a test script and it was able to
parse the entire log without problem. Very quirky.

This is my first foray from Perl to Python so I appreciate any help.

Thanks in advance.

--Andrew

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


Re: File not read to end

2007-04-25 Thread Larry Bates
[EMAIL PROTECTED] wrote:
> Hi,
> 
> I'm trying to write a simple log parsing program. I noticed that it
> isn't reading my log file to the end.
> 
> My log is around 200,000 lines but it is stopping at line 26,428. I
> checked that line and there aren't any special characters.
> 
> This is the file reading code segment that I'm using:
> sysFile=open(sysFilename,'r')
> lineCount = 0
> for line in sysFile:
> lineCount +=1
> print str(lineCount) + " -- " + line
> 
> I also stuck this same code bit into a test script and it was able to
> parse the entire log without problem. Very quirky.
> 
> This is my first foray from Perl to Python so I appreciate any help.
> 
> Thanks in advance.
> 
> --Andrew
> 

Show us more of your surrounding code so we have some chance of figuring
out why this working code stops.  There's nothing wrong with this code,
the problem is somewhere else.

Suggestion:

lineCount = 0
for line in sysFile:
lineCount +=1
print str(lineCount) + " -- " + line

can be written:

for lineCount, line in enumerate(sysFile):
print "%i--%s" % (lineCount, line)



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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread Donn Cave
In article <[EMAIL PROTECTED]>,
 Steven Howe <[EMAIL PROTECTED]> wrote:

> Interesting questions. What happens when an object is 'cleaned' up by
> using the 'del' command. Does the memory space stay in the python
> process, get handed back to the OS, or some combination of both?
> I remember 'C' on VMS at least, could be coerced into return memory on
> block boundaries. 'C++' was suppose to have garbage collect, but I was
> always doubtful it worked well.

Note that UNIX (and VMS) use "virtual" memory.  Real memory
space gets "handed back to the OS" by default -- if you don't
use it, you lose it.  It isn't coercion, but it does happen on
a per page basis, so fragmentation wastes space.

If a Python program uses more space than it ought to need, then
some knowledge of Python's reference counting allocation scheme
will be useful.  In particular, you need a fairly good grasp of
what a "reference" is.

   Donn Cave, [EMAIL PROTECTED]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: File not read to end

2007-04-25 Thread Facundo Batista
[EMAIL PROTECTED] wrote:

> My log is around 200,000 lines but it is stopping at line 26,428. I
> checked that line and there aren't any special characters.

Are you in Windows? Just in case, put "rb" as the mode of the open.

Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/


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


Re: Would You Write Python Articles or Screencasts for Money?

2007-04-25 Thread Anton Vredegoor
Steve Holden wrote:

> I'm sorry, but while the PSF is a democratically-run organization its 
> franchise doesn't extend beyond the membership.

I didn't realize this was about an PSF internal affair. Of course a 
group of people can decide on its internal matters without asking anyone 
else, as long as its actions do not damage the larger community around 
it. I'm sorry to have interfered with your private discussions, they 
took place on an international newsgroup aimed at the global python 
community at large, you might consider taking it elsewhere, but since 
there is no moderation, go and spam this group with your posts as much 
as you like.

> You might as well suggest that America isn't being democratic because it 
> doesn't allow the French to vote for its president.

Neither France nor America strike me as being very democratic at the 
moment, because large parts of their communities have no way of voting 
on a person or party that represents their specific interests. It's the 
same way in the Netherlands where I live by he way, so no criticism is 
intended by me, in any way.

I was picturing this thread more in terms like the international court 
which at least constitutionally *tries* to be democratic in a global 
community alike manner, albeit unfortunately also failing miserably.

It seems current western democracies are preferable over the total chaos 
that we see in Iraq because its internal legal structure was removed 
without providing a functional alternative. History shows -to me- that 
even an evil dictator is better than that. That doesn't mean people 
shouldn't try to aim higher. Higher than accepting even a benevolent 
dictator.

So in my case the question becomes if I would be willing to promote the 
interests of some group that doesn't represent me, for a chance that I 
may comply with their objectives, which I cannot influence. I'd say: No 
I don't want to do that, although I also wouldn't go out of my way in 
order to *not* comply.

Thanks for clearing it all up. Have a nice life.

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


Re: KOREAN MOON revolves around BUSH

2007-04-25 Thread Major Quaternion Dirt Quantum
"Global Warning,"
an *anonymous* article in an old issue of *National Review*,
the so-called conservative mag of the grotesque Establishment
creature,
William Buckley, was a sort of benignly-spun expose
of the Mont Pelerin Society, the vehicle of British imperialist "free
trade,"
free beer & free dumb, whose many "rightwing" affiliate foundations
are always in the news.  the universally-newspaper-lauded-when-
he-died founding president, Mitlon Friedman,
used Sir Henry of Kiss.Ass. to conduct their first experiment
in Chile, with the help of Augusto Pinochet & Dick Nixon.

(the fact that it was an awful failure, with the privatization
of Chile's social security, was only recently mention, but
only before Uncly Milty died.)

I realized, much later, since it was anonymous, that
it was probably taken from The Holy Spook Economist, but
I haven't checked that hypothesis.

yes, "Warning" was meant to evoke "warming," although
nowhere mentioned in the article, as I recall; can you say,
"emmissions trading schemes," Boys and Girl?

can you say, "hedge funds on out-of-the-way desert islands?"

Just Desserts Island

thus:
Kucinich is reportedly presenting a bill of impeachment
for Trickier Dick Cheeny, today, which may be augmented
by some rules of Congress via the state of Vermont.

now is the time to make him resign!

if you are not a PC Democrat, ask me, How?,
in person.  if you are not a PC Republican, please,
tell the others of the meaning of the word,
republic!

why do Dick, Borat, Osama, Harry P., Rumsfeld and Tony B. want us
to underwrite the 3rd British Invasion of Sudan,
so badly?

which are really fictional British characters?

whwat is the role of the Prime Minister in the Muggles government,
and who is he said to be by The Holy Economist?

anyway, Bertrand Russel published a jeremyad in the Bulletin
of the Atomic Scientists, while the USA was the only thermonukey
power,
that we should bomb them into the Stone Age;
that's your British "pacifist," whether before or after he went nuts
because of Godel's proof.

thus:
if you can't prove that all Fermat numbers are pairwise coprime,
again!

Darfur 'Mini-Summit'
http://www.larouchepub.com/other/1998/rice_2546.html

thus:
uh yeah; Borat wants you in Sudan,
why, Baby?...  Harry Potter wants you in Iran --
yeah, Baby; shag'US with a spoon?

--DARFURIA CONSISTS OF ARABs & nonARABs; NEWS-ITEM:
  we are marching to Darfuria, Darfuria, Darfuria!
Harry Potter IIX, ?Ordeal @ Oxford//Sudan ^ Aircraft Carrier!
http://larouchepub.com/other/2007/3410caymans_hedges.html
ALgoreTHEmovieFORpresident.COM:
http://larouchepub.com/eirtoc/site_packages/2007/al_gore.html?

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


Re: Python not giving free memory back to the os get's me in real problems ...

2007-04-25 Thread TimC
Donald 'Paddy' McCarthy <[EMAIL PROTECTED]> wrote

> Could you split the program into one handling the outer loop and
> calling another program, with data transfer, to handle the inner
> loops?
> 
> - Paddy.

I'm afraid this isn't possible, because the python macro is called
and started from within our commercial tool which leads to the
cirumstance that this tool eats up more and more memory.

Due to the fact that there is no way we can start the tool via
commandline giving an argument that tells the tool it has to
start macroXY.py after startup I don't see a way to lower the
memory usage by splitting it up in two loops.

thanks for all your help so far,
tim
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: script for seconds in given month?

2007-04-25 Thread skip

ed> I, unfortunately, failed to realize the actual platform the script
ed> is for is IronPython.  When trying to import calendar in IronPython,
ed> I get:

ed> SyntaxError: future feature is not defined: with_statement
ed> (c:\Python25\Lib\calendar.py, line 8)

So try the 2.4 version of calendar.py...

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


conditional print statement ?

2007-04-25 Thread Stef Mientki
hello,


As part of a procedure I've a number sequences like this:


 if Print_Info: print Datafile.readline()
 else:Datafile.readline()


Is there a more compressed way to write such a statement,
especially I dislike the redundancy "Datafile.readline()".

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


Re: conditional print statement ?

2007-04-25 Thread Martin v. Löwis
Stef Mientki schrieb:
> hello,
> 
> 
> As part of a procedure I've a number sequences like this:
> 
> 
> if Print_Info: print Datafile.readline()
> else:Datafile.readline()
> 
> 
> Is there a more compressed way to write such a statement,
> especially I dislike the redundancy "Datafile.readline()".

d=Datafile.readline()
if Print_info: print d

It's still two lines, but only has a single call to .readline().

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


bitwise shift?

2007-04-25 Thread desktop
I have found a code example with this loop.

for k in range(10, 25):
   n = 1 << k;


I have never read Python before but is it correct that 1 get multiplied 
with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift 
left by k" which is the same as multiplying with k.
-- 
http://mail.python.org/mailman/listinfo/python-list


Embedding Matplotlib in wxpython wx.Panel problem

2007-04-25 Thread Soren
Hi,

I'm trying to create a small GUI program where I can do plots using
Matplotlib. I've been trying to borrow code from the examples at the
matplotlib website, but I can't get it to work.

I want to be able to create a wx.Panel that contains an axis for
plotting. Around it i want other panels containing various settings,
buttons etc. to control the plot. So far I can't even get the program
to actually show a plot in a panel.

Does anyone here have experience in making a wxpython GUI with
matplotlib?

Any help would be appreciated!

Thanks,
Soren

My code shows a frame, and I'm trying to set up two panels.. one with
a plot and one with a button.. The plotpanel is just a little square
in the corner when I run it.. ???

My code is as follows:

import wx
import pylab
from matplotlib.numerix import arange, sin, cos, pi
import matplotlib

matplotlib.use('WXAgg')
from matplotlib.backends.backend_wxagg import FigureCanvasWxAgg
from matplotlib.backends.backend_wx import NavigationToolbar2Wx
from matplotlib.figure import Figure
matplotlib.interactive(False)

class App(wx.App):

def OnInit(self):
self.frame = MainFrame("Autoplotter", (50,60), (700,700))
self.frame.Show()

return True

class MainFrame(wx.Frame):

def __init__(self, title, pos, size):
wx.Frame.__init__(self, None, -1, title, pos, size)

pPanel = PlotPanel(self, -1)# Plot panel

bPanel = ButtonPanel(self, 100,500, (200,100))# button
panel

sizer = wx.BoxSizer(wx.VERTICAL)

sizer.Add(pPanel,0)
sizer.Add(bPanel,0)

self.SetSizer(sizer)

class ButtonPanel(wx.Panel):

def __init__(self, Parent, xPos, yPos, insize):

pos = (xPos, yPos)
wx.Panel.__init__(self, Parent, -1, pos, style =
wx.RAISED_BORDER, size = insize)

button = wx.Button(self, -1, 'HELLO!!', (10,10), (150,50))

class NoRepaintCanvas(FigureCanvasWxAgg):
"""We subclass FigureCanvasWxAgg, overriding the _onPaint method,
so that
the draw method is only called for the first two paint events.
After that,
the canvas will only be redrawn when it is resized.
"""
def __init__(self, *args, **kwargs):
FigureCanvasWxAgg.__init__(self, *args, **kwargs)
self._drawn = 0

def _onPaint(self, evt):
"""
Called when wxPaintEvt is generated
"""
if not self._isRealized:
self.realize()

if self._drawn < 2:
self.draw(repaint = False)
self._drawn += 1

self.gui_repaint(drawDC=wx.PaintDC(self))


class PlotPanel(wx.Panel):

def __init__(self, parent, id = -1, color = None,\
 dpi = None, style = wx.NO_FULL_REPAINT_ON_RESIZE,
**kwargs):

wx.Panel.__init__(self, parent, id = id, style = style,
**kwargs)

self.figure = Figure(None, dpi)
self.canvas = NoRepaintCanvas(self, -1, self.figure)
self._resizeflag = True

self.Bind(wx.EVT_IDLE, self._onIdle)
self.Bind(wx.EVT_SIZE, self._onSize)

self._SetSize()

def draw(self):   # just draw something!
if not hasattr(self, 'subplot'):
self.subplot = self.figure.add_subplot(111)
theta = arange(0, 45*2*pi, 0.02)
rad = (0.8*theta/(2*pi)+1)
r = rad*(8 + sin(theta*7+rad/1.8))
x = r*cos(theta)
y = r*sin(theta)
#Now draw it
self.subplot.plot(x,y, '-r')

def _onSize(self, event):
self._resizeflag = True

def _onIdle(self, evt):
 if self._resizeflag:
 self._resizeflag = False
 self._SetSize()
 self.draw()

def _SetSize(self, pixels = None):
"""
This method can be called to force the Plot to be a desired
size, which defaults to
the ClientSize of the panel
"""
if not pixels:
pixels = self.GetClientSize()
self.canvas.SetSize(pixels)
self.figure.set_figsize_inches(pixels[0]/
self.figure.get_dpi(),
pixels[1]/self.figure.get_dpi())


if __name__ == "__main__":

app = App(0)
app.MainLoop()

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


Re: bitwise shift?

2007-04-25 Thread Michael Hoffman
desktop wrote:
> I have found a code example with this loop.
> 
> for k in range(10, 25):
>   n = 1 << k;
> 
> 
> I have never read Python before but is it correct that 1 get multiplied 
> with the numbers 10,11,12,12,...,25

No.

> assuming that 1 << k means "1 shift left by k"

Yes.

> which is the same as multiplying with k.

No.

Try starting the Python interpreter and entering 1 << 10.
-- 
Michael Hoffman
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: getting scancodes

2007-04-25 Thread faulkner
On Apr 23, 8:39 pm, [EMAIL PROTECTED] wrote:
> Anyone knows if its possible to get scan codes ???
> I tried with getch () but with no success, just keycodes.
> May be using the something in the sys.stdin module ??

is this what you're looking for?
http://cheeseshop.python.org/pypi/sysio/1.0

and sys.stdin isn't a module. it's a file.

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


Re: bitwise shift?

2007-04-25 Thread Jean-Paul Calderone
On Wed, 25 Apr 2007 22:54:12 +0200, desktop <[EMAIL PROTECTED]> wrote:
>I have found a code example with this loop.
>
>for k in range(10, 25):
>   n = 1 << k;
>
>
>I have never read Python before but is it correct that 1 get multiplied
>with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift
>left by k" which is the same as multiplying with k.

No.

http://python.org/doc/ref/shifting.html

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


Re: bitwise shift?

2007-04-25 Thread Thomas Krüger
desktop schrieb:
> I have found a code example with this loop.
> 
> for k in range(10, 25):
>   n = 1 << k;
> 
> 
> I have never read Python before but is it correct that 1 get multiplied
> with the numbers 10,11,12,12,...,25 assuming that 1 << k means "1 shift
> left by k" which is the same as multiplying with k.


1 << n
is a more efficient replacement for
2**n

Thomas

-- 
sinature: http://nospam.nowire.org/signature_usenet.png
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: bitwise shift?

2007-04-25 Thread Sherm Pendley
desktop <[EMAIL PROTECTED]> writes:

> for k in range(10, 25):
>   n = 1 << k;
>
> I have never read Python before but is it correct that 1 get
> multiplied with the numbers 10,11,12,12,...,25 assuming that 1 << k
> means "1 shift left by k" which is the same as multiplying with k.

Shift left is *not* the same as multiplying by k. It is the same as multi-
plying by 2^k. That is, 1<<10 = 1024, 1<<11 = 2048, 1<<12 = 4096, etc.

sherm--

-- 
Web Hosting by West Virginians, for West Virginians: http://wv-www.net
Cocoa programming in Perl: http://camelbones.sourceforge.net
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Controlling gnuplot via subprocess.Popen

2007-04-25 Thread Ben C
On 2007-04-25, Peter Beattie <[EMAIL PROTECTED]> wrote:
> I am trying to plot something in gnuplot 4.2 using co-ordinates a Python
> 2.5 program computes. Here's what I'm doing:
>
> py> from subprocess import *
> py> plot = Popen("c:/progs/gp/bin/wgnuplot.exe", stdin=PIPE)
> py> plot.stdin.write("plot x*x")
>
> The first command dutifully opens gnuplot, but the second doesn't do
> anything. Could someone favour me with an explanation as to the whyness?

I think it may just be that you need a newline after "plot x*x", i.e.

plot.stdin.write("plot x*x\n")

or

print >>plot.stin, "plot x*x"

But some interactive programs need to be controlled with expect rather
than just writing to their stdin. I'm unclear of the details, perhaps
it's just ones that use curses in some form.

I usually write the gnuplot commands to a file, and then use
os.system("gnuplot plot.gpi") to run gnuplot in batch mode (or gnuplot
-persist if you want the window). You can also use Popen instead of
os.system.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Tutorial creates confusion about slices

2007-04-25 Thread Ant
On Apr 23, 1:38 pm, Antoon Pardon <[EMAIL PROTECTED]> wrote:
> The following is part of the explanation on slices in the
> tutorial:
>
> The best way to remember how slices work is
...
>   +---+---+---+---+---+
>   | H | e | l | p | A |
>   +---+---+---+---+---+
>   0   1   2   3   4   5
>  -5  -4  -3  -2  -1
>
> This is all very well with a simple slice like:
>
>   "HelpA"[2:4]=> "lp"
>
> But it give the wrong idea when using the following extended slice:
>
>   "HelpA"[4:2:-1]   =>   "Ap"

I think that the tutorial example is absolutely fine as it is. It
gives the new python programmer (the target demographic of the
tutorial) a visual tool to understand what simple slicing is. Extended
slicing (in particular ones using negative indices) are beyond the
scope of the tutorial, and thus are irrelevant as far as the example
goes.

Adding examples / memory aids to cover all the many varied and
possibly degenerate ways you can slice a string would merely confuse
the python newbie. By the time you actually *are* interested in the
more advanced slicing capabilities, it's time to read the Library
reference where the formula stating *exactly* how slicing works is
stated.

A tutorial has every reason to be simplistic, so as far as I'm
concerned, -1 for changing the docs.

Apologies if this turns out to be my third near identical post - I've
tried sending variations on this message twice already today from
Google Groups, and they seem to have got lost in the ether...


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


Re: Another Python Game Programming Challenge concludes

2007-04-25 Thread Terry Reedy

" ???" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
| The fourth Python Game Programming Challenge (PyWeek) has now concluded
| with
| judges (PyWeek being peer-judged) declaring the winners:
|
|  Individual: Which way is up? by Hectigo
|http://www.pyweek.org/e/Hectic/
|
|  Team: Bubble Kong by The Olde Battleaxe
|http://www.pyweek.org/e/toba4/

404 Not found

Ditto for links on rating page.

|
| and the scores here:
|http://media.pyweek.org/static/pyweek4_ratings.html

tjr



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


Re: bitwise shift?

2007-04-25 Thread Terry Reedy

"desktop" <[EMAIL PROTECTED]> wrote in message 
news:[EMAIL PROTECTED]
|I have found a code example with this loop.
|
| for k in range(10, 25):
|   n = 1 << k;
|
|
| I have never read Python before but is it correct ...

One of the super-nice feature of Python is the interactive mode, also 
available with IDLE and other IDEs. that lets you explore the meaning of 
Python code faster than you can ask here.  Use it and learn.

>>> for k in range(10, 25): print 1 << k

1024
2048
4096
8192
16384
32768
65536
131072
262144
524288
1048576
2097152
4194304
8388608
16777216 



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


  1   2   >