« first day (3071 days earlier)      last day (2102 days later) » 
00:00 - 23:0023:00 - 00:00

00:00
@roganjosh at work there was someone talking about it, I think it relates to making a part of the website, such as pictures, load only after everything else has loaded
it gives the user a perseption that the site loads fast, when really all its doing is managing what it loads when, sounded pretty cool :)
Too front-endy for me to care too much about until it bites me :) I know about lazy evaluation but I only know enough front-end to make things work :)
ok cya
haha
00:14
Testing the limits of 'Be welcoming'... this is seriously uhh incoherent.
@smci I think the rules you contravened are only the chat room rules for posting before 10 mins was up. The main feed is probably 80-90% of questions like that now.
If that is near the limits of being welcoming then I must be a rude jerk
It's a game of holding your nerve, and your comment isn't (to me) near rude
@roganjosh Oh sorry, I wasn't aware of that rule, apologies. But after waiting 3 min it didn't become coherent either. I'm not being rude to OP, just helpfully telling them straight up that noone (non-telepathic) will be able to understand. My point was that the OP was straining the limits of 'Be welcoming' in the coherency dept... but I'd help them if they clarified it.
@AndrasDeak that's an anagram of 'Y riffle'...
Meh, not a room mod. It was more to say that I don't think you were rude or that these kinda questions are abundant now.
00:28
@roganjosh If that is an official rule, it should be added to the room rules. I didn't know of it until now.
@smci it is in the rules that are linked-to from that page
Actually, I may have been pushing the cv-pls rules a bit there myself
@roganjosh No, I never called for a cv-pls. I actually hoped people would engage with the OP and persuade them to state things more clearly. Do not infer 'cv-pls' unless someone says it...
See my previous comment. But I suspect it will get closed, and I did engage with the OP. But you're correct.
00:44
@JackStout and all, thanks for the tip that pathlib replaces the soup of os.*, os.walk.*, glob.* we used to have to do, also more OS-independent. So that old kitchen-sink answer needs to be tidied up for 3.x and have the pathlib parts hoisted up above all else.
01:34
I’m still waiting for a cryptography expert to start shooting holes in my encryption recommendations post. No bullets so far.
02:04
@MartijnPieters I found that post very informative. +1
 
4 hours later…
05:49
@MartijnPieters I know a little bit of crypto, but I'm certainly no expert. But that answer looks fine by me. And it's lightyears ahead of those old answers suggesting ECB, and encryption of the password instead of proper hashing.
06:31
I'm surprised nobody answered with some one-liners, as was asked: stackoverflow.com/questions/2490334/…
 
