Re: change text of a Tkinter Button by clicking it

2011-09-28 Thread Peter Otten
Sean McIlroy wrote:

> hello
> 
> (how) can you change the text of a Tkinter Button by clicking it?
> something like
> 
> def click(index): return lambda: buttons[index].text = 'hello'
> buttons = [Button(root,command=click(index)) for index in
> range(numbuttons)]
> 
> only with an attribute that Buttons actually have. sorry to have to
> ask such a see-spot-run question. thanks if you can help.

See http://infohost.nmt.edu/tcc/help/pubs/tkinter/universal.html

You can set the text of a Button widget with

button["text"] = ...

or

button.configure(text=...)



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


Re: syntactic sugar for def?

2011-09-28 Thread Westley Martínez
On Wed, Sep 28, 2011 at 07:01:11PM -0400, Terry Reedy wrote:
> On 9/28/2011 5:26 PM, Ethan Furman wrote:
> 
> >I don't remember if 'def' is sugar for something besides lambda.
> 
> That is a bit backwards.
>   lambda x: expr(x)
> is syntactic sugar for
>   def (x): return expr(x)
>   del 
> ;-)
> 

lambda is less sugar and more of just a def as an expression.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-28 Thread Westley Martínez
On Wed, Sep 28, 2011 at 07:11:08PM -0700, rantingrick wrote:
> On Sep 28, 6:26 pm, Tim Johnson  wrote:
> > * DevPlayer  [110928 04:31]:
> > > On Sep 27, 10:25 pm, alex23  wrote:
> > > > rantingrick  wrote:
> > > > > Since, like the bible
> > > > > the zen is self contradicting, any argument utilizing the zen can be
> > > > > defeated utilizing the zen.
> >
> > > > And like the Bible, the Zen was created by humans as a joke. If you're
> > > > taking it too seriously, that's your problem.
> >
> > > > > If however you want to learn about the accepted rules for formatting
> > > > > code then you need to read "PEP-8"! PEP 8 is our style guide.
> >
> > > Contradiction is only seen by narrow perspectve.
> >
> > > Calling the Bible a joke is used to hurt people, not enlighten them.
> > > Those words show bitter arrogance, not constructive critism as it
> > > ignores how others feel about that book. What benefit to others is
> > > gained by calling someones belief a joke?
> >
> >  My wife and I are devout christians, but not fundamentalist. We
> >  would not take rantingrick too seriously. If _you_ take him
> >  seriously, you're just giving him 'street cred'.
> 
> DevPlayer was not even talking about what i said, he was replying to a
> statement by Alex23 who said (and i quote) "And like the Bible, the
> Zen was created by humans as a joke". Maybe you should spend the next
> fifteen or so minutes catching up to the conversation...(ಠ_ಠ)...of
> course only *after* you clean that egg from your face

Perhaps you should spend a little less time on the mailing list and a
little more time in church.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: change text of a Tkinter Button by clicking it

2011-09-28 Thread Sean McIlroy
never mind. i found it.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: memory error

2011-09-28 Thread questions anon
Hello All,
I am still having trouble with memory errors when I try to process many
netcdf files.
Originally I would get the memory error as mentioned in the previous post
but when I added gc.collect() after each for loop I receive the error:
GEOS_ERROR: bad allocation
with no additional information!
The error use to occur at the point when a new netcdf file was to be opened
and plotted but with the things I have 'fixed' thanks to suggestions from
this list it seems to happen while processing the second file.
I am just trying to plot 3hourly data for each file and each file contains
hourly data for a month and I am trying to do this for many months.
It seems like I cannot close down the last file properly so the computer has
a clean memory to start the next one.
Any feedback will be greatly appreciated.
My latest version of the code:

##

from netCDF4 import Dataset
import numpy as N
import matplotlib.pyplot as plt
from numpy import ma as MA
from mpl_toolkits.basemap import Basemap
from netcdftime import utime
from datetime import datetime
import os


shapefile1="E:/DSE_BushfireClimatologyProject/griddeddatasamples/test_GIS/DSE_REGIONS"
OutputFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/OutputsforValidation"

def plotrawdata(variable):
if variable=='TSFC':
ncvariablename='T_SFC'

MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/T_SFC/"
ticks=[-5,0,5,10,15,20,25,30,35,40,45,50]
Title='Surface Temperature'
cmap=plt.cm.jet

elif variable=='RHSFC':
ncvariablename='RH_SFC'

MainFolder=r"E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/RH_SFC/"
ticks=[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Title='Surface RH'
cmap=plt.cm.jet_r


fileforlatlon=Dataset("E:/DSE_BushfireClimatologyProject/griddeddatasamples/GriddedData/InputsforValidation/T_SFC/TSFC_1974_01/IDZ00026_VIC_ADFD_T_SFC.nc",
'r+', 'NETCDF4')
LAT=fileforlatlon.variables['latitude'][:]
LON=fileforlatlon.variables['longitude'][:]

startperiod=raw_input("Start slice (e.g. 1 ): ")
endperiod=raw_input("End slice (e.g. 2): ")
skipperiod=raw_input("skip slice (e.g. 1): ")
if startperiod == "":
startperiod = None
else:
startperiod = int(startperiod)
if endperiod == "":
endperiod = None
else:
endperiod = int(endperiod)
if skipperiod == "":
skipperiod = None
else:
skipperiod= int(skipperiod)

for (path, dirs, files) in os.walk(MainFolder):
for dir in dirs:
print dir
path=path+'/'

for ncfile in files:
if ncfile[-3:]=='.nc':
print "dealing with ncfiles:",
path+ncfile
ncfile=os.path.join(path,ncfile)
ncfile=Dataset(ncfile, 'r+', 'NETCDF4')
#global TSFC

variable=ncfile.variables[ncvariablename][startperiod:endperiod:skipperiod]

TIME=ncfile.variables['time'][startperiod:endperiod:skipperiod]

fillvalue=ncfile.variables[ncvariablename]._FillValue
ncfile.close()

for variable, TIME in
zip((variable[:]),(TIME[:])):
#for variable, TIME in
zip((variable[sliceperiod]),(TIME[sliceperiod])):

cdftime=utime('seconds since
1970-01-01 00:00:00')

ncfiletime=cdftime.num2date(TIME)
print ncfiletime
timestr=str(ncfiletime)
d = datetime.strptime(timestr,
'%Y-%m-%d %H:%M:%S')
date_string =
d.strftime('%Y%m%d_%H%M')
#Set up basemap using mercator
projection
http://matplotlib.sourceforge.net/basemap/doc/html/users/merc.html
map =
Basemap(projection='merc',llcrnrlat=-40,urcrnrlat=-33,

llcrnrlon=139.0,urcrnrlon=151.0,lat_ts=0,resolution='i')
x,y=map(*N.meshgrid(LON,LAT))

map.drawcoastlines(linewidth=0.5)
map.readshapefile(shapefile1,
'DSE_REGIONS')
map.drawstates()

plt.title(Title+' %s
UTC'%ncfiletime)

CS = map.contourf(x,y,variable,
ticks, cmap=cmap)
l,b,w,h =0.1,0.1,0.8,0.8
  

change text of a Tkinter Button by clicking it

2011-09-28 Thread Sean McIlroy
hello

(how) can you change the text of a Tkinter Button by clicking it?
something like

def click(index): return lambda: buttons[index].text = 'hello'
buttons = [Button(root,command=click(index)) for index in
range(numbuttons)]

only with an attribute that Buttons actually have. sorry to have to
ask such a see-spot-run question. thanks if you can help.

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


UnicodeDecodeError

2011-09-28 Thread gaurav gangalwar
I am getting this error while some testing on Python2.6,

 File "/usr/lib64/python2.6/httplib.py", line 774, in _send_output #msg
= "\r\n".join(self._buffer) UnicodeDecodeError: 'ascii' codec can't decode
byte 0xe1 in position 14: ordinal not in range(128)

I tried the change suggested on this link
http://web.archiveorange.com/archive/v/PJbOg9pxJoUpQA9AHp3X, its working
fine after that.

There seems to be some problem in httplib with unicode handling.
I am running it on centos5.
I am still not sure why its happening and what will be ideal solution for
this?

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


Re: A Trivial Question

2011-09-28 Thread Chris Angelico
On Thu, Sep 29, 2011 at 7:53 AM, Tayfun Kayhan
 wrote:
> def trial():
>class Foo(object):
>   def __init__(self):
>  print("Hello, world!")
> trial() # not worked, as expected.

Python doesn't have "class declarations" in the way that some other
languages do. The 'class' statement is an executable statement - it
builds a class object and binds it to the name Foo, just like any
other assignment. The 'def' command builds a function object in a
similar fashion. So in your trial() function, you're defining a class
and binding it to the local name Foo; and then doing nothing with it.
It's perfectly legal, and as Chris Rebert suggests, you can make it
useful by instantiating Foo() objects inside trial().

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


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Roy Smith
In article ,
 Tim Chase  wrote:

> On 09/28/11 19:52, Roy Smith wrote:
> > In many cases, there's only two states of interest:
> >
> > 1) All tests pass
> >
> > 2) Anything else
> 
> Whether for better or worse, at some places (such as a previous 
> employer) the number (and accretion) of test-points is a 
> marketing bullet-point for upgrades & new releases.

Never attribute to malice that which is adequately explained by the 
stupidity of the marketing department.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Tim Chase

On 09/28/11 19:52, Roy Smith wrote:

In many cases, there's only two states of interest:

1) All tests pass

2) Anything else


Whether for better or worse, at some places (such as a previous 
employer) the number (and accretion) of test-points is a 
marketing bullet-point for upgrades & new releases.


-tkc



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


Re: [OT] Benefit and belief

2011-09-28 Thread Ben Finney
Devin Jeanpierre  writes:

> > Forget money, or even the love of money. The idea that one mustn't
> > criticise another person's beliefs is the root of all evil.
>
> This was a technical discussion, and calling the bible a joke was not
> necessary at all. It creates a hostile atmosphere.

I disagree. It was not an attack on any person nor group of people. If
we are to be required to avoid jokes not directed at people, then *that*
is an atmosphere hostile to open friendly discussion.

> Can't you pick somewhere else to attack Christianity?

The person who wrote the “bible is a joke” intended it as a flippant
remark. Countless other flippant remarks pass through here all the time,
making jokes at the expense of some idea or other. Christianity will not
be an exception to that.

If you find someone attacking people, I'll join you in ostracising the
attacker. But no, don't attempt to silence jokes that attack an idea.

Off-topic? If we start discussing the content of the ideas being
attacked, yeah, I'd say religion is pretty off-topic.

But the topic of keeping this forum safe for technical discussion
entails that it must be safe for *any* idea to be the butt of a joke, be
it a religious text or the Zen of Python, and that is very much
on-topic.

