Re: with ignored

2013-04-07 Thread Barrett Lewis
>
> However, ignored() is actually implemented as a generator function
>
with the @contextmanager decorator shortcut.  This decorator takes a
> generator function and wraps it up as a class with the necessary
> __enter__ and __exit__ methods.  The __enter__ method in this case
> calls the .next() method of the generator and returns after it yields
> once.


I looked up the source to the decorator
found here:http://hg.python.org/cpython/file/406b47c64480/Lib/contextlib.py for
anyone interested.
It appears that they are using yield so that they can call it again and
force it to throw the stop iteration exception.



> The __exit__ method calls it again -- or it calls the .throw()
> method if an exception was passed in -- and expects the generator to
> exit as a result.
>
>
And here to go with what I said above, they want to be able to use the
generators throw ability to capture any exception and throw it to the
generator, but then why do they *need* the generator to not iterate again?
Or in other words, why when they create the context manager via
_GeneratorContextManager on line 33, is there the clause in __exit__ to
have stop iteration happen or else throw a runtime error?

I am thinking this is because it needs the yield to be over so that it can
return the control flow to normal, and that subroutine will be done. But I
am new to the whole subroutine paradigm so I could be misunderstanding
this.

Also, if the value was none, why are they instantiating a new exception
with value = type()? How could there be a type for the exception without
the exception? (From what I understand type is the error type, and value is
the error object).


So from the perspective of the generator it does its context setup (in
> this case, setting up a try block) prior to the yield, and then does
> the cleanup (in this case, selectively catching and suppressing the
> exceptions) after the yield.
>
This part makes sense logically. And I like the simplicity. Now I just need
to make sure I understand how the yield semantics are allowing this
construct to work.

Thanks for the reply Ian!

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


Re: with ignored

2013-04-07 Thread Ian Kelly
On Sun, Apr 7, 2013 at 6:40 PM, Barrett Lewis  wrote:
> I was recently watching that Raymond Hettinger video on creating Beautiful
> Python from this years PyCon.
> He mentioned pushing up the new idiom
>
> with ignored():
>  # do some work
>
> I tracked down his commit here http://hg.python.org/cpython/rev/406b47c64480
>
> But am unsure how the yield works in the given situation.
>
> I know about creating generators with yield and have read the docs on how it
> maintains state.
>
> I think it works because it is returning control back to the caller while
> maintaining the try so if the caller throws it is caught by the context. Is
> this correct? I would love an in depth explanation of how this is working. I
> am trying to learn as much as possible about the actual python internals.

The first thing to understand is that ignored() is a context manager
and how context managers work.  A context manager is an object with an
__enter__ method and an __exit__ method.  For example, the ignored()
context manager could have been written as:

class ignored:
def __init__(self, *exceptions):
self.__exceptions = exceptions
def __enter__(self):
return
def __exit__(self, exc_type, exc_value, traceback):
if exc_type is not None:
return issubclass(exc_type, self.__exceptions)

The __enter__ method is called when the with block is entered and sets
up the context.  The __exit__ method is called when the with block is
exited and is passed the exception if one was raised.  It returns True
to suppress the exception, or False to continue propagating it.

However, ignored() is actually implemented as a generator function
with the @contextmanager decorator shortcut.  This decorator takes a
generator function and wraps it up as a class with the necessary
__enter__ and __exit__ methods.  The __enter__ method in this case
calls the .next() method of the generator and returns after it yields
once.  The __exit__ method calls it again -- or it calls the .throw()
method if an exception was passed in -- and expects the generator to
exit as a result.

So from the perspective of the generator it does its context setup (in
this case, setting up a try block) prior to the yield, and then does
the cleanup (in this case, selectively catching and suppressing the
exceptions) after the yield.
-- 
http://mail.python.org/mailman/listinfo/python-list


"pip install PySide" fails from local Python installs

2013-04-07 Thread austinmatherne
I've used pythonbrew, pythonz, and pyenv to install CPython 3.3.1, but all of 
them give me the same error when running "pip install PySide":

error: Failed to locate the Python library /home/.../lib/libpython3.3m.so

Is this a problem with PySide, or with the various local Python installers I've 
used?

If I use the system version of pip, PySide installs just fine.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie to python. Very newbie question

2013-04-07 Thread Steven D'Aprano
On Sun, 07 Apr 2013 04:16:27 -0700, ReviewBoard User wrote:

> Hi
> I am a newbie to python and am trying to write a program that does a sum
> of squares of numbers whose squares are odd. For example, for x from 1
> to 100, it generates 165 as an output (sum of 1,9,25,49,81)
> 
> Here is the code I have
> print reduce(lambda x, y: x+y, filter(lambda x: x%2, map(lambda x: x*x,
> xrange(10**6 = sum(x*x for x in xrange(1, 10**6, 2))
> 
> I am getting a syntax error.
> Can you let me know what the error is?

Python already has told you what the error is. You should read the error 
message. If you don't understand it, you should copy and paste the full 
traceback, starting with the line "Traceback", and ask for help. But 
please do not expect us to *guess* what error you are seeing.

I'm now going to guess. I think you are seeing this error:


py> len(x) = len(y)
  File "", line 1
SyntaxError: can't assign to function call


In this example, I have a function call, len(x), on the left hand side of 
an assignment. That is illegal syntax.

In your code, you also have a function call reduce(...) on the left hand 
side of an assignment. If the error message is not clear enough, can you 
suggest something that would be more understandable?

Perhaps you meant to use an equality test == instead of = assignment.


> I am new to Python and am also looking for good documentation on python
> functions. http://www.python.org/doc/ does not provide examples of usage
> of each function


No, the reference material does not generally provide examples. Some 
people like that style, and some don't.

However, many pages do have extensive examples:

http://docs.python.org/2/library/string.html


You should also work through a tutorial or two. Also the "Module of the 
week" website is very good:

http://pymotw.com



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


Re: Splitting of string at an interval

2013-04-07 Thread Chris Angelico
On Mon, Apr 8, 2013 at 7:48 AM, Steven D'Aprano
 wrote:
> Like every programming problem, the solution is to break it apart into
> small, simple steps that even a computer can follow.
> ...

5) Shortcut the whole thing, since the problem was underspecified, by
using a literal.

words = ["The Sun", "rises in", "in the", "east of", "our earth"]

*dive for cover against rotten tomatoes*

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


Re: im.py: a python communications tool

2013-04-07 Thread Chris Angelico
On Mon, Apr 8, 2013 at 8:36 AM, Steven D'Aprano
 wrote:
> On Sun, 07 Apr 2013 14:47:11 -0700, jhunter.dunefsky wrote:
>
>> Actually, my current licence can be found here:
>> https://github.com/jhunter-d/im.py/blob/master/LICENCE.  Whaddaya think
>> about this, Useneters?
>
>
> I think you're looking for a world of pain, when somebody uses your
> software, it breaks something, and they sue you. Your licence currently
> means that you are responsible for the performance of your software.
>
> Why don't you use a recognised, tested, legally-correct licence, like the
> MIT licence, instead of trying to be clever and/or lazy with a one-liner?
>
> E.g. http://opensource.org/licenses/MIT

Plus there's the whole brevity thing. If I see something that says
"MIT license", I don't need to read the details. Compare the README
for one of my projects:

https://github.com/Rosuav/Gypsum/blob/master/README

(Actually, I need to update that; there are a few solved problems
listed there as still open.) You read "Licensed under the BSD Open
Source license" and then you can stop reading - you know what your
rights are. The lawyers at Roy Smith's company would have no trouble
comprehending this, and no trouble deciding whether or not it's
allowed - they either do or do not (there is no try).

License proliferation is actually a major problem. If I were to lift
code from your program and incorporate it into something GPL3, am I
violating either's terms? What if I want to put that code into
something BSD 2-clause? Am I allowed? At least if you use a well-known
license, I can do a quick web search, coming up with something like
[1], but a custom or unusual license would require careful analysis of
terms.

[1] http://www.dwheeler.com/essays/floss-license-slide.html

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


with ignored

2013-04-07 Thread Barrett Lewis
I was recently watching that Raymond Hettinger video on creating Beautiful
Python from this years PyCon.
He mentioned pushing up the new idiom

with ignored():
 # do some work

I tracked down his commit here http://hg.python.org/cpython/rev/406b47c64480

But am unsure how the yield works in the given situation.

I know about creating generators with yield and have read the docs on how
it maintains state.

I think it works because it is returning control back to the caller
while maintaining the try so if the caller throws it is caught by the
context. Is this correct? I would love an in depth explanation of how this
is working. I am trying to learn as much as possible about the actual
python internals.

Thanks in advance!
-Barrett
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie to python. Very newbie question

2013-04-07 Thread Miki Tebeka
>   I can't even read that mess... three nested lambda?
I have to say this and other answers in this thread seem not that friendly to 
me.
The OP said it's a newbie question, we should be more welcoming to newcomers.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I hate you all

2013-04-07 Thread Roland Koebler
Hi,

> Well all previous (python 2) code is meant to work for a tab size of
> 8.
yes, but even in Python 2, mixing spaces and tabs is considered bad
style and should be avoided. And code-checkers like pylint (which I
can recommend to everyone) create a warning.

> You may call this "categorically wrong", but it has been there a
> long while, is is still in use, and it sticks to the default.
As I said, mixing tabs and spaces for indentation was *always* a bad
idea, and is discouraged also in Python 2.

> Spaces-only can achieve compatibility between different people
> settings for formatted text like source code. But so does a common
> default for the tab size,
But there's no such thing as "default tab size". Configuring the
tab-size is quite common among programmers.


But why do you insist on using tabs at all? The best way -- in my
opinion -- is to use the tab- and backspace-key for indentation, and
let the editor convert it to spaces. (And use some tool to convert
all tabs in the old code.)

I don't see *any* advantage of mixed spaces and tabs, but quite some
disadvantages/problems.

> What I would expect is some option in python to make tabs work the
> way they used to. I want a choice for me to preserve my settings,
> the same way you want to preserve yours.
>
> What I want should not be much to ask, since this is how python 2
> used to do things.
> 
> I admit such a '--fixed-tabs' option, that will make tab stops be 8
> columns apart, and allow any number of spaces like in python 2,
> makes the code I write dependent on that option.
There's no need to add this to Python 3, since you already have what
you want. Simply use:

expand yourscript.py | python3


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


Re: Error in Python NLTK

2013-04-07 Thread Steven D'Aprano
On Sun, 07 Apr 2013 15:11:36 -0700, subhabangalore wrote:

[snip 200+ lines of irrelevant quoted text]
> Dear Sir,
> I was trying to give wrong input. I was making an input error.

Please, use the delete key to remove unnecessary text from your messages. 
We shouldn't have to scroll past THREE AND A HALF PAGES of quoted text to 
see a two line response.


Thank you.


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


Re: im.py: a python communications tool

2013-04-07 Thread Steven D'Aprano
On Sun, 07 Apr 2013 14:47:11 -0700, jhunter.dunefsky wrote:

> Actually, my current licence can be found here:
> https://github.com/jhunter-d/im.py/blob/master/LICENCE.  Whaddaya think
> about this, Useneters?


I think you're looking for a world of pain, when somebody uses your 
software, it breaks something, and they sue you. Your licence currently 
means that you are responsible for the performance of your software.

Why don't you use a recognised, tested, legally-correct licence, like the 
MIT licence, instead of trying to be clever and/or lazy with a one-liner?

E.g. http://opensource.org/licenses/MIT


Software licencing is a solved problem. Do you really think that people 
write three or four paragraph licences because they *like* legal 
boilerplate? Did you imagine that you were the first person to think, "I 
know! I'll write a one-liner telling people they can do whatever they 
want with my software! Nothing can possibly go wrong!"?

Use a known, tested, working solution, and save yourself the pain.



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


Re: Error in Python NLTK

2013-04-07 Thread subhabangalore
On Monday, April 8, 2013 1:50:38 AM UTC+5:30, subhaba...@gmail.com wrote:
> On Sunday, April 7, 2013 2:14:41 AM UTC+5:30, Dave Angel wrote:
> 
> > On 04/06/2013 03:56 PM, subhabangal...@gmail.com wrote:
> 
> > 
> 
> > > Dear Group,
> 
> > 
> 
> > >
> 
> > 
> 
> > > I was using a package named NLTK in Python.
> 
> > 
> 
> > >
> 
> > 
> 
> > > I was trying to write a code given in section 3.8 of
> 
> > 
> 
> > >
> 
> > 
> 
> > > http://docs.huihoo.com/nltk/0.9.5/guides/tag.html.
> 
> > 
> 
> > >
> 
> > 
> 
> > > Here, in the >>> test = ['up', 'down', 'up'] if I put more than 3 values 
> > > and trying to write the reciprocal codes, like,
> 
> > 
> 
> > >
> 
> > 
> 
> > >  sequence = [(t, None) for t in test] and print '%.3f' % 
> > > (model.probability(sequence))
> 
> > 
> 
> > 
> 
> > 
> 
> > This 'and' operator is going to try to interpret the previous list as a 
> 
> > 
> 
> > boolean.  Could that be your problem?  Why aren't you putting these two 
> 
> > 
> 
> > statements on separate lines?  And what version of Python are you using? 
> 
> > 
> 
> >   If 2.x, you should get a syntax error because print is a statement. 
> 
> > 
> 
> > If 3.x, you should get a different error because you don't put parens 
> 
> > 
> 
> > around the preint expression.
> 
> > 
> 
> > 
> 
> > 
> 
> > >
> 
> > 
> 
> > > I am getting an error as,
> 
> > 
> 
> > >
> 
> > 
> 
> > > Traceback (most recent call last): File "", line 1, in 
> > > model.probability(sequence) File 
> > > "C:\Python27\lib\site-packages\nltk\tag\hmm.py", line 228, in probability 
> > > return 2**(self.log_probability(self._transform.transform(sequence))) 
> > > File "C:\Python27\lib\site-packages\nltk\tag\hmm.py", line 259, in 
> > > log_probability alpha = self._forward_probability(sequence) File 
> > > "C:\Python27\lib\site-packages\nltk\tag\hmm.py", line 694, in 
> > > _forward_probability alpha[0, i] = self._priors.logprob(state) + \ File 
> > > "C:\Python27\lib\site-packages\nltk\probability.py", line 689, in logprob 
> > > elif self._prob_dict[sample] == 0: return _NINF ValueError: The truth 
> > > value of an array with more than one element is ambiguous. Use a.any() or 
> > > a.all()
> 
> > 
> 
> > >
> 
> > 
> 
> > > If any learned member may kindly assist me how may I solve the issue.
> 
> > 
> 
> > >
> 
> > 
> 
> > 
> 
> > 
> 
> > Your error display has been trashed, thanks to googlegroups.
> 
> > 
> 
> >  http://wiki.python.org/moin/GoogleGroupsPython
> 
> > 
> 
> > Try posting with a text email message, since this is a text forum.
> 
> > 
> 
> > 
> 
> > 
> 
> > Your code is also sparse.  Why do you point us to fragments on the net, 
> 
> > 
> 
> > when you could show us the exact code you were running when it failed? 
> 
> > 
> 
> > I'm guessing you're running it from the interpreter, which can be very 
> 
> > 
> 
> > confusing once you have to ask for help.  Please put a sample of code 
> 
> > 
> 
> > into a file, run it, and paste into your text email both the contents of 
> 
> > 
> 
> > that file and the full traceback.  thanks.
> 
> > 
> 
> > 
> 
> > 
> 
> > The email address to post on this forum is  python-list@python.org
> 
> > 
> 
> > 
> 
> > 
> 
> > 
> 
> > 
> 
> > -- 
> 
> > 
> 
> > DaveA
> 
> 
> 
> Dear Sir, 
> 
> I generally solved this problem from some other angle but I would like to fix 
> this particular issue also so I am posting soon to you. 
> 
> Regards,
> 
> Subhabrata.

Dear Sir,
I was trying to give wrong input. I was making an input error.

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


Re: Splitting of string at an interval

2013-04-07 Thread Steven D'Aprano
On Sun, 07 Apr 2013 13:25:57 -0700, subhabangalore wrote:

> Dear Group,
> 
> I was looking to split a string in a particular interval, like,
> 
> If I have a string,
> string="The Sun rises in the east of  our earth"
> 
> I like to see it as,
> words=["The Sun","rises in","in the","east of","our earth"]
> 
> If any one of the learned members can kindly suggest.


Like every programming problem, the solution is to break it apart into 
small, simple steps that even a computer can follow.


1) Split the string into words at whitespace.

words = string.split()


2) Search for the word "in", and if found, duplicate it.

tmp = []
for word in words:
if word == 'in':
tmp.append('in')
tmp.append(word)

words = tmp


3) Take the words two at a time.