2 hours later…
08:36
@MartijnPieters in general, IV reuse is fine if you don't reuse the key
@vaultah yup, but they are reusing the key...
@towc they are not asking for one liners. They want a simple function.
And Fernet is the best simple-function crypto currently available.
09:12
@MartijnPieters yeah, I just thought that that part is too simplified, especially since the answer also recommends random keys
I'm nitpicking, I know
09:51
@vaultah you’d generate a key once
@vaultah the password option generates a key, but the password used to generate it is still fixed. And I’d rather not weaken Fernet here any further
I guess I'm just bad at explaining myself. Sorry
@MartijnPieters what do I flag with if I find an answer that is a verbatim copy of an existing answer?
10:11
does anyone understand this question? stackoverflow.com/questions/55159469/…
10:30
@johnsmith voting to close as no MCVE; the OP seems unable to understand feedback
@Arne often vote to close the question as a duplicate -- remember, "duplicate" really means "same answer", not "same question"
10:53
Alright, in that case
@amcgregor our very own deceze!
@Arne custom mod
Alright, that's what i ended up doing anyway
plagiarism and missed dupe opportunity
Mods usually delete the answer and hammer the dupe if applicable
Depends on whether the answer authors are the same
(because the same author posting the same answer on multiple questions might stretch the concept of a duplicate a bit, but a user copying someone else's answer from another question will almost certainly go for an exact dupe)
11:37
@Arne Hammered
Sam
Sam
Anyone familiar with the anytree package? I'm having difficulty trying to search tree's by custom attributes
I'm creating nodes using a custom attribute "panel" Node('name', parent=root, panel=1) for example
the panel parameter isn't a default by the class so I guess it's being passed by **kwargs ?
@PM2Ring thx =)
12:16
@Arne flag it as a straight-up copy without proper attribution. While copying SO posts is permitted under the CC license, there was mo proper attribution, the post was not marked as a quote, and we want people to write original works where quotes are merely thee to support the answer, not be the answer.
Have we got a canonical dupe target for "what should I do if my console window only appears for a fraction of a second when I double-click my program?"? I don't feel like explaining how cmd works from the ground up.
I'd be tempted to write one up if I knew how to open consoles on macOS and Linux. As is, I could only write one third of an answer.
I need an advice on how to find simple cycles in directed graph effishiently
12:29
@БеляковаАнастасия Hi! That sounds like something that has either generic algorithms (independent of language), or specific implementations in the graph framework you're using, if you're lucky
The matter is that graph is quite large.
The topmost answer assumes the user already knows what a command prompt is and how to open one. The second answer gives instructions on how to open a command prompt in Windows, but not in any other OS. So they're in the same situation I would have been in.
@AndrasDeak Yes, I found some but they do not work with my too large graph
It has hundreds of edges
so...perhaps you should share what doesn't work so that others who know about graph theory won't suggest that only to learn that you tried that to no avail?
Maybe there shouldn't be a Q&A dedicated only to teaching how to open a command prompt. Strictly speaking, it's not a programming question. the quality of "is a useful resource for techies" is necessary but not sufficient for a piece of information to be on SO
12:33
@Kevin good point: try superuser
They do work with smaller graphs
they hang and are inefficient on large
I understand that.
it's actually pretty difficult to explain how to open a terminal on linux... it depends not only on what terminal you have installed, but also your desktop environment...
@БеляковаАнастасия They don't provide something like limit or max_depth?
Nope, nothing like that.
12:38
Meanwhile there's a whole bunch of OSes that boot directly into a terminal window. Lucky.
"How to open a terminal window in Unix Deluxe Graybeard's Edition: press the power button"
(step 0: endure a lecture about how U.D.G.E. doesn't have a concept of "window")
@Arne I don't have time to write an answer to your question right now, but long story short: exec(obj) is like calling the function, not like defining the function. You can use the code object to instantiate a function through the types.FunctionType constructor, but that won't work if the function has any default arguments or the like (because those aren't stored in the code object).
The easiest way to get access to those functions is probably the ast module. Parse the code, look for function definitions, compile them, exec them, and you're done
@Aran-Fey I had hoped I don't need to use ast, the last time I tried to understand it it felt like I had to handle 8 edge cases for every single thing I tried to do.
But if I have some time I'll try to get it to work, thanks for the input!
13:00
I feel like it's hard in the general case to extract function definitions from a code object because they may depend on on values that are only present in the function's original context. If you have x = 1 and def foo(): return x, if you only exec the latter, then you'll get a NameError when you call foo.
damn python and its implicit read-only scope mangling!
But it's fine in my case, since I control the code and can stop something like that
Incidentally here's a fun* quirk of the name resolution system:
def a():
    x = 1
    def b():
        return x
    del x
    return b

x = 2
print(a()())
Result: NameError: free variable 'x' referenced before assignment in enclosing scope
now that's just mean
well that's Rube Goldberg's footgun
like dangling a sweet in front of a child's face, just to yoink it away when it tries to grab it
13:07
@Kevin That's after everyone brings a part of the plane, there's at least a year of debate over design patterns, and at least two participants have finally managed to build their seats.
#UNIXAir
@Kevin That actually makes sense, given you're pulling the rug out from under it by deleting the label prior to any chance for the enclosed scope to actually use it. Similar in "gotcha intent" to my esolang's scoping rules. >:D
(Also similar to the trap for new players of assigning mutable argument defaults.)
Someone should make a Python scoping the Shining comparison. global? Don't be the axe murderer. ;P
This example shows a glimpse of how the sausage is made since evidently name resolution doesn't happen 100% at runtime, or else b would simply return the topmost-scoped x object
"b would simply return the topmost-scoped x object"

What's calling B in a timely enough fashion so as to grant that inner return access to that variable? Nothing, that's what. That variable is gone after b's inner definition, and _long_ gone by the time of execution by `(a()) ()`.
It's like issuing a del somedict['x'] and expecting x to remain somehow. Quite literally. ;^P
I am not sure if I have conveyed myself properly. Rephrase: the x local to a is certainly dead by the time b executes. But the global x is both alive and ostensibly visible from within b. So it is surprising that, when b cannot find a binding for x within its own scope or within a's scope, it doesn't go one scope up to find the global x.
Cabbage
I believe that's a trip-up of an optimization for efficient MRO-like label lookup. Specifically, once x is redefined within a, both a and b lose access to the global, unless not del'd, but global'd again.
Del eliminates the label from the scope, it doesn't reinstate inheritance of that label.
(For example, get rid of the x = 1 and keep the del. You'll still have the same problem.)
13:25
I learnt named tuple just now and it is so much fun.. however, can someone tell me a real life usage where I should probably use one?
I have issues not knowing where to use half of the things i know about python
@amcgregor Right. And I believe compile-time scope deduction is also necessary in order to get closures to work properly.
Example:
def c():
    y = 1
    def d():
        return y
    return d

y = 2
print(c()())
@Anarach I have a protocol for path dispatch (object resolution by hierarchical name) that in v1 had "events" being generated for each step of descent that were tuples.
@Anarach With a desire to customize these events and provide additional detail, as well as re-use the "event" for discovery/introspection, not just dispatching itself, v2 uses a custom named tuple providing substantially finer detail.
(Previously recommended was partial unpacking, a la foo, bar, *baz = mytuple, to allow for extension. But that got silly fast.)
@amcgregor How do I say that I am dumb! so as to not annoy you into giving a simple answer..
I think I should not use the terms "Real life " anymore in this chat. :-D
^_^ No worries, and apologies. I'm… not the best for quickly summarizing things. I'm too verbose. Basically, tuples themselves are only "extensible" by having optional trailing elements. E.g. most "events" are three-tuples (path, handler, is_endpoint), and unpacking these during iteration was fine, until I wanted to add additional information about the endpoint as part of dispatch. The example being the "options" value added to the named tuple representing the HTTP verbs allowed there.
(GET, POST, etc.)
Ok...
13:36
@Anarach Many of the existing use cases of namedtuple were taken over by dataclass
I have no background in web programming , I used to monitor COBOL scripts on a mainframe.
To clarify "partial unpacking", unpacking a 3-tuple would look like: path, handler, is_endpoint = event — if you have additional optional elements, to be safe (since you can't know from iteration to iteration of a for loop how many elements there might be) you unpack, then tell Python to "collect whatever remains and drop it in another variable": path, handler, is_endpoint, *extra = event. The 4th (and any subsequent) element will form the extra tuple.
I'd actually discourage using namedtuple, unless you are very sure that it is the right tool for your problem, mainly because it has a different metaclass than python's base object, which can trip up devs that are not familiar with that fact.
@Arne Though dataclass doesn't inherit tuple's singleton-like behaviour, correct? For events like the ones I'm generating, de-duplication is highly efficient given the "routes" will be effectively fixed during runtime.
And yeah, the metaclass difference is weird to deal with. __new__, not __init__ for tuple subclasses.
@Arne No worries there mate, no idea where to use them , I was just going through this Corey schaffer's tutorial on YouTube and my knowledge is limited to that..
I liked how he uses named tuples instead of dictionaries(which seem a pain compared to the dot notation these babies provide)
13:40
@amcgregor I haven't tried it yet, but using a slotted dataclass in conjunction with dataclass.astuple() might be comparably efficient. But at that point namedtuple is probably less confusing again.
@Anarach There's a really, gob-smackingly simple hack to make any object an attribute access dictionary. >:D
class AAD(object):
    __getitem__ = object.__getattribute__
    __setitem__ = object.__setattr__
    __delitem__ = object.__delattr__
Don't do exactly this, of course. (Gotta translate those AttributeErrors into KeyErrors!)
@amcgregor .. or dataclass.make_dataclass =D
My god , I cant even understand what solution you guys are giving , I am grateful for these guys , wont waste your time on this.. thanks again , i will probably drop by after i learn some more..
To, uh, self-stroke some ego, it's impressed me what has eventually made its way into the STDLIB that was independently developed years and years prior. Dict sort persistence, descriptor protocol announcement of assigned name, object protocol announcement of subclassing, …
… ultra-modern Python 3 has managed to deprecate ~80% of my declarative schema project.
Not all of it, though. The dict order thing, for example, doesn't provide for the pattern from my declarative library where subclass redefinition preserves the original order of that key. E.g. (a, b, c), subclass re-defines (b), instances thereof still have (a, b, c) ordering.
13:47
@Anarach I personally welcome questions like yours. It invites useful and fun chat, usually =)
@Anarach ._. apologies again — the code sample and ravings of mine from the last few have been relating to treating an object as a dictionary, or a dictionary as an object, where keys are accessible as attributes. (Think: JSON "objects".)
@amcgregor Oh oh .. dictionary as an object?? how do i do that??
oh wait , I should probably google it
@Anarach Similar to the code I've already given, but flipped. Instead of including getattr/setattr as dictionary access methods, include dictionary access methods as attribute access methods.
class AAD(dict):
    __getattribute__ = dict.__getitem__
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__
With the same warning to not do literally this, but instead translate any KeyError raised into an AttributeError.
@amcgregor hah..
nice
@amcgregor deprecate or obsolete?
13:53
@AndrasDeak Both. Directly replaced things were obsoleted, my method of preservation of attribute ordering on redefinition deprecated—that'll be potentially going away in a version or two if I decide to actually embrace these new protocols and behaviours. Instead of, y'know, reinventing the wheel.
why do I think you'll do the latter? :P
When I ran my own development company, my motto was literally: Re-inventing the wheel, every time.. ;P
Ever wonder why wheels are so popular to reinvent? Because there actually is a use for square wheels, if you have a very specific problem. (Dang, couldn't inline this…)
But then 20 years later you just order a set of Square Rollies from Goodyear
If you have perfect abs(sin(x)) washboard roads, yes, square wheels are literally optimum. The wheel becomes the "road", and the road the "wheel".
Bah, I got sucked into a meeting before I could describe my example. When c() finishes executing but d() hasn't executed yet, Python needs to know whether y's refcount has dropped to zero. If Python knows at compile time that d is referring to c.y and not global.y, then it knows that c.y's refcount isn't zero until d gets collected. If there wasn't any compile time scope deduction at all, then it can become quite expensive to determine whether any still-living scopes have a closure on c.y.
14:03
Speaking of dicts, I just got an upvote on this old thing
Reinventing stuff can be a good learning experience. But often, one of the most important lessons you learn is why the standard wheel does it the way it does, and that your alternative is sub-optimal. But not always.
I learn most efficiently by constructing a crossbow out of materials sourced from my backyard and firing a bolt into my foot
Greenspun's tenth rule of programming is an aphorism in computer programming and especially programming language circles that states: Any sufficiently complicated C or Fortran program contains an ad-hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.
@Kevin Ah. That explains the limp. ;)
If Kevin ever decides to make a language based on lisp he should call it Limp
I was playing around with a parser for lambda calculus the other day...
Naming things is hard. Searching around for a name for my own language, I was inspired by some science fiction (credit to John Todd) where Clueless was the name of a language that was… shockingly hands-free… and had the capability to simulate objets or whole people, in reality. A holoDECstation language.
> Source code may be entered using emacs or another texteditor and then compiled using the command `clucomp -i <filename>`.
>
> **NEVER** use clucomp without the `-i` flag.
14:16
I'm still confused that they passed up on the joke of calling it "Lipht" from the get-go
clucomp </usr6/pub/anime/dp.005oav.gif|fbps>~/dp.PS

WARNING!  Two separate entities--divided successfully.
WARNING! Insufficient data. Auto-crosschecking: please wait:
checking: dp.beverly.gif
checking: dp.bikini.gif
WARNING! Extraneous entity ignored!
checking: dp.calender.gif
checking: dp.chased.gif
checking: dp.cycle.gif
checking: dp.dressing.gif
WARNING! Significant deviation from previous data!
disregarding discrepant data.
checking: dp.gunpod.gif
WARNING! Significant deviation from previous data!
^ And one of the main characters brought Kei and Yuri of Dirty Pair to life, and hell proceeded to break loose.
@Arne lithp?
That makes more sense
jup, now the joke is that I can't spell correctly
pretend we're laughing with you
14:32
Ahola all - just thought I'd update those interested - adding multiprocessing to my bot improved scan times by around 2.7x
Pool size of 3
Leaving one free for the OS to use
So thanks to all again for the suggestions :)
sounds great, glad it worked
congrats, improving a python program by introducing multiprocessing is a notable feat in my book
@AndrasDeak Finally something I'm good at :p
Meh, it depends on the problem. They had a CPU-bound loop.
which is not to belittle CalvT's achievement, just saying ;)
I've successfully improved Fourier transforms with multiprocessing, which is a trivial use case for dumb parallelization
@Arne Thread parallelization of my Okapi BM-25 algorithm implementation quadrupled ranking throughput; never did figure out why it was so beneficial in that scenario, the calculation is pretty tight math. Absolutely independent per document being ranked, of course.
I do like to hear success stories. My default assumption is that all help seekers end up at a Nighthawks-esque cafe, looking out the window at the pouring rain while they internally monologue "where did it all go wrong? It all started when I went into the Python room...". Possibly they have an eyepatch.
14:44
And ornery pet sugar glider, also with an eyepatch, as likely to bite you as let you scratch its chin.
You and the sugar glider both have a cup of coffee. You take yours black. The sugar glider prefers a 1:1 ratio of coffee and sugar.
(This joke predicated on the unfounded assumption that sugar gliders like sugar)
Sap + nectar dominates its diet, so yup. Glucose fiend. XP
If their natural diet is sweet-tasting goop, perhaps tea with entirely too much honey would be their vice of choice.
"That stuff will kill you", you tell the sugar glider. It chitters and gestures towards your smoldering cigarette. You chuckle. Looks like this canopy dweller has the high ground once again.
15:06
@Kevin I take Dennis Leary's stance on smoking. ;)
> Smoking takes ten years off your life. Well it's the ten worst years, isn't it folks? It's the ones at the end! It's the wheelchair, kidney dialysis, adult diaper yam years. You can have those years! We don't want 'em, alright?
The filter is where they hide the cocaine. :puffs well into the filter: K-aaaaaaaaah.
Depends on how the smoking is killing you. It's quite possible that you'll still have a miserable final decade. It just means you'll get an oxygen tank at 55 instead of 65. Disclaimer: I acknowledge that jokes don't need to be true to be funny.
Se so. It's an exaggeratedly naive thought for comedic effect.
Dennis Leary's ideal vice would be one that has no observable effect on your health until it abruptly causes you to die after your 10000th dose. I'm not sure if there's any existing drug that fits the bill... Perhaps there are some that are harmless unless you OD at which point they're lethal, but that's not quite what we're looking for.
@MartijnPieters as a crypto ignoramus I can only say that the post is well-written and clear to noobs. I only have one practical concern: do you think the use of _ is well-known enough in your first demo? Or are you hoping that whoever wants to use that will not mindlessly copy from your interactive session?
@AndrasDeak I swithered about _ there. I may just replace it with an assignment and echo.
15:21
Yeah, that's what I was thinking. I can imagine both someone being put off by not knowing what's going on (and stopping reading), and the less bad scenario of just cargo-culting over that step (and not understanding why there's a NameError for _ :D)
@Kevin Certain patterns of heavy cocaine use would qualify. Recently spoke to someone who had a friend die from a spontaneous aneurism due to weakened blood vessel walls in the head.
I figured you meant the post to be as noob-friendly as possible
I think that's as close as we're going to get. When using the drug, people with naturally weak blood vessel walls will probably have a shorter countdown than the initially healthy, but that's likely also true for any other mechanism we care to come up with.
technically you can have something like LSA suddenly killing you due to a hallucination going wrong
but that's not really a Leary situation
Panic attack induced heart attack isn't… directly… the drug killing you, as such. ;P
15:31
A drug that has P chance of killing you and 1-P chance of not affecting your health at all doesn't quite give the drop-off cliff that we want, since repeated use will form a nice binomial curve of doom
@amcgregor I meant more like diving from a bridge or flying a jet fighter on the highway...
then again arguably that's the same thing
Always boils down to: there's only two ways to die. Not enough oxygen to the brain, or too much oxygen to the brain.
Crashing a jet fighter? Too much oxygen.
unless you're driving a car
Aneurism from cocaine? Not enough.
The definition will require some expansion in the glorious cyberpunk future where people routinely have their fleshbrains destructively replaced with computronium crystals
Many philosophers will argue that the original person dies during the procedure and the new crystal person merely resembles them very strongly, but this viewpoint is dismissed as depressing and an unwelcome legal complication
15:42
Similar to the teleportation paradox. I, personally, have no qualms about using such "destructive reconstructive" systems. I'm a meat machine. I accept this fact, esp. after last year's reminder of mortality and demonstrations of surgeons literally tinkering around in there.
say no to teleportation
Also let us not forget glorious cyberpunk androids who are sufficiently advanced to have legal personhood, and who never had a fleshbrain to begin with
I'm more concerned with conservation of energy problems. Teleport a distance with a change in altitude? Go up, you'll freeze, go down far enough, you are a literal nuke on delivery. (Changes in potential energy need to go somewhere, and heat entropy is the universal dumping ground.)
@Kevin I use the term ACI instead of AI, because "artificial" is a prejudiced loaded term, robot has its roots in literal slavery and mindless automata… "Advanced Cybernetic Intelligence" seems… better.
they'll kill you last
'Death occurs when X no longer reaches Y, or Y is irreversably destroyed, where X is "oxygen" or "computronium energy" or "all-purpose cyborg internal sauce recipe #7", and Y is "brain" or "central processing crystal", or "semi-autonomous nano-hiveswam"'
15:49
The thing about energy (proper, physical energy) is that it can only change continuously. Which is a pretty strong argument against (macroscopic) teleportation.
Good (clarification), there. ;P
But what about quantum entanglem--pfft I can't keep a straight face while suggesting that
Photons be easy. Mammals be hard unless you enjoy physical inversion. (Timmy! Yeah, did it work? Fetch the mop! Oh.)
Easier to just put your mindscan in a zip file and email it to your destination
There's dubious, but some, evidence towards neural activity involving quantum effects. A "brain scan" of the structural elements, in this vein, wouldn't reproduce the transient state (which is most state if I recall) of memory or thought; you'd have a brain. Just a brain. Enjoy that. ;P
15:56
what's with you and veins ;))
Common idiom, so I make no apology. :P
@amcgregor I am reminded of a scifi story where teleportation is possible but only between two points with identical potential gravitational energy. You can't teleport from the surface of the Earth to the moon, but you can travel to an earth orbit with 0.1654 g's and hop to the Moon from that point.
The math on my cocktail napkin tells me you need to go about 15,000 km out, which is quite a savings compared to the usual 300,000 km trip
By Grabthar's hammer, what a savings
This problem was similarly covered in Larry Niven's "known space" series (Ringworld, Fleet of Worlds, …) via the "stepping disc" teleporter devices produced by the species known as Pierson's Puppeteers. They could buffer a bit of excess differential, but there were limits.
(These tended to be littered about the public streets of a city, each step would teleport you a block in the given direction, a quad of outgoing discs in each cardinal direction around the receiving disk in the centre of each intersection.)
16:36
on the discworld you merely have to worry about conservation of momentum
If you ever gain teleportation powers and become a superhero, memorize the coordinates of a couple of circuses so that the next time your nemesis pushes you out of an airplane you can blip away and reappear over the acrobat safety net
You might also consider installing a three story tall pile of cardboard boxes in your lair
Pervasive natural teleportation is an interesting topic, actually! The Jaunt explored what the consequences might be if everyone could teleport, given the restriction that one needs to be aware of where they are and where they're going in precise physical detail.
Building security evolved into designing mazes. Get through the maze, and you can't teleport out of the building, let alone in, given the disorientation.
In lieu of preparations of this kind I wonder if you could just alternatively teleport between antipodes so that falling down becomes falling up, and you gradually bleed off your kinetic and potential energy thanks to air resistance
That might take a long time and/or require asymptotically smaller periods between jumps as you approach sea level though
16:53
Can anyone help me out please ?
@Kevin Humans aren't that good (accurate) with progressive escalation of force, assuming that natural teleportation would require some form of "effort" to enact. Additionally, the "hang time" would rapidly approach zero between teleportations. Tragic parkour videos attest, and there's the simple sample of drumming back and forth between your index fingers on a desk. Start slow, speed up, go even faster, and somehow try to keep the tempo even. ;)
@shome Most likely anybody in here with numpy experience has also been watching the new numpy questions list, in which case they've already seen your question. In other words, posting in here hasn't increased the size of your audience. But if you're still struggling with this in a day or two, posting in here again might get some fresh eyes on your question.
17:10
morning cabbage
17:23
cabbãge
17:46
I have a list of dictionaries and I want to find duplicates based on one particular key. Can I do this with Counter in some way?
I don't think Counter offers any particularly attractive features in that scenario
Or, well, I guess it depends on what output you're trying to get
Here's an example list: repl.it/@codeguru/FlippantSplendidDribbleware. Now I want something similar to Counter that groups all of the dictionaries with the same value for the key 'foo'.
If all you want is a list of the values that appear more than once, then that's just [k for k, v in Counter(d["foobar"] for d in list_of_dicts).items() if v > 1]
>>> seq = [k for k, v in Counter(d["foo"] for d in l).items() if v > 1]
>>> print(seq)
['abc']
Let's back up to the X of my XY problem...
Oops, I misread the problem statement.
What should the output look like? a dict of lists of dicts?
17:53
I have a list of dictionaries. I need to find any dictionaries that have the same value for a given key. And I want the index of any of these duplicates as well as the value at that key.
So the output can be a list of tuples or a list of dicts with the index and the value of the key.
So the output might be... [("abc", [0, 3]), ("baz", [1]), ("qux", [2])]?
@Kevin so this is close to what I want. Now I also need the indexes from the original list where those dupes occured
@Kevin yah, something like that will work fine
so I think I'm gonna just write this myself....I was hoping Counter would provide a way to do what I want, but I don't think so.
import collections
result = collections.defaultdict(list)
for idx, d in enumerate(l):
    result[d["foo"]].append(idx)
print(result)
#defaultdict(<class 'list'>, {'abc': [0, 3], 'baz': [1], 'qqq': [2]})
what's defaultdict?
It's a subclass of dict that handles KeyErrors by assigning a default value instead of crashing.
If you want a plain old dict, you can do
17:59
ahh, so it assigns an empty list instead of KeyError....that's very useful
result = {}
for idx, d in enumerate(l):
    result.setdefault(d["foo"], []).append(idx)
print(result)
#{'abc': [0, 3], 'baz': [1], 'qqq': [2]}
In either case you can get the list-of-tuples format via list(result.items())
The dictionary is just fine...it contains the same info that I need
I think the dict form is a little more logical than the list-of-tuples form (but ofc I know nothing about the end goal here)
the exact form of the output is not terribly important
p.s. I wasn't asking for a code solution. More just rubber ducking to get ideas flowing.
so thanks for the help, Kevin. 20 quatloos!
Third party library toolz has a function groupby (not to be confused with built-in method itertools.groupby) which is good for this kind of data aggregation
>>> toolz.groupby(lambda d: d["foo"], l)
{'abc': [{'foo': 'abc', 'bar': 3}, {'foo': 'abc', 'bar': 22}], 'baz': [{'foo': 'baz', 'bar': 8}], 'qqq': [{'foo': 'qqq', 'bar': 4}]}
Although it gets hairier if you absolutely must have the dicts' indices and not just direct references to the dict objects
>>> toolz.groupby(lambda idx: l[idx]["foo"], range(len(l)))
{'abc': [0, 3], 'baz': [1], 'qqq': [2]}
18:44
What happens to threads that get garbage collected? Does the thread terminate?
cbg
Installing pytype req VS tools...said install is larger than my current user files..
Packaging could really use some more love (not that it hasn't come a long way).
Today I am annoyed at packages whose package name is not the same as the module name. If I do pip install pyqt5, I expect import pyqt5 to work.
I counter verbose wrong-names with: pip install e; python -me …
Additionally I am annoyed at package documentation that does not have prominently visible sample usage showing a proper import statement
e best package.
19:09
Ooh I got the Good Answer badge.
But perhaps these are XY annoyances and I should really direct my ire at OPs that decide that import statements aren't important and they shouldn't post them
I… swear I didn't screw up, but the data is so wildly out of stddev something must have been done incorrectly. :| Most template engines I'm benchmarking on this single <table> generation (10 column, 1000 row) get 20-40 generations per second. Django's template engine (just the template engine) is getting 2. Wat.
Sam
Sam
I have a vector of integers [1, 2, 3, 4] and a dictionary of key value pairs. How can I get only values from said dict who's IDs exist in my vector?
[d[x] for x in vector_of_integers]
Assumes that "ID" means "key" and that it is guaranteed that every element of the vector exists as a key in the dict
and you can add if x in d to fix the other case
Sam
Sam
19:19
Elegant. Thanks
19:33
Straw poll: is having a separate function that is wrapped by a method of a class and a method of child class bad form, or sensible? I'd like to take a setting (it's a default image) at the app level, at the Class(room) level and individually at the Student level (Student classes belonging to a Class class.
I'm not sure what "wrapped by" means in this context. Certainly it's acceptable to define a method in the parent class, and also define it with different behavior in the child class.
Said method would essentially do similar things, so using the same function wrapped by methods on each of the classes and called with arguments particular to those cases seems DRY to me.
from module import universal_func

class Parent:
    def specific_method(self):
        universal_func('parent_specific')

class Child:
    def child_specific_method(self):
        universal_func('child_specific')
Ah, so perhaps "X wraps Y" means "X does very little on its own other than call Y"
Yes, apart from supplying different arguments.
Perhaps you could implement the method only in the parent class, and define the arguments as an attribute of the class.
class Parent:
    SETTINGS_KEY = 'parent_specific'
    def specific_method(self):
        universal_func(self.SETTINGS_KEY)

class Child(Parent):
    SETTINGS_KEY = 'child_specific'
19:42
Defining the function outside the class would also allow it to be used outside. Specifically I want to set a default avatar for the application, but allow a custom default at the Classroom level as well as setting a Student's avatar. Also a couple of functions like one I use to parse strings (eg names) into strings that are safe to use for filenames.
Nothing wrong with defining functions outside of classes if they don't have a strong conceptual connection.
Some might insist that you create an Application class and put the avatar-setting function inside there, but I don't consider it essential if there's only ever going to be one application
As long as it's not an antipattern to import and then call a function from inside a class. :)
Thanks
19:58
@toonarmycaptain importing is; calling is not
Ha, just spent a little too long looking at a question asking about preg_match("'<cas:user>(.*?)</cas:user>'", $resp, $match); before I could determine what was going on
if by "inside a class" you more broadly mean "inside the module where the class is defined" then it's fine
If Andras means "having an import inside a class definition is bad; imports should be at the global scope", I agree
The only time I place imports in places other than the top of the module is when I have pathological dependencies. (E.g. at the module scope it's impossible for it to resolve the import due to the ongoing import of the current module…)
stackoverflow.com/q/15901888/1222951 horrible, horrible no MCVE question with 26k(!!!!) views. Should've been obliterated from orbit YEARS ago
20:01
@AndrasDeak Point taken :) yes I meant importing in the module defining the class, not within a method in a class.
@Aran-Fey jeez how did that not have at least 1 close vote beforehand
might've had some close votes that aged away
@Aran-Fey is that a thing that happens? how does that work?
37
Q: How do close votes age away?

RoryThe help center states, Close votes age away harmlessly if the threshold is not reach after a number of days. If the question has at least 100 views, close votes will age away after 4 days; otherwise close votes will age away after 14 days. Each new close vote resets the timer, so all close v...

> Everything is working BUT that line over there. Why?
that's glorious
20:06
that is my new favorite quote
lol ikr
"that line over there"
wim
wim
@Kevin packages can export multiple top-level names (or none at all)
Traceback (most recent call last): File "<file>", that line over there, in <module>
@AlexanderReynolds I'm not sure exactly how the aging away works, I just know that if you vote to close an old question you have to get your friends involved if you don't want that vote to be wasted
@Aran-Fey Yeah, those links I posted cover it (dunno why I asked you instead of just looking it up). Doesn't seem to be too complicated, but I actually didn't know that was a thing!
wim
wim
20:11
as for PyQt5, the package name IS actually matching the import name unless I'm missing something.
so, really, you should be annoyed at pip, which is the one responsible for resolving pyqt5 to PyQt5.
Errors passing silently? Tell me it ain't so!
It seems I have too much time on my hands: I've come up with a stupid str.format trick. :|
Because {now.%Y%m%d} totally doesn't get the adrenaline flowing.
@WayneWerner I followed the link and was tempted to reply with a line from a question linked in the sidebar and "yeah, I know it doesn't work, but how's that relevant to your problem?
bwahahaha
that's great
20:27
@Aran-Fey not more than with new posts. Close vote queue is a thing, it just often doesn't suffice
wim
wim
stupid indeed. you are reinventing f"{now:%Y%m%d}" with some convoluted thing for reasons unknown.
wim
wim
and seconds since epoch is f"{now:%s}"
@wim Because this works back to the introduction of str.format in Python 2. No idea when :-formatting of date formats was actually added.
wim
wim
strftime syntax was always there for str.format
20:30
Interestingly, docs.python.org/2/library/stdtypes.html#string-formatting makes no mention of "date".
does everyone here just use this chatroom via browser? or is there other options?
A ha, the /3/ version does mention it, once, under the heading "Using type-specific formatting". It's a three line sample with no link to additional reading.
@AlexanderReynolds there are some hax out there, but otherwise basically just the browser
that's what I figured, just didn't know if there was something..."official"
20:32
@AlexanderReynolds Browser w/ userstyle via Cascadea for Safari. (Everything I use I make dark-mode.)
wim
wim
show me a Python version where "{now.%Y%m%d}".format(DateTimeProxy(now)) works but "{now:%Y%m%d}".format(now) doesn't
@AlexanderReynolds specifically for SO chat there's a dark theme courtesy of JS room peeps, firefox and chrome
@AndrasDeak Thanks, was more wondering service-wise so I could pop it into the app I use for all my messaging services. Might just build it. (I just don't like juggling browser windows as I typically have a bunch open)
Inteeeeeresting. So my "ugly, dirty hack" (beyond being happily unneeded! ;) reveals interesting implementation details about str.format and f-strings. That the expression within braces is not actually evaluated as Python, it's more of a simple str.split on . with iterative getattr lookup, or it'd SyntaxError.
Allows for impossible attribute lookup hacks like this, but on the other hand, impossible attribute lookups.
wim
wim
21:01
what are you on about? it is evaluating the expression. evaluating the expression invokes your custom __getattr__.
this is not an "impossible attribute lookup", it's normal datamodel stuff
21:26
cbg
Am I right in thinking that empty strings are not special and fall under the same case-specific rules of being interned or not?
There's an answer that uses is not '' quite a few times, and I suspect is not is just as fallible as any other string comparison.
wim
wim
interning should not be relied on regardless, so the question is moot
Maybe I'm wrong in my assumption that this is string interning. Let's drop "interning" and I'll just ask if [x for x in something if x is not ''] behaves just the same way as [x for x in something if x is not 'hello']? There's no special case for the empty string?
wim
wim
there might be.
IIRC CPython keeps around a cache of falsey things (such as empty tuple, empty string, empty list, various numeric zeros) as a performance optimization.
presumably if you want to check if myobj is falsey you can check if it's one of the usual suspects first
Interesting, I'll try dig into the source then. I assume this optimisation will be in C, but I guess I'll recognise an empty string?
@amcgregor I think it's slightly more complicated than "just Python"
Like... async is a keyword in Python 3.7, but you can get around that with **kwargs
oh that's super weird though
locals()['async'] = 'whatever'
f'{async}'
that produces a SyntaxError
 
1 hour later…
22:49
Could anyone please help me with this question on how to update the SQL database from python? stackoverflow.com/questions/55152478/…
hey guys, in matplotlib im graphing integer valued terms on a scatter plot, but it doesn't really capture data density well. I added a a uniform noise of +/-0.5 to get a better visualization but am wondering if there is a better practice
before
Adding noise is pretty common, otherwise you could do a 2D histogram/heatmap: goo.gl/images/WkNWEj
after
I'd consider something like that but in my case im working in a classification (kNN) problem so the color of the dots actually means something
Instead of color, you can also map it to the opacity of the point, the size of the point, or the height of the point in 3d
Though now you're visualizing 4 dimensions so it's confusing
I think the most natural is to do as you're doing and add noise.
There's a term specifically for adding noise to quantized points to visualize density, but I don't remember what it's called. Either way, it is very common.
22:54
good to hear my intuition was on point
and this isnt even the cleaned up graph (i'd radically seperated the clusters for a portion missing data so it could do a seperate cluster but then renormalized the data later, this graph is a bit outdated i guess
Note that density still may not be visually perfect if there's tons of points and the size of them is large enough to hide random overlaps; in that case, doing both noise and adding some alpha/transparency can give a good idea.
yea, i toyed around with alpha but its so easy for things to get muddled, here I'm writing a tutorial and wanted to just provide a high level "Squint" at the data and its trends
"jitter", derp
You add jitter to the points. That's the term. That took me way too long.
^ was just about to say
ah yes, that rings a bell
22:57
Of course, just make sure it's only for visualization :P but I'm sure you know that
jitter + alpha might work better
@AndrasDeak well thanks for thinking for me, anyways :)
Yeah that's my go-to, personally (I do this for 3D RGB histograms)
3D visualization is a pain
that is, jitter + alpha.
yea, i basically instantiated a copy of the dataframe with a noise summant at each data point and graphed the sum of both df so that its the only time those two are mixed together
22:59
What's the tutorial? Where will it be published? Might be interested in checking it oot
00:00 - 23:0023:00 - 00:00

« first day (3071 days earlier)      last day (2102 days later) »