-- 
 \ “We demand rigidly defined areas of doubt and uncertainty!” |
  `\—Vroomfondel, _The Hitch-Hiker's Guide To The Galaxy_, Douglas |
_o__)Adams |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Roy Smith
In article <874nzw3wxc@benfinney.id.au>,
 Ben Finney  wrote:

> Roy Smith  writes:
> 
> > In article <87k48szqo1@benfinney.id.au>,
> >  Ben Finney  wrote:
> >
> > > Worse, if one of the scenarios causes the test to fail, the loop will
> > > end and you won't get the results for the remaining scenarios.
> >
> > Which, depending on what you're doing, may or may not be important.  In 
> > many cases, there's only two states of interest:
> >
> > 1) All tests pass
> >
> > 2) Anything else
> 
> For the purpose of debugging, it's always useful to more specifically
> narrow down the factors leading to failure.

Well, sure, but "need to debug" is just a consequence of being in state 
2.  If a test fails and I can't figure out why, I can always go back and 
add additional code to the test case to extract additional information.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-28 Thread alex23
On Sep 28, 10:12 pm, DevPlayer  wrote:
> Calling the Bible a joke is used to hurt people, not enlighten them.

Y'know, I wouldn't even bother responding to this if Xianists were as
open, forgiving and accepting as their messiah told them to be. It was
a *flippant remark*. If you want to establish intent, aggression and
religio-politico-philosophy from every throwaway remark made on the
internet, you're not really going to have much time for Python.

My belief system isn't your's. Hell, my belief system doesn't even
require that I have *any respect whatsoever* for your's. If it's okay
for Xianists to "suffer not a witch to live", then I'm going to assert
my making light jokes about those whose world view is in direct
opposition to mine isn't even comparable to that mentality.

from attitude import humour

(Since we're already fully derailed here, I've always preferred
Borges' suggestion that it was actually Judas who carried the full
weight of man's sins, given that his betrayal of Christ and inevitable
condemnation to hell was a necessity. Then again, I'm able to safely
view this as *allegory* and am genuinely interested in the opinions of
modern minds over something first begun by nomads millenia ago...)


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


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Ben Finney
Steven D'Aprano  writes:

> I used to ask the same question, but then I decided that if I wanted
> each data point to get its own tick, I should bite the bullet and
> write an individual test for each.

Hence my advocating the ‘testscenarios’ library. Have you tried that?

It allows the best of both worlds: within the class, you write a
collection of data scenarios, and write one test case for each separate
behaviour, and that's all that appears in the code; but the test run
shows every test case for every scenario.

E.g. with a ParrotTestCase class having three test cases and four
scenarios, the test run will run the full combination of all of them and
report twelve distinct test cases and the result for each.

So the “bite the bullet” you describe isn't necessary to get what you
want.

> If you really care, you could subclass unittest.TestCase, and then
> cause each assert* method to count how often it gets called. But
> really, how much detailed info about *passed* tests do you need?

The ‘testscenarios’ library does subclass the standard library
‘unittest’ module.

But as explained elsewhere, it's not the counting which is the issue.
The issue is to ensure (and report) that every test case is actually
tested in isolation against every relevant scenario.

-- 
 \“Human reason is snatching everything to itself, leaving |
  `\  nothing for faith.” —Bernard of Clairvaux, 1090–1153 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Ben Finney
Roy Smith  writes:

> In article <87k48szqo1@benfinney.id.au>,
>  Ben Finney  wrote:
>
> > Worse, if one of the scenarios causes the test to fail, the loop will
> > end and you won't get the results for the remaining scenarios.
>
> Which, depending on what you're doing, may or may not be important.  In 
> many cases, there's only two states of interest:
>
> 1) All tests pass
>
> 2) Anything else

For the purpose of debugging, it's always useful to more specifically
narrow down the factors leading to failure.

