Re: Invoking return through a function?

2017-10-30 Thread Steve D'Aprano
On Tue, 31 Oct 2017 02:26 pm, Rustom Mody wrote:

> My own feeling about lisp-macros is conflicted:
> - They are likely the most unique feature of lisp, putting it at the top of
> the blub-language tower
> - They are the single reason Lisp can never succeed like mainstream
> languages: Any significant Lisp sub-ecosystem will inevitably develop a
> macro set which succinctly and precisely expresses its needs but is arcane
> and incomprehensible to someone from another sub-ecosystem.

Well said. That's one of the disadvantages of Forth as well: since Forth
allows you to define your own control-structures, even the structure of the
code can be unfamiliar.

Another way to put it might be that any sufficiently complex Lisp program
doesn't look like Lisp any more.

Except perhaps for the myriad parentheses *wink* 



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Invoking return through a function?

2017-10-30 Thread Steve D'Aprano
On Tue, 31 Oct 2017 02:34 pm, Chris Angelico wrote:

> On Tue, Oct 31, 2017 at 2:00 PM, Steve D'Aprano
>  wrote:
>> Python has no GOTO, fortunately, but C has at least two, GOTO and LONGJMP.
>> A C macro could, if I understand correctly, jump into the middle of another
>> function. (Yay for spaghetti code!)
> 
> No, I don't think you do understand them correctly - or at least, I
> don't know of any way for a C macro to jump into the middle of a
> function.

I presume a macro could contain a call to longjmp, yes? Since longjmp can jump
into another function (albeit only one which has prepared for it in advance),
so can the macro.

https://stackoverflow.com/questions/21355110/how-to-goto-into-different-function-in-c

And what about assembly? Couldn't you jump into a function from assembly? Of
course the stack will be all wrong, but if you're using assembly you have to
manage that yourself.


> There are three quite different things mentioned here.
> 
> 1) The 'goto' statement, which unconditionally jumps you to another
> location *in the same function*

Yes. And a large enough function can contain everything. If you wanted to
write BASIC-style unstructured code, you could dump everything into one
function and use GOTO.


> 2) setjmp/longjmp, which is not actually a "goto", but more of a
> "multi-level return"

Right-oh. So sort of like an exception then.

So perhaps C is not quite as unstructured as I had initially thought.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Invoking return through a function?

2017-10-30 Thread Rick Johnson
Steve D'Aprano wrote:
> 
> [...]
> 
> I suppose it wouldn't be too awful if macros required
> dedicated syntax, so at least you could distinguish between
> "this is a safe, ordinary function" and "this is a macro,
> it could mean anything".

In the same spirit, i've been trying in vain for *YEARS* to
convince the PyDev gods to mandate that all clobbered class-
methods be marked in some distinguishing fashion so they
won't be transparent in the source, but nobody has bothered
to listen. I assume the indifference is due to the anti-OOP
attitude of the more influential folks in the community.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-30 Thread Chris Angelico
On Tue, Oct 31, 2017 at 2:00 PM, Steve D'Aprano
 wrote:
> Python has no GOTO, fortunately, but C has at least two, GOTO and LONGJMP. A C
> macro could, if I understand correctly, jump into the middle of another
> function. (Yay for spaghetti code!)

No, I don't think you do understand them correctly - or at least, I
don't know of any way for a C macro to jump into the middle of a
function.

There are three quite different things mentioned here.

1) The 'goto' statement, which unconditionally jumps you to another
location *in the same function*
2) setjmp/longjmp, which is not actually a "goto", but more of a
"multi-level return"
3) Preprocessor macros, which expand to some form of C source code.

Since macros have to expand to legal C code, they can't do anything
that you couldn't do by simply writing out the code - they just hide
it behind a token that looks like a function call. To use
setjmp/longjmp (which, btw, are actually standard library functions,
not language features) to jump into another function, you first have
to call the destination; they're much more akin to exception handling
than to an unstructured 'goto' (in fact, they're often used in the
implementation of exception handling). Basically, longjmp can only
rewind you to a previous setjmp, and only if the function that called
setjmp has *not returned* - so you can only use it to jump outwards,
not inwards.

But feel free to point out something I've forgotten, wherein you can
actually jump into the middle of a function using a macro. There's
enough dark corners in C that it's entirely possible I've missed
something obvious.

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


Re: Invoking return through a function?

2017-10-30 Thread Rustom Mody
On Tuesday, October 31, 2017 at 7:45:18 AM UTC+5:30, Alberto Riva wrote:
> On 10/30/2017 12:23 AM, Rustom Mody wrote:
> > On Sunday, October 29, 2017 at 9:52:01 PM UTC+5:30, Rick Johnson wrote:
> >> On Sunday, October 29, 2017 at 9:19:03 AM UTC-5, Alberto Riva wrote:
> > 
> >>> In a language like Lisp
> >>
> >> Python is nothing like Lisp, and for good reason! Sure, we
> >> have a few lispers and functional fanboys who hang around
> >> here, and sometimes Rustom can get a little preachy about
> >> FP, but mostly, we tolerate the fanboyism -- so long as it's
> >> not rabid fanboyism.
> > 
> > Rick's personal comments are one of the standard entertainments of this 
> > list. Enjoy!
> > 
> > The comments on FP are more problematic:
> > 
> > - These misconceptions are more widespread than just Rick
> > - They are right enough to be hard to refute
> > - And wrong enough to cause confusion and misdirection
> > - And irrelevant to (threads like) this one
> > 
> > My super-short rejoiner to the FP-irrelevancy is:
> > «If there is one key takeaway from functional programming maybe it should 
> > be: "Truth is a function of time" »
> > 
> > In more detail:
> > - Lisp (1960)  was the second functional language; its predecessor was 
> > something called Formula Translator — usually shortened to Fortran (c. 1957)
> > - By the late 80s, many FPers had begun regard Lisp as a setback for 
> > functional programming. [Dont get me wrong: Ive enjoyed Scheme more than 
> > any other
> > programming language. Its just that conflating Lisp and FP is an error (in 
> > 2017)]
> > 
> > More historical details at 
> > http://blog.languager.org/2015/04/cs-history-1.html and sequel
> > 
> > At a more conceptual level, people dont get that there are two dimensions
> > - the apply-lambda axis — usually called functional programming
> > - the eval-quote axis — which has precious little to do with FP (and is 
> > more relevant to your question)
> > 
> > These two dimensions of power uniquely coincide in Lisp (Scheme).
> > 
> > As you correctly (almost) point out
> > - Python is very much a lisp… its semantic under-belly
> > - However, syntactically its more like C/Java etc in the sense of having a 
> > rigid
> > fixed-at-language-design-time syntax
> > 
> > More at http://blog.languager.org/2013/08/applying-si-on-sicp.html
> > 
> > For a question like macros (syntax-extensions) that sits between the two 
> > your
> > question is interesting and I am not sure I know how to do it…
> > I remember seeing something about this recently but my google-foo is 
> > failing me
> > at the moment
> > 
> > However I would look at
> > - PEP 263 https://www.python.org/dev/peps/pep-0263/ — Source Code Encodings…
> > - Hooking into the codec module 
> > https://docs.python.org/3/library/codecs.html
> > - hooking into ast module https://docs.python.org/3/library/ast.html
> > 
> > An old attempt in this direction: 
> > http://code.activestate.com/recipes/546539/
> > 
> > You've already got the moral-hi-horse guys giving you the dope of why this 
> > is evil. Swallow if you like. My own lightweight
> > suggestion would be that the natural pythonic way of unstructured exit is 
> > exceptions. Not as succinct as a tailormade syntax extension. But good 
> > enough IMHO
> > 
> > PS I personally would be interested if you get this (syntax extension) 
> > running
> 
> Thanks for the interesting reply! But once again: I was not proposing to 
> add lisp-style macros to Python; I have no interest in doing that since 
> I believe it's pretty much impossible :)

