Re: create shell history with python

2009-08-12 Thread garabik-news-2005-05
Diez B. Roggisch  wrote:
> Joel Juvenal Rivera Rivera schrieb:
>> I been thinking how to make a 'bash like history shell' in python,
>> i don't know if with stdin and stdout i can accomplish this or do i
>> need something like curses and stuff like that, anyway im start to
>> figure this out.
>> Does any body has try this? or have any interesting idea?
> 
> Don't waste your time, use IPython :)
> 
> http://ipython.scipy.org/moin/
> 

for python 2.x only, unfortunately

-- 
 ---
| Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
| __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
 ---
Antivirus alert: file .signature infected by signature virus.
Hi! I'm a signature virus! Copy me into your signature file to help me spread!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unrecognized escape sequences in string literals

2009-08-12 Thread Steven D'Aprano
On Tue, 11 Aug 2009 14:48:24 -0700, Douglas Alan wrote:

> In any case, my argument has consistently been that Python should have
> treated undefined escape sequences consistently as fatal errors, 

A reasonable position to take. I disagree with it, but it is certainly 
reasonable.


> not as warnings.

I don't know what language you're talking about here, because non-special 
escape sequences in Python aren't either errors or warnings:

>>> print "ab\cd"
ab\cd

No warning is made, because it's not considered an error that requires a 
warning. This matches the behaviour of other languages, including C and 
bash.



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


Re: hashability

2009-08-12 Thread Asun Friere
On Aug 12, 4:52 pm, James Stroud 
wrote:

> Sorry for being a twit.

Don't be ridiculous.  You haven't been a twit, I have!

I've just had a complete "blonde" moment here (with apologies to any
real blondes out there.  My only excuse is that I've been up to 02:30
for the last three nights running (or maybe it's the ageing process, a
cerebrovascular accident or something).

I just checked a class I recently wrote specifically for the purposes
of hashing a dict (in case I had made this error IRL).  Wouldn't you
know it, it's subclassed to tuple, and defines both __eq__ and
__cmp__.  Luckily when I write production code the guy who knows what
he's doing takes over.  And this in an app which compares keys from
different pickled files (representing DB holdings)?!  Of all things.

I can't believe how unfathomably stupid I've been.  I'm extremely
embarassed.  I think I'll just go out and shoot myself now.  Or get
some sleep.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: ElementTree - Howto access text within XML tag element...

2009-08-12 Thread Stefan Behnel
cmalmqui wrote:
> tree = etree.parse('10_07_2009 16_48_00_history.tcx')
> root = tree.getroot()
> 
> elem = root[0][0]
> 
> # iterate over all laps
> for i in range(1, len(elem)-1):

Note that you can iterate over elements as in

for lap_element in elem:
# ...

Then use

record = lap.find("recordtagname")

to find things inside the subtree. You can also use XPath-like expressions
such as

all_intersting_elements =
lap.findall("sometag/somechild//somedescendant")

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


Re: hashability

2009-08-12 Thread Asun Friere
On Aug 12, 5:14 pm, Dennis Lee Bieber  wrote:

> c1 = C()
> c2 = C()
>
> {c1:4}[c2]
>
> to behave? That IS the equivalent of your statement -- two instances are
> two distinctly different entities...
>

Thankyou, that is EXACTLY the mistake I made that sent me off into
lunacy.

At the risk of further embarassment, the answer is that one would
expect it to behave analogously to:

c1 = int(x)
c2 = int(x)

{c1:4}[c2]

Or is my brain still on vacation?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hashability

2009-08-12 Thread James Stroud

Dennis Lee Bieber wrote:

On Tue, 11 Aug 2009 17:54:36 -0700, James Stroud 
declaimed the following in gmane.comp.python.general:


   ...
   py> {C():4}[C()]
   
   Traceback (most recent call last):
 File "", line 1, in 
   : <__main__.C object at 0xe21610>

The basis for the exception is that the two instances do not have the 
same hash() although conceptually they might seem equal to the 
unitiated. Were I to re-design python, I'd throw an exception in this 
case because of the ill-defined behavior one might expect if a C() 
serves as a key for a dict.



"A" C()... How would you expect

c1 = C()
c2 = C()

{c1:4}[c2] 


to behave?



This seems like a subjective question. I think I demonstrated how it 
*does* behave, which is purely objective--and I know I can't do anything 
about that. But the subjective answer to the subjective question is that 
I would like an exception to be raised when the dictionary is 
constructed. I know an exception doesn't get thrown in the current 
incarnation of the python language. That is the objective reality of the 
situation which affronts my subjective notions of how reality should be.


That IS the equivalent of your statement -- two instances are

two distinctly different entities...


Tell that to two different machines on two different days. Then bet the 
life of yourself and your nearest and dearest family on that fact and 
see whether you really want to take a hash value for granted. If a 
property of the python language fails the "bet the lives of your nearest 
and dearest on a consistent result" test, I call it "ill defined" and, 
subjectively speaking, I prefer exceptions to be thrown--And, by damned, 
I'll throw them myself if I have to.


"If it saves one life, it's worth it all."

James


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


Re: hashability

2009-08-12 Thread Steven D'Aprano
On Tue, 11 Aug 2009 17:54:36 -0700, James Stroud wrote:

> Hello All,
> 
> I wrote the function to test hashability of arbitrary objects. My reason
> is that the built-in python (2.5) hashing is too permissive for some
> uses. A symptom of this permissiveness comes from the ability to
> successfully hash() arbitrary objects:

No it doesn't.


>>> hash([])
Traceback (most recent call last):
  File "", line 1, in 
TypeError: list objects are unhashable

Python successfully hashes *non*-arbitrary objects, including those that 
inherit from object.



>py> class C(object): pass
>...
>py> {C():4}[C()]
>
>Traceback (most recent call last):
>  File "", line 1, in 
>: <__main__.C object at 0xe21610>

Why would you expect that to succeed? The object you are using as the key 
is a different instance than the object you are looking up. Since your 
instances don't even compare equal, why would you expect them to hash 
equal?

>>> C() == C()
False



> The basis for the exception is that the two instances do not have the
> same hash() although conceptually they might seem equal to the
> unitiated. 

Yes, well, the ignorant and uninitiated frequently make mistakes. I feel 
your pain.



> Were I to re-design python, I'd throw an exception in this
> case because of the ill-defined behavior one might expect if a C()
> serves as a key for a dict.

It's not ill-defined, it's a perfectly reasonable design you just don't 
happen to like. It's quite useful for some.


> To prevent users of one of my libraries from falling into this and
> similar traps (which have potentially problematic consequences), I came
> up with this test for hashability:

That's not a test for hashability. That's a test for hashability and 
equality testing together.


> def hashable(k):
>try:
>  hash(k)
>except TypeError:
>  good = False
>else:
>  good = (hasattr(k, '__hash__') and
>  (hasattr(k, '__eq__') or hasattr(k, '__cmp__')))
>return good

The test for __hash__ is redundant, given that hash() has already 
succeeded.

It will wrongly reject classes that deliberately don't define equality, 
for whatever reason, and that *expect* the behaviour you are treating as 
an error.



> It works as I would like for most of the cases I can invent:
> 
>py> all(map(hashable, [1,1.0,"",(1,2,3)])) True
>py> any(map(hashable, [None, [1,2], {}, C(), __import__('sys')]))
>False

Well there you go -- why on earth would you prohibit None as a dictionary 
key??? That's a serious failure.



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


Re: Unrecognized escape sequences in string literals

2009-08-12 Thread Steven D'Aprano
On Tue, 11 Aug 2009 13:20:52 -0700, Douglas Alan wrote:

> On Aug 11, 2:00 pm, Steven D'Aprano  cybersource.com.au> wrote:
> 
>> > test.cpp:1:1: warning: unknown escape sequence '\y'
>>
>> Isn't that a warning, not a fatal error? So what does temp contain?
> 
> My "Annotated C++ Reference Manual" is packed, and surprisingly in
> Stroustrup's Third Edition, there is no mention of the issue in the
> entire 1,000 pages. But Microsoft to the rescue:
> 
>  If you want a backslash character to appear within a string, you
>  must type two backslashes (\\)
> 
> (From http://msdn.microsoft.com/en-us/library/69ze775t.aspx)

Should I assume that Microsoft's C++ compiler treats it as an error, not 
a warning? Or is is this *still* undefined behaviour, and MS C++ compiler 
will happily compile "ab\cd" whatever it feels like?

 
> The question of what any specific C++ does if you ignore the warning is
> irrelevant, as such behavior in C++ is almost *always* undefined. Hence
> the warning.

So a C++ compiler which follows Python's behaviour would be behaving 
within the language specifications.

I note that the bash shell, which claims to follow C semantics, also does 
what Python does:

$ echo $'a s\trin\g with escapes'
a s rin\g with escapes


Explain to me again why we're treating underspecified C++ semantics, 
which may or may not do *exactly* what Python does, as if it were the One 
True Way of treating escape sequences?


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


Re: better way?

2009-08-12 Thread Pet
On 12 Aug., 09:14, Dennis Lee Bieber  wrote:
> On Tue, 11 Aug 2009 11:45:50 -0700 (PDT), Pet 
> declaimed the following in gmane.comp.python.general:
>
> > Oh, forgotten to mention. It's PostGres
>
>         Really? There are still installations of an RDBMS that predates the
> commonalization of SQL?
>
>         I suspect you mean PostgreSQL -- it IS a different beast from the
> older Postgres.

O, yeah. Of course it is PostgreSQL

>
>         In either event -- my old books don't show an "all in one" solution.
>
>         Best answer is probably to create some stored procedures which you
> call instead of plain INSERT; the stored procedure could then do
> whatever is needed to check for a duplicate (actually the easiest, I'd
> think, would be: if primary key is supplied, it is an UPDATE; if primary
> key is NULL or not supplied, it is an insert and the primary key will be
> auto-generated).

I don't really like the idea of stored procedure, because query would
depend on existence of it then. On the other side, it looks like best
option.

>
> --
>         Wulfraed         Dennis Lee Bieber               KD6MOG
>         [email protected]     HTTP://wlfraed.home.netcom.com/

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


Re: httplib incredibly slow :-(

2009-08-12 Thread Chris Withers

Answering myself...

Chris Withers wrote:

In article ,
Chris Withers   wrote:
Does anyone know of an alternative library for creating http requests 
and getting their responses that's faster but hopefully has a similar 
interface?


PyCurl


This seems to be a wrapper around libcurl.

Does it work on Windows?


Not by my definition of work:

- there are no windows binaries for libcurl

- getting https support on windows seems pretty hit'n'miss:
http://stackoverflow.com/questions/197444/building-libcurl-with-ssl-support-on-windows

I'm still reeling from what seems to be such a huge problem with httplib 
that seem to be largely ignored :-(


Chris

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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Steven D'Aprano
On Tue, 11 Aug 2009 14:50:51 -0700, rurpy wrote:

>>> The issue tracker is fine for many things, but the process it provides
>>> is equivalent to peep-hole optimization.  How does one submit a
>>> tracker issue for something like the overall organization of the docs
>>> (for example, the mis-placement of things like data- types in the
>>> library manual rather than the language manual)?
>>
>> The same way you would submit a tracker issue for anything.
>>
>> "Documentation bug: Data types are misplaced in the library manual
>> instead of the language manual.
>>
>> Suggested alternative: move page docs.python.org/xyz.html to abc.html"
> 
> But that's the problem.  Such a reorg is not a simple matter of moving a
> file from here to there.  It will require a lot moving about of sections
> and a lot of word-smithing to glue them back together again in a
> coherent way.

That's no different from *any* major refactoring. The exact same problem 
exists for code as well as documentation. It's a solved problem for code, 
and it's a solved problem for documentation.

In some order:

Consensus that there is a problem that needs solving;
Volunteer(s) to do the work;
Somebody to take responsibility to check the changes in.


Sometimes, in the face of apathy or disagreement (which may very well be 
justified), you have to at least partly solve the problem *before* people 
will agree that it needed to be solved. Welcome to the real world.



> A tracker issue, even one that was fairly specific about how things
> should be reorganized but which did not provide all the needed changes
> (a large patch) would almost certainly be ignored or rejected.

Yes it would. Most patches are ignored, because the dev team are 
overworked, and if they don't see the need for a patch, they won't 
approve it.



> But
> providing a large patch raises two questions.  How likely is it to be be
> accepted? (Something anyone would want to know before investing the
> time.) And how to actually do the work needed to generate it (it could
> be a very large amount of work for an individual and I don't think it
> can be broken down into small independent issues.) How is one to test
> the waters as to acceptability, or solicit help, if one simply submits a
> tracker issue?

No, submitting a tracker issue is a necessary but not sufficient step. 
Without a tracker issue, you're very unlikely to have people agree to 
replace the existing docs with your docs, although a PEP would probably 
do it. (A PEP is significantly more effort than raising a tracker issue.)

You also have to get attention from those with check-in privileges. If 
they approve your patches, you're done. If they don't approve them, or 
fail to respond, you can try convincing them, or taking it to the Python-
Dev list and request somebody review your patches.

If you have no patches, perhaps because you're unwilling to invest the 
effort without a guarantee that it will be treated seriously, then you 
need to get some sort of consensus among the relevant people that the 
problem is worth solving.

Guess what? Sometimes others will disagree with you. What you see as the 
Worst. Docs. EVAR. may be seen as perfectly adequate, even excellent, by 
others. If this is the case, remember, Python isn't your product, you 
don't have veto over what goes into it. Feel free to publish your 
alternatives. Write a book. Go home and cry into your beer over it. 
Whatever. Sometimes you win, and sometimes you don't.

This is the same process whether dealing with code or documentation.


>> - if people are keen on a Python wiki, then by all means publish one,
>> just don't expect the Python dev team to build and manage it for you;
> 
> As luminous a Pythoneer as Fredrik Lundh set up a documentation wiki to
> collect user contributions but it has faded away.  If he couldn't pull
> it off then I'd say most other attempts without the backing of
> python.org are almost certainly doomed to failure.

Perhaps that's a good indication that a Python wiki *doesn't* fulfill a 
need in the community, and that despite what a few squeaky wheels think, 
the docs *are* doing a good job?



> As long as every "the docs
> sux" complaint is met here with the standard responses that I've
> mentioned, 

But they aren't met with such a so-called "standard response".


> rather than, "yes, they do have some problems, what do you
> think we should do about them?", 

We know that there are problems. We've said repeatedly that corrections 
and patches are welcome. We've repeatedly told you how to communicate 
your answer to the question of what should be done. None of this is good 
enough for you. I don't know what else you expect.


>> If you won't put in the effort, and you won't put in the money, then it
>> won't happen. Moaning that other people aren't putting in the money to
>> hire team of professional writers isn't productive, and moaning that
>> other people aren't putting in the effort to improve the docs isn't
>> either.

Re: Need cleanup advice for multiline string

2009-08-12 Thread Simon Brunning
2009/8/11 Robert Dailey :
> On Aug 11, 3:40 pm, Bearophile  wrote:
>> There are gals too here.
>
> It's a figure of speech. And besides, why would I want programming
> advice from a woman? lol. Thanks for the help.

Give the attitudes still prevalent in our industry (cf
 and many more), I'm sorry to say that I
don't think this is funny.

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


Invitation to connect on LinkedIn

2009-08-12 Thread Jey Simhan
LinkedIn




   
I'd like to add you to my professional network on LinkedIn.

- Jey

Learn more:
https://www.linkedin.com/e/isd/682391381/2q9uIjvU/


 
--
(c) 2009, LinkedIn Corporation

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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Hendrik van Rooyen
On Tuesday 11 August 2009 19:53:16 Steven D'Aprano wrote:

> You want community input into the docs, but you're not willing to give
> that input except to bitch and moan and sook that the tracker is no good.

wtf does the verb  "sook" mean?

I find:

sook
  /sʊk/ Show Spelled Pronunciation [sook] Show IPA
Use sook in a Sentence
–noun
1.  Australia and New Zealand. a timid, cowardly person, esp. a young 
person; 
crybaby.
–interjection
2.  Midland U.S. (used to summon cows from the pasture).
Origin:
1890–95; prob. from earlier sense “calf reared by hand,” perh. suck(-calf), 
with sp. repr. N England, Scots pron. of suck (but earliest cited pron. of 
sook is (so̅o̅k))

Sometimes English drives me crazy.

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


Re: Scraping Wikipedia with Python

2009-08-12 Thread Thorsten Kampe
* Dotan Cohen (Tue, 11 Aug 2009 21:29:40 +0300)
> >    Wikipedia has an API for computer access.  See
> >
> >        http://www.mediawiki.org/wiki/API
> >
> 
> Yes, I am aware of this as well. Does anyone know of a python class
> for easily interacting with it, or do I need to roll my own.

http://pypi.python.org/pypi?%3Aaction=search&term=wikipedia ?

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


Re: looping through values in a dictionary and appending to a list

2009-08-12 Thread Andre Engels
On Tue, Aug 11, 2009 at 8:17 PM, Krishna
Pacifici wrote:
> Nevermind,
> got it.
>
> Sorry.
>
 Krishna Pacifici 08/11/09 2:12 PM >>>
> Hi,
> I want to append the values of a dictionary to a list.  I have a dictionary
> sec_dict_clean and I want to append the values to a list, but am having a
> hard time looping through the values in the dictionary.
>
> I have tried something like this:
> lista=[]
> for i in sec_dict_clean.values():
>     for j in sec_dict_clean.values()[i]:
>         lista.append(sec_dict_clean.values()[i])
>
> But I keep on getting an error:
> TypeError: list indices must be integers
>
> Any ideas on how to loop through values in a dictionary?

lista=[]
for value in sec_dict_clean.values():
lista.append(value)

but even simpler would be:

lista = sec_dict_clean.values()


-- 
André Engels, [email protected]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need cleanup advice for multiline string

2009-08-12 Thread Hendrik van Rooyen
On Tuesday 11 August 2009 22:52:34 Robert Dailey wrote:
> On Aug 11, 3:40 pm, Bearophile  wrote:
> > Robert Dailey:
> > > This breaks the flow of scope. Would you guys solve this
> > > problem by moving failMsg into global scope?
> > > Perhaps through some other type of syntax?
> >
> > There are gals too here.
> > This may
> > help:http://docs.python.org/library/textwrap.html#textwrap.dedent
> >
> > Bye,
> > bearophile
>
> It's a figure of speech. And besides, why would I want programming
> advice from a woman? lol. Thanks for the help.

Well it may come as a surprise to you, but it was a woman who
wrote one of the first compilers.

She became an Admiral in the US navy as a result.

If I recall correctly, her name was Grace Hooper.

How many compilers have you written from scratch,
without a compiler to help you?

:-)

- Hendrik

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


Re: Unrecognized escape sequences in string literals

2009-08-12 Thread Steven D'Aprano
On Tue, 11 Aug 2009 14:29:43 -0700, Douglas Alan wrote:

> I need to preface this entire post with the fact that I've already used
> ALL of the arguments that you've provided on my friend before I ever
> even came here with the topic, and my own arguments on why Python can be
> considered to be doing the right thing on this issue didn't even
> convince ME, much less him. When I can't even convince myself with an
> argument I'm making, then you know there's a problem with it!


I hear all your arguments, and to play Devil's Advocate I repeat them, 
and they don't convince me either. So by your logic, there's obviously a 
problem with your arguments as well!

That problem basically boils down to a deep-seated philosophical 
disagreement over which philosophy a language should follow in regard to 
backslash escapes:

"Anything not explicitly permitted is forbidden"

versus  

"Anything not explicitly forbidden is permitted"

Python explicitly permits all escape sequences, with well-defined 
behaviour, with the only ones forbidden being those explicitly forbidden:

* hex escapes with invalid hex digits;

* oct escapes with invalid oct digits;

* Unicode named escapes with unknown names;

* 16- and 32-bit Unicode escapes with invalid hex digits.

C++ apparently forbids all escape sequences, with unspecified behaviour 
if you use a forbidden sequence, except for a handful of explicitly 
permitted sequences.

That's not better, it's merely different.

Actually, that's not true -- that the C++ standard forbids a thing, but 
leaves the consequences of doing that thing unspecified, is clearly a Bad 
Thing.



[...]

>> Apart from the lack of warning, what actually is the difference between
>> Python's behavior and C++'s behavior?
> 
> That question makes just about as much sense as, "Apart from the lack of
> a fatal error, what actually is the difference between Python's behavior
> and C++'s?"

This is what I get:

[steve ~]$ cat test.cc
#include 
int main(int argc, char* argv[])
{
std::cout << "x\yz" << std::endl;
return 0;
}
[steve ~]$ g++ test.cc -o test
test.cc:4:14: warning: unknown escape sequence '\y'
[st...@soy ~]$ ./test
xyz


So on at least one machine in the world, C++ simply strips out 
backslashes that it doesn't recognise, leaving the suffix. Unfortunately, 
we can't rely on that, because C++ is underspecified. Fortunately this is 
not a problem with Python, which does completely specify the behaviour of 
escape sequences so there are no surprises. 



[...]

>> I disagree with your sense of aesthetics. I think that having to write
>> \\y when I want \y just to satisfy a bondage-and-discipline compiler is
>> ugly. That's not to deny that B&D isn't useful on occasion, but in this
>> case I believe the benefit is negligible, and so even a tiny cost is
>> not worth the pain.
> 
> EXPLICIT IS BETTER THAN IMPLICIT.

Quoting the Zen without understanding (especially shouting) doesn't 
impress anyone. There's nothing implicit about escape sequences. \y is 
perfectly explicit. Look Ma, there's a backslash, and a y, it gives a 
backslash and a y!

Implicit has an actual meaning. You shouldn't use it as a mere term of 
opprobrium for anything you don't like.



>> > (2) That argument disagrees with the Python reference manual, which
>> > explicitly states that "unrecognized escape sequences are left in the
>> > string unchanged", and that the purpose for doing so is because it
>> > "is useful when debugging".
>>
>> How does it disagree? \y in the source code mapping to \y in the string
>> object is the sequence being left unchanged. And the usefulness of
>> doing so is hardly a disagreement over the fact that it does so.
> 
> Because you've stated that "\y" is a legal escape sequence, while the
> Python Reference Manual explicitly states that it is an "unrecognized
> escape sequence", and that such "unrecognized escape sequences" are
> sources of bugs.

There's that reading comprehension problem again.

Unrecognised != illegal.

"Useful for debugging" != "source of bugs". If they were equal, we could 
fix an awful lot of bugs by throwing away our debugging tools.

Here's the URL to the relevant page:
http://www.python.org/doc/2.5.2/ref/strings.html

It seems to me that the behaviour the Python designers were looking to 
avoid was the case where the coder accidentally inserted a backslash in 
the wrong place, and the language stripped the backslash out, e.g.:

Wanted "a\bcd" but accidentally typed "ab\cd" instead, and got "abcd".

(This is what Bash does by design, and at least some C/C++ compilers do, 
perhaps by accident, perhaps by design.)

In that case, with no obvious backslash, the user may not even be aware 
that there was a problem:

s = "ab\cd"  # assume the backslash is silently discarded
assert len(s) == 4
assert s[3] == 'c'
assert '\\' not in s

All of these tests would wrongly pass, but with Python's behaviour of 
leaving the backslash in, they would all fail, and the string is visually 
distinctive

Re: for key, value in dict.() - how to get? (which func)

2009-08-12 Thread Gary Duzan
In article ,
dmitrey   wrote:
>hi all,
>which method should I use to get iterator over (key, value) pairs for
>Python dict, Python v 2.6 and above?

   dict.iteritems()

>>> import sys
>>> for (key, value) in sys.modules.iteritems(): print key, value

Gary Duzan
Motorola H&NM


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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Steven D'Aprano
On Wed, 12 Aug 2009 10:45:51 +0200, Hendrik van Rooyen wrote:

> On Tuesday 11 August 2009 19:53:16 Steven D'Aprano wrote:
> 
>> You want community input into the docs, but you're not willing to give
>> that input except to bitch and moan and sook that the tracker is no
>> good.
> 
> wtf does the verb  "sook" mean?
> 
> I find:
> 
> sook
>   /sʊk/ Show Spelled Pronunciation [sook] Show IPA
> Use sook in a Sentence
> –noun
> 1.Australia and New Zealand. a timid, cowardly person, esp. a young
> person; crybaby.


That's the one. It's also used as a verb.




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


Re: Need cleanup advice for multiline string

2009-08-12 Thread MRAB

Hendrik van Rooyen wrote:

On Tuesday 11 August 2009 22:52:34 Robert Dailey wrote:

On Aug 11, 3:40 pm, Bearophile  wrote:

Robert Dailey:

This breaks the flow of scope. Would you guys solve this
problem by moving failMsg into global scope?
Perhaps through some other type of syntax?

There are gals too here.
This may
help:http://docs.python.org/library/textwrap.html#textwrap.dedent

Bye,
bearophile

It's a figure of speech. And besides, why would I want programming
advice from a woman? lol. Thanks for the help.


Well it may come as a surprise to you, but it was a woman who
wrote one of the first compilers.

She became an Admiral in the US navy as a result.

If I recall correctly, her name was Grace Hooper.


Grace Hopper. The saying "It's easier to ask forgiveness than it is to
get permission" is attributed to her.


How many compilers have you written from scratch,
without a compiler to help you?

:-)



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


matching patterns after regex?

2009-08-12 Thread Martin
Hi,

I have a string (see below) and ideally I would like to pull out the
decimal number which follows the bounding coordinate information. For
example ideal from this string I would return...

s = '\nGROUP  = ARCHIVEDMETADATA\n
GROUPTYPE= MASTERGROUP\n\n  GROUP  =
BOUNDINGRECTANGLE\n\nOBJECT =
NORTHBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
VALUE= 19.82039\nEND_OBJECT =
NORTHBOUNDINGCOORDINATE\n\nOBJECT =
SOUTHBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
VALUE= 9.910197\nEND_OBJECT =
SOUTHBOUNDINGCOORDINATE\n\nOBJECT =
EASTBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
VALUE= 10.6506458717851\nEND_OBJECT =
EASTBOUNDINGCOORDINATE\n\nOBJECT =
WESTBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
VALUE= 4.3188348375893e-15\nEND_OBJECT
= WESTBOUNDINGCOORDINATE\n\n  END_GROUP


NORTHBOUNDINGCOORDINATE = 19.82039
SOUTHBOUNDINGCOORDINATE = 9.910197
EASTBOUNDINGCOORDINATE = 10.6506458717851
WESTBOUNDINGCOORDINATE = 4.3188348375893e-15

so far I have only managed to extract the numbers by doing re.findall
("[\d.]*\d", s), which returns

['1',
 '19.82039',
 '1',
 '9.910197',
 '1',
 '10.6506458717851',
 '1',
 '4.3188348375893',
 '15',
etc.

Now the first problem that I can see is that my string match chops off
the "e-15" part and I am not sure how to incorporate the potential for
that in my pattern match. Does anyone have any suggestions as to how I
could also match this? Ideally I would have a statement which printed
the number between the two bounding coordinate strings for example

NORTHBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
VALUE= 19.82039\nEND_OBJECT =
NORTHBOUNDINGCOORDINATE\n\n

Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
decimal number before it hit the next string
"NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
suggestions would be appreciated.

Many thanks

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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Paul Boddie
On 12 Aug, 09:58, Steven D'Aprano
 wrote:
>
> We know that there are problems. We've said repeatedly that corrections
> and patches are welcome. We've repeatedly told you how to communicate
> your answer to the question of what should be done. None of this is good
> enough for you. I don't know what else you expect.

Maybe the problem is that although everyone welcomes contributions and
changes (or says that they do), the mechanisms remain largely beyond
criticism. Consequently, one sees occasional laments about there not
being enough people contributing to Python core development and soul-
searching about the reasons this might be so. If it were insisted that
changes to, say, Wikipedia were to be proposed by submitting a patch
or report for perusal by the editors and for future inclusion in some
version of the project, the whole project would most likely be a
shadow of its current self, and ambitions of large-scale collaborative
editing in general would still be ridiculed.

A free-for-all isn't likely to be the best solution for more actively
edited Python documentation, but Wiki solutions undeniably provide a
superior "fast path" for edits by trusted users to be incorporated and
published in accessible end-user documentation. Almost every analysis
of the current (and previous) documentation mechanisms has identified
the editorial workflow as a bottleneck and then proceeded to replicate
such a bottleneck in any proposed solution. I'm starting to believe
that there's a certain snobbery about Wiki solutions which lead many
people to develop all sorts of short-term, arcane solutions under the
illusion that something super-special and customised is necessary and
that they have to start virtually from scratch in order to cater to
the ultra-special needs of the target audience; by the time they're
done, no-one's interested any more, except to propose the next legacy
system in the making.

[...]

> > That some of us choose to
> > invest it somewhere other than Python does not deprive of of our right
> > to point out problems in Python when we note them.
>
> Of course not. But it does mean that you won't be taken seriously, and
> you have no right to be taken seriously.

That's an absurd position that has soured the reputation of numerous
projects. When someone spends the time to write a bug report, they are
often investing as much time and effort in something that they are
able to in any productive sense. I make a habit of submitting bug
reports to software distributions, typically so that the people who
are responsible for the components involved can investigate the
problem effectively. When the maintainers just close such reports or
mark them with a number of different labels which mostly indicate that
they consider those reports not worth their time, it sends the message
that they consider their time to be vastly more important than their
users, even though their users might have set aside an hour of their
potentially busy schedule which might have meant sacrificing something
else that should have taken higher priority (like time for sleeping,
in my own personal experience). Thus, I've had the impression with
some projects that I should be maintaining all sorts of stuff - the
bootloader, the kernel, various desktop applications, Mozilla - all so
that stuff actually gets fixed and that I'm not perceived as just
another user whose bug reports aren't welcome. I don't find this
reasonable at all when in many cases there *are* people getting paid
to do these jobs.

The Python core developers seem more attentive than in various other
projects, but please let us not establish the "delicate genius"
mentality that has infested other projects to the point that any
criticism is automatically labelled as ungrateful whining by people
who supposedly don't use the software, have an axe to grind, and who
are apparent simpletons who don't understand the revolutionary vision
of the project leadership. If you think throwing away goodwill is an
acceptable way of silencing complaints, please take a look at just
about any article about KDE 4 that permits reader comments to see how
much goodwill can be lost and what effect that has on a project's
reputation.

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


SQLObject 0.11.0

2009-08-12 Thread Oleg Broytmann
Hello!

I'm pleased to announce version 0.11.0, the first stable release of 0.11 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.11.0

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.10
-

Features & Interface


* Dropped support for Python 2.3. The minimal version of Python for
  SQLObject is 2.4 now.

* Dropped support for PostgreSQL 7.2. The minimal supported version of
  PostgreSQL is 7.3 now.

* New magic attribute 'j' similar to 'q' was added that automagically does
  join with the other table in MultipleJoin or RelatedJoin.

* SQLObject can now create and drop a database in MySQL, PostgreSQL, SQLite
  and Firebird/Interbase.

* Added some support for schemas in PostgreSQL.

* Added DecimalStringCol - similar to DecimalCol but stores data as strings
  to work around problems in some drivers and type affinity problem in
  SQLite.

* Added sqlobject.include.hashcol.HashCol - a column type that automatically
  hashes anything going into it, and returns out an object that hashes
  anything being compared to itself. Basically, it's good for really simple
  one-way password fields, and it even supports the assignment of None to
  indicate no password set. By default, it uses the md5 library for
  hashing, but this can be changed in a HashCol definition.

* RowDestroyedSignal and RowUpdatedSignal were added.

Minor features
~~

* Use reversed() in manager/command.py instead of .__reversed__().

* Minor change in logging to console - logger no longer stores the output
  file, it gets the file from module sys every time by name; this means
  logging will use new sys.stdout (or stderr) in case the user changed
  them.

* Changed the order of testing of SQLite modules - look for external
  PySQLite2 before sqlite3.

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[email protected]
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: adding multiple new values to the same key in a dictionary

2009-08-12 Thread Dave Angel

Dave Angel wrote:

Krishna Pacifici wrote:

Hi,
I want to be able to add multiple new values to a key in a dictionary.

I have tried the following:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}

for i in range(len(sec_dict_clean.values())):
for j in range(len(sec_dict_clean.values()[i])):

sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance) 



where blocks[...].abundance gives me a single value from an object,

but this gives me the following:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 
85, 4, 12, 11, 6, 9, 12, 11, 7, 10, 10, 12, 9, 6, 12, 15, 9, 8, 12, 
15, 12, 12]}


instead I want each abundance (starts with 4, 12...) to be associated 
with each of the values so that it would look like this:


sec_dict_clean=
{88: ([87, 89, 78, 98], [4,12,11,6]), 58: ([57, 59, 48, 68], 
[9,12,11,7]), 69: ([79], [10])...}


You can see there are several errors here (I have more things being 
appended than there are values in the dictionary), but I really just 
want to know how to add multiple values to the same key in a dictionary.


Thanks for any help,
Krishna



  
You're really distorting the purposes of both dictionary and list 
here.  It makes your code totally unreadable, which makes it hard to 
write, and hard to debug.


A dictionary is a mapping between key and value, where each key has 
exactly one value.  You cannot add another one to it.   All you can do 
is make the value something which is itself a collection.  Now, your 
desired dictionary looks achievable, almost.  If you change the parens 
(tuple) to square brackets (list), then it'll work.
   So key 88 has a single value, which is a list of two items.  Each 
of those items is itself a list with 4 items.  And each of those items 
are integers.


But then I got bogged down in your sample code.  I tried to simplify 
it, replacing the first two lines with these three:


for i, key in enumerate(sec_dict_clean):
   val = sec_dict_clean[key]
   for j, xxx in enumerate(val):
   
???sec_dict_clean.setdefault(key,[]).append(blocks[sec_dict_clean.values()[i][j]].abundance) 



But I can't make head nor tail of the third line.  You didn't have a 
variable key, so I don't know if I'm using the same one..  Since I 
can't figure out what you were trying to do, I can't see how to fix it.


I think the problem here is you're trying to reorganize the data as 
well as adding to it, in a single pass.  So is some previous code 
generating the dictionary incorrectly, and instead of fixing that, 
you're trying to reorganize it here?


To make each dictionary value a list of lists:

sec_dict_clean=
{88: [87, 89, 78, 98], 58: [57, 59, 48, 68], 69: [79], 95: [94, 96, 85]}

for key in sec_dict_clean:
   sec_dict_clean[key] = [sec_dict_clean[key]]

now,  the dict looks like:
{88: [[87, 89, 78, 98, 3]], 58: [[57, 59, 48, 68]], 69: [[79]], 95: 
[[94, 96, 85]]}


At this point, if you have some interesting data to add to it, you can 
just append a new list to

dict[key]

In an earlier message, you mentioned fields a and b, and assuming this 
is a similar problem, it would seem that 87 is somehow associated with 
4, and 89 with 12, and so on.  If that's the case, perhaps your 
desired final structure might look more like:


{88: [[87,4], [89,12], [78, 11],[98, 6],   58: [[57, 9], [59, 12], 
[48, 11], [68, 7]],   69: ...}



In this case, the structure is entirely different.  But the approach 
is the same.  And at least you'd be getting closer to the object 
approach where  [87,4] is replaced by an object of some type.


BTW, please don't top-post.  When you reply to this one, put your 
reply at the end, or sometimes interspersed.  But if you put it at the 
beginning, it's out of order.


DaveA




Look at the following (tested in Python 2.6.2).,  There are a number of 
things that could be cleaner, mainly the names of things.  I should 
never be calling something "value" unless it's a very generic routine.



class Sample(object):
   def __init__(self, mainval):
   self.mainval = mainval
   self.a = self.b = None
   def set_tags(self, a, b):
   self.a = a
   self.b = b
   def __repr__(self):
   return "<" + str(self.mainval) + " a=" + str(self.a) + " b=" + 
str(self.b) + ">"



diction2 = {88: [Sample(87), Sample(89), Sample(98), Sample(3)],
   58: [Sample(57), Sample(59), Sample(48), Sample(68)],
   69: [Sample(79)]
}

print diction2

for key, valuelist in diction2.iteritems():
   for item in valuelist:
   item.set_tags(12, 106) #here's where you'd be using 
that mysterious blocks dictionary


print diction2



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


Re: Frustrated with scopes

2009-08-12 Thread andrew cooke
On Aug 12, 1:51 am, James Stroud 
wrote:
> andrew cooke wrote:
> > Is there a way to make this work (currently scope and join are
> > undefined at runtime when the inner class attributes are defined):
>
> > class _StreamFactory(object):
>
> >     @staticmethod
> >     def __call__(lines, source, join=''.join):
>
> >         class Line(object):
>
> >             __source = source
> >             __join = join
> > [...]
>
> It would be helpful if you were to describe the type of behavior you expect.

Sorry, I didn't make myself clear.  When run the code gives
 NameError: name 'source' is not defined
because the class namespace blocks the function namespace (or
something...).

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


Re: Frustrated with scopes

2009-08-12 Thread andrew cooke
On Aug 12, 7:49 am, andrew cooke  wrote:
> On Aug 12, 1:51 am, James Stroud 
> wrote:
>
>
>
> > andrew cooke wrote:
> > > Is there a way to make this work (currently scope and join are
> > > undefined at runtime when the inner class attributes are defined):
>
> > > class _StreamFactory(object):
>
> > >     @staticmethod
> > >     def __call__(lines, source, join=''.join):
>
> > >         class Line(object):
>
> > >             __source = source
> > >             __join = join
> > > [...]
>
> > It would be helpful if you were to describe the type of behavior you expect.
>
> Sorry, I didn't make myself clear.  When run the code gives
>  NameError: name 'source' is not defined
> because the class namespace blocks the function namespace (or
> something...).

ie when the __call__ method is invoked on an instance of
_StreamFactory.

> Andrew

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


Re: matching patterns after regex?

2009-08-12 Thread Bernard
On 12 août, 06:15, Martin  wrote:
> Hi,
>
> I have a string (see below) and ideally I would like to pull out the
> decimal number which follows the bounding coordinate information. For
> example ideal from this string I would return...
>
> s = '\nGROUP                  = ARCHIVEDMETADATA\n
> GROUPTYPE            = MASTERGROUP\n\n  GROUP                  =
> BOUNDINGRECTANGLE\n\n    OBJECT                 =
> NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> VALUE                = 19.82039\n    END_OBJECT             =
> NORTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
> SOUTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> VALUE                = 9.910197\n    END_OBJECT             =
> SOUTHBOUNDINGCOORDINATE\n\n    OBJECT                 =
> EASTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> VALUE                = 10.6506458717851\n    END_OBJECT             =
> EASTBOUNDINGCOORDINATE\n\n    OBJECT                 =
> WESTBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> VALUE                = 4.3188348375893e-15\n    END_OBJECT
> = WESTBOUNDINGCOORDINATE\n\n  END_GROUP
>
> NORTHBOUNDINGCOORDINATE = 19.82039
> SOUTHBOUNDINGCOORDINATE = 9.910197
> EASTBOUNDINGCOORDINATE = 10.6506458717851
> WESTBOUNDINGCOORDINATE = 4.3188348375893e-15
>
> so far I have only managed to extract the numbers by doing re.findall
> ("[\d.]*\d", s), which returns
>
> ['1',
>  '19.82039',
>  '1',
>  '9.910197',
>  '1',
>  '10.6506458717851',
>  '1',
>  '4.3188348375893',
>  '15',
> etc.
>
> Now the first problem that I can see is that my string match chops off
> the "e-15" part and I am not sure how to incorporate the potential for
> that in my pattern match. Does anyone have any suggestions as to how I
> could also match this? Ideally I would have a statement which printed
> the number between the two bounding coordinate strings for example
>
> NORTHBOUNDINGCOORDINATE\n      NUM_VAL              = 1\n
> VALUE                = 19.82039\n    END_OBJECT             =
> NORTHBOUNDINGCOORDINATE\n\n
>
> Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
> decimal number before it hit the next string
> "NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
> suggestions would be appreciated.
>
> Many thanks
>
> Martin

Hey Martin,

here's a regex I've just tested : (\w+COORDINATE).*\s+VALUE\s+=\s([\d\.
\w-]+)

the first match corresponds to the whateverBOUNDINGCOORDINATE and the
second match is the value.

please provide some more entries if you'd like me to test my regex
some more :)

cheers

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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Steven D'Aprano
On Wed, 12 Aug 2009 03:32:08 -0700, Paul Boddie wrote:

> On 12 Aug, 09:58, Steven D'Aprano
>  wrote:
>>
>> We know that there are problems. We've said repeatedly that corrections
>> and patches are welcome. We've repeatedly told you how to communicate
>> your answer to the question of what should be done. None of this is
>> good enough for you. I don't know what else you expect.
> 
> Maybe the problem is that although everyone welcomes contributions and
> changes (or says that they do), the mechanisms remain largely beyond
> criticism. Consequently, one sees occasional laments about there not
> being enough people contributing to Python core development and soul-
> searching about the reasons this might be so. If it were insisted that
> changes to, say, Wikipedia were to be proposed by submitting a patch or
> report for perusal by the editors and for future inclusion in some
> version of the project, the whole project would most likely be a shadow
> of its current self, and ambitions of large-scale collaborative editing
> in general would still be ridiculed.

If Python had the tens of thousands of users, and hundreds of trusted 
(for some definition of trusted) editors, then Python could run using the 
same model as Wikipedia. The Wikipedia model is great, and I contribute 
to it myself.

But Wikipedia gets its users from the entire population of web-users, 
because there's something of interest to everyone in Wikipedia. 
Interested in movies? There are Wikipedia pages for you to contribute to. 
Interested in medicine? There are pages you can help with. Interested in 
the history and development of the mechanical pencil? There's probably 
even a page for you. And if there isn't, you can create one.

With tens of millions of web users, it's no surprise that Wikipedia can 
attract thousands of editors. But this does not apply to Python, which 
starts from a comparatively tiny population, primarily those interested 
in Python. Have a look at the Wikipedia page for Python. The Talk Page 
has comments from no more than *eight* people. The History stats suggest 
that, over seven years, only sixty-nine people have made more than a 
single edit to the page, most of them having made just two edits. Just 36 
people have made more than two edits, and some of those are bots. Only 
one user, Lulu of the Lotus-Eaters (David Mertz), has made more than 100 
edits.


> A free-for-all isn't likely to be the best solution for more actively
> edited Python documentation, but Wiki solutions undeniably provide a
> superior "fast path" for edits by trusted users to be incorporated and
> published in accessible end-user documentation. 

And the Python time-machine strikes again:

http://wiki.python.org/moin/


>> > That some of us choose to
>> > invest it somewhere other than Python does not deprive of of our
>> > right to point out problems in Python when we note them.
>>
>> Of course not. But it does mean that you won't be taken seriously, and
>> you have no right to be taken seriously.
> 
> That's an absurd position that has soured the reputation of numerous
> projects. When someone spends the time to write a bug report, they are
> often investing as much time and effort in something that they are able
> to in any productive sense. 

Firstly, in context, I wasn't talking to somebody who had made bug 
reports. I was talking to somebody whose only contribution, as near as I 
can tell, was to loudly complain that there are flaws in the Python 
documentation and insist that somebody else should fix them just the way 
he wants them fixed -- without being willing to even explain how he wants 
them fixed. Possibly the developers are expected to intuit from first 
principles what he wants.

Secondly, the world is full of complainers who won't lift a finger to 
help but demand others help them. It may be unfair to tar everybody with 
the same brush, but life is to short and time to valuable to avoid making 
judgements as to who to pay attention to. Those who invest a lot of 
effort into providing patches get listened to closely; so do those who 
make good quality detailed bug reports. Those who just say "It's broken, 
fix it" don't. Sometimes that will mean that someone with genuinely good 
ideas will be ignored, but that's the price one pays for avoiding being 
drowned by a chorus of trivial, contradictory, vague and insubstantial 
complaints.

If the Python Dev team paid attention to every post here claiming that 
Python "has a bug" when the bug was actually in the complainant's own 
code, we'd probably still be running Python 1.5.


> I make a habit of submitting bug reports to
> software distributions, typically so that the people who are responsible
> for the components involved can investigate the problem effectively.
> When the maintainers just close such reports or mark them with a number
> of different labels which mostly indicate that they consider those
> reports not worth their time, it sends the message that they consider

Re: Frustrated with scopes

2009-08-12 Thread Diez B. Roggisch
andrew cooke wrote:

> On Aug 12, 7:49 am, andrew cooke  wrote:
>> On Aug 12, 1:51 am, James Stroud 
>> wrote:
>>
>>
>>
>> > andrew cooke wrote:
>> > > Is there a way to make this work (currently scope and join are
>> > > undefined at runtime when the inner class attributes are defined):
>>
>> > > class _StreamFactory(object):
>>
>> > > @staticmethod
>> > > def __call__(lines, source, join=''.join):
>>
>> > > class Line(object):
>>
>> > > __source = source
>> > > __join = join
>> > > [...]
>>
>> > It would be helpful if you were to describe the type of behavior you
>> > expect.
>>
>> Sorry, I didn't make myself clear.  When run the code gives
>> NameError: name 'source' is not defined
>> because the class namespace blocks the function namespace (or
>> something...).
> 
> ie when the __call__ method is invoked on an instance of
> _StreamFactory.

But you can refer to the arguments if you don't insist on setting them as
class-attributes:




def factory(foo, bar):

class A(object):

def do_something(self):
print foo, bar

return A()

a = factory(10, 20)
a.do_something()



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


Re: matching patterns after regex?

2009-08-12 Thread Martin
On Aug 12, 12:53 pm, Bernard  wrote:
> On 12 août, 06:15, Martin  wrote:
>
>
>
> > Hi,
>
> > I have a string (see below) and ideally I would like to pull out the
> > decimal number which follows the bounding coordinate information. For
> > example ideal from this string I would return...
>
> > s = '\nGROUP  = ARCHIVEDMETADATA\n
> > GROUPTYPE= MASTERGROUP\n\n  GROUP  =
> > BOUNDINGRECTANGLE\n\nOBJECT =
> > NORTHBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
> > VALUE= 19.82039\nEND_OBJECT =
> > NORTHBOUNDINGCOORDINATE\n\nOBJECT =
> > SOUTHBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
> > VALUE= 9.910197\nEND_OBJECT =
> > SOUTHBOUNDINGCOORDINATE\n\nOBJECT =
> > EASTBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
> > VALUE= 10.6506458717851\nEND_OBJECT =
> > EASTBOUNDINGCOORDINATE\n\nOBJECT =
> > WESTBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
> > VALUE= 4.3188348375893e-15\nEND_OBJECT
> > = WESTBOUNDINGCOORDINATE\n\n  END_GROUP
>
> > NORTHBOUNDINGCOORDINATE = 19.82039
> > SOUTHBOUNDINGCOORDINATE = 9.910197
> > EASTBOUNDINGCOORDINATE = 10.6506458717851
> > WESTBOUNDINGCOORDINATE = 4.3188348375893e-15
>
> > so far I have only managed to extract the numbers by doing re.findall
> > ("[\d.]*\d", s), which returns
>
> > ['1',
> >  '19.82039',
> >  '1',
> >  '9.910197',
> >  '1',
> >  '10.6506458717851',
> >  '1',
> >  '4.3188348375893',
> >  '15',
> > etc.
>
> > Now the first problem that I can see is that my string match chops off
> > the "e-15" part and I am not sure how to incorporate the potential for
> > that in my pattern match. Does anyone have any suggestions as to how I
> > could also match this? Ideally I would have a statement which printed
> > the number between the two bounding coordinate strings for example
>
> > NORTHBOUNDINGCOORDINATE\n  NUM_VAL  = 1\n
> > VALUE= 19.82039\nEND_OBJECT =
> > NORTHBOUNDINGCOORDINATE\n\n
>
> > Something that matched "NORTHBOUNDINGCOORDINATE" and printed the
> > decimal number before it hit the next string
> > "NORTHBOUNDINGCOORDINATE". But I am not sure how to do this. any
> > suggestions would be appreciated.
>
> > Many thanks
>
> > Martin
>
> Hey Martin,
>
> here's a regex I've just tested : (\w+COORDINATE).*\s+VALUE\s+=\s([\d\.
> \w-]+)
>
> the first match corresponds to the whateverBOUNDINGCOORDINATE and the
> second match is the value.
>
> please provide some more entries if you'd like me to test my regex
> some more :)
>
> cheers
>
> Bernard

Thanks Bernard it doesn't seem to be working for me...

I tried

re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)

is that what you meant? Apologies if not, that results in a syntax
error:

In [557]: re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)

   File "", line 1
 re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
  ^
SyntaxError: unexpected character after line continuation character

Thanks



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


Re: Frustrated with scopes

2009-08-12 Thread Steven D'Aprano
On Wed, 12 Aug 2009 04:49:06 -0700, andrew cooke wrote:

>> It would be helpful if you were to describe the type of behavior you
>> expect.
> 
> Sorry, I didn't make myself clear.  When run the code gives
>  NameError: name 'source' is not defined
> because the class namespace blocks the function namespace (or
> something...).

James asked you to describe the behaviour you expect. Please explain what 
you expect, and what you actually get. Post the ACTUAL error message, not 
a summary, not a paraphrase, but an actual copy and paste.


In any case, your code snippet works for me:


>>> class _StreamFactory(object):
... @staticmethod
... def __call__(lines, source, join=''.join):
... class Line(object):
... __source = source
... __join = join
...
>>> obj = _StreamFactory()
>>> obj(['a', 'b'], "ab")
>>>

No errors. Of course it doesn't return anything, because your code 
snippet doesn't return anything either. Here's a modified version which 
returns the inner class:

>>> class _StreamFactory2(object):
... @staticmethod
... def __call__(lines, source, join=''.join):
... class Line(object):
... __source = source
... __join = join
... return Line
...
>>> obj = _StreamFactory2()
>>> K = obj(['a', 'b'], "ab")
>>> K

>>> K._Line__source
'ab'


Works perfectly. I suspect your error is probably something like you have 
misspelled "source" somewhere.


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


Re: matching patterns after regex?

2009-08-12 Thread Steven D'Aprano
On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:

> I tried
> 
> re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)

You need to put quotes around strings.

In this case, because you're using regular expressions, you should use a 
raw string:

re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)

will probably work.





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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Antoine Pitrou
Paul Boddie  boddie.org.uk> writes:
> 
> A free-for-all isn't likely to be the best solution for more actively
> edited Python documentation, but Wiki solutions undeniably provide a
> superior "fast path" for edits by trusted users to be incorporated and
> published in accessible end-user documentation.

Agreed.

> I'm starting to believe
> that there's a certain snobbery about Wiki solutions which lead many
> people to develop all sorts of short-term, arcane solutions under the
> illusion that something super-special and customised is necessary and
> that they have to start virtually from scratch in order to cater to
> the ultra-special needs of the target audience; by the time they're
> done, no-one's interested any more, except to propose the next legacy
> system in the making.

Not sure why you think it's snobbery... There are certain tacit expectations
regarding the docs:
- that they are versioned with the source tree (because, often, changes in
documentation will be synchronized with changes in behaviour / functionality, 
because we must maintain documentation for several versions at once, because you
want to use the same kind of merging that is used between different branches)
- that they can be used offline, rebuilt in different formats, etc.
- that you don't need a Web server (even locally) to navigate through them
- that proposed changes are to be reviewed by maintainers (core developers)
before they get actually committed

I'm not sure of any existing wiki system which fits the bill. So, while I agree
that the current situation can present a high threshold for occasional doc-only
contributions, there doesn't seem to be a simple solution to improve things.


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


Re: matching patterns after regex?

2009-08-12 Thread Martin
On Aug 12, 1:23 pm, Steven D'Aprano  wrote:
> On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:
> > I tried
>
> > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
>
> You need to put quotes around strings.
>
> In this case, because you're using regular expressions, you should use a
> raw string:
>
> re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
>
> will probably work.
>
> --
> Steven

Thanks I see.

so I tried it and if I use it as it is, it matches the first instance:
I
n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')]

So I adjusted the first part of the regex, on the basis I could sub
NORTH for SOUTH etc.

In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\.
\w-]+)",s)
Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')]

But in both cases it doesn't return the decimal value rather the value
that comes after NUM_VAL = , rather than VALUE = ?


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


Re: Frustrated with scopes

2009-08-12 Thread Dave Angel

andrew cooke wrote:

Is there a way to make this work (currently scope and join are
undefined at runtime when the inner class attributes are defined):

class _StreamFactory(object):

@staticmethod
def __call__(lines, source, join=''.join):

class Line(object):

__source = source
__join = join
[...]

I can get something working by bouncing through global values, but it
looks awful and I think it's a source of a bug due too values being
redefined.

Thanks,
Andrew

  
Supply us with just enough source code to actually try it, give the full 
error message including traceback, and tell us what you expected to 
see.  Also tell us Python version   (sys.version)


So far you've done none of these.  When I try the following, I get no 
errors, using Python 2.6.2



class _StreamFactory(object):

   @staticmethod
   def __call__(lines, source, join=''.join):

   class Line(object):

   __source = source
   __join = join
   return Line()


fact = _StreamFactory()
obj = fact(43, "name.txt")
print obj


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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Paul Boddie
On 12 Aug, 14:08, Steven D'Aprano  wrote:
>
> With tens of millions of web users, it's no surprise that Wikipedia can
> attract thousands of editors. But this does not apply to Python, which
> starts from a comparatively tiny population, primarily those interested
> in Python. Have a look at the Wikipedia page for Python.

