HNHacker News
TopNewBestAskShowJobs

nayuki

6,604 karma · joined May 31, 2011

I am a software developer.

Home page: https://www.nayuki.io/

submissionscomments
nayuki··on Move in C++ without a std:move
Kudos to the author for explaining these concepts, but I personally find this to be a poor use of my time and mental capacity.

I dabbled in C++ programming before Rust 1.0 was released (year 2015). I have spent some time understanding things like RVO, std::move(), rvalue references, T&&, move constructors, and so on. This was the main tutorial that I read a decade ago: https://web.archive.org/web/20240108142848/http://www.thbeck...

I began programming in Rust in 2017, and it is such a breath of fresh air. It has all the power of C++ but shed all the unnecessary baggage (e.g. confusing features, duplicate features).

In relation to this article, I like Rust's clear and simple semantics about moving objects. If x and y are variables of type T which implements the Copy trait, then `x = y;` performs a simple bitwise copy. Otherwise, `x = y;` moves the object `y` to `x` and `y` is no longer allowed to be accessed ("moved away"). Whereas in C++, the article states how copy elision behavior has changed over the years:

> You get guaranteed copy elision since C++17 in the following case [implying it wasn't guaranteed before C++17]

> Then you have named return value optimization (NRVO): [...] The latter is not subject to guaranteed copy elision. You probably don't pay for a copy or move there as well.

> While this code compiles, you will get a copy construction of the return value before C++20.

> Once you switch your compiler to C++23 mode, both cases do an implicit move. No std::move required.

This is why I prefer to deal with Rust instead of C++. And this is just my commentary on specifically the behavior of moves in C++. When I pile on other issues - like copious undefined behavior everywhere (e.g. signed integer overflow, array out-of-bounds accesses), too many footguns that result in bugs and security vulnerabilities - I developed an extreme distaste for programming in C and C++.

nayuki··on PageRank explained
Here are two excellent videos that explain and visualize the PageRank algorithm:

* [2020-06-17] Spanning Tree - "How Google's PageRank Algorithm Works" (5m16s): https://www.youtube.com/watch?v=meonLcN7LD4

* [2022-05-23] Reducible - "PageRank: A Trillion Dollar Algorithm" (25m25s): https://www.youtube.com/watch?v=JGQe4kiPnrU

nayuki··on Let’s take apart your phone
Humans have a bunch of digital components at their core: DNA, RNA, and peptides. It's not all analog.

Likewise, phones have numerous analog components: microphone, speaker, camera, screen, radio modem, power regulation.

Please don't equate the word "digital" to the notions of being electronic, man-made, or modern. Digital is simply an agreement between a sender and receiver that information is finite and perfectly copyable. (By contrast, analog information is infinite and cannot be copied perfectly.)

nayuki··on Let’s take apart your phone
> Petrol stores 50 times more energy by weight, but it needs to be exploded. A doughnut stores around 15 times, but it needs to be digested.

You left out a very important fact: Combustion requires external oxygen, which is not counted in the denominator when energy-by-mass is typically considered.

nayuki··on Why Can't You Pack a Bag? (2024)
https://archive.is/27YEq
nayuki··on 3D Pinball for Windows (1995)
In this port, using the menu to disable the music has no effect. Surprisingly, typing "hidden test" does have an effect, but the interpretation of mouse movements is weird and uncontrollable, unlike the original Windows EXE game.
nayuki··on Show HN: I mapped every US golf course
In Toronto, I think golf courses are built on flood plains along rivers (Don, Humber, etc.). Some other flood plains are public parks. Houses are generally not built on flood plains.
nayuki··on An ESP32 based plane radar for my desk
Exactly. Radar stands for "radio detection and ranging". Quoting https://en.wikipedia.org/wiki/Radar :

> Radar is a system that uses radio waves to determine the distance (ranging), direction (azimuth and elevation angles), and radial velocity of objects relative to the site. It is a radiodetermination method used to detect and track aircraft [...]

> A radar system consists of a transmitter producing electromagnetic waves in the radio or microwave domain, a transmitting antenna, a receiving antenna (often the same antenna is used for transmitting and receiving) and a receiver and processor to determine properties of the objects. Radio waves (pulsed or continuous) from the transmitter reflect off the objects and return to the receiver, giving information about the objects' locations and speeds.

The OP's project only passively receives the digital location information of each airplane transmitted by the airplane itself. The project does not transmit radio waves nor do any physical determination of the plane's location.

See also: https://en.wikipedia.org/wiki/Primary_radar (true radar), https://en.wikipedia.org/wiki/Primary_radar (ADS-B, which is what the OP receives)

nayuki··on Shinjuku Station in 3D
This is an excellent visualization! I would love to see someone adapt this data into a first-person navigation game. The game should put you at some location in the station complex and ask you to navigate to some location. This would be excellent training for people visiting the real-life Shinjuku station for the first time.
nayuki··on QR-Swastika-Avoider
I guess one could rack through many QR Code parameters while encoding the same payload text: Version (40 sizes with capacity constraints), 4 error correction levels (with capacity constraints), 8 mask patterns, splitting text into various blocks (with capacity constraints), using different character encoding modes (if applicable to the text), putting garbage data after the terminator (violates the spec, but can be a huge boost for generating some custom patterns).
nayuki··on When 2+2=5
lim_{2 -> 2.5} 2 + 2 = 5

/s

nayuki··on Synthesis is harder than analysis
> Synthesis is harder than analysis

Taking this statement at face value, it means something in computer science: computing an answer (synthesis) is currently believed to be harder than checking an answer (analysis).

The simplest example to illustrate the claim is that factoring a number is harder than multiplying the two factors to check that it equals the original number, or even to decide whether the original is prime or composite (but without yielding the factors).

This also cuts to the heart of what NP means - it means that the answer to a yes/no problem about binary strings can be checked in polynomial time. It doesn't give a recipe for how to generate the answer, but it is implied that finding an answer can take up to exponential time and no more.

nayuki··on Your Kids' School Bus Is About to Become a Roaming Surveillance Vehicle
True, but the article is complaining about other innocent people that might get caught in the surveillance dragnet.
nayuki··on Your Kids' School Bus Is About to Become a Roaming Surveillance Vehicle
Maybe design cities to be walkable and bikeable so that you have the option get things done without driving a car which is inherently trackable?
nayuki··on PlayStation Is Deleting 551 Movies from Customers' Accounts
> Reminding Us Nothing Digital Is Ever Truly Ours

Wrong, Kotaku. Lots of digital things are ours. Digital files on our personally owned HDDs and SSDs. Digital movies on DVD and Blu-Ray discs on our shelves. Digital ISO files on hard drives that are ripped from the aforementioned digital physical DVDs.

What you meant to say is, streaming content is not ours - and that is true by definition, because the data is streamed from somewhere else. Someone else can always delete files, take down servers, or go out of business entirely.

The word digital contrasts with analog. Digital and physical are two independent axes - there are digital physical things, digital virtual things, analog physical things, and analog virtual things.

nayuki··on PlayStation Is Deleting 551 Movies from Customers' Accounts
The game discs hold digital data. They're certainly not analog.
nayuki··on A game where you're an OS and have to manage processes, memory and I/O events
The game got too tedious to play by hand, so I wrote a script to play it automatically. It handles CPU, I/O, and processes quite well - but doesn't recognize a crown on a process and doesn't handle memory management at all.

I found that even on the easy level, the number of processes keeps growing slowly, and there isn't enough CPU time to keep all processes satisfied. I feel like the game is inherently setting you up for failure. Here is the script if anyone wants to play with it:

  // ==UserScript==
  // @name     Auto-play "You're the OS!" game
  // @include  https://plbrault.github.io/youre-the-os/
  // ==/UserScript==

  (async function() {
      const IO_EVENTS = {x: 160, y: 25};
      const CPUS = 4;
      const CPU1 = {x: 50+46, y: 50+42};
      const SQUARE = {w: 64+5, h: 64+5};
      const PROCESS = {x: 50+46, y: 155+42};
      const PROCESS_ROWS = 6;
      const PROCESS_COLS = 7;
      
      let cnv = document.querySelector("body > canvas");
      while (cnv.width != 1280 || cnv.height != 720)
          await new Promise(res => setTimeout(res, 100));
      
      while (true) {
          const pixels = new Uint32Array(cnv.getContext("2d").getImageData(0, 0, cnv.width, cnv.height).data.buffer);
          function getPixel(x, y) { return pixels[y * cnv.width + x]; }
          
          if (getPixel(IO_EVENTS.x, IO_EVENTS.y) == 0xFF808000);
              await pressKey("Space");
          let cpuStatuses = [];
          for (let i = 0; i < CPUS; i++) {
              const p = getPixel(CPU1.x + SQUARE.w * i, CPU1.y);
              cpuStatuses.push(
                  p == 0xFF000000 ? 1 :
                  p == 0xFF9A9B9B ? 2 :
                  p == 0xFF00FF00 ? 3 :
                  p == 0xFFE6D8B0 ? 4 :
                  0);
          }
          let processStatuses = [];
          for (let r = 0; r < PROCESS_ROWS; r++) {
              for (let c = 0; c < PROCESS_COLS; c++) {
                  const p = getPixel(PROCESS.x + SQUARE.w * c, PROCESS.y + SQUARE.h * r);
                  let s =
                      p == 0xFF000000 ? 1 :
                      p == 0xFF9A9B9B ? 2 :
                      p == 0xFF00FF00 ? 3 :
                      p == 0xFF00FFFF ? 4 :
                      p == 0xFF00A5FF ? 5 :
                      p == 0xFF0000FF ? 6 :
                      p == 0xFF00008B ? 7 :
                      p == 0xFF000050 ? 8 :
                      0;
                  if (s >= 3)
                      processStatuses.push({r, c, status: s});
              }
          }
          
          processStatuses.sort((a, b) => a.status - b.status);
          for (let i = 0; i < cpuStatuses.length; i++) {
              if (cpuStatuses[i] < 1)
                  continue;
              if (cpuStatuses[i] >= 2)
                  await pressKey("Digit" + "1234567890".charAt(i));
              const p = processStatuses.pop();
              if (p !== undefined)
                  await clickMouse(PROCESS.x + SQUARE.w * p.c, PROCESS.y + SQUARE.h * p.r);
          }
          
          await new Promise(res => setTimeout(res, 300));
      }
      
      async function clickMouse(x, y) {
          const rect = cnv.getBoundingClientRect();
          const opts = {
              bubbles: true,
              clientX: rect.left + x * rect.width / 1280,
              clientY: rect.top + y * rect.height / 720,
          };
          cnv.dispatchEvent(new MouseEvent("mousemove", {...opts, buttons: 0}));
          cnv.dispatchEvent(new MouseEvent("mousedown", {...opts, buttons: 1}));
          cnv.dispatchEvent(new MouseEvent("mouseup", {...opts, buttons: 0}));
          await new Promise(res => requestAnimationFrame(res));
      }
      
      async function pressKey(code) {
          cnv.dispatchEvent(new KeyboardEvent("keydown", {code, bubbles: true}));
          cnv.dispatchEvent(new KeyboardEvent("keyup", {code, bubbles: true}));
          await new Promise(res => requestAnimationFrame(res));
      }
  })();
nayuki··on Usbliter8: an A12/A13 SecureROM Exploit
I first thought of SecuROM, a CD/DVD copy protection scheme applied to computer game discs: https://en.wikipedia.org/wiki/SecuROM
nayuki··on The unreasonable effectiveness of simple HTML (2021)
Which was quoted in a recent post on the HN front page: https://mohkohn.co.uk/writing/html-first/ , https://news.ycombinator.com/item?id=48475483
nayuki··on Atherton spent $145K to delay train electrification. The rest of us paid $400M
https://en.wikipedia.org/wiki/Lawfare
nayuki··on Opaque Types in Python
Not only that, but Python had the benefit of doing a very painful break in version 3 (2008), when they had the option to cleaned up almost anything they wanted.

(Some changes in Python 3 I can recall: bytes/str/unicode being the biggest one; fixing mutable variables in nested functions; changing some obscure behavior in class hierarchies and overload resolution; changing things like range() and map() to lazy evaluation.)

For better or for worse, Java has maintained very good (not perfect) compatibility throughout, even with painful changes like generics in 1.5, lambdas in 8, modules in 9, eventual removal of applets and SecurityManager, etc. This also contrasts with C#/.NET, which I think had some breaking changes over the decades.

nayuki··on The real cost of owning a home
A condo is a type of home, so it's like you're saying "Do you drive a car or a vehicle?".

Also, condominium does not automatically imply apartment, because there are condo townhouses and condo detached houses.

A condominium is a legal structure that prescribes which parts are owned jointly and which parts are owned individually. https://en.wikipedia.org/wiki/Condominium

nayuki··on The real cost of owning a home
You somehow missed the second part of that sentence: "No, the statement is completely true: 100% of your rent money goes to someone else, and you also don't get any asset to sell later on."

The oft-repeated statement that "renting is throwing your money" is an implicit contrast to owning a home, where the mortgage payment "builds equity" in your asset that can be sold later.

"Throwing money away" means you don't get to own something that can be sold for money later on. That's why we "throw money away" on gasoline, but not "throw money away" in a savings account.

The second part of my argument is that throwing money away isn't necessarily a bad thing, because the alternative (such as paying to own something) can end up being more expensive and being a worse deal financially.

nayuki··on The real cost of owning a home
Great article, love that you enumerated all the costs in buying a home. I don't like how renters romanticize home ownership and fail to understand how many costs are involved.

> You've probably heard someone say something to the effect of "renting is just throwing your money away". Don't believe it. It's a glib statement that simply isn't true.

No, the statement is completely true: 100% of your rent money goes to someone else, and you also don't get any asset to sell later on.

However, this statement doesn't exist in a vacuum. You need some place to live, and you have to compare the cost of renting to the cost of owning.

To give an example, the typical rent in Toronto is $1000~2000/month, and the typical home ownership cost (including principal, interest, taxes, and maintenance) is $2000~3000/mo. We can just pretend that both are around $2000/mo.

If owning is still $2000/mo but suddenly rent is $500/mo, then renting suddenly becomes a great deal - even though you are still literally "throwing money away". You can use that differential $1500/mo to invest in a savings account, stocks, etc.

And speaking of that, I realized that the biggest cost in owning a home isn't the mortgage (and you correctly pointed out that paying down the principal doesn't change your net worth). The biggest cost is the opportunity cost of the down payment, when you could have instead invested in the stock market at 7~10%/year.