https://github.com/pythonql/pythonql

is the example that shows how lisp-style extended-syntax (macros) can be done 
via file-encodings in a modern python.  Or if you prefer modern lingo: “How to
embed an internal DSL into python”

Note: I am not recommending you take this line; just that its not impossible
as you seem to imagine.

My own feeling about lisp-macros is conflicted:
- They are likely the most unique feature of lisp, putting it at the top of the
blub-language tower
- They are the single reason Lisp can never succeed like mainstream languages:
Any significant Lisp sub-ecosystem will inevitably develop a macro set which
succinctly and precisely expresses its needs but is arcane and incomprehensible
to someone from another sub-ecosystem.

This is Turing-completeness Lisp-specific style: 
The basic Turing-result is that programs can be arbitrarily complex to the point
of being unanalysable.
For mainstream languages that complexity sits squarely in the application
For lisp there is a choice of simplifying the application by concentrating
the complexity in a macro/DSL layer between implementation and application
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-30 Thread Steve D'Aprano
On Tue, 31 Oct 2017 01:06 pm, Alberto Riva wrote:

> On 10/30/2017 10:27 AM, Rhodri James wrote:
[...]
>> You can do the same in C.  I've had the displeasure of trying to
>> maintain such code.  It was near-unreadable, because it constantly broke
>> your expectations of what the code flow *could* be.  The fact that
>> something that could return from the middle of your function without the
>> slightest indication was a rich source of bugs.
> 
> Just curious: how is this different from calling a function that throws
> an exception (that may or may not be caught by some other function
> higher up in the call stack)? That also breaks your expectations of what
> the code flow would be...

The mere possibility of an exceptions does not break the normal, unexceptional
code flow. You can still reason about the flow "if the data is valid, and
there are no exceptions" where execution proceeds from the top of the
function down, only exiting if there's a return. That's your base,
unexceptional case, and there's no traps there. Any jump (return, break,
continue) is explicit and obvious.

Then you can think about the exceptional case, where data is invalid and you
get an exception, separately. They're independent.

In the exceptional case, the control flow is different, but still predictable:
an exception is raised, and control exits the current block, to be either
caught by the nearest surrounding except block, or if no such block, halting
execution. Either way, its all relatively[1] straight-forward, with no
surprises. You can't jump into the middle of a function, you can only pop out
of the current call-chain into the surrounding function call.

But with macros, you can't do that. Anything can be anything. An ordinary
looking function call inside a loop might mask a hidden `continue` or
`break`. A function call might mask a secret `return`.

Python has no GOTO, fortunately, but C has at least two, GOTO and LONGJMP. A C
macro could, if I understand correctly, jump into the middle of another
function. (Yay for spaghetti code!)

I suppose it wouldn't be too awful if macros required dedicated syntax, so at
least you could distinguish between "this is a safe, ordinary function"
and "this is a macro, it could mean anything". But it would still increase
the maintenance burden, proportional to the number of macros used.


> To clarify, I agree with your concern. What I mean is that even in
> normal conditions there's never any guarantee that the code flow is what
> you expect it to be just by reading the body of a function.

True -- there's always *two* possible paths: the standard, unexceptional
control flow, when no exceptions are raised; and the exceptional control
flow. The second is more complex than the first, but in *practice* (if not in
theory) we can at least be reasonably sure of what exception is raised and
where it is caught.



[1] There's no doubt that exception handling, except in the simplest forms, is
more complex than code without exception handling. And this is why Rob Pike
designed Go without exceptions.


-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.

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


Re: Invoking return through a function?

2017-10-30 Thread Alberto Riva

On 10/30/2017 12:23 AM, Rustom Mody wrote:

On Sunday, October 29, 2017 at 9:52:01 PM UTC+5:30, Rick Johnson wrote:

On Sunday, October 29, 2017 at 9:19:03 AM UTC-5, Alberto Riva wrote:



In a language like Lisp


Python is nothing like Lisp, and for good reason! Sure, we
have a few lispers and functional fanboys who hang around
here, and sometimes Rustom can get a little preachy about
FP, but mostly, we tolerate the fanboyism -- so long as it's
not rabid fanboyism.


Rick's personal comments are one of the standard entertainments of this list. 
Enjoy!

The comments on FP are more problematic:

- These misconceptions are more widespread than just Rick
- They are right enough to be hard to refute
- And wrong enough to cause confusion and misdirection
- And irrelevant to (threads like) this one

My super-short rejoiner to the FP-irrelevancy is:
«If there is one key takeaway from functional programming maybe it should be: "Truth 
is a function of time" »

In more detail:
- Lisp (1960)  was the second functional language; its predecessor was 
something called Formula Translator — usually shortened to Fortran (c. 1957)
- By the late 80s, many FPers had begun regard Lisp as a setback for functional 
programming. [Dont get me wrong: Ive enjoyed Scheme more than any other
programming language. Its just that conflating Lisp and FP is an error (in 
2017)]

