thoughtSpace
TwitterGithubRSS Feed

Note Space

Hints, cheat sheets and notes on code.

Snippets

ML scripts


## Regression Evaluation Metrics


Here are three common evaluation metrics for regression problems:

**Mean Absolute Error** (MAE) is the mean of the absolute value of the errors:

$$\frac 1n\sum_{i=1}^n|y_i-\hat{y}_i|$$

**Mean Squared Error** (MSE) is the mean of the squared errors:

$$\frac 1n\sum_{i=1}^n(y_i-\hat{y}_i)^2$$

**Root Mean Squared Error** (RMSE) is the square root of the mean of the squared errors:

$$\sqrt{\frac 1n\sum_{i=1}^n(y_i-\hat{y}_i)^2}$$

Comparing these metrics:

- **MAE** is the easiest to understand, because it's the average error.
- **MSE** is more popular than MAE, because MSE "punishes" larger errors, which tends to be useful in the real world.
- **RMSE** is even more popular than MSE, because RMSE is interpretable in the "y" units.

All of these are **loss functions**, because we want to minimize them.
// configueStore and typescript
const composeEnhancers = window['__REDUX_DEVTOOLS_EXTENSION_COMPOSE__'] as typeof compose || compose;

//or

declare global {
    interface Window {
      __REDUX_DEVTOOLS_EXTENSION_COMPOSE__?: typeof compose;
    }
}

export default function configureStore(initialState: any) {
    const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
    return createStore(rootReducer,initialState,composeEnhancers(applyMiddleware(authMiddleware, logger,thunk)))

}
refusing to merge unrelated histories
 --allow-unrelated-histories
// Redirect to top of page
import { useEffect } from "react";
import { useLocation } from "react-router-dom";

export default function ScrollToTop() {
  const { pathname } = useLocation();

  useEffect(() => {
    window.scrollTo(0, 0);
  }, [pathname]);

  return null;
}

<ScrollToTop />

<Routes>
// Sum a property per object in an array
let sum =0
incomes.forEach(income => {
  sum += income.total;
});

const sum2 = incomes.reduce((accumulator, income) => {
  return accumulator + income.total;
}, 0);


var pets = ['dog', 'chicken', 'cat', 'dog', 'chicken', 'chicken', 'rabbit'];

var petCounts = expenses.reduce(function(obj, expense){
    if (!obj[expense.category]) {
        obj[expense.category] = 1;
    } else {
        obj[expense.category]++;
    }
    return obj;
}, {});

/*
Output:
 { 
    dog: 2, 
    chicken: 3, 
    cat: 1, 
    rabbit: 1 
 }
 */


const myUsers = [
    { name: 'shark', likes: 'ocean' },
    { name: 'turtle', likes: 'pond' },
    { name: 'otter', likes: 'fish biscuits' }
]

const usersByLikes = myUsers.map(item => {
    const container = {};

    container[item.name] = item.likes;
    container.age = item.name.length * 10;

    return container;
})

// Output
// [
//     {shark: "ocean", age: 50},
//     {turtle: "pond", age: 60},
//     {otter: "fish biscuits", age: 50}
// ]


// Centering a div
         <div className="body-font container mx-auto mb-8 items-center">

            <section className="text-gray-600 body-font overflow-hidden">
  <div className="container px-5 py-24 mx-auto">
    <div className="flex flex-wrap -m-12">
    <div className="flex flex-col items-center justify-center px-6 py-8 mx-40 md:h-screen lg:py-0">


        <div className="p-12 flex flex-col items-start">
            <span className="inline-block py-1 px-2 rounded bg-indigo-50 text-indigo-500 text-xs font-medium tracking-widest">CATEGORY</span>
            <h2 className="sm:text-3xl text-2xl title-font font-medium text-gray-900 mt-4 mb-4">Roof party normcore before they sold out, cornhole vape</h2>
            <p className="leading-relaxed mb-8">Live-edge letterpress cliche, salvia fanny pack humblebrag narwhal portland. VHS man braid palo santo hoodie brunch trust fund. Bitters hashtag waistcoat fashion axe chia unicorn. Plaid fixie chambray 90's, slow-carb etsy tumeric. Cray pug you probably haven't heard of them hexagon kickstarter craft beer pork chic.</p>
            <div className="flex items-center flex-wrap pb-4 mb-4 border-b-2 border-gray-100 mt-auto w-full">
              <a className="text-indigo-500 inline-flex items-center">Learn More
                <svg className="w-4 h-4 ml-2" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M5 12h14"></path>
                  <path d="M12 5l7 7-7 7"></path>
                </svg>
              </a>
              <span className="text-gray-400 mr-3 inline-flex items-center ml-auto leading-none text-sm pr-3 py-1 border-r-2 border-gray-200">
                <svg className="w-4 h-4 mr-1" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24">
                  <path d="M1 12s4-8 11-8 11 8 11 8-4 8-11 8-11-8-11-8z"></path>
                  <circle cx="12" cy="12" r="3"></circle>
                </svg>1.2K
              </span>
              <span className="text-gray-400 inline-flex items-center leading-none text-sm">
                <svg className="w-4 h-4 mr-1" stroke="currentColor" stroke-width="2" fill="none" stroke-linecap="round" stroke-linejoin="round" viewBox="0 0 24 24">
                  <path d="M21 11.5a8.38 8.38 0 01-.9 3.8 8.5 8.5 0 01-7.6 4.7 8.38 8.38 0 01-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 01-.9-3.8 8.5 8.5 0 014.7-7.6 8.38 8.38 0 013.8-.9h.5a8.48 8.48 0 018 8v.5z"></path>
                </svg>6
              </span>
            </div>
            <a className="inline-flex items-center">
              <img alt="blog" src="https://dummyimage.com/104x104" className="w-12 h-12 rounded-full flex-shrink-0 object-cover object-center"/>
              <span className="flex-grow flex flex-col pl-4">
                <span className="title-font font-medium text-gray-900">Holden Caulfield</span>
                <span className="text-gray-400 text-xs tracking-widest mt-0.5">UI DEVELOPER</span>
              </span>
            </a>
          </div>