-- 
 \  “A lie can be told in a few words. Debunking that lie can take |
  `\   pages. That is why my book… is five hundred pages long.” —Chris |
_o__)Rodda, 2011-05-05 |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-28 Thread DevPlayer
Oh I was just testing my intellecual-enlightenment-from-ranter-
conversation algorithm found in a previous post. I think my OOP model
failed as I'm just too tired to finished that pattern test. He had
some good points which fit the process I layed out. But the original
topic is just so much better:

Suggested coding style Options



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


Re: Suggested coding style

2011-09-28 Thread rantingrick
On Sep 28, 6:26 pm, Tim Johnson  wrote:
> * DevPlayer  [110928 04:31]:
> > On Sep 27, 10:25 pm, alex23  wrote:
> > > rantingrick  wrote:
> > > > Since, like the bible
> > > > the zen is self contradicting, any argument utilizing the zen can be
> > > > defeated utilizing the zen.
>
> > > And like the Bible, the Zen was created by humans as a joke. If you're
> > > taking it too seriously, that's your problem.
>
> > > > If however you want to learn about the accepted rules for formatting
> > > > code then you need to read "PEP-8"! PEP 8 is our style guide.
>
> > Contradiction is only seen by narrow perspectve.
>
> > Calling the Bible a joke is used to hurt people, not enlighten them.
> > Those words show bitter arrogance, not constructive critism as it
> > ignores how others feel about that book. What benefit to others is
> > gained by calling someones belief a joke?
>
>  My wife and I are devout christians, but not fundamentalist. We
>  would not take rantingrick too seriously. If _you_ take him
>  seriously, you're just giving him 'street cred'.

DevPlayer was not even talking about what i said, he was replying to a
statement by Alex23 who said (and i quote) "And like the Bible, the
Zen was created by humans as a joke". Maybe you should spend the next
fifteen or so minutes catching up to the conversation...(ಠ_ಠ)...of
course only *after* you clean that egg from your face.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Python 2.6.7 on Windows

2011-09-28 Thread rantingrick
On Sep 27, 11:25 pm, Steven D'Aprano  wrote:

> The Python development team is relatively small and chronically busy: too
> much to do and not enough time to do it.

If that is the case then why do they snub their noses at anyone who
wishes to help? What kind of people would chase off good help just to
save ego? I imagine the folks at py dev sort of like a dying man in
need of a heart transplant; the man informs the doctor that he would
happy to get a transplant but not if the heart came from a jew, asian,
african, latin, russian, or canuck.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Eric Snow
On Wed, Sep 28, 2011 at 6:50 PM, Devin Jeanpierre
 wrote:
>> I used to ask the same question, but then I decided that if I wanted each
>> data point to get its own tick, I should bite the bullet and write an
>> individual test for each.
>
> Nearly the entire re module test suite is a list of tuples. If it was
> instead a bunch of TestCase classes, there'd be a lot more boilerplate
> to write. (At a bare minimum, there'd be two times as many lines, and
> all the extra lines would be identical...)
>
> Why is writing boilerplate for a new test a good thing? It discourages
> the authorship of tests. Make it as easy as possible by e.g. adding a
> new thing to whatever you're iterating over. This is, for example, why
> the nose test library has a decorator for generating a test suite from
> a generator.

+1

>
> Devin
>
> On Wed, Sep 28, 2011 at 8:16 PM, Steven D'Aprano
>  wrote:
>> Tim Chase wrote:
>>
>>> While I asked this on the Django list as it happened to be with
>>> some Django testing code, this might be a more generic Python
>>> question so I'll ask here too.
>>>
>>> When performing unittest tests, I have a number of methods of the
>>> form
>>>
>>>    def test_foo(self):
>>>      data = (
>>>        (item1, result1),
>>>        ... #bunch of tests for fence-post errors
>>>        )
>>>      for test, result in data:
>>>        self.assertEqual(process(test), result)
>>>
>>> When I run my tests, I only get a tick for running one the one
>>> test (test_foo), not the len(data) tests that were actually
>>> performed.  Is there a way for unittesting to report the number
>>> of passed-assertions rather than the number of test-methods run?
>>
>> I used to ask the same question, but then I decided that if I wanted each
>> data point to get its own tick, I should bite the bullet and write an
>> individual test for each.
>>
>> If you really care, you could subclass unittest.TestCase, and then cause
>> each assert* method to count how often it gets called. But really, how much
>> detailed info about *passed* tests do you need?
>>
>> If you are writing loops inside tests, you might find this anecdote useful:
>>
>> http://mail.python.org/pipermail/python-list/2011-April/1270640.html
>>
>>
>>
>> --
>> Steven
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Installing Python 2.6.7 on Windows

2011-09-28 Thread Gabriel Genellina

En Wed, 28 Sep 2011 21:10:38 -0300, Nobody  escribió:


On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote:


No, it was a deliberate decision.  After a release is in security-fix
mode only, we don't build Windows or Mac OS X installers for them.


But you continue to offer the installers for the unfixed version.


As well as all the previous ones back to Python 1.x

I can think of several alternatives:

* Upgrade to Python 2.7, the current stable and maintained release.

* Compile Python 2.6.7 yourself. For the 32 bits version, you may use  
Microsoft Visual C++ 2008 Express Edition (free/gratis); see  
PCbuild\readme.txt for details. Obtain the required dependencies using  
Tools\buildbot\external.bat. It compiles cleanly out of the box.


* Obtain the compiled binary somewhere else. Considering that 2.6.7 is  
just a security patch, I'm not sure if running a precompiled binary from  
untrusted sources is any better than sticking with the official, previous  
version. I've built the binaries, in case you're interested.


* Compare both source trees and look at their differences. Most of them  
are in Python modules that you can just drop over an existing 2.6.6  
install. Only two C modules have changed, and require rebuilding  
python26.dll:


 timemodule.c r87648: Issue #8013: Fixed time.asctime segfault when OS's  
asctime fails

 unicodedata.c http://bugs.python.org/issue10254

If you think you're not affected by these, just ignore 2.6.7 (or apply  
only the .py changes)


--
Gabriel Genellina

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


Re: [OT] Benefit and belief [was Re: Suggested coding style]

2011-09-28 Thread Devin Jeanpierre
> Forget money, or even the love of money. The idea that one mustn't
> criticise another person's beliefs is the root of all evil.

This was a technical discussion, and calling the bible a joke was not
necessary at all. It creates a hostile atmosphere.

Can't you pick somewhere else to attack Christianity?

Devin

On Wed, Sep 28, 2011 at 9:14 PM, Steven D'Aprano
 wrote:
> DevPlayer wrote:
>
>> On Sep 27, 10:25 pm, alex23  wrote:
>>> And like the Bible, the Zen was created by humans as a joke. If you're
>>> taking it too seriously, that's your problem.
> [...]
>> Calling the Bible a joke is used to hurt people, not enlighten them.
>> Those words show bitter arrogance, not constructive critism as it
>> ignores how others feel about that book. What benefit to others is
>> gained by calling someones belief a joke?
>
> It is the same benefit as the little boy who pointed out that the Emperor
> was not wearing any clothes. (In real life, the story was called "The
> Little Boy Who Said The Emperor Wasn't Wearing Any Clothes, and Got
> Arrested and Thrown in Prison Together With His Parents for Insulting The
> Emperor".)
>
>
>> To put the "believers" minds
>> straight? I think not. I think the unsensitive person who attackes
>> others beliefs, even if illogical or unrealistic, is after some kind
>> of self grandizement or to illude themself into thinking "they know
>> the truth of the universe" and should attack others to prove they do.
>
> There is a difference between attacking ideas and attacking people.
>
> "The Bible is a joke" attacks the idea.
>
> "Insensitive people after self-aggrandisement deluding themselves" attacks
> the person.
>
> We live in a world where religion is privileged, where governments pander to
> the most sick and twisted, hateful, bigoted beliefs because of religion,
> where organised conspiracies to support and protect child molesters and
> sexual predators are nevertheless looked up to as sources of morality.
>
> There are some ideas that are simply incompatible with civilization, and the
> idea that religious beliefs should be beyond criticism is one of them.
> Forget money, or even the love of money. The idea that one mustn't
> criticise another person's beliefs is the root of all evil.
>
>
>
> --
> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


[OT] Benefit and belief [was Re: Suggested coding style]

2011-09-28 Thread Steven D'Aprano
DevPlayer wrote:

> On Sep 27, 10:25 pm, alex23  wrote:
>> And like the Bible, the Zen was created by humans as a joke. If you're
>> taking it too seriously, that's your problem.
[...]
> Calling the Bible a joke is used to hurt people, not enlighten them.
> Those words show bitter arrogance, not constructive critism as it
> ignores how others feel about that book. What benefit to others is 
> gained by calling someones belief a joke? 

It is the same benefit as the little boy who pointed out that the Emperor
was not wearing any clothes. (In real life, the story was called "The
Little Boy Who Said The Emperor Wasn't Wearing Any Clothes, and Got
Arrested and Thrown in Prison Together With His Parents for Insulting The
Emperor".)


> To put the "believers" minds 
> straight? I think not. I think the unsensitive person who attackes
> others beliefs, even if illogical or unrealistic, is after some kind
> of self grandizement or to illude themself into thinking "they know
> the truth of the universe" and should attack others to prove they do.

There is a difference between attacking ideas and attacking people.

"The Bible is a joke" attacks the idea.

"Insensitive people after self-aggrandisement deluding themselves" attacks
the person.

We live in a world where religion is privileged, where governments pander to
the most sick and twisted, hateful, bigoted beliefs because of religion,
where organised conspiracies to support and protect child molesters and
sexual predators are nevertheless looked up to as sources of morality.

There are some ideas that are simply incompatible with civilization, and the
idea that religious beliefs should be beyond criticism is one of them.
Forget money, or even the love of money. The idea that one mustn't
criticise another person's beliefs is the root of all evil.



-- 
Steven

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


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Roy Smith
In article <87k48szqo1@benfinney.id.au>,
 Ben Finney  wrote:

> Worse, if one of the scenarios causes the test to fail, the loop will
> end and you won't get the results for the remaining scenarios.

Which, depending on what you're doing, may or may not be important.  In 
many cases, there's only two states of interest:

1) All tests pass

2) Anything else
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Devin Jeanpierre
> I used to ask the same question, but then I decided that if I wanted each
> data point to get its own tick, I should bite the bullet and write an
> individual test for each.

Nearly the entire re module test suite is a list of tuples. If it was
instead a bunch of TestCase classes, there'd be a lot more boilerplate
to write. (At a bare minimum, there'd be two times as many lines, and
all the extra lines would be identical...)

Why is writing boilerplate for a new test a good thing? It discourages
the authorship of tests. Make it as easy as possible by e.g. adding a
new thing to whatever you're iterating over. This is, for example, why
the nose test library has a decorator for generating a test suite from
a generator.

Devin

On Wed, Sep 28, 2011 at 8:16 PM, Steven D'Aprano
 wrote:
> Tim Chase wrote:
>
>> While I asked this on the Django list as it happened to be with
>> some Django testing code, this might be a more generic Python
>> question so I'll ask here too.
>>
>> When performing unittest tests, I have a number of methods of the
>> form
>>
>>    def test_foo(self):
>>      data = (
>>        (item1, result1),
>>        ... #bunch of tests for fence-post errors
>>        )
>>      for test, result in data:
>>        self.assertEqual(process(test), result)
>>
>> When I run my tests, I only get a tick for running one the one
>> test (test_foo), not the len(data) tests that were actually
>> performed.  Is there a way for unittesting to report the number
>> of passed-assertions rather than the number of test-methods run?
>
> I used to ask the same question, but then I decided that if I wanted each
> data point to get its own tick, I should bite the bullet and write an
> individual test for each.
>
> If you really care, you could subclass unittest.TestCase, and then cause
> each assert* method to count how often it gets called. But really, how much
> detailed info about *passed* tests do you need?
>
> If you are writing loops inside tests, you might find this anecdote useful:
>
> http://mail.python.org/pipermail/python-list/2011-April/1270640.html
>
>
>
> --
> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


red bull hats, snapback hats, hello kitty hats, monster energy hats of http://www.currenthats.com/

2011-09-28 Thread Bertha Jonanna
Welcome to the www. currenthats.com,. The currenthats.com is a
promotional shop from monster energy hats. It was authorized to
provide red bull hats,snapback hats,hello kitty hats and the
fashionable sports items to meet red bull hats Fans shopping needs.
-- 
http://mail.python.org/mailman/listinfo/python-list


red bull hats, snapback hats, hello kitty hats, monster energy hats of http://www.currenthats.com/

2011-09-28 Thread Bertha Jonanna
Welcome to the www. currenthats.com,. The currenthats.com is a
promotional shop from monster energy hats. It was authorized to
provide red bull hats,snapback hats,hello kitty hats and the
fashionable sports items to meet red bull hats Fans shopping needs.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Roy Smith
In article <4e83b8e0$0$29972$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:

> If you are writing loops inside tests, you might find this anecdote useful:
> 
> http://mail.python.org/pipermail/python-list/2011-April/1270640.html

On the other hand, the best test is one that gets written.  I will often 
write tests that I know do not meet the usual standards of purity and 
wholesomeness.  Here's a real-life example:

for artist in artists:
name = artist['name']
self.assertIsInstance(name, unicode)
name = name.lower()
# Due to fuzzy matching, it's not strictly guaranteed that the 
# following assertion is true, but it works in this case.  
self.assertTrue(name.startswith(term), (name, term))

Could I have written the test without the loop?  Probably.  Would it 
have been a better test?  I guess, at some level, probably.  And, of 
course, the idea of a "not strictly guaranteed" assertion is probably 
enough to make me lose my Unit Tester's Guild Secret Decoder Ring 
forever :-)

But, the test was quick and easy to write, and provides value.  I could 
have spent twice as long writing a better test, and it would have 
provided a little more value, but certainly not double.  More 
importantly, had I spent the extra time writing the better test, I might 
have not had enough time to write all the other tests I wrote that day.

Sometimes good enough is good enough.
-- 
http://mail.python.org/mailman/listinfo/python-list


options for plotting points on geographic map

2011-09-28 Thread CM
Recommendations sought for using Python to plot points/custom markers
(and maybe other things?) on a map of an area of the U.S. of maybe 100
miles radius.  (This would be a "political" map showing towns, such as
from Google Maps or Mapquest, and not a "physical" map).  I'll need to
place markers or something based on zip codes.

I see there is pymaps, a Python wrapper for Google Maps.  I may try
that but it seems to be barely documented and would require making a
webpage with javascript to display the map, whereas I'd probably
prefer a desktop app for this--though I'd consider a web page (it's
probably easier than I think).

I already use Matplotlib, but its Basemap seems to be only for
physical geography needs.

Are there other options one might recommend?  (It is a little hard to
Google for this given the map() function).

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


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Steven D'Aprano
Tim Chase wrote:

> While I asked this on the Django list as it happened to be with
> some Django testing code, this might be a more generic Python
> question so I'll ask here too.
> 
> When performing unittest tests, I have a number of methods of the
> form
> 
>def test_foo(self):
>  data = (
>(item1, result1),
>... #bunch of tests for fence-post errors
>)
>  for test, result in data:
>self.assertEqual(process(test), result)
> 
> When I run my tests, I only get a tick for running one the one
> test (test_foo), not the len(data) tests that were actually
> performed.  Is there a way for unittesting to report the number
> of passed-assertions rather than the number of test-methods run?

I used to ask the same question, but then I decided that if I wanted each
data point to get its own tick, I should bite the bullet and write an
individual test for each.

If you really care, you could subclass unittest.TestCase, and then cause
each assert* method to count how often it gets called. But really, how much
detailed info about *passed* tests do you need? 

If you are writing loops inside tests, you might find this anecdote useful:

http://mail.python.org/pipermail/python-list/2011-April/1270640.html



-- 
Steven

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


Re: Installing Python 2.6.7 on Windows

2011-09-28 Thread Nobody
On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote:

> No, it was a deliberate decision.  After a release is in security-fix 
> mode only, we don't build Windows or Mac OS X installers for them.

But you continue to offer the installers for the unfixed version.

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


Re: Suggested coding style

2011-09-28 Thread Tim Johnson
* DevPlayer  [110928 04:31]:
> On Sep 27, 10:25 pm, alex23  wrote:
> > rantingrick  wrote:
> > > Since, like the bible
> > > the zen is self contradicting, any argument utilizing the zen can be
> > > defeated utilizing the zen.
> >
> > And like the Bible, the Zen was created by humans as a joke. If you're
> > taking it too seriously, that's your problem.
> >
> > > If however you want to learn about the accepted rules for formatting
> > > code then you need to read "PEP-8"! PEP 8 is our style guide.
> >
> Contradiction is only seen by narrow perspectve.
> 
> Calling the Bible a joke is used to hurt people, not enlighten them.
> Those words show bitter arrogance, not constructive critism as it
> ignores how others feel about that book. What benefit to others is
> gained by calling someones belief a joke? 

 My wife and I are devout christians, but not fundamentalist. We
 would not take rantingrick too seriously. If _you_ take him
 seriously, you're just giving him 'street cred'.

-- 
Tim 
tim at tee jay forty nine dot com or akwebsoft dot com
http://www.akwebsoft.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Wrote a new library - Comments and suggestions please!

2011-09-28 Thread Gregory Ewing

Steven D'Aprano wrote:


I googled on "SAS PROC FREQ" and found this:

http://support.sas.com/documentation/cdl/en/procstat/63104/HTML/default/procstat_freq_sect006.htm

Documentation like that really makes me appreciate the sterling work done on
Python's docs.


I think you have to read it in context. A couple of levels up
there is a section called "The FREQ Procedure" which seems to
explain more about what's going on, including examples. (I
didn't look too closely at it, though, in case my eyes started
to bleed...)

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


Re: syntactic sugar for def?

2011-09-28 Thread Terry Reedy

On 9/28/2011 5:26 PM, Ethan Furman wrote:


I don't remember if 'def' is sugar for something besides lambda.


That is a bit backwards.
  lambda x: expr(x)
is syntactic sugar for
  def (x): return expr(x)
  del 
;-)

--
Terry Jan Reedy

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


Re: syntactic sugar for def?

2011-09-28 Thread Eric Snow
On Wed, Sep 28, 2011 at 3:26 PM, Ethan Furman  wrote:
> I remember that 'class' is sugar for type().
>
> I don't remember if 'def' is sugar for something besides lambda.

This is something I have thought about a lot since PyCon this year.  I
apologize in advance.  

Since 3.0, class statements are syntactic sugar for some extra steps
beyond "meta(...)" [1].  In CPython this is facilitated through the
"hidden" __build_class__() builtin[2].  We have the __import__()
builtin for customizing module creation. But, as you asked, what about
functions?

Currently there isn't a way to customize function creation.  There is
no __build_function__() builtin.  The best you can do is, like others
have said, directly call FunctionType(...) or type(f)(...) where f is
an existing function.

I expect that if there were a __build_function__, it would wrap the
code that is currently run for the MAKE_FUNCTION/MAKE_CLOSURE
opcodes[3].

Also, both modules and classes have mechanisms built-in to allow for
customization in certain parts of the creation process (PEP 302[4] and
metaclasses[5], respectively).  Functions lack this as well, though
there hasn't been a big clamor for it.  :)  Nick Coghlan proposed an
interesting idea for this in March[6], with some later follow-up[7].
Nothing much came of it though.

Definitely an interesting topic, which has led me to learn a lot about
Python and CPython.

-eric

[1] http://www.python.org/dev/peps/pep-3115/
 http://mail.python.org/pipermail/python-3000/2007-March/006338.html
[2] http://hg.python.org/cpython/file/default/Python/bltinmodule.c#l35
[3] http://hg.python.org/cpython/file/default/Python/ceval.c#l2680
[4] http://www.python.org/dev/peps/pep-0302/
 http://docs.python.org/release/2.3.5/whatsnew/section-pep302.html
 http://docs.python.org/dev/reference/simple_stmts.html#the-import-statement
[5] 
http://docs.python.org/dev/reference/datamodel.html#customizing-class-creation
 http://www.python.org/doc/essays/metaclasses/
[6] http://mail.python.org/pipermail/python-ideas/2011-March/009391.html
[7] http://mail.python.org/pipermail/python-ideas/2011-March/009625.html
 http://mail.python.org/pipermail/python-ideas/2011-April/009765.html

>
> Any clues for me?  Heck, I'll even be grateful for outright answers!
>
> ~Ethan~
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: syntactic sugar for def?

2011-09-28 Thread Gabriel Genellina
En Wed, 28 Sep 2011 18:51:00 -0300, Chris Kaynor  
 escribió:


On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle   
wrote:

On 28 September 2011 22:26, Ethan Furman  wrote:

I remember that 'class' is sugar for type().

I don't remember if 'def' is sugar for something besides lambda.

Any clues for me?  Heck, I'll even be grateful for outright answers!


It's not really sugar.  But I think you mean something like this:



class A: pass

...

type(A)



type is type(A)

True

So the closest you get for functions will be:


def f(): pass

...

type(f)



Try help(type(f)) to see how to use it to create a function object.
The problem is that you need to provide a code object, and the easiest
way to create a code object is to use a def statement :)


I would say compile isn't too much harder to use:

c = compile('a = 123', 'test', 'exec')
d = {}
f = types.FunctionType(c, d, 'test')
f()
print d

{'a': 123}

Although it appears you get all of the variables defined as global
apparently (try "f = types.FunctionType(c, globals(), 'test')"
instead).


I know no way of compiling a function body alone. Suppose you have this  
function:


def foo(x):
  print x
  y = 2*x
  return y

py> compile("  print x\n  y = 2*x\n  return y", "", "exec")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
print x
^
IndentationError: unexpected indent
py> compile("print x\ny = 2*x\nreturn y", "", "exec")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3
SyntaxError: 'return' outside function

If you include the 'def' statement in the source string, the resulting  
code object does not represent the function itself, but a "module"  
defining it:


py> f = FunctionType(compile("def foo(x):\n print x\n y = 2*x\n return  
y\n",

...   "", "exec"), globals(), "foo")
py> f(3)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: () takes no arguments (1 given)
py> dis.dis(f)
  1   0 LOAD_CONST   0 (file "", line 1>)

  3 MAKE_FUNCTION0
  6 STORE_NAME   0 (foo)
  9 LOAD_CONST   1 (None)
 12 RETURN_VALUE

To get at the actual function code, one should use  
f.func_code.co_consts[0]; this would be the 'code' parameter for  
types.FunctionType. Very complicated, really; nothing can beat the 'def'  
statement for defining a function ;)


--
Gabriel Genellina

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


Re: Installing Python 2.6.7 on Windows

2011-09-28 Thread Ned Deily
In article <4e82a1a1$0$29965$c3e8da3$54964...@news.astraweb.com>,
 Steven D'Aprano  wrote:
> On Tue, 27 Sep 2011 14:32:43 -0700, Wanderer wrote:
> > I need to stay in sink with the rest of the company which is still using
> > 2.6 flavors. There was some investigation into going to Python 3 but not
> > enough of the libraries we use were available. I'll install 2.6.6. I
> > don't think the security stuff really effects me. I think it is strange
> > to release a security update but not really expect people to use it.
> 
> 
> More likely the person who builds the Windows installers just hasn't made 
> a new release yet.
> 
> The Python development team is relatively small and chronically busy: too 
> much to do and not enough time to do it. As I understand it, most of them 
> use Linux, so I'm afraid that Windows sometimes takes a back seat. (At 
> least it's not Mac OS, which is stuck riding in the boot of the car, or 
> the other semi-supported OSes, which are on a skateboard desperately 
> hanging onto the bumper trying not to be left behind.)

No, it was a deliberate decision.  After a release is in security-fix 
mode only, we don't build Windows or Mac OS X installers for them.  The 
emphasis is on the actively maintained release branches, currently 3.2.x 
and 2.7.x.  If third-party distributors want to support their users with 
binary installers, that is of course their option.

"Python 2.6.7 is a security-fix only source release for Python 2.6.6, 
fixing several reported security issues. Python 2.6.7 was released on 
June 3, 2011.

Python 2.6 is now in security-fix-only mode; no new features are being 
added, and no new bug fix releases are planned. We intend to provide 
source-only security fixes for the Python 2.6 series until October 2013 
(five years after the 2.6 final release). For ongoing maintenance 
releases, please see the Python 2.7 series."

http://www.python.org/getit/releases/2.6.7/

(And I think you may be just slightly mischaracterizing the status of 
both Mac OS X and Windows support.)

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

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


Re: A Trivial Question

2011-09-28 Thread Chris Rebert
On Wed, Sep 28, 2011 at 2:53 PM, Tayfun Kayhan
 wrote:
> I accidentally wrote such a code (below) while trying to write sth else for
> my application but i am now just wondering much how to run the class Foo, if
> it is possible. Is not it weird that Python does not give any error when I
> run it ? Sorry for that it's pretty unimportant question according to the
> other questions being asked here :D
> def trial():
> class Foo(object):
> def __init__(self):
> print("Hello, world!")
> trial() # not worked, as expected.

Right now, you've merely defined a class in the local scope of a
function, which is perfectly valid, although you don't take advantage
of this, so there's no particular reason to put the class definition
inside trial(). Foo.__init__() only gets called when you create an
instance of Foo, which you aren't doing currently, hence why "Hello,
world!" isn't printed.

Try this:

def trial():
class Foo(object):
def __init__(self):
print("Hello, world!")
Foo()
trial()


Or this:

class Foo(object):
def __init__(self):
print("Hello, world!")

def trial():
Foo()
trial()


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


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Terry Reedy

On 9/28/2011 10:16 AM, Tim Chase wrote:


When performing unittest tests, I have a number of methods of the form

def test_foo(self):
data = (
(item1, result1),
... #bunch of tests for fence-post errors
)
for test, result in data:
self.assertEqual(process(test), result)

When I run my tests, I only get a tick for running one the one test
(test_foo), not the len(data) tests that were actually performed. Is
there a way for unittesting to report the number of passed-assertions
rather than the number of test-methods run?


In my view, unittest, based on JUnit from Java, is both overkill and 
inadequate for simple function testing of multiple input-output pairs. 
So I wrote my own short function test function that does just what I 
want, and which I can change if I change what I want.


Ben has described the combinatorial explosion solution. But if I were 
using unittest, I might do something like the following:


  def test_foo(self):
data = (
  (item1, result1),
  ... #bunch of tests for fence-post errors
  )
errors = []
for input, expected in data:
  try:
actual = process(input)
if actual != expected: errors.append(input, expected, actual)
  except Exception as e:
errors.append(input, expected, actual)
self.assertEqual((0,[]), (len(errors),errors))

except that I would write a functest(func, iopairs) that returned the 
error pair. (This is essentially what I have done for for myself.)  I am 
presuming that one can run unittest so that it prints the unequal items.


--
Terry Jan Reedy

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


A Trivial Question

2011-09-28 Thread Tayfun Kayhan
I accidentally wrote such a code (below) while trying to write sth else for my 
application but i am now just wondering much how to run the class Foo, if it is 
possible. Is not it weird that Python does not give any error when I run it ? 
Sorry for that it's pretty unimportant question according to the other 
questions being asked here :D

def trial():
class Foo(object):
def __init__(self):
print("Hello, world!")
trial() # not worked, as expected.-- 
http://mail.python.org/mailman/listinfo/python-list


Re: syntactic sugar for def?

2011-09-28 Thread Chris Kaynor
On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle  wrote:
> On 28 September 2011 22:26, Ethan Furman  wrote:
>> I remember that 'class' is sugar for type().
>>
>> I don't remember if 'def' is sugar for something besides lambda.
>>
>> Any clues for me?  Heck, I'll even be grateful for outright answers!
>
> It's not really sugar.  But I think you mean something like this:
>
>
 class A: pass
> ...
 type(A)
> 
 type is type(A)
> True
>
> So the closest you get for functions will be:
>
 def f(): pass
> ...
 type(f)
> 
>
> Try help(type(f)) to see how to use it to create a function object.
> The problem is that you need to provide a code object, and the easiest
> way to create a code object is to use a def statement :)

I would say compile isn't too much harder to use:
>>> c = compile('a = 123', 'test', 'exec')
>>> d = {}
>>> f = types.FunctionType(c, d, 'test')
>>> f()
>>> print d
{'a': 123}

Although it appears you get all of the variables defined as global
apparently (try "f = types.FunctionType(c, globals(), 'test')"
instead).

>
> HTH
>
> --
> Arnaud
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: syntactic sugar for def?

2011-09-28 Thread Arnaud Delobelle
On 28 September 2011 22:26, Ethan Furman  wrote:
> I remember that 'class' is sugar for type().
>
> I don't remember if 'def' is sugar for something besides lambda.
>
> Any clues for me?  Heck, I'll even be grateful for outright answers!

It's not really sugar.  But I think you mean something like this:


>>> class A: pass
...
>>> type(A)

>>> type is type(A)
True

So the closest you get for functions will be:

>>> def f(): pass
...
>>> type(f)


Try help(type(f)) to see how to use it to create a function object.
The problem is that you need to provide a code object, and the easiest
way to create a code object is to use a def statement :)

HTH

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


Re: syntactic sugar for def?

2011-09-28 Thread Ian Kelly
On Wed, Sep 28, 2011 at 3:26 PM, Ethan Furman  wrote:
> I remember that 'class' is sugar for type().
>
> I don't remember if 'def' is sugar for something besides lambda.
>
> Any clues for me?  Heck, I'll even be grateful for outright answers!

If you mean is there a way to create functions using reflection, you
can use types.FunctionType.  Like type() requires a dict,
FunctionType() requires a code object that must first be compiled.

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


syntactic sugar for def?

2011-09-28 Thread Ethan Furman

I remember that 'class' is sugar for type().

I don't remember if 'def' is sugar for something besides lambda.

Any clues for me?  Heck, I'll even be grateful for outright answers!

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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Terry Reedy

On 9/28/2011 5:28 AM, Xah Lee wrote:

curious question.

suppose you have 300 different strings and they need all be replaced
to say "aaa".

is it faster to replace each one sequentially (i.e. replace first
string to aaa, then do the 2nd, 3rd,...)
, or is it faster to use a regex with “or” them all and do replace one
shot? (i.e. "1ststr|2ndstr|3rdstr|..." ->  aaa)


Here the problem is replace multiple random substrings with one random 
substring that could create new matches. I would start with the re 'or' 
solution.



btw, the origin of this question is about writing a emacs lisp
function that replace ~250 html named entities to unicode char.


As you noted this is a different problem in that there is a different 
replacement for each. Also, the substrings being searched for are not 
random but have a distinct and easily recognized structure. The 
replacement cannot create a new match. So the multiple scan approach 
*could* work.


Unspecified is whether the input is unicode or ascii bytes. If the 
latter I might copy to a bytearray (mutable), scan forward, replace 
entity defs with utf-8 encoding of the corresponding unicode (with a 
dict lookup, and which I assume are *always* fewer chars), and shift 
other chars to close any gaps created.


If the input is unicode, I might do the same with array.array (which is 
where bytearray came from). Or I might use the standard idiom of 
constructing a list of pieces of the original, with replacements, and 
''.join() at the end.


--
Terry Jan Reedy


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


Re: new to python question

2011-09-28 Thread Benjamin Kaplan
On Wed, Sep 28, 2011 at 5:06 PM, The Geek  wrote:
> I'm clearly not understanding something about scope in python...  Any help
> is appreciated
> In the following script I'm attempting to create 2 Foo objects, for each Foo
> object I create 2 Bars and add them to Foo's bar array
> Something hokey is occurring with the "foo.bars.append(bar)" line such that
> Foo.bars is treated as a "static" (I know python doesn't have statics)
> I have a workaround using encapsulation for the bars array but I prefer
> would also like to understand the issue.
> TIA,
> Brad
> [SCRIPT]
> foos = []
> class Foo:
> id = 0
> bars = []
> class Bar:
> id = 0
> for j in range(0, 2):
> foo = Foo()
> for i in range(0, 2):
> bar = Bar()
> bar.id = i
> foo.bars.append(bar)
> foos.append(foo)
> for myFoo in foos:
> print("foo id: ", myFoo.id)
> for myBar in myFoo.bars:
> print ("\tbar id: ", myBar.id)
> [/SCRIPT]


It's a pretty common gotcha for people coming from other languages.
Everything declared in the class scope becomes an attribute of the
class.
>>> class Foo(object) :
...a = 3
...def b() : pass
...
>>> dir(Foo)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribut
e__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_e
x__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_
_weakref__', 'a', 'b']

Mutating those objects mutates the attribute of the class, which is
visible to all instances of the class.

In order to get an instance of a class, you have to add the field to
the instance of the class instead of to the class itself.

class Bar(object) :
def ___init__(self) :
self.a = 3
-- 
http://mail.python.org/mailman/listinfo/python-list


new to python question

2011-09-28 Thread The Geek
I'm clearly not understanding something about scope in python...  Any help
is appreciated

In the following script I'm attempting to create 2 Foo objects, for each Foo
object I create 2 Bars and add them to Foo's bar array

Something hokey is occurring with the "foo.bars.append(bar)" line such that
Foo.bars is treated as a "static" (I know python doesn't have statics)

I have a workaround using encapsulation for the bars array but I prefer
would also like to understand the issue.

TIA,
Brad

[SCRIPT]
foos = []

class Foo:
id = 0
bars = []

class Bar:
id = 0

for j in range(0, 2):
foo = Foo()

for i in range(0, 2):
bar = Bar()
bar.id = i
foo.bars.append(bar)
foos.append(foo)

for myFoo in foos:
print("foo id: ", myFoo.id)
for myBar in myFoo.bars:
print ("\tbar id: ", myBar.id)

[/SCRIPT]

[OUTPUT]
python test.py
foo id:  0
bar id:  0
bar id:  1
bar id:  0
bar id:  1
foo id:  0
bar id:  0
bar id:  1
bar id:  0
bar id:  1
[/OUTPUT]
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread John Bokma
Willem  writes:

> Eli the Bearded wrote:
> ) In comp.lang.perl.misc, Willem   wrote:
> )> In Perl, it would be applicable.  You see, in Perl, you can call a function
> )> in the replacement of the regex substitution, which can then look up the
> )> html entity and return the wanted unicode literal.
> )
> ) A function? I'd use a hash.
>
> A function can return a sensible value for unknown substitutions.

You can do that also in the RHS of the substitution and still keep it
readable if you use something like

s{..}{

your
code
goes
here
}ge;

However, a function can be easier on the eye:

s{...}{ some_good_name( ... ) }ge;

-- 
John Bokma   j3b

Blog: http://johnbokma.com/Perl Consultancy: http://castleamber.com/
Perl for books:http://johnbokma.com/perl/help-in-exchange-for-books.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Willem
Eli the Bearded wrote:
) In comp.lang.perl.misc, Willem   wrote:
)> In Perl, it would be applicable.  You see, in Perl, you can call a function
)> in the replacement of the regex substitution, which can then look up the
)> html entity and return the wanted unicode literal.
)
) A function? I'd use a hash.

A function can return a sensible value for unknown substitutions.
In the case where you prebuild a giant regex or-list, that is not an issue,
but I would match html entities generically.


SaSW, Willem
-- 
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Eli the Bearded
In comp.lang.perl.misc, Willem   wrote:
> In Perl, it would be applicable.  You see, in Perl, you can call a function
> in the replacement of the regex substitution, which can then look up the
> html entity and return the wanted unicode literal.

A function? I'd use a hash.

> I think you can do that in some other languages as well.

Hash / array type substitutions indexed by $1 (or language equivilent)
are probably easy to implement in many languages.

Elijah
--
for really fast, write code to generate a C lexer to do it
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Ian Kelly
On Wed, Sep 28, 2011 at 3:28 AM, Xah Lee  wrote:
> curious question.
>
> suppose you have 300 different strings and they need all be replaced
> to say "aaa".
>
> is it faster to replace each one sequentially (i.e. replace first
> string to aaa, then do the 2nd, 3rd,...)
> , or is it faster to use a regex with “or” them all and do replace one
> shot? (i.e. "1ststr|2ndstr|3rdstr|..." -> aaa)
>
> let's say the sourceString this replacement to be done on is 500k
> chars.
>
> Anyone? i suppose the answer will be similar for perl, python, ruby.
>
> btw, the origin of this question is about writing a emacs lisp
> function that replace ~250 html named entities to unicode char.

I haven't timed it at the scale you're talking about, but for Python I
expect regex will be your best bet:

# Python 3.2: Supposing the match strings and replacements are
# in a dict stored as `repls`...

import re

pattern = '|'.join(map(re.escape, repls.keys()))
new_str = re.sub(pattern, lambda m: repls[m.group()], old_str)

The problem with doing 300 str.replace calls is the 300 intermediate
strings that would be created and then collected.

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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread MRAB

On 28/09/2011 18:00, Willem wrote:

Xah Lee wrote:
) the question originally came from when i was coding elisp of a
) function that changes html entities to unicode char literal. The
) problem is slightly complicated, involving a few questions about speed
) in emacs. e.g. string vs buffer, and much more... i spent several
) hours on this but it's probably too boring to detail (but i'll do so
) if anyone wishes). But anyway, while digging these questions that's
) not clear in my mind, i thought of why not generate a regex or
) construct and do it in one shot, and wondered if that'd be faster. But
) afterwards, i realized this wouldn't be applicable to my problem
) because for my problem each string needs to be changed to a unique
) string, not all to the same string.

In Perl, it would be applicable.  You see, in Perl, you can call a function
in the replacement of the regex substitution, which can then look up the
html entity and return the wanted unicode literal.

I think you can do that in some other languages as well.


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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Willem
Xah Lee wrote:
) the question originally came from when i was coding elisp of a
) function that changes html entities to unicode char literal. The
) problem is slightly complicated, involving a few questions about speed
) in emacs. e.g. string vs buffer, and much more... i spent several
) hours on this but it's probably too boring to detail (but i'll do so
) if anyone wishes). But anyway, while digging these questions that's
) not clear in my mind, i thought of why not generate a regex or
) construct and do it in one shot, and wondered if that'd be faster. But
) afterwards, i realized this wouldn't be applicable to my problem
) because for my problem each string needs to be changed to a unique
) string, not all to the same string.

In Perl, it would be applicable.  You see, in Perl, you can call a function
in the replacement of the regex substitution, which can then look up the
html entity and return the wanted unicode literal.

I think you can do that in some other languages as well.


SaSW, Willem
-- 
Disclaimer: I am in no way responsible for any of the statements
made in the above text. For all I know I might be
drugged or something..
No I'm not paranoid. You all think I'm paranoid, don't you !
#EOT
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python 2.5 zlib trouble

2011-09-28 Thread Alec Taylor
Fix: 
http://lipyrary.blogspot.com/2011/05/how-to-compile-python-on-ubuntu-1104.html

On Tue, Sep 27, 2011 at 5:04 AM, Benjamin Kaplan
 wrote:
> On Mon, Sep 26, 2011 at 2:16 PM, Jesramz  
> wrote:
>>
>> I appreciate all the help, but I am still a little confused. Sorry,
>> I'm a lay person.
>>
>> Should I download zlib1g-dev and install it to get the zlib module?
>>
>> and Alter the configure script to avoid future issues?
>>
>> Also about getting zlib I found the following:
>>
>> "I was able to recompile zlib
>>
>> $./configure --shared
>>
>> then recompile Python 2.5.1; I am now able to import the zlib module.
>>
>> cheers
>>
>> -sg"
>>
>> Does this mean that while in the zlib folder run ./configure shared
>> and then install python?
>> --
>
> Not quite. This person was talking about configuring zlib, not Python.
> Just about every Linux program out there has a ./configure file- it's
> part of GNU Autotools, which many programs use as an easy way to
> compile and install their software. Since the version of zlib on
> Ubuntu Natty doesn't work for Python 2.5, this person just compiled
> their own zlib (calling ./configure --shared; make; make install from
> the zlib *source* folder that they downloaded) and then compiled their
> own Python version (from the Python source folder that they
> downloaded)
>
>
>> http://mail.python.org/mailman/listinfo/python-list
>>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to run in xp?

2011-09-28 Thread David Robinow
On Wed, Sep 28, 2011 at 9:29 AM, Peter Otten <__pete...@web.de> wrote:
> =?gbk?B?ytjW6rT9zcM=?= wrote:
>
>> it can run ,but there is still a problem ,nothing in my file.
>> please run the code in xp+python32
>> import urllib.request, urllib.parse, urllib.error
>> exchange=['NASDAQ','NYSE','AMEX']
>> for down in exchange:
>>     url='http://www.nasdaq.com/screening/companies-by-
> industry.aspx?exchange='+down+'&render=download'
>>     file=urllib.request.urlopen(url).read()
>>     print (file)
>> what you get is:
>>
>
>> b''
>> b''
>> b''
>
>>
>> how to fix it?
>
> I get the expected output, but I'm on Linux. Are you using the latest bugfix
> release (Python 3.2.2)? Can you download the data with your browser?
I get the expected output, but I'm on Windows (Vista, Python 3.2.2.)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Ben Finney
Ben Finney  writes:

> You can use the third-party ‘testscenarios’ library

The URL got a bit mangled. The proper PyPI URL for that library is
http://pypi.python.org/pypi/testscenarios>.

> to generate test cases at run time, one for each combination of
> scenarios with test cases on the class. They will all be run and
> reported as distinct test cases.
>
> There is even another library integrating this with Django
> http://pypi.python.org/pypi/django-testscenarios>.

-- 
 \“Don't worry about people stealing your ideas. If your ideas |
  `\ are any good, you'll have to ram them down people's throats.” |
