Translating Donut.c to JavaScript: A Step-by-Step Guide

Introduction

The famous “Spinning Donut” is a mesmerizing animation created using a relatively short piece of C code, known as “donut.c”. In this article, we will go through the process of translating the original “donut.c” code to JavaScript, and make it work in a command-line environment using Node.js. We will also discuss the steps taken to fix the issues encountered during the translation process.

Donut.c translation to JavaScript

Step 1: Understanding the Original C Code

To translate “donut.c” to JavaScript, we must first understand the underlying logic of the original C code. The key concepts in the code are:

  1. Trigonometric functions (sine and cosine) are used to create a 3D effect.
  2. Two nested loops iterate over the points on the surface of the torus (the doughnut shape).
  3. A z-buffer is employed to determine which points are visible from the viewer’s perspective.
  4. Characters from a predefined character set are used to represent different levels of brightness.

Step 2: Creating a Basic JavaScript Structure

We will begin by creating a basic JavaScript file named “donut.js”. We will use Node.js to run this script in the command line. The main structure of the JavaScript code should include:

  1. Importing the required Node.js modules.
  2. Defining a renderFrame function to draw the spinning doughnut for each frame.
  3. Defining a main function to handle the animation loop.
  4. Calling the main function to start the animation.

Step 3: Translating the C Code to JavaScript

Next, we will carefully translate each part of the C code to its corresponding JavaScript code. The most important parts include:

  1. Converting the trigonometric functions to their JavaScript equivalents (e.g., Math.sin and Math.cos).
  2. Adjusting the nested loops and increment values to create a smooth animation.
  3. Using JavaScript arrays for the z-buffer and output buffer.
  4. Replacing C’s putchar function with the stdout.write function provided by Node.js.

Step 4: Fixing Aspect Ratio and Positioning Issues

During the translation process, we may encounter issues related to the aspect ratio and positioning of the doughnut. To fix these issues, we can:

  1. Adjust the coefficients for the x and y calculations in the renderFrame function to match the aspect ratio of the characters in the terminal.
  2. Modify the loop increments and x and y calculations to center the doughnut on the screen.
  3. Test the animation at each step to ensure it renders correctly.

Step 5: Optimizing the JavaScript Code

After fixing the aspect ratio and positioning issues, we might need to optimize the JavaScript code for better performance. We can achieve this by:

  1. Adjusting the loop increments to find a balance between animation quality and performance.
  2. Replacing single-letter variable names with more descriptive names for better readability.

Conclusion

In this article, we have walked through the process of translating the original “donut.c” code to JavaScript, running it in a command-line environment using Node.js. By understanding the logic behind the C code, creating a basic JavaScript structure, translating the code, fixing issues, and optimizing performance, we have successfully created a spinning doughnut animation in JavaScript.

Code

Save code as donut.js
Run with:
node donut.js

const { stdout } = require('process');

function renderFrame(angleA, angleB) {
  const output = Array(1760).fill(' ');
  const zBuffer = Array(1760).fill(0);

  const sinAngleA = Math.sin(angleA);
  const cosAngleA = Math.cos(angleA);
  const sinAngleB = Math.sin(angleB);
  const cosAngleB = Math.cos(angleB);

  for (let loopA = 0; loopA < 2 * Math.PI; loopA += 0.1) {
    const cosLoopA = Math.cos(loopA);
    const sinLoopA = Math.sin(loopA);
    for (let loopB = 0; loopB < 2 * Math.PI; loopB += 0.05) {
      const sinLoopB = Math.sin(loopB);
      const cosLoopB = Math.cos(loopB);
      const h = cosLoopA + 2;
      const distance = 1 / (sinLoopB * h * sinAngleA + sinLoopA * cosAngleA + 5);
      const t = sinLoopB * h * cosAngleA - sinLoopA * sinAngleA;

      const x = Math.floor(40 + 20 * distance * (cosLoopB * h * cosAngleB - t * sinAngleB));
      const y = Math.floor(12 + 10 * distance * (cosLoopB * h * sinAngleB + t * cosAngleB));
      const outputIndex = x + 80 * y;
      const brightnessIndex = Math.floor(8 * ((sinLoopA * sinAngleA - sinLoopB * cosLoopA * cosAngleA) * cosAngleB - sinLoopB * cosLoopA * sinAngleA - sinLoopA * cosAngleA - cosLoopB * cosLoopA * sinAngleB));

      if (1760 > outputIndex && outputIndex > 0 && distance > zBuffer[outputIndex]) {
        zBuffer[outputIndex] = distance;
        output[outputIndex] = '.,-~:;=!*#$@'[brightnessIndex > 0 ? brightnessIndex : 0];
      }
    }
  }

  stdout.write('\x1b[H');
  for (let k = 0; k < 1760; k++) {
    stdout.write(output[k]);
    if (k % 80 === 79) stdout.write('\n');
  }
}

