Snippets Collections
const bottomUpFib = function(n) {
  if (n < 2) return n
  
  const cache = [0,1]
  
  for (let i=2; i<= n; i++) {
    cache[i] = cache[i-1] + cache[i-2]
    console.log(`Iteration ${i} ---> \n
                Cache ${cache}\n`)
  }
return cache[n]
}

console.log(bottomUpFib(5))

//If you go to a more complicated problem, you might need to build a 2d array or matrix and you need to find the solution. Each index in the array, corresponds to a solution to a sub-fib problem. You are creating a lookup table. This is what makes dynamic programming so cool
$(document).on('click', function(e) {
  // Elements you don't want to remove the class name with...
  if($(e.target).is('.element-name, .element-open-toggle') === false) {
    // If anything outside of those is clicked, remove the active class to hide the popup.
    $('body').removeClass('class-name');
  }
})
const validateEmail = email => {
    const regex = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    return regex.test(String(email).toLowerCase());
  }
let story = 'Last weekend, I took literally the most beautiful bike ride of my life. The route is called "The 9W to Nyack" and it actually stretches all the way from Riverside Park in Manhattan to South Nyack, New Jersey. It\'s really an adventure from beginning to end! It is a 48 mile loop and it basically took me an entire day. I stopped at Riverbank State Park to take some extremely artsy photos. It was a short stop, though, because I had a really long way left to go. After a quick photo op at the very popular Little Red Lighthouse, I began my trek across the George Washington Bridge into New Jersey.  The GW is actually very long - 4,760 feet! I was already very tired by the time I got to the other side.  An hour later, I reached Greenbrook Nature Sanctuary, an extremely beautiful park along the coast of the Hudson.  Something that was very surprising to me was that near the end of the route you actually cross back into New York! At this point, you are very close to the end.';

let overusedWords = ['really', 'very', 'basically'];

let unnecessaryWords = ['extremely', 'literally', 'actually' ];

let storyWords = story.split(' ');
//console.log('Amount of words: ' + story.length);

let betterWords = storyWords.filter(function(word) {
  return !unnecessaryWords.includes(word) //si no tuviera el '!', incluiría todas las palabras de ese arreglo.
}); 

// console.log(betterWords.join(' '));

let reallyCount = 0;
let veryCount = 0;
let basicallyCount = 0;

for (word of storyWords) {
  if (word === "really") {
    reallyCount += 1;
  } else if (word === "very") {
    veryCount += 1;
  } else if (word === "basically") {
    basicallyCount += 1;
  }
};

let sentencesCount = 0;

for (word of storyWords) {
  if (word[word.length - 1] === '.' || word[word.length - 1] === '!') {
    sentencesCount += 1;
  }
};

console.log('Word count: ' + storyWords.length);
console.log('How many sentences: ' + sentencesCount);
console.log('Really count: ', reallyCount);
console.log('Very count: ', veryCount);
console.log('Basically count: ', basicallyCount);

console.log(betterWords.join(' '));
let secretMessage = ['Learning', 'is', 'not', 'about', 'what', 'you', 'get', 'easily', 'the', 'first', 'time,', 'it', 'is', 'about', 'what', 'you', 'can', 'figure', 'out.', '-2015,', 'Chris', 'Pine,', 'Learn', 'JavaScript'];

secretMessage.pop();

// console.log(secretMessage.length);

secretMessage.push('to', 'Program.');

secretMessage[7] = 'right';

// console.log(secretMessage);

secretMessage.shift();

secretMessage.unshift('Programming');

secretMessage.splice(6, 5, 'know');

// console.log(secretMessage);

console.log(secretMessage.join(' '));
const person = {
  name: 'Sam',
  age: 300,
}

const twinPerson = {
  ...person
}
var element = document.getElementById('image_1'),
    style = window.getComputedStyle(element),
    top = style.getPropertyValue('top');
let userName = '';
/* Con nombre o sin nombre */
userName ? console.log(`Hello, ${userName}!`) : console.log('Hello!');
/* Se guarda la pregunta */
let userQuestion = 'Is this true?';
/* Se muestra la pregunta */
console.log(`Hey ${userName}! You just asked this: ${userQuestion}`);
/* Se genera un número aleatorio entre 0-8 */
randomNumber = Math.floor(Math.random() * 8);
/* Se guarda la respuesta en una variable */
let eightBall = '';
/* Se guardan distintas respuestas para el número que toque */
// takes in randomNumber, then eightBall = 'Reply'
// you can use if/else or switch;
// If the randomNumber is 0, then save an answer to the eightBall variable; if randomNumber is 1, then save the next answer, and so on.
/* Se utiliza switch */
/*
switch (randomNumber) {
  case 0:
    eightBall = 'It is certain';
    break;
  case 1:
    eightBall = 'It is decidedly so';
    break;
  case 3:
    eightBall = 'Reply hazy try again';
    break;
  case 4:
    eightBall = 'Cannot predict now';
    break;
  case 5:
    eightBall = 'My sources say no';
    break;
  case 6:
    eightBall = 'Outlook not so good';
    break;
  case 7:
    eightBall = 'Signs point to yes';
    break;
}
*/
/* Se utiliza if */
if (randomNumber === 0) {
  eightBall = 'It is certain';
} 
if (randomNumber === 1) {
  eightBall = 'It is decidedly so';
}
if (randomNumber === 2) {
  eightBall = 'Reply hazy try again';
}
if (randomNumber === 3) {
  eightBall = 'Cannot predict now';
}
if (randomNumber === 4) {
  eightBall = 'Do not count on it';
}
if (randomNumber === 5) {
  eightBall = 'My sources say no';
}
if (randomNumber === 6) {
  eightBall = 'Outlook not so good';
}
if (randomNumber === 7) {
  eightBall = 'Signs point to yes';
}
/* Se muestra */
console.log(eightBall);
 <input type="text" class="form-control" datepicker-popup="{{format}}" ng-model="dt" is-open="opened" min-date="minDate" max-date="'2022-06-22'" datepicker-options="dateOptions" ng-required="true" close-text="Close"
          />
jQuery( document ).ready(function() {
 
    // Add jQuery code here to be loaded once the DOM is ready
 
});
app.post("/properties", async (req, res, next) => {
  try {
    const { body } = req;
    const property = new PropertyModel(body);
    await property.save();
    return res.status(201).send(formatProperty(property));
  } catch (error) {
    if (error.name === "ValidationError") {
      error.status = 400;
    }
    next(error);
  }
});
/* The forecast today is 293 Kelvin */
const kelvin = 300;
/* We convert Kelvin to Celsius; */
/* Celsius is 273 degrees less than Kelvin */
const celsius = kelvin - 273;
/* We convert Celsius to Fahrenheit using a equation */
let fahrenheit = celsius * (9/5) + 32
/* .floor() method from the built-in Math object to round down the Fahrenheit temperature */
fahrenheit = Math.floor(fahrenheit);

let newtonscale = celsius * (33/100);

newtonscale = Math.floor(newtonscale);

console.log(`The temperature is ${fahrenheit} degrees Fahrenheit.`);

console.log(`The temperature Newton is ${newtonscale} degrees.`);
function randomRange(myMin, myMax) {
  // Only change code below this line
  return Math.floor(Math.random()* (myMax - myMin+1)+myMin);
  // Only change code above this line
}
import { useState } from "react";
import { useHistory } from "react-router-dom";

const Create = () => {
  const [title, setTitle] = useState("");
  const [body, setBody] = useState("");
  const [author, setAuthor] = useState("mario");
  const [isLoading, setIsLoading] = useState(false);
  const history = useHistory();

  const handleSubmit = (e) => {
    e.preventDefault();
    const blog = { title, body, author };

    fetch("http://localhost:8000/blogs", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify(blog),
    }).then(() => {
      setIsLoading(false);
      history.push("/");
    });
  };

  return (
    <div className="create">
      <h2>Add a New Blog</h2>
      <form onSubmit={handleSubmit}>
        <label>Blog title:</label>
        <input
          type="text"
          required
          value={title}
          onChange={(e) => setTitle(e.target.value)}
        />
        <label>Blog body:</label>
        <textarea
          required
          value={body}
          onChange={(e) => setBody(e.target.value)}
        ></textarea>
        <label>Blog author:</label>
        <select value={author} onChange={(e) => setAuthor(e.target.value)}>
          <option value="mario">mario</option>
          <option value="yoshi">mario</option>
        </select>
        {!isLoading && <button>Add Blog</button>}
        {isLoading && <button disabled>Adding blog...</button>}
      </form>
    </div>
  );
};

export default Create;
ar circle = {
	radius: 10,
  circumference(){
    var Circum = 2 * Math.PI * this.radius;
		return Circum.toFixed(2); // For Precision to 2 decimal point
  },
	area(){
		var Area = Math.PI * (this.radius ** 2);
  	return Area.toFixed(2); // For Precision to 2 decimal point
	}
};
const Form = () => {
  const [value, setValue] = useState("grapefruit");
  
  const handleChange = (event) => {
    setValue(event.target.value);
  }
  
   return (
  <form onSubmit={handleSubmit}>
    <label>
    Fav fruit
    	<select value={value} onChange={handleChange}>
          <option value="grapefruit">Grapefruit</option>
  		  <option value="apple">Apple</option>
  		</select>
  	</label>
  </form>
  )
 }
const App = () => {
  const [title, setTitle] = useState("default input");

  const handleSubmit = (event) => {
    event.preventDefault();

    const body = {
      title: title,
    };
    console.log(title);
  };

  return (
    <div className="container">
      <form onSubmit={handleSubmit}>
        <label htmlFor="title">Title</label>
        <input
          type="text"
          required
          id="title"
          value={title}
          onChange={(event) => {
            const value = event.target.value;
            setTitle(value);
          }}
        />
        <button>Submit</button>
      </form>
    </div>
  );
};
// THE HTML/PHP

// Categories Nav START
<? $terms = get_terms( array(
    'taxonomy' => 'category-name', // <-- update this
    'orderby' => 'ID',
  )); 
  if ( $terms && !is_wp_error( $terms ) ){ ?>
   <ul class="CHANGEME-categories-nav">
      <? foreach( $terms as $term ) { ?>
        <li id="cat-<?php echo $term->term_id; ?>">
           <a href="#" class="<?= $term->slug; ?> ajax" data-term-number="<?= $term->term_id; ?>" title="<?= $term->name;?>"><?= $term->name; ?></a>
        </li>
      <? } ?>
   </ul>
<? } ?>
// Categories Nav END
                                       
// Results Container START
<div id="CHANGEME-results-container" class="CHANGEME-filter-result">
   <? // post query
     $query = new WP_Query( array(
        'post_type' => 'post-name', // <-- update this
        'posts_per_page' => -1,
      ) ); 
   if( $query->have_posts() ): while( $query->have_posts()): $query->the_post(); ?>
    
      // POST TEMPLATE HERE
    
   <? endwhile; endif; wp_reset_query(); ?>
</div>                      
// Results Container END

// The onpage JS for the page template
<script>
(function($) {
        'use strict';
        function cat_ajax_get(catID) {
            jQuery.ajax({
                type: 'POST',
                url: raindrop_localize.ajaxurl,
                data: {"action": "filter", cat: catID },
                success: function(response) {
                    jQuery("#CHANGEME-results-container").html(response);
                    return false;
                }
            });
        }
        $( ".CHANGEME-categories-nav a.ajax" ).click(function(e) {
            e.preventDefault();
            $("a.ajax").removeClass("current");
            $(this).addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
            var catnumber = $(this).attr('data-term-number');
            cat_ajax_get(catnumber);
        });

    })(jQuery);
</script>
                                       
// Callback function for functions.php or some other functions specific php file like theme.php
// Aside from the inital add actions and a few other things, the actual query and post template should be the same as what is on the page.
                                       
add_action( 'wp_ajax_nopriv_filter', 'CHANGEME_cat_posts' );
add_action( 'wp_ajax_filter', 'CHANGEME_cat_posts' );
                                       
function CHANGEME_cat_posts () {
    $cat_id = $_POST[ 'cat' ];
    $args = array (
	  'tax_query' => array(
		    array(
		      'taxonomy' => 'category-name', // <-- update this
		      'field' => 'term_id',
		      'terms' => array( $cat_id )
		    )
		  ),
	    'post_type' => 'post-name', // <-- update this
	    'posts_per_page' => -1,
	  );
	global $post;
    $posts = get_posts( $args );
    ob_start ();
    foreach ( $posts as $post ) { 
	    setup_postdata($post); ?>

	    // POST TEMPLATE HERE

   <?php } wp_reset_postdata();
   $response = ob_get_contents();
   ob_end_clean();
   echo $response;
   die(1);
}
function cname(name){
const username = `${name}`;
return username;
}

fname = prompt(`Enter your first name ${name}`)
lname = prompt(`Enter your last name ${name}`)

console.log(`Hello ${fname} ${lname}`);

----------------------------------------------

// Say hello to the user
const sayHello = (firstName, lastName) => `Hello, ${firstName} ${lastName}!`;

// Alternative solution using a function declaration
/* function sayHello(firstName, lastName) {
  return `Hello, ${firstName} ${lastName}!`;
} */

const firstName = prompt("Enter your first name:");
const lastName = prompt("Enter your last name:");
console.log(sayHello(firstName, lastName));
const docURI = document.documentURI;
const docTitle = document.title;
const docHost = document.location.host;

void function getFileInfo() {
console.log(`1. Void function. Dokumenttitel är ${docTitle} & IP-adressen är ${docHost}`);
}();
var plan = new GlideRecord('sm_maint_plan');
plan.addQuery('active', true);
plan.query();
while(plan.next()){
    new PlannedMaintenanceUtils().addPlan(plan);
}
import "./Reservations.css";
import React, { useState, useEffect } from "react";
import { formatDate } from "../utils/formatDate";
import { Link } from "react-router-dom";

const ReservationList = () => {
  const [reservationList, setReservationList] = useState([]);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch("http://localhost:5000/reservations");

      const data = await response.json();
      setReservationList(data);
      setIsLoading(false);
    };

    fetchData();
  }, []);

  if (isLoading) {
    return <p>Loading...</p>;
  }

  return (
    <>
      <h1 className="upcoming-reservations">Upcoming reservations</h1>
      <ul className="reservation-list">
        {reservationList.map((reservation) => {
          return (
            <li key={reservation.id} className="reservation">
              <h2 className="name-grid-item">{reservation.restaurantName}</h2>
              <p className="date-grid-item">{formatDate(reservation.date)}</p>
              <Link
                to={`/reservations/${reservation.id}`}
                className="view-details"
              >
                View details &rarr;
              </Link>
            </li>
          );
        })}
      </ul>
    </>
  );
};

export default ReservationList;
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import { formatDate } from "../utils/formatDate";
import "./Reservations.css";
import BackButton from "./BackButton";

const Reservation = () => {
  const { id } = useParams();
  const [reservation, setReservation] = useState({});
  const [isNotFound, setIsNotFound] = useState(false);
  const [isNotValid, setIsNotValid] = useState(false);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(`http://localhost:5000/reservations/${id}`);

      if (response.status === 404) {
        setIsNotFound(true);
        return;
      }

      if (response.status === 400) {
        setIsNotValid(true);
        return;
      }

      const data = await response.json();
      setReservation(data);
      setIsLoading(false);
    };

    fetchData();
  }, [id]);

  if (isNotFound) {
    return (
      <>
        <p className="error">Sorry! We can't find that reservation.</p>
        <BackButton />
      </>
    );
  }

  if (isNotValid) {
    return (
      <>
        <p className="error">Sorry! The reservation ID is invalid.</p>
        <BackButton />
      </>
    );
  }

  if (isLoading) {
    return <p>Loading...</p>;
  }

  return (
    <>
      <div className="reservation">
        <h1 className="restaurant-name">{reservation.restaurantName}</h1>
        <p className="date">{formatDate(reservation.date)}</p>
        <p className="party-size">
          <strong>Party size: </strong>
          {reservation.partySize}
        </p>
      </div>
      <BackButton />
    </>
  );
};

export default Reservation;
import "./Header.css";
import { Link } from "react-router-dom";
import Logo from "../logo.png";

const Header = () => {
  return (
    <header className="header">
      <Link to="/" className="header-title">
        <img src={Logo} alt="" width="300" />
      </Link>
    </header>
  );
};

export default Header;
import { Link } from "react-router-dom";

const BackButton = () => {
  return (
    <Link to="/" className="btn">
      &larr; Back to reservations
    </Link>
  );
};

export default BackButton;
import "./App.css";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

import ProductListing from "./Pages/Product.js";
import ProductListings from "./Pages/ProductList.js";

function App() {
  return (
    <Router>
      <>
        <div className="container">
          <Switch>
            <Route path="/product/:id">
              <ProductListing />
            </Route>
            <Route path="/">
              <ProductListings />
            </Route>
          </Switch>
        </div>
      </>
    </Router>
  );
}

export default App;
import React, { useState, useEffect } from "react";
import ProductList from "../components/ProductList";

const ProductListings = () => {
  const [products, setProducts] = useState([]);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch("http://localhost:5000/products");
      const data = await response.json();
      setProducts(data);
    };
    fetchData();
  }, []);

  return (
    <>
      <h1>Comics for sale</h1>
      <ProductList products={products} />
    </>
  );
};

export default ProductListings;
import React, { useState, useEffect } from "react";
import { useParams } from "react-router-dom";
import Product from "../components/Product";
import { Link } from "react-router-dom";

const ProductListing = () => {
  const { id } = useParams();
  const [product, setProduct] = useState({});
  const [isLoading, setIsLoading] = useState(true);
  const [isNotFound, setIsNotFound] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(`http://localhost:5000/products/${id}`);

      if (response.status === 404) {
        setIsNotFound(true);
        setIsLoading(false);
        return;
      }

      const data = await response.json();
      setProduct(data);
      setIsLoading(false);
    };

    fetchData();
  }, [id]);

  if (isLoading) {
    return <p>Loading...</p>;
  }

  if (isNotFound) {
    return (
      <>
        <p className="error">Sorry! We can't find that product</p>
        <Link to="/" className="btn">
          &larr; Back to listings
        </Link>
      </>
    );
  }

  return (
    <>
      <Product
        title={product.title}
        isbn={product.isbn}
        rating={product.rating}
        img={product.img}
        price={product.price}
        description={product.description}
        id={product.id}
        headingLevel="h1"
      />
      <Link to="/" className="btn">
        &larr; Back to listings
      </Link>
    </>
  );
};

export default ProductListing;
import Product from "./Product";

const ProductList = ({ products }) => {
  return (
    <ul className="product-list">
      {products.map((product) => {
        return (
          <li key={product.id} className="property-list-item">
            <Product
              img={product.img}
              title={product.title}
              description={product.description}
              price={product.price}
              rating={product.rating}
              linkToProduct={product.id}
              headingLevel="h2"
            />
          </li>
        );
      })}
    </ul>
  );
};

export default ProductList;
const Product = ({ title, img, description, price, rating }) => {
  return (
    <li className="product-grid-item">
      <img className="product-img" src={img} alt={title} />
      <div className="product-text">
        <h3 className="product-title">{title}</h3>
        <p className="product-description">{description}</p>
        <p className="price">{price}</p>
        <p className="rating">{rating}</p>
      </div>
    </li>
  );
};

export default Product;
import { render, screen } from "@testing-library/react";
import properties from "./properties.json";
import App from "../App";

beforeAll(() => jest.spyOn(window, "fetch"));

test("displays all the properties and their information", async () => {
  window.fetch.mockResolvedValueOnce({
    ok: true,
    json: async () => properties,
  });

  render(<App />);

  expect.assertions(properties.length * 5);

  for (const property of properties) {
    const title = await screen.findByText(property.title);
    expect(title).toBeInTheDocument();
    const askingPrice = await screen.findByText(property.askingPrice);
    expect(askingPrice).toBeInTheDocument();
    const description = await screen.findByText(property.description);
    expect(description).toBeInTheDocument();
    const address = await screen.findByText(property.address);
    expect(address).toBeInTheDocument();
    const img = document.querySelector(`img[src="${property.img}"]`);
    expect(img).toBeInTheDocument();
  }
});
import React, { useEffect, useState } from "react";
import "./App.css";
import Header from "./components/Header/Header";

const App = () => {
  const [properties, setProperties] = useState([]);

  const fetchData = async () => {
    const response = await fetch("http://localhost:5000/properties");
    const data = await response.json();
    setProperties(data);
  };

  useEffect(() => {
    fetchData();
  }, []);

  return (
    <>
      <Header />
      <div className="container">
        <h1>Properties for sale</h1>
        {properties.map((property) => {
          return (
            <li key={property.id}>
              <img src={property.img} alt={property.address} />
              <div class="text">
                <h2 class="title">{property.title}</h2>
                <p class="address">{property.address}</p>
                <p class="price">{property.askingPrice}</p>
                <p class="description">{property.description}</p>
              </div>
            </li>
          );
        })}
      </div>
    </>
  );
};

export default App;
version: "3"
services:
  db:
    image: mongo
    expose:
      - "27017"
    volumes:
      - mongodb_data_container:/data/db
    ports:
      - "27017:27017"
volumes:
  mongodb_data_container:
const port = process.env.PORT || 5000;
const app = require("./app");
const mongoose = require("mongoose");

mongoose.connect("mongodb://localhost:27017/mongo");

app.listen(port, () => {
  console.log(`API server started at http://localhost:${port}`);
});
const mongoose = require("mongoose");
const { Schema } = mongoose;

const propertySchema = new Schema(
  {
    askingPrice: { type: String, required: true },
    description: { type: String, required: true },
    address: { type: String, required: true },
    title: { type: String, required: true },
    img: { type: String, required: true },
  },
  {
    toJSON: {
      transform(doc, ret) {
        ret.id = ret._id;
        delete ret._id;
        delete ret.__v;
      },
    },
  }
);

const Property = mongoose.model("Property", propertySchema);
module.exports = Property;
const mongoose = require("mongoose");

const validId = (id) => {
  return mongoose.Types.ObjectId.isValid(id);
};

module.exports = validId;
const express = require("express");
const app = express();
const PropertyModel = require("./models/PropertyModel");
const validId = require("./validId");

app.use(express.json());

app.get("/properties", async (req, res) => {
  const properties = await PropertyModel.find({});
  return res.status(200).send(properties);
});

app.get("/properties/:id", async (req, res) => {
  const propertyId = req.params.id;
  if (validId(propertyId)) {
    const property = await PropertyModel.findById(propertyId);
    if (property) {
      return res.status(200).send(property);
    } else {
      return res.status(404).send({ message: "id not found" });
    }
  }
  return res.status(400).send({ message: "id provided is invalid" });
});

app.post("/properties", async (req, res) => {
  const { body } = req;
  const property = new PropertyModel(body);
  await property.save();

  return res.status(200).send(property);
});

module.exports = app;
const request = require("supertest");
const app = require("./app");

describe("app.get", () => {
  test("get /properties should return the list of properties and 200 status", async () => {
    const response = await request(app).get("/properties");

    expect(response.statusCode).toBe(200);
    expect(response.body).toEqual(
      expect.arrayContaining([
        expect.objectContaining({
          askingPrice: expect.any(String),
          description: expect.any(String),
          address: expect.any(String),
          title: expect.any(String),
          img: expect.any(String),
          id: expect.any(String),
        }),
      ])
    );
  });

  test("get /properties/:id should return a single property and 200 status", async () => {
    const response = await request(app).get(
      "/properties/61480db44ab0cf7175467757"
    );

    expect(response.statusCode).toBe(200);
    expect(response.body).toEqual(
      expect.objectContaining({
        askingPrice: expect.any(String),
        description: expect.any(String),
        address: expect.any(String),
        title: expect.any(String),
        img: expect.any(String),
        id: expect.any(String),
      })
    );
  });

  test("get /properties/invalid-id should return a 400 status and custom message", async () => {
    const response = await request(app).get("/properties/invalid-id");

    expect(response.statusCode).toBe(400);
    expect(response.body).toEqual({ message: "id provided is invalid" });
  });

  test("get /properties/valid-but-not-found-id should return a 404 status and custom message", async () => {
    const response = await request(app).get(
      "/properties/61480db44ab0cf7175467717"
    );

    expect(response.statusCode).toBe(404);
    expect(response.body).toEqual({ message: "id not found" });
  });
});