_o__)—Howard Aiken |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Ben Finney
Tim Chase  writes:

>   def test_foo(self):
> data = (
>   (item1, result1),
>   ... #bunch of tests for fence-post errors
>   )
> for test, result in data:
>   self.assertEqual(process(test), result)

The sets of data for running the same test we might call “scenarios”.

> When I run my tests, I only get a tick for running one the one test
> (test_foo), not the len(data) tests that were actually performed.

Worse, if one of the scenarios causes the test to fail, the loop will
end and you won't get the results for the remaining scenarios.

> Is there a way for unittesting to report the number of
> passed-assertions rather than the number of test-methods run?

You can use the third-party ‘testscenarios’ library
http://pypi.python.org/pypi/test-scenarios> to generate test cases
at run time, one for each combination of scenarios with test cases on
the class. They will all be run and reported as distinct test cases.

There is even another library integrating this with Django
http://pypi.python.org/pypi/django-testscenarios>.

-- 
 \ “Books and opinions, no matter from whom they came, if they are |
  `\ in opposition to human rights, are nothing but dead letters.” |
_o__)  —Ernestine Rose |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Suggested coding style

2011-09-28 Thread Ben Finney
DevPlayer  writes:

> Calling the Bible a joke is used to hurt people, not enlighten them.

How do you know that?

> Those words show bitter arrogance, not constructive critism

How do you know that?

> as it ignores how others feel about that book.

That strikes me as a good thing; how people feel about a book should not
in any way restrain our criticism of the book.

> What benefit to others is gained by calling someones belief a joke? To
> put the "believers" minds straight? I think not.

I can't speak for the person who wrote that. But when I call a religious
belief a joke, it is to point out the folly of the belief in the pursuit
of convincing people not to hold beliefs I consider to be foolish.

> I think the unsensitive person who attackes others beliefs, even if
> illogical or unrealistic, is after some kind of self grandizement or
> to illude themself into thinking "they know the truth of the universe"
> and should attack others to prove they do.

You are wrong to conflate “attack others's beliefs” with “attack
others”.

You are not your beliefs. If your beliefs are shown to be false – even
ridiculous – you can distance yourself from those beliefs. It is even
virtuous to do so.

We must always be free to attack any belief, and encourage everyone to
stop taking it as any kind of personal attack.

> Although this is not the place to defend about such things it is also
> not the place to attack those same things (that being someone's
> faith).

I will join you in deploring any attack on a person. But that's not what
you're doing, and I deny your attempt to shield any idea from ridicule,
in any forum.

Ideas don't have feelings, and you don't get to put people in front of
them as human shields against attacking those ideas.

Any idea is and must be open to attack in any forum; those that can't
survive ridicule deserve to go.

-- 
 \  “Ridicule is the only weapon which can be used against |
  `\   unintelligible propositions.” —Thomas Jefferson, 1816-07-30 |
