« first day (2386 days earlier)      last day (2555 days later) » 
00:00 - 17:0017:00 - 00:00

12:25 AM
Why won't you answer my question? an excellent writeup on question asking
 
wim
I found it, it's g in the format spec
>>> '{:.2g}'.format(12.34)
'12'
>>> '{:.2g}'.format(1.234)
'1.2'
>>> '{:.2g}'.format(0.001234)
'0.0012'
@AndrasDeak because you shouldn't be doing the maths yourself, that's why we have format
 
 
1 hour later…
1:45 AM
@wim Does format() truncate or round?
@KevinMGranger I get a 500 error :-(
 
2:07 AM
Anyone have any idea how I can trigger a message on my laptop via a python script?
 
print("some message")
 
 
2 hours later…
3:46 AM
how to optimize:
```
if price == 0 or (price < 500 and price > 10):
continue
```
 
Backticks don't work on multiline code here. Just format your code normally and hit Ctrl-k, or the "Fixed Font" button. You still have a minute or so to edit your post.
if price == 0 or 10 < price < 500:
    continue
You could also write that like:
if not price or 10 < price < 500:
    continue
but I think the first version is more readable.
 
You can do 10 < price < 500 in python?
 
Sure!
 
@PM2Ring Thanks for solution and usage in chat.stackoverflow.com.
 
To mean 10 < price and price < 500?
 
3:53 AM
It's called comparison chaining "Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false)."
 
Nice! So much more mathematical than most languages I know.
 
This is quite handy when the middle term is an actual expression, eg a < f(x) < b because it's guaranteed that f(x) only gets called once.
 
Many beginner programmers with a strong algebra background are understandably confused when that notation does not work the way they expect.
 
People coming from algebra have to deal with stuff like x = x + 1, though. So they ought to expect programming languages to be a bit different to what they're used to. :)
 
In Java, C, and C++, for example
Someone told me they had trouble with x = x + 1 and it took me quite a while to understand why. I never stumbled over that.
From my experience most people who do well with math do well with programming, too.
 
4:01 AM
Sure. I remember being amazed in my younger days that I could store the result of a boolean expression, eg a = b < c. I'm used to it now, but it still looks weird to my algebra-trained brain. :)
 
As long as they keep in mind those kinds of differences
Not to mention if a == true:
 
@Code-Apprentice It always disturbs when coders say that they're hopeless at mathematics. I guess they may have just had bad teachers, but if you can't do the kind of abstract yet methodical thinking required to do basic algebra you're probably not going to be a very good coder.
 
Recently, a programmer told me he doesn't use algebra at his job. He did Business in college rather than CS.
His argument was that he never factors polynomials so he doesn't use algebra
I was like if you add, subtract, multiply, or divide numbers then you are doing algebra
 
4:37 AM
> Elementary algebra differs from arithmetic in the use of abstractions, such as using letters to stand for numbers that are either unknown or allowed to take on many values.
So your acquaintance is wrong, but what you're describing is arithmetic.
 
Arithmetic and algebra have a large intersection
 
What Zero said. Still, having some algebra skills is often useful when your program need to perform some arithmetic.
 
@wim but you never said anything about string formatting! :D
5 hours ago, by wim
how to round to 2 significant figures ?
cbg
 
I've seen plenty of code that does arithmetic stuff very inefficiently that can easily be optimised with a little bit of algebra, eg getting the cumulative sum of an arithmetic progression.
 
 
2 hours later…
6:53 AM
cbg'all folks
 
7:41 AM
cbg
 
 
1 hour later…
8:55 AM
morning cbg
 
9:12 AM
hey @Withnail
 
Morning!
 
9:36 AM
Cabbage
 
o/
merry eurogang
 
Thank goodness it's friday.
It's been a busy couple of weeks/months in WithnailCo.
 
10:08 AM
recbg
With the risk of indulging in braggadocio, I just learned this neat word today. @DSM please consider it as my proposal as word of the day
 
Nice.
I like 'transpontine'
 
...what's vappu? :D
 
First of May party in Finland :P
or among students it starts like a week (or a month before) :D
 
Hehe.
 
10:59 AM
Guys, I need some Pandas help
I have a dataframe with a bunch of plants and their number of leaves labelled 'leaves' as a feature
they also have a cluster they belong to as 'cluster'
I want to generate a dataframe with some statistics from that, named clu_df, and I want to calculate the average leaves per cluster
clu_df[clu_df['cluster'] == name]['avg_leaves'] = data[clu_df['cluster'] == name]['leaves'].mean()
this doesn't seem to be working
name is the name of the cluster, in a for-loop
it tells me "pandas.core.indexing.IndexingError: Unalignable boolean Series key provided"
 
11:14 AM
>>> df1 = pd.DataFrame({'a':[1,2,3]})
>>> df2 = pd.DataFrame({'b':[4,5]})
>>> df1[df2['b']<2]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/frame.py", line 2053, in __getitem__
    return self._getitem_array(key)
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/frame.py", line 2093, in _getitem_array
    key = check_bool_indexer(self.index, key)
  File "/usr/local/lib/python3.5/dist-packages/pandas/core/indexing.py", line 1816, in check_bool_indexer
my guess would be that data and clu_df have a different number of rows
in which case you can directly use logical indices of one to index the other, for obvious reasons
perhaps you meant data[data['cluster'] == name] on the right-hand side?
 
facepalm yeah, obviously, that's where the leaf counts ARE
thank you!
 
no worries
and of course when I wrote "can" I meant "can't" three messages above, again for obvious reasons...
 
Yeah, it was a dumb on my part. The clu_df doesn't seem to be updating though
 
perhaps your index series is all False
 
def cluster_data(data):
        clusters = data['cluster'].unique()
        clu_df = pd.DataFrame({'cluster': clusters})
        clu_df['avg_leaves'] = 0
        for name in clusters:
            metric = data[data['cluster'] == name][feature].mean()
            clu_df[clu_df['cluster'] == name]['avg_leaves'] = metric
            print('avg {}: {}'.format(feature, metric))
        print(clu_df)

    to_clu = pd.DataFrame({
        "petals": [10, 15, 40, 35],
        "leaves": [3, 3, 10, 20],
        "cluster": ['pine', 0, 'cactus', 'cactus']
it's not false, I can see it when printing in the for-loop
if I print clu_df[clu_df['cluster'] == name], I see the right row, so I try to update that and it doesn't last
 
11:38 AM
hbase shell is retarded
 
12:01 PM
I have what I assume to be some basic question. I have some function that creates a 2D slice out of a 3D dataset. As it stands right now, I can't really give the slice (xy, xz, yz) as input because I have a line of code

positions_xz = np.array([(x, y) for x, y, z in positions])

where (x, y) decides the slice. Would there be some way to define something like 2dslice = [(x, y),(y, z),(x, z)] so that I could write
positions_xz = np.array([2dslice[0] for x, y, z in positions]) for a xy slice? Positions is something like
 
Guys... can someone help with my thing above?
 
12:14 PM
@user129412 Yeah kinda.
>>> seq = [
...     [2.0, 0.0, 10.0],
...     [3.0, 0.0, 10.0]
... ]
>>> two_d_slice = [lambda x,y,z: (x,y), lambda x,y,z: (x,z), lambda x,y,z: (y,z)]
>>> [two_d_slice[0](*item) for item in seq]
[(2.0, 0.0), (3.0, 0.0)]
>>> [two_d_slice[1](*item) for item in seq]
[(2.0, 10.0), (3.0, 10.0)]
>>> [two_d_slice[2](*item) for item in seq]
[(0.0, 10.0), (0.0, 10.0)]
But you're not really reducing complexity this way, just pushing it around... You still have to write the slice pairs somewhere.
 
@Kevin True. Not a bad solution though! I could give (0,1,2) as input for the function to decide which slice to take.
In the end I could also just write some if statement and write the code three times, but this is already cleaner.
 
>>> two_d_slice = [lambda tuple, i=i: [item for idx, item in enumerate(tuple) if idx!=i] for i in range(3)]
>>> [two_d_slice[0](item) for item in seq]
[[0.0, 10.0], [0.0, 10.0]]
>>> [two_d_slice[1](item) for item in seq]
[[2.0, 10.0], [3.0, 10.0]]
>>> [two_d_slice[2](item) for item in seq]
[[2.0, 0.0], [3.0, 0.0]]
I guess I fibbed slightly when I said you had to specify the pairs manually. You can avoid it... If you don't mind writing monstrous nested list comps.
 
Hmm, yes, I had to think for a bit to understand that one. But that's also cool
 
I had to use .loc(stuff) to use a view, my apologies
 
@user129412 I'm only a beginner with Numpy myself, but I suspect that there are more efficient ways for you to use Numpy. Your positions looks like a Python list containing a bunch of Numpy arrays. It probably should be a pure Numpy array.
 
12:22 PM
morning everyone
 
Morning, corvid.
 
@PM2Ring It is something to look into, although for now the optimization is not so relevant. But still a good idea.
 
Not sure why, but when corvid greets people in the morning, it reminds me of:
 
Generally, if you find yourself using Python for loops on Numpy arrays there's probably a much faster way using pure Numpy.
 
I guess they're both talking animals with cryptic motivations.
 
12:26 PM
Cbg
 
@PM2Ring Back reference to the drummer convo - yes, very lucky - he is something quite phenomenal.
 
I was going for more of this youtube.com/watch?v=eaEMSKzqGAg
 
:)
Mayday on Monday. Happy Snape.
 
@corvid Nope, you're a floating cat potato.
 
@AlexMitan what do you mean "doesn't last"? Do you understand how local variable work?
 
12:30 PM
like I haven't heard that one before
 
@Code-Apprentice Yeah, I do, I printed them inside the function. The problem was rather that I was operating on a slice copy rather than a reference/view
 
@JRichardSnape I really appreciate playing with a drummer who can keep a rock-solid beat. It lets the lead instruments do subtle stuff with the timing.
 
What do you play?
 
@PM2Ring Indeed. Rare to find one quite that accurate. Very rare, in fact. It can make a band so tight. Particularly if the bass player can stick with them. I used to play bass on a lot of swing stuff - when it clicked.... ah, yeah...
Not that I was anything special rhythm wise - as revealed upon recording against a computerised click track.
 
Just got this on youtube's autoplay, which makes me like it way better youtube.com/watch?v=ZWv_2e53MQQ
 
12:35 PM
Is there a name for "a mathematical function that is defined only for integers"?
 
@JRichardSnape And when it doesn't quite click, it's the bass player's job to keep the drummer on the beat. :)
 
@PM2Ring mais oui, naturellement.
 
@user129412 Here's a quick demo:
import numpy as np
# Make some fake data
a = [[i+j for j in (0,1,2)] for i in range(10, 50, 10)]
#Convert Python list to Numpy array
positions = np.array(a)
print(positions)
#Get various slices
for t in ((0,1), (1,2), (2,0)):
    print(t)
    print(positions[:,t])
#output
[[10 11 12]
 [20 21 22]
 [30 31 32]
 [40 41 42]]
(0, 1)
[[10 11]
 [20 21]
 [30 31]
 [40 41]]
(1, 2)
[[11 12]
 [21 22]
 [31 32]
 [41 42]]
(2, 0)
[[12 10]
 [22 20]
 [32 30]
 [42 40]]
@Code-Apprentice These days, I mostly play blues harp. I used to play guitar quite a bit (and bass in my younger days), but these days it's a bit painful on my left shoulder, and my knuckles.
 
@Kevin not that I know
Other than maybe "integer-valued function"
Since we have "real-valued functions"
@PM2Ring the only instrument I play is the radio
 
12:51 PM
I guess "function on the domain of integers" is about right.
 
Yeah, Wiki just has Integer-valued function, but that applies to any function that outputs integers. The domain (the inputs) could be real, complex, or whatever.
 
My first implementation of dynamically-sized fonts isn't going well... I detect window change events, and in response call find_best_font_size, which picks a font size based on the current height of the window. But when the font size changes, the window resizes itself, which fires a change event, which calls find_best_font_size.
 
Oops
 
Resulting in one of these outcomes: 1) the window shrinks as small as possible; 2) the window stays the same size but locks up; 2) the window grows as large as possible.
 