describe("app.post", () => {
  test("post /properties should create a new property", async () => {
    const body = {
      askingPrice: "$1",
      description: "house",
      address: "1 house street",
      title: "cool house",
      img: "https://placeimg.com/642/482/arch",
    };
    const response = await request(app).post("/properties").send(body);

    expect(response.statusCode).toBe(200);
    expect(response.body).toEqual(
      expect.objectContaining({ ...body, id: expect.any(String) })
    );
  });
});
// Get a single resource
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then((response) => response.json())
  .then((json) => console.log(json));

// Get a list of all resources
fetch('https://jsonplaceholder.typicode.com/posts')
  .then((response) => response.json())
  .then((json) => console.log(json))

// Create a resource
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

// Create a resource (using a variable as the request body)
const requestBody = {
  title: 'foo',
  body: 'bar',
  userId: 1,
};
fetch('https://jsonplaceholder.typicode.com/posts', {
  method: 'POST',
  body: JSON.stringify(requestBody),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));

// Create a resource (using a variable for options)
const fetchOptions = {
  method: 'POST',
    body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
};

fetch('https://jsonplaceholder.typicode.com/posts', fetchOptions)
  .then((response) => response.json())
  .then((json) => console.log(json))
let number = 0;
while(number <2 || number >9){
  number = Number(prompt("Enter a number between 2 and 9"))
}
for(i = 1; i <= 10; i++){
    result = (number * i)
console.log(`${number} x ${i} = ${result}`);
}
const { useState } = React;

function PageComponent() {
  const [count, setCount] = useState(0);
  const increment = () => {
    setCount(count + 1)
  }

  return (
    <div className="App">
      <ChildComponent onClick={increment} count={count} />         
      <h2>count {count}</h2>
      (count should be updated from child)
    </div>
  );
}

const ChildComponent = ({ onClick, count }) => {
  return (
    <button onClick={onClick}>
       Click me {count}
    </button>
  )
};

ReactDOM.render(<PageComponent />, document.getElementById("root"));
let number = Number(prompt("Enter Number Of Turns: "))
let turns = 1;

while(turns <= number){
    console.log(`Turn number: ${turns}`)
      ++turns;
}
let hour = Number(prompt("Enter the hour: "))
let minutes = Number(prompt("Enter the minutes: "))
let seconds = Number(prompt("Enter the seconds: "))

if (
hour >= 0 &&
hour <= 23 &&
minutes >= 0 &&
minutes <= 59 &&
seconds >=0 &&
seconds <= 59
){
seconds++
if (seconds === 60){
seconds = 0;
minutes++
if (minutes === 60){
minutes = 0;
hour++
if (hour === 24){
hour = 0;
}
}
}
console.log (`In a second the time will be ${hour}: ${minutes} : ${seconds}`);
}
else {
console.log("Enter correct information");
}
const month = prompt("Enter month number :");

switch (month){
case "1": console.log("Number of days: 31")
break;
case "2": console.log("Number of days: 28")
break;
case "3": console.log("Number of days: 31")
break;
case "4": console.log("Number of days: 30")
break;
case "5": console.log("Number of days: 31")
break;
case "6": console.log("Number of days: 30")
break;
case "7": console.log("Number of days: 31")
break;
case "8": console.log("Number of days: 31")
break;
case "9": console.log("Number of days: 30")
break;
case "10": console.log("Number of days: 31")
break;
case "11": console.log("Number of days: 30")
break;
case "12": console.log("Number of days: 31")
break;
default:
console.log("Incorrect month entered, enter numbers from 1 - 12")
}
let number1 = prompt("Enter first number: ");
let number2 = prompt("Enter Second number: ");

if (number1 > number2){
console.log(`${number1} is greater than ${number2}`)
}
else if (number1 < number2)
{
console.log(`${number1} is smaller than ${number2}`)
}
else
{
console.log("Incorrect number")
}
const day = promp("What day is it today?");
if (day === Monday){ console.log(`today is ${day}, tomorrow is Tuesday`)
}else if (day === Tuesday) {console.log(`today is ${day}, tomorrow is Wednesday`)}
else if (day === wednesday) {console.log(`today is ${day}, tomorrow is Thursday`)}
else if (day === thursday) {console.log(`today is ${day}, tomorrow is Friday`)}
else if (day === Friday) {console.log(`today is ${day}, tomorrow is Saturday`)}
else if (day === Saturday) {console.log(`today is ${day}, tomorrow is Sunday`)}
else if (day === Sunday) {console.log(`today is ${day}, tomorrow is Monday`)}
else 
{console.log ("Incorect day entered, try again.")}
const robotFactory = (model, mobile) => {
  return {
    model: model,
    mobile: mobile,
    beep() {
      console.log('Beep Boop');
    }
  }
};

const tinCan = robotFactory('P-500', true);

tinCan.beep();
const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  _numOfSensors: 15,
  get numOfSensors(){
    if(typeof this._numOfSensors === 'number'){
      return this._numOfSensors;
    } else {
      return 'Sensors are currently down.'
    }
  },
  set numOfSensors(num) {
    if (typeof num === 'number' && num >= 0){
      this._numOfSensors = num;
    } else {
      console.log('Pass in a number that is greater than or equal to 0')
    }   
  } 
};

robot.numOfSensors = 100;
console.log(robot.numOfSensors);
const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  get energyLevel() {
    if (typeof this._energyLevel === 'number') {
      return `My current energy level is ${this._energyLevel}`
    } else {
      return 'System malfunction: cannot retrieve energy level'
    }
  }
};

console.log(robot.energyLevel)
let spaceship = {
    crew: {
    captain: { 
        name: 'Lily', 
        degree: 'Computer Engineering', 
        cheerTeam() { console.log('You got this!') } 
        },
    'chief officer': { 
        name: 'Dan', 
        degree: 'Aerospace Engineering', 
        agree() { console.log('I agree, captain!') } 
        },
    medic: { 
        name: 'Clementine', 
        degree: 'Physics', 
        announce() { console.log(`Jets on!`) } },
    translator: {
        name: 'Shauna', 
        degree: 'Conservation Science', 
        powerFuel() { console.log('The tank is full!') } 
        }
    }
}; 

// Write your code below

for (let crewMember in spaceship.crew) {
  console.log(`${crewMember}: ${spaceship.crew[crewMember].name}`)
};

for (let crewMember in spaceship.crew) {
  console.log(`${spaceship.crew[crewMember].name}: ${spaceship.crew[crewMember].degree}`)
};
let spaceship = {
  passengers: null,
  telescope: {
    yearBuilt: 2018,
    model: "91031-XLT",
    focalLength: 2032 
  },
  crew: {
    captain: { 
      name: 'Sandra', 
      degree: 'Computer Engineering', 
      encourageTeam() { console.log('We got this!') },
     'favorite foods': ['cookies', 'cakes', 'candy', 'spinach'] }
  },
  engine: {
    model: "Nimbus2000"
  },
  nanoelectronics: {
    computer: {
      terabytes: 100,
      monitors: "HD"
    },
    'back-up': {
      battery: "Lithium",
      terabytes: 50
    }
  }
}; 

let capFave = spaceship.crew.captain['favorite foods'][0]

spaceship.passengers = [{name: 'Space Dog'}]

let firstPassenger = spaceship.passengers[0]
const newNumbers = [1, 3, 5, 7];

const newSum = newNumbers.reduce((accumulator, currentValue) => {
  console.log('The value of accumulator: ', accumulator);
  console.log('The value of currentValue: ', currentValue);
  return accumulator + currentValue
}, 10);

// es como: .reduce(A, B) | .reduce(A:(a)=>{}, B)

console.log(newSum);
const animals = ['hippo', 'tiger', 'lion', 'seal', 'cheetah', 'monkey', 'salamander', 'elephant'];

const startsWithS = animals.findIndex(animal => {
  return animal[0] === 's' ? true : false;
});

console.log(startsWithS);
const randomNumbers = [375, 200, 3.14, 7, 13, 852];

// Call .filter() on randomNumbers below
const smallNumbers = randomNumbers.filter(numbers => {
  return numbers < 250;
});

console.log(smallNumbers);

const favoriteWords = ['nostalgia', 'hyperbole', 'fervent', 'esoteric', 'serene'];


// Call .filter() on favoriteWords below
const longFavoriteWords = favoriteWords.filter(words => {
  return words.length > 7;
});

console.log(longFavoriteWords);
// Primera forma

const groceries = ['brown sugar', 'salt', 'cranberries', 'walnuts'];

groceries.forEach(function(groceryItem){
  console.log(' - ' + groceryItem);
});

// Segunda forma

groceries.forEach(groceryItem => console.log(groceryItem));

// Tercera forma

function printGrocery(element){
  console.log(element);
}
 
groceries.forEach(printGrocery);
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};

const addTwo = num => num + 2;

const timeFuncRuntime = funcParameter => {
  let t1 = Date.now();
  funcParameter();
  let t2 = Date.now();
  return t2 - t1;
};

// Write your code below

const time2p2 = timeFuncRuntime(checkThatTwoPlusTwoEqualsFourAMillionTimes);

const checkConsistentOutput = (func, val) => {
    let firstTry = func(val);
    let secondTry = func(val);
    if (firstTry === secondTry) {
        return firstTry
    } else {
        return 'This function returned inconsistent results'
    }
};

console.log(checkConsistentOutput(addTwo, 10));
const checkThatTwoPlusTwoEqualsFourAMillionTimes = () => {
  for(let i = 1; i <= 1000000; i++) {
    if ( (2 + 2) != 4) {
      console.log('Something has gone very wrong :( ');
    }
  }
};

const addTwo = num => num + 2;

const timeFuncRuntime = funcParameter => {
  let t1 = Date.now();
  funcParameter();
  let t2 = Date.now();
  return t2 - t1;
};

// Write your code below

const VARIABLE = N1(N2);




var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];    
function Validate(oForm) {
    var arrInputs = oForm.getElementsByTagName("input");
    for (var i = 0; i < arrInputs.length; i++) {
        var oInput = arrInputs[i];
        if (oInput.type == "file") {
            var sFileName = oInput.value;
            if (sFileName.length > 0) {
                var blnValid = false;
                for (var j = 0; j < _validFileExtensions.length; j++) {
                    var sCurExtension = _validFileExtensions[j];
                    if (sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
                        blnValid = true;
                        break;
                    }
                }
                
                if (!blnValid) {
                    alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
                    return false;
                }
            }
        }
    }
  
    return true;
}
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };
var today  = new Date();

console.log(today.toLocaleDateString("en-US")); // 9/17/2016
console.log(today.toLocaleDateString("en-US", options)); // Saturday, September 17, 2016
console.log(today.toLocaleDateString("hi-IN", options)); // शनिवार, 17 सितंबर 2016
document.querySelectorAll("a").forEach(item => {
    item.addEventListener("click", e => {
        e.preventDefault();
        if(history.pushState) {
            history.pushState(null, null, e.target.href);
        }
        return false;
    });
});
var powerHouse = new GlideRecord('sys_choice');
//Daily check
powerHouse.addEncodedQuery('name=core_company^element=u_powerhouse^language=en^sys_created_onONToday@javascript:gs.beginningOfToday()@javascript:gs.endOfToday()');
powerHouse.query();
while(powerHouse.next()){
    var mra = new GlideRecord('u_mra');
	var gr = new GlideRecord('u_mra_config');
	gr.addQuery('install_status','!=', '7');
	gr.query();
	while(gr.next()){
		mra.initialize();
		mra.u_software = gr.sys_id;
		mra.u_powerhouse = powerHouse.value;
		mra.u_active = false;
		mra.insert();
	}

}
<script src="https://cdn.jsdelivr.net/npm/js-cookie@3.0.1/dist/js.cookie.min.js"></script>
<script>
  // Add dark mode classes and elements' classes
  // newDarkClass - a name of a class with dark mode attributes 
  // defaultClass - a class of an element a new class will be added to
  var darkClasses = [

    { newDarkClass: 'bodyDark', defaultClass: 'body' },
    { newDarkClass: 'h2_dark', defaultClass: 'h2' },

  ];
	
  // Listening to a switch and running a function on click
  document.getElementById("switch").addEventListener("click", darkSwitch);

  // checking if cookie exists
  var cookieState = Cookies.get('darkMode');

  // First visit - cookieState is undefined
  // If cookie exists we are parsing it to get a boolean
  if (cookieState === undefined) {
    var isDarkmodeEnabled = false;
  } else {
    var isDarkmodeEnabled = JSON.parse(cookieState)
  };

  // Cookie doesn't exist: darkMode = false 
  // Cookie exists: darkMode = true/false
  var darkMode = isDarkmodeEnabled;

  // Adding classes on page load if darkmode is enabled
  window.onload = addClassesOnLoad();

  // Changing darkMode state and adding or removing classes
  function darkSwitch() {

    // Setting darkMode to its opposite value
    darkMode = !darkMode;

    if (darkMode === true) {
      // Looping through an array and deleting classes
      darkClasses.forEach(item => {
        var element = document.querySelectorAll(`.${item.defaultClass}`)
        element.forEach(h => h.classList.add(item.newDarkClass))
      });
    } else {
      // Looping through an array and deleting classes
      darkClasses.forEach(item => {
        var element = document.querySelectorAll(`.${item.defaultClass}`)
        element.forEach(h => h.classList.remove(item.newDarkClass))
      });
    };
    // Saving darkMode state to the cookie
    Cookies.set('darkMode', darkMode);
  }

  // Adding classes on page load if darkmode is enabled
  //
  function addClassesOnLoad() {

    if (darkMode === true) {

      // Changing switch state
      document.getElementById("switch").checked = true;


      darkClasses.forEach(item => {
        var element = document.querySelectorAll(`.${item.defaultClass}`)
        element.forEach(h => h.classList.add(item.newDarkClass))
      });
    };
  }

</script>

<style>

  /* DEFINE DARK MODE CLASSES HERE */

</style>
const Slider = () => {

const { data, loading, error } = useQuery(GET_LATEST_POSTS)


const [ currentMovie, setMovie ] = useState()

 useEffect(() => {
    if(!loading && data){
        setMovie(data);
    }
  }, [loading, data])

if (loading) return 'Loading...'               //your component's return should always be after all hook calls//
if (error) return `Error! ${error.message}`
}
export default {
  name: 'gallery',
  type: 'object',
  title: 'Gallery',
  fields: [
    {
      name: 'images',
      type: 'array',
      title: 'Images',
      of: [
        {
          name: 'image',
          type: 'image',
          title: 'Image',
          options: {
            hotspot: true,
          },
          fields: [
            {
              name: 'alt',
              type: 'string',
              title: 'Alternative text',
            },
          ],
        },
      ],
      options: {
        layout: 'grid',
      },
    },
    {
      name: 'display',
      type: 'string',
      title: 'Display as',
      description: 'How should we display these images?',
      options: {
        list: [
          { title: 'Stacked on top of eachother', value: 'stacked' },
          { title: 'In-line', value: 'inline' },
          { title: 'Carousel', value: 'carousel' },
        ],
        layout: 'radio', // <-- defaults to 'dropdown'
      },
    },
    {
      name: 'zoom',
      type: 'boolean',
      title: 'Zoom enabled',
      description: 'Should we enable zooming of images?',
    },
  ],
  preview: {
    select: {
      images: 'images',
      image: 'images.0',
    },
    prepare(selection) {
      const { images, image } = selection;

      return {
        title: `Gallery block of ${Object.keys(images).length} images`,
        subtitle: `Alt text: ${image.alt}`,
        media: image,
      };
    },
  },
};
		var mail = new EmailUtils().getLastReceivedEmail(current.sys_id);
		template.print("<blockquote>");
		// Remove html, head, body and style tags
		template.print(sn_notification.EmailResponse.getOriginalEmailHtml(mail));
		template.print("</blockquote></div>");
getLastReceivedEmail: function(target) {
		var mail = new GlideRecord('sys_email');
		mail.addQuery('instance',target);
		mail.addQuery('type', 'received');
		mail.orderByDesc('sys_created_on');
		mail.setLimit('1');
		mail.query();
		if(mail.next()){
			return mail.sys_id;
		}
		else
			return;
	},
const concept = ['arrays', 'can', 'be', 'mutated'];

function changeArr(arr){
  arr[3] = 'MUTATED';
}

changeArr(concept);

console.log(concept);

const removeElement = newArr => {
  newArr.pop()
};

removeElement(concept);

console.log(concept);
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

const pastaIndex = groceryList.indexOf('pasta');

console.log(pastaIndex);
const groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

groceryList.shift();
console.log(groceryList);

groceryList.unshift('popcorn');
console.log(groceryList);

console.log(groceryList.slice(1,4));

console.log(groceryList);
// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

});
function monitorCount(rows, columns) {
  return rows * columns
}

const numOfMonitors = monitorCount(5, 4)

console.log(numOfMonitors);
// Replace this with a relevant selector.
// If you use a tool that auto-generates classes,
// you can temporarily add an ID and select it
// with '#id'.
const selector = '.the-fixed-child';
function findCulprits(elem) {
  if (!elem) {
    throw new Error(
      'Could not find element with that selector'
    );
  }
  let parent = elem.parentElement;
  while (parent) {
    const {
      transform,
      willChange
    } = getComputedStyle(parent);
    if (transform !== 'none' || willChange === 'transform') {
      console.warn(
        '🚨 Found a culprit! 🚨\n',
        parent,
        { transform, willChange }
      );
    }
    parent = parent.parentElement;
  }
}
findCulprits(document.querySelector(selector));
function mergeLists(headone, headtwo) {
  if (headone === null || headtwo === null) {
    return headone === null ? headtwo : headone
  }

  let p1 = headone.val <= headtwo.val ? headone : headtwo
  let p2 = p1 === headone ? headtwo : headone
  const head = p1

  head.next = mergeLists(p1.next, p2)

  return head
}
// Arrow function
filter((element) => { ... } )
filter((element, index) => { ... } )
filter((element, index, array) => { ... } )

// Callback function
filter(callbackFn)
filter(callbackFn, thisArg)

// Inline callback function
filter(function callbackFn(element) { ... })
filter(function callbackFn(element, index) { ... })
filter(function callbackFn(element, index, array){ ... })
filter(function callbackFn(element, index, array) { ... }, thisArg)
  handleFilter = key => {
    const selected = parseInt(key);
    if (selected === 3) {
      return this.setState({
        eventsData
      });
    }

    const statusMap = {
      1: "complete",
      2: "inProgress"
    };

    const selectedStatus = statusMap[selected];

    const filteredEvents = eventsData.filter(
      ({ status }) => status === selectedStatus
    );
    this.setState({
      eventsData: filteredEvents
    });
  };
  handleSearch = searchText => {
    const filteredEvents = eventsData.filter(({ title }) => {
      title = title.toLowerCase();
      return title.includes(searchText);
    });

    this.setState({
      eventsData: filteredEvents
    });
  };
function NaturalSort (a, b) {
        var ax = [], bx = [];

        a.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
        b.replace(/(\d+)|(\D+)/g, function (_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });

        while (ax.length && bx.length) {
            var an = ax.shift();
            var bn = bx.shift();
            var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
            if (nn) return nn;
        }

        return ax.length - bx.length;
    }
<!DOCTYPE html>
<html>
<head>
	<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
</head>
<body ng-app="_APPNAME_" ng-controller="_CONTROLLERNAME_">

	<h2>_APPNAME_</h2>

	
	<input type="text" ng-model="value" />
	

	<p>
		<button ng-click="save()">Save</button>
		<button ng-click="clear()">Clear</button>
	</p>

	<p>Saved Value: <span ng-bind="savedValueFunction()"></span></p>



	<script>
	var app = angular.module("_APPNAME_", []); 
	app.controller("_CONTROLLERNAME_", function($scope) {
		
		$scope.value = "";
		$scope.savedValue = "";
		
		$scope.savedValueFunction = function() {
			return $scope.savedValue;
		};
		$scope.clear = function() {
			$scope.value = "";
      $scope.savedValue="";
		};
		$scope.save = function() {
			alert("Saved");
      $scope.savedValue=$scope.value;
		};
	});
	</script>



</body>
</html>
let users = [
  {
    firstName: "Bradley",
    lastName: "Cooper",
  },
  {
    firstName: "Lady",
    lastName: "Gaga",
  },
];

users.forEach(function (user, index) {
  for (let prop in user) {
    alert(prop + " is " + user[prop]);
  }
});
function fullName(firstName, lastName) {
  alert(firstName + " " + lastName);
}

let firstName = prompt("What's your first name?");
let lastName = prompt("What's your last name?");
fullName(firstName, lastName);
fullName("Kate", "Robinson");
function sayFact() {
  let name = prompt("What's your name?");

  if (name === "Sofia") {
    alert("Your name comes from the Greek -> Sophia");
  }
}

sayFact();
let times = 0;
do {
  console.log(times);
  times = times + 1;
} while(times < 10)
let fruits = ['apples', 'oranges', 'bananas'];
fruits.forEach(function(fruit) {
  alert("I have " + fruit + " in my shopping bag");
});
let times = 0;
while (times < 10) {
  console.log(times);
  times = times + 1;
}
let myList = [];
let fruits = ["apples", "oranges", "bananas"];
myList = ['banana', 3, go, ['John', 'Doe'], {'firstName': 'John', 'lastName': 'Smith'}]
if (continent === "Europe" && language === "Portuguese") {
  alert("You are from Portugal 🇵🇹");
} else {
  alert("You are not from Portugal");
}
if (age < 18 || gender === "male") {
  alert("You can't join SheCodes 👩‍💻");
}
let city = " Montreal  "
city.trim() // "Montreal"
// The trim() method removes whitespace from both ends of a string.
let country = prompt("What country are you from?");

if (country === "Portugal") {
  alert("You are cool");
}

if (country !== "Portugal") {
  alert("Too bad for you");
}
let firstName = prompt("What is your first name");

let lastName = prompt("What is your last name");

let fullName = firstName + " " + lastName;

document.write(fullName);
using System;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Web;

namespace Common
{
    public static class CacheHelper
    {
        public static void AddOrUpdate(string key, object value, int expiresinhours)
        {
            if (HttpContext.Current != null)
            {
                if (HttpContext.Current.Cache[key] != null)
                {
                    HttpContext.Current.Cache[key] = value;
                }
                else
                {
                    HttpContext.Current.Cache.Add(key, value, null, DateTime.Now.AddHours(expiresinhours), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null);
                }
            }
            else if (MemoryCache.Default != null)
            {
                if (MemoryCache.Default[key] != null)
                {
                    MemoryCache.Default[key] = value;
                }
                else
                {
                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = DateTime.Now.AddHours(expiresinhours);
                    MemoryCache.Default.Set(key, value, policy);
                }
            }
        }

        public static object Get(string key)
        {
            ObjectCache cache = MemoryCache.Default;
    
            if (HttpContext.Current!= null && HttpContext.Current.Cache[key] != null)
            {
                return HttpContext.Current.Cache[key];
            }
            else if (MemoryCache.Default != null && MemoryCache.Default[key] != null)
            {
                return MemoryCache.Default[key];
            }

            return null;
        }