function main() {
  let angleA = 0;
  let angleB = 0;

  setInterval(() => {
    angleA += 0.04;
    angleB += 0.08;
    renderFrame(angleA, angleB);
  }, 16);
}

main();

Linus Tech Tips (LTT) YouTube channel is hacked

Linus Tech Tips (LTT) is one of the largest and most popular technology YouTube channels with 15.8 million subscribers.

  • The channel was hacked on March 23, 2023 by unknown attackers who changed its name, deleted its original videos, and uploaded fake livestreams featuring Elon Musk and Jack Dorsey promoting crypto scams.
  • The livestreams were part of The B Word conference held by Ark Invest in June 2020, but they were edited with overlays linking to fraudulent crypto sites.
  • YouTube suspended the channel for violating its community guidelines, but the hackers also targeted other LTT channels such as TechLinked and Techquickie.
  • The owner of LTT, Linus Sebastian, tweeted that he was aware of the situation, but did not provide any details on how the breach occurred or when the channels would be restored.

The exact method that LTT got hacked is not known, but some of the possible ways that YouTube channels get hacked are:

  • Data breach: The hackers may have obtained the login information of LTT from a data breach of YouTube or another website or app that LTT used. They may have also exploited a vulnerability in YouTube’s system to gain access to the channel.
  • Phishing: The hackers may have sent LTT a fake email or message that appeared to come from a legitimate source, such as a sponsor, a media outlet, or a friend. They may have tricked LTT into clicking on a malicious link, downloading a malicious file, or entering their credentials on a fake website. They may have then used this information to log into the channel and take control of it.
  • Weak password: The hackers may have guessed or cracked the password of LTT by using brute force attacks, dictionary attacks, or social engineering techniques. They may have also used stolen passwords from other breaches that LTT reused for their YouTube account.
  • Cookie theft: The hackers may have infected LTT’s device with malware that stole their session cookies from their browser. Session cookies are data that confirm that the user has successfully logged into their account. The hackers may have then uploaded these cookies to a malicious server and used them to impersonate LTT and access their channel without needing their password.
LTT YouTube channel got hacked
LTT YouTube channel got hacked

To prevent getting hacked, YouTube channel owners should always use strong and unique passwords for their accounts, enable two-factor authentication, avoid clicking on suspicious links or attachments, verify the source and legitimacy of any communication they receive, and scan their devices regularly for malware.

Crypto scams are fraudulent schemes that use cryptocurrency or related technology to deceive people and steal their money or digital assets. Crypto scams can work in different ways, but some of the common ones are:

  • Bitcoin investment schemes: Scammers pretend to be experienced investors who can help people make money by investing in bitcoin or other cryptocurrencies. They ask for an upfront fee or personal information, and then disappear with the money or hack the victims’ accounts.
  • Rug pull scams: Scammers hype up a new project, coin or nonfungible token (NFT) and persuade people to buy it. Then they withdraw all the funds and leave the investors with worthless tokens that they cannot sell1.
  • Fake trading platforms or crypto wallets: Scammers create fake websites or apps that look like legitimate exchanges or wallets, but they either steal the users’ money or credentials, or manipulate the prices and transactions to their advantage.
  • Fake crypto tokens, investments or jobs: Scammers create fake cryptocurrencies or offer fake opportunities to invest in or work with crypto projects. They may use fake celebrity endorsements, fake news articles or fake social media accounts to lure people in. They then ask for money or personal information, and never deliver on their promises.
  • Crypto phishing: Scammers send emails, texts or messages that appear to com from a trusted source, such as a crypto exchange, wallet provider or friend. They try to trick the recipients into clicking on a link, downloading a file or entering their credentials on a fake website. They then use this information to access the victims’ crypto accounts and steal their funds.