What does the Python entry on Wikipedia have to do with editing the
Python documentation in a Wiki? Once everyone has agreed that the
description of Python on Wikipedia is reasonable, there's not much
point in editing it, is there? In contrast, there's a continuous
stream of people who don't think Python's documentation is that great.

[...]

> > A free-for-all isn't likely to be the best solution for more actively
> > edited Python documentation, but Wiki solutions undeniably provide a
> > superior "fast path" for edits by trusted users to be incorporated and
> > published in accessible end-user documentation.
>
> And the Python time-machine strikes again:
>
> http://wiki.python.org/moin/

And I suggested that the complainants use it as a starting point.

[...]

> Oh dear me. You mean that they don't agree that YOUR time is more
> important than theirs??? What horrible people they must be, to expect you
> to sacrifice some of your sleep time just so *they* can get some sleep
> themselves!!! Who do they think they are???

That's quite an attempt to make my position more extreme than it
actually is. I get people asking me to improve my own software, you
know, and even if I don't have the time or inclination to do what they
ask, I do spend time discussing it with them. Such people, including
myself when I'm on the other side of the fence, appreciate more than
just a brush-off and no: they don't insist that their own time be
valued above anyone else's (as you would have me misrepresented); they
just ask that their own efforts aren't treated as having no value
because they're not part of the "elite" development team. You get
various projects doing soul-searching about embracing the efforts of
non-programmers, and the first port of call on that particular voyage
is to not treat them like idiot consumers whose remarks can only be
considered as mere heckling while the visionaries act out their
flawless production.

Paul

P.S. The mention of "social problems" ties in with other remarks made
recently, and I've increasingly found it more trouble than has been
worthwhile to pursue Python-related matters of late. When one tries to
encourage people to participate in improving various things, which
usually means the community having to accept a degree of criticism,
people claim that it's encouraging "undesirable" influences to point
such critics in the right direction instead of showing them the door.
When one tries to pursue such improvement matters oneself, people
always have something to say about the choice of technology or whether
they like the particular background colour being used or indeed have
an opinion, typically shallow and negative, about anything but the
task at hand, and there'll always be someone queuing up to dismantle
anything that does get done at the first opportunity. In contrast,
I've found other groups of people to be grateful for even modest
technical assistance, and I know that such people are much more likely
to get my support and input in the future than those who think that
it's some kind of advantage to have potential contributors run the
gauntlet of denial (that there are structural problems in their
project), skepticism (that newcomers can have anything to contribute),
discouragement (because any solution which doesn't validate someone's
technology preferences must be criticised) and, indeed, outright
hostility.

One can always spend one's time doing something which isn't 100%
enjoyable or 100% rewarding if one feels that the time is still being
spent on something worthwhile. I'm getting the feeling that lots of
Python-related stuff doesn't quite satisfy such criteria any more.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need cleanup advice for multiline string

2009-08-12 Thread Jean-Michel Pichavant

Simon Brunning wrote:

2009/8/11 Robert Dailey :
  

On Aug 11, 3:40 pm, Bearophile  wrote:


There are gals too here.
  

It's a figure of speech. And besides, why would I want programming
advice from a woman? lol. Thanks for the help.



Give the attitudes still prevalent in our industry (cf
 and many more), I'm sorry to say that I
don't think this is funny.

  
Having someone present technical informations with porn content cannot 
be qualified as "prevalent in our industry". I would even dare to say 
this is the opposite, it is almost unique.
I would also add that Robert was very far from this attitude, I consider 
his joke as a friendly tickle, not a male chauvinist aggression. I'm no 
women, but I'm sure they are as capable as me, not to say more, of 
making the distinction.


It has been said this list is not very friendly to newbies, let's not 
make it hostile to gentle jokes (even those not funny) when thanking 
helpers.


JM


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


Re: Frustrated with scopes

2009-08-12 Thread andrew cooke
On Aug 12, 8:52 am, Dave Angel  wrote:
> Supply us with just enough source code to actually try it, give the full
> error message including traceback, and tell us what you expected to
> see.  Also tell us Python version   (sys.version)
>
> So far you've done none of these.  When I try the following, I get no
> errors, using Python 2.6.2
>
> class _StreamFactory(object):
>
>     @staticmethod
>     def __call__(lines, source, join=''.join):
>
>         class Line(object):
>
>             __source = source
>             __join = join
>         return Line()
>
> fact = _StreamFactory()
> obj = fact(43, "name.txt")
> print obj

Ah!  OK, thanks for that.  I need to look at this again.  I'll post
again if necessary, but if it works for you then I clearly don't
understand what the issue is myself.

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


best practice for documenting a project? pydoc?

2009-08-12 Thread Esmail

Hello,

A project that I have been working on is getting larger
and more complex, and I would like to unload some of the
information from my memory/head to some other media (a
set of web pages?). I am primarily interested in documenting
the classes/methods.

This documentation is primarily for my use only - as I can't
continuously work on this project and have to come back to it
after some time, it would be nice to have some documentation
available to help jog my memory.

What is the best way to do this in an automated way? I have
been documenting my code as I've gone along.

Is pydoc still the way to go, or should I use something else?

Thanks,
Esmail

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


Re: Need cleanup advice for multiline string

2009-08-12 Thread exarkun

On 01:27 pm, [email protected] wrote:

Simon Brunning wrote:

2009/8/11 Robert Dailey :

On Aug 11, 3:40 pm, Bearophile  wrote:

There are gals too here.

It's a figure of speech. And besides, why would I want programming
advice from a woman? lol. Thanks for the help.


Give the attitudes still prevalent in our industry (cf
 and many more), I'm sorry to say that I
don't think this is funny.
Having someone present technical informations with porn content cannot 
be qualified as "prevalent in our industry". I would even dare to say 
this is the opposite, it is almost unique.
I would also add that Robert was very far from this attitude, I 
consider his joke as a friendly tickle, not a male chauvinist 
aggression. I'm no women, but I'm sure they are as capable as me, not 
to say more, of making the distinction.


It has been said this list is not very friendly to newbies, let's not 
make it hostile to gentle jokes (even those not funny) when thanking 
helpers.


It's lots of little things like this which combine to create an 
environment which is less friendly towards women than it is towards 
others.  You might read it as a joke, others might not.  Even if it is a 
joke, it's in poor taste and doesn't really belong on python-list.


There's a difference between pointing out inappropriate behavior and 
being unfriendly.  Hopefully Robert got help with his problem.  That's 
what the list is here for.  Having accomplished that, it is not 
unfriendly to ask him not to make disparaging comments, "jokes" or 
otherwise, about groups of people.


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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Mark Lawrence

Paul Boddie wrote:
[snip]

One can always spend one's time doing something which isn't 100%
enjoyable or 100% rewarding if one feels that the time is still being
spent on something worthwhile. I'm getting the feeling that lots of
Python-related stuff doesn't quite satisfy such criteria any more.


I've been strongly considering volunteering to do Python work but this 
thread has put me off completely.  I've time to spare as I only work 
part time due to long term health problems. However I don't feel that 
the time would be well spent on Python work, as I get the impression 
that a lot of it would go on cleaning some people's snotty noses, and on 
wiping other people's bottoms.


I'll just wait until my normal voluntary work starts again next month 
after the summer break.  Working with an extremely pleasant bunch of 
people hacking foreigners to death, that's more like it.  See the 
following links should anyone be interested.


http://www.dorsetforyou.com/index.jsp?articleid=386553
http://www.dorsetforyou.com/index.jsp?articleid=386598

--
Kindest regards.

Mark Lawrence.

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