        public static void DeleteCacheThatContains(string value)
        {
            if (HttpContext.Current != null)
            {
                List<string> keys = new List<string>();

                // retrieve application Cache enumerator
                IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();

                // copy all keys that currently exist in Cache
                while (enumerator.MoveNext())
                {
                    if (enumerator.Key.ToString().Contains(value))
                        keys.Add(enumerator.Key.ToString());
                }

                // delete every key from cache
                for (int i = 0; i < keys.Count; i++)
                {
                    HttpContext.Current.Cache.Remove(keys[i]);
                }
            }
        }


        public static void ClearAllCache()
        {
            if (HttpContext.Current != null)
            {
                List<string> keys = new List<string>();

                // retrieve application Cache enumerator
                IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator();

                // copy all keys that currently exist in Cache
                while (enumerator.MoveNext())
                {
                    keys.Add(enumerator.Key.ToString());
                }

                // delete every key from cache
                for (int i = 0; i < keys.Count; i++)
                {
                    HttpContext.Current.Cache.Remove(keys[i]);
                }
            }
        }
    }
}
Syntax
array.map(function(currentValue, index, arr), thisValue)
Parameter Values
Parameter	Description
function(currentValue, index, arr)	Required. A function to be run for each element in the array.
Function arguments:
Argument	Description
currentValue	Required. The value of the current element
index	Optional. The array index of the current element
arr	Optional. The array object the current element belongs to
thisValue	Optional. A value to be passed to the function to be used as its "this" value.
If this parameter is empty, the value "undefined" will be passed as its "this" value

examples

service.currencyList.map(each({value:each.currencySymbol,displayValue:each.currencySymbol}))

######################################################################

const persons = [
  {firstname : "Malcom", lastname: "Reynolds"},
  {firstname : "Kaylee", lastname: "Frye"},
  {firstname : "Jayne", lastname: "Cobb"}
];

persons.map(getFullName);

function getFullName(item) {
  return [item.firstname,item.lastname].join(" ");
}
distinct: function (list, identifierFunc) {

                let result = [];

                const map = new Map();

                list.forEach(item => {
                    let id = identifierFunc(item).toUpperCase();
                    if (!map.has(id)) {
                        map.set(id, true);

                        result.push(item);
                    }
                });

                return result;
            }
JSONToCSVConvertor: function (JSONData, FileName, ShowLabel) {
                //If JSONData is not an object then JSON.parse will parse the JSON string in an Object
                var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;

                var CSV = '';
                //Set Report title in first row or line

                //CSV += ReportTitle + '\r\n\n';

                //This condition will generate the Label/Header
                if (ShowLabel) {
                    var row = "";

                    //This loop will extract the label from 1st index of on array
                    for (var index in arrData[0]) {

                        //Now convert each value to string and comma-seprated
                        row += index + ',';
                    }

                    row = row.slice(0, -1);

                    //append Label row with line break
                    CSV += row + '\r\n';
                }

                //1st loop is to extract each row
                for (var i = 0; i < arrData.length; i++) {
                    var row = "";

                    //2nd loop will extract each column and convert it in string comma-seprated
                    for (var index in arrData[i]) {
                        row += '"' + arrData[i][index] + '",';
                    }

                    row.slice(0, row.length - 1);

                    //add a line break after each row
                    CSV += row + '\r\n';
                }

                if (CSV == '') {
                    alert("Invalid data");
                    return;
                }

                //Generate a file name
                var fileName = FileName;
                //this will remove the blank-spaces from the title and replace it with an underscore
                //fileName += ReportTitle.replace(/ /g, "_");

                //Initialize file format you want csv or xls
                var uri = 'data:text/csv;charset=utf-8,' + escape(CSV);

                // Now the little tricky part.
                // you can use either>> window.open(uri);
                // but this will not work in some browsers
                // or you will not get the correct file extension    

                //this trick will generate a temp <a /> tag
                var link = document.createElement("a");
                link.href = uri;

                //set the visibility hidden so it will not effect on your web-layout
                link.style = "visibility:hidden";
                link.download = fileName + ".csv";

                //this part will append the anchor tag and remove it after automatic click
                document.body.appendChild(link);
                link.click();
                document.body.removeChild(link);
            }
buildComboDataSource: function (endpoint, sortField, pageSize) {
                return {
                    type: "odata-v4",
                    transport: {
                        read: {
                            url: this.odata.url() + endpoint,
                            dataType: "json",
                            xhrFields: {
                                withCredentials: true //needed for windows auth
                            }
                        }
                    },
                    schema: {
                        total: function (data) {
                            return data["@odata.count"];
                        }
                    },
                    pageSize: pageSize,
                    serverPaging: pageSize > 0 ? true : false,
                    serverFiltering: true,
                    serverSorting: true,
                    sort: {
                        field: sortField,
                        dir: "asc"
                    }
                };
            }