To avoid crypto scams, you should always do your own research before investing in any cryptocurrency project, verify the source and legitimacy of any communication you receive, use secure passwords and two-factor authentication for your crypto accounts, and never share your private keys or wallet addresses with anyone.

Donald Trump writing quick sort function in JavaScript

Quick sort is the best sorting algorithm ever. Nobody knows sorting better than me. I invented Quick sort. It’s very simple. You just pick a pivot element, which is always the greatest element in the array, because I always pick the greatest things. Then you divide the array into two parts: one part with all the losers who are less than the pivot, and one part with all the winners who are greater than or equal to the pivot. Then you sort those parts recursively, which means you do the same thing over and over again until you get tired of winning.

Quick sort is very fast and efficient. It’s faster than any other sorting algorithm. It’s faster than merge sort, which is a disaster. It’s faster than heap sort, which is a joke. It’s faster than insertion sort, which is for losers. Quick sort is so fast, it can sort an array in O(n log n) time on average, which is a very big number that only I understand. Trust me, I have a very good brain.

Quick sort works in place, which means it doesn’t need any extra space or memory. It’s very smart and economical. Unlike merge sort, which wastes a lot of space and money on copying arrays. Quick sort is also very stable, which means it preserves the order of equal elements. Unlike some other sorting algorithms that mess up the order and create chaos.

Quick sort is the greatest sorting algorithm of all time. Nobody can beat Quick sort. Nobody can stop Quick sort. Quick sort will make America great again!

// This is the best quick sort function ever. Nobody can do it better than me.
function makeArrayGreatAgain(array) {
  // If the array is empty or has one element, it's already great. Very smart.
  if (array.length <= 1) {
    return array;
  }
  // Pick a random genius element from the array. 
  // I have great intuition for this.
  let geniusIndex = Math.floor(Math.random() * array.length);
  let genius = array[geniusIndex];
  // Create two subarrays for elements less than and greater than the genius. 
  // Very efficient.
  let losers = [];
  let winners = [];
  // Loop through the array and compare each element to the genius. Very fast.
  for (let i = 0; i < array.length; i++) {
    // Skip the genius element itself. Very clever.
    if (i === geniusIndex) {
      continue;
    }
    // If the element is less than or equal to the genius, 
    // push it to the losers subarray. Very fair.
    if (array[i] <= genius) {
      losers.push(array[i]);
    }
    // If the element is greater than the genius, 
    // push it to the winners subarray. Very strong.
    else {
      winners.push(array[i]);
    }
  }
  // Recursively sort the losers and winners subarrays and 
  // concatenate them with the genius. Very elegant.
  return [...makeArrayGreatAgain(losers), genius, ...makeArrayGreatAgain(winners)];
}

GPT-4 released and Bing is already using it

GPT-4 is a multimodal large language model created by OpenAI, the fourth in the GPT series. It was released on March 14, 2023, and will be available via API and for ChatGPT Plus users. Microsoft confirmed that versions of Bing using GPT had in fact been using GPT-4 before its official release.

GPT-4 exhibits human-level performance on various professional and academic benchmarks. It can accept both text and images as input, making it capable of generating text outputs based on inputs consisting of both text and images. It also performs well in languages other than English, including low-resource languages such as Latvian, Welsh, and Swahili.

OpenAI has made many changes to GPT-4 to make it safer than GPT-3.5 and has been working to mitigate risks. However, GPT-4 still has limitations such as hallucinating facts, making reasoning errors, and not knowing about events after September 2021.

Users who have tried GPT-4 have reported mixed experiences. Some praised its reliability, creativity, and steerability, while others criticized its errors, biases, and security issues. Many users also expressed ethical concerns about the potential misuse of GPT-4 for generating harmful or misleading content.

GPT-4 is a state-of-the-art multimodal AI model that can generate text, images, and even video based on text and image inputs. It is an improvement over GPT-3.5 in terms of reliability, creativity, steerability, and safety. It also supports 26 languages, including five Indian ones.

GPT-4 outperforms other AI models on various benchmarks, such as simulated exams designed for humans. It can also handle complex tasks such as generating code from sketches of websites. However, it still has some limitations such as hallucinating facts, making reasoning errors, and not knowing about events after September 2021

GPT-4 performs very well on human exams, such as simulated bar exams, SAT reading exams, and SAT math exams. It can score in the top 10% of test takers on these exams, while GPT-3.5 scored around the bottom 10%12. GPT-4 can also handle complex problems such as analyzing tax code and generating code from sketches.