When expanding the font size, choose a slightly smaller size than what the raw calculation suggests (and vice versa) and don't do a font size change if the difference in size between the old & new font is less than a threshold, eg 2 or 3 points.
 
12:59 PM
I could add a flag which would let me know whether any particular change event was caused by user action, and only resize fonts based on that... But it's inelegant. And might cause the window to jitter as the user resizes it.
 
new-gorillaz-album-cbg
 
@PM2Ring Yeah, I was thinking of implementing some kind of hysteresis anyway.
You might get a dozen change events when the user spends half a second resizing, so I may as well not do the full work on each of them
 
@Kevin I've never messed around with that stuff in Tkinter. And I can only vaguely remember how it's handled in GTK. Maybe just wait until you get a mousebutton up event? But maybe the window manager swallows those events when the user's fiddling with the window size...
 
@Kevin that is probably more accurate
 
Hmm, I don't know whether mouseup fires if you're dragging the window frame around and then release the mouse. My guess is "no". But that's only my guess.
 
1:06 PM
I know in GTK that you can switch between getting every change in mouse position vs only getting events when the mouse starts & stops moving, which reduces a lot of pointless events when you don't actually need them.
If all else fails, you could use a timer and only resize the font if a sane time interval has passed since the last time you resized.
 
> Depending on your platform, there may be up to three ways to specify [font] type style.