Continuing with the Toronto example, if you bought a home for $500k with 20% down, then the counterfactual if you had continued renting is that the $100k chunk of money could've generated $7000~10000/year = $580~$830/mo, which is a substantial fraction of the $2000/mo rent.

Shoutout to this article again: "You Are Naturally Short Housing" https://thezikomoletter.wordpress.com/2012/12/10/you-are-nat...

nayuki··on Opaque Types in Python
(I'd like to note that I wrote a lot of code in Java and Python, and continue to use each language in its respective strong areas. This isn't meant as a drive-by attack of "Java r00lz, Python sux"; this is an experienced take.)

My real problem with the evolution of Python is that initially, the language and the community was positioned as anti-Java, anti-big-OOP-like-C++, and then it changed into the thing that it was against, but in a roundabout and suboptimal way. To me, the initial vibe of Python was, "write a 100-line script, don't worry about explicitly documenting types, don't worry about grand architecture, don't worry about creating custom classes, don't worry about encapsulation and public/private". I've been with Python since year 2007 in the 2.x days, and Java since 2002.

Initial examples: Why go through the ceremony of `public static void main(String[] args)` when Python just executes the script line by line at the top level? Oh wait, now you have things like `import` actually executing code instead of simply being a compile-time namespace convenience, and you need weird techniques like `if __name__ == "__main__"`. Why `System.out.println()` when `print()` is so much more concise? But now you're polluting the global namespace, and `print(file=sys.stderr)` isn't that elegant either.