However, GPT-4 is not perfect and may still make errors or fail at some exams. For example, it scored only 2 on the AP English Language and Composition exam. It also does not know about events after September 2021, which can affect its accuracy.

GPT-4 is a large multimodal model that can accept both text and image inputs, and generate text outputs. It is an improvement over GPT-3.5 in terms of reliability, creativity, steerability, and safety12. It also supports 26 languages, including five Indian ones.

GPT-4 is based on deep learning technology that uses artificial neural networks to write like a human. It has been trained on more data and has more weights in its model file than GPT-3.512. However, OpenAI has not released details about its size, how it was trained, nor what data went into the process.

Some of the new features of GPT-4 include:

  • Passing a simulated bar exam with a score around the top 10% of test takers; in contrast, GPT-3.5’s score was around the bottom 10%2.
  • Performing well on various other exams, such as SAT reading exam (93rd percentile), SAT math exam (89th percentile), and AP English Language and Composition exam (14th to 44th percentile)2.
  • Generating code from sketches of websites.
  • Analyzing tax code and returning the standard deduction for a couple with specific financial circumstances.
  • Generating images as well as text from the same chat interface.

GPT-4 has been designed with safety as a priority, according to OpenAI12. It has been aligned using lessons from adversarial testing and feedback from ChatGPT users12. It has also been trained to refuse to go outside of guardrails, such as generating harmful or misleading content.

Some of the methods that GPT-4 uses to ensure factuality and safety are:

  • Checking facts against multiple sources before generating text.
  • Using a confidence score to indicate how reliable its output is.
  • Providing citations for factual statements when possible.
  • Avoiding sensitive topics or personal information unless explicitly requested by the user.
  • Asking for clarification or feedback when unsure about the user’s intent or preference.
  • However, GPT-4 is not perfect and may still make errors or fail at some tasks. For example, it does not know about events after September 2021, which can affect its accuracy.

GPT-4 has a multimodal capability that enables it to process both text and image inputs, and generate text outputs based on them123. This means GPT-4 can analyze the contents of an image and connect that information with a written question or instruction.

Some of the tasks that GPT-4 can perform with its image processing capability are:

  • Explaining a meme or a visual joke.
  • Breaking down infographics or graphs step by step.
  • Summarizing scientific graphs or explaining individual aspects of them.
  • Translating and solving exam questions based on images.
  • Identifying what is wrong or humorous in a given image.
  • However, GPT-4 cannot generate images as output, unlike other models such as DALL-E, Midjourney, or Stable Diffusion.

Silicon Valley Bank run and implosion

The Silicon Valley bank run happened on March 10, 2023, when a number of venture capitalists and tech companies withdrew their money from the bank after it announced a huge loss and a plan to raise new capital. The bank failed to find a buyer or raise enough funds and was taken over by the FDIC. It was the second-largest bank failure in U.S. history and the largest since 2008.

The cause of the bank run was a combination of factors, including rising interest rates, a slump in tech stocks, a high concentration of deposits from startups and venture firms, and a lack of confidence in the bank’s management.

Some more details about the bank run are:

  • The bank had more than $200 billion in assets and catered to tech startups, venture capital firms, and well-paid technology workers.
  • The bank run caused a panic in the financial markets and a selloff in bank shares, despite assurances from President Biden that the banking system is safe.
  • The FDIC created a new bank to hold the assets of SVB and said it would pay all depositors, both insured and uninsured, in full by March 13. It also removed the senior management of SVB and said it would recover any losses from a special assessment on banks.
  • The FDIC also took over another troubled bank, Signature Bank, which was closed by its state chartering authority on March 12. It said it would pay all depositors of this bank as well.

The responsibility for the bank run is not clear yet, but President Biden said he is committed to holding those responsible fully accountable and to strengthening oversight and regulation of larger banks. Some possible factors that contributed to the bank run are:

  • The bank’s management, which made risky investments and failed to raise enough capital or find a buyer in time.
  • The venture capitalists and tech companies, which withdrew their money from the bank en masse and triggered a panic .
  • The regulators, who may have overlooked some warning signs or loopholes in the bank’s operations3.