As a tuple whose first element is the font family, followed by a size (in points if positive, in pixels if negative), optionally followed by a string containing one or more of the style modifiers bold, italic, underline, and overstrike.
Using sign to distinguish between different units of measurement... How very "unique"
 
I can't even remember if Tkinter events contain a timestamp. I expect they do: it's a pretty common thing to do. And it's not exactly modern technology: even the Amiga used to do that.
 
If I set font height to -button_height/2, then I don't get cascading changes, but there's a larger margin around the text than I'd like.
I could find the largest non-cascading multiplier through trial and error, but I'd have no guarantee that it works on any machine other than my own.
 
When netscape / mozilla was being open sourced, the company lawyers made them take out any and all curse words from the codebase. But someone made a diff and kept the list, and it's just resurfaced: (language warning) censorzilla
> # define rename hpux_sucks_wet_farts_from_dead_pigeons
 
The pixel size is probably the same as the point size. The traditional printer's point didn't have a definite absolute size, and varied from foundary to foundary. PostScript chose a standard 72 points per inch, and it's become a defacto standard. That's alright on paper, but how do you apply it to a screen? Well, some systems equated a screen pixel to a point, others assumed that there are 75 pixels to the inch. But that was a few years ago...
 
1:19 PM
r'konto?[-_ ]nummer'
Why does the re expression above not match with: 'kontonummer' ?
 