Static typing in Python is the biggest hypocrisy ever. As I understood it, Python scripts were meant to be lightweight and free of the tyranny of enterprise OOP which was epitomized by Java. But people found out that keeping track of types in your head is laborious and error-prone, and getting a compiler to check {that the shape of your objects and function calls match} is a huge productivity boost. And so Python 3 enabled static type hints... which, like I said before, Java had from day zero. To make matters worse, static type hint features were introduced progressively over the years, leading to things getting deprecated from the `typing` module and moved to things like `T|None` and `list[T]` and `collections.abc`.

IIRC the old practice in Python was that you specified some kind of interface in prose or in code (e.g. `class IoStream: def read(); def close()`), but you didn't need to explicitly use that interface as a superclass; you can just duck-type your way around things. But this completely goes against static typing, so I'm pretty sure the new preferred way is to explicitly use abstract superclasses... just like Java did all along (and is mandatory).

I really don't think having top-level (module) variables and functions in Python is a good thing, especially because then they are duplicated as fields and methods in classes. In Java, fields and methods (whether static or instance) can only be placed in classes, and I think this particular straitjacket is a good thing.

> because Python wants these things to be optional

We can both agree that Python gives multiple ways to do things (e.g. no static type hints vs. static type hints). This flies in the face of:

> Readability counts.

