368 points · by Decabytes · 3y ago · 233 comments
It goes B, KiB, MiB, GiB, TiB, EiB and no more than that (in all the answers) so that can be solved with three if statements at most, no five.
I mean: if it's greater or equal to GiB, you know it won't be B, KiB or MiB. Dichotomy search for the win!
Not a single of the hardcoded solutions do it that way.
Now let's go up to ZiB and YiB: still only three if statements at most, vs up to seven for the hardcoded solutions.
I mention it because I'd personally definitely not go for the whole log/pow/floating-points if I had to write a solution myself (because I precisely know all too well the SNAFU potential).
I'd hardcode if statements... But while doing a dichotomy search. I must be an oddball.
P.S: no horse in this race, no hill to die on, and all the usual disclaimers
for a problem space limited by your input size (signed 64 bit number) to a 6 entry dictionary? At best you may want to optimize some in-lining or compiler hints if your language supports it. maybe setup some batching operations if this is called hundreds of times a frame so you're not creating/desrtoying the stack frame everytime (even then, the compiler can probably optimize that).
But otherwise, just throw that few dozen byte lookup table into the registers and let the hardware chew through it. Big N notations aren't needed for data at this scale.
The most copied StackOverflow snippet of all time is flawed (2019) - https://news.ycombinator.com/item?id=27533684 - June 2021 (334 comments)
The most copied StackOverflow snippet of all time is flawed - https://news.ycombinator.com/item?id=21698619 - Dec 2019 (88 comments)
The most copied StackOverflow snippet of all time is flawed - https://news.ycombinator.com/item?id=21693431 - Dec 2019 (3 comments)
Notably, it's still slightly better than the first code example in the original article, as it takes the rounding bug into account.
Also 6 comparisons is only if you’d have the max value which seems unlikely in actual usage. Linear could be better if most of the time values are in B or KB ranges
The snippet from S/O may be four lines but these are much more extensive, come with tests, output formatting options, conversion between sizes, and more.
But in a completely benign way. I question why a few edge cases of writing 1000kb instead of 1Mb—so not even a misrepresentation—would ever be worth the code bloat. This is about making stuff slightly more convenient to read.
(The subject at hand isn't whether libraries are good or not, it's whether copying something off the internet is. In the post, it turns out it isn't. If it was a library, the author could have fixed and updated the library, and the issue would be fixed for everyone that uses it. left-pad isn't an issue with libraries per se, it's an issue with library management)
Accounting for correctness even in edge-cases is what large libraries do better than throwaway bits of code.
[1]: https://github.com/microsoft/STL/blob/6735beb0c2260e325c3a4c...
The conjecture that people just copy from StackOverflow is obviously popular but I always thought this was just conjecture and humor until I saw someone do it. Don't get me wrong, I use StackOverflow to give me a head start on solving a problem in an area I'm not as familiar with yet, but I've never just straight copied code from there. I don't do that because rarely does the snippet do exactly and only exactly what I need. It requires me to look at the APIs and form my own solution from the explained approach. StackOverflow has pointed me in the direction of some niche APIs that are useful to me, especially in Python.
Now he was an extreme case, but yes, there are a lot of developers out there with the mindset of “I need code; Stack Overflow has code; problem solved!” that don’t put any thought at all into whether it’s an appropriate solution.
But for whatever reason, in one hiring round the vast majority had cut and pasted answers from search results verbatim (we dealt with a new recruiter, and I frankly suspected this new recruiter was telling them this was ok despite the instructions we'd given).
These were not subtle. But the very worst one was one who did like the developer you described: He'd found a forum post about a problem pretty close to the question, had cut and pasted the code from the first answer he found.
He'd not even bothered to read a few comments further down in the replies where the answer in question was totally savaged by other commenters explaining why it was entirely wrong.
This was someone who was employed as a senior developer somewhere else, and it was clear in retrospect looking at his CV that he probably kept "fleeing the scene of the crime" on a regular basis before it was discovered he was a total fraud. We regularly got those people, but none that delivered such obviously messed up answers.
For ever developer like this, you're probably right there will be a lot more that are less extreme about it, and more able to make things work well enough that they're not discovered.
The problem? They were passing the input text as hardcoded plaintext, i.e. it wasn't even a string with quotes or anything -- just `foo(here is my raw, non-string input, no quotes necessary lol)`, and they could not conceive of what the issue might be.
Sure, it isn't good practice. Sure, it probably isn't what NASA should be doing. But if you're literally building yet another uber-like app, you probably shouldn't be spending too long thinking about details.
No it can’t. Quick and dirty? Sure. Take on some tech debt to get to market quicker. Blindly copying and pasting? You’re never going to build functional software that way. This guy was committing code with syntax errors that he’d obviously never even run. How are you going to get to market quickly that way?
I'm not sure why, maybe people are missing knowledge that would allow them to understand, so they just try random things in the hope that it works? It surprises me every time it happens.
Sounds like this guy understands concurrency. :)
Personally I can’t see how it would be faster to ask ChatGPT for an answer then carefully scrutinize the output to make sure I understand what it’s doing. Code is often easier to write than read - especially when it’s not your code.
In hindsight the solution is obvious, just run the code without reading it then try to fix it if it doesn’t produce acceptable results.
My most copy-pasted code is projecting a point onto a line segment. I end up needing it all the time, it's never in whatever standard library for vector math I'm using, and it's faster to find on SO than to find and translate the code out of whatever my last project that needed it is. Way faster than re-deriving it.
Your vector math library is probably already code imported from random strangers, likely even imported by random strangers, so adding one more function from a random stranger feels entirely appropriate.
Also if I come across the problem a second time, I'll have better luck remembering what I did (as opposed to blindly copying).
Somewhere in my history is a recent HN (or maybe Reddit) post where somebody insists Curl has been 100% compatible from day one, and like, no, originally curl ignores certificates, today you need to specify that explicitly if it's what you want.
I think (but don't take my word for it) that Requests (the Python library) was the same. Initially it didn't check, then years back the authors were told that if you don't check you get what you didn't pay for (ie nothing) and they changed the defaults.
Python itself is trickier because it was really hard to convince Python people that DNS names, the names we actually care about in certificates, aren't Unicode. I mean, they can be (IDNs), but not in a way that's useful to a machine. If your job is "Present this DNS name to a user" then sure, here's a bunch of tricky and maybe flawed code to best efforts turn the bytes into human Unicode text, but your cert checking code isn't a human, it wants bytes and we deliberately designed the DNS records and the certificate bytes to be identical, so you're just doing a byte-for-byte comparison.
The Python people really wanted to convert everything messily to Unicode, which is - at best if you do it perfectly - slower with the same results and at worst a security hole for no reason.
OpenSSL is at least partly to blame for terrible TLS APIs. OpenSSL is what I call a "stamp collector" library. It wants to collect all the obscure corner cases, because some of its authors are interested. Did the Belgian government standardise a 54-bit cipher called "Bingle Bongle" in 1997? Cool, let's add that to our library. Does anybody use it? No. Should anybody use it? No. But it exists so we added it. A huge waste of everybody's time.
The other reason people don't validate is that it was easier to turn it off and get their work done, which is a big problem that should be addressed systemically rather than by individually telling people "No".
So I'd guess that today out of a thousand pieces of software that ought to do TLS, maybe 750 of them don't validate certificates correctly, and maybe 400 of those deliberately don't do it correctly because the author knew it would fail and had other priorities.
Had an exchange like this some time ago:
Me: Hey, I'm reviewing your PR. Looks pretty fine to me. Except for this function which looks like it was copy-pasted from SO: I literally found the same function in an answer on SO (it was written in pure JS while we were using TS in our project).
Dev: Yes, everyone copies from SO.
Me: Well, in that case I hope you always copy the right thing. Because this code might run but it is not good enough (e.g. the variable names are inexpressive, it creates DOM elements without removing them after they are not needed anymore).
But for personal projects where I just want to get something running, then yes, I would copy paste and barely even read the code.
I don't really care about bugs like this either - I'm happy to make something that works 99% of the time, and only fix that last 1% if it turns out to be an issue.
Underrated comment. I think most tech companies' General Counsel would have a heart attack if they were aware of StackOverflow copy-pasting by their developers. I highly doubt some rando-engineer who pastes bubblesort code into their company's code base gave even a passing though to what license the SO code was under, what license his own company's code was under, and whether they were compatible.
The big (FAANG) tech companies I've worked at all have written policies about copying and pasting code from external sources (TLDR: Don't), but I've seen even medium-sized (~1000+) companies with zero guidance for their developers.
not long ago I worked on a team who actively chose libraries and frameworks based on the likelihood they felt their questions would be answered on StackOverflow.
This is why PHP got such a bad reputation. A lot of new developers where copy and pasting quick example code from stack overflow, or code from other new developers who only kind of knew what they were doing.
I don't think that's the only reason, lol.
Unless I'm missing something, this gives you an accurate value of floor(log2(value)) for anything positive less than 2^63 bytes, and it's much faster too:
Long.bitCount( (Long.highestOneBit(value) << 1) - 1) - 1I wonder with the rate Stack Exchange is losing active contributors, what it would take for 'fastest gun' answers to be corrected that are later found to be off mark, and what it would mean for our collective knowledge once these 'slightly off' answers are further cemented in our annals of search and increasingly, LLM history.
Something similar happens in public economic forecasts because those who get it wrong when others get it right are treated much more harshly than those who get it wrong when others get it wrong too.
I guess the next logical exercise would be asking them to do something with instructions that are complete, but incorrect or at least inefficient, to teach the lesson of questioning superior orders rather than just peers. Actually, I'm honestly not sure it that's desired in military discipline or not (no direct experience here)
I had a supervisor tell me to do something that was clearly not right and I refused. I came in the next day and they tried to write me up and I refused to sign the paperwork for it.
The one thing no one could accurately describe is why the supervisor was right.
I agree with the idea of being willing to go against authority but disagree that it's always a good career move :)
Of course it was easier for me, it was just a summer job, I was going back to Uni in the fall.
You can imagine some perfect future programming language where floating point errors don't exist, and don't have to be accounted for. Thats the language I'm targeting with 99% of my algorithms.
They had another one that went R 2/4 4/4
I'm still undecided which was more weird. You can see them both on eBay.
But one thing that I would really love to see are actual liters or gallons (depending on the country where I am at the moment).
Pay attention to comments and compare a few answers.
Then I saw that you could get points for editing answers. OK, I thought, I can get some points by fixing some bugs. I found a highly upvoted post that had code that didn’t work, found that it was because one section had used the wrong variable, and tried to fix it. Well, the variable name was too short to meet the necessary 6 characters to edit the code (something like changing “foo” to “bar”).
I went to see what other people did in these situations, and they suggested just adding unnecessary edits in order to reach the character limit.
At that point, I just left the bug in, and gave up on trying to contribute to Stack Overflow.
My breaking point was when I saw a question with an incorrect answer. I posted a correct answer, explained why the other answer was incorrect, and downvoted the incorrect answer. The author of the incorrect answer then posted a rant as a comment on my answer about how I shouldn't have downvoted their answer because they were going to fix it, and a couple other people chimed in agreeing that it was inconsiderate or inappropriate of me to have downvoted the other answer.
I decided Stack Exchange was dumb and stopped spending time there, which was probably good for my PhD progress.
I was quite active on stack overflow back around 2010, asking a lot of questions, answering questions when I knew the answers, and so on. The idea of getting a gold badge seemed wildly crazy, and someone who had one (or even two!) was clearly a sign that they knew what was what. I used it for a while, never made much of a reputation, but did manage to earn a small handful of silver badges which I was quite proud of.
Then I forgot about it for quite a while.
Fast forward to today. My reputation chart just keeps going up at a steady linear rate. At this point I am in the top 3% of users with 14,228 reputation and 25 gold badges. I haven't been active in a decade. I don't know what most of my badges even are.
---
Most of my reputation comes from my questions. In case you're wondering what a top-3%er's top questions looks like, they are:
Apr 15, 2011 (207) -- CSS: bolding some text without changing its container's size
Aug 19, 2009 (110) -- How long should SQL email fields be? [duplicate]
Jun 29, 2010 (89) -- php: check if an array has duplicates
Jul 3, 2010 (63) -- centering a div between one that's floated right and one that's floated left
Jan 5, 2010 (44) -- CodeIgniter sessions vs PHP sessions
Apr 12, 2011 (40) -- Java: what's the big-O time of declaring an array of size n?
Jan 11, 2011 (28) -- Javascript / CSS: set (firefox) zoom level of iframe?
Jul 15, 2010 (25) -- Javascript: get element's current "onclick" contents
Aug 22, 2009 (21) -- SQL: what exactly do Primary Keys and Indexes do?
Jul 3, 2010 (20) -- Getting the contents of an element WITHOUT its children [duplicate]
For anyone keeping score, that last one one was marked as a duplicate of a question that was asked a year after mine, and which seems similar on the surface to someone who does not have a good understanding of the DOM structure but is actually not the same thing.
It's interesting to see some of the top (5- or 6-digit SO scores) people's activity charts.
They usually have a 3-5-digit answer history, and a 1-digit question history, with the digit frequently being "0."
In my case, I have asked almost twice as many questions, as I have given answers[0].
For a long time, I had a very low SO score (I've been on the platform for many years), but some years ago, they decided to award questions the same score as answers (which pissed a lot of people off), and my score suddenly jumped up. It's still not a top score, but it's a bit less shabby.
Over the years, I did learn to ask questions well (which means they get ignored, as opposed to insulted -an improvement), but these days, I don't bother going there, anymore.
I had gotten most of my points by asking and answering things about Blender workflow/API/development specifics, so I got to skip some of the dumb gatekeeping on StackOverflow.
Worldbuilding's fun, too— Codegolf's not bad either, if you can come up with an interesting way to do it— Arquade looks good, and so does Cooking— Literature, English, Scifi, etc look interesting— If you program software, I suppose CodeReview might be a safe bet.
it's mostly people asking you to do their comp sci homework.
Unfortunately people trying to game the system creates enormous work for those who can review.
(Not saying you were doing anything wrong just pointing out why there are automated guards)
I just got beaten up in HN for asking how the hell sql injection is still a problem. People get defensive, apparently.
Not even a few years ago I worked with people who insisted it was ok to write injection unsafe code if you knew for sure that you owned the injected values. Didn't matter that maybe one day that function would change to accept user-supplied data, that's not their problem! It was a Rails app and they were literally arguing wanting to do:
.where("id = #{id}")
over: .where("id = ?", id)
in those certain situations. So, you know, it takes all kinds, I guess.It's possible for developers to think they're actually doing the right thing, but it turns out they're not.
https://www.npmjs.com/package/mysql#escaping-query-values
> This looks similar to prepared statements in MySQL, however it really just uses the same connection.escape() method internally.
And depending on how the MySQL server is configured, connection.escape() can be bypassed.
In my defense, we trusted the input. But that's post-rationalisation, because I simply didn't know what I was doing at the time.
It gets worse. If I'd done it properly, my senior would have beaten me up in code review for "complexity". That was a man who would never use a screwdriver when a hammer was already in his hand.
Well.. duh?
Until AI takes over the world, this will be correct for everything. News, comments, everything.
I've been a moderator on a couple of ForumBB kind of forums and the idea of karma points was often brought up in moderator meetings. Those with more experience in this field would usually try to dissuade the less experienced mods from implementing any karma system.
Moderators used to have ways of promoting specific posts. In the context of ForumBB you had a way to mark a thread as important or to make it sticky. Also, a post by a moderator would stand out (or could be made to stand out), so that other forum users would know if someone speaks from a position of experience / authority or is this yet to be determined.
Social media went increasingly in the direction of automating moderator's work by extracting that information from the users... but this is definitely not the only (and probably not the best) way of approaching this problem. Moderators are just harder to make and are more expensive to keep.
Please, tell me that was sarcastic.
Sounds like you're counting that as a negative. Obviously it depends on the use case, but more often than not I'll lean towards the easier to read code than the most optimal one.
This has generally been my experience.
The example implied that this object would be an instance of a class interested in handling events, but didn't want to blow up the size of this example with not so relevant bits of code.
There was a time when I very actively participated in various forums related to ActionScript. And, as you can imagine, loading of XML was paramount to success in that field. Invariably, I'd encounter code that copied the documentation example and had this useless dummy object with handlers defined (and subsequently struggled to extract information thus loaded).
It was simply amazing how regardless of the overall skill of the programmer or the purpose of the applet, the same exact useless object would appear in the same situation -- be it XML socket or XML loaded via HTTP, submitted and parsed by user... it was always there.
----
Today, I often encounter code like this in unit tests in various languages. Often programmers will copy some boilerplate code from example in the manual and will create hundreds or even thousands of unit tests all with some unnecessary code duplication / unnecessary objects. Not sure why in this specific area, but it looks like programmers both treat these kinds of test as some sort of magic but also unimportant, worthless code that doesn't need attention.
----
Finally, specifically on the subject of human-readable encoding of byte sizes. Do you guys like parted? Because it's so fun to work with it because of this very issue! You should try it, if you have some spare time and don't feel misanthropic enough for today.
All code is wrong, but some is useful.
This is the reason.
OTO: It's at least easily upgrade able so it has an advantage.
There's no chance if you avoid random_person1 and use known_oss_provider’s package instead. At the very least, look at the tests.
Any package with tests is guaranteed to be more correct than a never-before-run SO answer.
It never dawned on me to approach it that way and I had never seen that solution(not that I ever looked). Not sure where it got that from but was pretty cool and.... Yeah, it gets simple stuff wrong all the time haha.
https://github.com/lattera/glibc/blob/master/sysdeps/ieee754...
Test all edge cases, especially for code copied from Stack Overflow.
It's according to this paper: https://link.springer.com/article/10.1007/s10664-018-9650-5
According to [this paper](https://link.springer.com/article/10.1007/s10664-018-9650-5) it's the most copied *from SO java answers*.
> A PhD student by the name Sebastian Baltes publishes a paper in the journal of Empirical Software Engineering. The title is Usage and Attribution of Stack Overflow Code Snippets in GitHub Projects [...] As part of their analysis they extracted code snippets from the Stack Overflow data dump and matched them against code from public GitHub repos.
> How does the author determine this is the "most copied snippet" on SO?
People answered. Should they not have?
Its a O(1) operation because of limited size allowed for numeric types
public static String convertBytes(long bytes) {
String[] suffixes = {"B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"};
if (bytes < 1024) return bytes + " " + suffixes[0];
int exp = (int) (Math.log(bytes) / Math.log(1024));
return String.format("%.2f %s", bytes / Math.pow(1024, exp), suffixes[exp]);
}And the key takeaway is "Stack Overflow snippets can be buggy, even if they have thousands of upvotes."
I don't disagree, but is this really the example to prove it.....
Why 300K+ people copied this in the first place shows some basic level of ignorance about what's happening under the hood.[1]
As someone who's been at this for decades now and knows my own failings better than ever, it also shows how developers can be too attracted by shiny things (ooh look, you can solve it with logs instead, how clever!) at the expense of readable, maintainable code.
[1] But hey, maybe that's why we were all on StackOverflow in the first place
And here's something to consider -- if you're converting a number to human readable format it's more likely than not your about to do I/O with the resulting string, which is probably going to be an order of magnitude more expensive than the little function here.
It's key to be able to recognize this when thinking about performant code.
In other words, the entire exercise is silliness because the eventual printf is going to blow away any nanoseconds of savings by a smarter/shorter routine.
For one thing, It assumes "regex" as used in programming are the same as "regular expressions" (defining regular languages) in formal use. More info on that [1]
But the question isn't even about a full parsing of HTML, with bracket balancing. It's just about syntactically matching all the opening tags. More "lexing" than "parsing". Instinctively that does look like a simple regular language to me, though I'm not claiming certainly. The super-regularity of HTML comes from nested elements, but it's just the tag syntax this user cares about, with no context-sensitivity
One red herring is comments and CDATA sections, but since they cannot be nested, they do not change the language class, as you just transition to a skip state and back when you see the start/end markers. But they do make the expression much more ugly of course
[1] https://en.wikipedia.org/wiki/Regular_expression#Patterns_fo...