23 Apr 2023

Passing props to a Component in React

Example props

  • className
  • src
  • width

Basic Usage

Define component:

function Avatar({person, size}) {
    return (
        <img
            className="avatar"
            src="www.avatarurl.com"
            alt="person.name"
            width="size"
            height="size"
        />
    );
}

Pass props:

export default function Profile() {
    return (
        <Avatar
            person={{ name: "Carol", occupation: "Software Developer"}}
            size={100}
        />
    );
}   

Other ways to access props

function Avatar(props) {
    let person = props.person;
}

or

function Avatar({person, size}) {
    // ...
}

You can also specify the default value of a prop:

function Avatar({person, size = 100}) {
    // ...
}

Forwarding props with JSX spread syntax

Instead of this:

<div className="card">
    <Avatar
        person={person}
        size={size}
    />
</div>

Do this:

<div className="card">
    <Avatar {...props} />
</div>

The children prop

You can also pass JSX to a component. The component will receive it as a prop called children:

function Card({ children }) {
    return (
        <div className="card">
            {children}
        </div>
    );
}

<Card>
    <Avatar />
</Card>

18 Apr 2023

React Component State

  • setState schedules an update to a component’s state object. When state changes, the component re-renders.
  • Calls to setState are asynchronous for performance reasons.

Example

// Assume count starts at 0

incrementCount() {
  this.setState({count: this.state.count + 1});
}