Why would it? The middle character group matches one of a space, underscore, or dash
 
it's not designed to
 
?[-_ ]
would match one or none of the charecters inside the brackets
 
nope
 
question mark goes after the group.
>>> re.match(r"konto[-_ ]?nummer", "kontonummer")
<_sre.SRE_Match object; span=(0, 11), match='kontonummer'>
Same way + and * work
 
1:21 PM
uh, I see. thanks.
 
\o cbg
 
@PM2Ring They're at least close enough that most people with questions about exactly sizing tkinter fonts will accept answers that set font sizes by point size and not pixel size. This implies at least that the difference isn't noticeable in the general case
ofc you can't be completely sure of the bounding box of the text because "a" has a smaller height than "Ij" despite having the same font size
 
hi
What is the difference between undirected and bidirectional graph?
 
One doesn't have directions and one has directions going both ways
 
There's no practical difference between the two types of graphs, as far as I can tell.
 
1:29 PM
so which one should I use? I want to traverse in all directions in the graph
 
I guess you would draw the latter with double ended arrows, and the former with regular lines?
 
@Kevin Indeed. And variations from font to font can be quite significant, unless the fonts all come from the same source. So you can have two fonts that are supposed to have the same point size but one takes up more space than the other.
 
"Which path should I go down?" asked the traveler. Seeing only one path before us, I did not know how to answer him.
 
Undirected graphs are symmetric: if you can go from i to j you can go from j to i
 
There's always T̻͖̫͇̖͟h͏e͇͘ ̵͕̻̩p̛̰̯ͅa̵̲̻̯t҉̙̙̬̞͓h͓ ͖̼̞̖͞b̤͔̝ͅe͢t͓̖̗w͚e̝̞̜̩̥̕e̖̬͔͙̯n̻̹ ̩͎̺͈͎͕t͍ḥ̞͓̲e̴̝̝̬̣͓͖ ̭̖̯r̻̕oa҉̪̪̥d͕̟̹̟͓s̭,̣̙̭͇ ̧̘̜͍͇̱b͔͚̥͇̩̬͢ḛ͔͚̫̲t̜̕w̡̞͈̼̩̲ȩ̻en ̧̟̫t͘h͈̪͎͈͖͙e̙͕ ̜̣̺͢w̜̗̝͝a̹ĺ͚͎͈l̬̭̞̭s͕̕,̨̰͕ ̼̦͔o̘̙̗̪̣u̠̣̰̮̭̩̜̕t҉̲̰͈̥s̷̜͚̘̼i͕̦̥̼͈͕d͓͖̤̖͘ẹ̳̘ ̝o̡̘f̪̭̙ ̰̩̣͇̫̙o̙̞̮̦̯̕u̩̱r̫̯̼̭̻͎ ̧̬̹̮̗̯͇f̯̪̖̬͍͔͙e̫͓̩̻͖͢e͏̣̘͖̼͚͉͍b͏͍͕l̼͉͍̱͉̝ͅe̖ ̴̺̠͕͔̮͈̠u̩̗͙͠n͓͔͈͚̘i̟̞v͎̼̰̮̦͈̳e̴̞͙̜̯̺̹̝r̠̱̻͇̻̫s̵͙̘͓e͉̠̝̱ͅ
 