More historical details at http://blog.languager.org/2015/04/cs-history-1.html 
and sequel

At a more conceptual level, people dont get that there are two dimensions
- the apply-lambda axis — usually called functional programming
- the eval-quote axis — which has precious little to do with FP (and is more 
relevant to your question)

These two dimensions of power uniquely coincide in Lisp (Scheme).

As you correctly (almost) point out
- Python is very much a lisp… its semantic under-belly
- However, syntactically its more like C/Java etc in the sense of having a rigid
fixed-at-language-design-time syntax

More at http://blog.languager.org/2013/08/applying-si-on-sicp.html

For a question like macros (syntax-extensions) that sits between the two your
question is interesting and I am not sure I know how to do it…
I remember seeing something about this recently but my google-foo is failing me
at the moment

However I would look at
- PEP 263 https://www.python.org/dev/peps/pep-0263/ — Source Code Encodings…
- Hooking into the codec module https://docs.python.org/3/library/codecs.html
- hooking into ast module https://docs.python.org/3/library/ast.html

An old attempt in this direction: http://code.activestate.com/recipes/546539/

You've already got the moral-hi-horse guys giving you the dope of why this is 
evil. Swallow if you like. My own lightweight
suggestion would be that the natural pythonic way of unstructured exit is 
exceptions. Not as succinct as a tailormade syntax extension. But good enough 
IMHO

PS I personally would be interested if you get this (syntax extension) running


Thanks for the interesting reply! But once again: I was not proposing to 
add lisp-style macros to Python; I have no interest in doing that since 
I believe it's pretty much impossible :)


Thanks!

Alberto