_o__)  |
Ben Finney
-- 
http://mail.python.org/mailman/listinfo/python-list


Unittest testing assert*() calls rather than methods?

2011-09-28 Thread Tim Chase
While I asked this on the Django list as it happened to be with 
some Django testing code, this might be a more generic Python 
question so I'll ask here too.


When performing unittest tests, I have a number of methods of the 
form


  def test_foo(self):
data = (
  (item1, result1),
  ... #bunch of tests for fence-post errors
  )
for test, result in data:
  self.assertEqual(process(test), result)

When I run my tests, I only get a tick for running one the one 
test (test_foo), not the len(data) tests that were actually 
performed.  Is there a way for unittesting to report the number 
of passed-assertions rather than the number of test-methods run?


-tkc


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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Chris Angelico
On Wed, Sep 28, 2011 at 11:22 PM, Neil Cerutti  wrote:
> I'd like to know what "string replacement" is supposed to mean in
> the context of Python.
>

Substring replacement, such as:
>>> "Hello, world!".replace(", "," -- ")
'Hello -- world!'

The str method doesn't accept a list, though, so it won't do
simultaneous replaces. (At least, I don't think it can. Tried it only
in Python 3.2 on Windows.)

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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Roy Smith
In article <9egld1f38...@mid.individual.net>,
 Neil Cerutti  wrote:

> On 2011-09-28, Chris Angelico  wrote:
> > On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee  wrote:
> >> each string needs to be changed to a unique string, not all to
> >> the same string.
> >
> > And you'll find that this is, by and large, the most normal
> > situation. Folding many strings down to one string is a lot
> > less common. So, let's have some real-world use cases and then
> > we can talk recommendations.
> 
> I'd like to know what "string replacement" is supposed to mean in
> the context of Python.

You just need to use "string" in the more generic computer-sciency 
sense, not in the python-data-type sense.

s = "I am an immutable string"
l = list(s)  # now you can pretend strings are mutable
do_stuff_to_string(l)
s = ''.join(l)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to run in xp?

2011-09-28 Thread Peter Otten
=?gbk?B?ytjW6rT9zcM=?= wrote:

> it can run ,but there is still a problem ,nothing in my file.
> please run the code in xp+python32
> import urllib.request, urllib.parse, urllib.error
> exchange=['NASDAQ','NYSE','AMEX']
> for down in exchange:
> url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download'
> file=urllib.request.urlopen(url).read()
> print (file)
> what you get is:
> 
 
> b''
> b''
> b''
 
> 
> how to fix it?

I get the expected output, but I'm on Linux. Are you using the latest bugfix 
release (Python 3.2.2)? Can you download the data with your browser?

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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Neil Cerutti
On 2011-09-28, Chris Angelico  wrote:
> On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee  wrote:
>> each string needs to be changed to a unique string, not all to
>> the same string.
>
> And you'll find that this is, by and large, the most normal
> situation. Folding many strings down to one string is a lot
> less common. So, let's have some real-world use cases and then
> we can talk recommendations.

I'd like to know what "string replacement" is supposed to mean in
the context of Python.

-- 
Neil Cerutti
"A politician is an arse upon which everyone has sat except a man."
  e. e. cummings 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Chris Angelico
On Wed, Sep 28, 2011 at 11:14 PM, Xah Lee  wrote:
> (while (< ii (length pairs))
>      (setq mystr (replace-regexp-in-string
>                   (elt tempMapPoints ii)
>                   (elt (elt pairs ii) 1)
>                   mystr t t))
>      (setq ii (1+ ii))
>      )

from __future__ import lisp_syntax

There, that makes it on-topic for the Python list... I guess.

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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Xah Lee
here's more detail about the origin of this problem. Relevant to emacs
lisp only.

--

in the definition of “replace-regexp-in-string”, there's this comment:

  ;; To avoid excessive consing from multiple matches in long strings,
  ;; don't just call `replace-match' continually.  Walk down the
  ;; string looking for matches of REGEXP and building up a (reversed)
  ;; list MATCHES.  This comprises segments of STRING which weren't
  ;; matched interspersed with replacements for segments that were.
  ;; [For a `large' number of replacements it's more efficient to
  ;; operate in a temporary buffer; we can't tell from the function's
  ;; args whether to choose the buffer-based implementation, though it
  ;; might be reasonable to do so for long enough STRING.]

note: «For a `large' number of replacements it's more efficient to
operate in a temporary buffer».

my question is, anyone got some idea, how “large” is large?

currently, i have a function replace-pairs-in-string which is
implemented by repeatedly calling “replace-pairs-in-string” like this:

(while (< ii (length pairs))
  (setq mystr (replace-regexp-in-string
   (elt tempMapPoints ii)
   (elt (elt pairs ii) 1)
   mystr t t))
  (setq ii (1+ ii))
  )

When there are 260 pairs of strings to be replaced on a file that's
26k in size, my function takes about 3 seconds (which i think is too
slow). I'm at pain deciding whether my function should be implemented
like this or whether it should create a temp buffer. The problem with
temp buffer is that, if you repeatedly call it, the overhead of
creating buffer is going to make it much slower.

i was actually surprised that replace-regexp-in-string isn't written
in C, which i thought it was.

is there technical reason the replace-regexp-in-string isn't C? (i
suppose only because nobody every did it and the need for speed didn't
suffice?) and also, shouldn't there also be a replace-in-string
(literal, not regex)? because i thought implementing replacement for
string should be much simpler and faster, because buffers comes with
it a whole structure such as “point”, text properties, buffer names,
buffier modifier, etc.

 Xah