function PushIfUnique (arr, element) {
    if (!arr.includes(element)) {
        arr.push(element);
    }
};
function arraysAreEqual(a, b) {
    return Array.isArray(a) &&
        Array.isArray(b) &&
        a.length === b.length &&
        a.every((val, index) => val === b[index]);
}
String.prototype.replaceAll = function (find, replace) {
    var str = this;
    return str.replace(new RegExp(find.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'), 'g'), replace);
};
function grid_product_filter(element) {
    build_gridfilter(element, '/Products/GridFilterRead');
}


function build_gridfilter(element, url) {
   
    var combobox = element.kendoComboBox({

    placeholder: "Select",
    autoBind: true,
    filter: "contains",

        dataTextField: "Name",
        dataValueField: "Name",

        dataSource: {
            type: "aspnetmvc-ajax",
            sort: { field: "Name", dir: "asc" },
            transport: {
                read: {
                    url: url,
                }
            },
            schema: {
                data: "Data",
                total: "Total"
            },
            pageSize: 200,
            serverPaging: true,
            serverFiltering: true,
            serverSorting: true
        }
    });
    setdropdownwidth(combobox);
}
var standardfilterwidth = 300;
function setdropdownwidth(combobox) {
    if (combobox.data("kendoComboBox"))
        combobox.data("kendoComboBox").list.width(standardfilterwidth);
    else if (combobox.data("kendoExtendedComboBox"))
        combobox.data("kendoExtendedComboBox").list.width(standardfilterwidth);
}



function GridAddItemHandler(gridid) {
    var grid;

    if (gridid == undefined)
        grid = $("#grid").data("kendoGrid");
    else
        grid = $("#" + gridid).data("kendoGrid");
   
    if (grid) {

            grid.addRow();
        
    }
}
$(document).ready(function () {

    GridRowDoubleClickHandler();
  
}
                  
function GridRowDoubleClickHandler(gridid) {
    
        var grid;

        if (gridid == undefined)
            grid = $("#grid");
        else
            grid = $("#" + gridid);

        if (grid) {

            grid.delegate("tbody > tr", "dblclick", function () {
                var kendogrid = grid.data("kendoGrid");
                if (kendogrid.options.editable.mode == "popup") {
                    var row = $(this);
                    editrowdataitem = kendogrid.dataItem(row);
                    if (compliant) {
                        kendogrid.editRow(row);
                    }
                }
            });

            grid.delegate(".k-grid-edit", "click", function () {
                var kendogrid = grid.data("kendoGrid");
                if (kendogrid.options.editable.mode == "popup") {
                    var row = $(this).closest("tr");
                    editrowdataitem = kendogrid.dataItem(row);
                }
            });
        }

}
<div class="environment @Server.Environment.ToString().ToLower()">
  @Server.Environment.ToString().ToUpper() ENVIRONMENT
</div>
<style>
	.environment {
		display: block;
		position: absolute;
		width: 100%;
		padding: 5px 0;
		font-weight: bold;
		text-align: center;
		color: #fff;
	}

	.environment.local {
		background-color: #56ca85;
	}

	.environment.development {
		background-color: #000dbe;
	}

	.environment.test {
		background-color: #be5500;
	}

	.environment.production {
		display: none;
	}
</style>

<script type="text/javascript">
  $(document).ready(function () {
    if ($(".development").length || $(".test").length || $(".local").length) {
      setTimeout("HideEnvironment('.environment')", 2000);   
      $(".title").mouseenter(function () {
        ShowEnvironment();
      })
        .mouseleave(function(){
        HideEnvironment(".environment");
      });
    }
  });

  function ShowEnvironment() {
      $(".environment").stop().animate({
          height: '22px',
          padding: '5px 0px',
          'text-indent': '-0px'
      }, 400);
  }

  function HideEnvironment(selector) {
      $(selector).stop().animate({
          height: '2px',
          padding: '0px 0px',
         'text-indent': '-9999px'
      }, 400);
  }
</script>
$(document).ready(function(){
  
});
function isEmpty(obj) {
    return Object.keys(obj).length === 0;
}
function ToShortDescription(str, numberOfWords) {
  var words = str.split(' ');
  words.splice(numberOfWords, words.length-1);
  return words.join(' ') + 
    (words.length !== str.split(' ').length ? '&helip;' : '');
}
function isNullOrEmpty(value){
    return (!value || value.length == 0);
}
sudo nano /etc/nginx/sites-available/default

location / {
    proxy_pass http://localhost:8080;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
    proxy_cache_bypass $http_upgrade;
}

sudo nginx -t 
sudo service nginx restart
// SOLUTION 1 - MY (DISCOVERED) SOLUTION (RUNTIME - 104MS, 44.9 MB)
var isAnagram = function(s, t) {
    
    // set function to split, sort, and rejoin characters in a string
    const sortString = (str) => {
        return str.split("").sort().join("");
    }
    
    // regex removes any non-alphabet characters in the string and makes it lowercase
    s = s.replace(/[^\w]/g, '').toLowerCase()
    t = t.replace(/[^\w]/g, '').toLowerCase()

    // final comparison
    return sortString(s) === sortString(t)
  
  // ATTEMPT 1
  //     let anagram = []
    
  // return false is lengths don't match
  //     if (s.length !== t.length) return false;
  //     else {
  //         for (let i = 0; i < s.length; i++) {
  //             let arrT = t.split("")
  //             let newArrT;
  //             if (arrT.includes(s.charAt(i))) {
  //                 let index = arrT.indexOf(s.charAt(i));
  //                 console.log("s char: ", s.charAt(i));
  //                 console.log("index: ", index);

  //                 anagram.push(s.charAt(i))

  //                 console.log("splice: ", arrT.splice(index, 1))
  //                 arrT.splice(index, 0)

  //                 newArrT = arrT
  //                 console.log("newArr: ", newArrT)
  //             };
  //         };
  //     }
  //     console.log(anagram)
  //     return anagram.join("") === s;
}

// SOLTUION 2 - (BEST RUNTIME - 60MS)
var isAnagram = function(s, t) {
    const key = w => Object.entries([...w].reduce((a, c) => {
        if (!(c in a)) a[c] = 0;
        a[c] += 1;
      
        return a;
    }, {})).sort(([c1], [c2]) => c1.localeCompare(c2)).flat().join('');
  
    return key(s) === key(t);
};

// SOLUTION 3 - (RUNTIME - 72MS)
var isAnagram = function(s, t) {
    if(s.length !== t.length) return false;
  
    let map = {};
  
    for(let item of s) {
        map[item] = map[item] + 1 || 1;
    }
    
    for(let item of t) {
        if(!map[item]) return false;
        else map[item]--;
    }
  
    return true;
};
/**
 * AdWords Performance Monitoring in Slack via Labels
 * @author: Dustin Recko
 *
 */

// Config Section //>

var DB_URL = 'https://...'; // The Firebase Database URL
var DB_AUTH = 'xxx'; // The Firebase Database Secret

var SLACK_HOOK = 'https://...'; // The Slack Hook URL
var SLACK_CHANNEL = '#adwords'; // The Slack Channel
var SLACK_EMOJI = ':smile:'; // The Slack Emoji

var TRIGGER = {
  clicks: 30, //Stats as a trigger with a specified threshold
  weeks: [1,4] //Time as a trigger with a start and end threshold
};

var LABEL_NAME = "CONTROL"; // The name of the label used in AdWords to activate monitoring for Keywords, AdGroups, and Ads

var NOW = new Date();

// End of Config <//

function main() {

  init();

  var ACC = AdWordsApp.currentAccount().getName().split(" ")[0];

  var myDb = new firebase(DB_URL,DB_AUTH);
  var myDbJson = myDb.getJson(LABEL_NAME+'/'+ACC) || nest({},[LABEL_NAME,ACC]);

  var mySlack = new slack(SLACK_HOOK,SLACK_CHANNEL,SLACK_EMOJI);

  var myLabel = AdWordsApp.labels().withCondition("Name = '"+LABEL_NAME+"'").get().next();

  var process = {
    "keywords": myLabel.keywords().get(),
    "adGroups": myLabel.adGroups().get(),
    "ads": myLabel.ads().get()
  };

  /// Main process

  for(var handler in process) {

    /// Check items with the label

    while(process[handler].hasNext()) {

      var h = process[handler].next();

      if(!myDbJson[handler] || !myDbJson[handler][h.getId()]) {

        var obj = {
          "name"    : (h.getText instanceof Function) ? h.getText() : ((h.getDescription1 instanceof Function) ? h.getDescription1() : h.getName()),
          "campaign": h.getCampaign().getName(),
          "qsStart"  : (h.getQualityScore instanceof Function) ? h.getQualityScore() : 0,
          "started" : NOW.getTime(),
          "trigger": initTrigger(TRIGGER)
        };
        myDb.patch(obj,LABEL_NAME+'/'+ACC+'/'+handler+'/'+h.getId());
        myDbJson = nest(myDbJson,[handler,h.getId()]);

      } else {

        for(var i in TRIGGER) {
          switch(typeof(myDbJson[handler][h.getId()].trigger[i])) {
            case "boolean":        
              if(!myDbJson[handler][h.getId()].trigger[i]) {
                if(statsBasedCheck(handler,h,i,myDbJson[handler][h.getId()])) {
                  var status = {};
                  status[i] = true;
                  myDb.patch(status,LABEL_NAME+'/'+ACC+'/'+handler+'/'+h.getId()+'/trigger');
                }
              }
              break;
            case "number":
              var weeksPassed = Math.round((NOW.getTime() - myDbJson[handler][h.getId()].started)/(1000*60*60*24)) / 7;
              if(weeksPassed%1 === 0 && TRIGGER[i][0] <= weeksPassed && weeksPassed <= TRIGGER[i][1] && weeksPassed > myDbJson[handler][h.getId()].trigger[i]) {
                timeBasedCheck(handler,h,i,myDbJson[handler][h.getId()]);
                var status = {};
                status[i] = weeksPassed;
                myDb.patch(status,LABEL_NAME+'/'+ACC+'/'+handler+'/'+h.getId()+'/trigger');
              }
              break;
          }
        }
      }
      /// Flag processed items
      myDbJson[handler][h.getId()].flag = true;
    }
      /// Cleanup no longer labelled items, i.e., non-flagged
      for(var i in myDbJson[handler]) {
      if(myDbJson[handler][i].flag == undefined)
        myDb.purge(LABEL_NAME+'/'+ACC+'/'+handler+'/'+i);
    }
  }


  /// Some functions

  function init() {
    Date.prototype.yyyymmdd = function(days) {
      if(days) {
        this.setDate(this.getDate() + days);
      }
      return Utilities.formatDate(this, AdWordsApp.currentAccount().getTimeZone(),'yyyyMMdd');
    }
  }

  function firebase(db,auth) {
    this.db = db;
    this.auth = auth;

    this.patch = function(payload,path) {
      path = path+'/.json?auth=';
      var options = {
        "method"  : "patch",
        "payload" : JSON.stringify( payload )
      };
      UrlFetchApp.fetch(this.db+path+this.auth,options);
    }

    this.purge = function(path) {
      path = path+'/.json?auth=';
      var options = {
        "method": "delete"
      };
      UrlFetchApp.fetch(this.db+path+this.auth,options);
    }

    this.getJson = function(path) {
      path = path+'/.json?auth=';
      return JSON.parse(
        UrlFetchApp
        .fetch(this.db+path+this.auth)
        .getContentText()
      );
    }
  }

  function slack(hook,channel,emoji) {

    this.hook = hook;
    this.channel = channel;
    this.emoji = emoji;

    this.msg = function(payload) {
      payload.channel = this.channel;
      payload.icon_emoji = this.emoji;
      var options = {
        method: "POST",
        contentType: 'application/json',
        payload: JSON.stringify(payload)
      };
      UrlFetchApp.fetch(this.hook,options);
    }
  }

  function initTrigger() {
    var obj = {};
    for(var i in TRIGGER) {
      if(typeof(TRIGGER[i]) == "number")
        obj[i] = false
      else
        obj[i] = 0
    }
    return obj;
  }

  function statsBasedCheck(type,handler,trigger,dbData) {

    var sh = handler.getStatsFor(new Date(dbData.started).yyyymmdd(),NOW.yyyymmdd());

    var stats = {
      avgCpc: sh.getAverageCpc().toFixed(2),
      avgPos: sh.getAveragePosition(),
      clicks: sh.getClicks(),
      conversions: sh.getConversions(),
      cost: sh.getCost(),
      qs: (type == 'keywords') ? handler.getQualityScore() : 0
    };

    if(stats[trigger] >= TRIGGER[trigger])  {

      var daysPassed = Math.round((NOW.getTime() - dbData.started)/(1000*60*60*24));

      var sh = handler.getStatsFor(new Date(dbData.started).yyyymmdd(daysPassed*-1),new Date(dbData.started).yyyymmdd());

      var beforeStats = {
        avgCpc: sh.getAverageCpc().toFixed(2),
        avgPos: sh.getAveragePosition(),
        clicks: sh.getClicks(),
        conversions: sh.getConversions(),
        cost: sh.getCost(),
        qs: dbData.qsStart
      };

      var attachments = [];
      for(var s in stats) {
        attachments.push({
          title: s,
          text: 'is '+stats[s]+ (stats[s]>=beforeStats[s] ? ' (up' : '(down') +' from '+beforeStats[s]+')'
        });
      }

      mySlack.msg({
        text: LABEL_NAME+" > "+ACC+" > "+type+" > "+dbData.name+" in "+dbData.campaign+" passed "+stats[trigger]+" "+trigger+" in "+daysPassed+" days (was "+beforeStats[trigger]+" in the previous period)",
        attachments: attachments
      });

      return true;
    }

    return false;
  }

  function timeBasedCheck(type,handler,trigger,dbData) {

    var sh = handler.getStatsFor(new Date(dbData.started).yyyymmdd(),NOW.yyyymmdd());

    var stats = {
      avgCpc: sh.getAverageCpc().toFixed(2),
      avgPos: sh.getAveragePosition(),
      clicks: sh.getClicks(),
      conversions: sh.getConversions(),
      cost: sh.getCost(),
      qs: (type == 'keywords') ? handler.getQualityScore() : 0
    };

    var sh = handler.getStatsFor(new Date(dbData.started).yyyymmdd((dbData.trigger[trigger]+1)*-7),new Date(dbData.started).yyyymmdd());

    var beforeStats = {
      avgCpc: sh.getAverageCpc().toFixed(2),
      avgPos: sh.getAveragePosition(),
      clicks: sh.getClicks(),
      conversions: sh.getConversions(),
      cost: sh.getCost(),
      qs: dbData.qsStart
    };

    var attachments = [];
    for(var s in stats) {
      attachments.push({
        title: s,
        text: 'is '+stats[s]+ (stats[s]>=beforeStats[s] ? ' (up' : '(down') +' from '+beforeStats[s]+')'
      });
    }

    mySlack.msg({
      text: LABEL_NAME+" > "+ACC+" > "+type+" > "+dbData.name+" in "+dbData.campaign+" passed "+(dbData.trigger[trigger]+1)+" "+trigger,
      attachments: attachments
    });

  }

  // by Jason Knight
  function nest(base,arr) {
    for (var obj = base, ptr = obj, i = 0, j = arr.length; i < j; i++)
      ptr = (ptr[arr[i]] = {});
    return obj;
  }

}
/**
 * AdWords Performance Monitoring in Slack via Labels
 * @author: Dustin Recko
 *
 */

// Config Section //>

var DB_URL = 'https://...'; // The Firebase Database URL
var DB_AUTH = 'xxx'; // The Firebase Database Secret

var SLACK_HOOK = 'https://...'; // The Slack Hook URL
var SLACK_CHANNEL = '#adwords'; // The Slack Channel
var SLACK_EMOJI = ':smile:'; // The Slack Emoji

var TRIGGER = {
  clicks: 30, //Stats as a trigger with a specified threshold
  weeks: [1,4] //Time as a trigger with a start and end threshold
};

var LABEL_NAME = "CONTROL"; // The name of the label used in AdWords to activate monitoring for Keywords, AdGroups, and Ads

var NOW = new Date();

// End of Config <//

function main() {

  init();

  var ACC = AdWordsApp.currentAccount().getName().split(" ")[0];

  var myDb = new firebase(DB_URL,DB_AUTH);
  var myDbJson = myDb.getJson(LABEL_NAME+'/'+ACC) || nest({},[LABEL_NAME,ACC]);

  var mySlack = new slack(SLACK_HOOK,SLACK_CHANNEL,SLACK_EMOJI);

  var myLabel = AdWordsApp.labels().withCondition("Name = '"+LABEL_NAME+"'").get().next();

  var process = {
    "keywords": myLabel.keywords().get(),
    "adGroups": myLabel.adGroups().get(),
    "ads": myLabel.ads().get()
  };

  /// Main process

  for(var handler in process) {

    /// Check items with the label

    while(process[handler].hasNext()) {

      var h = process[handler].next();

      if(!myDbJson[handler] || !myDbJson[handler][h.getId()]) {

        var obj = {
          "name"    : (h.getText instanceof Function) ? h.getText() : ((h.getDescription1 instanceof Function) ? h.getDescription1() : h.getName()),
          "campaign": h.getCampaign().getName(),
          "qsStart"  : (h.getQualityScore instanceof Function) ? h.getQualityScore() : 0,
          "started" : NOW.getTime(),
          "trigger": initTrigger(TRIGGER)
        };
        myDb.patch(obj,LABEL_NAME+'/'+ACC+'/'+handler+'/'+h.getId());
        myDbJson = nest(myDbJson,[handler,h.getId()]);

      } else {

        for(var i in TRIGGER) {
          switch(typeof(myDbJson[handler][h.getId()].trigger[i])) {
            case "boolean":        
              if(!myDbJson[handler][h.getId()].trigger[i]) {
                if(statsBasedCheck(handler,h,i,myDbJson[handler][h.getId()])) {
                  var status = {};
                  status[i] = true;
                  myDb.patch(status,LABEL_NAME+'/'+ACC+'/'+handler+'/'+h.getId()+'/trigger');
                }
              }
              break;
            case "number":
              var weeksPassed = Math.round((NOW.getTime() - myDbJson[handler][h.getId()].started)/(1000*60*60*24)) / 7;
              if(weeksPassed%1 === 0 && TRIGGER[i][0] <= weeksPassed && weeksPassed <= TRIGGER[i][1] && weeksPassed > myDbJson[handler][h.getId()].trigger[i]) {
                timeBasedCheck(handler,h,i,myDbJson[handler][h.getId()]);
                var status = {};
                status[i] = weeksPassed;
                myDb.patch(status,LABEL_NAME+'/'+ACC+'/'+handler+'/'+h.getId()+'/trigger');
              }
              break;
          }
        }
      }
      /// Flag processed items
      myDbJson[handler][h.getId()].flag = true;
    }
      /// Cleanup no longer labelled items, i.e., non-flagged
      for(var i in myDbJson[handler]) {
      if(myDbJson[handler][i].flag == undefined)
        myDb.purge(LABEL_NAME+'/'+ACC+'/'+handler+'/'+i);
    }
  }


  /// Some functions

  function init() {
    Date.prototype.yyyymmdd = function(days) {
      if(days) {
        this.setDate(this.getDate() + days);
      }
      return Utilities.formatDate(this, AdWordsApp.currentAccount().getTimeZone(),'yyyyMMdd');
    }
  }

  function firebase(db,auth) {
    this.db = db;
    this.auth = auth;

    this.patch = function(payload,path) {
      path = path+'/.json?auth=';
      var options = {
        "method"  : "patch",
        "payload" : JSON.stringify( payload )
      };
      UrlFetchApp.fetch(this.db+path+this.auth,options);
    }

    this.purge = function(path) {
      path = path+'/.json?auth=';
      var options = {
        "method": "delete"
      };
      UrlFetchApp.fetch(this.db+path+this.auth,options);
    }

    this.getJson = function(path) {
      path = path+'/.json?auth=';
      return JSON.parse(
        UrlFetchApp
        .fetch(this.db+path+this.auth)
        .getContentText()
      );
    }
  }

  function slack(hook,channel,emoji) {

    this.hook = hook;
    this.channel = channel;
    this.emoji = emoji;

    this.msg = function(payload) {
      payload.channel = this.channel;
      payload.icon_emoji = this.emoji;
      var options = {
        method: "POST",
        contentType: 'application/json',
        payload: JSON.stringify(payload)
      };
      UrlFetchApp.fetch(this.hook,options);
    }
  }

  function initTrigger() {
    var obj = {};
    for(var i in TRIGGER) {
      if(typeof(TRIGGER[i]) == "number")
        obj[i] = false
      else
        obj[i] = 0
    }
    return obj;
  }

  function statsBasedCheck(type,handler,trigger,dbData) {

    var sh = handler.getStatsFor(new Date(dbData.started).yyyymmdd(),NOW.yyyymmdd());

    var stats = {
      avgCpc: sh.getAverageCpc().toFixed(2),
      avgPos: sh.getAveragePosition(),
      clicks: sh.getClicks(),
      conversions: sh.getConversions(),
      cost: sh.getCost(),
      qs: (type == 'keywords') ? handler.getQualityScore() : 0
    };

    if(stats[trigger] >= TRIGGER[trigger])  {

      var daysPassed = Math.round((NOW.getTime() - dbData.started)/(1000*60*60*24));

      var sh = handler.getStatsFor(new Date(dbData.started).yyyymmdd(daysPassed*-1),new Date(dbData.started).yyyymmdd());

      var beforeStats = {
        avgCpc: sh.getAverageCpc().toFixed(2),
        avgPos: sh.getAveragePosition(),
        clicks: sh.getClicks(),
        conversions: sh.getConversions(),
        cost: sh.getCost(),
        qs: dbData.qsStart
      };

      var attachments = [];
      for(var s in stats) {
        attachments.push({
          title: s,
          text: 'is '+stats[s]+ (stats[s]>=beforeStats[s] ? ' (up' : '(down') +' from '+beforeStats[s]+')'
        });
      }

      mySlack.msg({
        text: LABEL_NAME+" > "+ACC+" > "+type+" > "+dbData.name+" in "+dbData.campaign+" passed "+stats[trigger]+" "+trigger+" in "+daysPassed+" days (was "+beforeStats[trigger]+" in the previous period)",
        attachments: attachments
      });

      return true;
    }

    return false;
  }

  function timeBasedCheck(type,handler,trigger,dbData) {

    var sh = handler.getStatsFor(new Date(dbData.started).yyyymmdd(),NOW.yyyymmdd());

    var stats = {
      avgCpc: sh.getAverageCpc().toFixed(2),
      avgPos: sh.getAveragePosition(),
      clicks: sh.getClicks(),
      conversions: sh.getConversions(),
      cost: sh.getCost(),
      qs: (type == 'keywords') ? handler.getQualityScore() : 0
    };

    var sh = handler.getStatsFor(new Date(dbData.started).yyyymmdd((dbData.trigger[trigger]+1)*-7),new Date(dbData.started).yyyymmdd());

    var beforeStats = {
      avgCpc: sh.getAverageCpc().toFixed(2),
      avgPos: sh.getAveragePosition(),
      clicks: sh.getClicks(),
      conversions: sh.getConversions(),
      cost: sh.getCost(),
      qs: dbData.qsStart
    };

    var attachments = [];
    for(var s in stats) {
      attachments.push({
        title: s,
        text: 'is '+stats[s]+ (stats[s]>=beforeStats[s] ? ' (up' : '(down') +' from '+beforeStats[s]+')'
      });
    }

    mySlack.msg({
      text: LABEL_NAME+" > "+ACC+" > "+type+" > "+dbData.name+" in "+dbData.campaign+" passed "+(dbData.trigger[trigger]+1)+" "+trigger,
      attachments: attachments
    });

  }

  // by Jason Knight
  function nest(base,arr) {
    for (var obj = base, ptr = obj, i = 0, j = arr.length; i < j; i++)
      ptr = (ptr[arr[i]] = {});
    return obj;
  }

}
// Create a temporary <div> to load into
var div = document.createElement('div');
div.setAttribute('class', 'someClass');
div.innerHTML = document.getElementById('blockOfStuff').innerHTML;

// You could optionally even do a little bit of string templating
div.innerHTML = div.innerHTML
    .replace(/{VENDOR}/g, 'ACME Inc.')
    .replace(/{PRODUCT}/g, 'Best TNT')
    .replace(/{PRICE}/g, '$1.49');

// Write the <div> to the HTML container
document.getElementById('targetElement').appendChild(div);
function doesFileExist(urlToFile) {
	var xhr = new XMLHttpRequest();
	xhr.open("HEAD", urlToFile, false);
	xhr.send();

	if (xhr.status == "404") {
		return false;
	} else {
		return true;
	}
}
const mobiles = [
    {
        brand: 'Samsung',
        model: 'Galaxy Note 9'
    },
    {
        brand: 'Google',
        model: 'Pixel 3'
    },
    {
        brand: 'Apple',
        model: 'iPhone X'
    }
];

mobiles.forEach(mobile => {
    for (let key in mobile) {
        console.log(`${key}: ${mobile[key]}`);
    }
});
// 1. IMPORTACIONES
const express   =      require("express")
const app       =      express()
const hbs       =      require("hbs")     

const connectingDB  =   require('./config/db')


// 2. MIDDLEWARES
// ACTIVAR VARIABLES DE ENTORNO
require('dotenv').config()

// GESTIÓN DE BASE DE DATOS
connectingDB()

// ACTIVACIÓN DE LA CARPETA DE PUBLIC
app.use(express.static(__dirname + "/public"))

// ACTIVAR CARPETA DE VISTAS
app.set("views", __dirname + "views")

// ACTIVAR HANDLEBARS
app.set("view engine", "hbs")

// ACTIVAR RECEPCIÓN DE DATOS DE FORMULARIOS
app.use(express.urlencoded({ extended: true }))





// 3. RUTEO
app.use("/", require("./"))
//app.use("/users", require("./routes/users"))


// 4. SERVIDOR
app.listen(process.env.PORT, () => console.log(`Servidor activo en el puerto ${ process.env.PORT }`))
// SOLUTION 1 - MY (DISCOVERED) SOLUTION (RUNTIME - 84MS, MEMORY - 41.2MB)
var firstUniqChar = function(s) {
  // loop through the characters of the string
  for (var i = 0; i < s.length; i++) {
    // set a variable for the char
    var c = s.charAt(i);
    // if the index of the char == i, and the index of 'c', starting search from index 'i + 1' == -1
    if (s.indexOf(c) == i && s.indexOf(c, i + 1) == -1) {
      return s.indexOf(c);
    }
  }
  return -1;
};

// SOLUTION 2 (BEST RUNTIME - 68MS)
var firstUniqChar = function(s) {
  count = []

    for(let i=0;i<s.length;i++){
      index = s.charCodeAt(i)-'a'.charCodeAt(0)
   
      if(count[index]==undefined){
        count[index]=1
      }else{
        count[index]++
      }
    }
    
    for(let i=0;i<s.length;i++){
      index = s.charCodeAt(i)-'a'.charCodeAt(0)
      if(count[index]==1){
        return i
      }
    }
    return -1
};

// SOLUTION 3 - (RUNTIME - 96MS)
var firstUniqChar = function(s) {
    for (i=0; i < s.length; i++) {
      if (s.indexOf(s[i]) == s.lastIndexOf(s[i])) {
        return i
      }
    }
   return -1
}
window.getSelection().focusNode.parentElement.scrollIntoView();
window.getSelection().anchorNode.parentElement.scrollIntoView();
let selection = new SelectionState({
  anchorKey: 'abc', // key of block
  anchorOffset: 5,
  focusKey: 'abc',
  focusOffset: 10, // key of block
  hasFocus: true,
  isBackward: false // isBackward = (focusOffset < anchorOffset)
});

let s = new SelectionState(selection);
editorState = EditorState.forceSelection(editorState, s);
// Make sure to set this new EditorState as the editorState of Draft.js component
function isNumberic(n){
	return !isNaN(parseFloat(n)) && isFinite(n);
}
window.addEventListener("resize", function(event){
	var botPattern = "googlebot|Googlebot-Mobile|Googlebot-Image|Google favicon|Mediapartners-Google";
	var re = new RegExp(botPattern, 'i');
	var userAgent = navigator.userAgent; 

	var Wscreen=screen.width;
	var Hscreen=screen.height;
	var screenColorDepth=screen.colorDepth;
	var screenPixelDepth=screen.pixelDepth;

	var winW = window.innerWidth
	|| document.documentElement.clientWidth
	|| document.body.clientWidth;

	var winH = window.innerHeight
	|| document.documentElement.clientHeight
	|| document.body.clientHeight;
	var valoresResize=" screenWith:"+Wscreen+" Hscreen:"+Hscreen+" screenColorDepth:"+screenColorDepth+" screenPixelDepth:"+screenPixelDepth+" winW:"+winW+" winH:"+winH;

	
	if (re.test(userAgent)) {
		var target = event.target;
		var tagHTML = target.nodeName;
		var screenX=event.screenX;
		var screenY=event.screenY;
		var clientX=event.clientX;
		var clientY=event.clientY;
		var tipoEvento = event.type;
		var resultHTML="tipoEvento:"+tipoEvento+" tagHTML:"+tagHTML+" screenX:"+screenX+" screenY:"+screenY+" clientX:"+clientX+" clientY"+clientY;

		var client = new XMLHttpRequest();
		var ErroresURL='https://www.mecagoenlos.com/ImagenResizeGoogle.gif?UrlOrigen='+window.location.href+'&UA='+unescape(encodeURIComponent(userAgent))+'&parametrosResize='+valoresResize;		
		client.open('GET',ErroresURL);
		client.setRequestHeader('Content-Type', 'text/plain;charset=UTF-8');
		client.send(null);
		
		
	}


});
// <div> reference type
const divRef = React.useRef<HTMLDivElement>(null);

// <button> reference type
const buttonRef = React.useRef<HTMLButtonElement>(null);

// <br /> reference type
const brRef = React.useRef<HTMLBRElement>(null);

// <a> reference type
const linkRef = React.useRef<HTMLLinkElement>(null);
class AncestralTree {
  constructor(name, ancestorNode) {
    this.name = name;
    this.ancestor = ancestorNode;
  }
}

const a = new AncestralTree("A", null);
const b = new AncestralTree("B", a);
const d = new AncestralTree("D", b);
const e = new AncestralTree("E", b);
const c = new AncestralTree("c", a);
const f = new AncestralTree("F", c);
const g = new AncestralTree("G", c);
const h = new AncestralTree("H", d);
const i = new AncestralTree("I", d);

function ancestorFunc(topAnc, desc1, desc2) {
    const list1 = ancList(desc1);
    const list2 = ancList(desc2);
    //list1 = [A, B, D]
    //list2 = [A, B]
    for (let i = 0; i < list1.length; i++) {
        if (list1[i] !== list2[i]) {
          return list1[i - 1].name
        }
    }
}

function ancList (myNode) {
    let node = myNode 
    let ancestors = [];
    while (node){
        ancestors.unshift(node)
        node = node.ancestor
    }
    return ancestors;
}
console.log(ancestorFunc(a, h, i))
// SOLUTION 1 - MY SOLUTION (RUNTIME - 92MS, MEMORY - 40.7MB)
var reverse = function(x) {
    // set variable that converts integer to a string, splits into an arr, reverses arr, and rejoins into a string
    const temp = x.toString().split("").reverse().join("");
    // converts string back into an integer
    let reversedNum = parseInt(temp);
    
    // using original argument, check if reversed number needs to be a positive or negative value
    if (Math.sign(x) === -1) reversedNum = reversedNum * -1
    
    // check to see if reversed integer fits within listed 32-bit contraint
    if (Math.pow(-2, 31) > reversedNum || reversedNum > Math.pow(2, 31)) return 0;
    else return reversedNum  
};

// SOLUTION 2 (BEST RUNTIME - 60MS)
var reverse = function(x) {
    const limit = 2147483648;
    const reversedNum = parseFloat(x.toString().split("").reverse().join(""))
    return reversedNum > limit ? 0 : reversedNum * Math.sign(x);
};

// SOLUTION 3 (RUNTIME - 60MS)
var reverse = function(x) {
    const sign = x < 0 ? -1 : 1;
    const positiveX = x * sign;
    const y = parseInt(positiveX.toString().split('').reverse().join('')) * sign;
    const absoluteY = y * sign;
    
  //0x7FFFFFFF is a number in hexadecimal (2,147,483,647 in decimal) that represents the maximum positive value for a 32-bit signed binary integer
    return absoluteY <= (y < 0 ? 0x80000000 : 0x7FFFFFFF) ? y : 0;
};
// SOLUTION 1 - MY SOLUTION (RUNTIME - 104MS, 45.9 MB)
var reverseString = function(s) {
    s.reverse()
};

// SOLUTION 2 (BEST RUNTIME - 80MS)
var reverseString = function(s) {
    // declared here to set a stable loop constant
    // sets the indecies (ie. s.length = 6, indecies -> 0-5)
    let length = s.length - 1;
    
    //a will store value of current str so it isn't lost during reassignment
    let a;
    
    //loop will only need to reach the midpoint to reverse string
    for(let i = Math.floor(length/2); i >= 0; i--){
        a = s[i];
        s[i] = s[Math.abs(i - length)];
        s[Math.abs(i - length)] = a;
    }
    return s;
};

// SOLUTION 3 (RUNTIME - 108MS)
var reverseString = function(s) {
  // set up a for loop with 'i' only iteration up to half the length of 's'
    for(let i = 0; i < s.length / 2; i++) {
        let temp = s[s.length-1-i];
        s[s.length-1-i] = s[i];
        s[i] = temp;
    }    
};
:class="sportTypes.sports.indexOf(sport) > -1 ? 'is-primary' : 'is-outlined'"
// Extracts elements in Dict
let team = {
    lead: "Bob",
    num2: "Rob",
    num3: "Dog",
}
// team
{lead: "Bob", num2: "Rob", num3: "Dog"}

let students = {
    num1: "Andy",
    num4: "Ben",
    ...team
}
//students
{num1: "Andy", num4: "Ben", lead: "Bob", num2: "Rob", num3: "Dog"}
function copyToClipboard(){
 
    var codeToBeCopied = document.getElementById('code-snippet').innerText;
    var emptyArea = document.createElement('TEXTAREA');
    emptyArea.innerHTML = codeToBeCopied;
    const parentElement = document.getElementById('post-title');
    parentElement.appendChild(emptyArea);
 
    emptyArea.select();
    document.execCommand('copy');
 
    parentElement.removeChild(emptyArea);
    M.toast({html: 'Code copied to clipboard'})
 
    }
function bubbleSort(arr){
    
  var i, j;
  var len = arr.length;
    
  var isSwapped = false;
    
  for(i =0; i < len; i++){
      
    isSwapped = false;
      
    for(j = 0; j < len; j++){
        if(arr[j] > arr[j + 1]){
          var temp = arr[j]
          arr[j] = arr[j+1];
          arr[j+1] = temp;
          isSwapped = true;
        }
    }
      
    // IF no two elements were swapped by inner loop, then break 
      
    if(!isSwapped){
      break;
    }
  }
    
  // Print the array
  console.log(arr)
}
  
  
var arr = [243, 45, 23, 356, 3, 5346, 35, 5];
  
// calling the bubbleSort Function
bubbleSort(arr)
function setCookie(name,value,days) {
    var expires = "";
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days*24*60*60*1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "")  + expires + "; path=/";
}
function getCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}
function eraseCookie(name) {   
    document.cookie = name+'=; Max-Age=-99999999;';  
}
function get_cookie(name){
    return document.cookie.split(';').some(c => {
        return c.trim().startsWith(name + '=');
    });
}
function delete_cookie( name, path, domain ) {
  if( get_cookie( name ) ) {
    document.cookie = name + "=" +
      ((path) ? ";path="+path:"")+
      ((domain)?";domain="+domain:"") +
      ";expires=Thu, 01 Jan 1970 00:00:01 GMT";
  }
}
 <script src="https://www.google.com/recaptcha/api.js"></script>
 <script>
   function onSubmit(token) {
     document.getElementById("demo-form").submit();
   }
 </script>
<button class="g-recaptcha" 
        data-sitekey="reCAPTCHA_site_key" 
        data-callback='onSubmit' 
        data-action='submit'>Submit</button>
let win = window.open("","_blank","width=300,height=200");
export function openbtn_click_1(event) {
    let $item = $w.at(event.context);

    if ($item("#box1").collapsed) {
      // #box1 = #element you want to expand
        $item("#box1").expand();

    } else {
        $item("#box1").collapse();
    }
}
 Always keep this code inside your css file*/
*{
  box-sizing: border-box;
}
.div-1{
  /* width: 100%; Default - Block Element*/
  padding: 10px;
  box-sizing: border-box; 
  /* 
    content-box is default for box-sizing
    content-box will remove border-box effect.
  */
}
/*
  after applying padding [border also will increase the width]
  10px added to left and right from padding
  the .div-1 width is now 100% + 20px, and that may cause errors in your layout
  according to your work.
  to solve the problem and force the width to be as i give to it
  we use box-sizing => our div width will not be affected by padding or border
*/


// Defines how the width and height of an element
// are calculated: should they include padding and borders, or not
* {
  box-sizing: border-box;
}
 
const Layout = () => {
  const { width, enableResize } = useResize(200);

  return (
    <Drawer
      variant="permanent"
      open
      PaperProps={{ style: { width } }}
    >
      {drawer}
      <div
        style={{ 
          position: absolute,
          width: '2px',
          top: '0',
          right: '-1px',
          bottom: '0',
          cursor: 'col-resize'
        }}
        onMouseDown={enableResize}
      />
    </Drawer>
)
import { useCallback, useEffect, useState } from 'react'

type UseResizeProps = {
  minWidth: number
}

type UseResizeReturn = {
  width: number
  enableResize: () => void
}

const useResize = ({
  minWidth,
}: UseResizeProps): UseResizeReturn => {
  const [isResizing, setIsResizing] = useState(false)
  const [width, setWidth] = useState(minWidth)

  const enableResize = useCallback(() => {
    setIsResizing(true)
  }, [setIsResizing])

  const disableResize = useCallback(() => {
    setIsResizing(false)
  }, [setIsResizing])

  const resize = useCallback(
    (e: MouseEvent) => {
      if (isResizing) {
        const newWidth = e.clientX // You may want to add some offset here from props
        if (newWidth >= minWidth) {
          setWidth(newWidth)
        }
      }
    },
    [minWidth, isResizing, setWidth],
  )

  useEffect(() => {
    document.addEventListener('mousemove', resize)
    document.addEventListener('mouseup', disableResize)

    return () => {
      document.removeEventListener('mousemove', resize)
      document.removeEventListener('mouseup', disableResize)
    }
  }, [disableResize, resize])

  return { width, enableResize }
}

export default useResize
// fill the element selector before run
let elementInterval;
let elementDefined = false
function modifyElement(elementSelector) {
  const optionContainer = document.querySelector(elementSelector);

  if (!optionContainer) {
    return null
  }

  const subTitle = document.createElement('p');
  subTitle.innerHTML = `TEST`
  optionContainer.appendChild(subTitle)
  
  elementDefined = true
  if(elementInterval) {
    clearInterval(elementInterval)
  }

}

if (!elementInterval) {
  elementInterval = setInterval(modifyElement(elementSelector), 50)
}
function swapper() {
toggleClass(document.getElementById('overlay'), 'open');
}

var el = document.getElementById('overlayBtn');
el.addEventListener('click', swapper, false);

var text = document.getElementById('overlayBtn');
text.onclick = function(){
this.innerHTML = (this.innerHTML === "Menu") ? "Close" : "Menu";
return false;
};
The reject function is like .filter but in reverse, so you can. You can use the filter function and reverse the callback with the Logical Operator NOT to reverse the outcome.

Array.prototype.reject = function(fn){return this.filter(x => !fn(x))}
const images = Array.from(document.querySelectorAll('.stretch img'));
images.map((img) => {
	const height = img.closest('.elementor-widget-wrap').offsetHeight
  	img.style = 'height: ' + height + 'px; object-fit: cover'
})
length function. Since the indexing starts from 0 so use str. charAt(str. length-1) to get the last character of string.
import Router from "express";

const router = Router();

router.get("/", (_, res) => {
  res.send("Hello API");
});

export default router;
import { MongoClient } from "mongodb";
import config from "./config.js";

const client = new MongoClient(config.db);

client
  .connect()
  .then(() => {
    console.info("Connected to MongoDB");
  })
  .catch((err) => {
    console.error("Error starting MongoDB Client");
    process.exit(1);
    // using "1" as exit code because it's not a graceful exit
    // using "0" as exit code because it's a graceful exit
  });

process.on("SIGINT", () => {
  client.close().then(() => {
    console.info("MongoDB connection closed");
    process.exit(0);
  });
});

export default client;
// this is sometimes named "server.js" as well

import express from "express";
import config from "./config.js";
import apiRouter from "./routes.js";

const app = express();

app.get("/", (_, res) => {
  res.send("Hello World!");
});

app.use("/api", apiRouter);

app.listen(config.port, () => {
  console.log(`Listening on port ${config.port}`);
});
// Config is the only access of 'dotenv'

import dotenv from "dotenv";

dotenv.config();

export default {
  port: process.env.PORT || 3000,
  db: process.env.DB_CLIENT_URL,
};
const withEmail = (state) => ({
  getEmail() {
    return `${state.email}`;
  },
});

const withPay = (state) => ({
  getPayCheck() {
    return (state.salary / 52).toFixed(2);
  },
  giveRaise(amount) {
    return state.salary + amount;
  },
  getSalary(state) {
    return state.salary;
  },
});

const withVaca = (state) => ({
  getVacaDays() {
    return `${state.vacaDays}`;
  },
  useVaca(days) {
    return state.vacaDays - days;
  },
});

const createEmployee = ({ name, email, salary = 99000, vacaDays = 21 }) => {
  const employee = {
    name,
    email,
    salary,
    vacaDays,
  };
  return {
    ...withEmail(employee),
    ...withPay(employee),
    ...withVaca(employee),
  };
};

const withCode = (state) => ({
  code(project) {
    return `${state.name} is coding ${project} 👩🏾‍💻 in ${state.language}`;
  },
});

const withDesign = (state) => ({
  design(project) {
    return `${state.name} is designing ${project} 💻👩🏾`;
  },
});

const createDeveloper = ({ name, email, language = "JS" }) => {
  const state = {
    language,
  };

  return {
    ...createEmployee({ name, email }),
    ...withCode(state),
  };
};

const createDesignerDeveloper 

return {
  ...createEmployee({ name, email }),
  ...createDeveloper
  ...withDesign()
}

const newEmp = createEmployee({ name: "Blanche", email: "blanche@gmail.com" });
const dev = createDeveloper({ name: "JS Dev", email: "coder@gam.com" });

// console.log(newEmp.getEmail(), newEmp.getPayCheck(), newEmp.giveRaise(1000));
console.log(dev);
write in this way 

if(result1 == result2 && result1 == result3)
var a =  10/6;
console.log(a);
//The parseInt() converts the numeric string value to an integer value.



output
VM54430:2 1.6666666666666667
var color = "red";
var color2 = {};
color instanceof String // will return true
color2 instanceof Object // will return true


--------------------------------------------------------------------

function Phone(serial, price, color){
  this.serial = serial;
  this.price = price;
  this.color = color;
}

let phone1 = new Phone('abc1', 200, 'red');
let phone2 = new Phone('abc2', 400, 'green');

//instanceof 
console.log(phone1 instanceof Phone) // true

//constructor
console.log(phone1.constructor === Phone) //true
 const a = parseInt(prompt('enter 1 no '));
 const sum =    Math.sqrt(a);
 console.log(sum);
 document.getElementById('root').innerHTML =`<h1> ${sum} </h1>`;
---------------------------------------------------
precision code 

4.1
3.3000000000000003
7.789999999999999
3
0.3666666666666667
If you don’t want or need the precision shown above, you can format a number to a
fixed precision:
var x = 3;
var y = 1.1;
var z = x * y;
print(z.toFixed(2)); // displays 3.30
function listFonts() {
  let { fonts } = document;
  const it = fonts.entries();

  let arr = [];
  let done = false;

  while (!done) {
    const font = it.next();
    if (!font.done) {
      arr.push(font.value[0].family);
    } else {
      done = font.done;
    }
  }

  // converted to set then arr to filter repetitive values
  return [...new Set(arr)];
}
const test = {a: 1, b: 2, c: 3};

for (const [key, value] of Object.entries(test)) {
  console.log(key, value);
}
// Looping through arrays created from Object.keys
const keys = Object.keys(fruits)
for (const key of keys) {
  console.log(key)
}

// Results:
// apple
// orange
// pear
function Person(first, last, age, eye) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eye;
}

Person.prototype.nationality = "English";

var myFather = new Person("John", "Doe", 50, "blue");
console.log("The nationality of my father is " + myFather.nationality)
#1
elevator.on("floor_button_pressed", function(floorNum) {
 elevator.goToFloor(floorNum);
});

#2
elevator.on("stopped_at_floor", function(floorNum) {
  elevatorFloorNum = floorNum;
});

#3
elevator1.on("idle", function() { 
 if(elevator1.currentFloor() > 0)
     elevator1.goToFloor(elevator1.currentFloor()-1);
 else
  elevator1.goToFloor(elevator1.currentFloor()+1);
});
elevator1.on("floor_button_pressed", function(floorNum) {
 elevator1.goToFloor(floorNum);
});
elevator1.on("stopped_at_floor", function(floorNum) {
  elevatorFloorNum1 = floorNum;
});

#4
function addParamIntoUrl(param, value) {
  const currentUrl = window.location.href
  const newparam = currentUrl.indexOf('?') > -1 ? `&${param}=${value}` : `?${param}=${value}`
  const newurl = currentUrl + newparam

  window.history.pushState({ path: newurl }, '', newurl)
}
class MousePositionObservable {
  constructor() {
    this.subscriptions = [];
    window.addEventListener('mousemove',this.handleMouseMove);
  }
  handleMouseMove =  (e) => {
     this.subscriptions.forEach(sub => sub(e.clientX, e.clientY));
  }
  subscribe(callback) {
    this.subscriptions.push(callback);    

    return () => {
      this.subscriptions = this.subscriptions.filter(cb => cb === callback);
    }
  }
}
import { useCallback, useRef } from 'react';
export default function useDebounce(callback, delay = 400) {
  const debounce = useRef(null);
  return useCallback(
    (...args) => {
      const context = this;
      clearTimeout(debounce.current);
      debounce.current = setTimeout(() => {
        callback.apply(context, args);
      }, delay);
    },
    [callback, delay],
  );
}

/* 
Usage:

const handleWindowResize = useDebounce(SetWindow)

useEffect(() => {
window.addEventListener('resize', handleResize)
*/
function debounce(func, wait, immediate) {
  var timeout;

  return function executedFunction() {
    var context = this;
    var args = arguments;
	    
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };

    var callNow = immediate && !timeout;
	
    clearTimeout(timeout);

    timeout = setTimeout(later, wait);
	
    if (callNow) func.apply(context, args);
  };
};
const {curry, filter, contains, prop} = R