--
E-mail address:
((lambda (s a b c) (map 'string #'code-char (mapcar (lambda (v)
(setq s (+ a (mod (+ s v (- a)) b (map 'list (lambda (v)
(- (char-code v) c)) " 1`-THUZ&+Wh1" 97 46 73 32)
--
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-30 Thread Alberto Riva

On 10/30/2017 10:27 AM, Rhodri James wrote:

On 29/10/17 16:45, Alberto Riva wrote:

On 10/29/2017 11:13 AM, bartc wrote:


(What the OP wants was also proposed a few weeks back in comp.lang.c. 
But that was only within nested functions, so if H is inside G, and G 
is inside F, then a 'returnall' from H would return directly directly 
from F. Apparently Lisp allows this...)


Well, not directly, but it can be simulated with the condition system 
(equivalent to try/except) or with throw/catch, which is similar but 
doesn't use exceptions.


But my point was that in Lisp you don't need to do this, because you 
can write a macro that expands into a return *in place*, without 
calling a separate function, and this eliminates the problem entirely. 
Since Python doesn't have macros I was looking for the next-best 
solution, but there doesn't seem to be one. Oh, well...


You can do the same in C.  I've had the displeasure of trying to 
maintain such code.  It was near-unreadable, because it constantly broke 
your expectations of what the code flow *could* be.  The fact that 
something that could return from the middle of your function without the 
slightest indication was a rich source of bugs.


Just curious: how is this different from calling a function that throws 
an exception (that may or may not be caught by some other function 
higher up in the call stack)? That also breaks your expectations of what 
the code flow would be...


To clarify, I agree with your concern. What I mean is that even in 
normal conditions there's never any guarantee that the code flow is what 
you expect it to be just by reading the body of a function. The kind of 
statement I was trying to add would at least have made that explicit: 
return-if-so-and-so-happens.


Alberto



--
E-mail address:
((lambda (s a b c) (map 'string #'code-char (mapcar (lambda (v)
(setq s (+ a (mod (+ s v (- a)) b (map 'list (lambda (v)
(- (char-code v) c)) " 1`-THUZ&+Wh1" 97 46 73 32)
--
https://mail.python.org/mailman/listinfo/python-list


Re: [Tutor] request.post in If condition

2017-10-30 Thread Mike Miller
What do you mean when you say it is not hitting? Is there a specific error,
or are you saying it simply isn't posting to your site?

Mike

On Mon, Oct 30, 2017, 8:21 AM sourav voip  wrote:

> Hi All,
>
> I'm trying to hit request.post with condition using if-else as below...
> I;m posting the full script here...as I've tried declaring post url details
> tested with multiple places..
>
> If condition for disk utiliztion is working perfect ,however request.post
> is not hitting.
> Please suggest any hint/clue as I'm a new learner in python.
>
> Regards,
> Sourav
>
> 
> -
> #!/usr/bin/python
> import re,sys,commands
> import requests
> # Set the request parameters
> url = 'https://dev.service-now.com/api/now/table/incident'
>
> # Eg. User name="admin", Password="admin" for this code sample.
> user = 'admin'
> pwd = ''
>
> # Set proper headers
> headers = {"Content-Type":"application/json","Accept":"application/json"}
>
>
> #
> #Set variables
> command = "df /"
> critical = 50.0
> warning = 40.0
> #
>
> #build regex
> dfPattern = re.compile('[0-9]+')
>
> #get disk utilization
> diskUtil = commands.getstatusoutput(command)
>
> #split out the util %
> diskUtil = diskUtil[1].split()[11]
>
> #look for a match. If no match exit and return an
> #UNKNOWN (3) state to Nagios
>
> matchobj = dfPattern.match(diskUtil)
> if (matchobj):
> diskUtil = eval(matchobj.group(0))
> else:
> print "STATE UNKNOWN"
> sys.exit(3)
>
> #Determine state to pass to Nagios
> #CRITICAL = 2
> #WARNING = 1
> #OK = 0
> if diskUtil >= critical:
> url = 'https://dev.service-now.com/api/now/table/incident'
> user = 'admin'
> pwd = ''
> headers = {"Content-Type":"application/json","Accept":"application/
> json"}
> requests.post(url, auth=(user, pwd), headers=headers
> ,data="{\"assignment_group\":\Hardware\",\"short_description\":\"Threshold
> critical\"}")
> print "FREE SPACE CRITICAL: '/' is %.2f%% full" % (float(diskUtil))
> sys.exit(2)
> elif diskUtil >= warning:
> requests.post(url, auth=(user, pwd), headers=headers
> ,data="{\"assignment_group\":\Hardware\",\"short_description\":\"Threshold
> Warning\"}")
> print "FREE SPACE WARNING: '/' is %.2f%% full" % (float(diskUtil))
> sys.exit(1)
> else:
> print "FREE SPACE OK: '/' is %.2f%% full" % (float(diskUtil))
> sys.exit(0)
>
>
> On Mon, Oct 30, 2017 at 4:04 PM, sourav voip 
> wrote:
>
> > Hi All,
> >
> > I'm trying to hit request.post with condition using if-else as below...
> > I;m posting the full script here...as I've tried declaring post url
> > details tested with multiple places.
> >
> >
> >
> >
> >
> ___
> Tutor maillist  -  tu...@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Vim, ctags jump to python standard library source

2017-10-30 Thread Cameron Simpson

On 19Oct2017 12:08, Matt Schepers  wrote:

I prefer to use vim and ctags when developing python, but I'm having
trouble getting ctags to index the standard library. Sometimes I would like
to see an object's constructor etc...

Does anyone know how to do this?


Will "ctags -o your-tags-file -a -R /path/to/your/python/lib" not scan the 
python library?  Haven't tried it myself, and the tags file would be HUGE...


Hmm...

 [~]fleet*> ctags -o testtags -a -R /usr/lib/python2.7
 [~]fleet*> L testtags
 -rw-rw-r--  1 cameron  cameron  7208525 31 Oct 10:19 testtags

Superficially looks ok...

Cheers,
Cameron Simpson  (formerly c...@zip.com.au)
--
https://mail.python.org/mailman/listinfo/python-list


Re: from packaging import version as pack_version ImportError: No module named packaging

2017-10-30 Thread Cameron Simpson

On 30Oct2017 10:48, David Gabriel  wrote:

When I run this command I got this error message:

ubuntu@orchestrateur:/tmp/pack$ virtualenv -p $(which python3.5) .

[...]

OSError: [Errno 13] Permission denied


Peter has explained this failure. Note that in the shell you can show command 
execution, which is very helpful for figuring out this kind of thing:


 set -x
 virtualenv -p $(which python3.5) .
 set +x

which would show you the actual virtualenv command invoked. In particular, it 
would be apparent (if Peter's suggestion is correct) that the result of "which 
python3.5" was empty, leading to an invalid "virtualenv" incantation.


However, I write about something else:


This error is also reproducible using sudo.


I've seen this before. NEVER EVER do this! If something fails, DO NOT reach for 
"sudo" to "fix" the problem. Usually things fail because of mistaken use (such 
as your example) or because of some system policy forbidding the action.


In both cases the correct process is to understand why the failure occurred, 
NOT to try to run the action in some special privileged mode to avoid the 
check.


Please try not to reach for "sudo" by reflex. It _will_ get you into trouble 
one day, either by doing unintended damage to your stuff or by raising the ire 
of some sysadmin when you try it on some system that is their responsibility.


Thank you,
Cameron Simpson  (formerly c...@zip.com.au)
--
https://mail.python.org/mailman/listinfo/python-list


Re: right list for SIGABRT python binary question ?

2017-10-30 Thread Karsten Hilbert
On Mon, Oct 30, 2017 at 02:02:25PM +0100, M.-A. Lemburg wrote:

> PS: Please CC me on replies as I don't regularly read c.l.p anymore.

Sure.

> >> Could you check whether you have similar import errors with
> >> other modules that have C extensions ? E.g. lxml.
> >>
> >> What you're seeing appears to be a compilation problem
> >> with Python 2.7.14 on Debian. The executable doesn't appear
> >> to export its symbols to the .so files, or only some of them.
> > 
> > Let's see:
> > ... using -dbg packages for everything, the imports work ...
> 
> Ah, so you were mixing debug packages with non-debug ones. This
> explains the import errors.

I am not sure I do.

I installed normal and -dbg packages for modules with
c extensions, say psycopg2:

python-psycopg2:
  Installiert:   2.7.3-1
  Installationskandidat: 2.7.3-1
  Versionstabelle:
 *** 2.7.3-1 990
990 http://httpredir.debian.org/debian buster/main i386 Packages
500 http://httpredir.debian.org/debian unstable/main i386 
Packages
100 /var/lib/dpkg/status
 2.6.2-1 500
500 http://httpredir.debian.org/debian stretch/main i386 
Packages
python-psycopg2-dbg:
  Installiert:   2.7.3-1
  Installationskandidat: 2.7.3-1
  Versionstabelle:
 *** 2.7.3-1 990
990 http://httpredir.debian.org/debian buster/main i386 Packages
500 http://httpredir.debian.org/debian unstable/main i386 
Packages
100 /var/lib/dpkg/status
 2.6.2-1 500
500 http://httpredir.debian.org/debian stretch/main i386 
Packages

Now, when running either python2.7 or python2.7-dbg, which
are installed alongside

python2.7-dbg:
  Installiert:   2.7.14-2
  Installationskandidat: 2.7.14-2
  Versionstabelle:
 *** 2.7.14-2 990
990 http://httpredir.debian.org/debian buster/main i386 Packages
500 http://httpredir.debian.org/debian unstable/main i386 
Packages
100 /var/lib/dpkg/status
 2.7.13-2 500
500 http://httpredir.debian.org/debian stretch/main i386 
Packages

python2.7:
  Installiert:   2.7.14-2
  Installationskandidat: 2.7.14-2
  Versionstabelle:
 *** 2.7.14-2 990
990 http://httpredir.debian.org/debian buster/main i386 Packages
500 http://httpredir.debian.org/debian unstable/main i386 
Packages
100 /var/lib/dpkg/status
 2.7.13-2 500
500 http://httpredir.debian.org/debian stretch/main i386 
Packages

the Debian version does (should ?) take care to import either
the -dbg or the normal version of modules. It seems it so
does because when I got both module versions installed I
don't get any import errors. So I don't think I am mixing, at
least not to my knowledge.

(But I still get the SIGABORT on shutdown regardless.)

> Do you just see the SIGABRT when running the debug versions or
> also with the production versions (memory management works differently
> in Python debug mode) ?

Either version fails.

Why haven't I tried running this under python3 ?  Because the
whole shebang is part of a wxPython application (GNUmed) and
there are no Debian packages for wxPython/wxPhoenix on py3 as
far as I know.

> BTW: It would help if you'd post the stack trace with symbols.
> The one you posted in one of your earlier emails only includes
> addresses.

I'd gladly comply if I knew how. This is what apt says about python2.7-dbg:

Package: python2.7-dbg
Version: 2.7.14-2
Description-en: Debug Build of the Python Interpreter (version 2.7)
 The package holds two things:
 .
 - A Python interpreter configured with --pydebug. Dynamically loaded 
modules
   are searched as _d.so first. Third party extensions need a 
separate
   build to be used by this interpreter.
 - Debug information for standard python interpreter and extensions.

So from that I conferred it does contain symbols.

I am getting a fresh run under gdb with python2.7-dbg. Maybe
you can point out where you'd have expected to see symbols
and help me figure out which -dbg package is missing on this
Debian system:

[...]
==> verifying target database schema ...
==> checking migrated data for plausibility ...
Done bootstrapping GNUmed database: We very likely succeeded.
log: 
/home/ncq/Projekte/gm-git/gnumed/gnumed/server/bootstrap/bootstrap-latest.log
Debug memory block at address p=0x6aab7c: API ''
0 bytes originally requested
The 3 pad bytes at p-3 are not all FORBIDDENBYTE (0xfb):
at p-3: 0x33 *** OUCH
at p-2: 0x47 *** OUCH
at p-1: 0x00 *** OUCH
Because memory is corrupted at the

Re: pythonw.exe error

2017-10-30 Thread Rustom Mody
On Monday, October 30, 2017 at 10:11:49 PM UTC+5:30, Igor Korot wrote:
> Hi,
> 
> 
> 
> On Oct 30, 2017 11:27 AM, "George Kalamaras via Python-list" wrote:
> 
> When I am running IDLE return to me Missing python36.dll error
> 
> Στάλθηκε από την Αλληλογραφία για Windows 10
> 
> 
> Could you please translate this from Greek?

Google translate tells me this is "Sent from mail for Windows 10"

IOW its probably a mail auto-footer of the OP, not the error message
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: pythonw.exe error

2017-10-30 Thread Igor Korot
Hi,



On Oct 30, 2017 11:27 AM, "George Kalamaras via Python-list" <
python-list@python.org> wrote:

When I am running IDLE return to me Missing python36.dll error

Στάλθηκε από την Αλληλογραφία για Windows 10


Could you please translate this from Greek?

Thank you.


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


pythonw.exe error

2017-10-30 Thread George Kalamaras via Python-list
When I am running IDLE return to me Missing python36.dll error

Στάλθηκε από την Αλληλογραφία για Windows 10

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


Re: Coding style in CPython implementation

2017-10-30 Thread Rhodri James

On 28/10/17 19:42, Στέφανος Σωφρονίου wrote:

Greetings everyone.

I have noticed that in many if conditions the following syntax is used:

a) if (variable == NULL) { ... }
b) if (variable == -1) { ... }
c) if (variable != NULL) { ... }

What I wanted to ask is, is there a particular reason for not choosing

a) if (!variable) { ... } in place of if (variable == NULL) { ... },


"if (variable == NULL)" emphasises that "variable" is a pointer 
variable, aiding readability.



b) if (-1 == variable) { ... } in place of if (variable == -1) { ... }, and


It's just not natural English.  It's safer to write it with the constant 
first, but modern compilers will warn you about assignments in 
conditions these days, and it's not worth the reduction in readability 
in my opinion.


(Also, if you aren't using the -Werror -Wall flags to the compiler, you 
deserve everything that will be coming to you.)



c) if (variable) { ... } in place of if (variable) { ... } ?


I assume you mean "if (variable != NULL)" here.  Again, it emphasises 
the type; variable will be a pointer.


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: Getting started with python

2017-10-30 Thread Bill

subhendu.pand...@gmail.com wrote:

Hi,

Could you please help me with the below if possible:


Possible and reasonable are two different things.  Why don't you try 
some web searches and try to answer some of your own questions.  I offer 
this advice as a Python newbe myself.


Bill




1. Best site to go ahead for python.
2. How python is different from other languages and future scope of it.
3. Tasks that are getting done using python in present.
4. Link where I can be able to get python videos, ebooks from basics to expert 
level free.

Thanks
Subhendu


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


Getting started with python

2017-10-30 Thread subhendu . panda93
Hi,

Could you please help me with the below if possible:

1. Best site to go ahead for python.
2. How python is different from other languages and future scope of it.
3. Tasks that are getting done using python in present.
4. Link where I can be able to get python videos, ebooks from basics to expert 
level free.

Thanks
Subhendu
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Invoking return through a function?

2017-10-30 Thread Rhodri James

On 29/10/17 16:45, Alberto Riva wrote:

On 10/29/2017 11:13 AM, bartc wrote:


(What the OP wants was also proposed a few weeks back in comp.lang.c. 
But that was only within nested functions, so if H is inside G, and G 
is inside F, then a 'returnall' from H would return directly directly 
from F. Apparently Lisp allows this...)


Well, not directly, but it can be simulated with the condition system 
(equivalent to try/except) or with throw/catch, which is similar but 
doesn't use exceptions.


But my point was that in Lisp you don't need to do this, because you can 
write a macro that expands into a return *in place*, without calling a 
separate function, and this eliminates the problem entirely. Since 
Python doesn't have macros I was looking for the next-best solution, but 
there doesn't seem to be one. Oh, well...


You can do the same in C.  I've had the displeasure of trying to 
maintain such code.  It was near-unreadable, because it constantly broke 
your expectations of what the code flow *could* be.  The fact that 
something that could return from the middle of your function without the 
slightest indication was a rich source of bugs.


(I didn't have to tell my boss to up our rates for dealing with this 
code.  It took several days to do the work anyway, which was punishment 
enough at our rates.)


--
Rhodri James *-* Kynesim Ltd
--
https://mail.python.org/mailman/listinfo/python-list


Re: right list for SIGABRT python binary question ?

2017-10-30 Thread M.-A. Lemburg
n 25.10.2017 11:51, Karsten Hilbert wrote:
> On Tue, Oct 24, 2017 at 08:47:58PM +0200, M.-A. Lemburg wrote:
> 
 This error suggests that you have 32- and 64-bit versions of
 Python and mxDateTime mixed in your installation.

 Py_InitModule4 is only available in the 32-bit build of
 Python. With the 64-bit build, it's called Py_InitModule4_64.
> ...
>> Could you check whether you have similar import errors with
>> other modules that have C extensions ? E.g. lxml.
>>
>> What you're seeing appears to be a compilation problem
>> with Python 2.7.14 on Debian. The executable doesn't appear
>> to export its symbols to the .so files, or only some of them.
> 
> Let's see:
> ... using -dbg packages for everything, the imports work ...

Ah, so you were mixing debug packages with non-debug ones. This
explains the import errors.

> mx.DateTime imports fine as well (but the SIGABRT persists).

Do you just see the SIGABRT when running the debug versions or
also with the production versions (memory management works differently
in Python debug mode) ?

BTW: It would help if you'd post the stack trace with symbols.
The one you posted in one of your earlier emails only includes
addresses.

PS: Please CC me on replies as I don't regularly read c.l.p anymore.

Thanks,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Experts (#1, Oct 30 2017)
>>> Python Projects, Coaching and Consulting ...  http://www.egenix.com/
>>> Python Database Interfaces ...   http://products.egenix.com/
>>> Plone/Zope Database Interfaces ...   http://zope.egenix.com/


::: We implement business ideas - efficiently in both time and costs :::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
  http://www.malemburg.com/

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


Re: request.post in If condition

2017-10-30 Thread sourav voip
Hi All,

I'm trying to hit request.post with condition using if-else as below...
I;m posting the full script here...as I've tried declaring post url details
tested with multiple places..

If condition for disk utiliztion is working perfect ,however request.post
is not hitting.
Please suggest any hint/clue as I'm a new learner in python.

Regards,
Sourav


-
#!/usr/bin/python
import re,sys,commands
import requests
# Set the request parameters
url = 'https://dev.service-now.com/api/now/table/incident'

# Eg. User name="admin", Password="admin" for this code sample.
user = 'admin'
pwd = ''

# Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}


#
#Set variables
command = "df /"
critical = 50.0
warning = 40.0
#

#build regex
dfPattern = re.compile('[0-9]+')

#get disk utilization
diskUtil = commands.getstatusoutput(command)

#split out the util %
diskUtil = diskUtil[1].split()[11]

#look for a match. If no match exit and return an
#UNKNOWN (3) state to Nagios

matchobj = dfPattern.match(diskUtil)
if (matchobj):
diskUtil = eval(matchobj.group(0))
else:
print "STATE UNKNOWN"
sys.exit(3)

#Determine state to pass to Nagios
#CRITICAL = 2
#WARNING = 1
#OK = 0
if diskUtil >= critical:
url = 'https://dev.service-now.com/api/now/table/incident'
user = 'admin'
pwd = ''
headers = {"Content-Type":"application/json","Accept":"application/
json"}
requests.post(url, auth=(user, pwd), headers=headers
,data="{\"assignment_group\":\Hardware\",\"short_description\":\"Threshold
critical\"}")
print "FREE SPACE CRITICAL: '/' is %.2f%% full" % (float(diskUtil))
sys.exit(2)
elif diskUtil >= warning:
requests.post(url, auth=(user, pwd), headers=headers
,data="{\"assignment_group\":\Hardware\",\"short_description\":\"Threshold
Warning\"}")
print "FREE SPACE WARNING: '/' is %.2f%% full" % (float(diskUtil))
sys.exit(1)
else:
print "FREE SPACE OK: '/' is %.2f%% full" % (float(diskUtil))
sys.exit(0)


On Mon, Oct 30, 2017 at 4:04 PM, sourav voip 
wrote:

> Hi All,
>
> I'm trying to hit request.post with condition using if-else as below...
> I;m posting the full script here...as I've tried declaring post url
> details tested with multiple places.
>
>
>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


request.post in If condition

2017-10-30 Thread sourav voip
Hi All,

I'm trying to hit request.post with condition using if-else as below...
I;m posting the full script here...as I've tried declaring post url details
tested with multiple places.
-- 
https://mail.python.org/mailman/listinfo/python-list


Performance of map vs starmap.

2017-10-30 Thread Kirill Balunov
Sometime ago I asked this question at SO [1], and among the responses
received was paragraph:

 - `zip` re-uses the returned `tuple` if it has a reference count of 1 when
the `__next__` call is made.
 - `map` build a new `tuple` that is passed to the mapped function every
time a `__next__` call is made.

Why can not `map` use the same approach as `zip`?

Also it turns out that a faster solution looks not reasonable, since it
requires additional calculations..

[1] https://stackoverflow.com/questions/46172018/perfomance-
of-map-vs-starmap

Thanks,
- gdg
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: why it append one more letter after decode?

2017-10-30 Thread ROGER GRAYDON CHRISTMAN
On Sun, Oct 29, 2017 11:06 PM, Ho Yeung Lee wrote:
>
if run these function to decode in python interactive console,
>it can decode correct, 
>
>but when run with a big project, it append a letter Y
>
>
>On Monday, October 30, 2017 at 9:48:36 AM UTC+8, Ho Yeung Lee wrote:
>> def leftrotate(l, n):
>> return l[n:] + l[:n]
>> 
>> def rightrotate(l, n):
>> return l[-n:] + l[:-n]
>> 
>> def encode(s, k, kk):
>> l = [ord(i) for i in s]
>> return leftrotate(''.join([chr(i + k) for i in l]), kk)
>> 
>> def decode(s, k, kk):
>> l = [ord(i) for i in rightrotate(s, kk)]
>> return ''.join([chr(i - k) for i in l])
>> 
>> 
>> yesterday i add above code and run it with batch file 
>> it can decode a correct password
>> 
>> then i install cx_freeze to produce executable file
>> 
>> but today when i run it, i see the source of encrypted password is correct
>> but the decode one, it append one more letter Y at the end of string
>> 
>> why?
>> is cx_freeze change the source python 2.7?
>
>i discover when 
>it 
>decode("\\",1,2)
>in interactive console
>is [
>
>but decode in big project
>it see as
>decode(r"\\",1,2)
>[[
>
>it double
>
>


My first inclination is that the data could have changed.
For example, obtaining a string from the keyboard using input()
would suppress the carriage return.   But obtaining
a string from a file might preserve the carriage return
at the end of the line.   I could imagine then that the
extra carriage return contributed an extra character to your data.

But then I see you had an example with "\\" in one case,
and r"\\" in the other case.  These are not equal to each other,
and naturally would not give equal results from your function.

So that leads to the second possibility that you are not calling
the function in the same way.

In either case, you cannot blame the function for giving you
different results if you give it different data.

Roger Christman
Pennsylvania State University 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: from packaging import version as pack_version ImportError: No module named packaging

2017-10-30 Thread Peter Otten
David Gabriel wrote:

> Dears,
> 
> When I run this command I got this error message:
> 
> ubuntu@orchestrateur:/tmp/pack$ virtualenv -p $(which python3.5) .
> Running virtualenv with interpreter /usr/local/sbin/.
> Traceback (most recent call last):
>   File "/usr/bin/virtualenv", line 3, in 
> virtualenv.main()
>   File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 784, in main
> popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env)
>   File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
> errread, errwrite)
>   File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
> raise child_exception
> OSError: [Errno 13] Permission denied
> 
> 
> This error is also reproducible using sudo.

When `which` does not find python3.5 your virtualenv invocation is 
effectively

$ virtualenv -p .

It should be clear that the current directory is usually not a python 
interpreter ;)

> Please advise how to fix it.

Provide the path to an actually existing interpreter. If you insist on 
which-craft test the command first:

$ which python3.3 
$ which python3.4
/usr/bin/python3.4
 
So on my system $(which python3.4) might work while $(which python3.3) will 
not.

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


Re: Pandas to_html cannot apply style

2017-10-30 Thread zljubisic
> This is not an in-place operation: it returns a style which you can then
> render.
> 
> style = df.style.apply(function2, axis=1)
> html = style.render()
> 
> appears to work.

After your suggestion, rows are properly colored, but now I have lost all table 
lines, font is smaller...
Is there an option for keeping table format, and change only rows background 
color?

Regards.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: from packaging import version as pack_version ImportError: No module named packaging

2017-10-30 Thread David Gabriel
Dears,

When I run this command I got this error message:

ubuntu@orchestrateur:/tmp/pack$ virtualenv -p $(which python3.5) .
Running virtualenv with interpreter /usr/local/sbin/.
Traceback (most recent call last):
  File "/usr/bin/virtualenv", line 3, in 
virtualenv.main()
  File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 784, in main
popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 13] Permission denied


This error is also reproducible using sudo.
Please advise how to fix it.

Thanks in advance.
Best regards


2017-10-28 14:33 GMT+02:00 David Gabriel :

> I forget to precise that I am using pycharm.
> And this issue is reproducible also using command line to run the code.
>
> Best regards
>
> 2017-10-28 14:31 GMT+02:00 David Gabriel :
>
>> Thanks so Lutz much for your reply.
>> I am using python2.7 and I am running this code in an Openstack instance.
>> I will apply your recommandation and let you know about the result ...
>>
>> Kind regards.
>>
>> 2017-10-27 16:13 GMT+02:00 Lutz Horn :
>>
>>> On Fri, Oct 27, 2017 at 03:56:39PM +0200, David Gabriel wrote:
>>> > from packaging import version as pack_version
>>> > ImportError: No module named packaging
>>> >
>>> > I googled it and I have found so many suggestions regarding updating
>>> > 'pip' and installing python-setuptools but all of these did not fix
>>> > this issue.
>>>
>>> So many questions:
>>>
>>> * What is your Python version?
>>> * Do you use virtualenv?
>>> * How?
>>> * Did you install packaging in this virtualenv?
>>>
>>> Just one example of making this work:
>>>
>>> $ mkdir /tmp/pack
>>> $ cd /tmp/pack
>>> $ virtualenv -p $(which python3.5) .
>>> Running virtualenv with interpreter /usr/bin/python3.5
>>> Using base prefix '/usr'
>>> New python executable in /tmp/pack/bin/python3.5
>>> Also creating executable in /tmp/pack/bin/python
>>> Installing setuptools, pkg_resources, pip, wheel...done.
>>> $ source bin/activate
>>> $ pip3 install packaging
>>> Collecting packaging
>>>   Using cached packaging-16.8-py2.py3-none-any.whl
>>> Collecting six (from packaging)
>>>   Using cached six-1.11.0-py2.py3-none-any.whl
>>> Collecting pyparsing (from packaging)
>>>   Using cached pyparsing-2.2.0-py2.py3-none-any.whl
>>> Installing collected packages: six, pyparsing, packaging
>>> Successfully installed packaging-16.8 pyparsing-2.2.0 six-1.11.0
>>> $ python3.5
>>> Python 3.5.2 (default, Sep 14 2017, 22:51:06)
>>> [GCC 5.4.0 20160609] on linux
>>> Type "help", "copyright", "credits" or "license" for more
>>> information.
>>> >>> from packaging import version as pack_version
>>> >>>
>>> --
>>> https://mail.python.org/mailman/listinfo/python-list
>>>
>>
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pandas to_html cannot apply style

2017-10-30 Thread zljubisic
 
> This is not an in-place operation: it returns a style which you can then
> render.
> 
> style = df.style.apply(function2, axis=1)
> html = style.render()
> 
> appears to work.

This was a missing link.
Thank you very very much Thomas. 

Regards and best wishes.
-- 
https://mail.python.org/mailman/listinfo/python-list


pandas finding field difference between two dataframes

2017-10-30 Thread zljubisic

Hi,

I have to compare two pandas dataframes and find difference between each row.
For example, in the code bellow, rows with index 0 and 3 are intentionally 
different.
Row 0 is different in field A, and row 3 is different in field 3.

After merging dataframes, I can concentrate to the dfm with dfm['_merge'] != 
'both'.
How to find which field is different?
End result should be:
row 0, A
row 3, B

Regards.


import pandas as pd
import numpy as np


idx = pd.date_range('01.01.2017', periods=7, freq='D')
A = [False, True, True, False, True, False, True]
B = np.random.randn(7)
C = np.random.randn(7)

data1 = { 'A' : [False, True, True, False, True, False, True],
'B' : list(range(len(idx))),
'C' : list(range(len(idx), len(idx) + len(idx)))
}

dfl = pd.DataFrame(data1, index=idx)

data2 = data1.copy()
data2['A'][0] = True
data2['B'][3] = 30

dfr = pd.DataFrame(data2, index=idx)


# dfm = dfl.merge(dfr, indicator=True, how='outer', left_on=dfl.index, right_on 
= dfr.index)
dfm = dfl.merge(dfr, indicator=True, how='outer')

print(dfl)
print(dfr)
print(dfm)

print(dfl.iloc[[0,3]])
print(dfr.iloc[[0,3]])

Output:

A  B   C
2017-01-01  False  0   7
2017-01-02   True  1   8
2017-01-03   True  2   9
2017-01-04  False  3  10
2017-01-05   True  4  11
2017-01-06  False  5  12
2017-01-07   True  6  13
A   B   C
2017-01-01   True   0   7
2017-01-02   True   1   8
2017-01-03   True   2   9
2017-01-04  False  30  10
2017-01-05   True   4  11
2017-01-06  False   5  12
2017-01-07   True   6  13
   A   B   C  _merge
0  False   0   7   left_only
1   True   1   8both
2   True   2   9both
3  False   3  10   left_only
4   True   4  11both
5  False   5  12both
6   True   6  13both
7   True   0   7  right_only
8  False  30  10  right_only
Backend TkAgg is interactive backend. Turning interactive mode on.
A  B   C
2017-01-01  False  0   7
2017-01-04  False  3  10
A   B   C
2017-01-01   True   0   7
2017-01-04  False  30  10
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pandas to_html cannot apply style

2017-10-30 Thread Thomas Jollans
On 30/10/17 08:44, zljubi...@gmail.com wrote:
> Hi,
> 
> the following code never applies style and I cannot figure out why.
> Can someone please help?
> 
> import pandas as pd
> 
> def function2(row):
> if row.A == True:
> color = '#FF'
> else:
> color = '#00FF00'
> 
> background_color = 'background-color: {}'.format(color)
> 
> return [background_color] * len(row.values)
> 
> idx = pd.date_range('01.01.2017', periods=7, freq='D')
> A = [False, True, True, False, True, False, True]
> B = np.random.randn(7)
> C = np.random.randn(7)
> 
> data = { 'A' : [False, True, True, False, True, False, True],
> 'B' : np.random.randn(7),
> 'C' : np.random.randn(7)
> }
> 
> df = pd.DataFrame(data, index=idx)
> 
> df.style.apply(function2, axis=1)

This is not an in-place operation: it returns a style which you can then
render.

style = df.style.apply(function2, axis=1)
html = style.render()

appears to work.

> 
> html = df.style.render()
> 
> if '#FF' in html or '#00FF00' in html:
> print('style applied')
> else:
> print('style not applied')
> 
> Regards.
> 

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


Re: Invoking return through a function?

2017-10-30 Thread Christian Gollwitzer

Am 30.10.17 um 01:42 schrieb Steve D'Aprano:

On Mon, 30 Oct 2017 03:35 am, Alberto Riva wrote:

And as Bartc
pointed out, we already have this situation with exceptions, so it would
be nothing new.


Pardon me, but it was *me* who pointed out the analogy with exceptions, not
Bart. But this is different from an exception.

The similarity is quite weak:

- any function can raise an exception;

- your hoped for feature would allow any function to cause the
   caller to return;


For another data point, I'm regularly using another language, which does 
have this feature without macros - Tcl. In Tcl, you can return a control 
code alongside with the value which causes the caller to /return/, throw 
an /error/ or execute a /break/ or /continue/ statement. It is realised 
by additional options to "return"; translated into Python syntax it 
would look like:


return ("somevalue", code=return)

The caller can still intercept this return code using "catch".
This feature can be used to implement one's own control structures, but 
it is rarely used in other contexts. It is there for completeness; in 
order to allow functions to be written which mimic exactly break, 
continue, error (="raise" in Python) and return. In practice, the only 
situation where it is regularly used is argument checking. Consider:


def root(X):
if X < 0:
return("X must be positive", code=error)

root(-1)

With "raise" instead of "return", the stack trace points to the line 
containing "raise", but the actual error is at the call site. With 
"return code=error" the stack trace ends at the invocation of "root", 
where the real error is, and thus "root" would behave more like 
math.sqrt(), where you also don't get a stack trace pointing to the line 
of C code which throws the error.



Indeed, what I'm asking for could be accomplished by
wrapping the body of each function in a try/catch block for an ad-hoc
exception type.


A terrible idea. Why not just write a "validate input" function that checks
your input and returns True for valid and False for invalid, then:

 if not valid(args):
 return

>
> That's little harder to type than
>
>  returnIfNotValid(args)
>
> and much more comprehensible.
>


Indeed, that is way better for this use case. The OP really wants to 
abuse that feature. For statistics, I ran a few greps over the entire 
tcllib:


return   16309
return -code error2271
return -code continue   54
return -code break   7
return -code return 56

Returning an "error" is prevalent, which is mostly used for the case 
described above. Returning "break", "continue" and "return" is used in 
the guts of some parsing engines and in tricky control structures, but 
otherwise very rare. It is also used in Tk code to interrupt a series of 
bindings, and therefore also in Tkinter code (where the string "break" 
is returned)





But again, since the language doesn't have macros


And this is the sort of misfeature why Guido is dead-set against Python ever
getting them.

Yes, we get it that Lisp macros are really, really powerful. But there are two
bottle-necks in coding:

- writing the code in the first place;

- maintaining the code afterwards.

Macros are aimed at simplifying the first, at the cost of the second. That's
not a strategy Python follows.


Abusus non tollit usum. Python already has a macro-esque feature, namely 
decorators. "But everyone can write a decorator which does magic things 
and hide it under an @blabla" - yes they can, but on the other hands 
they allow such wonderful things as asyncio, properties or the numba jit 
compiler. It is never a good argument to say "there is no feature X, 
because GvR is such a god that he knew the feature isn't needed, and 
see? we are doing well without it!". Unfortunately, that logical fallacy 
is heard quite often in this group.


Christian

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


Pandas to_html cannot apply style

2017-10-30 Thread zljubisic
Hi,

the following code never applies style and I cannot figure out why.
Can someone please help?

import pandas as pd

def function2(row):
if row.A == True:
color = '#FF'
else:
color = '#00FF00'

background_color = 'background-color: {}'.format(color)

return [background_color] * len(row.values)

idx = pd.date_range('01.01.2017', periods=7, freq='D')
A = [False, True, True, False, True, False, True]
B = np.random.randn(7)
C = np.random.randn(7)

data = { 'A' : [False, True, True, False, True, False, True],
'B' : np.random.randn(7),
'C' : np.random.randn(7)
}

df = pd.DataFrame(data, index=idx)

df.style.apply(function2, axis=1)

html = df.style.render()

if '#FF' in html or '#00FF00' in html:
print('style applied')
else:
print('style not applied')

Regards.
-- 
https://mail.python.org/mailman/listinfo/python-list