> The Zen of Python / There should be one-- and preferably only one --obvious way to do it. -- https://peps.python.org/pep-0020/

Probably the most tragic example is the ways to build up strings in Python: `+` and str(), `%` operator, `str.format()`, f-string.

(To be fair, I have a laundry list of complaints about Java too, such as: .class files and the JVM being an intermediate layer that needs to be understood which is actually different from the Java source language, lack of in-place structs so `new Point[]` is very painful on the memory system, awkward string interpolation/formatting compared to Python's f-strings, very awkward JDBC compared to for example Python sqlite3 API, kinda clunky for web server programming, very awkward JSON handling, enterprisey libraries and APIs that are perfectly documented but are impossible to actually understand.)

nayuki··on What we lost when we stopped letting kids leave the front yard
> lead to Dredd-like Mega Cities just taking over the entire continent

This is impossible. Look at even the densest cities today such as Hong Kong, with many 50-storey buildings packed closely. HK as a whole has maybe 25% land area allocated for buildings and the rest is forest and green space.

Or consider Tokyo - sure, it is a big sprawling metropolis and pretty much an uninterrupted patch of concrete. But the urban area does eventually end, and much of the land area of Japan is mountains, forests, farms, etc.

nayuki··on Opaque Types in Python
Java made opaque types possible from the very start by private and package-private constructors.

It's sad to see that many features regarding object-oriented programming and static typing are implemented worse in Python than Java. Various examples: __str__() vs. toString(); underscore vs. private; @staticmethod/@classmethod vs. static; generic types are so clunky in Python; types are not shown in the official Python standand library documentation; __init__() doesn't force you to call super() whereas it's mandatory in Java; @override (Python 3.12; year 2023) copying Java @Override (JDK 1.5; year 2004) very late; convention changing from duck typing (always available in Python) to structural typing (optional in Python, mandatory in Java).

nayuki··on US bill proposes new national EV tax, while some push to slash gas tax to zero
I agree with your comment a lot. My ideal for road pricing is something like a https://en.wikipedia.org/wiki/Vehicle_miles_traveled_tax multiplied by weight (maybe squared, due to the https://en.wikipedia.org/wiki/Fourth_power_law of road damage).

I do think that a lot of people think that public roads are "free" and cost nothing to build and maintain. It is really hard to make people think about where the labor, materials, and funding come from.

nayuki··on US bill proposes new national EV tax, while some push to slash gas tax to zero
It's not flawed logic though. If, say, a mile of highway costs $1 million and it needs some expensive repaving/reconstruction every 20 years, who should bear the cost?

The current model is roughly that all of society shoulders the cost roughly equally per person, regardless of how much they use that road or how much they drive in general. But clearly, some people derive more benefit from the road than others. The guy who doesn't drive derives 0 units of benefit. The gal who drives on it once a year derives 1 unit of benefit. The daily commuter gets 100 units of benefit. For the trucker moving $10M of goods a year on that road, their company gets 3000 units of benefit. So in a sense, the people who drive less are subsidizing the people who drive more - kind of like going to a fixed-price buffet dinner (people who eat more are subsidized by people who eat less).

Targeting more of the cost burden on heavy goods vehicles isn't an issue in my opinion. The thing is, that highway costs $1M no matter what. The only thing we can decide as a society is how to split that cost among the people. In the current way, I think the truck is underpriced and is doing more than its fair share of damage. If we change the prices so that car drivers pay less (not zero) and the truck driver pays more, that's okay. The truck's costs get passed onto consumer, such that people who buy more goods pay more road tax - exactly as intended.

Taking a step back, I think a lot of (not all) problems in society are a result of mispricing - often for political, special-interest, and/or "feel-good" reasons. When people pay less than the true cost, they over-consume. When people pay more than the true cost, they under-consume.

nayuki··on US bill proposes new national EV tax, while some push to slash gas tax to zero
When it comes to any good or service, there are only two choices: the user pays, or other people pay. The status quo is that drivers pay a lot for roads through gasoline taxes and vehicle registration fees, but the rest of society (including non-drivers) pay through income taxes, sales taxes, and property taxes. Moreover, a lot of taxes paid for road construction/maintenance are not proportional to how much you drive; a driver doing double the miles in a year is paying less than twice of another driver.

Please explain your ideal scenario of who pays for roads. And if your answer is "someone else" (e.g. "taxes", "government", "corporations", "billionaires"), further explain why "someone else" can't use the same argument to make you pay.

← PreviousPage 2 of 34Next →