handleSomething() {
  this.incrementCount();
  this.incrementCount();
  this.incrementCount();

When react re-renders this component the state will be 1 even though we called it three times.

→ Why? React doesn’t update this.state.count until the component is re-rendered. incrementCount() ends up reading count as 0 three times.

Fix: Pass an update function:

incrementCount() {
  this.setState((state) => {
    // Use state, not this.state cause it's a parameter
    return {count: state.count + 1} 
  });
}

Difference between state and props

  • both plain JS objects
  • props get passed to the component (similar to function parameters)
  • state is managed within the component

15 Apr 2023

Powerlvl10k Icons Not Working

  1. Download these four ttf files (most likely you’ll only need this one MesloLGS NF Regular.ttf):
  2. Double-click on each file and click "Install". This will make MesloLGS NF font available to all applications on your system.

  3. Open Settings in Visual Studio Code: Code → Preferences → Settings.

  4. Enter terminal.integrated.fontFamily in the search box at the top of Settings tab and set the value below to MesloLGS NF.

11 Apr 2023

Node.js OpenSSL issue

The algorithm being used for hashing is not supported by your version of OpenSSL.

library: 'digital envelope routines',
reason: 'unsupported',
code: 'ERR_OSSL_EVP_UNSUPPORTED'

Solution

Add this to your .zshrc

export NODE_OPTIONS=--openssl-legacy-provider

09 Apr 2023

Mac Setup

Run Homebew script

git clone https://gist.github.com/2e8440007c55d914e05ec61f3b20635a.git && cd 2e8440007c55d914e05ec61f3b20635a && sh install.sh

Run dotfiles install script

git clone https://github.com/vnctptr/dotfiles.git && cd dotfiles && sh bootstrap.sh

Install CLI tools

15 Mar 2023

Turing Completeness

Turing machine is an endless piece of tape with 2 heads, one for reading, one for writing. It can compute anything that can be computed.

A language that is Turing complete when it is able to do anything a Turing machine can do.

Conditions

  1. Has conditional branching (if statements)
  2. Able to have an arbitrary amount of memory (as much as the problem needs).

Fun fact: CSS is Turing-complete.

08 Mar 2023

Structural Design Patterns

  • Facade:

    • basically a simplified API
    • jQuery is a facade for JavaScript features
class House {
    private plumbing = new Plumbing();
    private electrical = new Electrical();

    public turnOnSystems() {
        this.plumbing.on();
        this.electrical.setVoltage(120);
    }   
}
  • Proxy:

    • Replace a target object with a proxy, eg. to override functions
    • Controls access to the original object, allowing you to perform something either before or after the request gets through to the original object
    • Why? For example you have a large object that you only need occasionally.
    • Create a new proxy class with the same interface as an original object → update your app so that it passes the proxy object to all of the original object’s clients → the proxy creates a real service object and delegates all the work to it.
    • Benefit: If you need to execute something either before or after the primary logic of the class, the proxy lets you do this without changing that class.

06 Mar 2023

Behavioral Design Patterns

  • Iterator: traverses a collection of objects
  • Observer:
    • A subscription mechanism that notifies multiple objects (one-to-many) about events,
    • e.g. subscribe → next in JS.
  • Mediator:
    • Solves a many-to-many problem,
    • Restricts direct communications between the objects and forces them to collaborate only via a mediator object,
    • eg. in express middleware that intercepts request.
  • State:
    • Alternative to a “switch” or “if” statement,
    • Finite number of states,
    • Closely related to the concept of finite state machines.

02 Mar 2023

Creational Design Patterns

  • Singleton:
    • a type of object that can only be instantiated once
    • often used in C++
class Settings {
    static instance: Settings;
    public readonly mode = "dark";

    private constructor() { // a private constructor ensures no one else can create it
        ...
    };
  • Prototype:

    • a clone
    • alternative to inheritance, which can create complex tree patterns
    • instead of inheriting from a class it inherits form an object that’s already been created
    • creates a flat prototype chain
  • Builder:

    • building object step by step using methods instead of all at once

Do:

addKetchup() {
 this.ketchup = true;
}

Don’t:

constructor(
    public ketchup: boolean;
) {};
  • Factory:

    • e.g. We have 2 similar classes (eg. one for iOS one for Android) we could do this:

Do:

class ButtonFactory {
    createButton(os: string) : IOSButton | AndroidButton {
        if (os === 'ios') {
                return new IOSButton();
        else {
                return new AndroidButton();
        }

const button = ButtonFactory('ios');

Don’t:

const button = os === 'ios' ? 
                             new IOSButton :
                             new AndroidButton;

16 Feb 2023

Activation Functions in Machine Learning

Used to get the output of the node. It is also known as the Transfer Function.

Why do we use them?

  • Determine the output of a neural network.
  • Maps the resulting values in between 0 to 1, -1 to 1 etc.

Linear/Identity Activation Function

  • Output not confined behind any range.

  • f(x) = x

Sigmoid (Logistic Activation Function)

  • Range: 0 to 1
  • Used for models that try to predict probability

Softmax

A more generalized logistic activation function, used for multiclass classification.

Tanh

  • Like sigmoid but ranges from -1 to 1.
  • Advantage over sigmoid: negative inputs will be mapped strongly negative and 0 will be mapped to 0.
  • Mainly used in classification between 2 classes.

ReLU

  • Very popular right now (used for deep learning).
  • Range: 0 to infinity
  • Disadvantages: all the negative values become zero, which decreases the ability of model to fit or train from data.

Leaky ReLU

  • Attempts to solve the “dying” ReLU problem.
  • Usually uses the f(x) = 0.01x function for the left side of the graph.
  • Range: -infinity to infinity

15 Feb 2023

Circuit-Switched Networks

  • Relies on a physical connection between two distinct network nodes,
  • Requires the link to be set up before the nodes can communicate,
  • Data is transferred directly across an already chosen and dedicated channel without interruption until the complete information has been sent to the destination and the communication link ends,
  • Created in 1878 and is the technology on which Alexander Bell built his telephone.

31 Jan 2023

Creating a new Rails page

Scaffolding

Creates a new page with model, view, and controller, including CRUD operations.

rails g scaffold Person name:string quote:text
rails db:migrate

Simple Page

Does not create a model or CRUD operations.

rails g controller Person index

18 Jan 2023

Software Design Principles

KISS (Keep It Simple, Stupid)

  • Keep things simple and avoid unnecessary complexity in a system.
  • Avoid installing an entire library for the sake of one function.
  • Only implement what is asked and needed at the moment.
  • Ensure that each method solves one specific problem.
  • Move logic to helper functions.
  • Instead of creating a project architecture or directory from scratch, look for examples and choose the best one.

YAGNI (You are not gonna need it)

  • Implement only what is needed at the moment.
  • Get rid of any code that is not necessary.
  • Programmers should not include new features that have not been requested.

DRY (Don’t Repeat Yourself)

  • Avoid copying code.
  • Before adding functionality, check if it has already been created in the project.

Occam’s Razor

  • Entities should not be created unnecessarily.
  • Start with simple code and gradually increase complexity.

BDUF (Big Design Up Front)

  • Ensure that everything is planned out before starting implementation.
  • Divide the requirements into multiple stages and prioritize them accordingly.

03 Jan 2023

Ruby on Rails Cheat Sheet

Basic Commands

Start the Rails server

rails s

Scaffolding

Creates a table and pages to create new entires

rails g scaffold Note title:string description:text
rails db:migrate

Simple Page

Does not create a model or CRUD operations.

rails g controller Person index

03 Jan 2023

Latent Space

Latent (lat. being hidden) space is a representation on compressed data. Is used to simplify the data representation for the purpose of finding patterns.

In machine learning data is compressed (using lossy compression by definition) to learn important information about data points. This happens in the encoding stage,

The value of compression is that it allows us to discard the noise and only leave the information we need for learning →This “compressed state” is the Latent Space Representation.

The model needs to store all the relevant information, because it is then required to reconstruct the compressed data (in the decoding stage).

What does it look like?

Latent space is usually a matrix that we can use to perform different operations on.

A useful property of the latent space is that “similar” values (eg. colour of object) will be closer to one another in the latent space.

(Note: “closeness” is is an ambiguous term as different models use different algorithms to denote “closeness”).

Autoencoders and Generative Models

  • Autoencoder is a neural network that acts as an identity function, it outputs whatever is inputted. But we don’t care so much about what the model outputs. We care more about what the model learns in the process.
  • When force a model to act as an identity function we are forcing it to store all the relevant features in a compressed way → The model can later reconstruct it.
  • Similar data points in the latent space tend to cluster together, and we can later sample the points from the latent space to generate new data.
  • Here’s an example of image generation through latent space interpolation:

03 Nov 2022

Hotfix, Bugfix, Coldfix, Patch

Hotfix

→ In production environment

Bugfix

→ In development environment

Coldfix

  • Scheduled in advance,
  • Usually with system outage,
  • Users are notified in advance.

Patch

  • Temporary fix,
  • Often automatic, with self-install packages,
  • Usually planned, between full releases of software.

10 Oct 2022

Cross-Site Scripting

What is XSS?

→ web security vulnerability

→ usually allows an attacker to masquerade as a victim user

How does XSS work?

  • manipulate website to return malicious JavaScript to users
  • it’s common practice to use the alert() function for this purpose because it's short, harmless, and pretty hard to miss when it's successfully called
  • you solve the majority of our XSS labs by invoking alert()  in a simulated victim's browser

How to prevent XSS attacks

  • filter input on arrival
  • encode user-controlled data on output to prevent it from being interpreted as active content
  • use appropriate response headers:
    • for responses that aren’t intended to contain HTML or JS use Content-Type  and X-Content-Type-Options to define content

06 Oct 2022

Packet Switching

  • At the destination packets belonging to the same file have to be reassembled
  • packet switching uses Store and Forward technique → packet switches must receive a packet in its entirety before forwarding to the next switch in the network.
  • Packet-Switched networks were designed to overcome the weaknesses of circuit-switched networks since circuit-switched networks were not very effective for small messages.

Advantages

  • more reliable thanks to Store and Forward
  • more fault tolerant ← packets may follow different path in case a link is down
  • cheaper to implement

Disadvantages

  • doesn’t give packets in order → need to provide sequence numbers for each packet
  • beneficial only for small messages, circuit switching better for large data

18 Jul 2022

Latency vs Throughput vs Bandwidth

Latency

→ Total time of delay between the time a user takes an action and the time they receive a response.

  • so called “round-trip
  • measured in milliseconds
  • impossible to have a zero-latency network
  • good latency < 150 ms

What Affects Latency?

Transmission Medium (eg. copper) can affect latency. Fibre optic cables are generally better than copper.

Routers and the speed at which they receive and forward data.

Bandwidth

→ the amount of data that can pass through a network at a given time

  • measured in kb/mb/gb per second

Throughput

→ The amount of data that can pass through, on average, over a specific period of time.

Throughput vs Bandwidth

Bandwidth is the potential speed of a connection.

Throughput is the actual speed.

24 Jun 2022

Stored Procedure

Stored procedure is a prepared SQL code that you can save, so the code can be reused over and over again.

Creation

CREATE PROCEDURE procedure_name
AS
sql_statement
GO;

Execution

EXEC procedure_name;