1:31 PM
@jason If you're asking "when I implement a graph class for the problem I'm working on, should I name it 'undirected' or 'bidirectional'?", I like "undirected" because it's easier to type.
 
If you need asymmetry, go with directed. Otherwise undirected.
 
If you're asking "which of the two existing graph classes should I use? Undirected or bidirectional?", my reply is, "what two existing graph classes? There's nothing like that in the standard libs"
 
@Kevin I'm asking the 2nd one
 
If you're using a third party library that implements both, that would have been useful information to provide at the beginning of the conversation
 
I'm using QuickGraph library which is a C# library. It has two different implementations for them
Sorry, I didn't guess that would matter
 
1:34 PM
Sorry, maybe I'm being too demanding.
It's reasonable that from the question-asker's POV, it's not necessarily apparent what information is necessary to answer the question. If they knew that, then they probably wouldn't be asking.
 
At this point if you needed a directed graph, you'd know it.
 
I definitely don't need a directed graph
 
What is the basic atom of information? "A and B are connected" Or "there's a path from A to B"?
 
I'm looking at the documentation for the quickgraph bidirectional graph. It looks like it allows you to have different edge values for "out" and "in". So traversing from A to B may have a different cost than traversing from B to A.
My opinion is: if you need different weights for A-to-B and B-to-A, use bidirectional. If edge values should be the same regardless of direction, use undirected.
 
@AndrasDeak they are just connected, but I will need to use BFS, DFS, Dijkstra's etc.
 
1:37 PM
If you don't have edge values at all, also use undirected.
I typically implement graphs with regular dicts. {"a": {"b", "c"}, "b": {"a"}}, kind of thing.
Perfectly serviceable if you don't mind writing the traversal algorithms from scratch.
 
ok I will go with undirected, thanks a lot
 
I'm a little worried because the QuickGraph documentation page for undirected leads to a "page not found" message.
I'm not clear on the difference between undirected and quickgraph.codeplex.com/wikipage?title=AdjacencyGraph
 
@Kevin you followed the wrong path :D
 
Actually, if you don't have edge costs, I guess Adjacency graphs are better.
 
@Jason you should study about graph theory while you are at it, at least to understand the basic mathematical terminology and definitions
 
1:44 PM
Assuming that the undirected graph class stores edge values, and the adjacency graph doesn't. It's hard to compare them thanks to the spotty documentation
 
Hi folks!
I'm trying to help a python project in solving a problem I've encoutered.
http://stackoverflow.com/questions/43501106/transferring-files-with-pysftp-get-r-between-linux-and-windows/43502128?noredirect=1#comment74096482_43502128
But I don't know where to start.
I mean.
There is probably a standard library that, if put in the right place, will solve the issue.
I just don't know where to start looking
 
Hmm, I was under the impression that windows interpreted both slashes and backslashes as separators.
>>> with open("desktop/foo.txt", "w") as file:
...     file.write("blah")
...
4
>>> with open("desktop\\bar.txt", "w") as file:
...     file.write("troz")
...
4
Yep, works on my machine.
 
Well, but from the little I know, it is possible that you're using some standar library not in use by the pysftp implementation
 
That would surprise me but I suppose it's not impossible
It seems unlikely since I can tell from the stack trace that they're calling open the same way I am. They'd have to go out of their way to override open's behavior
And in doing so, intentionally make it worse
 
@LuizAngioletti Python uses the OS's standard system calls to do stuff like that. There's a tiny bit of Python stuff involved, but the bulk of the work is handled by the OS just as if you were doing it from C.
 
1:58 PM
@Kevin That would be an act of open rebellion. Which, as any infant teacher knows, should be squashed immediately.
 
Hmm, does os.mkdir ever raise an OSError for a reason other than "the directory already exists"?
 
I think you've misdiagnosed your problem
 
Insufficient permissions, perhaps?
 
Because the pysft code assumes that's the only possible reason
 
@LuizAngioletti However, I wrote that post before I looked at your question. :) And now I see you aren't simply reading or writing a local file. I can understand Windows getting a bit upset at a mixture of slashes and backslashes in a single file name.
 