</div>
    </div>
  </div>
</section>

            </div>
// Calling find() on non-array objects

const arrayLike = {
  length: 3,
  0: 2,
  1: 7.3,
  2: 4,
};
console.log(
  Array.prototype.find.call(arrayLike, (x) => !Number.isInteger(x)),
); // 7.3
// 7 JavaScript Array Methods
[3, 4, 5, 6].at(1); // 4 
[3, 4, 5, 6].pop(); // [3, 4, 5]
[3, 4, 5, 6].push(7); // [3, 4, 5, 6, 7] 
[3, 4, 5, 6].fill(1); // [1, 1, 1, 1] 
[3, 4, 5, 6].join(""); // '3-4-5-6' 
[3, 4, 5, 6].shift(); // [4, 5, 6]  // removes an element from the start of the array
[3, 4, 5, 6].reverse(); // [6, 5, 4, 3] 
[3, 4, 5, 6].toReverse(); // [6, 5, 4, 3] but array retains order
[3, 4, 5, 6].unshift(1); // [1, 3, 4, 5, 6] // unshift adds element to the start of the array
[3, 4, 5, 6].includes(5); // true 
[3, 4, 5, 6].map((num) => num + 6); // [9, 10, 11, 12] 
[3, 4, 5, 6].find((num) => num > 4); // 5 
[3, 4, 5, 6].filter((num) => num > 4); // [5, 6] 
[3, 4, 5, 6].every((num) => num > 5); // false 
[3, 4, 5, 6].slice(0,2); // [3,4,5]
[3, 4, 5, 6].some((element) => element % 2 === 0) // true // // Checks whether at least one element in the array passes the test implemented by the provided function.
[3, 4, 5, 6].findIndex((num) => num > 4); // 2, 
[3, 4, 5, 6].reduce((acc, num) => acc + num, 0); // 18
Array.from([1, 2, 3], x => x + x); // [2, 4, 6]
array.indexOf('val')
[1, 2, [3], [4, 5], 6, []].flatMap(num => num); // [1, 2, 3, 4, 5, 6] flatMap() method returns a new array formed by applying a given callback function to each element of the array, and then flattening the result by one level

// Group By an array of objects

const inventory = [
  { name: "asparagus", type: "vegetables", quantity: 5 },
  { name: "bananas", type: "fruit", quantity: 0 },
  { name: "goat", type: "meat", quantity: 23 },
  { name: "cherries", type: "fruit", quantity: 5 },
  { name: "fish", type: "meat", quantity: 22 },
];

const result = Object.groupBy(inventory, ({ type }) => type);

/* Result is:
{
  vegetables: [
    { name: 'asparagus', type: 'vegetables', quantity: 5 },
  ],
  fruit: [
    { name: "bananas", type: "fruit", quantity: 0 },
    { name: "cherries", type: "fruit", quantity: 5 }
  ],
  meat: [
    { name: "goat", type: "meat", quantity: 23 },
    { name: "fish", type: "meat", quantity: 22 }
  ]
}
*/
// create groups inferred from values in one or more properties of the elements
function myCallback({ quantity }) {
  return quantity > 5 ? "ok" : "restock";
}

const result2 = Object.groupBy(inventory, myCallback);

/* Result is:
{
  restock: [
    { name: "asparagus", type: "vegetables", quantity: 5 },
    { name: "bananas", type: "fruit", quantity: 0 },
    { name: "cherries", type: "fruit", quantity: 5 }
  ],
  ok: [
    { name: "goat", type: "meat", quantity: 23 },
    { name: "fish", type: "meat", quantity: 22 }
  ]
}
*/
// get unique elements in an array
const numbers = [1, 2, 3, 4, 5, 5]

const uniqueNumbers = new Set(numbers) // {1, 2, 3, 4, 5}

const mySet1 = new Set();

mySet1.add(1); // Set(1) { 1 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add(5); // Set(2) { 1, 5 }
mySet1.add("some text"); // Set(3) { 1, 5, 'some text' }
const o = { a: 1, b: 2 };
mySet1.add(o);