On Sep 28, 5:28 am, Xah Lee  wrote:
> On Sep 28, 3:57 am, mer...@stonehenge.com (Randal L. Schwartz) wrote:
>
> > > "Xah" == Xah Lee  writes:
>
> > Xah> curious question.
> > Xah> suppose you have 300 different strings and they need all be replaced
> > Xah> to say "aaa".
>
> > And then suppose this isn't the *real* question, but one entirely of
> > Fiction by Xah Lee.
>
> > How helpful do you want to be?
>
> it's a interesting question anyway.
>
> the question originally came from when i was coding elisp of a
> function that changes html entities to unicode char literal. The
> problem is slightly complicated, involving a few questions about speed
> in emacs. e.g. string vs buffer, and much more... i spent several
> hours on this but it's probably too boring to detail (but i'll do so
> if anyone wishes). But anyway, while digging these questions that's
> not clear in my mind, i thought of why not generate a regex or
> construct and do it in one shot, and wondered if that'd be faster. But
> afterwards, i realized this wouldn't be applicable to my problem
> because for my problem each string needs to be changed to a unique
> string, not all to the same string.
>
>  Xah

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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Chris Angelico
On Wed, Sep 28, 2011 at 10:28 PM, Xah Lee  wrote:
> each string needs to be changed to a unique
> string, not all to the same string.

And you'll find that this is, by and large, the most normal situation.
Folding many strings down to one string is a lot less common. So,
let's have some real-world use cases and then we can talk
recommendations.

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


Re: oauth2 server implementation

2011-09-28 Thread Roy Smith
In article 
<862e37e9-f4d2-4423-8d28-485923f1c...@p11g2000yqe.googlegroups.com>,
 Aljosa Mohorovic  wrote:

> On Sep 28, 2:17 am, Roy Smith  wrote:
> > We rolled our own oauth2 client on top of basic urllib calls.  It's not
> > terribly difficult.
> 
> i'm asking about oauth2 server implementation, not client.
> it's easy to consume oauth2 stuff but what to do when you need to
> implement server side stuff?

Oh, my apologies, I read your post too fast and misunderstood what you 
were asking.  I suspect writing an oauth2 provider will be on my plate 
soon, so let me know what you figure out :-)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Hierarchical commnd line parsing / help texts

2011-09-28 Thread Michele Simionato
plac is based on argparser and it is intended to be much easier to use. See
http://plac.googlecode.com/hg/doc/plac.html

Here is an example of usage.

$ cat vcs.py
class VCS(object):
"A fictitious version control tool"
commands = ['checkout', 'commit']
def checkout(self, url):
return 'ok'
def commit(self):
return 'ok'

if __name__ == '__main__':
import plac; plac.Interpreter.call(VCS)

The line plac.Interpreter.call instantiates the VCS class by passing to it the 
arguments in the command line and then calls the appropriate method.

You can use the script as follows:

$ python vcs.py -h
usage: vcs.py [-h] [args [args ...]]

positional arguments:
  args

optional arguments:
  -h, --help  show this help message and exit

$ python vcs.py checkout url
ok
$ python vcs.py commit
ok
plac takes care of parsing the command line, giving the correct error message 
if you pass wrong arguments or not enough arguments:

$ python vcs.py checkout
usage:  checkout url
 checkout: error: too few arguments

plac can also be used to write command interpreters.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Xah Lee
On Sep 28, 3:57 am, mer...@stonehenge.com (Randal L. Schwartz) wrote:
> > "Xah" == Xah Lee  writes:
>
> Xah> curious question.
> Xah> suppose you have 300 different strings and they need all be replaced
> Xah> to say "aaa".
>
> And then suppose this isn't the *real* question, but one entirely of
> Fiction by Xah Lee.
>
> How helpful do you want to be?

it's a interesting question anyway.

the question originally came from when i was coding elisp of a
function that changes html entities to unicode char literal. The
problem is slightly complicated, involving a few questions about speed
in emacs. e.g. string vs buffer, and much more... i spent several
hours on this but it's probably too boring to detail (but i'll do so
if anyone wishes). But anyway, while digging these questions that's
not clear in my mind, i thought of why not generate a regex or
construct and do it in one shot, and wondered if that'd be faster. But
afterwards, i realized this wouldn't be applicable to my problem
because for my problem each string needs to be changed to a unique
string, not all to the same string.

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


Re: Suggested coding style

2011-09-28 Thread DevPlayer
On Sep 27, 10:25 pm, alex23  wrote:
> rantingrick  wrote:
> > Since, like the bible
> > the zen is self contradicting, any argument utilizing the zen can be
> > defeated utilizing the zen.
>
> And like the Bible, the Zen was created by humans as a joke. If you're
> taking it too seriously, that's your problem.
>
> > If however you want to learn about the accepted rules for formatting
> > code then you need to read "PEP-8"! PEP 8 is our style guide.
>
Contradiction is only seen by narrow perspectve.

Calling the Bible a joke is used to hurt people, not enlighten them.
Those words show bitter arrogance, not constructive critism as it
ignores how others feel about that book. What benefit to others is
gained by calling someones belief a joke? To put the "believers" minds
straight? I think not. I think the unsensitive person who attackes
others beliefs, even if illogical or unrealistic, is after some kind
of self grandizement or to illude themself into thinking "they know
the truth of the universe" and should attack others to prove they do.

Although this is not the place to defend about such things it is also
not the place to attack those same things (that being someone's
faith). There is no real forum to defend a faith or religion, or words
in a book about that, other then where such faiths are in fact
attacked.

However I did laugh at the ironic use of using any-kind of zen to
seriously, even Python's, as that is very unzen-like. That is a
contradiction by it's very own definitions!
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: how to run in xp?

2011-09-28 Thread 守株待兔
it can run ,but there is still a problem ,nothing in my file.
please run the code in xp+python32
import urllib.request, urllib.parse, urllib.error
exchange=['NASDAQ','NYSE','AMEX']
for down in exchange:

url='http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download'
file=urllib.request.urlopen(url).read()
print (file)
what you get is:

>>> 
b''
b''
b''
>>> 

how to fix it?
-- Original --
From:  "Peter Otten"<__pete...@web.de>;
Date:  Wed, Sep 28, 2011 04:04 PM
To:  "python-list"; 

Subject:  Re: how to run in xp?

 
=?gbk?B?ytjW6rT9zcM=?= wrote:

> #coding:utf-8
> import urllib
> exchange=['NASDAQ','NYSE','AMEX']
> for down in exchange:
> myfile=open('./'+down,'w')
> url='http://www.nasdaq.com/screening/companies- \ 
> by-industry.aspx?exchange='+down+'&render=download'
> file=urllib.urlopen(url).read() myfile.write(file)
> print ('ok',down)
> myfile.close()
> 
> it can run in ubuntu+python2.6 ,when it run in window xp+python32,the
> output is Traceback (most recent call last):
>   File "C:\Python32\getcode.py", line 8, in 
> file=urllib.urlopen(url).read()
> AttributeError: 'module' object has no attribute 'urlopen'
> 
> i change it into:
> #coding:utf-8
> import urllib.request
> exchange=['NASDAQ','NYSE','AMEX']
> for down in exchange:
> myfile=open('./'+down,'w')
> url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download'
> file=urllib.request.urlopen(url).read()
> myfile.write(file)
> print ('ok',down)
> myfile.close()
> 
> the output is :
> Traceback (most recent call last):
>   File "C:\Python32\getcode.py", line 9, in 
> myfile.write(file)
> TypeError: must be str, not bytes
> 
> how to make it run in xp+python32?

The problem here is the switch from Python 2 to 3. Python 3 has some 
backwards-incompatible Syntax changes along with changes to classes and 
library organisation. The good news is that there's a tool, 2to3, that can 
handle most of these changes:

$ cat getcode.py
#coding:utf-8   
import urllib   
exchange=['NASDAQ','NYSE','AMEX'] 
for down in exchange: 
myfile=open('./'+down,'wb')   
url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download' 
file=urllib.urlopen(url).read() 
   
myfile.write(file)  
   
print 'ok', down
myfile.close()
$ cp getcode.py getcode3.py
$ 2to3-3.2 getcode3.py -w
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored getcode3.py
--- getcode3.py (original)
+++ getcode3.py (refactored)
@@ -1,10 +1,10 @@
 #coding:utf-8
-import urllib
+import urllib.request, urllib.parse, urllib.error
 exchange=['NASDAQ','NYSE','AMEX']
 for down in exchange:
 myfile=open('./'+down,'wb')
 url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download'
-file=urllib.urlopen(url).read()
+file=urllib.request.urlopen(url).read()
 myfile.write(file)
-print 'ok', down
+print('ok', down)
 myfile.close()
RefactoringTool: Files that were modified:
RefactoringTool: getcode3.py
$ cat getcode3.py
#coding:utf-8
import urllib.request, urllib.parse, urllib.error
exchange=['NASDAQ','NYSE','AMEX']
for down in exchange:
myfile=open('./'+down,'wb')
url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download'
file=urllib.request.urlopen(url).read()
myfile.write(file)
print('ok', down)
myfile.close()
$ python3.2 getcode3.py
ok NASDAQ
ok NYSE
ok AMEX


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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Randal L. Schwartz
> "Xah" == Xah Lee  writes:

Xah> curious question.
Xah> suppose you have 300 different strings and they need all be replaced
Xah> to say "aaa".

And then suppose this isn't the *real* question, but one entirely of
Fiction by Xah Lee.

How helpful do you want to be?

-- 
Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095
 http://www.stonehenge.com/merlyn/>
Smalltalk/Perl/Unix consulting, Technical writing, Comedy, etc. etc.
See http://methodsandmessages.posterous.com/ for Smalltalk discussion
-- 
http://mail.python.org/mailman/listinfo/python-list


RE: python 2.7.1 HP-UX 11 ia64 built not supporting thread

2011-09-28 Thread Wong Wah Meng-R32813
Hello there,