2:00 PM
If it fails for some other reason, perhaps a permission issue, then the try-catch will happily silence the error and move forward with program execution under the assumption that the directory exists and everything's fine
 
It's trying to open a file that doesn't exist. I don't think it cares about the slashes.
If it's trying to replicate the remote directory structure locally, it has failed.
IMHO
 
Yeah I'm putting my money on "it's failing to replicate the structure of the remote directory"
 
Possibly silently and earlier in the code.
 
Is it too early for me to suggest switching to linux as a solution
 
but a plain old open won't try to create the directory if it's not there.
 
2:02 PM
It definitely silences errors during directory creation, as demonstrated by my link
 
Does pysftp normally create directories if they don't exist?
 
Never to early for the "Use Linux" solution, Kevin M
 
It does create the directories, as demonstrated by my link.
 
PM2 asks the crucial question.
Kevin manfully continues with the assumption that anyone has clicked his link ;)
 
docs.python.org/2/library/os.html#os.mkdir says "If the directory already exists, OSError is raised." Which might be interpreted to mean "if and only if..."
Perhaps wrongfully interpreted.
 
2:04 PM
A total guess
 
Exercise for Windows users: fiddle with permissions until you can get an os.mkdir call to fail.
 
the path_advance that sftp is using inthat loop only looks for OS specific separator
therefore, sees the whole path as a dirname on windows, tries to make it, isn't allowed, hits the error path and assumes it already exists.
I hope that's right. It will enhance my self-image as a psychic debugging machine tries to avoid being nerd-sniped into code diving
 
I might suggest filing a bug on the project page, but it looks like it's gone quiet for the last nine months
 
 
2:10 PM
@JRichardSnape well.. I don't have a linux machine available to switch to...
 
As you're on windows it will try to split the path on \` so will try to mkdir` on test_sftp/n1/M51, which will fail
And be assumed
to exist
 
Nice find
 
@Kevin I've seen that too
 
In that case, patch your pysftp locally - change the path_advance function in helpers.py to use either separator
OR
 
Now I must tearfully retract my statement that the problem probably has nothing to do with slahses & backslashes ;_;
Let it never be said that I can do no wrong
 
2:13 PM
patch that whole loop in Kevin's link out to use os.makedirs() instead of mkdir in a loop
 
@Kevin well you are a windows user
 
Thanks, people
 
@Kevin I, for one, promise never to say that you can do no wrong.
 
Cool thanks
 
I might even try to submit a bug and a bug fix, even though I'm very noob in coding projects
 
2:13 PM
:D
@LuizAngioletti Do it - very good for the open source community. If you do, worth putting the link here and you might well get some helpful reviewers :)
 
I looked briefly at the issues page and there was another guy with a get_r problem, and he said "here's how I'd fix it, I'm too lazy to write a patch" and the code he wrote mostly matches with what's in the source now, so maybe the author is reading issues but not closing them for some reason
 
Maybe so.
Mmmm, looks like there's a lack of activity in there. There's a pull request hanging around from Nov 2016 which sould fix a very similar issue with put_r - bitbucket.org/dundeemt/pysftp/pull-requests/11/fix-for-issue-69/…
Not a great fix IMHO
 
2:48 PM
I should figure out how super works.
When you're in Foo's class definition and you call super().blah(), how does it know to look for Foo.blah? Literal magic?
Call stack analysis shenanigans, perhaps? I don't know if I approve of that.
 
If you're in Foo, calling super().blah() would not call Foo.blah
 
Oh, duh. Let me revise the question.
 
would call object or what ever the parent it inherit from, no ?
 
It "just" removes it from the MRO. I think it's actually trickier than that but I'm not sure. If you listen to the episode of Talk Python To Me with Martijn, they mention it
 
When you're in Foo's class definition and Foo inherits from Bar, and you call super().blah(), how does it know to look for Bar.blah?
 
2:53 PM
looks up foo.__mro__ and calls what's next in line, IIRC
 
But how can super get a reference to foo when you pass it no arguments?
 
class Bar:
    def blah(self):
        return 23

class Foo(Bar):
    def blah(self):
        return 42
    def zort(self):
        return f().blah()

x = Foo()
print(x.zort())
Exercise: in the above code, implement f without using super so that this program prints "23"
And don't just do f = Bar. You know what I mean.
 
def f():
    return Bar()
 
do you mean super().blah()
 