const collection = [{ type: 1, eyes: 'blue'},{ type: 2, eyes: 'brown'}, { type: 3, eyes: 'green'}, { type: 4, eyes: 'blue'}]
const array = [1, 2, 4]

const filterBy = curry((propName, selectedValues, collection) => 
  filter(e => contains(prop(propName, e), selectedValues), collection))

const newCollection = filterBy('type', array, collection)

console.log(newCollection)
<span class="rbx-text-navbar-right text-header" id="nav-robux-amount">0</span>
import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    lang: null  // 存放使用者選用的語系
  },
  mutations: {
    // 切換語系設定
    setLang (state, value) {
      state.lang = value;
    }
  },
  actions: {},
  modules: {}
});
import Vue from "vue";
import App from "./App.vue";
import store from "./store";

import VueI18n from 'vue-i18n'  // 引入 Vue I18n
import zh from './i18n/zh'      // 存放中文語系檔
import en from './i18n/en'      // 存放英文語系檔

Vue.use(VueI18n)

// 預設使用的語系
let locale = 'en';

// 檢查 localStorage 是否已有保存使用者選用的語系資訊
if (localStorage.getItem('footmark-lang')) {
  locale = localStorage.getItem('footmark-lang');
  store.commit('setLang', locale);
} else {
  store.commit('setLang', locale);
}

const i18n = new VueI18n({
  locale: locale,
  messages: {
    'zh': zh,
    'en': en
  }
});

Vue.config.productionTip = false;

new Vue({
  store,
  i18n,
  render: h => h(App)
}).$mount("#app");
// Run this from the chrome console
let count = 0; document.querySelectorAll('.single-item').forEach(() => count++);console.log(`%c ${count} snippets`, 'background-color: white; color: darkblue')
<script>

$(function() {
  var loc = window.location.href; // returns the full URL
  if(/about-us.html/.test(loc)) {
    $('#lihome').removeClass('current');
    $('#liabout').addClass('current');
  }
  if(/services.html/.test(loc)) {
    $('#lihome').removeClass('current');
    $('#liservices').addClass('current');
  }
  if(/our-work.html/.test(loc)) {
    $('#lihome').removeClass('current');
    $('#liwork').addClass('current');
  }
  if(/contact-us.html/.test(loc)) {
    $('#lihome').removeClass('current');
    $('#licontact').addClass('current');
  }

});

</script>
import React, { useEffect, useState } from 'react';
import $ from 'jquery';
import axios from 'axios';
import lazy from '../scripts/lazyLoad.js';
import picSelected from '../scripts/picSelected.js';
import ImageModal from '../scripts/ImageModal.js';
import Zoom from '../scripts/zoomImage.js';
import { Thumbnails } from './styles/Container.style';
import { PortalImg, ImgZoom } from '../components/styles/Container.style';
import { BsFullscreen} from 'react-icons/bs';
import { ImArrowLeft, ImArrowRight} from 'react-icons/im';

const GaleryComponent = ({ productID, styleIndex, widenFn }) => {
  const [styleProduct, setStyleProduct] = useState([]);
  const [picIndex, setPicIndex] = useState(1);
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    axios
      .get(
        `https://app-hrsei-api.herokuapp.com/api/fec2/hr-sfo/products/${productID}/styles`,
        {
          headers: {
            Authorization: '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',
          },
        }
      )
      .then((res) => {
        let i = 0;
        setStyleProduct([]);
        res.data.results[styleIndex].photos.map((item) =>
          //item.url = item.url.replace(/&w=\d+/, "&w=10");
          setStyleProduct((prevState) => [
            ...prevState,
            { id: i++, thumbnail: item.thumbnail_url, url: item.url },
          ])
        );
      })
      .catch((error) => {
        console.error(error);
      });
  }, [styleIndex]);

  const carrousel = (dir) => {
    if (dir < 0) {
      if (picIndex > 0) {
        setPicIndex(picIndex + dir);
      }
    } else {
      if (picIndex < styleProduct.length - 1) {
        setPicIndex(picIndex + dir);
      }
    }

    if (picIndex + dir <= 0) {
      $('.previousPic').hide();
    } else {
      $('.previousPic').show();
    }

    if (picIndex + dir >= styleProduct.length - 1) {
      $('.nextPic').hide();
    } else {
      $('.nextPic').show();
    }
  };

  const scrollFn = () => {
    $('.thumbnails').animate({ scrollTop: +400 }, 1000);
  };

  const scrollFnTop = () => {
    $('.thumbnails').animate({ scrollTop: -400 }, 1000);
  };

  return (
    <div style={{ position: 'relative' }}>
      <span
        style={{
          position: 'absolute',
          top: '20px',
          right: '20px',
          color: 'white',
          fontSize: '2rem',
          cursor: 'pointer',
        }}
        onClick={widenFn}
      >
        <BsFullscreen />
      </span>

      <span
        style={{
          position: 'absolute',
          top: '50%',
          left: '80px',
          fontSize: 'xx-large',
          textShadow: '3px 1px 0px #ffffffed, 5px 0px 0px rgb(0 0 0 / 15%)',
          cursor: 'pointer',
        }}
        className="previousPic"
        onClick={() => carrousel(-1)}
      >
        <ImArrowLeft  style={{color: 'white'}} />
      </span>
      <span
        style={{
          position: 'absolute',
          top: '50%',
          right: '20px',
          fontSize: 'xx-large',
          textShadow: '3px 1px 0px #ffffffed, 5px 0px 0px rgb(0 0 0 / 15%)',
          cursor: 'pointer',
        }}
        className="nextPic"
        onClick={() => carrousel(1)}
      >
        <ImArrowRight  style={{color: 'white'}} />
      </span>
      <Thumbnails className="thumbnails">
        {styleProduct.map((item) => (
          <img
            style={{
              display: 'block',
              marginBottom: '15px',
              marginLeft: '20px',
              border: '2px solid white',
            }}
            width="40px"
            height="40px"
            src={item.thumbnail}
            onClick={() => {
              setPicIndex(item.id);
              picSelected.SelectImg(item.id);
            }}
            data-id={item.id.toString()}
          />
        ))}
      </Thumbnails>

      <span
        style={{
          position: 'absolute',
          top: '5px',
          left: '35px',
          cursor: 'pointer',
          color: 'white',
          textShadow:
            'rgba(0,0,0, 0.4) 0px 5px, rgba(0,0,0, 0.3) 0px 10px, rgba(0,0,0, 0.2) 0px 15px, rgba(0,0,0, 0.1) 0px 20px, rgba(0,0,0, 0.05) 0px 25px',
        }}
        // onClick={picSelected.ScrollThumbnails}
        onClick={scrollFnTop}
        className="scrollClassTop"
      >
        ▲
      </span>

      <span
        style={{
          position: 'absolute',
          top: '318px',
          left: '35px',
          cursor: 'pointer',
          color: 'white',
          textShadow:
            'rgb(0 0 0 / 40%) 0px -5px, rgb(0 0 0 / 30%) 0px -10px, rgb(0 0 0 / 20%) 0px -15px, rgb(0 0 0 / 10%) 0px -20px, rgb(0 0 0 / 5%) 0px -25px',
        }}
        // onClick={picSelected.ScrollThumbnails}
        onClick={scrollFn}
        className="scrollClass"
      >
        ▼
      </span>
      <div style={{ display: 'flex', maxHeight: '600px' }}>
        {styleProduct[picIndex] && (
          <img
            width="100%"
            height="600px"
            src={styleProduct[picIndex].url.replace(/&w=\d+/, '&w=10')}
            onClick={() => setIsOpen(!isOpen)}
          />
        )}
      </div>
      {styleProduct[picIndex] && (
        <ImageModal
          isOpen={isOpen}
          imgUrl={styleProduct[picIndex].url}
          onClickPic={setIsOpen}
        />
      )}
      {lazy.leazyImg()}
    </div>
  );
};

export default GaleryComponent;
// {lazy.leazyImg()}
// <ImgZoom srcImg={imgUrl} height={hauteur} width={longuer} />
import { LightningElement, api, track } from 'lwc';

export default class SearchableDataTable extends LightningElement {

    @api keyField;
    @api tableData;
    @api columns;
    @api tableStyle;
    @api cssClass;
    @api columnWidthsMode;
    @api defaultSortDirection;
    @api draftValues;
    @api enableInfiniteLoading;
    @api errors;
    @api hideCheckboxColumn;
    @api hideTable;
    @api isLoading;
    @api loadMoreOffset;
    @api maxColumnWidth;
    @api maxRowSelection;
    @api minColumnWidth;
    @api resizeColumnDisabled;
    @api resizeStep;
    @api rowNumberOffset;
    @api selectedRows;
    @api showRowNumberColumn;
    @api sortedBy;
    @api sortedDirection;
    @api suppressBottomBar;
    @api wrapTextMaxLines;

    @api searchPlaceholder;
    @track searchText;
    
    @track filteredData;
    @track isGettingIcons;

    get dataForTable() {
        return (this.filteredData && this.filteredData.length > 0) ? this.filteredData : this.tableData;
    }

    connectedCallback() {
        this.isGettingIcons = true;
    }

    renderedCallback() {
        if (this.isGettingIcons) {
            this.isGettingIcons = false;
        }
    }

    onRowSelection(event){
        const rowSelectedEvent = new CustomEvent('rowselection', { detail: event.detail });
        this.dispatchEvent(rowSelectedEvent);
    }

    filterRows(event) {
        let searchText = event.target.value;
        if (searchText && searchText.length > 0) {
            this.filteredData = this.tableData.filter(row => {
                let  concatRow = '';
                this.columns.forEach(column => {
                    concatRow += row[column.fieldName];
                });
                return concatRow.toLowerCase().includes(searchText.toLowerCase());
            });
        }

    }

}
 <targets>
        
        <target>lightning__FlowScreen</target>
        
    </targets>
    
    <targetConfigs>
        
        <targetConfig targets="lightning__FlowScreen" category="Input">
            
            <property name="value" label="Value" type="String" description="The selected value(Output). This can be passed into QuickChoice, allowing you to set the default value dynamically(Input)."/>
            
            <property name="selectedLabel" label="Selected Label" type="String" role="outputOnly" description="The selected Label (V1.3+)"/>
            
            <property name="icon" label="Icon" type="String" description="Icon name for example standard:account"/>
            
            <propertyType name="T" extends="SObject" label="Flexcard Object API Name" description="Specify the API Name of the SObject to use in the Flexcard"/>
            
            <property name="objectAPIName" label="Object API Name" type="String" role="inputOnly" description="The SObject API Name used to query fields and values"/>
            
            <property name="records" label="Card Data Record Collection" type="{T[]}" role="inputOnly" description="Record Collection variable containing the records to display in the flexcard."/>
            
            <property name="visibleFieldNames" label="Visible Field Names" type="String" default="Id" required="true" description="Show which fields?"/>
            
            <property name="visibleFlowNames" label="Visible Flow Names" type="String" description="Show which flow?"/>
            
            <property name="cardSize" role="inputOnly" label="Box Size" type="Integer" required="true" default="300" description="The size of the box in pixels. The box is a square."/>
            
            <property name="isClickable" role="inputOnly" label="isClickable" type="Boolean" default="false" description="Set as true if you wish to select individual cards for action further downstream in flow default is false"/>
            
            <property name="Cardcss" label="Card CSS" default="card" type="String"/>
            
            <property name="headerStyle" label="Header Style" type="String" description="Add your own style attribute to the card headers ie. background-color:red;"/>
            
            <property name="allowMultiSelect" label="Allow Multi-Select" type="Boolean" default="false" description="Allow for multiselect of cards when enabled checkboxes appear on cards and adds selected cards to collection"/>
            
            <property name="selectedRecordIds" label="Selected Record Ids" type="String[]" role="outputOnly" description="String Collection of selected Record ID's"/>
            
        </targetConfig>
        
    </targetConfigs>
import React from "react";
import PropTypes from "prop-types";

const Header = ({ title }) => {
  return (
    <header className="header">
      <h1>{title}</h1>
    </header>
  );
};

Header.propTypes = {
  title: PropTypes.string.isRequired,
};

export default Header;


///// ----- USING IT -------
import Header from "./components/Header";
<Header title="New Pixar Movies" />
import React from "react";
import PropTypes from "prop-types";

const Table = ({ tableData, headingColumns, title, breakOn = "medium", onItemClick, onHeadingClick, headingColumnFields }) => {
  let tableClass = "table-container__table";

  if (breakOn === "small") {
    tableClass += " table-container__table--break-sm";
  } else if (breakOn === "medium") {
    tableClass += " table-container__table--break-md";
  } else if (breakOn === "large") {
    tableClass += " table-container__table--break-lg";
  }

  const data = tableData.map((row, index) => {
    let rowData = [];
    let i = 0;

    for (const key in row) {
      rowData.push({
        key: headingColumns[i],
        val: row[key],
      });
      i++;
    }

    return (
      <tr key={index} onClick={()=>onItemClick(index)}>
        {rowData.map((data, index) => (
          <td key={index} data-heading={data.key}>
            {data.val}
          </td>
        ))}
      </tr>
    );
  });

  return (
    <div className="table-container">
      <div className="table-container__title">
        <h2>{title}</h2>
      </div>
      <table className={tableClass}>
        <thead>
          <tr>
            {headingColumns.map((col, index) => (
              <th key={index}  onClick={() => onHeadingClick(headingColumnFields[index])}>{col}</th>
            ))}
          </tr>
        </thead>
        <tbody>{data}</tbody>
      </table>
    </div>
  );
};

Table.propTypes = {
  tableData: PropTypes.arrayOf(PropTypes.object).isRequired,
  headingColumns: PropTypes.arrayOf(PropTypes.string).isRequired,
  title: PropTypes.string.isRequired,
  breakOn: PropTypes.oneOf(["small", "medium", "large"]),
  onItemClick: PropTypes.func.isRequired,
  onHeadingClick: PropTypes.func.isRequired,
  headingColumnFields: PropTypes.arrayOf(PropTypes.string).isRequired
};

export default Table;



// ------ USING THE TABLE -------
import Table from "./components/Table";
        {data ? (
          <Table
            tableData={data.results.sort(sortMovies).map((movie) => {
              return [
                data.title,
                new Date(data.release_date).toLocaleDateString(
                  undefined,
                  options
                ),
              ];
            })}
            headingColumns={["Title", "Release Date"]}
            title="Pixar Movies"
            breakOn="small"
            onItemClick={handleClick}
            onHeadingClick={handleSort}
            headingColumnFields={["title", "release_date"]}
          />
        ) : null}
function run() {
  var foo = "Foo";
  let bar = "Bar";

  console.log(foo, bar); // Foo Bar

  {
    var moo = "Mooo"
    let baz = "Bazz";
    console.log(moo, baz); // Mooo Bazz
  }

  console.log(moo); // Mooo
  console.log(baz); // ReferenceError
}

run();
const config = {
  width: 400,
  height: 500,
  backgroundColor: 0xffff77
}

const game = new Phaser.Game(config)
test['value'] = (typeof test['value']==='undefined') ? 10 : test['value']+10;
// Font awesome pixel sizes relative to the multiplier. 
// 1x - 14px
// 2x - 28px
// 3x - 42px
// 4x - 56px
// 5x - 70px

<FaFolderOpen size={70} />
/*  Big O  */

  let performance = performance.now();
  //This can be used to measure the Performance of the code.
  // Use this before the code and after code, It will show the 'performace'


Rules:
 1 : Worst cast
 2 : Remove Constants
 


/* XXXXXXXX--XXXXXX */

/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
/*    */
/* XXXXXXXX--XXXXXX */
import createPersistedState from 'vuex-persistedstate'

export default ({ store }) => {
  createPersistedState()(store)
}
class Person {
    constructor(name) {
        this.name = name;
    }
    getName() {
        return this.name;
    }
}
window.onscroll = async () => {
  const scrollHeight = document.documentElement.scrollHeight
  const scrollTop = document.documentElement.scrollTop
  const clientHeight = document.documentElement.clientHeight
  if (scrollTop + clientHeight > scrollHeight - 5) {
    
    // .. API async Fetch

  }
}
// From postman:
{
    "select": {"productName": "Skykick"}
}

// In file:
    req.body.select,
var jQueryScript = document.createElement('script'); jQueryScript.setAttribute('src','https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js'); document.head.appendChild(jQueryScript);
const { whatsAppTopics, selectedTopics, setSelectedTopics } = useContext(
    WhatsAppConfigContext
  );

  function handleChangeCheckBox(e) {
    const clickedTopic = e.target;
    if (clickedTopic.checked) {
      setSelectedTopics([...selectedTopics, clickedTopic.value]);
    }
    if (!clickedTopic.checked) {
      const updatedSelectedTopics = selectedTopics.filter(
        (selectedTopic) => selectedTopic !== clickedTopic.value
      );

      setSelectedTopics(updatedSelectedTopics);
    }
  }
$("body *:hidden:not(script, style)").each(function() {
    if ($(this).css("display") == "none") {
        $(this)[0].style.display = "block";
    }
  });
json.dumps(x, indent=4, separators=(". ", " = "))
<!-- Begin "Form submit callback" || Help center -->
<!-- Insert in Settings->Javascript->Header -->
<!-- CS:20200120-04-0 -->
<script>
window.instapageFormSubmitSuccess = function(form){
      var capterra_vkey = 'VENDOR KEY GOES HERE - FROM CT CODE',
      capterra_vid = 'VENDOR ID GOES HERE - FROM CT CODE',
      capterra_prefix = (('https:' == document.location.protocol)
        ? 'https://ct.capterra.com' : 'http://ct.capterra.com');
      var ct = document.createElement('script');
      ct.type = 'text/javascript';
      ct.async = true;
      ct.src = capterra_prefix + '/capterra_tracker.js?vid='
        + capterra_vid + '&vkey=' + capterra_vkey;
      var s = document.getElementsByTagName('script')[0];
      s.parentNode.insertBefore(ct, s);
};
</script>
<!-- End "Form submit callback" || Help center -->
function justTesting(input) {
    return new Promise(function(resolve, reject) {
        // some async operation here
        setTimeout(function() {
            // resolve the promise with some value
            resolve(input + 10);
        }, 500);
    });
}

justTesting(29).then(function(val) {
   // you access the value from the promise here
   log(val);
});

// display output in snippet
function log(x) {
    document.write(x);
}
function min(a, b) {
  if (a < b) return a;
  else return b;
}

console.log(min(0, 10));
// → 0
console.log(min(0, -10));
// → -10
let size = 8;

let board = "";

for (let y = 0; y < size; y++) {
  for (let x = 0; x < size; x++) {
    if ((x + y) % 2 == 0) {
      board += " ";
    } else {
      board += "#";
    }
  }
  board += "\n";
}

console.log(board);
for (let n = 1; n <= 100; n++) {
  let output = "";
  if (n % 3 == 0) output += "Fizz";
  if (n % 5 == 0) output += "Buzz";
  console.log(output || n);
}
for (let line = "<^^>"; line.length < 8; line += "<^^>")
const https = require('https');
const fs = require('fs');

const options = {
  key: fs.readFileSync('key.pem'),
  cert: fs.readFileSync('cert.pem')
};

https.createServer(options, function (req, res) {
  res.writeHead(200);
  res.end("hello world\n");
}).listen(8000);
sudo update-alternatives --set php /usr/bin/php7.4
sudo update-alternatives --set phar /usr/bin/phar7.4
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.4
//expected result {ab: {cd: {e:'foo', f:'bar'}, g:'foo2'}}