I included --with-threads option into the configure script calling, which it 
failed to add the -D_REENTRANT into Makefile. So I manually added this into OPT 
of the Makefile. I ran make again and generated a new python binary. However, 
the new binary is still not able to start a new thread from the thread module. 

I reviewed the config.log file, I think this failure has caused the build with 
threads failed. Cthreads.h header file is missing. Should this be included in 
my HP UX Compiler or it comes from python source? In python source I only found 
pythread.h. Anyway, I am only guessing what is wrong. 

Hope to hear some feedback here, whether this is something missing or a bug. 

configure:8407: checking for --with-threads
configure:8427: result: yes
configure:8484: checking for _POSIX_THREADS in unistd.h
configure:8503: result: yes
configure:8508: checking cthreads.h usability
configure:8508: cc +DD64 -I/home/r32813/local/include -c -g  conftest.c >&5
"conftest.c", line 128: error #3696-D: cannot open source file "cthreads.h"
  #include 
   ^
1 error detected in the compilation of "conftest.c".

| #define HAVE_LIBDLD 1
| #define _REENTRANT 1
| /* end confdefs.h.  */
| #include 
configure:8508: result: no
configure:8508: checking for cthreads.h
configure:8508: result: no
configure:8521: checking mach/cthreads.h usability
configure:8521: cc +DD64 -I/home/r32813/local/include -c -g  conftest.c >&5
"conftest.c", line 128: error #3696-D: cannot open source file "mach/cthreads.h"
  #include 
^

1 error detected in the compilation of "conftest.c".
configure:8521: $? = 2
configure: failed program was:
| /* confdefs.h */
| #define _GNU_SOURCE 1

| #define HAVE_LIBDLD 1
| #define _REENTRANT 1
| /* end confdefs.h.  */
| #include 
configure:8521: result: no
configure:8521: checking for mach/cthreads.h
configure:8521: result: no
configure:8533: checking for --with-pth
configure:8548: result: no
configure:8556: checking for pthread_create in -lpthread
configure:8572: cc +DD64 -I/home/r32813/local/include -o conftest -g  
-L/home/r32813/local/lib -L/home/r32813/Build/2.7.1/Python-2.7.1 conftest.c -l
nsl -lrt -ldld -ldl  -lpthread >&5


Regards,
Wah Meng
Genesis Wafermap Support Ticket: 
To report a problem: 
http://dyno.freescale.net/Question/QuestionMain3.asp?location=zmy02&category=&tickettype=6820
To request a service: 
http://dyno.freescale.net/Question/Questionmain3.asp?location=74&category=2&tickettype=6819
Or if it is related to EWM or DSA: 
http://dyno.freescale.net/Question/Questionmain3.asp?location=ZMY02&tickettype=6539

-Original Message-
From: Wong Wah Meng-R32813 
Sent: Wednesday, September 28, 2011 4:37 PM
To: python-list@python.org
Subject: python 2.7.1 built not supporting thread? 


Hello there,

I couldn't detect this problem until I run my application that utilizes thread 
module in python that I just built on HP-UX 11.31 ia64 using aCC.

Could it be the build did not include enable thread option? _REENTRANT as 
stated in the README file? If yes, it looks like threading may not work "out of 
the box". 


>>> thread.start_new_thread(testing, ())
Traceback (most recent call last):
  File "", line 1, in 
thread.error: can't start new thread
>>>

Excerpts from README file for python 2.7 build

HP-UX:  When using threading, you may have to add -D_REENTRANT to the
OPT variable in the top-level Makefile; reported by Pat Knight,
this seems to make a difference (at least for HP-UX 10.20)
even though pyconfig.h defines it. This seems unnecessary when
using HP/UX 11 and later - threading seems to work "out of the
box".

 

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


Re: oauth2 server implementation

2011-09-28 Thread Aljosa Mohorovic
On Sep 28, 2:17 am, Roy Smith  wrote:
> We rolled our own oauth2 client on top of basic urllib calls.  It's not
> terribly difficult.

i'm asking about oauth2 server implementation, not client.
it's easy to consume oauth2 stuff but what to do when you need to
implement server side stuff?

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


Re: question about speed of sequential string replacement vs regex or

2011-09-28 Thread Chris Angelico
On Wed, Sep 28, 2011 at 7:28 PM, Xah Lee  wrote:
> suppose you have 300 different strings and they need all be replaced
> to say "aaa".
>
> is it faster to replace each one sequentially

Before you ask "is it faster", you need to first be sure it's correct.
I would recommend doing all the replaces in a single function call to
avoid risk of overlaps or other issues causing problems.

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


question about speed of sequential string replacement vs regex or

2011-09-28 Thread Xah Lee
curious question.

suppose you have 300 different strings and they need all be replaced
to say "aaa".

is it faster to replace each one sequentially (i.e. replace first
string to aaa, then do the 2nd, 3rd,...)
, or is it faster to use a regex with “or” them all and do replace one
shot? (i.e. "1ststr|2ndstr|3rdstr|..." -> aaa)

let's say the sourceString this replacement to be done on is 500k
chars.

Anyone? i suppose the answer will be similar for perl, python, ruby.

btw, the origin of this question is about writing a emacs lisp
function that replace ~250 html named entities to unicode char.

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


python 2.7.1 built not supporting thread?

2011-09-28 Thread Wong Wah Meng-R32813

Hello there,

I couldn't detect this problem until I run my application that utilizes thread 
module in python that I just built on HP-UX 11.31 ia64 using aCC.

Could it be the build did not include enable thread option? _REENTRANT as 
stated in the README file? If yes, it looks like threading may not work "out of 
the box". 


>>> thread.start_new_thread(testing, ())
Traceback (most recent call last):
  File "", line 1, in 
thread.error: can't start new thread
>>>

Excerpts from README file for python 2.7 build

HP-UX:  When using threading, you may have to add -D_REENTRANT to the
OPT variable in the top-level Makefile; reported by Pat Knight,
this seems to make a difference (at least for HP-UX 10.20)
even though pyconfig.h defines it. This seems unnecessary when
using HP/UX 11 and later - threading seems to work "out of the
box".

 

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


Re: how to run in xp?

2011-09-28 Thread Peter Otten
=?gbk?B?ytjW6rT9zcM=?= wrote:

> #coding:utf-8
> import urllib
> exchange=['NASDAQ','NYSE','AMEX']
> for down in exchange:
> myfile=open('./'+down,'w')
> url='http://www.nasdaq.com/screening/companies- \ 
> by-industry.aspx?exchange='+down+'&render=download'
> file=urllib.urlopen(url).read() myfile.write(file)
> print ('ok',down)
> myfile.close()
> 
> it can run in ubuntu+python2.6 ,when it run in window xp+python32,the
> output is Traceback (most recent call last):
>   File "C:\Python32\getcode.py", line 8, in 
> file=urllib.urlopen(url).read()
> AttributeError: 'module' object has no attribute 'urlopen'
> 
> i change it into:
> #coding:utf-8
> import urllib.request
> exchange=['NASDAQ','NYSE','AMEX']
> for down in exchange:
> myfile=open('./'+down,'w')
> url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download'
> file=urllib.request.urlopen(url).read()
> myfile.write(file)
> print ('ok',down)
> myfile.close()
> 
> the output is :
> Traceback (most recent call last):
>   File "C:\Python32\getcode.py", line 9, in 
> myfile.write(file)
> TypeError: must be str, not bytes
> 
> how to make it run in xp+python32?

The problem here is the switch from Python 2 to 3. Python 3 has some 
backwards-incompatible Syntax changes along with changes to classes and 
library organisation. The good news is that there's a tool, 2to3, that can 
handle most of these changes:

$ cat getcode.py
#coding:utf-8   
import urllib   
exchange=['NASDAQ','NYSE','AMEX'] 
for down in exchange: 
myfile=open('./'+down,'wb')   
url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download' 
file=urllib.urlopen(url).read() 
   
myfile.write(file)  
   
print 'ok', down
myfile.close()
$ cp getcode.py getcode3.py
$ 2to3-3.2 getcode3.py -w
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored getcode3.py
--- getcode3.py (original)
+++ getcode3.py (refactored)
@@ -1,10 +1,10 @@
 #coding:utf-8
-import urllib
+import urllib.request, urllib.parse, urllib.error
 exchange=['NASDAQ','NYSE','AMEX']
 for down in exchange:
 myfile=open('./'+down,'wb')
 url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download'
-file=urllib.urlopen(url).read()
+file=urllib.request.urlopen(url).read()
 myfile.write(file)
-print 'ok', down
+print('ok', down)
 myfile.close()
RefactoringTool: Files that were modified:
RefactoringTool: getcode3.py
$ cat getcode3.py
#coding:utf-8
import urllib.request, urllib.parse, urllib.error
exchange=['NASDAQ','NYSE','AMEX']
for down in exchange:
myfile=open('./'+down,'wb')
url='http://www.nasdaq.com/screening/companies-by-
industry.aspx?exchange='+down+'&render=download'
file=urllib.request.urlopen(url).read()
myfile.write(file)
print('ok', down)
myfile.close()
$ python3.2 getcode3.py
ok NASDAQ
ok NYSE
ok AMEX


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


Re: Multiplication error in python

2011-09-28 Thread Chris Angelico
On Wed, Sep 28, 2011 at 4:28 PM, Tim Roberts  wrote:
> My guess is that you actually typed
>    p=3*a
> instead of
>    p=2*a
>
> That produces 45.
>

Or alternatively, that you used an interactive Python environment and
didn't clear i between runs.

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


how to run in xp?

2011-09-28 Thread 守株待兔
#coding:utf-8
import urllib
exchange=['NASDAQ','NYSE','AMEX']
for down in exchange:
myfile=open('./'+down,'w')
url='http://www.nasdaq.com/screening/companies- \  
by-industry.aspx?exchange='+down+'&render=download'
file=urllib.urlopen(url).read()
myfile.write(file)
print ('ok',down)
myfile.close()

it can run in ubuntu+python2.6 ,when it run in window xp+python32,the output is 
 
Traceback (most recent call last):
  File "C:\Python32\getcode.py", line 8, in 
file=urllib.urlopen(url).read()
AttributeError: 'module' object has no attribute 'urlopen'

i change it into:
#coding:utf-8
import urllib.request
exchange=['NASDAQ','NYSE','AMEX']
for down in exchange:
myfile=open('./'+down,'w')

url='http://www.nasdaq.com/screening/companies-by-industry.aspx?exchange='+down+'&render=download'
file=urllib.request.urlopen(url).read()
myfile.write(file)
print ('ok',down)
myfile.close()

the output is :
Traceback (most recent call last):
  File "C:\Python32\getcode.py", line 9, in 
myfile.write(file)
TypeError: must be str, not bytes

how to make it run in xp+python32?-- 
http://mail.python.org/mailman/listinfo/python-list