mySet1.add({ a: 1, b: 2 }); // o is referencing a different object, so this is okay

mySet1.has(1); // true
mySet1.has(3); // false, since 3 has not been added to the set
mySet1.has(5); // true
mySet1.has(Math.sqrt(25)); // true
mySet1.has("Some Text".toLowerCase()); // true
mySet1.has(o); // true
uniqueNumbers.delete(1) // delete 2


// The Map object holds key-value pairs and remembers the original insertion order of the keys.
// Map is similar to Object
const map1 = new Map();
// map.get() get by key
// map.has() // check if exists
// map.set(key, value)
// map.size() the length

map1.set('a', 1);
map1.set('b', 2);
map1.set('c', 3);
map1.get('a'); //1
map1.size // 3
map1.delete('b'); //true
map1.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"})
map1.has('Jessie') // true
map.get('Hilary') // undefined
map.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"})
map.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"}
map.delete('Raymond') // false
map.delete('Jessie') // true

const map2 = new Map();

map2.set('0', 'foo');
map2.set(1, 'bar');

const iterator1 = map2.entries(); // returns a new iterator object that contains the [key, value] pairs for each element in the Map object in insertion order hence can be used in a for-of loop.

// Each next() call calls the next item after an initial one is called

// iterating over map
for (let [key, value] of mm.entries()) 
{
  //returning element with frequency 1
  if(value==1) 
    return key;
}

console.log(iterator1.next().value); // Expected output: Array ["0", "foo"]

console.log(iterator1.next().value); // Expected output: Array [1, "bar"]

// Split text and map the resulting words
text.split(' ').map(word => word && '🍕').join(' ')

// Find sum of N arrays of possibly different lengths
function sumArrays(...arrays) {
  const n = arrays.reduce((max, xs) => Math.max(max, xs.length), 0);
  const result = Array.from({ length: n });
  return result.map((_, i) => arrays.map(xs => xs[i] || 0).reduce((sum, x) => sum + x, 0));
}
// sumArrays([0, 1, 2], [1, 2, 3, 4], [1, 2])


// Access the last itme in an array
array[array.length - 1]

// Run a loop over an array in Javascript
array.forEach(function(arrayItem, index){
  console.log(arrayItem, index)
})

const isVowel = (letter) => ["a", "e", "i", "o", "u"].includes(letter); // check if a string is equal to one of multiple values


// For of (arrays)
const arr = [1, 2, 3, 4, 5];

// Long-hand
for (let i = 0; i < arr.length; i++) {
  const element = arr[i];
  // ...
}

// Short-hand
for (const element of arr) {
  // ...
}


//For in (objects)
const obj = {
  a: 1,
  b: 2,
  c: 3,
};

// Long-hand
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) {
  const key = keys[i];
  const value = obj[key];
  // ...
}

// Short-hand
for (const key in obj) {
  const value = obj[key];
  // ...
}


// Function calls. Call signature of the functions must be the same
function f1() {
  // ...
}
function f2() {
  // ...
}

// Long-hand
if (condition) {
  f1();
} else {
  f2();
}

// Short-hand
(condition ? f1 : f2)();
const user = await getUser();
const products = await getProducts();

const [user, products] = await Promise.all([getUser(), getProducts()])

Determining parts of a url using Javascript

  • document.write("The protocol used is - ", location.protocol, "

    ");

  • document.write("The hostname is - ", location.hostname, "

    ");

  • document.write("The port used is - ", location.port, "

    ");

  • document.write("The pathname is - ", location.pathname, "

    ");

  • document.write("The search query is - ", location.search, "

    ");

  • document.write("The fragment identifier is - ", location.hash, "

    ");

  • document.write("The complete URL is - ", location.href, "")

Projects

MjengoSmart brings structured processes, guidelines and management in the construction industry by creating an ecosystem that is transparent and efficient.

Typescript Pick/Omit feature

type User = {
  id: string
  name: string
  age: number
}

type NewUser = Pick<User, "name" | "age">
type NewUser = Omit<User, "id">

const newUser: NewUser = {
  name: "Shanice",
  age: 28,
}

Debounce function

  function debounce<T extends (...args: ChangeEvent<HTMLInputElement>[]) => void>(func: T, timeout = 300): (...args: Parameters<T>) => void{
    let timer: NodeJS.Timeout;
    return (...args: Parameters<T>) => {
      clearTimeout(timer);
      timer = setTimeout(() => { func(...args); }, timeout);
    };
  }

Replacing conditional rendering with Enums

const RoleViews = {
  GUEST: GuestView,
  ADMIN: AdminView,
  CONTRIBUTOR: ContributorVIew
};

const UserViews = ({role}) => {
  const CurrentViews = RoleViews[role] ?? DefaultView;
  return (
    <div>
      <CurrentView/>
    </div>
  )
}

Note Space © 2022 — Published with Nextjs

HomeTopicsLinksDefinitionsCommandsSnippetsMy works