@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 :)
@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.
@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.
@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...
@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.
@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.
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)
@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.
@БеляковаАнастасия 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 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.
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
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...
@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!
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.
@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.
I believe that's a trip-up of an optimization for efficient MRO-like label lookup. Specifically, once x is redefined within a, both aandb 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.)
@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.)
^_^ 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.
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)
@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.
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.
@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".)
@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.
@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.
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…)
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.
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.
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.
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.
@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.
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.
@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.
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?
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 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.
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
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
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.
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.
'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"'
The thing about energy (proper, physical energy) is that it can only change continuously. Which is a pretty strong argument against (macroscopic) teleportation.
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
@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
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.)
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
@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.
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']
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.
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
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.
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')
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
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
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…)
The 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...
@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!
@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?
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.
@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.
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?
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
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
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.
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
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