2:58 PM
If you're saying "that code you just posted doesn't work because f is not defined. Did you mean to write super instead of f?", no, I intentionally left super out because the point of the exercise is to demonstrate that it's hard to get super's functionality without using super.
 
It's not that hard to get super's 2-arg functionality, though
 
Or if you're saying "do you mean that f().blah() should have identical behavior to super().blah()?", yes, that is my intention.
 
oh so your asking how to replace f() to make it work like super()?
 
Yeah.
 
You can't. zero-arg-super is magic. Two-argument super is not magic.
 
2:59 PM
@KevinMGranger Agreed.
 
And by "magic" I mean uses some attributes defined at class creation time, but, you know, magic.
 
if you will let us fill blah() with a self argument... but I'm not sure if that's cheating or not
best I can think of is: but it's not what you want... I dont think ...
def f(self):
    return self.__class__.__mro__[1]()
 
It's cheating. You can't have any arguments.
I worked along similar lines and got:
 
Yes we can.
 
def fakesuper():
    return inspect.stack()[-2][0].f_locals["self"].__class__.mro()[1]
 
3:09 PM
Oh jeebus you were serious, I thought it was a rhetorical question
 
Which still isn't quite right because it only returns Bar, not a Bar-like object that you can call blah on and where self will point to the right thing
 
Need to go digging for the super() source code ...
 
Also I think my stack indexing might only work if you call zort() from the file level scope
And even if I did bind self to Bar properly, it still doesn't exactly mimic super's behavior, because if Foo has two parents and only one implements blah, then super().blah() will work properly* and fakesuper().blah() would fail half the time.
(*If I understand the behavior of super, which I have already demonstrated that I don't)
Also it fails if you don't use the conventional name "self" for the first argument of your method
 
There's a Martijn answer that explains how zero arg super does its magic, but I'm on my phone so it might be tricky for me to find it.
 
A google for super martijn site:stackoverflow.com reveals stackoverflow.com/q/19608134/953482
 
3:14 PM
Time to read and learn I guess :)
 
But it involves stuff that's impossible to do with pure Python, IIRC.
 
Looking at his answer, the short answer appears to be: Python looks for functions named "super" and slyly makes __class__ available to them
Possibly using frame inspection shenanigans similar to what I just had
 
> Congratulations, you've found another reason for me to dislike the implicit hidden closure creation utilised for super(). – Martijn Pieters♦ Oct 26 '13 at 14:59
I love his comment to zero's question :D
 
@Kevin Yep, that's the one I was thinking of.
 
cbg
 
3:22 PM
I think I had a hard time remembering the proper usage of super because the zero argument form could not be implemented using only conventional progamming techniques. So my brain rejected it the same way that chess masters have a harder time memorizing impossible board states compared to ones that are likely to occur.
Perhaps now that I explicitly know that the compiler cheats, I'll be able to properly mentally model the behavior of the function and remember it.
But I have a nagging feeling this isn't the first time I've had this conversation...
Sometimes I wonder if people are as frustrated as I am when I consistently fail to learn something after several attempts. One might say that the journey matters more than the destination, but sometimes it feels like I'm journeying on a hamster wheel, which is not terribly fulfilling.
3
 
at least you get fit on the process. you get better at "learning" even if you don't learn anything
 
What's the problem with super()?
 
nothing - it's magical
 
wim
3:44 PM
10
Q: Schrödinger's variable: the __class__ cell magically appears if you're checking for its presence?

wimThere's a surprise here: >>> class B: ... print(locals()) ... def foo(self): ... print(locals()) ... print(__class__ in locals().values()) ... {'__module__': '__main__', '__qualname__': 'B'} >>> B().foo() {'__class__': <class '__main__.B'>, 'self': <__main__.B ob...

user2357112's answer here is instructive about how super does the magic
 
There's basically something I've got to be doing wrong...
 
It's not clear to me why you would need to add __class__ to the method that calls super, and just not to super itself, but who am I to question the devs
 
In pandas, what's the easiest way, out of an existing dataframe, say 'iris', to make a dataframe of statistics per species, with columns like 'species', which is the grouping criterion, and also avg_height, avg_length, etc. for any number of features?
 
Perhaps itertools.groupby would be useful? Not sure if it plays nice with dataframes.
Don't listen to me, I don't use pandas.
 
DSM
@AlexMitan: this is a pretty straightforward use of groupby. The docs cover some similar cases.
Right-before-lunch cabbage for all.
 
3:55 PM
cbg \o :D I get to be stuck in a meeting for lunch oh joy..
 