phrases = [words[i:i+2] for i in range(0, len(words), 2)]


4) Join the phrases into strings.

phrases = [' '.join(phrase) for phrase in phrases]



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


Re: im.py: a python communications tool

2013-04-07 Thread jhunter . dunefsky
On Sunday, April 7, 2013 4:59:10 AM UTC-4, 
garabik-ne...@kassiopeia.juls.savba.sk wrote:
> Andrew Berg  wrote:
> 
> > On 2013.04.05 20:07, Roy Smith wrote:
> 
> >> I know this is off-topic, but I encourage people to NOT invent their own 
> 
> >> licenses.
> 
> > Perhaps he meant this existing license: http://www.wtfpl.net/about/
> 
> 
> 
> I like the Python Powered Logo license by Just van Rossum (Guido's
> 
> brother, in case someone doesn't know..)
> 
> 
> 
> http://mail.python.org/pipermail/python-list/1999-December/013413.html
> 
> 
> 
> -- 
> 
>  ---
> 
> | Radovan Garabík http://kassiopeia.juls.savba.sk/~garabik/ |
> 
> | __..--^^^--..__garabik @ kassiopeia.juls.savba.sk |
> 
>  ---
> 
> Antivirus alert: file .signature infected by signature virus.
> 
> Hi! I'm a signature virus! Copy me into your signature file to help me spread!

Actually, my current licence can be found here: 
https://github.com/jhunter-d/im.py/blob/master/LICENCE.  Whaddaya think about 
this, Useneters?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: __doc__ string for getset members

2013-04-07 Thread Steven D'Aprano
On Sun, 07 Apr 2013 21:21:03 +0100, Arnaud Delobelle wrote:

> On 7 April 2013 19:02, Nick Gnedin  wrote:
[...]
>> My question is - how do I access the doc string "mem-doc-string"
>> supplied in the PyGetSetDef structure? If I type
>>
>> print(obj.mem.__doc__)
>>
>> then the __doc__ string for the result of a call to MemGet(...) is
>> printed, not the doc string supplied in the PyGetSetDef structure.
>>
>>
> That's not how Python works.  You won't be able to get the docstring of
> a descriptor this way.  You need to do it from the class.  The behaviour
> you observe is normal and cannot be overriden.


All very well and good, but how about putting Nick out of his misery and 
showing how to do it?


print(obj.__class__.mem.__doc__)


ought to work.



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


Re: __doc__ string for getset members

2013-04-07 Thread Arnaud Delobelle
On 7 April 2013 21:38, Nick Gnedin  wrote:
>
> Arnaud,
>
> Thanks for the answer. I understand that I cannot access the docstring as an
> attribute of a getter, but what did you mean when you said "You need to do
> it from the class"? I am still confused - is there a way to get that
> docstring or not?
>
> Nick
>

Please reply on-list

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


Re: Splitting of string at an interval

2013-04-07 Thread Dave Angel

On 04/07/2013 04:25 PM, subhabangal...@gmail.com wrote:

Dear Group,

I was looking to split a string in a particular interval, like,

If I have a string,
string="The Sun rises in the east of  our earth"


Are you asserting that there is nothing but letters and whitespace in 
the string, and that any amount of consecutive whitespace may be 
considered a blank?




I like to see it as,
words=["The Sun","rises in","in the","east of","our earth"]


Those aren't words, they're phrases.  But more importantly, you're 
somehow doubling the word "in" before parsing.




If any one of the learned members can kindly suggest.



split it into a list, use slices to divide that into even and odd 
numbered words.  Use zip to combine those two list together, and then 
combine the resultant tuples with a space between.



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


Splitting of string at an interval

2013-04-07 Thread subhabangalore
Dear Group,

I was looking to split a string in a particular interval, like,

If I have a string, 
string="The Sun rises in the east of  our earth"

I like to see it as, 
words=["The Sun","rises in","in the","east of","our earth"]

If any one of the learned members can kindly suggest.

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


Re: __doc__ string for getset members

2013-04-07 Thread Arnaud Delobelle
On 7 April 2013 19:02, Nick Gnedin  wrote:
>
> Folks,
>
> I am writing an extension where I follow the guide on the web
> (http://docs.python.org/3.3/extending/newtypes.html#generic-attribute-management).
> I have an object declared,
>
> struct Object
> {
> PyObject_HEAD
> };
>
> and a member set through tp_getset mechanism,
>
> PyGetSetDef ObjectGetSet[] =
> {
> {"mem", (getter)MemGet, (setter)MemSet, "mem-doc-string", NULL},
> {NULL}  /* Sentinel */
> };
>
> My question is - how do I access the doc string "mem-doc-string" supplied in
> the PyGetSetDef structure? If I type
>
> print(obj.mem.__doc__)
>
> then the __doc__ string for the result of a call to MemGet(...) is printed,
> not the doc string supplied in the PyGetSetDef structure.
>

That's not how Python works.  You won't be able to get the docstring
of a descriptor this way.  You need to do it from the class.  The
behaviour you observe is normal and cannot be overriden.

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


Re: Error in Python NLTK

2013-04-07 Thread subhabangalore
On Sunday, April 7, 2013 2:14:41 AM UTC+5:30, Dave Angel wrote:
> On 04/06/2013 03:56 PM, subhabangal...@gmail.com wrote:
> 
> > Dear Group,
> 
> >
> 
> > I was using a package named NLTK in Python.
> 
> >
> 
> > I was trying to write a code given in section 3.8 of
> 
> >
> 
> > http://docs.huihoo.com/nltk/0.9.5/guides/tag.html.
> 
> >
> 
> > Here, in the >>> test = ['up', 'down', 'up'] if I put more than 3 values 
> > and trying to write the reciprocal codes, like,
> 
> >
> 
> >  sequence = [(t, None) for t in test] and print '%.3f' % 
> > (model.probability(sequence))
> 
> 
> 
> This 'and' operator is going to try to interpret the previous list as a 
> 
> boolean.  Could that be your problem?  Why aren't you putting these two 
> 
> statements on separate lines?  And what version of Python are you using? 
> 
>   If 2.x, you should get a syntax error because print is a statement. 
> 
> If 3.x, you should get a different error because you don't put parens 
> 
> around the preint expression.
> 
> 
> 
> >
> 
> > I am getting an error as,
> 
> >
> 
> > Traceback (most recent call last): File "", line 1, in 
> > model.probability(sequence) File 
> > "C:\Python27\lib\site-packages\nltk\tag\hmm.py", line 228, in probability 
> > return 2**(self.log_probability(self._transform.transform(sequence))) File 
> > "C:\Python27\lib\site-packages\nltk\tag\hmm.py", line 259, in 
> > log_probability alpha = self._forward_probability(sequence) File 
> > "C:\Python27\lib\site-packages\nltk\tag\hmm.py", line 694, in 
> > _forward_probability alpha[0, i] = self._priors.logprob(state) + \ File 
> > "C:\Python27\lib\site-packages\nltk\probability.py", line 689, in logprob 
> > elif self._prob_dict[sample] == 0: return _NINF ValueError: The truth value 
> > of an array with more than one element is ambiguous. Use a.any() or a.all()
> 
> >
> 
> > If any learned member may kindly assist me how may I solve the issue.
> 
> >
> 
> 
> 
> Your error display has been trashed, thanks to googlegroups.
> 
>  http://wiki.python.org/moin/GoogleGroupsPython
> 
> Try posting with a text email message, since this is a text forum.
> 
> 
> 
> Your code is also sparse.  Why do you point us to fragments on the net, 
> 
> when you could show us the exact code you were running when it failed? 
> 
> I'm guessing you're running it from the interpreter, which can be very 
> 
> confusing once you have to ask for help.  Please put a sample of code 
> 
> into a file, run it, and paste into your text email both the contents of 
> 
> that file and the full traceback.  thanks.
> 
> 
> 
> The email address to post on this forum is  python-list@python.org
> 
> 
> 
> 
> 
> -- 
> 
> DaveA

Dear Sir, 
I generally solved this problem from some other angle but I would like to fix 
this particular issue also so I am posting soon to you. 
Regards,
Subhabrata.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie to python. Very newbie question

2013-04-07 Thread Arnaud Delobelle
On 7 April 2013 20:23, Ian Foote  wrote:
> I'm surprised no one has suggested:
>
 import math
 sum( x*x for x in range(1, int(math.sqrt(100)), 2))

Yeah! And I'm surprised no one came up with:

>>> from itertools import count, takewhile
>>> sum(takewhile((100).__gt__, filter((2).__rmod__, map((2).__rpow__, 
>>> count(1)
165

:)

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


Re: can anyone help me in developing a simple webpage in jinja2

2013-04-07 Thread Cousin Stanley
Satabdi Mukherjee wrote:

> i am a rookie in python and i am trying 
> to develop a simple webpage using jinja2. 
>
> can anyone please help me how to do that  

  You might try using your jinja template
  with named tuples 

# ---

from jinja2 import Template

from collections import namedtuple as NT

nt = NT( 'Navigation' , 'href  caption' )

n1 = nt( 'http://python.org' , 'python' )
n2 = nt( 'http://cython.org' , 'cython' )
n3 = nt( 'http://jython.org' , 'jython' )
n4 = nt( 'http://pypy.org/'  , 'pypy' )

nav = ( n1 , n2 , n3 , n4 )

tmpl = Template( '''\



My Webpage



{% for url , caption  in navigation %}
{{ caption }}
{% endfor %}


My Webpage
{{ a_variable }}


''' )
 
print tmpl.render(
variable   = 'Navigation' ,  navigation = nav )


-- 
Stanley C. Kitching
Human Being
Phoenix, Arizona

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


Re: Newbie to python. Very newbie question

2013-04-07 Thread Ian Foote

On 07/04/13 20:09, Dennis Lee Bieber wrote:

On Sun, 7 Apr 2013 04:16:27 -0700 (PDT), ReviewBoard User
 declaimed the following in
gmane.comp.python.general:


Hi
I am a newbie to python and am trying to write a program that does a
sum of squares of numbers whose squares are odd.
For example, for x from 1 to 100, it generates 165 as an output (sum
of 1,9,25,49,81)

Here is the code I have
print reduce(lambda x, y: x+y, filter(lambda x: x%2, map(lambda x:
x*x, xrange
(10**6 = sum(x*x for x in xrange(1, 10**6, 2))

I am getting a syntax error.
Can you let me know what the error is?


I can't even read that mess... three nested lambda?

Not the most efficient version but...


sum( x*x for x in range(100/2) if (x*x % 2) and (x*x < 100) )

165




The range(100/2) is a simple reduction to avoid invoking a sqrt
function... the more economical is


import math
sum( x*x for x in range(int(math.sqrt(100))) if x*x % 2)

165




I'm surprised no one has suggested:

>>> import math
>>> sum( x*x for x in range(1, int(math.sqrt(100)), 2))

Regards,
Ian F

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


Re: IDE for GUI Designer

2013-04-07 Thread Fabio Zadrozny
Well, I usually use the Qt Designer and it does work well for me.

It generates a .ui file with it which has to be passed to pyuic to generate
the actual Python code -- and you have to generate a subclass to implement
the slots -- for that, I add an external builder to Eclipse, so, in the end
it's mostly a matter of saving the ui in designer and going on to implement
the actual code for the actions in PyDev/Eclipse (sure, you don't click on
a link to add Python code, but for me that separation is good).

Cheers,

Fabio


On Sun, Apr 7, 2013 at 2:40 PM, Wolfgang Keller  wrote:

> > Guys, is this, I wonder if there is an IDE with native support for the
> > development of GUI's
>
> A decent Python IDE would probably integrate well enough with any decent
> GUI builder. If there was one (decent GUI builder).
>
> Unfortunately there's afaik currently no GUI builder available for any
> of the Python GUI frameworks that actually makes use of the dynamic
> interpreted nature of Python (in a way comparable to Cocoa's Interface
> Builder or the Visualworks Smalltalk IDE). They are unfortunately all
> just conceived following the clumsy tedious static C++-ish
> code-generation method. X-(
>
> Sincerely,
>
> Wolfgang
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I hate you all

2013-04-07 Thread Roy Smith
In article ,
 Ethan Furman  wrote:

> On 04/07/2013 04:44 AM, Timothy Madden wrote:
> >
> > I am ok with the people that like python the way it is.
> 
> Really?  'Cause I totally missed that from the subject line...
> 
> --
> ~Ethan~

Take this logically...

1) Ethan hates all clp readers

2) Ethan does not hate people who "like python the way it is"

I therefore deduce that Ethan believes there are no clp readers who 
"like python the way it is".  This may be a mistaken belief, but at 
least there's no logical contradiction.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: I hate you all

2013-04-07 Thread Mark Lawrence

On 05/04/2013 22:41, terminato...@gmail.com wrote:

snipped as loads of comments already made.


Timothy Madden



The BDFL's view from many moons ago 
www.python.org/doc/essays/ppt/regrets/PythonRegrets.ppt slide 3.


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


Re: I hate you all

2013-04-07 Thread Ethan Furman

On 04/07/2013 04:44 AM, Timothy Madden wrote:


I am ok with the people that like python the way it is.


Really?  'Cause I totally missed that from the subject line...

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


__doc__ string for getset members

2013-04-07 Thread Nick Gnedin


Folks,

I am writing an extension where I follow the guide on the web 
(http://docs.python.org/3.3/extending/newtypes.html#generic-attribute-management). 
I have an object declared,


struct Object
{
PyObject_HEAD
};

and a member set through tp_getset mechanism,

PyGetSetDef ObjectGetSet[] =
{
{"mem", (getter)MemGet, (setter)MemSet, "mem-doc-string", NULL},
{NULL}  /* Sentinel */
};

My question is - how do I access the doc string "mem-doc-string" 
supplied in the PyGetSetDef structure? If I type


print(obj.mem.__doc__)

then the __doc__ string for the result of a call to MemGet(...) is 
printed, not the doc string supplied in the PyGetSetDef structure.


Many thanks for the advice,

Nick Gnedin

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


Re: IDE for GUI Designer

2013-04-07 Thread Wolfgang Keller
> Guys, is this, I wonder if there is an IDE with native support for the
> development of GUI's

A decent Python IDE would probably integrate well enough with any decent
GUI builder. If there was one (decent GUI builder).

Unfortunately there's afaik currently no GUI builder available for any
of the Python GUI frameworks that actually makes use of the dynamic
interpreted nature of Python (in a way comparable to Cocoa's Interface
Builder or the Visualworks Smalltalk IDE). They are unfortunately all
just conceived following the clumsy tedious static C++-ish
code-generation method. X-(

Sincerely,

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


Re: Newbie to python. Very newbie question

2013-04-07 Thread rusi
On Apr 7, 4:16 pm, ReviewBoard User 
wrote:
> Hi
> I am a newbie to python and am trying to write a program that does a
> sum of squares of numbers whose squares are odd.
> For example, for x from 1 to 100, it generates 165 as an output (sum
> of 1,9,25,49,81)
>
> Here is the code I have
> print reduce(lambda x, y: x+y, filter(lambda x: x%2, map(lambda x:
> x*x, xrange
> (10**6 = sum(x*x for x in xrange(1, 10**6, 2))
>
> I am getting a syntax error.
> Can you let me know what the error is?
>
> I am new to Python and am also looking for good documentation on
> python functions.http://www.python.org/doc/does not provide examples
> of usage of each function

In problems like this it is usually preferable to use list
comprehensions over map/filter.
Your problem is literally solvable like this:

>>> [sq for sq in [x*x for x in range(100)] if sq%2 == 1 and sq <= 100]
[1, 9, 25, 49, 81]
>>> sum([sq for sq in [x*x for x in range(100)] if sq%2 == 1 and sq <= 100])
165

Using Dave's observation that odd(x) == odd(x*x) it simplifies to
>>> sum([x*x for x in range(100) if x%2==1 and x*x <=100])
165

Note: Python comprehensions unlike Haskell does not allow local lets
so the x*x has to be repeated
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Newbie to python. Very newbie question

2013-04-07 Thread Miki Tebeka
> I am a newbie to python
Welcome! I hope you'll do great things with Python.

> and am trying to write a program that does a
> sum of squares of numbers whose squares are odd.
OK.

> For example, for x from 1 to 100, it generates 165 as an output (sum
> of 1,9,25,49,81)
I don't follow, you seem to be missing a lot of numbers. For example 3^2 = 9 
which is odd as well.

> Here is the code I have
> print reduce(lambda x, y: x+y, filter(lambda x: x%2, map(lambda x:
> x*x, xrange
> (10**6 = sum(x*x for x in xrange(1, 10**6, 2))

print X = Y is a syntax error. Why do you need the 2'nd part.
In general, we're moving to list/generator comperhension over map/filter.
Something like:
print(sum(x*x for x in xrange(10**6) if (x*x)%2))

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


Re: new.instancemethod - how to port to Python3

2013-04-07 Thread Helmut Jarausch
On Sun, 07 Apr 2013 11:07:07 +, Steven D'Aprano wrote:

> On Sun, 07 Apr 2013 10:54:46 +, Helmut Jarausch wrote:
> 
>> class  Foo :
>> 
>> def to_binary(self, *varargs, **keys):
>>
>>code= ...
>>args= ...
>># Add function header
>>code = 'def to_binary(self, %s):\n' % ', '.join(args) + code
>>exec(code)
>>self.to_binary = new.instancemethod(to_binary, self,
>>self.__class__)
>>return self.to_binary(*varargs, **keys)
> 
> 
> Self-modifying code! Yuck!
> 
> Nevertheless, try changing the line with new.instancemethod to this:
> 
> self.to_binary = types.MethodType(to_binary, self)
> 
> 
> and see if it works. If it complains about the call to exec, then change 
> that part of the code to this:

Thanks, that worked
> 
> ns = {}
> exec(code, ns)
I just had to replace this with
  exec(code,globals(),ns)

> to_binary = ns['to_binary']
> self.to_binary = types.MethodType(to_binary, self)

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


Re: new.instancemethod - how to port to Python3

2013-04-07 Thread Helmut Jarausch
On Sun, 07 Apr 2013 10:52:11 +, Steven D'Aprano wrote:

> On Sun, 07 Apr 2013 09:50:35 +, Helmut Jarausch wrote:
> 
>> Hi,
>> 
>> I'm trying to port a class to Python3.3 which contains
>> 
>> class  Foo :
>> 
>> def to_binary(self, *varargs, **keys):
>>
>> 
>> self.to_binary = new.instancemethod(to_binary, self, self.__class__)
>> # Finally call it manually
>> return apply(self.to_binary, varargs, keys)
> 
> 
> I do not understand this code. Can you give a short example that actually 
> works please?
> 
> As written, your code has a class that defines a to_binary method. Then, 
> *outside* of the method, in the class definition, you refer to "self", 
> and use a return statement. This is not possible -- self does not exist, 
> and return gives a SyntaxError.
> 
> But, if the indentation is wrong, it looks like you are trying to get the 
> to_binary method to replace itself with a global to_binary function. I do 
> not understand this.

Sorry, the first excerpt was to too short.
As noted in the reply to Arnaud, a better excerpt is:

class  Foo :

def to_binary(self, *varargs, **keys):
   
   code= ...
   args= ...
   # Add function header
   code = 'def to_binary(self, %s):\n' % ', '.join(args) + code
   exec(code)
   self.to_binary = new.instancemethod(to_binary, self, self.__class__)
   return self.to_binary(*varargs, **keys)

If you'd like to see the full code (not by me)
please see the Python package http://python-xlib.sourceforge.net/
file Xlib/protocol/rq.py   method to_binary in class Struct
> 
> I cannot answer your question, because I don't understand it. But perhaps 
> this will help:
> 
> 
> # === Python 2 version ===
> class Spam:
> pass
> 
> x = Spam()
> 
> def method(self, arg):
> return {arg: self}
> 
> import new
> x.method = new.instancemethod(method, x, x.__class__)
> 
> x.method("hello")
> => returns {'hello': <__main__.Spam instance at 0xa18bb4c>}
> 
> 
> Here is the Python 3 version:
> 
> 
> # === Python 3 ===
> class Spam:
> pass
> 
> x = Spam()
> 
> def method(self, arg):
> return {arg: self}
> 
> import types
> x.method = types.MethodType(method, x)
> 
> x.method("hello")
> => returns {'hello': <__main__.Spam object at 0xb7bc59ac>}
> 
> 
> 
> Does this help?

Yes, 

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


Re: Performance of int/long in Python 3

2013-04-07 Thread Mark Lawrence

On 06/04/2013 22:24, Chris Angelico wrote:

On Sat, Apr 6, 2013 at 8:09 PM, Serhiy Storchaka  wrote:

04.04.13 00:57, Chris Angelico написав(ла):

http://bugs.python.org/issue17629 opened.



See also the discussion at
http://comments.gmane.org/gmane.comp.python.ideas/15640 . I agree with
rejection. This is an implementation detail and different Python
implementations (including future CPython versions) can have different
internal string implementations.


I really don't see why this means that there can't be a function in
sys, or something. I mean, other Pythons aren't expected to return the
exact same values from sys.getsizeof, are they? But clearly the weight
of opinion is against me, so fine, I don't care that much.

ChrisA



There is nothing to stop anybody providing a patch to give this 
functionality.  The downside is long term someone has to maintain it.  I 
strongly prefer having python devs spending their time looking after
the 3905 open issues of which 1729 have patches, see 
http://comments.gmane.org/gmane.comp.python.devel/138310


--
If you're using GoogleCrap™ please read this 
http://wiki.python.org/moin/GoogleGroupsPython.


Mark Lawrence

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


Re: [OT?]gmane not updating

2013-04-07 Thread Chris “Kwpolska” Warrick
On Sat, Apr 6, 2013 at 9:01 PM, Neal Becker  wrote:
> breamore...@yahoo.co.uk wrote:
>
>> The gmane site is online but none of the Python lists I subscribe to have 
>> been
>> updated for over 24 hours.  I fired off an email yesterday evening to larsi +
>> gmane at gnus dot org but I've no idea whether there's anybody to read it, or
>> even if it's actually been delivered :(  Is there anybody lurking who could
>> stir the embers to get things rolling?
>>
>> TIA.
>>
>> Mark Lawrence
>
> Working again.  Funny how you come to rely on these things.  There is no
> alternative to gmane.
>
> --
> http://mail.python.org/mailman/listinfo/python-list

There is: http://mail.python.org/mailman/listinfo/python-list — it’s
the official (as in PSF) mirror of comp.lang.python.  Much more fun
than gmane or usenet.

--
Kwpolska  | GPG KEY: 5EAAEA16
stop html mail| always bottom-post
http://asciiribbon.org| http://caliburn.nl/topposting.html
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help: pickle module unable to load "rb" mode files in linux

2013-04-07 Thread 88888 Dihedral
Surya Kasturi於 2013年4月2日星期二UTC+8下午10時54分25秒寫道:
> Hi, hope you can help me on it..
> 
> 
> 
> with open(pickle_f, 'r') as fhand:
>         obj = pickle.load(fhand)
> 
> 
> 
> 
> This works on linux but not in windows until  I use "rb" mode while creating 
> file object. Surprisingly, the "rb" mode is not working on Linux.. raising 
> EOFError.
> 
Just use a decorator with a pass in parameter about the OS
to wrap the two versions in different platforms.

By the way any function can be saved in a variable  to 
be passed around means that the lambda 1-liner is not 
necessarily required in Python.

In C++,  the sub-classing with virtual membership function 
reload mechanism is the equivalent part.


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


Re: Help: pickle module unable to load "rb" mode files in linux

2013-04-07 Thread Peter Otten
Surya Kasturi wrote:

> I am attaching the file which has to be read.. please take a look into it.
> The actual source code can be observed at
> 
https://github.com/scipy/SciPyCentral/blob/master/scipy_central/rest_comments/views.py#L235
> 
> 
> when we use "rb" mode in windows, its working. but its not working in
> linux system (particularly CentOS)
> 
> 
> 
> On Tue, Apr 2, 2013 at 8:50 PM, Peter Otten <__pete...@web.de> wrote:
> 
>> Surya Kasturi wrote:
>>
>> > Hi, hope you can help me on it..
>> >
>> > with open(pickle_f, 'r') as fhand:
>> > obj = pickle.load(fhand)
>> >
>> >
>> > This works on linux but not in windows until  I use "rb" mode while
>> > creating file object. Surprisingly, the "rb" mode is not working on
>> > Linux.. raising EOFError.
>> >
>> > Why is this happening?
>>
>> I don't know.
>>
>> Please give a complete self-contained example that uses "wb" to write the
>> file and "rb" to read it, and that fails on Linux. Don't forget to tell
>> us the version of Python you used to run that script.

I am using Linux, but I cannot reproduce an EOFError with the attached file:

Python 2.7.2+ (default, Jul 20 2012, 22:15:08) 
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open("index.fpickle", "rb") as f:
... obj = pickle.load(f)
... 
>>> obj
{'body': u'yahoo\n', 'prev': None, 'display_toc': False, 'title': 
u'', 'sourcename': 'index.txt', 'customsidebar': None, 
'current_page_name': 'index', 'next': None, 'rellinks': [('genindex', 
u'General Index', 'I', u'index')], 'meta': {}, 'parents': [], 'toc': u'\n\n', 'sidebars': None, 'metatags': ''}

As the data has only built-in types it cannot be a library thing either.

Given that the file's location is determined dynamically

[views.py]
call_sphinx_to_compile(settings.SPC['comment_compile_dir'])

pickle_f = ''.join([settings.SPC['comment_compile_dir'], os.sep,
'_build', os.sep, 'pickle', os.sep, 
'index.fpickle'])
with open(pickle_f, 'rb') as fhand:
obj = pickle.load(fhand)

I'd add a

print pickle_f

statement just before the with-statement to ensure that you don't have two 
different pickle files, one of them being empty or otherwise broken.

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


Re: Newbie to python. Very newbie question

2013-04-07 Thread Dave Angel

On 04/07/2013 07:16 AM, ReviewBoard User wrote:

Hi
I am a newbie to python


Then why are you trying to do 7 or 8 things on one line?


and am trying to write a program that does a
sum of squares of numbers whose squares are odd.
For example, for x from 1 to 100, it generates 165 as an output (sum
of 1,9,25,49,81)



No it doesn't.  A small piece of it does, and I'd recommend making that 
piece a separate line or three, probably making a function out of it.


Then if you want to write other code to exercise that function, go right 
ahead.


If you're new to Python, concentrate on the algorithm needed, and keep 
the program straightforward.  After you've got something simple working, 
and you're comfortable with the algorithm, then you can play code-golf 
to your heart's content.


Perhaps you hadn't realized that any odd number when squared will yield 
an odd number, and likewise for even.  So the stated problem is much 
simpler than what you're trying to do.


3 lambda's in one line of code?  Silly.



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


Re: I hate you all

2013-04-07 Thread Timothy Madden

On 07.04.2013 06:00, Dylan Evans wrote:

Then you see my point, unless you are being told what to use by a boss
then there are plenty of other languages you can choose from. Python is
rigid about it's format, that's just what it is and a lot of people like
it but if it's not your thing then some other language will probably
suit you better. However, if you are working for a company, or OSS
project, you are probably going to have your style dictated whatever
language you use [...]


I am ok with the people that like python the way it is.

But an option from python authors to make tabs work the way they used to 
would have been nice.


Just my opinion, I do see other people here think otherwise...


Timothy Madden

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


Re: I hate you all

2013-04-07 Thread Timothy Madden

On 06.04.2013 23:17, Larry Hudson wrote:
[...]

What you want and what you think are irrelevant.  The Python language
(whatever version) is already defined.  If you want to use it, you have
to accept it and adapt to what it is.  Live with it and move on.
Complaining about it is a complete waste of time -- it's NOT going to
change just because YOU don't like it.


Adding an option for fixed size tabs will not change the language
(and someone even suggested I patch my own copy, but this discussion is 
not about me, is about tabs).



I guess a discussion like this thread is the price to be paid for
relying solely on white space
to delimit code blocks, like the python syntax does.


And in actual practice, that has been shown to be a Good Thing.


Yes, I agree, it is. It just could have been better.

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


Re: Newbie to python. Very newbie question

2013-04-07 Thread Kruno Saho
On Sunday, April 7, 2013 9:16:27 PM UTC+10, ReviewBoard User wrote:
> Hi
> 
> I am a newbie to python and am trying to write a program that does a
> 
> sum of squares of numbers whose squares are odd.
> 
> For example, for x from 1 to 100, it generates 165 as an output (sum
> 
> of 1,9,25,49,81)
> 
> 
> 
> Here is the code I have
> 
> print reduce(lambda x, y: x+y, filter(lambda x: x%2, map(lambda x:
> 
> x*x, xrange
> 
> (10**6 = sum(x*x for x in xrange(1, 10**6, 2))
> 
> 
> 
> I am getting a syntax error.
> 
> Can you let me know what the error is?
> 
> 
> 
> I am new to Python and am also looking for good documentation on
> 
> python functions. http://www.python.org/doc/ does not provide examples
> 
> of usage of each function

Are you sure you do not mean '==' instead of '='?
-- 
http://mail.python.org/mailman/listinfo/python-list


Newbie to python. Very newbie question

2013-04-07 Thread ReviewBoard User
Hi
I am a newbie to python and am trying to write a program that does a
sum of squares of numbers whose squares are odd.
For example, for x from 1 to 100, it generates 165 as an output (sum
of 1,9,25,49,81)

Here is the code I have
print reduce(lambda x, y: x+y, filter(lambda x: x%2, map(lambda x:
x*x, xrange
(10**6 = sum(x*x for x in xrange(1, 10**6, 2))

I am getting a syntax error.
Can you let me know what the error is?

I am new to Python and am also looking for good documentation on
python functions. http://www.python.org/doc/ does not provide examples
of usage of each function
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new.instancemethod - how to port to Python3

2013-04-07 Thread Steven D'Aprano
On Sun, 07 Apr 2013 10:54:46 +, Helmut Jarausch wrote:

> class  Foo :
> 
> def to_binary(self, *varargs, **keys):
>
>code= ...
>args= ...
># Add function header
>code = 'def to_binary(self, %s):\n' % ', '.join(args) + code
>exec(code)
>self.to_binary = new.instancemethod(to_binary, self,
>self.__class__)
>return self.to_binary(*varargs, **keys)


Self-modifying code! Yuck!

Nevertheless, try changing the line with new.instancemethod to this:

self.to_binary = types.MethodType(to_binary, self)


and see if it works. If it complains about the call to exec, then change 
that part of the code to this:

ns = {}
exec(code, ns)
to_binary = ns['to_binary']
self.to_binary = types.MethodType(to_binary, self)


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


Re: new.instancemethod - how to port to Python3

2013-04-07 Thread Helmut Jarausch
On Sun, 07 Apr 2013 11:41:46 +0100, Arnaud Delobelle wrote:

> On 7 April 2013 10:50, Helmut Jarausch  wrote:
>> Hi,
>>
>> I'm trying to port a class to Python3.3 which contains
>>
>> class  Foo :
>> 
>> def to_binary(self, *varargs, **keys):
>>
>>
>> 
>> self.to_binary = new.instancemethod(to_binary, self,
>> self.__class__)
> 
> `self` isn't bound in this lexical scope (the class scope).  Or is your
> indentation incorrect?  However, if this statement was within the
> `to_binary` method, then `to_binary` wouldn't be bound so I can't make a
> reasonable guess.
> 
>> # Finally call it manually return apply(self.to_binary, varargs,
>> keys)
>>
> [...]

Sorry, the excerpt wasn't complete (it's not my code):
Here a more complete excerpt:

class  Foo :

def to_binary(self, *varargs, **keys):
   
   code= ...
   args= ...
   # Add function header
   code = 'def to_binary(self, %s):\n' % ', '.join(args) + code
   exec(code)
   self.to_binary = new.instancemethod(to_binary, self, self.__class__)
   return self.to_binary(*varargs, **keys)
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: new.instancemethod - how to port to Python3

2013-04-07 Thread Steven D'Aprano
On Sun, 07 Apr 2013 09:50:35 +, Helmut Jarausch wrote:

> Hi,
> 
> I'm trying to port a class to Python3.3 which contains
> 
> class  Foo :
> 
> def to_binary(self, *varargs, **keys):
>
> 
> self.to_binary = new.instancemethod(to_binary, self, self.__class__)
> # Finally call it manually
> return apply(self.to_binary, varargs, keys)


I do not understand this code. Can you give a short example that actually 
works please?

As written, your code has a class that defines a to_binary method. Then, 
*outside* of the method, in the class definition, you refer to "self", 
and use a return statement. This is not possible -- self does not exist, 
and return gives a SyntaxError.

But, if the indentation is wrong, it looks like you are trying to get the 
to_binary method to replace itself with a global to_binary function. I do 
not understand this.


> 
> 
> The last line has been transformed to
> return self.to_binary(*varargs, **keys)
> 
> by  2to3
> 
> But how to transform the line with new.instancemethod. I've seen
> examples where
> new.instancemethod(to_binary, )
> is replaced by  to_binay
> but this doesn't work here since to_binary isn't known.

I cannot answer your question, because I don't understand it. But perhaps 
this will help:


# === Python 2 version ===
class Spam:
pass

x = Spam()

def method(self, arg):
return {arg: self}

import new
x.method = new.instancemethod(method, x, x.__class__)

x.method("hello")
=> returns {'hello': <__main__.Spam instance at 0xa18bb4c>}


Here is the Python 3 version:


# === Python 3 ===
class Spam:
pass

x = Spam()

def method(self, arg):
return {arg: self}

import types
x.method = types.MethodType(method, x)

x.method("hello")
=> returns {'hello': <__main__.Spam object at 0xb7bc59ac>}



Does this help?




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


Re: new.instancemethod - how to port to Python3

2013-04-07 Thread Arnaud Delobelle
On 7 April 2013 10:50, Helmut Jarausch  wrote:
> Hi,
>
> I'm trying to port a class to Python3.3 which contains
>
> class  Foo :
> 
> def to_binary(self, *varargs, **keys):
>
>
> 
> self.to_binary = new.instancemethod(to_binary, self, self.__class__)

`self` isn't bound in this lexical scope (the class scope).  Or is
your indentation incorrect?  However, if this statement was within the
`to_binary` method, then `to_binary` wouldn't be bound so I can't make
a reasonable guess.

> # Finally call it manually
> return apply(self.to_binary, varargs, keys)
>
[...]

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


new.instancemethod - how to port to Python3

2013-04-07 Thread Helmut Jarausch
Hi,

I'm trying to port a class to Python3.3 which contains

class  Foo :

def to_binary(self, *varargs, **keys):
   


self.to_binary = new.instancemethod(to_binary, self, self.__class__) 

# Finally call it manually
return apply(self.to_binary, varargs, keys)



The last line has been transformed to 
return self.to_binary(*varargs, **keys)

by  2to3

But how to transform the line with new.instancemethod.
I've seen examples where
new.instancemethod(to_binary, )
is replaced by  to_binay
but this doesn't work here since to_binary isn't known.

If I simply delete it, I get an infinite recursion.

So, what's a working transcript of this code?

Many thanks for a hint,
Helmut.

P.S.  Is there collection of examples of necessary transformations to
Python3 which are not managed by 2to3 ?
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Help: pickle module unable to load "rb" mode files in linux

2013-04-07 Thread Surya Kasturi
I am attaching the file which has to be read.. please take a look into it.
The actual source code can be observed at
https://github.com/scipy/SciPyCentral/blob/master/scipy_central/rest_comments/views.py#L235


when we use "rb" mode in windows, its working. but its not working in linux
system (particularly CentOS)



On Tue, Apr 2, 2013 at 8:50 PM, Peter Otten <__pete...@web.de> wrote:

> Surya Kasturi wrote:
>
> > Hi, hope you can help me on it..
> >
> > with open(pickle_f, 'r') as fhand:
> > obj = pickle.load(fhand)
> >
> >
> > This works on linux but not in windows until  I use "rb" mode while
> > creating file object. Surprisingly, the "rb" mode is not working on
> > Linux.. raising EOFError.
> >
> > Why is this happening?
>
> I don't know.
>
> Please give a complete self-contained example that uses "wb" to write the
> file and "rb" to read it, and that fails on Linux. Don't forget to tell us
> the version of Python you used to run that script.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


index.fpickle
Description: Binary data
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: im.py: a python communications tool

2013-04-07 Thread garabik-news-2005-05
Andrew Berg  wrote:
> On 2013.04.05 20:07, Roy Smith wrote:
>> I know this is off-topic, but I encourage people to NOT invent their own 
>> licenses.
> Perhaps he meant this existing license: http://www.wtfpl.net/about/

I like the Python Powered Logo license by Just van Rossum (Guido's
brother, in case someone doesn't know..)

http://mail.python.org/pipermail/python-list/1999-December/013413.html

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


Re: parse the file

2013-04-07 Thread Dylan Evans
You can read the fantastic manual at
http://docs.python.org/2/library/xml.etree.elementtree.html or i'm sure
someone will do it for a modest fee.


On Sat, Apr 6, 2013 at 3:11 PM, 水静流深 <1248283...@qq.com> wrote:

> I have an xml file . http://s.yunio.com/bmCS5h
>
> It is the list of my files in Google-blogger, how can I parse it in python
> to get every article?please give me the right code,which can get exact
> result.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>


-- 
"The UNIX system has a command, nice ... in order to be nice to the other
users. Nobody ever uses it." - Andrew S. Tanenbaum
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Performance of int/long in Python 3

2013-04-07 Thread Steven D'Aprano
On Sat, 06 Apr 2013 19:58:02 -0600, Ian Kelly wrote:

> On Sat, Apr 6, 2013 at 7:29 PM, Steven D'Aprano
>  wrote:
>> For some definition of "easily".
>>
>> if implementation == "CPython":
>> if version < "3.3":
>> if sys.maxunicode exists:
>> use it to decide whether this is a wide or narrow build if
>> a wide build: return 4
>> else: return 2
>> else:
>> ???
>> elif version == "3.3":
>> scan the string, in some efficient or inefficient way return 1,
>> 2, 4 depending on the largest character you find
>> else:
>> ???
>> else:
>> ???
> 
> None of which goes away if a char width function is added to 3.4 and you
> still want to support earlier versions as this does.  It just adds
> another "if".

I grant you that for supporting earlier versions. But it will help with 
*future* versions. In principle, by Python 3.9, there could be six 
different checks just in the CPython section, to say nothing of PyPy, 
Jython, IronPython, and any other implementation.

An officially supported way of querying the kind of strings used will 
future-proof Python. In this regard, it's no different from (say) 
sys.float_info.



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


Re: Performance of int/long in Python 3

2013-04-07 Thread Serhiy Storchaka

On 07.04.13 00:24, Chris Angelico wrote:

On Sat, Apr 6, 2013 at 8:09 PM, Serhiy Storchaka  wrote:

See also the discussion at
http://comments.gmane.org/gmane.comp.python.ideas/15640 . I agree with
rejection. This is an implementation detail and different Python
implementations (including future CPython versions) can have different
internal string implementations.


I really don't see why this means that there can't be a function in
sys, or something. I mean, other Pythons aren't expected to return the
exact same values from sys.getsizeof, are they? But clearly the weight
of opinion is against me, so fine, I don't care that much.


The most strong argument for adding this feature in stdlib is that it 
has O(1) complexity against of O(N) complexity of any manual 
implementation. But this argument is not valid for other implementations.


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


Re: Library to work with SSH public keys

2013-04-07 Thread Darren Spruell
On Sat, Apr 6, 2013 at 5:49 AM, Roy Smith  wrote:
> In article ,
>  Darren Spruell  wrote:
>
>> I'd like to work with user submitted/uploaded SSH public keys from
>> Python. I'm trying to solve what I'd thought might be a simple need:
>> given a user's OpenSSH formatted _public_ key (RSA, or DSA, or
>> whatever), how do you obtain information about it such as: key type
>> (e.g. ssh-rsa, etc.); bit length (e.g. 2048); key comment (e.g.
>> user@hostname); key fingerprint? I've been fiddling with the Paramiko
>> API and looked at PyCrypto (supports OpenSSH keys) and Twisted Conch
>> but didn't see anything that looked like it did this.
>>
>> I'm looking for the equivalent to this:
>>
>> $ ssh-keygen -l -f tmp.key.pub
>> 2048 9b:31:06:6a:a4:79:97:33:d7:20:15:1f:cd:b4:86:4d dspruell@Sydney.local
>> (RSA)
>>
>> ...to get the attributes of the public key: key type, bit length,
>> fingerprint and comment.
>>
>> Is there an SSH library capable of doing this from Python? Can break
>> out to shell commands to parse them but I'd prefer not to.
>
> The first hit on googling "paramiko fingerprint" got me this:
>
> http://www.lag.net/paramiko/docs/paramiko.PKey-class.html

Indeed, and I seem to find it's not suited for the need. Many of the
methods appear to assume deriving information about public key parts
from private key input or for handling public keys sent by server when
connecting from client. I can't manage to wrangle desired or accurate
data out of passing in OpenSSH format public keys from a user keypair
(authentication key, not host key).

-- 
Darren Spruell
phatbuck...@gmail.com
-- 
http://mail.python.org/mailman/listinfo/python-list


parse the file

2013-04-07 Thread ????????
I have an xml file. http://s.yunio.com/bmCS5h  
It is the list of my files in Google-blogger, how can I parse it in python to 
get every article?please give me the right code,which can get exact result.-- 
http://mail.python.org/mailman/listinfo/python-list