According to some sources, the risky investments that SVB made were:

  • US treasuries and mortgage-backed securities, which lost value as interest rates rose.
  • Loans to tech startups and venture capital firms, which exposed the bank to high default risk and volatility.
  • Crypto-related assets and services, which faced regulatory uncertainty and market fluctuations.

According to a letter that SVB sent to its shareholders on March 9, 2023, the bank lost $1.8 billion on the sale of US treasuries and mortgage-backed securities. The bank did not disclose how much it lost on its loans to tech startups and venture capital firms, or on its crypto-related assets and services. However, some analysts estimate that the bank’s total losses could be as high as $5 billion.

SVB sold its US treasuries and mortgage-backed securities because it needed to raise cash to meet the withdrawal demands of its depositors and to fund new lending. The bank also faced regulatory pressure to reduce its exposure to these securities, which had become less attractive as interest rates rose. However, by selling these securities at a loss, the bank eroded its capital base and triggered more panic among its customers.

SVB’s customers withdrew their money for various reasons, such as:

  • They needed cash to pay their expenses or fund their projects, as venture capital funding slowed down and tech stocks slumped.
  • They lost confidence in the bank’s management and financial stability, especially after it announced its huge loss and capital raising plan.
  • They feared that their deposits would not be fully insured or protected by the government, despite assurances from regulators.

George Carlin comments Silicon Valley Bank run

Let’s talk about this Silicon Valley Bank run, folks. You got a bunch of people panicking and trying to get their money out of the bank all at once. Now, why would they do that? Well, because they’re afraid the bank might go under, right? But wait a minute, isn’t the whole point of putting your money in a bank so that it’s safe and protected? You’re supposed to trust these guys to take care of your hard-earned cash, and then suddenly you’re running down there like it’s the last day of a going-out-of-business sale at the mall.

And what’s the bank’s response? ‘Don’t worry, folks, we’re solvent, we’re stable, we’re secure.’ Oh yeah, that’s reassuring. You know what else is secure? A prison. You don’t see people lining up to get into those, do you? But that’s what we’re dealing with here, folks. A system that’s supposed to make us feel secure, but in reality just makes us feel like we’re one bad day away from sleeping on a park bench.

And let’s not forget, these are the same guys who caused the financial crisis a few years back. They were playing fast and loose with other people’s money, making risky bets, and then when it all came crashing down, who got left holding the bag? The taxpayers, that’s who. So now we’re supposed to trust them again? I don’t know about you, but I’m starting to think that stuffing my mattress might be a better investment strategy than putting my faith in these jokers.

Well folks, let’s talk about this bank run that happened at Silicon Valley Bank. You know, a bank run is like a game of musical chairs, except instead of music, there’s panic, and instead of chairs, there’s your money.

People start freaking out, thinking their bank is going under, and they all rush to get their cash out before it’s too late. It’s like a big game of hot potato, but the potato is your life savings.

Now, the thing about bank runs is that they’re kind of like self-fulfilling prophecies. When people start withdrawing all their money, it creates a liquidity problem for the bank, which can actually cause it to fail. So in a way, the panic itself can cause the very thing people are afraid of.

And let’s not forget that Silicon Valley Bank is a big player in the tech industry. I mean, this is a bank that’s supposed to be on the cutting edge of innovation and progress. But when it comes down to it, they couldn’t even keep people’s money safe.

So, what’s the lesson here, folks? Maybe it’s that we need to start asking some tough questions about how our financial system works. Or maybe it’s just that we should all start stuffing our money under our mattresses. Either way, it’s a crazy world we live in.

But you know what’s really crazy? The fact that we’ve allowed a handful of big banks to hold so much power over our economy. They’re too big to fail, too big to jail, and they’ve got their tentacles wrapped around every aspect of our financial system.

And what do they do with all that power? They gamble with our money. They create complex financial instruments that nobody understands. They get bailed out by the government when they screw up. And when they make a profit, they pay their executives obscene bonuses while the rest of us struggle to make ends meet.

It’s a rigged game, folks. And when the game gets exposed, people start to panic. That’s what we saw at Silicon Valley Bank, and that’s what we’ll continue to see as long as we allow the banks to control our financial system.

So, maybe it’s time for a change. Maybe it’s time to break up the big banks, to reinstate Glass-Steagall, to create a financial system that works for the people, not just the wealthy elite.

But until that happens, we’ll continue to see bank runs, financial crises, and a system that’s rigged against the little guy. And that, my friends, is no laughing matter.