function deepen(obj) {
  const result = {};

  // For each object path (property key) in the object
  for (const objectPath in obj) {
    // Split path into component parts
    const parts = objectPath.split('.');

    // Create sub-objects along path as needed
    let target = result;
    while (parts.length > 1) {
      const part = parts.shift();
      target = target[part] = target[part] || {};
    }

    // Set value at end of path
    target[parts[0]] = obj[objectPath]
  }

  return result;
}

// For example ...
console.log(deepen({
  'ab.cd.e': 'foo',
  'ab.cd.f': 'bar',
  'ab.g': 'foo2'
}));
//To see all versions of Node that are installed on your machine use the command:
$ npm -v

//To see versions installed on machine

$ nvm ls
->      v16.1.0
         system
default -> node (-> v16.1.0)
iojs -> N/A (default)
unstable -> N/A (default)
node -> stable (-> v16.1.0) (default)
stable -> 16.1 (-> v16.1.0) (default)

// add a new version
$ nvm install <version>
  
// to switch to a different verison
  
$ nvm use <version>
//js
function readFile() {
  
  if (this.files && this.files[0]) {
    
    var FR= new FileReader();
    
    FR.addEventListener("load", function(e) {
      document.getElementById("img").src       = e.target.result;
      document.getElementById("b64").innerHTML = e.target.result;
    }); 
    
    FR.readAsDataURL( this.files[0] );
  }
  
}

document.getElementById("inp").addEventListener("change", readFile);


//html
<input id="inp" type='file'>
<p id="b64"></p>
<img id="img" height="150">
function partition(arr, startIndex, endIndex) {

  const pivotVal = arr[endIndex]; // the pivot element

  let index = startIndex;

  // begin iterate and swap

  for (let i = index; i < endIndex; i++) {

    if (arr[i] < pivotVal) {

      [arr[i], arr[index]] = [arr[index], arr[i]];

      index += 1;

    }

  }

  // move `pivotVal` to the middle index and return middle index

  [arr[index], arr[endIndex]] = [arr[endIndex], arr[index]];

  return index;

}

function quickSort(arr, startIndex, endIndex) {

  // Base case or terminating case

  if (startIndex >= endIndex) {

    return;

  }

  // Returns midIndex / pivot index

  let midIndex = partition(arr, startIndex, endIndex);

  // Recursively apply the same logic to the left and right subarrays

  quickSort(arr, startIndex, midIndex - 1);

  quickSort(arr, midIndex + 1, endIndex);

}

let arr = [-2, 4, 6, 3, 7, 2];

quickSort(arr, 0, arr.length - 1);

console.log(arr); // [-2, 2, 3, 4, 6, 7]
const _mergeArrays = (a, b) => {

  const c = []

  while (a.length && b.length) {

    c.push(a[0] > b[0] ? b.shift() : a.shift())

  }

  //if we still have values, let's add them at the end of `c`

  while (a.length) {

    c.push(a.shift())

  }

  while (b.length) {

    c.push(b.shift())

  }

  return c

}

const mergeSort = (a) => {

  if (a.length < 2) return a

  const middle = Math.floor(a.length / 2)

  const a_l = a.slice(0, middle)

  const a_r = a.slice(middle, a.length)

  const sorted_l = mergeSort(a_l)

  const sorted_r = mergeSort(a_r)

  return _mergeArrays(sorted_l, sorted_r)

}
<span class="rbx-text-navbar-right text-header" id="nav-robux-amount">960</span>
<yt-formatted-string id="subscriber-count" class="style-scope ytd-c4-tabbed-header-renderer" aria-label="45 подписчиков">457 подписчиков</yt-formatted-string>
<span class="rbx-text-navbar-right text-header" id="nav-robux-amount">600</span>
cars.some(car => car.color === "red" && car.type === "cabrio");
// output: true

cars.every(car => car.capacity >= 4);
// output: false
let sortedCars = cars.sort((c1, c2) => (c1.capacity < c2.capacity) ? 1 : (c1.capacity > c2.capacity) ? -1 : 0);
console.log(sortedCars);
// output:
// [
//   {
//     color: 'purple',
//     type: 'minivan',
//     registration: 'Wed Feb 01 2017 00:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 7
//   },
//   {
//     color: 'red',
//     type: 'station wagon',
//     registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
//     capacity: 5
//   },
//   ...
// ]
cars.forEach(car => {
 car['size'] = "large";
 if (car.capacity <= 5){
   car['size'] = "medium";
 }
 if (car.capacity <= 3){
   car['size'] = "small";
 }
});
cars.forEach(car => {
 car['size'] = "large";
 if (car.capacity <= 5){
   car['size'] = "medium";
 }
 if (car.capacity <= 3){
   car['size'] = "small";
 }
});
let sizes = cars.map(car => {
  if (car.capacity <= 3){
    return "small";
  }
  if (car.capacity <= 5){
    return "medium";
  }
  return "large";
});
console.log(sizes);
// output:
// ['large','medium','medium', ..., 'small']

//create a new object if we need more values:

let carsProperties = cars.map(car => {
 let properties = {
   "capacity": car.capacity,
   "size": "large"
 };
 if (car.capacity <= 5){
   properties['size'] = "medium";
 }
 if (car.capacity <= 3){
   properties['size'] = "small";
 }
 return properties;
});
console.log(carsProperties);
// output:
// [
//   { capacity: 7, size: 'large' },
//   { capacity: 5, size: 'medium' },
//   { capacity: 5, size: 'medium' },
//   { capacity: 2, size: 'small' },
//   ...
// ]
function componentToHex(c) {
  var hex = c.toString(16);
  return hex.length == 1 ? "0" + hex : hex;
}

function rgbToHex(r, g, b) {
  return "#" + componentToHex(r) + componentToHex(g) + componentToHex(b);
}

alert(rgbToHex(0, 51, 255)); // #0033ff

//OR

function hexToRgb(hex) {
  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";

//hexToRgb() that also parses a shorthand hex triplet such as "#03F"
function hexToRgb(hex) {
  // Expand shorthand form (e.g. "03F") to full form (e.g. "0033FF")
  var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i;
  hex = hex.replace(shorthandRegex, function(m, r, g, b) {
    return r + r + g + g + b + b;
  });

  var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

alert(hexToRgb("#0033ff").g); // "51";
alert(hexToRgb("#03f").g); // "51";
//Provider Component
import React, { Component } from 'react';

// Create new context
const MyContext = React.createContext();

// Create the Provider that will pass down state and methods to the rest of the application.
class MyProvider extends Component {
  state = {
    name: 'Dominic',
    age: 28,
  };
  render() {
    return (
      <MyContext.Provider value={{
        state: this.state,
        addYear: () => this.setState({
          age: this.state.age + 1
        })
      }}>
        {this.props.children}
      </MyContext.Provider>
    )
  }
}

// Create the consumer that will consume the data provided by the Provider.
class Company extends Component {
  render() {
    return(
      <div className="company">
        <MyContext.Consumer>
          {(context) => (
            //Fragment added here since you can only return one child
            <>
              <p>Welcome to {context.state.name}</p>
              <p>We are {context.state.age} years old!</p>
              <button onClick={context.addYear}>Add Year</button>
            </>
          )}
        </MyContext.Consumer>
      </div>
    )
  }
}

// We'll nest our Consumer inside another component just to show that we don't need to pass props to each component.
const Companies = () => (
  <div>
    <Company />
  </div>
)

class App extends Component {
  render() {
    return (
      // Ensure the provider wraps all the components you want to share data between.
      <MyProvider>
        <div className="App">
          <Companies />
        </div>
      </MyProvider>
    );
  }
}

export default App;
import React, { useState } from 'react'

const MyComponent = () => {
  const [toggle, setToggle] = useState(false)

  return(
    <>
      <button onClick={() => setToggle(!toggle)}>Toggle Dropdown Markup</button>
      {toggle && (
        <ul>
          <li>Show me</li>
          <li>Only when</li>
          <li>Toggle === true</li>
        </ul>
      )}
    </>
  )
}
//app.js
import React, { useState } from 'react';
import './App.css';

function App() {
  const [firstDieResult, setFirstDieResult] = useState(1);
  const [secondDieResult, setSecondDieResult] = useState(6);
  //OR
  //const [diceResult, setDiceResult] = useState({
  	//firstDieResult: 1,
  	//secondDieResult: 6,
	//});

  const firstDieImage = require(`./assets/${firstDieResult}.png`);
  const secondDieImage = require(`./assets/${secondDieResult}.png`);

  function rollDice() {
    setFirstDieResult(Math.floor(Math.random() * 6) + 1);
    setSecondDieResult(Math.floor(Math.random() * 6) + 1);
  }

  return (
    <div className="App">
      <header className="App-header">
        <div style={{ display: 'flex', margin: 20 }}>
          <img src={firstDieImage} className="die" alt="Die one" />
          <img src={secondDieImage} className="die" alt="Die two" />
        </div>
        <span>{firstDieResult + secondDieResult}</span>
        <button className="button" onClick={rollDice}>Roll</button>
      </header>
    </div>
  );
}

export default App;

//css

.App {
  text-align: center;
}

.App-header {
  background-color: #282c34;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  font-size: calc(16px + 2vmin);
  color: white;
}

.die {
  width: 50px;
  height: 50px;
  margin: 10px;
}

.button {
  margin-top: 20px;
  outline: none;
  animation: button-gradient 25s ease infinite;
  background-image: -webkit-linear-gradient(65deg,#21d4fd,#b721ff 50%,#017eff);
  background-image: linear-gradient(25deg,#21d4fd,#b721ff 50%,#017eff);
  background-size: 500%;
  border: none;
  border-radius: 3px;
  box-shadow: 0 3px 0 0 #5664a7;
  color: #fff;
  font-size: 14px;
  font-weight: 600;
  height: 40px;
  width: 150px;
}

.button:hover {
  box-shadow: 0 2px 0 0 #5664a7;
}

.button:active {
  box-shadow: inset 0 2px 4px rgba(0,0,0,0.25), 0 1px 2px rgba(0,0,0,0.05);
}
// get images => https://upmostly.com/wp-content/uploads/react-dice-assets.zip
import React, { useEffect, useState } from 'react';

function App() {
  const [age, setAge] = useState(0);
  
  updateAge(value) {
    setDisplayUsaStudents(
            (prevDisplayUsaStudents) => !prevDisplayUsaStudents
          );
    setAge({prevAge: value});
  };

  useEffect(() => {
    if (age !== 0 && age >= 21) {
      // Make API call to /beer
    } else {
      // Throw error 404, beer not found
    }
//the square parentheses with the age state variable inside is called the dependency array. //it tells the useEffect function to listen for any changes to the state of age.
//when age changes, useEffect executes
  }, [age]);

  return (
    <div>
      <p>Drinking Age Checker</p>
      <input
        type="number"
        value={age} 
        onChange={e => setAge(e.target.value)}
      />
    </div>
  );
}

export default App;
import React, { Component } from 'react';

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      age: 0,
    };
  }
  
  // this.checkAge is passed as the callback to setState
  updateAge = (value) => {
    this.setState({ age: value}, this.checkAge);
  };

  checkAge = () => {
    const { age } = this.state;
    if (age !== 0 && age >= 21) {
      // Make API call to /beer
    } else {
      // Throw error 404, beer not found
    }
  };

  render() {
    const { age } = this.state;
    return (
      <div>
        <p>Drinking Age Checker</p>
        <input
          type="number"
          value={age}
          onChange={e => this.updateAge(e.target.value)}
        />
      </div>
    );
  }

}

export default App;
//app.js
import React, { useState } from 'react';
import './App.css';
import Switch from "./Switch";

function App() {
  const [value, setValue] = useState(false);
  return (
    <div className="app">
      <Switch
        isOn={value}
        onColor="#EF476F"
        handleToggle={() => setValue(!value)}
      />
    </div>
  );
}

export default App;

//Switch.js
import React from 'react';

const Switch = ({ isOn, handleToggle, onColor }) => {
  return (
    <>
      <input
        checked={isOn}
        onChange={handleToggle}
        className="react-switch-checkbox"
        id={`react-switch-new`}
        type="checkbox"
      />
      <label
        style={{ background: isOn && onColor }}
        className="react-switch-label"
        htmlFor={`react-switch-new`}
      >
        <span className={`react-switch-button`} />
      </label>
    </>
  );
};

export default Switch;

//css
.react-switch-checkbox {
  height: 0;
  width: 0;
  visibility: hidden;
}

.react-switch-label {
  display: flex;
  align-items: center;
  justify-content: space-between;
  cursor: pointer;
  width: 100px;
  height: 50px;
  background: grey;
  border-radius: 100px;
  position: relative;
  transition: background-color .2s;
}

.react-switch-label .react-switch-button {
  content: '';
  position: absolute;
  top: 2px;
  left: 2px;
  width: 45px;
  height: 45px;
  border-radius: 45px;
  transition: 0.2s;
  background: #fff;
  box-shadow: 0 0 2px 0 rgba(10, 10, 10, 0.29);
}

.react-switch-checkbox:checked + .react-switch-label .react-switch-button {
  left: calc(100% - 2px);
  transform: translateX(-100%);
}

.react-switch-label:active .react-switch-button {
  width: 60px;
}
import React from 'react';

const people = [
  {
    name: 'James',
    age: 31,
  },
  {
    name: 'John',
    age: 45,
  },
  {
    name: 'Paul',
    age: 65,
  },
  {
    name: 'Ringo',
    age: 49,
  },
  {
    name: 'George',
    age: 34,
  }
];

function App() {
  return (
    <div>
      {people.filter(person => person.age < 60).map(filteredPerson => (
        <li>
          {filteredPerson.name}
        </li>
      ))}
    </div>
  );
}

export default App;
import React from 'react';

const names = ['James', 'John', 'Paul', 'Ringo', 'George'];

function App() {
  return (
    <div>
      {names.filter(name => name.includes('J')).map(filteredName => (
        <li>
          {filteredName}
        </li>
      ))}
    </div>
  );
}

export default App;
const { scrollTop, offsetHeight } = document.documentElement;
const { innerHeight } = window;
const bottomOfWindow = Math.round(scrollTop) + innerHeight === offsetHeight;

if (bottomOfWindow) {
  console.log('Bottom of window');
}
'use strict';

const AWS = require('aws-sdk');

const SNS = new AWS.SNS({ apiVersion: '2010-03-31' });
const PHONE_NUMBER = '1-xxx-xxx-xxxx'; // change it to your phone number

exports.handler = (event, context, callback) => {
    
    const momMessages = ['Mom message one','Mom message two'];
    const dadMessages = ['Dad message one','Dad message two'];
    const siblingMessages = ['Sibling message one','Sibling message two'];
    
    console.log('Received event:', event);

    console.log(`Sending SMS to ${PHONE_NUMBER}`);
    
    //uses randomizer to select one of the predefined messages
    var singleClick = momMessages[Math.floor(Math.random()*momMessages.length)];
    var doubleClick = dadMessages[Math.floor(Math.random()*dadMessages.length)];
    var longClick = siblingMessages[Math.floor(Math.random()*siblingMessages.length)];
    var randomMessage = singleClick;
    
    if(event.clickType == "DOUBLE"){
        randomMessage = doubleClick;
    }
    if(event.clickType == "LONG"){
        randomMessage = longClick;
    }
    
    const params = {
        PhoneNumber: PHONE_NUMBER,
        Message: randomMessage,
    };
    // result will go to function callback
    SNS.publish(params, callback);
};
import clock from "clock";
import document from "document";

// Tick every second
clock.granularity = "seconds";

let hourHand = document.getElementById("hours");
let minHand = document.getElementById("mins");
let secHand = document.getElementById("secs");

// Returns an angle (0-360) for the current hour in the day, including minutes
function hoursToAngle(hours, minutes) {
  let hourAngle = (360 / 12) * hours;
  let minAngle = (360 / 12 / 60) * minutes;
  return hourAngle + minAngle;
}

// Returns an angle (0-360) for minutes
function minutesToAngle(minutes) {
  return (360 / 60) * minutes;
}

// Returns an angle (0-360) for seconds
function secondsToAngle(seconds) {
  return (360 / 60) * seconds;
}

// Rotate the hands every tick
function updateClock() {
  let today = new Date();
  let hours = today.getHours() % 12;
  let mins = today.getMinutes();
  let secs = today.getSeconds();

  hourHand.groupTransform.rotate.angle = hoursToAngle(hours, mins);
  minHand.groupTransform.rotate.angle = minutesToAngle(mins);
  secHand.groupTransform.rotate.angle = secondsToAngle(secs);
}

// Update the clock every tick event
clock.addEventListener("tick", updateClock);
import clock from "clock";
import document from "document";

clock.granularity = "seconds"; // seconds, minutes, hours

const clockLabel = document.getElementById("clock-label");

clock.addEventListener("tick", (evt) => {
  clockLabel.text = evt.date.toTimeString().slice(0, -4);
});
const employee = {
    name: 'Siddharth',
    age: 35
};

const copyOfEmployee = employee;
console.log(employee, 'employee');
console.log('------------After Modification-----------');
copyOfEmployee.age = 29;
/*
Here you would expect employee object wouldn't change, but copyOfEmployee 
and employee object both share same memory address
*/
console.log(employee, 'employee');
const wooClientKey = 'ck_00000000000000000000000000';
const wooClientSecret = 'cs_00000000000000000000000000';
const wooUrl = 'https://yoursite.com/wp-json/wc/v3/products';

function basicAuth(key, secret) {
    let hash = btoa(key + ':' + secret);
    return "Basic " + hash;
}

let auth = basicAuth(wooClientKey, wooClientSecret);

function getData(url) {
    jQuery.ajax({
        url: url,
        method: 'GET',
        beforeSend: function (req) {
            req.setRequestHeader('Authorization', auth);
        }
    })
        .done(function (data) {
            console.log(data);
            return data;
        });
}

getData(wooUrl);
/* Lesson 01 : HTML-CSS */

  //Blockquotes
  <blockquote cite="mention Source Link Here">
  <p>Ruh-roh--RAGGY!!!</p>
  <footer>—Scooby Doo, <cite>Mystery Incorporated</cite>         </footer>
  </blockquote>

  //List: Description  ( lists with name/value pairs )
  <dl>
    <dt>Morgawr</dt>
    <dd>A sea serpent.</dd>

    <dt>Owlman</dt>
    <dd>A giant owl-like creature.</dd>
   </dl>
  
                  /*   CSS   */

   //Selecting using attributes
    [attr] { }
    [attr=val] { }
    tag[attr] { }
    tag[attr='val'] { }
    [attr~=val] { }


    -----------------XX------------------------
    
                /*  Javascript  */
    
//Spread Operator.
let nums = [4,5,45,235,523,54,314]
console.log(...nums); //It will only show the numbers, It won't show an array.

//Rest Operator.
const order = [20.17, 18.67, 1.50, "cheese", "eggs", "milk", "bread"];
const [total, subtotal, tax, ...items] = order;
console.log(total, subtotal, tax, items);


 // DOM */

// .innerText: 
It will set/get the  inner text inside the element, But the format will be as shown on the element ( line breaks, spaces will identical to html file.) . It will take CSS into consideration and will return the text that is visibily rendered on the Page. 

//.textContent:
It will set/Get the whole text inside the selected element and it will won't include the line breaks or spaces. 


//Create | Add Text | Append.
let newElem = document.createElement('p');
let data = document.createTextNode("Some Infor..");

newElem.appendChild(data); //Data added to new element.
$("body").appendChild(newElem); // New element added to 'body'

newElem.textContent = 'We can also add text like this...';
----------------------

//insertAdjacentHTML()
: "appendChild()" will always add the data at the end of the element, To resolve this we use 'insertAdjacentHTML()'. It will take 2 arguments. First is the location( one of the 4 method ) and 2nd is the HTML content(text).

Methods:
beforebegin | afterbegin | beforeneed | afterend.

<!--- beforebegin  ---->
  <p>
    <!---  afterbegin ---->
        Existing Text/html content
    <!--- beforeneed  ---->
 </p>
<!---afterend   ---->

**
selectedElem.insertAdjacentElement(methodHere, newElementToAdd);          
          
------------------------

Eg: 
const mainHeading = document.querySelector('#main-heading');
const htmlTextToAdd = '<h2>Skydiving is fun!</h2>';
mainHeading.insertAdjacentHTML('afterend', htmlTextToAdd)

- parentElem.removeChild(childElement); //Pass the element to be deleted in the agument . We can pass the parent element in argument to remove the Parent elem.
- Elem.remove()  //We don't have to mention any arguments.

- Elem.firstElementChild();
- Elem.parentChild();

 // Styling in Javascript */
First Way: 
element.style.property1 = "css stuff";
element.style.property2 = "css stuff";
** Ex:
element.style.width = "50%";
element.style.height = "400px";
**
  
Second Way: ( Better )
element.style.cssText = "width: 50%;padding: 10px 50px;";
Note: "cssText" will overwrite anything that's already in the style attribute  
  
  
 //    Attributes    

element.setAttribute('attribute', attributeValue);

**
aTag.setAttribute('target','_blank');


 //   Classes
Properties:
add() | remove() | toggle() | contains();


elem.className; //It will list all the classes an Combined String.(old way)
or
elem.classList; //It will list all the classes in an ( DOMTokenList ) object.(new way)

elem.classList.add('class-1','class-2',....);//We can assign  single/Multiple classes to the element.

elem.classList.remove('class-1','class-2'); //We can unassign single/multiple classes from the element. 

elemem.classList = 'class-1'; //This will replace all the existing classes assigned to the Element. 

elem.classList.toggle('class1');//to add the class if it doesn't exists or remove it from the list if it does already exist ( other classes are not affected. )

elem.contains('class1'); //returns a boolean based on if the class exists in the list or not


// Events

mouseEvents(document); //It will monitor all the events on docuemnt ( Just for test/practise/fun )

Methods:
addEventListener() | removeEventListener() | dispatchEvent()

addEventListener() and removeEventListener() // Works similarly. ( similar syntax )

//Phases of an Event.
  : Some times events are there on parent and there children. So using Phase events we can change the order ( To fire parent first or the child )

1. Capturing Phase ( parent to child )
  //:It the first phase, Moving from Parent(top) to the selected elem.
 2. At Target Phase  
  // It's the the selected element on which event is attached.
3. Bubbling Phase ( child to parent )
 // It's opposite of capturing, Once the handler is run, It will go back from selected element to the parent element

**
elem.addEventListener('click',()=>{},true)

- By default, It will run in Bubble phase(child first and then parent) .If we pass 3rd argument to 'true' in parentElem.addEventListener()? Then It will run the event in Capturing Phase( Parent will be working first ).


//Node-Name
  //How to know the target element.
if(event.target.nodeName == 'SPAN'){
   //The node name will be always in uppercase.
  takeAction();
}

//To load the HTML content before using the DOM.
document.addEventListener('DOMContentLoaded', function () {
    console.log('the DOM is ready to be interacted with!');
});



**
   {  scrollTo(x, y); }
**  

 /* 
 Lesson 2: Node and Express Environment
 */
  
  > npm list express
  // Return the list of express 'version'. or just check the 'package.json'
  
  
  //Installing packages
  > npm install express
  
  // Express to run server and routes
const express = require('express');

// Start up an instance of app
const app = express();
  

// method '.listen'
const port = 8080;
const server = app.listen(port, listening); //Listening is callback function. 
function listening(){
  console.log("Server runing on Port",port)
}



Methods:
get | post | put | delete

**
  const express = require('express');
  const app = express(); //Creating Instance

  app.get('/', function(req, res ){
    // '/' is the URL Path on the browser. '/' is the           home/root folder on the project.
    // 'request'( Client to server)
    // 'response' ( Server to client )
    res.send("<h1>Jaskaran Singh</h1>");
   })

  app.get('/karan', function(req, res ){
      res.send("<h1>Hi Karan Singh</h1>");
  })
   //It will work for url 'http://localhost:8080/karan'
  
// POST method route
app.post('/', function (req, res) {
  res.send('POST received')
})  

app.listen(8080, ()=>{
    console.log("Runnung....")
   });
**
  // TODO-ROUTES!
app.post('/add', callBack1 )

function callBack1(req, res){
    res.send('Post Received')
  //create a POST route that uses the url /add and sends the response POST received when used to make a request.
}
**
  const data = [];
  app.post('/flavor', addFlavor);

 function addFlavor (req, res) {
  data.push(req.body);
   // A way to store the data
};
**
  let data = []
 app.post('/animal', callBack2 );
 function callBack2(req, res){
  data.push( req.body )   
   //Add a POST route for adding a favorite animal via the path ’/animal’ to an array named data. You will need to create the array as well.
}
**
   /* ------------------------ ------------------*/ 
  
                    /* Async Js */
 : The keyword async before a function makes the function return a promise
  
**
 aync function test(){
   return "Some results...";
   // Since we are using 'aync', test() will be a            asynchrounous function.
 }   
> test(); //It will return a 'pending' Promise
> test().then((res)=>{},(rej)=>{})
**   
**
  const retrieveData = async (url='') =>{ 
  const request = await fetch(url);
  try {
  // Transform into JSON
  const allData = await request.json()
  }
  catch(error) {
    console.log("error", error);
    // appropriately handle the error
  }
}
**
  
//Server and Client side.
//Async Js.

**
const express = require('express');
const app = express();

//Movie Empty List.
let fakeData = {
    animal : 'lion', fact : 'lions are fun'
};
app.get('/fakeAnimalData', getFakeData );
function getFakeData(req, res){
 res.send(fakeData)
}
app.listen(8080, ()=>{
    console.log("Runnung....")
});
// 'localhost:8080/fakeAnimalData'  will return 'fakeData' Object

**
  /*    Chaining Promises    */
  
  
  
 
   /* ------------------------ ------------------*/ 
   /* ------------------------ ------------------*/ 
 
if (typeof variable !== 'undefined') {
    // the variable is defined
}
window.countNQueensSolutions = function(n) {
  var solutionCount = 0; //fixme


    // means we reached the end of the board.
    // but what if reached the end of the board, but don't have a solution? will that never happen?
  var board = new Board({'n': n});

  // recurse on columns
  var repeat = function(board,j){

    // means we reached the end of the board.
    // but what if reached the end of the board, but don't have a solution? will that never happen?

    if(j >= n){
      return true;
    }



   for(var i = 0; i < n; i++) // loop on rows
   {
      board.togglePiece(i, j);
     if(!board.hasRowConflictAt(i) && !board.hasMajorDiagonalConflictAt(board._getFirstRowColumnIndexForMajorDiagonalOn(i,j))
      && !board.hasMinorDiagonalConflictAt(board._getFirstRowColumnIndexForMinorDiagonalOn(i,j)))
     {
       if(repeat(board, j + 1) === true)
       {
        solutionCount++;
       }

     }
     board.togglePiece(i, j);
   };



    return false;
  }

  repeat(board,0);

  console.log('Number of solutions for ' + n + ' queens:', solutionCount);
  return solutionCount;
};
window.findNQueensSolution = function(n) {
  var solution; //fixme
  var done = false;

  // means we reached the end of the board.
  // but what if reached the end of the board, but don't have a solution? will that never happen?
  var board = new Board({'n': n});

  if(n===0){
      return [];
  }
  // recurse on columns
  var repeat = function(board,j){

    // means we reached the end of the board.
    // but what if reached the end of the board, but don't have a solution? will that never happen?


    // we only increment j when we place a rook/queen. so when j reaches n, it means we
    // placed all n rooks/queens, since we reached the end of the board.
    if(j >= n){
      return true;
    }

   for(var i = 0; i < n; i++) // loop on rows
   {
      board.togglePiece(i, j);
     if(!board.hasRowConflictAt(i) && !board.hasMajorDiagonalConflictAt(board._getFirstRowColumnIndexForMajorDiagonalOn(i,j))
      && !board.hasMinorDiagonalConflictAt(board._getFirstRowColumnIndexForMinorDiagonalOn(i,j)))
     {
       if(repeat(board, j + 1) === true)
       {
          if(solution === undefined){
            solution = board;
            done = true;
          }
          return true;
       }

     }
     board.togglePiece(i, j);
     if(done)
      return true;
   };

    return false;
  }

  repeat(board, 0);

  if(solution === undefined){
    solution = board.rows();
  }
  else{
    solution = solution.rows();
  }


  console.log('Single solution for ' + n + ' queens:', JSON.stringify(solution));
  return solution;
};
 var solutionCount = 0; //fixme
  var board = new Board({'n': n});


  // recurse on columns
  var repeat = function(board,j){

    // means we reached the end of the board.
    // but what if reached the end of the board, but don't have a solution? will that never happen?
    if(j >= n){
      return true;
    }

   for(var i = 0; i < n; i++) // loop on rows
   {
      board.togglePiece(i, j);

      // we only check for row conflict, since we never place two items(rooks/queens) in the same column,
      // when we place a piece, we go to the next column straight away.
     if(!board.hasRowConflictAt(i))
     {
       if(repeat(board, j + 1) === true)
       {

        solutionCount++;
        //return true;
       }

     }
     board.togglePiece(i, j);
   }



    return false;
  }

  repeat(board,0);
import clock from "clock";
import document from "document";

// Tick every second
clock.granularity = "seconds";

let hourHand = document.getElementById("hours");
let minHand = document.getElementById("mins");
let secHand = document.getElementById("secs");

// Returns an angle (0-360) for the current hour in the day, including minutes
function hoursToAngle(hours, minutes) {
  let hourAngle = (360 / 12) * hours;
  let minAngle = (360 / 12 / 60) * minutes;
  return hourAngle + minAngle;
}

// Returns an angle (0-360) for minutes
function minutesToAngle(minutes) {
  return (360 / 60) * minutes;
}

// Returns an angle (0-360) for seconds
function secondsToAngle(seconds) {
  return (360 / 60) * seconds;
}

// Rotate the hands every tick
function updateClock() {
  let today = new Date();
  let hours = today.getHours() % 12;
  let mins = today.getMinutes();
  let secs = today.getSeconds();

  hourHand.groupTransform.rotate.angle = hoursToAngle(hours, mins);
  minHand.groupTransform.rotate.angle = minutesToAngle(mins);
  secHand.groupTransform.rotate.angle = secondsToAngle(secs);
}

// Update the clock every tick event
clock.addEventListener("tick", updateClock);
function createEqualLengthArray(array1, array2) {
    while(array1.length < array2.length) {
        console.log(array1.length, array2.length)
        let randIdx = Math.floor(Math.random() * array2.length);
        let randElement = array2.splice(randIdx, 1)[0];
        array1.push(randElement)
    }
    return {hand1: array1, hand2: array2}
}
const pokemonCard = [
			{ id: 4, name: "Charmander", type: "fire", base_experience: 62 },
			{ id: 7, name: "Squirtle", type: "water", base_experience: 63 },
			{ id: 11, name: "Metapod", type: "bug", base_experience: 72 },
			{ id: 12, name: "Butterfree", type: "flying", base_experience: 178 },
			{ id: 25, name: "Pikachu", type: "electric", base_experience: 112 },
			{ id: 39, name: "Jigglypuff", type: "normal", base_experience: 95 },
			{ id: 94, name: "Gengar", type: "poison", base_experience: 225 },
			{ id: 133, name: "Eevee", type: "normal", base_experience: 65 },
		],

let hand1 = [];
let hand2 = [...this.props.pokemonCards]
const hands = createEqualLengthArray(hand1, hand2)
const padToThreeDigits = (num) => (num <= 999 ? `00${num}`.slice(-3) : num); 
$(document).ready(function() {
  window.dancers = [];

  $('.addDancerButton').on('click', function(event) {
    /* This function sets up the click handlers for the create-dancer
     * buttons on dancefloor.html. You should only need to make one small change to it.
     * As long as the "data-dancer-maker-function-name" attribute of a
     * class="addDancerButton" DOM node matches one of the names of the
     * maker functions available in the global scope, clicking that node
     * will call the function to make the dancer.
     */

    /* dancerMakerFunctionName is a string which must match
     * one of the dancer maker functions available in global scope.
     * A new object of the given type will be created and added
     * to the stage.
     */
    var dancerMakerFunctionName = $(this).data('dancer-maker-function-name');

    // get the maker function for the kind of dancer we're supposed to make
    var dancerMakerFunction = window[dancerMakerFunctionName];

    // make a dancer with a random position

    var dancer = dancerMakerFunction(
      $("body").height() * Math.random(),
      $("body").width() * Math.random(),
      Math.random() * 1000
    );
    $('body').append(dancer.$node);
  });
});
var makeBlinkyDancer = function(top, left, timeBetweenSteps) {
  var blinkyDancer = makeDancer(top, left, timeBetweenSteps);

  // we plan to overwrite the step function below, but we still want the superclass step behavior to work,
  // so we must keep a copy of the old version of this function

  var oldStep = blinkyDancer.step;

  blinkyDancer.step = function() {
    // call the old version of step at the beginning of any call to this new version of step
    oldStep();
    // toggle() is a jQuery method to show/hide the <span> tag.
    // See http://api.jquery.com/category/effects/ for this and
    // other effects you can use on a jQuery-wrapped html tag.
    blinkyDancer.$node.toggle();
  };

  return blinkyDancer;
};
// Creates and returns a new dancer object that can step
var makeDancer = function(top, left, timeBetweenSteps) {

  var dancer = {};

  // use jQuery to create an HTML <span> tag
  dancer.$node = $('<span class="dancer"></span>');

  dancer.step = function() {
    // the basic dancer doesn't do anything interesting at all on each step,
    // it just schedules the next step
    setTimeout(dancer.step, timeBetweenSteps);
  };
  dancer.step();

  dancer.setPosition = function(top, left) {
    // Use css top and left properties to position our <span> tag
    // where it belongs on the page. See http://api.jquery.com/css/
    //
    var styleSettings = {
      top: top,
      left: left
    };
    dancer.$node.css(styleSettings);
  };

  // now that we have defined the dancer object, we can start setting up important parts of it by calling the methods we wrote
  // this one sets the position to some random default point within the body
  dancer.setPosition(top, left);

  return dancer;
};
function randomEl(array) {
	const idx = Math.floor(Math.random() * array.length);
	return array[idx];
}
/* Answer to: "[nodemon] app crashed - waiting for file changes before starting..." */

/*
  This is most likely happening because of all the running server
  process in the background. So just stop them from the terminal.
  
  All you have to do is kill them all by running the command below
  in the terminal then restart nodemon.
*/

  pkill -f node
const _ = {
  clamp(number, lower, upper) {
    const lowerClampedValue = Math.max(number, lower);
    const clampedValue = Math.min(lowerClampedValue, upper);
    return clampedValue;
  },
  inRange(number, start, end) {
    if (end === undefined) {
      end = start;
      start = 0;
    }
    if (start > end) {
      [start, end] = [end, start];
    }
    const isInRange = start <= number && number < end ? true : false;
    return isInRange;
  },
  words(string) {
    return string.split(' ')
  },
  pad(string, length) {
    if (length <= string.length) {
      return string;
    }
    startPad = Math.floor((length - string.length)/2);
    endPad = length - startPad - string.length;
    const paddedString = ' '.repeat(startPad) + string + ' '.repeat(endPad);
    return paddedString;
  },
  has(object, key) {
    const hasValue = object[key] !== undefined ? true : false;
    return hasValue;
  }
};
function removeAllItems(arr, value) {
  var i = 0;
  while (i < arr.length) {
    if (arr[i] === value) {
      arr.splice(i, 1);
    } else {
      ++i;
    }
  }
  return arr;
}

console.log(removeAllItems([2,5,9,1,5,8,5], 5))
function remove(array, el) {
	const index = array.indexOf(el);
	if (index > -1) {
		const foundEl = array.splice(index, 1);
        return foundEl;
	}
    return undefined;
}
console.log(remove([2,5,9,1,5,8,5], 5))
app.set('port', port);
 /**
 * Create HTTP server.
 */

var server = http.createServer(app);

 /**
 * Listen on provided port, on all network interfaces.
 */

server.listen(port);
server.on('error', onError);
server.on('listening', onListening);

 /**
 * Normalize a port into a number, string, or false.
 */

function normalizePort(val) {
    var port = parseInt(val, 10);

  if (isNaN(port)) {
    // named pipe
    return val;
  }

  if (port >= 0) {
    // port number
    return port;
   }

   return false;
}

/**
* Event listener for HTTP server "error" event.
*/

function onError(error) {
  if (error.syscall !== 'listen') {
    throw error;
  }

  var bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // handle specific listen errors with friendly messages
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
      break;
    case 'EADDRINUSE':
      console.error(bind + ' is already in use');
      process.exit(1);
      break;
    default:
      throw error;
  }
}