I know, I tried, but I can't seem to manage to generate some straightforward data... after the join with groupby, the columns are left the same name
I don't want 'leaves' after the join, I want 'leaves_mean' or 'leaves_median''
def cluster_data(data):
        clusters = data['cluster'].unique()
        clu_df = pd.DataFrame({'cluster': clusters})
        means = data.groupby('cluster').mean()
        print('means')
        print(means)
        clu_df.merge(means, on='cluster')
        print('joined')
        print(clu_df)

    to_clu = pd.DataFrame({
        "cluster": ['pine', 0, 'cactus', 'cactus'],
        "leaves": [3, 3, 11, 20],
        "petals": [10, 15, 41, 30]
    })
    cluster_data(to_clu)
on the merge line, can I tell it to basically bring in the columns from the right, but with a suffix or prefix?
 
Just rename the column afterwards?
 
Yeah, but I can have any number of columns, that's the thing
 
Rename them all? :P
I don't know, sorry:)
 
can I at least name them differently in 'means'? with a suffix? preferrably without a peasanty for-loop?
 
wim
4:01 PM
@Kevin I don't think you get it ... super needs the mro
for all practical purposes, you could think of the __class__ as being passed as an argument to super, implicitly. Instead of via a magical closure variable.
 
I acknowledge that super needs the mro. I think I'm misunderstanding what is meant by "closure" in this context.
 
wim
so you can't have def fakesuper(): , you need to take an argument
and even the zero-arg form super() takes an argument , via the closure variable
so to say taking an argument is cheating , then super() itself is cheating
 
DSM
@AlexMitan: merge doesn't act in-place. So I'm not sure what the end of your code is testing.
 
I think merge does.. either way... I guess a better question is "how do I rename all but one of a frame's columns?"?
 
wim
@Kevin closure:
def foo():
    var = 'potato'
    def super():
        print(var)
    super()

foo()
super has access to the var 'potato' via closure
 
4:05 PM
So super is acting as though it were defined inside the method that's calling it, effectively? At least as far as name resolution is concerned.
 
wim
yeah, it's exactly the same with zero arg form of super, using __class__
Martijn's answer is hand-wavy and doesn't really explain it at all, he just talks about the history
This answer is much more enlightening, imo
 
It's a little odd but I guess it's not an unreasonable way to implement it
 
DSM
@AlexMitan: yeah, I'm pretty sure it doesn't. :-) You can rename all but one using something like
In [9]: df.rename(columns=lambda x: x + '_mean' if x != 'A' else x)
Out[9]:
   A  B_mean  C_mean
0  1       2       3
1  2       3       4
2  3       4       5
but I don't know if you're going down the right path here.
 
Insofar as magical functions are reasonable at all
 
wim
in particular the part at the bottom where he shows that making __class__ be a local variable instead of a closure variable, it breaks super !!
 
4:08 PM
I feel like I should write that down for later usage in a Python riddle
 
Thank you, @DSM!
If I want to iterate through rows should I do 'for row in frame.values' or should I iloc? I'm doing k-means, so I just need raw data
 
user6845426
4:38 PM
cbg
 
Does anyone else think non-inclusive ranging and slicing is a bit unnecessary? I mean it works fine inclusively on pandas, right
 
The nice thing about non-inclusive is that range(y,z) and x[y:z] will both have a length of z-y.
Dijkstra had a nice little article about this, available at cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html
It's also nice that x == x[:z] + x[z:], which wouldn't be true if we used exclusive-exclusive slice boundaries or inclusive-inclusive ones.
 
I wish I could communicate this to end users, but making an interface with "the end date should be the moment after the event is over" just doesn't fly.
So instead we have to remember that all user data is inclusive-inclusive, but all internal data is inclusive-exclusive.
 
:-I
I once used event planning software and entered an event occurring between 8:00 PM and 12:00AM and I was annoyed that it recorded it as "from 4/28 to 4/29". It was not a two day long party. I changed the end time to 11:59 PM.
 
4:53 PM
an extra use case for that issue :\
 
cbg
needed a quick help
lazania
 
Mm, lasagna.
 
Hi,
anyone managed to work with PROXY Authentication box with python code in Chrome ?
it work for me if i manually enter username&password and i can see my IP using the proxy server but can't find solution to do it automatically using selenium..
any help will be very appreciate .
thanks,
 
Can't say I know anything about Selenium.
 
> It still works fine for me, I've tried it.
 
00:00 - 17:0017:00 - 00:00

« first day (2386 days earlier)      last day (2555 days later) »