Re: httplib incredibly slow :-(

2009-08-12 Thread Max Erickson
Chris Withers  wrote:
> 
> I'm still reeling from what seems to be such a huge problem with
> httplib that seem to be largely ignored :-(
> 
> Chris
> 

There is an httplib2 (but I don't know anything further about it...):

http://code.google.com/p/httplib2/

Calling wget or curl using a subprocess is probably as easy as it is 
ugly, I use the wget build from here:

http://gnuwin32.sourceforge.net/packages/wget.htm


max

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


Re: better way?

2009-08-12 Thread Scott David Daniels

Pet wrote:

On 11 Aug., 22:19, "Rami Chowdhury"  wrote:
Ah, my apologies, I must have been getting it confused with ON UPDATE  
[things]. Thanks for correcting me.


On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft  


 wrote:

"Rami Chowdhury"  writes:

IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
MySQL...

PostgreSQL does not have ON DUPLICATE KEY UPDATE.
The SQL standard way to do what the OP wants is MERGE. PostgreSQL
doesn't have that either.


So, I'm doing it in right way?
What about building columns? map(lambda s: s + ' = %s', fields)
Is that o.k.?

Isn't
t = [field + ' = %s' for field in fields]
clearer than
t = map(lambda s: s + ' = %s', fields)
? your call of course.

I don't quite understand why you are building the SQL from data
but constructing the arguments in source.  I'd actually set the
SQL up directly as a string, making both the SQL and Python more
readable. To the original question, you could unconditionally
perform a queries vaguely like:

UPDATE_SQL = '''UPDATE table ...
 WHERE id = %s AND location = %s;'''
INSERT_SQL = '''INSERT INTO table(...
 WHERE NOT EXISTS(SELECT * FROM table
  WHERE id = %s AND location = %s;);'''
I'd put the NOW() and constant args (like the 1) in the SQL itself.
then your code might become:
row = (self.wl, name, location, id)
self._execQuery(db, UPDATE_SQL, [row])
self._execQuery(db, INSERT_SQL, [row + (location, id)])
if _execQuery is like the standard Python DB interfaces.  Having
the SQL do the checking means you allows the DB to check its
index and use that result to control the operation, simplifying
the Python code without significantly affecting the the DB work
needed.  The "SELECT *" form in the EXIST test is something DB
optimizers look for, so don't fret about wasted data movement.



--Scott David Daniels
[email protected]
--
http://mail.python.org/mailman/listinfo/python-list


Re: Need cleanup advice for multiline string

2009-08-12 Thread Robert Dailey
On Aug 12, 9:09 am, [email protected] wrote:
> On 01:27 pm, [email protected] wrote:
>
>
>
>
>
> >Simon Brunning wrote:
> >>2009/8/11 Robert Dailey :
> >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> There are gals too here.
> >>>It's a figure of speech. And besides, why would I want programming
> >>>advice from a woman? lol. Thanks for the help.
>
> >>Give the attitudes still prevalent in our industry (cf
> >> and many more), I'm sorry to say that I
> >>don't think this is funny.
> >Having someone present technical informations with porn content cannot
> >be qualified as "prevalent in our industry". I would even dare to say
> >this is the opposite, it is almost unique.
> >I would also add that Robert was very far from this attitude, I
> >consider his joke as a friendly tickle, not a male chauvinist
> >aggression. I'm no women, but I'm sure they are as capable as me, not
> >to say more, of making the distinction.
>
> >It has been said this list is not very friendly to newbies, let's not
> >make it hostile to gentle jokes (even those not funny) when thanking
> >helpers.
>
> It's lots of little things like this which combine to create an
> environment which is less friendly towards women than it is towards
> others.  You might read it as a joke, others might not.  Even if it is a
> joke, it's in poor taste and doesn't really belong on python-list.
>
> There's a difference between pointing out inappropriate behavior and
> being unfriendly.  Hopefully Robert got help with his problem.  That's
> what the list is here for.  Having accomplished that, it is not
> unfriendly to ask him not to make disparaging comments, "jokes" or
> otherwise, about groups of people.
>
> Jean-Paul

Hey everyone,

I was actually joking about my remark, I was making fun of the fact
that Bearophile took my figure of speech literally. I have worked with
a lot of women in the past and they even use "guys" to refer to
everyone in a room (When there were obviously other females in that
room as well).

On a more serious note, I do apologize to those offended by my remark.
I realize that these things can be a touchy subject for some people. I
expected more of a laid-back attitude from everyone. No need to be so
serious all the time. I cannot completely doubt that there are logical
women out there. I just haven't seen one yet. But that doesn't mean
I'm a sexist.

With my apology presented, I would like to propose that we end the
discussion here. As I said, this is a very sensitive subject and this
thread could spin way out of control if we don't just ignore the
issue. For those that took it as a friendly, harmless joke, hopefully
you had a laugh. For those that took it seriously or as an offense,
please take my apology to heart. Thanks once again to everyone for
your help. I've long been a member of this community and I really
appreciate the continuous support I've been receiving!

Take care everyone!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Need cleanup advice for multiline string

2009-08-12 Thread Robert Dailey
On Aug 12, 9:41 am, Robert Dailey  wrote:
> On Aug 12, 9:09 am, [email protected] wrote:
>
>
>
>
>
> > On 01:27 pm, [email protected] wrote:
>
> > >Simon Brunning wrote:
> > >>2009/8/11 Robert Dailey :
> > >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> > There are gals too here.
> > >>>It's a figure of speech. And besides, why would I want programming
> > >>>advice from a woman? lol. Thanks for the help.
>
> > >>Give the attitudes still prevalent in our industry (cf
> > >> and many more), I'm sorry to say that I
> > >>don't think this is funny.
> > >Having someone present technical informations with porn content cannot
> > >be qualified as "prevalent in our industry". I would even dare to say
> > >this is the opposite, it is almost unique.
> > >I would also add that Robert was very far from this attitude, I
> > >consider his joke as a friendly tickle, not a male chauvinist
> > >aggression. I'm no women, but I'm sure they are as capable as me, not
> > >to say more, of making the distinction.
>
> > >It has been said this list is not very friendly to newbies, let's not
> > >make it hostile to gentle jokes (even those not funny) when thanking
> > >helpers.
>
> > It's lots of little things like this which combine to create an
> > environment which is less friendly towards women than it is towards
> > others.  You might read it as a joke, others might not.  Even if it is a
> > joke, it's in poor taste and doesn't really belong on python-list.
>
> > There's a difference between pointing out inappropriate behavior and
> > being unfriendly.  Hopefully Robert got help with his problem.  That's
> > what the list is here for.  Having accomplished that, it is not
> > unfriendly to ask him not to make disparaging comments, "jokes" or
> > otherwise, about groups of people.
>
> > Jean-Paul
>
> Hey everyone,
>
> I was actually joking about my remark, I was making fun of the fact
> that Bearophile took my figure of speech literally. I have worked with
> a lot of women in the past and they even use "guys" to refer to
> everyone in a room (When there were obviously other females in that
> room as well).
>
> On a more serious note, I do apologize to those offended by my remark.
> I realize that these things can be a touchy subject for some people. I
> expected more of a laid-back attitude from everyone. No need to be so
> serious all the time. I cannot completely doubt that there are logical
> women out there. I just haven't seen one yet. But that doesn't mean
> I'm a sexist.
>
> With my apology presented, I would like to propose that we end the
> discussion here. As I said, this is a very sensitive subject and this
> thread could spin way out of control if we don't just ignore the
> issue. For those that took it as a friendly, harmless joke, hopefully
> you had a laugh. For those that took it seriously or as an offense,
> please take my apology to heart. Thanks once again to everyone for
> your help. I've long been a member of this community and I really
> appreciate the continuous support I've been receiving!
>
> Take care everyone!

Oh, one last thing... So everyone knows, I chose the following
formatting solution to multiline strings:

def MyFunction():
   multilineString = (
  'This is a string that spans '
  'multiple lines.'
  )
   print( multilineString )

I think this is as good as it is going to get for my personal needs.
However, I do not like having to put a space at the end of each
string. I've also done this in the past, which is slightly more ugly:

  multilineString = (
 'This is a string that spans',
 'multiple lines.'
 )
  print( ' '.join( multilineString ) )

This will add the spaces between lines for you. However, in a
production quality application I would always have strings external to
the scripts and have an advanced localization system. However this is
useful for quick little scripts that I want to keep tidy.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: best practice for documenting a project? pydoc?

2009-08-12 Thread Mark Lawrence

Esmail wrote:

Hello,

A project that I have been working on is getting larger
and more complex, and I would like to unload some of the
information from my memory/head to some other media (a
set of web pages?). I am primarily interested in documenting
the classes/methods.

This documentation is primarily for my use only - as I can't
continuously work on this project and have to come back to it
after some time, it would be nice to have some documentation
available to help jog my memory.

What is the best way to do this in an automated way? I have
been documenting my code as I've gone along.

Is pydoc still the way to go, or should I use something else?

Thanks,
Esmail


The docs for the constraint package look good, see
http://labix.org/python-constraint and http://labix.org/doc/constraint.
I think they've been produced with epydoc see http://epydoc.sourceforge.net/

--
Kindest regards.

Mark Lawrence.

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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Steven D'Aprano
On Wed, 12 Aug 2009 06:24:18 -0700, Paul Boddie wrote:

> On 12 Aug, 14:08, Steven D'Aprano  cybersource.com.au> wrote:
>>
>> With tens of millions of web users, it's no surprise that Wikipedia can
>> attract thousands of editors. But this does not apply to Python, which
>> starts from a comparatively tiny population, primarily those interested
>> in Python. Have a look at the Wikipedia page for Python.
> 
> What does the Python entry on Wikipedia have to do with editing the
> Python documentation in a Wiki? 

Good question. I was responding to you mentioning Wikipedia as a possible 
role model for the Python docs.


> Once everyone has agreed that the
> description of Python on Wikipedia is reasonable, there's not much point
> in editing it, is there? 

And once we're all fabulously wealthy, there won't be any point in anyone 
working any more either!

The problem for your argument is, even if it were correct, not everyone 
agrees the Python article is "reasonable" -- there were three edits made 
since the 7th of this month. And before that, there was a stream of 22 
edits on the 5th, and another 25 edits since the  8th of July. Obviously 
the Python article is still in active development.

Some of those edits were, apparently, vandalism, which gives yet another 
reason why the Wikipedia model is not necessarily the right model to 
follow.


> In contrast, there's a continuous stream of
> people who don't think Python's documentation is that great.

And a great flood of those who think it's pretty good and gets the job 
done adequately, and a trickle of those who think it's perfect just the 
way it is.

It's not the people who suggest improvements to the docs that are the 
problem, but the ones who insist that the docs are terrible, but aren't 
willing to do anything but complain. Oh, and trolls like ... I hesitate 
to mention his name in case he has a bot monitoring the list ... first 
name starts with "X" followed by "ah", second name sounds like "Mee" ... 
who even if they make a few good points, they're lost in a sea of insults 
to others, arrogance and self-aggrandisement.


>> And the Python time-machine strikes again:
>>
>> http://wiki.python.org/moin/
> 
> And I suggested that the complainants use it as a starting point.

Sorry, I seem to have missed that.


> [...]
> 
>> Oh dear me. You mean that they don't agree that YOUR time is more
>> important than theirs??? What horrible people they must be, to expect
>> you to sacrifice some of your sleep time just so *they* can get some
>> sleep themselves!!! Who do they think they are???
> 
> That's quite an attempt to make my position more extreme than it
> actually is. 

Well, you did raise the issue of the sacrifices you were making to report 
these bugs. All I did was exaggerate the attitude a tad.


> I get people asking me to improve my own software, you
> know, and even if I don't have the time or inclination to do what they
> ask, I do spend time discussing it with them. Such people, including
> myself when I'm on the other side of the fence, appreciate more than
> just a brush-off and no: they don't insist that their own time be valued
> above anyone else's 

Then you're incredibly lucky to attract a better class of end-users. In 
my experience, most end-users won't even spend the effort to describe the 
problem they're having beyond "it doesn't work". And they usually 
misspell that.



> (as you would have me misrepresented); they just ask
> that their own efforts aren't treated as having no value because they're
> not part of the "elite" development team. You get various projects doing
> soul-searching about embracing the efforts of non-programmers, and the
> first port of call on that particular voyage is to not treat them like
> idiot consumers whose remarks can only be considered as mere heckling
> while the visionaries act out their flawless production.

A noble vision, but wait until the idiot heckling consumers discover your 
software, then we'll see how much time you're prepared to give them.



> 
> Paul
> 
> P.S. The mention of "social problems" ties in with other remarks made
> recently, and I've increasingly found it more trouble than has been
> worthwhile to pursue Python-related matters of late. When one tries to
> encourage people to participate in improving various things, which
> usually means the community having to accept a degree of criticism,
> people claim that it's encouraging "undesirable" influences to point
> such critics in the right direction instead of showing them the door.

Can you point me to a discussion where this has happened?


> When one tries to pursue such improvement matters oneself, people always
> have something to say about the choice of technology or whether they
> like the particular background colour being used 

You've discovered bike-shedding.

> or indeed have an
> opinion, typically shallow and negative, about anything but the task at
> hand, 

When you're agitating for change, anyone defending

Re: better way?

2009-08-12 Thread Pet
On Aug 12, 4:29 pm, Scott David Daniels  wrote:
> Pet wrote:
> > On 11 Aug., 22:19, "Rami Chowdhury"  wrote:
> >> Ah, my apologies, I must have been getting it confused with ON UPDATE  
> >> [things]. Thanks for correcting me.
>
> >> On Tue, 11 Aug 2009 13:10:03 -0700, Matthew Woodcraft  
>
> >>  wrote:
> >>> "Rami Chowdhury"  writes:
>  IIRC Postgres has had ON DUPLICATE KEY UPDATE functionality longer than
>  MySQL...
> >>> PostgreSQL does not have ON DUPLICATE KEY UPDATE.
> >>> The SQL standard way to do what the OP wants is MERGE. PostgreSQL
> >>> doesn't have that either.
>
> > So, I'm doing it in right way?
> > What about building columns? map(lambda s: s + ' = %s', fields)
> > Is that o.k.?
>
> Isn't
>      t = [field + ' = %s' for field in fields]
> clearer than
>      t = map(lambda s: s + ' = %s', fields)
> ? your call of course.

Yes, I think so

> I don't quite understand why you are building the SQL from data
> but constructing the arguments in source.  I'd actually set the
> SQL up directly as a string, making both the SQL and Python more

Sometimes, column list could be long, besides I keep column list in
sync for both update and insert query

> readable. To the original question, you could unconditionally
> perform a queries vaguely like:
>
> UPDATE_SQL = '''UPDATE table ...
>       WHERE id = %s AND location = %s;'''
> INSERT_SQL = '''INSERT INTO table(...
>       WHERE NOT EXISTS(SELECT * FROM table
>                        WHERE id = %s AND location = %s;);'''
> I'd put the NOW() and constant args (like the 1) in the SQL itself.

yes, but I'm building both UPDATE in INSERT from same list of columns,
so I didn't found better way as this one


> then your code might become:
>      row = (self.wl, name, location, id)
>      self._execQuery(db, UPDATE_SQL, [row])
>      self._execQuery(db, INSERT_SQL, [row + (location, id)])

I'm going to rebuild my queries like that.

Thank you very much!


> if _execQuery is like the standard Python DB interfaces.  Having
> the SQL do the checking means you allows the DB to check its
> index and use that result to control the operation, simplifying
> the Python code without significantly affecting the the DB work
> needed.  The "SELECT *" form in the EXIST test is something DB
> optimizers look for, so don't fret about wasted data movement.
>
> --Scott David Daniels
> [email protected]

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


Re: Need cleanup advice for multiline string

2009-08-12 Thread Simon Forman
On Aug 12, 10:41 am, Robert Dailey  wrote:
> On Aug 12, 9:09 am, [email protected] wrote:
>
>
>
> > On 01:27 pm, [email protected] wrote:
>
> > >Simon Brunning wrote:
> > >>2009/8/11 Robert Dailey :
> > >>>On Aug 11, 3:40 pm, Bearophile  wrote:
> > There are gals too here.
> > >>>It's a figure of speech. And besides, why would I want programming
> > >>>advice from a woman? lol. Thanks for the help.
>
> > >>Give the attitudes still prevalent in our industry (cf
> > >> and many more), I'm sorry to say that I
> > >>don't think this is funny.
> > >Having someone present technical informations with porn content cannot
> > >be qualified as "prevalent in our industry". I would even dare to say
> > >this is the opposite, it is almost unique.
> > >I would also add that Robert was very far from this attitude, I
> > >consider his joke as a friendly tickle, not a male chauvinist
> > >aggression. I'm no women, but I'm sure they are as capable as me, not
> > >to say more, of making the distinction.
>
> > >It has been said this list is not very friendly to newbies, let's not
> > >make it hostile to gentle jokes (even those not funny) when thanking
> > >helpers.
>
> > It's lots of little things like this which combine to create an
> > environment which is less friendly towards women than it is towards
> > others.  You might read it as a joke, others might not.  Even if it is a
> > joke, it's in poor taste and doesn't really belong on python-list.
>
> > There's a difference between pointing out inappropriate behavior and
> > being unfriendly.  Hopefully Robert got help with his problem.  That's
> > what the list is here for.  Having accomplished that, it is not
> > unfriendly to ask him not to make disparaging comments, "jokes" or
> > otherwise, about groups of people.
>
> > Jean-Paul
>
> Hey everyone,
>
> I was actually joking about my remark, I was making fun of the fact
> that Bearophile took my figure of speech literally. I have worked with
> a lot of women in the past and they even use "guys" to refer to
> everyone in a room (When there were obviously other females in that
> room as well).
>
> On a more serious note, I do apologize to those offended by my remark.
> I realize that these things can be a touchy subject for some people. I
> expected more of a laid-back attitude from everyone. No need to be so
> serious all the time. I cannot completely doubt that there are logical
> women out there. I just haven't seen one yet. But that doesn't mean
> I'm a sexist.

Oh my.  And you were doing so well.  You haven't seen a logical
woman?  Perhaps you're blind because your eyes were torn out by a
raging marmoset?

Guess what?  Thinking (or just saying) that /does/ mean you're a
sexist.  (Even if it was just another "friendly, harmless joke".)




> With my apology presented, I would like to propose that we end the
> discussion here. As I said, this is a very sensitive subject and this
> thread could spin way out of control if we don't just ignore the
> issue. For those that took it as a friendly, harmless joke, hopefully
> you had a laugh. For those that took it seriously or as an offense,
> please take my apology to heart. Thanks once again to everyone for
> your help. I've long been a member of this community and I really
> appreciate the continuous support I've been receiving!
>
> Take care everyone!

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


Re: Need cleanup advice for multiline string

2009-08-12 Thread Steven D'Aprano
On Wed, 12 Aug 2009 07:47:58 -0700, Robert Dailey wrote:

> On Aug 12, 9:41 am, Robert Dailey  wrote:
... 
> > I was actually joking about my remark, I was making fun of the fact
> > that Bearophile took my figure of speech literally. 

Keep in mind that the Internet is a global forum, and not everyone here 
speaks English as a first language. I believe Bearophile is one of those. 
Although his, or possibly her, English is excellent, it wouldn't surprise 
me that (s)he would misinterpret "guys" as just referring to men. I'm a 
native English speaker, and I would have done the same.


> > I have worked with
> > a lot of women in the past and they even use "guys" to refer to
> > everyone in a room (When there were obviously other females in that
> > room as well).

Yes, I've seen this myself, but it's still uncommon enough to surprise me 
every time I see it.


> > On a more serious note, I do apologize to those offended by my remark.
> > I realize that these things can be a touchy subject for some people. I
> > expected more of a laid-back attitude from everyone. No need to be so
> > serious all the time. I cannot completely doubt that there are logical
> > women out there. I just haven't seen one yet. 

That's okay, I haven't seen terribly many logical men out there either.


> Oh, one last thing... So everyone knows, I chose the following
> formatting solution to multiline strings:
> 
> def MyFunction():
>multilineString = (
>   'This is a string that spans '
>   'multiple lines.'
>   )
>print( multilineString )
> 
> I think this is as good as it is going to get for my personal needs.
> However, I do not like having to put a space at the end of each
> string. 

So put them at the beginning of the next line. It makes the space more 
obvious, so it's clearer what you have done. That's what I sometimes do.


> I've also done this in the past, which is slightly more ugly:
> 
>   multilineString = (
>  'This is a string that spans',
>  'multiple lines.'
>  )
>   print( ' '.join( multilineString ) )


It's also less efficient, as it does the concatenation at runtime instead 
of compile time. But for a small script, that's not likely to be a 
problem worth worrying about.
 


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


Re: best practice for documenting a project? pydoc?

2009-08-12 Thread shaileshkumar
Hello,

EPYDOC is very good for automatic generation of documentation from
source code.

You may also consider Sphinx http://sphinx.pocoo.org/ which is used
for many
projects including the official Python documentation, documentation of
Zope (http://docs.zope.org/).
See the full list of projects using Sphinx at 
http://sphinx.pocoo.org/examples.html

- Shailesh


On Aug 12, 7:49 pm, Mark Lawrence  wrote:
> Esmail wrote:
> > Hello,
>
> > A project that I have been working on is getting larger
> > and more complex, and I would like to unload some of the
> > information from my memory/head to some other media (a
> > set of web pages?). I am primarily interested in documenting
> > the classes/methods.
>
> > This documentation is primarily for my use only - as I can't
> > continuously work on this project and have to come back to it
> > after some time, it would be nice to have some documentation
> > available to help jog my memory.
>
> > What is the best way to do this in an automated way? I have
> > been documenting my code as I've gone along.
>
> > Is pydoc still the way to go, or should I use something else?
>
> > Thanks,
> > Esmail
>
> The docs for the constraint package look good, 
> seehttp://labix.org/python-constraintandhttp://labix.org/doc/constraint.
> I think they've been produced with epydoc seehttp://epydoc.sourceforge.net/
>
> --
> Kindest regards.
>
> Mark Lawrence.

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


Re: Programming by Contract

2009-08-12 Thread shaileshkumar
zope.interface provides extensive support for design by contract.
http://pypi.python.org/pypi/zope.interface.
This package can be used independently of zope in other projects.
- Shailesh

On Aug 12, 2:20 am, Ethan Furman  wrote:
> Charles Yeomans wrote:
>
> > On Aug 11, 2009, at 3:30 PM, Ethan Furman wrote:
>
> >> Ethan Furman wrote:
>
> >>> Greetings!
> >>> I have seen posts about the assert statement and PbC (or maybe it  
> >>> was DbC), and I just took a very brief look at pycontract
> >>> (http://www.wayforward.net/pycontract/) and now I have at least one
> >>> question:  Is this basically another  way of thinking about unit
> >>> testing, or is the idea of PbC more  along the lines of *always*
> >>> checking the input/output of functions  to ensure they are correct?  
> >>> (*Contstant vigilance!* as Prof Moody  would say ;)
> >>> I know asserts can be turned off, so they obviously won't work for  
> >>> the latter case, and having seen the sample of pycontract it seems  
> >>> it only does its thing during debugging.
> >>> So is Design (Programming) by Contract a fancy way of saying  
> >>> "Document your inputs/outputs!" or is there more to it?
> >>> ~Ethan~
>
> >> Hmmm...
>
> >> Well, from the (apparently) complete lack of interest, I shall take  
> >> away the (better?) documentation ideas and unit testing ideas, and  
> >> not worry about the rest.  :)
>
> > Design by contract is complementary to unit testing (I notice that the  
> > author of PEP 316 appears confused about this).  DbC is, roughly  
> > speaking, about explicit allocation of responsibility.  Consider this  
> > contrived example.
>
> > def foo(s):
> >     require(s is not None)
> >     //code
> >     ensure(hasattr(returnValue, '__iter__'))
>
> > The require condition tells you that it's the caller's responsibility  
> > to pass a non-nil argument to foo.  The ensure condition is a  guarantee
> > that foo will return something suitable for iteration, if  the
> > precondition in the require condition is satisfied.  These  conditions
> > can be enforced at runtime, but may not be, for reasons of  performance.
>
> > DbC is in fact about not *always* checking the input/output of  
> > functions; on the contrary, Bertrand Meyer, the inventor of DbC,  claims
> > that DbC allows one to eliminate such redundancy, and the  resulting
> > overhead.
>
> > Charles Yeomans
>
> Many thanks!
>
> So if I understand -- Python's EAFP fits well with DbC, as DbC seems
> well suited to say, "This is your responsibility, and this is mine,"
> stated in programming terms (who needs comments? ;)  Combined with unit
> testing (which should be easier to design correctly given the DbC code),
> healthy code seems more attainable.
>
> Interesting.  Thank you for the information.
>
> ~Ethan~

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


Re: Need cleanup advice for multiline string

2009-08-12 Thread Steven D'Aprano
On Wed, 12 Aug 2009 08:11:43 -0700, Simon Forman wrote:

[quoting Robert Dailey]
>> I cannot completely doubt that there are logical
>> women out there. I just haven't seen one yet. But that doesn't mean I'm
>> a sexist.
> 
> Oh my.  And you were doing so well.  You haven't seen a logical woman? 
> Perhaps you're blind because your eyes were torn out by a raging
> marmoset?
> 
> Guess what?  Thinking (or just saying) that /does/ mean you're a sexist.
>  (Even if it was just another "friendly, harmless joke".)

It was an incredibly insensitive thing for Robert to say, having just 
been slapped for a previous insensitive "joke" about women. But still, 
most people, male or female, *aren't* logical. I know I've never met 
somebody who is entirely logical, of either sex, and I'm pretty sure I've 
not met very many people who are even mostly logical. Vulcans we are not. 
Does this mean I'm equally sexist against men *and* women? ("I'm not 
biased, I hate everyone equally!" *wink*)

Hell, here I am, at 2am, defending somebody I don't know, for saying 
something I don't approve of, against somebody who is saying something I 
agree with, out of some sort of misguided sense of fairness. Logic? Ha, 
what's logic got to do with it?



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


Re: httplib incredibly slow :-(

2009-08-12 Thread shaileshkumar
We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre-
built versions for Windows and it works out of the box.

- Shailesh



On Aug 12, 7:14 pm, Max Erickson  wrote:
> Chris Withers  wrote:
>
> > I'm still reeling from what seems to be such a huge problem with
> > httplib that seem to be largely ignored :-(
>
> > Chris
>
> There is an httplib2 (but I don't know anything further about it...):
>
> http://code.google.com/p/httplib2/
>
> Calling wget or curl using a subprocess is probably as easy as it is
> ugly, I use the wget build from here:
>
> http://gnuwin32.sourceforge.net/packages/wget.htm
>
> max

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


Re: Need cleanup advice for multiline string

2009-08-12 Thread David Bolen
Robert Dailey  writes:

> Hey guys. Being a C++ programmer, I like to keep variable definitions
> close to the location in which they will be used. This improves
> readability in many ways. However, when I have a multi-line string
> definition at function level scope, things get tricky because of the
> indents. In this case indents are serving two purposes: For syntax and
> actual text output. The tabs for function scope should not be included
> in the contents of the string. (...)

Personally I'm in the camp that something like this should be hoisted
out of the code path (whether to global scope, a dedicated message
module or configuration file is a design choice).

But if it's going to stay inline, one approach that can maintain some
of the attractive qualities of a triple quoted string is to make use
of the textwrap module:

import textwrap

def RunCommand( commandList ):
   # ...
   if returnCode:
   failMsg = textwrap.dedent('''\
 *
 The following command returned exit code [{:#x}].
 This represents failure of some form. Please review
 the command output for more details on the issue.
 
 {}
 *
 ''')

which removes any common leading whitespace (must be identical in terms
of any tabs/spaces).

This is still additional run-time processing, and most likely less
efficient than the joining of individual strings, but it does permit a
clean triple-quoted string so IMO is easier to read/maintain in the
source - providing the code indentation level doesn't get in the way
of the desired line length of the string.  You can also choose to
dedent the string a bit (say to the level of "failMsg") if needed
without being forced all the way back to the left margin.

You can also combine textwrap.dedent with some of the other options if
where the strings are defined makes it nicer if they still have some
indentation (say in a global Python module).  In that case, you'd most
likely just process them once when the module was imported, so any
inefficiency in textwrap.dedent is far less important.

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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Paul Boddie
On 12 Aug, 17:08, Steven D'Aprano  wrote:
> On Wed, 12 Aug 2009 06:24:18 -0700, Paul Boddie wrote:
>
> > What does the Python entry on Wikipedia have to do with editing the
> > Python documentation in a Wiki?
>
> Good question. I was responding to you mentioning Wikipedia as a possible
> role model for the Python docs.

Yes, but claiming that only a few people want to edit a single entry
on one site (admittedly a popular one) isn't the same as saying that
few people would edit a documentation Wiki covering numerous different
things. A bunch of people edit the existing Python Wiki now, although
there's not that much direction behind it.

[...]

> It's not the people who suggest improvements to the docs that are the
> problem, but the ones who insist that the docs are terrible, but aren't
> willing to do anything but complain. Oh, and trolls like ... I hesitate
> to mention his name in case he has a bot monitoring the list ... first
> name starts with "X" followed by "ah", second name sounds like "Mee" ...
> who even if they make a few good points, they're lost in a sea of insults
> to others, arrogance and self-aggrandisement.

Right, but those good points are still worth taking on board. There
have been Xah Lee posts which have been relatively constructive, but
when the only responses are from people who see the name and can't be
bothered reading the message before issuing a stock "he's a troll"
response, the tone is likely to remain vulgar from that point onwards.
Xah Lee can be quite coherent and rational on comp.lang.lisp, which is
more than can be said for a number of regulars on that group.

[...]

> > P.S. The mention of "social problems" ties in with other remarks made
> > recently, and I've increasingly found it more trouble than has been
> > worthwhile to pursue Python-related matters of late. When one tries to
> > encourage people to participate in improving various things, which
> > usually means the community having to accept a degree of criticism,
> > people claim that it's encouraging "undesirable" influences to point
> > such critics in the right direction instead of showing them the door.
>
> Can you point me to a discussion where this has happened?

I won't name names as in some cases I've corresponded privately with
various people who have been perceived to be "trolls" (as you put it
above) and who have had the "don't talk to them" responses from
various regulars. Some people criticise in apparently unacceptable
ways for their own amusement, but most critics do so because they are
unaware of any better way and aren't aware of the most effective
methods to fix the issues that bother them, and this latter group is
clearly invested in finding solutions because they could quite easily
go and use something else. Certainly, I wouldn't spend my time
repeatedly enumerating the problems with a piece of technology if no-
one were interested in helping me do something about them.

> > When one tries to pursue such improvement matters oneself, people always
> > have something to say about the choice of technology or whether they
> > like the particular background colour being used
>
> You've discovered bike-shedding.
>
> > or indeed have an
> > opinion, typically shallow and negative, about anything but the task at
> > hand,
>
> When you're agitating for change, anyone defending the status quo has
> opinions which are shallow and negative. When you're happy with the
> status quo, possibly even for good, rational reasons and not just because
> you're a shallow-minded, ignorant, know-nothing nay-sayer, it's those
> agitating for change who have shallow and negative opinions. It's such a
> bother trying to determine who is right, so I prefer to just accuse the
> other guy of being shallow and negative rather than try to understand his
> point of view. I find it saves time in the long run.

I can expand what I've written to just about any project,
"improvement" or otherwise, where there may not be an existing
solution that anyone actually supports or is willing to use. And
still, if you give people something they could use (which is better
than effectively nothing), my experience is that in some communities
your work, however trivial, will be appreciated. But I get the
impression that in Python-related communities, it's all "Why didn't
you use XYZ?" or "What a toy!" instead.

[...]

> There seems to be a hidden assumption in your sentence that there *are*
> structural problems in the project.

Let me assume that maybe the barriers aren't really that bad for
Python documentation; that anyone who is really going to care about
submitting something will jump through the hoops and deliver something
that can be merged by the core developers. Even then, there's going to
be a whole class of improvements that won't get made by outsiders and
will fall on the editors to make. Now, more often than not, the people
who are already the most overworked are precisely those in the
position of reviewing and merging changes

Multithreaded library for Python?

2009-08-12 Thread Robert Dailey
Hey guys,

I realize the python library has multithreading support in it, but not
the kind I'm really looking for. I want something like Intel's TBB,
but for Python 3.1. I need to be able to spawn off "Tasks" that
operate until completed and then end by themselves. I could create my
own framework for this, but why bother if a solution already exists?
Anyone know of any libraries out there that would work?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scraping Wikipedia with Python

2009-08-12 Thread Dotan Cohen
> maybe you want dbpedia.

I did not know about this. Thanks!

That is the reason why I ask. This list has an unbelievable collective
knowledge and I am certain that asking "how much is 2+2" would net an
insightful answer that would teach me something.

Thank you, Paul, and thank you to the entire Python list!

-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Scraping Wikipedia with Python

2009-08-12 Thread Dotan Cohen
> http://pypi.python.org/pypi?%3Aaction=search&term=wikipedia ?
>

Thanks, Thorsten, I will go through those. I did not know about that
resource, I am not a regular coder. One more resource to add to the
toolbox!


-- 
Dotan Cohen

http://what-is-what.com
http://gibberish.co.il
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: httplib incredibly slow :-(

2009-08-12 Thread David Stanek
On Tue, Aug 11, 2009 at 4:25 PM, Chris Withers wrote:
> Hi All,
>
> I'm using the following script to download a 150Mb file:
>
> from base64 import encodestring
> from httplib import HTTPConnection
> from datetime import datetime
>
> conn = HTTPSConnection('localhost')
> headers = {}
> auth = 'Basic '+encodestring('username:password').strip()
> headers['Authorization']=auth
> t = datetime.now()
> print t
> conn.request('GET','/somefile.zip',None,headers)
> print 'request:',datetime.now()-t
> response = conn.getresponse()
> print 'response:',datetime.now()-t
> data = response.read()
> print 'read:',datetime.now()-t
>
> The output shows it takes over 20 minutes to do this.
> However, this is on a local network, and downloading the same file in IE
> takes under 3 seconds!
>
> I saw this issue:
>
> http://bugs.python.org/issue2576
>
> I tried changing the buffer size to 4096 in a subclass as the issue
> suggested, but I didn't see the reported speed improvement.
> I'm using Python 2.6.2.
>
> Does anyone know of an alternative library for creating http requests and
> getting their responses that's faster but hopefully has a similar interface?
>

I tried to reproduce this, but I could not. Could you paste in the
output of your script? Also on the same box where you run this script
can you test with curl or wget?

-- 
David
blog: http://www.traceback.org
twitter: http://twitter.com/dstanek
-- 
http://mail.python.org/mailman/listinfo/python-list


Mimicing an HTML form

2009-08-12 Thread Zach Hobesh
Hi all,
I'm having alot of trouble automating the submitting of form.  I have an
HTML page that works and it looks like this:









When I put valid values for the handling script an app ID, this page works.
 Now I'm trying to turn this same functionality into a script.  Here's my
code:

import urllib
import os
import urllib2

appID = *value here*
video = os.path.normpath(os.getcwd() + '/news.wmv')
title = 'News'
desc = 'Here is a sample News video'

uploader = *script here*

print "Encoding url..."
data = urllib.urlencode({"FileUploadedVideo": video,
 "hdnADCID" : appID,
 "txtTitle" : title,
 "txtDescription": desc})

user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }


print "Calling url..."
req = urllib2.Request(uploader, data, headers)

response = urllib2.urlopen(req)
s = response.read()
response.close()

print "Writing results..."
result = open('result.html','w')
result.write(s)
result.close()

Does anybody have any suggestions?  I keep on getting bad request, so I'm
assuming that the html page is passing something that my script is not.  Is
there some way to scrape the POST request from the html form?

Thanks,

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


Re: httplib incredibly slow :-(

2009-08-12 Thread Chris Withers

Max Erickson wrote:

There is an httplib2 (but I don't know anything further about it...):

http://code.google.com/p/httplib2/


I had a look, it uses httplib, so will likely suffer from the same 
problems...


Calling wget or curl using a subprocess is probably as easy as it is 
ugly, I use the wget build from here:


http://gnuwin32.sourceforge.net/packages/wget.htm


Yeah, no ;-)

Chris

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


Re: matching patterns after regex?

2009-08-12 Thread Martin
On Aug 12, 1:42 pm, Martin  wrote:
> On Aug 12, 1:23 pm, Steven D'Aprano 
>
>
> cybersource.com.au> wrote:
> > On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:
> > > I tried
>
> > > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
>
> > You need to put quotes around strings.
>
> > In this case, because you're using regular expressions, you should use a
> > raw string:
>
> > re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
>
> > will probably work.
>
> > --
> > Steven
>
> Thanks I see.
>
> so I tried it and if I use it as it is, it matches the first instance:
> I
> n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
> Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')]
>
> So I adjusted the first part of the regex, on the basis I could sub
> NORTH for SOUTH etc.
>
> In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\.
> \w-]+)",s)
> Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')]
>
> But in both cases it doesn't return the decimal value rather the value
> that comes after NUM_VAL = , rather than VALUE = ?

I think I kind of got that to work...but I am clearly not quite
understanding how it works as I tried to use it again to match
something else.

In this case I want to print the values 0.00 and 2223901.039333
from a string like this...

YDim=1200\n\t\tUpperLeftPointMtrs=(0.00,2223901.039333)\n\t\t

I tried which I though was matching the statement and printing the
decimal number after the equals sign??

re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s)

where s is the string

Many thanks for the help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: httplib incredibly slow :-(

2009-08-12 Thread Shailesh Kumar
Yes it includes libcurl. I didn't have to install it separately. I still
continue to use Python 2.4. So cannot say about Python 2.6.

- Shailesh

On Wed, Aug 12, 2009 at 10:23 PM, Chris Withers wrote:

> shaileshkumar wrote:
>
>> We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre-
>> built versions for Windows and it works out of the box.
>>
>
> Does it include libcurl? Are these builds available for Python 2.6?
>
> Chris
>
> --
> Simplistix - Content Management, Batch Processing & Python Consulting
>   - http://www.simplistix.co.uk
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: httplib incredibly slow :-(

2009-08-12 Thread Chris Withers

shaileshkumar wrote:

We use PyCURL on Windows. http://pycurl.sourceforge.net/ provides pre-
built versions for Windows and it works out of the box.


Does it include libcurl? Are these builds available for Python 2.6?

Chris

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


How to find all possibly overlapping matches?

2009-08-12 Thread kj


re.findall finds all non-overlapping matches, but what if one wants
all (maximal) matches, even those that overlap?

All the solutions I can come up involve calling re.search iteratively,
each time giving it a pos parameter starting just after the start
of the previous match.

Is there a built-in solution to such a task?

TIA!

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


Re: best practice for documenting a project? pydoc?

2009-08-12 Thread Esmail

shaileshkumar wrote:

Hello,

EPYDOC is very good for automatic generation of documentation from
source code.

You may also consider Sphinx http://sphinx.pocoo.org/ which is used
for many
projects including the official Python documentation, documentation of
Zope (http://docs.zope.org/).
See the full list of projects using Sphinx at 
http://sphinx.pocoo.org/examples.html

- Shailesh


Hi,

Thanks for the links. Have you heard of something called HappyDoc? I just
came across it by looking for info on epydoc.

Thanks,
Esmail

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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Ethan Furman

Paul Boddie wrote:

On 12 Aug, 17:08, Steven D'Aprano  wrote:

It's not the people who suggest improvements to the docs that are the
problem, but the ones who insist that the docs are terrible, but aren't
willing to do anything but complain. Oh, and trolls like ... I hesitate
to mention his name in case he has a bot monitoring the list ... first
name starts with "X" followed by "ah", second name sounds like "Mee" ...
who even if they make a few good points, they're lost in a sea of insults
to others, arrogance and self-aggrandisement.



Right, but those good points are still worth taking on board. 


The responsibility for communication is shared.  How much to each party 
varies by circumstance (employer/employee, rank, volunteer, etc.).  For 
myself, his posts are automatically deleted -- my time is precious to me.


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


Re: httplib incredibly slow :-(

2009-08-12 Thread Chris Withers

David Stanek wrote:

I tried to reproduce this, but I could not. Could you paste in the
output of your script? 


Not sure how that'll help, but sure:

2009-08-11 21:27:59.153000
request: 0:00:00.109000
response: 0:00:00.109000
read: 0:24:31.266000

> Also on the same box where you run this script

can you test with curl or wget?


It's a Windows box, so no :-(
But it really does download in a few seconds with IE, and 20min+ using 
the script I included...


Chris

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


Re: best practice for documenting a project? pydoc?

2009-08-12 Thread Esmail

Mark Lawrence wrote:
Hi Mark,


The docs for the constraint package look good, see
http://labix.org/python-constraint and http://labix.org/doc/constraint.
I think they've been produced with epydoc see 
http://epydoc.sourceforge.net/


Thanks for the links, I'll take a look.

Any experience with something called HappyDoc? Just came across it.

Esmail


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


Re: How to find all possibly overlapping matches?

2009-08-12 Thread MRAB

kj wrote:


re.findall finds all non-overlapping matches, but what if one wants
all (maximal) matches, even those that overlap?

All the solutions I can come up involve calling re.search iteratively,
each time giving it a pos parameter starting just after the start
of the previous match.

Is there a built-in solution to such a task?


Not in the re module.

It has been requested and is in my regex implementation at
http://bugs.python.org/issue2636 if you want to try that.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unrecognized escape sequences in string literals

2009-08-12 Thread Douglas Alan
On Aug 12, 3:08 am, Steven D'Aprano
 wrote:

> On Tue, 11 Aug 2009 14:48:24 -0700, Douglas Alan wrote:
> > In any case, my argument has consistently been that Python should have
> > treated undefined escape sequences consistently as fatal errors,
>
> A reasonable position to take. I disagree with it, but it is certainly
> reasonable.
>
> > not as warnings.
>
> I don't know what language you're talking about here, because non-special
> escape sequences in Python aren't either errors or warnings:
>
> >>> print "ab\cd"
>
> ab\cd

I was talking about C++, whose compilers tend to generate warnings for
this usage. I think that the C++ compilers I've used take the right
approach, only ideally they should be *even* more emphatic, and
elevate the problem from a warning to an error.

I assume, however, that the warning is a middle ground between doing
the completely right thing, and, I assume, maintaining backward
compatibility with common C implementations. As Python never had to
worry about backward compatibility with C, Python didn't have to walk
such a middle ground.

On the other hand, *now* it has to worry about backward compatibility
with itself.

|>ouglas


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


Re: best practice for documenting a project? pydoc?

2009-08-12 Thread Mark Lawrence

Esmail wrote:

Mark Lawrence wrote:
Hi Mark,


The docs for the constraint package look good, see
http://labix.org/python-constraint and http://labix.org/doc/constraint.
I think they've been produced with epydoc see 
http://epydoc.sourceforge.net/


Thanks for the links, I'll take a look.

Any experience with something called HappyDoc? Just came across it.

Esmail



Sorry never heard of it, or if I had I've forgotten it.

--
Kindest regards.

Mark Lawrence.

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


Re: fileinput

2009-08-12 Thread Dave Angel

naaman wrote:

I'm writing my first Python script and
I want to use fileinput to open a file in r+ mode.
Tried fileinput.input(sys.argv[1:],"r+") but that didn't work.
ANy ideas?

Need to find and overwrite a line in a file several times.
I can do it using open and seek() etc. but was wondering if I can use
fileinput.

thanks;


  

I haven't used it, but check out the 'inplace' keyword parameter.

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


Re: hashability

2009-08-12 Thread James Stroud

Steven D'Aprano wrote:
Well there you go -- why on earth would you prohibit None as a dictionary 
key??? That's a serious failure.



roentgen 1% python
Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) 
[GCC 3.4.2] on linux2

Type "help", "copyright", "credits" or "license" for more information.
py> hash(None)
135543872


mbi136-176 98% /usr/bin/python
Python 2.5.1 (r251:54863, Feb  6 2009, 19:02:12) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin

Type "help", "copyright", "credits" or "license" for more information.
py> hash(None)
2030240



That's why. Read the whole thread. You are one of the abrasive ones.
--
http://mail.python.org/mailman/listinfo/python-list


Re: Unrecognized escape sequences in string literals

2009-08-12 Thread Douglas Alan
On Aug 12, 3:36 am, Steven D'Aprano
 wrote:

> On Tue, 11 Aug 2009 13:20:52 -0700, Douglas Alan wrote:

> > My "Annotated C++ Reference Manual" is packed, and surprisingly in
> > Stroustrup's Third Edition, there is no mention of the issue in the
> > entire 1,000 pages. But Microsoft to the rescue:
>
> >      If you want a backslash character to appear within a string, you
> >      must type two backslashes (\\)
>
> > (From http://msdn.microsoft.com/en-us/library/69ze775t.aspx)
>
> Should I assume that Microsoft's C++ compiler treats it as an error, not
> a warning?

In my experience, C++ compilers generally generate warnings for such
situations, where they can. (Clearly, they often can't generate
warnings for running off the end of an array, which is also undefined,
though a really smart C++ compiler might be able to generate a warning
in certain such circumstances.)

> Or is is this *still* undefined behaviour, and MS C++ compiler
> will happily compile "ab\cd" whatever it feels like?

If it's a decent compiler, it will generate a warning. Who can say
with Microsoft, however. It's clearly documented as illegal code,
however.

> > The question of what any specific C++ does if you ignore the warning is
> > irrelevant, as such behavior in C++ is almost *always* undefined. Hence
> > the warning.
>
> So a C++ compiler which follows Python's behaviour would be behaving
> within the language specifications.

It might be, but there are also *recommendations* in the C++ standard
about what to do in such situations, and the recommendations say, I am
pretty sure, not to do that, unless the particular compiler in
question has to meet some very specific backward compatibility needs.

> I note that the bash shell, which claims to follow C semantics, also does
> what Python does:
>
> $ echo $'a s\trin\g with escapes'
> a s     rin\g with escapes

Really? Not on my computers. (One is a Mac, and the other is a Fedora
Core Linux box.) On my computers, bash doesn't seem to have *any*
escape sequences, other than \\, \", \$, and \`. It seems to treat
unknown escape sequences the same as Python does, but as there are
only four known escape sequences, and they are all meant merely to
guard against string interpolation, and the like, it's pretty darn
easy to keep straight.

> Explain to me again why we're treating underspecified C++ semantics,
> which may or may not do *exactly* what Python does, as if it were the One
> True Way of treating escape sequences?

I'm not saying that C++ does it right for Python. The right thing for
Python to do is to generate an error, as Python doesn't have to deal
with all the crazy complexities that C++ has to.

|>ouglas
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hashability

2009-08-12 Thread Chris Rebert
On Wed, Aug 12, 2009 at 1:37 PM, James Stroud wrote:
> Steven D'Aprano wrote:
>>
>> Well there you go -- why on earth would you prohibit None as a dictionary
>> key??? That's a serious failure.
>
>
> roentgen 1% python
> Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) [GCC 3.4.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> py> hash(None)
> 135543872
>
>
> mbi136-176 98% /usr/bin/python
> Python 2.5.1 (r251:54863, Feb  6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc.
> build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> py> hash(None)
> 2030240

Actually, None is a special-case as a built-in singleton value --
there's only ever *exactly one* instance of it in a given interpreter
session. And I'm reasonably sure dict pickles don't store the hash
code of items (the dict gets recreated from scratch), so there's no
problem.

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


Re: How to find all possibly overlapping matches?

2009-08-12 Thread kj
In  MRAB 
 writes:

>kj wrote:
>> 
>> re.findall finds all non-overlapping matches, but what if one wants
>> all (maximal) matches, even those that overlap?
>> 
>> All the solutions I can come up involve calling re.search iteratively,
>> each time giving it a pos parameter starting just after the start
>> of the previous match.
>> 
>> Is there a built-in solution to such a task?
>> 
>Not in the re module.

>It has been requested and is in my regex implementation at
>http://bugs.python.org/issue2636 if you want to try that.

Cool.  Thanks!

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


Re: SQLObject 0.11.0

2009-08-12 Thread William
I don't want to start a flame war and would just like some information before 
diving in--
What are some the advantages and disadvantages of SQLObject compared to 
SQLAlchemy?

Thanks,
William




From: Oleg Broytmann 
To: Python Mailing List ; Python Announce Mailing List 

Sent: Wednesday, August 12, 2009 6:24:53 AM
Subject: SQLObject 0.11.0

Hello!

I'm pleased to announce version 0.11.0, the first stable release of 0.11 branch
of SQLObject.


What is SQLObject
=

SQLObject is an object-relational mapper.  Your database tables are described
as classes, and rows are instances of those classes.  SQLObject is meant to be
easy to use and quick to get started with.

SQLObject supports a number of backends: MySQL, PostgreSQL, SQLite,
Firebird, Sybase, MSSQL and MaxDB (also known as SAPDB).


Where is SQLObject
==

Site:
http://sqlobject.org

Development:
http://sqlobject.org/devel/

Mailing list:
https://lists.sourceforge.net/mailman/listinfo/sqlobject-discuss

Archives:
http://news.gmane.org/gmane.comp.python.sqlobject

Download:
http://cheeseshop.python.org/pypi/SQLObject/0.11.0

News and changes:
http://sqlobject.org/News.html


What's New
==

News since 0.10
-

Features & Interface


* Dropped support for Python 2.3. The minimal version of Python for
  SQLObject is 2.4 now.

* Dropped support for PostgreSQL 7.2. The minimal supported version of
  PostgreSQL is 7.3 now.

* New magic attribute 'j' similar to 'q' was added that automagically does
  join with the other table in MultipleJoin or RelatedJoin.

* SQLObject can now create and drop a database in MySQL, PostgreSQL, SQLite
  and Firebird/Interbase.

* Added some support for schemas in PostgreSQL.

* Added DecimalStringCol - similar to DecimalCol but stores data as strings
  to work around problems in some drivers and type affinity problem in
  SQLite.

* Added sqlobject.include.hashcol.HashCol - a column type that automatically
  hashes anything going into it, and returns out an object that hashes
  anything being compared to itself. Basically, it's good for really simple
  one-way password fields, and it even supports the assignment of None to
  indicate no password set. By default, it uses the md5 library for
  hashing, but this can be changed in a HashCol definition.

* RowDestroyedSignal and RowUpdatedSignal were added.

Minor features
~~

* Use reversed() in manager/command.py instead of .__reversed__().

* Minor change in logging to console - logger no longer stores the output
  file, it gets the file from module sys every time by name; this means
  logging will use new sys.stdout (or stderr) in case the user changed
  them.

* Changed the order of testing of SQLite modules - look for external
  PySQLite2 before sqlite3.

For a more complete list, please see the news:
http://sqlobject.org/News.html

Oleg.
-- 
 Oleg Broytmannhttp://phd.pp.ru/[email protected]
   Programmers don't die, they just GOSUB without RETURN.
-- 
http://mail.python.org/mailman/listinfo/python-list



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


Re: hashability

2009-08-12 Thread Steven D'Aprano
On Wed, 12 Aug 2009 10:37:45 -0700, James Stroud wrote:

> Steven D'Aprano wrote:
>> Well there you go -- why on earth would you prohibit None as a
>> dictionary key??? That's a serious failure.
> 
> 
> roentgen 1% python
> Python 2.5 (r25:51908, Sep 20 2006, 17:36:21) [GCC 3.4.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> py> hash(None)
> 135543872
> 
> 
> mbi136-176 98% /usr/bin/python
> Python 2.5.1 (r251:54863, Feb  6 2009, 19:02:12) [GCC 4.0.1 (Apple Inc.
> build 5465)] on darwin Type "help", "copyright", "credits" or "license"
> for more information. py> hash(None)
> 2030240
> 
> 
> 
> That's why. Read the whole thread. You are one of the abrasive ones.

I've read the whole thread. Pay close attention:

[st...@ando ~]$ python
Python 2.4.3 (#1, Mar 14 2007, 18:51:08)
[GCC 4.1.1 20070105 (Red Hat 4.1.1-52)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> d = {None: 42}
>>> f = open('pickled_dict', 'w')
>>> pickle.dump(d, f)
>>> f.close()
>>>
[st...@ando ~]$ ssh sylar
st...@sylar's password:
Last login: Wed Aug 12 21:44:47 2009
[st...@sylar ~]$ python2.6
Python 2.6.1 (r261:67515, Dec 24 2008, 00:33:13)
[GCC 4.1.2 20070502 (Red Hat 4.1.2-12)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> f = open('pickled_dict', 'r')
>>> d = pickle.load(f)
>>> d
{None: 42}


I have successfully pickled a dict using None as a key on one machine 
using Python 2.4, and unpickled it on a completely different machine 
running Python 2.6.

Still think that pickling None is a problem?



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


Pulling arrays from database for plotting

2009-08-12 Thread Kurt Schwehr
Hi all,

What's the best way to pull arrays from a database for plotting?
Right now, this is what I do, but can it be done simpler / more
efficiently?

ipython -pylab
import sqlite3
cx = sqlite3.connect('20080407.decimated.db3')
a = array( [tuple(row) for row in cx.execute('SELECT cg_offset,
delta_t_sec FROM bs_time WHERE recvr=2;')] )
x = a[:,0]
y = a[:,1]
plot(x,y)

However, if I try to plot it directly using transpose, it hangs:

import sqlite3
cx = sqlite3.connect('20080407.decimated.db3')
plot(array( [tuple(row) for row in cx.execute('SELECT cg_offset,
delta_t_sec FROM bs_time WHERE recvr=2;')] ).transpose())

It is that plot just doesn't know what to do with a 2D array?  Then I
tried this and it works, but is long and confusing to the uninitiated.

plot(*array( [tuple(row) for row in cx.execute('SELECT cg_offset,
delta_t_sec FROM bs_time WHERE recvr=2;')] ).T)



In [4]: a
Out[4]:
array([[  2.4000e+01,   0.e+00],
   [  2.5000e+01,  -1.e+00],
   [  3.4000e+01,   0.e+00],
   ...,
   [  8.6384e+04,   2.e+01],
   [  8.6394e+04,   2.e+01],
   [  8.6404e+04,   2.e+01]])

In [5]: a.transpose()
Out[5]:
array([[  2.4000e+01,   2.5000e+01,   3.4000e+01, ...,
  8.6384e+04,   8.6394e+04,   8.6404e+04],
   [  0.e+00,  -1.e+00,   0.e+00, ...,
  2.e+01,   2.e+01,   2.e+01]])



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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Raymond Hettinger
On Aug 12, 3:32 am, Paul Boddie  wrote:
> Maybe the problem is that although everyone welcomes contributions and
> changes (or says that they do), the mechanisms remain largely beyond
> criticism.

FWIW, I support the idea the regular docs incorporating links to
freely editable wiki pages.  That will at least make it easier for
people to make changes or add notes.

That being said, I would like to add a few thoughts about the
current process.   ISTM that important corrections (when the
docs are clearly in error) tend to get made right away.  What
is more interesting are the doc requests that get rejected
and why:

* Many doc requests come from people just learning the language
(that makes sense because the learning process involves reading
the docs).  Unfortunately, a fair number of those requests are
flat-out wrong or represent a profound misunderstanding of the
feature in question.  That may be an indicator that the docs
need to be improved, but the specific suggestion can be inane.

* Some doc requests come from people who simply do not like the
feature in question.  It is natural for tastes, styles, and
preferences to vary; however, we do have a firm rule that Guido's
tastes, styles, and preferences are the ones that go into the
language.  So the doc writers need to try to channel Guido instead
of fighting him.  So, if you think eval() is evil (I don't but many
do), we're not going to document that eval() should *never* be used.
If you hate super(), that's too bad -- the docs need to describe
what it does and how it was intended to be used -- the docs are no
place for diatribes on why inheritance is over-used and why you
think the world would be a better place without mixins or
multiple inheritance.

* Then, there is a matter of where to put a particular piece of
documentation (how many times do you repeat a concept that pervades
the language).  Hashing is a good example.  The docs can discuss how
some objects hash to their object id and that object ids can change
from run-to-run, but if someone gets tripped-up by the idea (hey,
my set reprs changed between runs, wtf!), they want the docs updated
in the specific place that tripped them up (i.e. you must put big
red warnings in the set documentation, and the dict documentation,
and everywhere else a hash gets used ...).   The core problem is that
the docs are interrelated -- the one place you're looking for
documentation of a specific builtin or function can't contain
every concept in the language.

* Some behaviors are intentionally left unspecified.  For the longest
time, Tim did not want to guarantee sort stability.  This left him
free to continue to search for algorithmic improvements that did not
have stability.  Later, the property was deemed so important that it
did become a guaranteed behavior.  Also, some things are unspecified
to make things easier for other implementations (IronPython, PyPy,
Jython, etc.)  We need to make sure that some one doesn't casually
go through the docs making doc promises that are hard to keep.

* Some things are just plain difficult to fully explain in English
and not misrepresent that actual behavior.  For example, the str.split
()
docs have been continuously tweaked over the years.  Even now, I think
there are corner cases that are not fully captured by the docs.
Casual
edits to str.split() docs are more likely than not to take them
farther
away from the truth.

* Then, there is the problem of talking too much.  A book could be
written about super(), but that shouldn't all go into the docs for
the super builtin.  Beginners often want to master all the builtins
and they try to read the doc page on builtin functions.  It used to be
that you could read through the builtin descriptions in a few minutes.
Now, it takes a concerted effort to get through.  It is hard to take
a sip of water from a firehose.  Too much information has make a
function harder to understand.

* My biggest pet peeve are requests to fill the docs with big red
warnings.  I do not want the docs to look like a mine field.  The
warnings
should be reserved for a handful of security or data corruption risks.
For the most part, the docs should be matter-of-fact, explaining what
a function or method does and how it was intended to be used.

Preferred:  "The value str.letters is locale dependent"

Not preferred:  "Caution, the str.letters value can be adversely
affected by the locale setting (it could even change length!); use
this
only when you are certain the locale setting will not violate any of
your program invariants; consider using a string literal instead; I
hate
string.letters and think Guido was smoking crack when it was
introduced."

* Another category of rejected doc requests come from people looking
for
absolution from one of their programming bugs.  It typically takes the
form of, "I made an assumption that the language did X, but it did Y
and my program didn't do what I wanted; therefore, the docs must be
to blame and they must change ...". 

Re: SQLObject 0.11.0

2009-08-12 Thread Daniel Fetchinson
> I don't want to start a flame war and would just like some information
> before diving in--
> What are some the advantages and disadvantages of SQLObject compared to
> SQLAlchemy?

In short: sqlobject is much simpler (to use, to understand, etc) than
sqlalchemy and so I prefer it in small projects. This advantage is
also a disadvantage when you have large and complex projects in mind.

Cheers,
Daniel

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: hashability

2009-08-12 Thread Carl Banks
On Aug 12, 10:37 am, James Stroud  wrote:
> Steven D'Aprano wrote:
> > Well there you go -- why on earth would you prohibit None as a dictionary
> > key??? That's a serious failure.
>
> roentgen 1% python
> Python 2.5 (r25:51908, Sep 20 2006, 17:36:21)
> [GCC 3.4.2] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> py> hash(None)
> 135543872
>
> mbi136-176 98% /usr/bin/python
> Python 2.5.1 (r251:54863, Feb  6 2009, 19:02:12)
> [GCC 4.0.1 (Apple Inc. build 5465)] on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> py> hash(None)
> 2030240
>
> That's why. Read the whole thread. You are one of the abrasive ones.

FYI: If you need the actual hash value to be consistent across
versions of Python the built hash function won't suffice.  The
language doesn't guanrantee they will persist across versions.  (IIRC,
there was a change to the hash value of longs at one point related to
int/long unification issues.)

Now, when I saw your explanation I assumed that your persistence
mechanism merely doesn't preserve identity (unlike, say, simple
pickling, which does), meaning that objects that were once identical
might be reconstituted as non-identical (or vice versa), which would
be an issue if these objects are stored in dicts or sets.  Equality
must be preserved for dict keys and set members to continue to work
property.  However, the actual hash code doesn't need to be preserved.

As was mentioned already, None is guaranteed by the language to be
equal to itself, so equality is preserved and there should be no issue
with it, even if the hash code changes across invocations.

Now, if you are doing something weird with the hash value itself--
which I highly discourage--then all bets are off.


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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Raymond Hettinger
[Xah Lee]
> i've wrote several articles about this issue, total time spend on this
> is probably more than 2 months full-time work. See:
>
> • Python Documentation Problems
>  http://xahlee.org/perl-python/python_doc_index.html

I just read you post.   You did devote a substantial amount of time
to the project.  Some of your criticisms are valid.  Wish you had
posted patches, I think many of them would have been accepted.

Since you wrote this a few years ago, many examples have
been added to the docs and more are forthcoming.



> I often receive thank you emails for 2 particular articles, which are
> most frequently google searched as indicated by my weblog:
>
> • Python Doc Problem Example: gzip
>  http://xahlee.org/perl-python/python_doc_gzip.html
>
> • Python Doc Problem Example: sort()
>  http://xahlee.org/perl-python/python_doc_sort.html
>
> • Sorting in Python and Perl
>  http://xahlee.org/perl-python/sort_list.html

Some are the criticisms are valid; others seem off-base.

Here are a few thoughts on list.sort() for those who are interested:

* The key= and reversed= parameters are not intended for special
cases, leaving cmp= for the general case.  They were intended to
be full replacements.  In Python3.x, the cmp function is gone.

* The interaction of the key= and cmp= functions can be made to
interact (the key function is first applied to every element and
the cmp function then gets applied to the results of the key
function).  This isn't a normal or intended use case, so the docs
don't delve into the subject.

* The reversed parameter does more than list.sort() followed by
list.reverse().  It also preserves stability in the event of equal
keys:

   >>> sorted([(1,2), (1,3)], key=itemgetter(0), reverse=True)
   [(1,2), (1,3)]

So it was not correct to say that the following are equivalent:

li.sort(lambda x, y: cmp(x[1],y[1]), reverse=True)
li.sort(lambda x, y: cmp(y[1],x[1]))

* We should link the sorted() and list.sort() docs to the
sorting how-to (with a fuller discussion on the art of sorting
including a discussion of operator.itemgetter() and
operator.attrgetter() which were designed to work with the key=
parameter.


Raymond


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


Extending embedded python-can extensions be local to a dictionary?

2009-08-12 Thread Michael Kohout
Hello all-

I've got a multithreaded server-based application that I'd like to use
python to provide plugin support for.  At execution time I would like
each call to the plugin/plugins to have their own implementation of
these extension methods.

Looking at 
http://docs.python.org/extending/embedding.html#extending-embedded-python,
I see how to add functions, but it looks like they are added at a
global scope-not in a particular environment.  Is there any way to add
an extension to a local environment but not pollute the global env?

FYI, I'm embedding python 2.6, but I'm more than open to embedding
something newer.

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


Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread r
On Aug 12, 1:27 pm, Raymond Hettinger  wrote:
(snip)
> * Many doc requests come from people just learning the language
> (that makes sense because the learning process involves reading
> the docs).  Unfortunately, a fair number of those requests are
> flat-out wrong or represent a profound misunderstanding of the
> feature in question.  That may be an indicator that the docs
> need to be improved...

Yes, if many people have problems with the docs then that must be a
*clue* to some underling problem in the way the docs are presented.
Whether its from misinfomation, misguidance, or just plain
misunderstanding on the reader's part that does not matter. There are
problems and we need the feedback from everybody noob-to-pro on how to
fix this conundrum. One thing that some naysayers may forget is the
fact that these noobs most likely have no idea *how*, *when*, or
*where* to voice a complaint so they just move on to the next language
or suffer with an incomplete understanding of the language and/or
proper python idioms. I would say the complaints that this list has
seen concerning docs only scratches the surface of the huge underling
issues that face us here!

> So, if you think eval() is evil (I don't but many
> do), we're not going to document that eval() should *never* be used.
> If you hate super(), that's too bad -- the docs need to describe
> what it does and how it was intended to be used -- the docs are no
> place for diatribes on why inheritance is over-used and why you
> think the world would be a better place without mixins or
> multiple inheritance.

Eloquent and beautiful a paragraph that was Raymond. Why, because
common sense is just so damn beautiful. Keep the docs clean of
personal opinions and just give us the facts people. Who cares about
the history of OOP --Google it!-- i want to read about using Python.
Give me the nitty-gritty-down-and-dirty-facts that relate to Python
syntax and structure, and only the facts, in the most strait forward
and common sense way so i can get on to actually writing some code!

If you seek self gratification visit c.l.py and vent away, everyone
else seems to.
-- 
http://mail.python.org/mailman/listinfo/python-list


Format Code Repeat Counts?

2009-08-12 Thread jschwab
Are repeat counts supported Python's str.format() in some fashion?

In Fortran my format strings can have repeat counts.


write(*, fmt="3F8.3") [1, 2, 3]
   1.000  2.000   3.000


I don't think printf-style format codes, which is what'd I'd
previously used in Python, allow for repeat counts.

As a more concrete example, say I have several sets of letters in a
list of strings
 letters = ["aeiou", "hnopty", "egs", "amsp"]
and I wanted to build a regular expression string out of them like
 re_str <==> "[aeiou][hnopty][egs][amsp]"
Right now, the best I've got that doesn't require an explicit string
like "[{1}][{2}][{3}][{4}]" is
 re_str = "".join(map(lambda x: "[{0}]".format(x), letters))

Is there a better way?

Thanks,
Josiah


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


csv.DictWriter.write_header()

2009-08-12 Thread Alan G Isaac
Given a csv.DictWriter instance `dw`
I think it would be nice to be able to
say dw.write_header()
instead of
dw.writer.writerow(dw.fieldnames)

Good idea?

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


Re: matching patterns after regex?

2009-08-12 Thread Bernard
On 12 août, 12:43, Martin  wrote:
> On Aug 12, 1:42 pm, Martin  wrote:
>
>
>
>
>
> > On Aug 12, 1:23 pm, Steven D'Aprano 
> > cybersource.com.au> wrote:
> > > On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:
> > > > I tried
>
> > > > re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)
>
> > > You need to put quotes around strings.
>
> > > In this case, because you're using regular expressions, you should use a
> > > raw string:
>
> > > re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
>
> > > will probably work.
>
> > > --
> > > Steven
>
> > Thanks I see.
>
> > so I tried it and if I use it as it is, it matches the first instance:
> > I
> > n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
> > Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')]
>
> > So I adjusted the first part of the regex, on the basis I could sub
> > NORTH for SOUTH etc.
>
> > In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\.
> > \w-]+)",s)
> > Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')]
>
> > But in both cases it doesn't return the decimal value rather the value
> > that comes after NUM_VAL = , rather than VALUE = ?
>
> I think I kind of got that to work...but I am clearly not quite
> understanding how it works as I tried to use it again to match
> something else.
>
> In this case I want to print the values 0.00 and 2223901.039333
> from a string like this...
>
> YDim=1200\n\t\tUpperLeftPointMtrs=(0.00,2223901.039333)\n\t\t
>
> I tried which I though was matching the statement and printing the
> decimal number after the equals sign??
>
> re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s)
>
> where s is the string
>
> Many thanks for the help

You have to do it with 2 matches in the same regex:

regex = r"UpperLeftPointMtrs=\(([\d\.]+),([\d\.]+)"

The first match  is before the , and the second one is after the , :)

You should probably learn how to play with regexes.
I personnaly use a visual tool called RX Toolkit[1] that comes with
Komodo IDE.

[1] http://docs.activestate.com/komodo/4.4/regex.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Extending embedded python-can extensions be local to a dictionary?

2009-08-12 Thread Carl Banks
On Aug 12, 12:44 pm, Michael Kohout  wrote:
> Hello all-
>
> I've got a multithreaded server-based application that I'd like to use
> python to provide plugin support for.  At execution time I would like
> each call to the plugin/plugins to have their own implementation of
> these extension methods.

I am guessing that what you really want is each call to have its own
data.  There isn't much reason for each call to have its own methods.

If that's not correct you will have to elaborate.


> Looking 
> athttp://docs.python.org/extending/embedding.html#extending-embedded-py...,
> I see how to add functions, but it looks like they are added at a
> global scope-not in a particular environment.  Is there any way to add
> an extension to a local environment but not pollute the global env?

A couple things.  They're not in a global scope, "globals" in Python
have a scope local to a module (global is a misnomer, at best it means
"globally accessible").  So you don't have to worry about a function
defined on one module clashing with a function defined in another
modules.

However, even if name-clashes aren't an issue there isn't much point
to defining the same function mulitple times for multiple calls.

What you probably want is to define a new type that contains all the
data extension code would need.  For each call to the plugin, you
would create an object of this type, then pass it to the appropriate
plugin function.


I have given you a vague answer because your question was vague; if
you want a better answer please rephrase to be more specific.  Include
details like what you would like the code of a Python plugin to look
like.


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


How to launch a function at regular time intervals ?

2009-08-12 Thread David
Hi all, I'm trying to launch a function at regular time intervals but
cannot find the way to do it. Here is the code I wrote (time_interval
is a user defined variable in seconds):

while(1)
  timestamp=datetime.now()
 
timestamp_seconds=timestamp.hour*3600+timestamp.minute*60+timestamp.second
  if timestamp_seconds % time_interval == 0: Call Function

This does not work because during the second at which the condition
holds true, there is time to call the function several times. Since I
want to have this function called only once every x seconds, I tried
to add the following condition:

if timestamp_seconds % time_interval ==0 & timestamp.microsecond == 0

But it seems this second condition hardly ever happens (i.e. the
timestamp variable is not updated every microsecond, therefore it can
be 9998 then jump directly to 0003 for instance).

Has anyone run into a similar problem (and solved it) ?

Thanks for your help
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unrecognized escape sequences in string literals

2009-08-12 Thread Douglas Alan
On Aug 12, 5:32 am, Steven D'Aprano
 wrote:

> That problem basically boils down to a deep-seated
> philosophical disagreement over which philosophy a
> language should follow in regard to backslash escapes:
>
> "Anything not explicitly permitted is forbidden"
>
> versus
>
> "Anything not explicitly forbidden is permitted"

No, it doesn't. It boils down to whether a language should:

(1) Try it's best to detect errors as early as possible,
especially when the cost of doing so is low.

(2) Make code as readable as possible, in part by making
code as self-evident as possible by mere inspection and by
reducing the amount of stuff that you have to memorize. Perl
fails miserably in this regard, for instance.

(3) To quote Einstein, make everything as simple as
possible, and no simpler.

(4) Take innately ambiguous things and not force them to be
unambiguous by mere fiat.

Allowing a programmer to program using a completely
arbitrary resolution of "unrecognized escape sequences"
violates all of the above principles.

The fact that the meanings of unrecognized escape sequences
are ambiguous is proved by the fact that every language
seems to treat them somewhat differently, demonstrating that
there is no natural intuitive meaning for them.

Furthermore, allowing programmers to use "unrecognized escape
sequences" without raising an error violates:

(1) Explicit is better than implicit:

Python provides a way to explicitly specify that you want a
backslash. Every programmer should be encouraged to use
Python's explicit mechanism here.

(2) Simple is better than complex:

Python currently has two classes of ambiguously
interpretable escape sequences: "unrecognized ones", and
"illegal" ones. Making a single class (i.e. just illegal
ones) is simpler.

Also, not having to memorize escape sequences that you
rarely have need to use is simpler.

(3) Readability counts:

See above comments on readability.

(4) Errors should never pass silently:

Even the Python Reference Manual indicates that unrecognized
escape sequences are a source of bugs. (See more comments on
this below.)

(5) In the face of ambiguity, refuse the temptation to
guess.

Every language, other than C++, is taking a guess at what
the programmer would find to be most useful expansion for
unrecognized escape sequences, and each of the languages is
guessing differently. This temptation should be refused!

You can argue that once it is in the Reference Manual it is
no longer a guess, but that is patently specious, as Perl
proves. For instance, the fact that Perl will quietly convert
an array into a scalar for you, if you assign the array to a
scalar variable is certainly a "guess" of the sort that this
Python koan is referring to. Likewise for an arbitrary
interpretation of unrecognized escape sequences.

(6) There should be one-- and preferably only one --obvious
way to do it.

What is the one obvious way to express "\\y"? It is "\\y" or
"\y"?

Python can easily make one of these ways the "one obvious
way" by making the other one raise an error.

(7) Namespaces are one honking great idea -- let's do more
of those!

Allowing "\y" to self-expand is intruding into the namespace
for special characters that require an escape sequence.

> C++ apparently forbids all escape sequences, with
> unspecified behaviour if you use a forbidden sequence,
> except for a handful of explicitly permitted sequences.
>
> That's not better, it's merely different.

It *is* better, as it catches errors early on at little
cost, and for all the other reasons listed above.

> Actually, that's not true -- that the C++ standard forbids
> a thing, but leaves the consequences of doing that thing
> unspecified, is clearly a Bad Thing.

Indeed. But C++ has backward compatibly issues that make
any that Python has to deal with, pale in comparison. The
recommended behavior for a C++ compiler, however, is to flag
the problem as an error or as a warning.

> So on at least one machine in the world, C++ simply strips
> out backslashes that it doesn't recognize, leaving the
> suffix. Unfortunately, we can't rely on that, because C++
> is underspecified.

No, *fortunately* you can't rely on it, forcing you to go
fix your code.

> Fortunately this is not a problem with
> Python, which does completely specify the behaviour of
> escape sequences so there are no surprises.

It's not a surprise when the C++ compiler issues a warning to
you. If you ignore the warning, then you have no one to
blame but yourself.

> Implicit has an actual meaning. You shouldn't use it as a
> mere term of opprobrium for anything you don't like.

Pardon me, but I'm using "implicit" to mean "implicit", and
nothing more.

Python's behavior here is "implicit" in the very same way
that Perl implicitly converts an array into a scalar for
you. (Though that particular Perl behavior is a far bigger
wart than Python's behavior is here!)

> > Because you've stated that "\y" is a legal escape
> > sequence, while the Python Reference Manual

Re: Social problems of Python doc [was Re: Python docs disappointing]

2009-08-12 Thread Raymond Hettinger
[Raymond Hettinger]
> Here are a few thoughts on list.sort() for those who are interested:

After one more reading of Xah Lee's posts on the documentation for
sort,
here are couple more thoughts:

* The reason that list.sort() allows None for the cmp parameter is not
so that you can write list.sort(None).  It was put there to make it
easier for people writing function definitions where the cmp function
is a possible argument:

   def sort_and_chop(seq, maxlen, cmp=None):
   s = seq[:]
   s.sort(cmp)   # needs to accept None as a possible
argument
   return s[:maxlen]

* The reason for implementing the key= parameter had nothing to do
with limitations of Python's compiler.  Instead, it was inspired by
the
decorate-sort-undecorate pattern.


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


Re: matching patterns after regex?

2009-08-12 Thread Mark Lawrence

Bernard wrote:

On 12 août, 12:43, Martin  wrote:

On Aug 12, 1:42 pm, Martin  wrote:






On Aug 12, 1:23 pm, Steven D'Aprano  wrote:

On Wed, 12 Aug 2009 05:12:22 -0700, Martin wrote:

I tried
re.findall((\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+),s)

You need to put quotes around strings.
In this case, because you're using regular expressions, you should use a
raw string:
re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
will probably work.
--
Steven

Thanks I see.
so I tried it and if I use it as it is, it matches the first instance:
I
n [594]: re.findall(r"(\w+COORDINATE).*\s+VALUE\s+=\s([\d\.\w-]+)",s)
Out[594]: [('NORTHBOUNDINGCOORDINATE', '1')]
So I adjusted the first part of the regex, on the basis I could sub
NORTH for SOUTH etc.
In [595]: re.findall(r"(NORTHBOUNDINGCOORDINATE).*\s+VALUE\s+=\s([\d\.
\w-]+)",s)
Out[595]: [('NORTHBOUNDINGCOORDINATE', '1')]
But in both cases it doesn't return the decimal value rather the value
that comes after NUM_VAL = , rather than VALUE = ?

I think I kind of got that to work...but I am clearly not quite
understanding how it works as I tried to use it again to match
something else.

In this case I want to print the values 0.00 and 2223901.039333
from a string like this...

YDim=1200\n\t\tUpperLeftPointMtrs=(0.00,2223901.039333)\n\t\t

I tried which I though was matching the statement and printing the
decimal number after the equals sign??

re.findall(r"(\w+UpperLeftPointMtrs)*=\s([\d\.\w-]+)", s)

where s is the string

Many thanks for the help


You have to do it with 2 matches in the same regex:

regex = r"UpperLeftPointMtrs=\(([\d\.]+),([\d\.]+)"

The first match  is before the , and the second one is after the , :)

You should probably learn how to play with regexes.
I personnaly use a visual tool called RX Toolkit[1] that comes with
Komodo IDE.

[1] http://docs.activestate.com/komodo/4.4/regex.html

Haven't tried it myself but how about this?
http://re-try.appspot.com/

--
Kindest regards.

Mark Lawrence.

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


Plotting Quadratic Functions, pygame

2009-08-12 Thread Senad Ibraimoski -student-Mathematical Institute Belgrade
Hello, I'm a new guy to this group, my professor recommend this group
to me, because I was boring him with questions.I'm new to python, and
I have problem plotting Quadratic Functions. Using module pygame.
Here is the code:

#!/usr/bin/env python
import pygame
def main():
import sys
import math
from math import sqrt
#Input equation coefficients
screen=pygame.display.set_mode((400,400))
pygame.display.set_caption( ' Ploting ' )
screen.fill((255,255,255))
pen=((0,0,255))
dark=(0,0,0)
ox=200
oy=200
a= int(raw_input('Input coefficient a ' ))
b= int(raw_input('Input coefficient b ' ))
c= int(raw_input('Input coefficient c ' ))
pygame.draw.aaline(screen,((255,0,0)),((200,0)) ,((200,400)))
pygame.draw.aaline(screen,((255,0,0)),((0,200)), ((400,200)))
if a==0:
if b==0:
print 'No solutions'
else:
x= -c/b
print x
else:
d=b*b-4*a*c
if d<0:
num=complex(-b/(2*a),sqrt(-d)/(2*a))
print num
else:
x1=(-b+sqrt(d))/(2*a)
x2=(-b-sqrt(d))/(2*a)
print 'x1= ' ,x1
print 'x2= ' ,x2
while 1:
for event in pygame.event.get():
if event ==pygame.QUIT:
print ' Quitting'
pygame.quit()
sys.exit(1)

x=-50;
while x<=50:
y=(a*(x**2) + b*x + c) *(-1)
screen.set_at(((x+ox),(y+oy)),dark)
pygame.display.flip()
x=x+1;

return 0

if __name__ == '__main__': main()

For now I'm plotting function only when Determinant >0. Or in other
words, when equation has two solutions,
x1,x2 e R... Now if you start my program you will see where problem
is. It's with function, It so bad drawn.
When I try to increment x in loop by 0.1 for every pass, I get
problems because method set_at() Which sets pixel requires integer...

Also I see I have problems with event handling here:
while 1:
for event in pygame.event.get():
if event ==pygame.QUIT:
print ' Quitting'
pygame.quit()
sys.exit(1)

When I click X, or exit on windows it doesn't exit.
What do you suggest I do...?
I don't have in this year Computer Graphics on my faculty. So this are
my first steps in this area of CS.

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


How to page output in >>> ?

2009-08-12 Thread kj


How does one tell the python interactive interpreter to run the
next output to stdout through the default pager?  Basically, I'm
looking for Python's equivalent of Perl's debugger's "|" prefix,
as in

  DB<1> |print $long_output

TIA!

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


Re: httplib incredibly slow :-(

2009-08-12 Thread i3dmaster
On Aug 12, 9:37 am, Chris Withers  wrote:
> David Stanek wrote:
> > I tried to reproduce this, but I could not. Could you paste in the
> > output of your script?
>
> Not sure how that'll help, but sure:
>
> 2009-08-11 21:27:59.153000
> request: 0:00:00.109000
> response: 0:00:00.109000
> read: 0:24:31.266000
>
>  > Also on the same box where you run this script
>
> > can you test with curl or wget?
>
> It's a Windows box, so no :-(
> But it really does download in a few seconds with IE, and 20min+ using
> the script I included...
>
> Chris
>
> --
> Simplistix - Content Management, Batch Processing & Python Consulting
>             -http://www.simplistix.co.uk

Just wanted to check if you can try turning on the debug mode for
httplib and see if you can read a bit more debug info on where the
calls get hung. In your example, it would be conn.set_debuglevel(1)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to launch a function at regular time intervals ?

2009-08-12 Thread Christian Heimes

David wrote:

Has anyone run into a similar problem (and solved it) ?


Yeah, here is my implementation as a perpetual timer based some cherrypy 
code and threading timer.


import threading

class PerpetualTimer(threading._Timer):
"""A subclass of threading._Timer whose run() method repeats.

Based on cherrpy.process.plugins.PerpetualTimer
"""
def __init__(self, interval, function, name=None, daemon=False, 
args=(), kwargs={}):
super(PerpetualTimer, self).__init__(interval, function, args, 
kwargs)

self.setName(name)
self.setDaemon(daemon)

def run(self):
while True:
self.finished.wait(self.interval)
if self.finished.isSet():
return
self.function(*self.args, **self.kwargs)

def stop(self, timeout=None):
self.cancel()
self.join(timeout)

def callback(egg):
egg.cook()

timer = PerpetualTimer(100, callback, name="EggTimer", args=(somegg,))
timer.start()

...

timer.stop()

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


  1   2   >