/**
 * Event listener for HTTP server "listening" event.
 */

function onListening() {
  var addr = server.address();
  var bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
}

Like I said in the beginning, I'm a complete beginner with command-line/github, but I'm already in love with it. I try to practice it every night after I finish my homework, and am getting really frustrated about getting stuck because I haven't been able to move forward for four days now. Also, I'm running this on node.js and the OS is Windows 8. Anything helps!  Let me know if you want me to post any of the other code; I omitted so as to not add more than necessary.

 "../app (app.js file) JUST ADDED"***************************
../app file:
    [ App.js   ]
 var express = require('express');
 var path = require('path');
 var favicon = require('serve-favicon');
 var logger = require('morgan');
 var cookieParser = require('cookie-parser');
 var bodyParser = require('body-parser'); 

var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();

///  catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});
var app = express();
// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
        app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}


var app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json({estended: true}));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieParser({extended:true}));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);





//  production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});
// Write function below
const range = (start, end, length = end - start + 1) =>
  Array.from({ length }, (_, i) => start + i)

const factorial = number => {
  const numArray = range(1, number);
  return numArray.reduce((total, value) => total*value)
};
const range = (start, end, length = end - start + 1) =>
  Array.from({ length }, (_, i) => start + i)
axios.post('http://10.0.1.14:8001/api/logout',request_data, {
          headers: {
              'Content-Type': 'application/json',
              'Authorization': 'Bearer '+token
          },      
      })      
      .then((response) => {
        console.log('response',response.data)

      })
      .catch((error) => {
        alert('error',error.response)
        dispatch(userUpdateProfileFail())

      })

  // console.log('----cheers---------',data)
dispatch(userUpdateProfileSuccess(data))
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']

let countedNames = names.reduce(function (allNames, name) {
  if (name in allNames) {
    allNames[name]++
  }
  else {
    allNames[name] = 1
  }
  return allNames
}, {})
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
Example: Shuffle Deck of Cards

// program to shuffle the deck of cards

// declare card elements
const suits = ["Spades", "Diamonds", "Club", "Heart"];
const values = [
  "Ace",
  "2",
  "3",
  "4",
  "5",
  "6",
  "7",
  "8",
  "9",
  "10",
  "Jack",
  "Queen",
  "King",
];

// empty array to contain cards
let deck = [];

// create a deck of cards
for (let i = 0; i < suits.length; i++) {
    for (let x = 0; x < values.length; x++) {
        let card = { Value: values[x], Suit: suits[i] };
        deck.push(card);
    }
}

// shuffle the cards
for (let i = deck.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * i);
    let temp = deck[i];
    deck[i] = deck[j];
    deck[j] = temp;
}

console.log('The first five cards are:');

// display 5 results
for (let i = 0; i < 5; i++) {
    console.log(`${deck[i].Value} of ${deck[i].Suit}`)
}

//output
The first five cards are:
4 of Club
5 of Diamonds
Jack of Diamonds
2 of Club
4 of Spades
function shuffle(array) {
  const curIdx = array.length;

  // While there remain elements to shuffle...
  while (0 !== cur_idx) {
    // Pick a remaining element...
    const randIdx = Math.floor(Math.random() * curIdx);
    curIdx -= 1;

    // And swap it with the current element.
    const originalIdx = array[curIdx];
    array[curIdx] = array[randIdx];
    array[randIdx] = originalIdx;
  }
  return array;
}

// Usage of shuffle
const arr = [1, 2, 3, 4, 5, 6];
arr = shuffle(arr);
console.log(arr);

// shorter
function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        var j = Math.floor(Math.random() * (i + 1));
        var originalIdx = array[i];
        array[i] = array[j];
        array[j] = originalIdx;
    }
}

//es6
function shuffle_array(array) {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}
const shuffleArray = array => {
  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    const temp = array[i];
    array[i] = array[j];
    array[j] = temp;
  }
}
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const shuffledArray = array.sort((a, b) => 0.5 - Math.random());

// using Array map and Math.random
const shuffledArr = array => array.map(a => ({ sort: Math.random(), value: a })).sort((a, b) => a.sort - b.sort).map(a => a.value);

Object.keys(empty).length === 0 && empty.constructor === Object
var getStart = function(index, text){
  while(index > 0 && text[index] !== " "){
    index--;
  }
  return index;
}

var getEnd = function(index, text){
  while(index < text.length && text[index] !== " "){
    index++;
  }
  return index;
}

var getSelectedWord = function(firstIndex, lastIndex, text){
  return text.substring(getStart(firstIndex, text), getEnd(lastIndex, text)).split(' ');
}
const date = '2021-06-14T08:29:40.886+00:00'
const formattedDate = date.substring(0,date.lastIndexOf('T'))
console.log(formattedDate)

// prints: "2021-06-14"
let cars = [
  {
    "color": "purple",
    "type": "minivan",
    "registration": new Date('2017-01-03'),
    "capacity": 7
  },
  {
    "color": "red",
    "type": "station wagon",
    "registration": new Date('2018-03-03'),
    "capacity": 5
  },
  {
    ...
  },
  ...
]

// add to the beginning 
const car = {
  "color": "red",
  "type": "cabrio",
  "registration": new Date('2016-05-02'),
  "capacity": 2
}
cars.unshift(car);

// add to the end
const car = {
 "color": "red",
 "type": "cabrio",
 "registration": new Date('2016-05-02'),
 "capacity": 2
}
cars.push(car);

// add somewhere in the middle 
Array.splice(
  {index where to start},
  {how many items to remove},
  {items to add}
);

// place the car after the 4th element in the array
let car = {
  "color": "red",
  "type": "cabrio",
  "registration": new Date('2016-05-02'),
  "capacity": 2
}
cars.splice(4, 0, car);
axios.all([
 axios.get('https://api.github.com/users/abc');
 axios.get('https://api.github.com/users/abc/repos')
])
.then(axios.spread(function (userResponse, reposResponse) {
  console.log('User', userResponse.data);
  console.log('Repositories', reposResponse.data);
}));
$(document).on('click', 'a', function(e) {
	e.preventDefault();

	const blank = $(this).attr('target');
	const fromDomain = location.origin;
	const from = fromDomain + location.pathname + location.search;
	const to = $(this).prop('href');
	const check = to.replace(from,'');

	if(blank == '_blank' || to.indexOf(fromDomain) == -1) {
		hrefBlank(to);
	} else if( check.indexOf('#') == 0 || check == '') {
		var target = 0;
		if (check != '') {
			target = $(check).offset().top;
		}
		hrefInPage(target);
	} else {
		hrefPageToPage(to);
	}
});
function hrefBlank(target) {
	window.open(target, '_blank');
}
function hrefPageToPage(target) {
	// ローディング演出
	$("演出に使ったDOM要素").on('animationend webkitAnimationEnd',function(){
	  window.location = target;
	});
}
function hrefInPage(target) {
	$('body,html').stop().animate({scrollTop:target}, 800);
}
import axios from "axios";
import { redirect } from "helpers/historyDom";

import store from 'app/store';
import  {logout} from 'app/actions/authAction';
// const { default: axios } = require("axios");

/* creating custom axios  */
const axiosIntercept = axios.create({
    //baseURL : process.env.REACT_APP_API_URL , 
    //timeout : 200 , 
    headers : {
        'Content-Type': 'application/json',
        'Authorization' : `Token ${localStorage.getItem('god_token')}` , 
    },
});

/* callback to clear storage and local state */
const clearStorage = async (_callback) => {
    // await localStorage.clear()
    await store.dispatch(logout())
    _callback();
}
 
const requestHandler = (request) => {
    // console.log(request)
    request.headers.Authorization = `Token ${localStorage.getItem('god_token')}` ;
    return request ;
};
 
const responseHandler  = (response) => {
    if(response.status === 401){
        // console.log(response)
        // console.log("got yaaaaaaaaaaaaaaaaaa response")
        clearStorage(()=>{
            redirect('/Connexion')
        })
    }
    return response

};


const errorHandler = (error) => {
    if(error.response.status === 401){
        clearStorage(()=>{
            redirect('/Connexion')
        })
    };
    return Promise.reject(error)
    // return error
};


axiosIntercept.interceptors.request.use(
    (request) => requestHandler(request) ,
    (error) => errorHandler(error) ,
);


axiosIntercept.interceptors.response.use(
    (request) => responseHandler(request) ,
    (error) => errorHandler(error) ,
);

export default  axiosIntercept ;
// ...

const BASE_URL = 'https://jsonplaceholder.typicode.com';

const getTodoItems = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/todos?_limit=5`);

    const todoItems = response.data;

    console.log(`GET: Here's the list of todos`, todoItems);

    return todoItems;
  } catch (errors) {
    console.error(errors);
  }
};
function getRandomValue(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}
  function waitForElementToDisplay(selector, callback, checkFrequencyInMs = 100, timeoutInMs = 10000) {
    const startTimeInMs = Date.now();

    if(!callback){
      callback = () => document.querySelector(selector).style.display = 'none';
    }

    (function loopSearch() {
      if (document.querySelector(selector) != null) {
        callback();
        return;
      }

      setTimeout(function () {
        if (timeoutInMs && Date.now() - startTimeInMs > timeoutInMs){
          return;
        }
        loopSearch();
      }, checkFrequencyInMs);
    })();
  }
hbs.registerHelper(`capitalizeFirstLetter`, function (input) {
    const stringifiedInput = `${input}`;
    const capitalizedInput = stringifiedInput.charAt(0).toUpperCase() + stringifiedInput.slice(1);
    return capitalizedInput;
});
// capitalize first letter(s) of words in a string
hbs.registerHelper(`capitalizeFirstLetters`, function (input) {
    const stringifiedInput = `${input}`;
    console.log(`input`, stringifiedInput);
    const inputArray = stringifiedInput.split(` `);
    if (stringifiedInput.indexOf(` `) >= 0) {
        const capitalizedWords = inputArray.map((word) => word[0].toUpperCase() + word.slice(1)).join(` `);
        return capitalizedWords;
    }
    const capitalizedWord = stringifiedInput.charAt(0).toUpperCase() + stringifiedInput.slice(1);
    return capitalizedWord;
});
function hasWhiteSpace(s) {
  return s.indexOf(' ') >= 0;
}

//or

function hasWhiteSpace(s) {
  return /\s/g.test(s);
}
import { LightningElement, wire } from 'lwc';
import { NavigationMixin } from 'lightning/navigation';

 navigateToContact() {
        this[NavigationMixin.Navigate]({
            type: 'standard__recordPage',
            attributes: {
                recordId: this.contact.data.Id,
                objectApiName: 'Contact',
                actionName: 'view' //to edit change value to edit
            }
        });
    }
  
import { LightningElement } from 'lwc';
import Id from '@salesforce/user/Id';

export default class MiscGetUserId extends LightningElement {
    userId = Id;
}
const visibleCheckboxes = document.querySelectorAll('.checky')

visibleCheckboxes.forEach(checkbox => checkbox.addEventListener('change', () => {
let hiddenCheckbox = checkbox.nextElementSibling;
checkbox.checked ? hiddenCheckbox.value = 'Yes' : hiddenCheckbox.value = 'No';
}))

//html
<label>
  <input type="checkbox" class="checky" />
  <input type="text" value="no" /> Cats
</label>
<label>
  <input type="checkbox" class="checky" />
  <input type="text" value="no" /> Dogs
</label>
<label>
  <input type="checkbox" class="checky" />
  <input type="text" value="no" /> Fish
</label>
function valuesToArray(obj) {
    var result = [];
    for (var key in obj) {
       if (obj.hasOwnProperty(key)) {
           result.push(obj[key]);
       }
    }
    return result;
}
var hms = '02:04:33';   // your input string
var a = hms.split(':'); // split it at the colons

// minutes are worth 60 seconds. Hours are worth 60 minutes.
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]); 

console.log(seconds);
//solution 1
$("option:selected").removeAttr("selected");

//solution 2
$("option:selected").prop("selected", false); 
// TIP: Try re-using reduce() here.
    var test = true;
    if (iterator === undefined) {
      for (var key in collection) {
        if (! collection[key] && test) {
          return false;
        }
      }
    } else {
      for (var key in collection) {
        if (! iterator(collection[key]) ) {
          return false;
        }
      }
    }
    return test;
const numbers = [1,2,3,4,5,6];
function isEven(number){
  return number % 2 === 0;
}
const evenNumbers = numbers.filter(isEven);
var getElementsByClassName = function(className) {
  var listArray = [];

  // START INNER FUNCTION
  var innerFn = function(node) {
    if (node.nodeType === 1) {
      if (node.classList.value.includes(className)) {
        listArray.push(node);
      }
    }
    node.childNodes.forEach( function(element) {
      return innerFn(element);
    });
  };
  // END INNER FUNCTION
  
  innerFn(document.body);
  return listArray;
};
//Recursive implementation of jSON.stringify;
var stringifyJSON = function(obj) {

    var arrOfKeyVals = [],
        arrVals = [],
        objKeys = [];

    /*********CHECK FOR PRIMITIVE TYPES**********/
    if (typeof obj === 'number' || typeof obj === 'boolean' || obj === null)
        return '' + obj;
    else if (typeof obj === 'string')
        return '"' + obj + '"';

    /*********CHECK FOR ARRAY**********/
    else if (Array.isArray(obj)) {
        //check for empty array
        if (obj[0] === undefined)
            return '[]';
        else {
            obj.forEach(function(el) {
                arrVals.push(stringifyJSON(el));
            });
            return '[' + arrVals + ']';
        }
    }
    /*********CHECK FOR OBJECT**********/
    else if (obj instanceof Object) {
        //get object keys
        objKeys = Object.keys(obj);
        //set key output;
        objKeys.forEach(function(key) {
            var keyOut = '"' + key + '":';
            var keyValOut = obj[key];
            //skip functions and undefined properties
            if (keyValOut instanceof Function || typeof keyValOut === undefined)
                arrOfKeyVals.push('');
            else if (typeof keyValOut === 'string')
                arrOfKeyVals.push(keyOut + '"' + keyValOut + '"');
            else if (typeof keyValOut === 'boolean' || typeof keValOut === 'number' || keyValOut === null)
                arrOfKeyVals.push(keyOut + keyValOut);
            //check for nested objects, call recursively until no more objects
            else if (keyValOut instanceof Object) {
                arrOfKeyVals.push(keyOut + stringifyJSON(keyValOut));
            }
        });
        return '{' + arrOfKeyVals + '}';
    }
};
function currying(fn, ...args) {
    return (..._arg) => {
        return fn(...args, ..._arg);
    }
}
database.ref('message').child('key').update({text: 'This is my updated text!'})

database.ref('message').child('key').set({text: 'This is my updated text!'})
database.ref('object').on('child_removed', snapshot => console.log(snapshot.val()));
database.ref('object').on('child_added', snapshot => console.log(snapshot.val()));
database.ref('object').remove()

database.ref('object').child('child').remove()
database.ref('parent').child('child-1').child('child2').set('value');

alternative:
database.ref('parent/child-1/child-2').set('value');
database.ref('object').push({nickname: 'carl', age: 20})
database.ref('object').on('value', snapshot => console.log(snapshot.val()))
var getElementsByClassName = function(className) {
  const myNodes = [];

  function innerFn(node) {
    if (node.classList && node.classList.value.indexOf(className) > -1) {
      myNodes.push(node)
    }
    node.childNodes.forEach((child) => innerFn(child))
  }
  innerFn(document.body)

  return myNodes;
};
var getElementsByClassName = function (cName) {
  var obj = {};
  var count = 0;
  var allNodes = document.body.childNodes;
  // look inside body root for any element has className
  // if the className found, go over all child element
  for (var i = 0; i < allNodes.length; i++) {
    if (allNodes[i].nodeType === 1) {
      if (allNodes[i].classList == cName) {
        obj[count] = allNodes[i];
        count++;
        //return obj[count];
      }
    }
  }
  console.log(obj);
};

getElementsByClassName("example color");
var countValuesInObj = function(obj, value) {
  var count = 0;
  for ( const property in obj ) {

    if( typeof obj[property] === 'object') {
      count = count + countValuesInObj(obj[property], value);
    } 

    if(obj[property] === value ) {
      return 1; // count = count + 1; // count++;
    }
  }
  return count;
};

var obj = {
'e':{'x':'y'},
't':{
  'r':{'e':'r'},
  'p':{'y':'r'}
  },
'y':'e'
};
console.log(countValuesInObj(obj, 'r')) // 2
console.log(countValuesInObj(obj, 'e')) // 1
function checkSign(num){
    
return num > 0 ? "Postive": num<0 ? "Negative": "zero";
}

console.log(checkSign(0));
function randomRange(myMin, myMax) {
    return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin;
}

var myRandom = randomRange(5, 15);

console.log(myRandom);
console.log(Math.floor(Math.random()*10));
var i = 10;
var myArr = [];

do{
    myArr.push(i);
    i++
}while (i<3)

console.log("i = " + i);
console.log("myArrmy = " + myArr);
// This function is used to detect the actual image type, 
function getMimeType(file, fallback = null) {
	const byteArray = (new Uint8Array(file)).subarray(0, 4);
    let header = '';
    for (let i = 0; i < byteArray.length; i++) {
       header += byteArray[i].toString(16);
    }
	switch (header) {
        case "89504e47":
            return "image/png";
        case "47494638":
            return "image/gif";
        case "ffd8ffe0":
        case "ffd8ffe1":
        case "ffd8ffe2":
        case "ffd8ffe3":
        case "ffd8ffe8":
            return "image/jpeg";
        default:
            return fallback;
    }
}
/*
Basic
Numbers
Functions
Array
Objects

Landscape of JS
*/


//DOM


/* AJAX  */
- Developed by MS.
- Technical name is "XMLHttpRequest ( XHR ) Object".

   How to set up:
   1. Create XHR object.
   2. Create call back ( what to do with API) 
   3. OPEN
   4. SEND
   
    : Limitations of AJAX:
 - Ajax can only communicate within same website/server. It    can not communicate with another website/server.      
 - Can not change the port( parent domain has to be same        (will not work with different server )) Number and nor       change the Protocol ( https-http)
   

 How to resolve this issue:
 1. Web proxy :  We can request from client ->            server1(original) to server2. After that server2 will send    back response to server1 ( original ) -> Client.

 2. JSONP: JSON with padding.
 ( way CDN's work)
 3. CORS - Cross Origin resource sharing. ( This allows requests from different domains )


xhr.readState
  1-4 ( 4 is good )

xhr.status Codes
 : 200 ( OK ) 
 : 404 (file not found)
 : 401 ( not auth)
 : 500 (Server Error/Problem)

Syntax:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
  if(xhr.readyState === 4 && xhr.status === 200 ){ 
         
     }
};
xhr.open('GET', 'sidebar.html');
xhr.send();

                   /* JSON */

JSON: Javascript object Notation.
 - Keys and values have to use double quotations ( single      will not work)
 

          /*      Asynchronous Progamming   */


##Cool Example ( Playing with two API's. )
//Make AJAX request
function getJSON(url, callBack) {
    let xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onreadystatechange = function () {
        if (this.readyState == 4) {
            let data = (JSON.parse(this.responseText));
            callBack(data);
        }
    }
    xhr.send();
}

//Loading Data
    getJSON(astroUrl, (jsonData) => {
        jsonData.people.map(person => {
            getJSON(wikiUrl + person.name, generateHTML )
        });
    })




                        /*       Promises                 */

//Promise Contsructor takes 1 Parameter with two arguments.
let breakFast = new Promise(( res , rej )=>{
   setTimeout(()=>{
     res("it's resolved")
     rej("It's Rejected");
   },2000);
})

> breakFast.then( val => console.log(val) ); // It will resolve it

> breakFast
     .then()
     .catch( val => console.log(Error,val) )
// Catch is used to Handle the rejections.


 > Promise.all( val )
// It will provide the values from multiple promises.It is used when program needs to wait for the more then 1 promise to resolve.
// IF any values is failed? It will not show any results. ( all the values have to be resolved. )

                           
                        /*  Fetch     */


    fetch('apiLink...')
       .then( respo => respo.json() )
       .then( data => consoe.log(data) )
       .catch()
       .finally( ()=> )
                
                
                
                 /*         Await         */
                
async function gettingData(data){
     let response = await fetch(data);
     let dataRes = await response.json();
     return dataRes;
}

gettingData(astroUrl).then( data => console.log(data));

> Await:
   - Async function always return a promise.
   - It pauses the execution of an async function and waits for the resolution of a promise
   - Is Valid only inside function marked 'async'.
   
   
   
**
 async function gettingData(astroUrl){
     
     let response = await fetch(astroUrl).catch( e => {
          console.log( e ,"JEh Panga Ess API ch")
     })
     let dataRes = await response.json()
      
     let output1 = dataRes.people.map ( async element => {

          let craft = (element.craft)
           let response = await fetch( wikiUrl + element.name);
           let dataRes = await response.json();

           return {...dataRes, craft}
     });
     return Promise.all(output1)
 } 
**     
   
     
         /*        Fetch API              */
     
     //Posting the Data
function postData(event) {
  event.preventDefault();
  const name = document.querySelector('#name').value;
  const comment = document.querySelector('#comment').value;

  fetch('http://jsonplaceholder.typicode.com/comments', {
    method: 'POST',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify({ name, comment })
  })

    .then(data => data.json())
    .then(data => console.log(data))
}
   


//Or
let config = {
    method: 'POST',
    headers: {
      'Content-type': 'application/json'
    },
    body: JSON.stringify({ name, comment })
  };
fetch('url', config)
  .then(..//What to do with Code..)


               /*        OOPS       */
               /*        Clasees    */
      // Convert value to String
      toString(val);
      String(val);
----------------------------
//GET
let obj = {
 get  power(){
    return "Power"
  }
}
console.log(obj.power)
-----------------------------
// Same thing without using "GET", ( make the Power function as IIFA )
let obj = {
   power: (function(){
     return "Power...";
   }())
}
console.log(obj.power)
------------------------

//SET ( set will always have 1 parameter )
class Student {
    set someName(name){
      this._name = name; 
      // can not use same as parameter, So convection is to use                    Underscore and store it. '_name' ( called - **Backing Property** )
    }
     get valueFromSomeName(){
       //This is used to 'get' value from '_name'(stored variable ) from            above 'set' method, We can also the retrieve value without using the        'get' ( by calling like regular method ( .valueFromSomeName() ) )
       return this._name;
   }
}

let stuJaskaran  = new Student();

stuJaskaran.someName = "Jaskaran";

console.log("Logging 1 : ",stuJaskaran.valueFromSomeName);



//We can access 1 method from a different method.
class Student {
      set major(subject){
        if(this.level == 'Junior' || this.level == 'Senior'){ //We are      getting value from method "level"
           this._major = subject; 
        }else {
           this._major = 'None' ;
        }

      }
    get level() {
        if (this.credits > 90 ) {
            return 'Senior';
        } else if (this.credits > 60) {
            return 'Junior';
        } else if (this.credits > 30) {
            return 'Sophomore';
        } else {
            return 'Freshman';
        }
    }  
}


-------------------------------------------
  
 //We can use the return from one Oject and add to another new class property.
   class Student{
    //Blaah Blaah
     set someVar( name ){
       this._name = name;
     }
     
   }

   class Prof{
     //Blaah Blaah
   }
let Jaskaran = new Student();
Jaskaran.someVar = new Prof()
   //Check S20 gallery for more details. ( pic taken on 12th June 2021)
  ------------------------------------------------------
import React, { Component, PropTypes } from 'react';
import {
  Linking,
  Text,
  StyleSheet
} from 'react-native';

export default class HyperLink extends Component {

  constructor(){
      super();
      this._goToURL = this._goToURL.bind(this);
  }

  static propTypes = {
    url: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
  }

  render() {

    const { title} = this.props;

    return(
      <Text style={styles.title} onPress={this._goToURL}>
        >  {title}
      </Text>
    );
  }

  _goToURL() {
    const { url } = this.props;
    Linking.canOpenURL(url).then(supported => {
      if (supported) {
        Linking.openURL(this.props.url);
      } else {
        console.log('Don\'t know how to open URI: ' + this.props.url);
      }
    });
  }
}

const styles = StyleSheet.create({
  title: {
    color: '#acacac',
    fontWeight: 'bold'
  }
});
var test = true;
    if (iterator === undefined) {
      for (var key in collection) {
        if (! collection[key]) {
          return false;
        }
      }
    } else {
      for (var key in collection) {
        if (! iterator(collection[key]) ) {
          return false;
        }
      }
    }
    return test;
_.delay = function(func, wait) {
    var result;
    var params = [...arguments];
    setTimeout(function() {
      result = func.apply(this, params.slice(2));
    }, wait);
    return result;
  };
function isArrayInArray(arr, item){
  var item_as_string = JSON.stringify(item);

  var contains = arr.some(function(ele){
    return JSON.stringify(ele) === item_as_string;
  });
  return contains;
}

var myArray = [
  [1, 0],
  [1, 1],
  [1, 3],
  [2, 4]
]
var item = [1, 0]

console.log(isArrayInArray(myArray, item));  // Print true if found
_.memoize = function(func) {
    var alreadyCalled = false;
    var result;
    var arr = [];
    return function() {
      //console.log(arguments[0]);
      if (!alreadyCalled) {
        if ( !(arr.join(' ')).includes(arguments[0])) {
          arr.push(arguments[0]);
          result = func.apply(this, arguments);
          alreadyCalled = true;
        } else {
          //arr.push(arguments[0]);
          alreadyCalled = true;
        }
        return result;
      }
      return result;
    };

  };
function sum(a, b) {
  let result = a + b; // DevTools pauses on this line.
  return result;
}
debug(sum); // Pass the function object, not a string.
sum();
db.doc.find({_id : { $gt : ObjectId(Math.floor(new Date(new Date().getFullYear()+'/'+(new Date().getMonth()+1)+'/'+new Date().getDate())/1000).toString(16)+"0000000000000000") }})
_.uniq = function(array, isSorted, iterator) {
    var uniqueArray = [];
    var storeObj = {};
    var iteratorArray = [];

    _.each(array, function(item, index) {
      if (iterator) {
        iteratorArray.push(iterator(item));
      } else {
        iteratorArray.push(_.identity(item));
      }
    });

    _.each(iteratorArray, function(item, index) {
      if (storeObj[item] === undefined) {
        storeObj[item] = array[index];
      }
    });

    for(var key in storeObj) {
      uniqueArray.push(storeObj[key]);
    }

    return uniqueArray;
  };
_.uniq = function(array, isSorted, iterator) {
    var newArr = [];
    if(iterator === undefined) {
      for(var i = 0; i<array.length; i++) {
        if(! newArr.join('').includes(array[i])) {
          newArr.push(array[i]);
        }
      }
    } else {
      for(var i = 0; i<array.length; i++) {
      var test = iterator(array[i],i,array);
       if (test && array[i] == array[0]) {
          newArr.push(array[0], array[1]);
          return newArr;
       }
      }
      if(!test) newArr.push(array[0]);
    }
    return newArr;
  };


//
iterator(newArr[j],j,newArr) ? arr2.push(newArr[j]) : '';
var firebaseConfig = {
apiKey: "AIzaSyBrZb4v8u3ht6VG6yzAC3fc0UZ6HF5Ypk",
authDomain: "upload-c77ba.firebaseapp.com",
projectId: "upload-c77ba",
storageBucket: "upload-c77ba.appspot.com",
messagingSenderId: "712086498758",
appId: "1:712086498758:web:ae2f17977cc95d3b8cd6c7",
measurementId: "G-9JYB3GET1V"
};
// Initialize Firebase
firebase.initializeApp(firebaseConfig);

let profileView = document.getElementById('profile-view');
let signupView = document.getElementById('signup-view');
let email = document.getElementById('email');
let prord = document.getElementById('pword');
let img = document.getElementById('img');

let file = {};

function chooseFile(e) {
file = e.target.files[0];
}

function signUpButtonPressed(e) {
firebase.auth().createUserWithEmailAndPassword(email.value, pword.value)
.then(auth => {
firebase.storage().ref('users/' + auth.user.uid + '/profile.jpg').put(file).then(() => {
console.log('success!');
}).catch(err => {
console.log(err);
})
}).catch(err => {
console.log(err.message);
})
}

firebase.auth().onAuthStateChanged(user => {
if (user) {
firebase
.storage()
.ref("users")
.child(user.uid + "/profile.jpg")
.getDownloadURL()
.then(imgUrl => {
img.src = imgUrl;
});
console.log(user)
} else {
signupView.style.visibility = 'visible';
profileView.style.visibility = 'hidden';
}
})

function signOutButtonPressed() {
firebase.auth().signOut();
}
const LyricSchema = new Schema({
  song: {
    type: Schema.Types.ObjectId,
    ref: 'song'
  },
  likes: { type: Number, default: 0 },
  content: { type: String }
});

LyricSchema.statics.like = function(id) {
  const Lyric = mongoose.model('lyric');

  return Lyric.findById(id)
    .then(lyric => {
      ++lyric.likes;
      return lyric.save();
    })
}

mongoose.model('lyric', LyricSchema);
_.each = function(collection, iterator) {
    if (Array.isArray(collection)) {
      for (var i = 0; i < collection.length; i++) {
        iterator(collection[i], i, collection);
      }
    } else {
      for (var property in collection) {
        iterator(collection[property], property, collection);
      }
    }

  };
return n === undefined ? array[0] : array.slice(0, n);
export default (type, id) => {
  console.table([ type, id ]);
  return fetch(`https://swapi.co/api/${type}/?page=${id}`)
    .then(response => response.json())
    .then(json => {
      console.log(json);
      return json;
    })
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
html {
  font-size: 10px;
}

body {
  font-family: "Open Sans", sans-serif;
  background-color: #eee;
}

p {
  font-size: 1.6rem;
  line-height: 1.5;
}

.container {
  max-width: 900px;
  margin: 0 auto;
  padding: 0 20px;
}

/* Start Here */
.box {
  width: 100%;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <script
      src="https://kit.fontawesome.com/1935d064dd.js"
      crossorigin="anonymous"
    ></script>
    <!-- CSS only -->
    <link
      href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css"
      rel="stylesheet"
      integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6"
      crossorigin="anonymous"
    />
    <link rel="stylesheet" href="styles.css" />
  </head>
  <body>
    <div class="container">
      <div class="row box">
        <div class="col-md-6">
          <p>Share this on Twitter.</p>
          <form action="">
            <textarea cols="30" rows="5" class="form-control fs-5">
Hello</textarea
            >
            <div
              class="button d-flex justify-content-end align-items-center mt-2"
            >
              <span class="limit px-3 fs-4">80</span>
              <button class="btn btn-primary">Tweet</button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <script src="script.js"></script>
  </body>
</html>
// This is what I've been using, pretty straight forward
// It passes the JSON to the children as props
// Of course, you fetch what you will

import React, { Component, Fragment } from 'react';

export class FetchJsonController extends Component
{
	constructor(props) {
		super(props);
		this.state = {
			data: null,
		};
	}

	componentDidMount() {
		fetch(this.props.src)
			.then(response => response.json())
			.then(data => {
				console.log(data);
				this.setState({ data })
			});
	}

	render() {
		const _data = this.state.data;
		const children = React.Children.map(this.props.children, child => {
			return React.cloneElement(child, {
				jsonData: _data
			});
		});
		return (
			<div>{ children }</div>
		)
	}
}

// This is how it's used
// SomeCompnent will receive the JSON data
<FetchJsonController src="somefile.json">
  <SomeComponent />
</FetchJsonController>
import '../styles/globals.css'

function MyApp({ Component, pageProps }) {
  console.log(`pageProps : ` , pageProps);
  return <Component {...pageProps} />
}

export default MyApp
const password = document.querySelector("#password");
const eyeIcon = document.querySelector("#eye");

eyeIcon.addEventListener("click", () => {
  if (eyeIcon.classList.contains("fa-eye")) {
    password.setAttribute("type", "text");
    eyeIcon.classList.replace("fa-eye", "fa-eye-slash");
  } else {
    password.setAttribute("type", "password");
    eyeIcon.classList.replace("fa-eye-slash", "fa-eye");
  }
});
const password = document.querySelector("#password");
const eyeIcon = document.querySelector("#eye");

eyeIcon.addEventListener("click", () => {
  if (eyeIcon.classList.contains("fa-eye")) {
    password.setAttribute("type", "text");
    eyeIcon.classList.remove("fa-eye");
    eyeIcon.classList.add("fa-eye-slash");
  } else {
    password.setAttribute("type", "password");
    eyeIcon.classList.remove("fa-eye-slash");
    eyeIcon.classList.add("fa-eye");
  }
});
/**
 * Stop iframe video
 *
 * @param {Node} iframe
 */
function stopIframeVideo(iframe) {
  const url = iframe.getAttribute('src');
  iframe.setAttribute('src', '');
  iframe.setAttribute('src', url);
}
function isPalindrome(str) {
  str = str.replace(/\W/g, '').toLowerCase();
  return (str == str.split('').reverse().join(''));
}
react-routerの使いかたを学ぶ。
参考にしたサイトはhttps://dezanari.com/react-react-router/

1. まず、react-create-appで土台を作成。

2. react-router-domをインストール(react-create-appだといらない?!)
```
yarn add react-router-dom
```
3. 
(例えば)App.jsで、
import { BrowserRouter, Route, Link, Switch } from 'react-router-dom'; 
と、インポートしておいて、

Linkで飛ぶ先はコンポーネントとして作成し、このファイルにインポートする。
import PageA from '../PageA/PageA';
import PageB from '../PageB/PageB';

そして、切り替えを以下のように設定。

```
<BrowserRouter>         /* 全体をBrowserRouterで囲む。*/

    <div className="wrapper"> 

      <div className="nav">             
        <h1>Do you like A or B???</h1>
        <Link to="/pageA">PageA</Link><br/>  /*Linkでアンカーと同じものを作れる。*/
        <Link to="/pageB">PageB</Link>
      </div>
    
      <div className="main">
        <Switch>                    /* Switchで囲んだ中には、、、*/
          <Route path="/pageA" component={PageA}/>  /* RouteでLinkで飛ぶ先を設定。*/
          <Route path="/pageB" component={PageB}/>  
        </Switch>    
      </div>
    
    </div>

    </BrowserRouter>
```
fetch("http://www.example.com/books/1", { // note we are going to /1
  method: "PATCH",
  headers: {
      "Content-Type" : "application/json"
    },
  body: JSON.stringify(
    {
      "likes": 5           // we are changing the "likes" value to 5
    }
  )
});
const array = [1,2,3,4]
array.forEach(number => console.log(number))
// [1]
// [2]
// [3]
// [4]