Snippets Collections
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); }
**  


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();
  var getColumnName = async (err) => {
    var product = await ProductType.findOne({
      _id: productType,
    });
    if (err) {
      console.log('Something is wrong');
    }
    return product;
  };

  var columnName = await getColumnName();
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]
const array = [1,2,3,4]
const reduceArray = array.reduce(a => a + b)
console.log(reduceArray)
// [10]
const array = [1,2,3,4,5,6,7,8]
const findArray = array.filter(a => a > 4)
console.log(findArray)
// 5
const array = [1,2,3,4,5,6,7,8]
const filterArray = array.filter(a => a > 4)
console.log(filterArray)
// [5,6,7,8]
const array = [1,2,3,4]
const newArray = array.map(a => a * 2)
console.log(newArray)
// [2,4,6,8]
const scale = (num, in_min, in_max, out_min, out_max) => {
  return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
<?php
$the_query = new WP_Query(
	array(
		'post_type' => 'post',
		'posts_per_page' => -1,
		'post_status' => array( 'publish' ),
	)
);
if ( $the_query->have_posts() ) {
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
?>

<div class="container">
	<article id="post-<?php the_ID(); ?>" <?php post_class('blog-item'); ?>>
		<div class="blog-item__info">
			<div class="blog-item__author">
				<?php if (get_field('single_author')) { ?>
					<?php echo get_field('single_author'); ?>
				<?php } else { ?>
					<?php the_author(); ?>
				<?php } ?>
			</div>
			<div class="blog-item__date">
				<?php the_date('F j, Y'); ?>
			</div>
		</div>
		<div class="blog-item__category">
			<?php
			$categories = get_the_category();
			if ( ! empty( $categories ) ) {
				foreach( $categories as $category ) {
			?>
				<a href="<?php echo esc_url( get_category_link( $category->term_id ) )?>">
					<?php echo esc_html( $category->name );?>
				</a>
			<?php
				}
			}
			?>
		</div>
		<h2 class="blog-item__title">
			<a href="<?php the_permalink(); ?>" class="link link--underline-left link link--underline-left--invert">
				<?php the_title(); ?>
			</a>
		</h2>
		<div class="blog-item__thumb">
			<a href="<?php the_permalink(); ?>">
				<?php if (has_post_thumbnail() ): ?>
					<?php the_post_thumbnail(); ?>
				<?php endif; ?>
			</a>
		</div>
		<?php if (has_excerpt()) { ?>
			<div class="blog-item__excerpt">
				<?php the_excerpt(); ?>
			</div>
		<?php } ?>
		<div class="blog-item__more">
			<div class="btn-round-invert">
				<a href="<?php the_permalink(); ?>">
					<?php _e('Read more', 'theme'); ?>
				</a>
			</div>
		</div>
	</article>
</div>

<?php
}
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>
export default class Controller {
    static instance = Controller.instance || new Controller()

    helloWorld() {
        console.log("Hello World... \(^_^)/ !!")
    }
}
var i ;

for ( i = 0; i <= 5; i++ ) { 
  console.log ( i ) ; // Prints the numbers from 0 to 5 
}
let fullUrl = req.protocol + '://' + req.get('host') + req.originalUrl;
Cannot update while running on a read-only volume. The application is on a read-only volume. Please move the application and try again. If you're on macOS Sierra or later, you'll need to move the application out of the Downloads directory. See https://github.com/Squirrel/Squirrel.Mac/issues/182 for more information.
var date = new Date("Sun May 11,2014");
var dateString = new Date(date.getTime() - (date.getTimezoneOffset() * 60000 ))
                    .toISOString()
                    .split("T")[0];

console.log(dateString);
function plant(seed, water, fert, temp){
  return 20 <= temp && temp <= 30 ? ("-".repeat(water) + seed.repeat(fert)).repeat(water) : "-".repeat(water * water) + seed
}
const game = {
  name: 'Fornite',
  developer: 'Epic Games'
};
const fakeAPI = (param) => new Promise((resolve, reject) => {
	console.log('Calling API...');
	setTimeout(() => {
  	if (param === 4) {
    	reject('Error: ' + param);
    }
  	resolve('Done: ' + param);
    
  }, 2000);
})

async function main() {
	const arr = [1, 2, 3, 4,5];
  
/*   Promise.all(arr.map(item => {
    if (item === 2) {
      return;
    }
    return fakeAPI(item);
  })).then(data => {
    console.log(data);
  }) */
  
  for (let item of arr) {
  	try {
  	if (item === 2) {
  		continue;
  	}
    /* if (item !== 2) { */
      const result = await fakeAPI(item);
      console.log(result);
    // }
    } catch (err) {
    	console.log(err);
    }
  }
}

main();
//> Create Firebase Context /context/firebase.js

import {createContext} from "react";
const FirebaseContext = createContext(null)
export default FirebaseContext

//> Create /lib/firebase.js
import firebase from "firebase/app";
import "firebase/auth";

// Your web app's Firebase configuration
var firebaseConfig = {
  apiKey: "AIzaSyCZu5pSf6reJ4Kl7vrwe-lwuunlpf_BvEE",
  authDomain: "ecomm-project-ec107.firebaseapp.com",
  projectId: "ecomm-project-ec107",
  storageBucket: "ecomm-project-ec107.appspot.com",
  messagingSenderId: "260651895409",
  appId: "1:260651895409:web:01599a25f81e581086e9d0",
};
// Initialize Firebase
const firebaseapp = firebase.initializeApp(firebaseConfig);
/*
const auth = firebase.auth(); //this function handle  user registration
const googleAuthProvider = new firebase.auth.googleAuthProvider(); //this function handle google login

*/
export default firebaseapp;

//> on Index.js
import firebaseapp from "./lib/firebase";
import FirebaseContext from "./context/firebase";

ReactDOM.render(
  <Provider store={store}>
    <FirebaseContext.Provider value={{ firebaseapp }}>
      <App />
    </FirebaseContext.Provider>
  </Provider>,
  document.getElementById("root")
);


// Example Consume the firebase context
import React, { useState, useContext, useEffect } from "react";
import firebase from "firebase";
import FirebaseContext from "../../context/firebase";

const { firebaseapp } = useContext(FirebaseContext);
// 1 Example
const handleSubmit = async (e) => {
    try {
      const result = await firebaseapp
        .auth()
        .signInWithEmailAndPassword(email, password);

// 2 Example 
const googleLogin = async () => {
    const googleAuthProvider = new firebase.auth.GoogleAuthProvider();

    firebaseapp
      .auth()
      .signInWithPopup(googleAuthProvider)
      .then(async (result) => {
        const { user } = result;
        const idTokenResult = await user.getIdTokenResult();
// Longhand
Math.floor(5.25) === 5 //true
//Shorthand
~~5.25 === 5 //true
/**
 * Returns data about an available .com domain.
 *
 * @param {string} name The name of the domain.
 * @return Registrar name, registration & expiration date of a .com domain.
 * @customfunction
 */
function DOT_COM_DATA(name) {
  const nameComponents = name.replace(/\s+/g, '').split(".");
  if (nameComponents.length > 2) return "INVALID INPUT";
  if (nameComponents.length == 2 && nameComponents[1] != "com") return "TLD NOT SUPPORTED";
  name = nameComponents[0];
  const url = `https://rdap.verisign.com/com/v1/domain/${name}.com`;
  const response = UrlFetchApp.fetch(url,{ muteHttpExceptions: true });
  if (response.getResponseCode() !== 200) return "AVAILABLE";
  let comData = [];
  const jsonData = JSON.parse(response.getContentText());
  const registrar = jsonData.entities[0].vcardArray[1][1][3];
  const registrationDate = jsonData.events[0].eventDate.replace("T"," ").replace("Z","");
  const expirationDate = jsonData.events[1].eventDate.replace("T"," ").replace("Z","");
  comData.push([registrar, registrationDate, expirationDate]);
  return comData;
}
/**
 * Removes the vowels from a name.
 *
 * @param {string} name The name of the domain.
 * @return The name with the vowels removed.
 * @customfunction
 */
function REMOVE_VOWELS(name) {
  const vowels = ["a", "e", "i", "o", "u"];
  const letters = name.toLowerCase().split("");
  let newName = [];
  letters.map(letter => vowels.includes(letter) ? null : newName.push(letter));
  return newName.join("");
}
/**
 * Returns the CVNX notation of a domain name.
 *
 * @param {string} name The name of the domain (without the TLD).
 * @return The CVNX notation of the domain name.
 * @customfunction
 */
function DOMAIN_PATTERN(name) {
  const vowels = ["a", "e", "i", "o", "u"];
  const consonents = ["b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z"];
  const letters = name.toLowerCase().split("");
  let pattern = [];
  letters.map(letter => vowels.includes(letter) ? pattern.push("V") : (consonents.includes(letter) ? pattern.push("C") : (!isNaN(letter) ? pattern.push("N") : pattern.push("X"))));
  return pattern.join("");
}
( function ($){
    jQuery (window).on ('load', function (){
        /* Global - Auto run animation for elements with data-animationcss - engine.js */
        animationCSS ();
    });

    /* Auto run animation for elements with data-animationcss */
    function animationCSS(){
        if ( !is_touch_device ()) {
            jQuery ('*[data-animationcss]').addClass (" animated ");

            /* ================ ANIMATED CONTENT ================ */
            if (jQuery (".animated")[ 0 ]) {
                jQuery ('.animated').css ('opacity', '0');
            }

            /* use scrollmagic */
            var animator = new ScrollMagic.Controller ();

            jQuery ('*[data-animationcss]').each (function (){
                var animation = jQuery (this).attr ('data-animationcss');

                var scene = new ScrollMagic.Scene ({
                    triggerElement: this,
                    triggerHook: 'onEnter',
                    offset: 50,
                    reverse: false
                }).on ('start', function (element){

                    jQuery (this.triggerElement ()).css ('opacity', 1);
                    jQuery (this.triggerElement ()).addClass (" animated " + animation);

                })
                .addTo (animator);
            });
        }
    }

} ) (jQuery);
//HTML
// getVimeoId($vleft['video']) = url do filmu vimeo

<div class="bottom__img">
	<iframe src="https://player.vimeo.com/video/<?php echo getVimeoId($vleft['video']); ?>?&autoplay=0&loop=0&muted=1&title=0&byline=0&portrait=0&fun=0&background=1" frameborder="0" allowfullscreen></iframe>
  <button class="play btn btn-transparent btn-rounded-inverse-mini" data-scrollinit="click">
      <svg width="12" height="14" viewBox="0 0 12 14" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M12 7L3.01142e-07 13.9282L9.06825e-07 0.0717964L12 7Z" fill="#F2FF00"/>
      </svg>
  </button>
  <button class="stop btn btn-transparent btn-rounded-inverse-mini">
      <svg width="8" height="14" viewBox="0 0 8 14" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M0.000244141 0.714355H2.28607V13.8572H0.000244141V0.714355Z" fill="#F2FF00"/>
          <path d="M5.71413 0.714111H7.99995V13.8572H5.71413V0.714111Z" fill="#F2FF00"/>
      </svg>
  </button>
</div>


//SCSS
.bottom__img {
	height: 0;
	width: 100%;
	padding-top: 74%;
	position: relative;

	iframe,
	img {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		object-fit: cover;
	}

	.play,
	.stop {
		position: absolute;
		right: 26px;
		bottom: calc(17.75% + 26px);

		&:hover {
			svg {
				path {
					fill: #000000;
				}
			}
		}

		&.stop {
			//display: none;
		}

		&.play {
			display: none;

			svg {
				margin-left: 2px;
			}
		}
	}
}

//JS
//need magicscroll

(function ($) {
	jQuery(window).on('load', function () {
		var localization = $('.bottom__img');
		var moduleIframe = $(localization).find('iframe');
		if (moduleIframe.length) {
			var player = new Vimeo.Player($(localization).find('iframe'));
			var playBtn = $(localization).find('.play');
			var stopBtn = $(localization).find('.stop');
			console.log(stopBtn);

			/* controls */
			playBtn.on('click', function (e) {
				e.stopPropagation();
				player.play();
			})
			stopBtn.on('click', function () {
				player.pause();
			})

			player.on('play', function () {
				stopBtn.show();
				playBtn.hide();
			});
			player.on('pause', function () {
				stopBtn.hide();
				playBtn.show();
			});
		}

		var autoPlay = new ScrollMagic.Controller();

		jQuery('.bottom__img *[data-scrollinit]').each(function () {
			var animation = jQuery(this).attr('data-scrollinit');

			var scene = new ScrollMagic.Scene({
				triggerElement: this,
				triggerHook: 'onEnter',
				offset: 100,
				reverse: false
			}).on('start', function (element) {
				player.play();

			})
				.addTo(autoPlay);
		});
	});
})(jQuery);



//if you have 2 videos you can play 2nd after finished first:
//playerLeft.on('ended', function () {
//	playerRight.play();
//});
// ex. zmorph3d - page product i500
const array = [2, 5, 9];

console.log(array);

const index = array.indexOf(5);
if (index > -1) {
  array.splice(index, 1);
}

// array = [2, 9]
console.log(array); 
//First Examples
function fibonacci(n) {
	const list = [0, 1];
	for (let x = 2; x < n + 1; x += 1) {
		list.push(list[x - 2] + list[x - 1]);
	}
	return list[n];
}

console.log(fibonacci(4));

//Second Examples
function fibonacci(nums) {
  
  let fib = [0, 1];
  let data = [];
  
  for(let i = 2; i <= nums; i++) {
    fib[i] = fib[i - 1] + fib[i - 2]; 
    data.push(fib[i]);
  }
  
  return data;
}

//Third Examples
function fibonacci(nums) {
  
  let fib = [0, 1];
  let data = [];
  
  for(let i = 2; i <= nums; i++) {
    fib[i] = fib[i - 1] + fib[i - 2]; 
    data.push(fib[i]);
  }
  
  return data;
}
# Try running these queries

# Simple query to fetch regions
query fetchRegions {
  regions {
    edges {
      node {
        UID
        Name
      }
    }
  }
}

# Query to fetch all "Queued Jobs"
query fetchQueuedJobs($filter: EQLQueryFilterJobs!) {
  jobs(filter: $filter) {
    edges {
      node {
        Name
        covid_self_isolate
        major_fault
        boiler_approx_age
        boiler_age
        Description
        additional_hours_rationale
        visit_type
        last_service
        hometree_office
        booking_tool_source
        labour_adjustment_description
        labour_adjustment_net_amount
      }
    }
  }
}

# Sample Create Query.
# Ensure the "createInput" variable is appropriately
# set for this query to run
mutation createJob($createInput: NewJobs!) {
  schema {
  	insertJobs(input: $createInput)
  }
}

# Sample Update Query.
# Ensure the "updateInput" variable is appropriately
# set for this query to run
mutation updateJob($updateInput: UpdateJobs!) {
  schema {
  	updateJobs(input: $updateInput)
  }
}

# Sample Delete Query.
# Ensure the "deleteInput" variable is appropriately
# set for this query to run
mutation deleteJob($deleteInput: ID!) {
  schema {
  	deleteJobs(UID: $deleteInput)
  }
}


{
  "filter": "Name == \"JOB-0459\"",
  "createInput": {
    "Duration": 50,
    "Description": "Inserted via GraphQL!",
    "RegionId": "<enter-region-id>"
  },
  "updateInput": {
    "UID": "<enter-job-id>",
    "Description": "Updated via GraphQL!"
  },
  "deleteInput": "<enter-job-id>"
}
$('.page-header').css({
  '-webkit-transform' : 'translateY(' + topbarHeight + 'px)',
  '-moz-transform'    : 'translateY(' + topbarHeight + 'px)',
  '-ms-transform'     : 'translateY(' + topbarHeight + 'px)',
  '-o-transform'      : 'translateY(' + topbarHeight + 'px)',
  'transform'         : 'translateY(' + topbarHeight + 'px)'
});
if (res === 25 || res === "twenty-five" || res === 25.0) {
  // some action here
}

// Shorthand
if ([25, "twenty-five", 25.0].includes(res)) {
  // some action here
}
export const Container = styled.div`
    ${ props => props.shouldHover 
        ? '&:hover { background: red }' 
        : ''
    }
`;
function isInViewport(elem) {
    const bounding = elem.getBoundingClientRect();
    return (
        bounding.top >= 0 &&
        bounding.left >= 0 &&
        bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
        bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
};
const EARTH_RADIUS_IN_METERS = 6371010
const TILE_SIZE = 256
const SCREEN_PIXEL_HEIGHT = 768

var zoom = (altitude, latitude) => Math.log(1 / Math.tan(Math.PI / 180 * 13.1 / 2) * (SCREEN_PIXEL_HEIGHT / 2) * 2 * Math.PI / (TILE_SIZE * altitude / (EARTH_RADIUS_IN_METERS * Math.cos(Math.PI / 180 * latitude)))) / Math.LN2;
const Test extends React.Component
const _handleBurger = () => {
const navBurger = document.getElementById("navBurger");
const navbarMenu = document.getElementById("navbarMenu");

navBurger.classList.toggle("is-active");
navbarMenu.classList.toggle("is-active");
};
const sum = (a, b) => a + b
const sum5 = sum.bind(null, 5)

sum5(10) // 15
function setup() {
  createCanvas(windowWidth, windowHeight);
  yCoordinatBold = 100;
  ySpeedBold = 6;
  windowWidth=650;
  GreenBallHit = false
}

let img;

function preload(){
  img = createImg('http://mpsteenstrup.dk/FN_maal/FN10.jpg','');
	img.hide();
}



function draw() {
	background(91,146,229);
	image(img,mouseX,mouseY,80,80)

// Græsplænen
	fill(100,200,80);
	rect(0,750,1500,100);
var x=400;
// Cirkel, rød når ramt af mus
  fill(0,200,0);  // grøn
 if(mouseX>300 && mouseX<500 && mouseY>yCoordinatBold-100 && mouseY<yCoordinatBold+100) {
	fill(200,0,0)	  // rød hvid ramt af mus
	}
	ellipse(x,yCoordinatBold,200,200);
   yCoordinatBold += ySpeedBold;

   
 // Skift retning på cirkel , hvis den rtammer grænserbne 
   if (yCoordinatBold>windowWidth || yCoordinatBold<0){
    ySpeedBold = -ySpeedBold;
   }
   
   //forhindring
	fill(200,0,0);
	rect(800,600,160,150);
	
	//Udsagn 1
	fill(0,0,0)
	textSize(20,30)
text("Blive diskrimineret",800,670)
	//Udsagn 1
	fill(0,0,0)
	textSize(20,30)
	text("pga din hudfarve",800,690)
text("hej"x,yCoordinatBold+30);	

 }
 
 // function mousePressed (){
 //	if(mouseX>300 && mouseX<500 && mouseY>300 && mouseY<500){}
//
 //}	

function setup() {
  createCanvas(windowWidth, windowHeight);
  yCoordinatBold = 100;
  ySpeedBold = 6;
  windowWidth=650;
  GreenBallHit = false
}

let img;

function preload(){
  img = createImg('http://mpsteenstrup.dk/FN_maal/FN10.jpg','');
	img.hide();
}



function draw() {
	background(91,146,229);
	image(img,mouseX,mouseY,80,80)
	fill(200,0,0)
	ellipse(400,yCoordinatBold,200,200);


textSize(30,30)
text("hej",400,200)

// Græsplænen
	fill(100,200,80);
	rect(0,750,1500,100);

// Cirkel, rød når ramt af mus
  fill(0,200,0).  // grøn
 if(mouseX>300 && mouseX<500 && mouseY>300 && mouseY<500); {
	fill(200,0,0)	  // rød hvid ramt af mus
	}
	ellipse(400,yCoordinatBold,200,200);
   yCoordinatBold += ySpeedBold;

   
 // Skift retning på cirkel , når den rammer grænserbne 
   if (yCoordinatBold>windowWidth || yCoordinatBold<0){
    ySpeedBold = -ySpeedBold;
   }
 }
 
 function mousePressed (){
 if(mouseX>300 && mouseX<500 && mouseY>300 && mouseY<500){}

 //	}	{
}
int dim;

void setup() {
  size(640, 360);
  dim = width/2;
  background(0);
  colorMode(HSB, 360, 100, 100);
  noStroke();
  ellipseMode(RADIUS);
  frameRate(1);
}

void draw() {
  background(0);
  for (int x = 0; x <= width; x+=dim) {
    drawGradient(x, height/2);
  } 
}

void drawGradient(float x, float y) {
  int radius = dim/2;
  float h = random(0, 360);
  for (int r = radius; r > 0; --r) {
    fill(h, 90, 90);
    ellipse(x, y, r, r);
    h = (h + 1) % 360;
  }
}
$('> .child-class', this);
$('.element', this);


$('.thisParent').each(function() {
  var imageUrl = $(this).find('img').attr('src');
  //console.log(imageUrl);
  $('> .vc_column-inner', this).css("background-image", "url(" + imageUrl + ")");
  $(this).find('img').addClass('hidden');
});
// w szablonie miejsce od którego nawigujemy scrollem
<?php
		if($instance['anchor']['active']){
	?>
		<div id="<?php echo url_slug($instance['anchor']['name']); ?>" class="anchor-local-element position-relative" data-anchor-local="<?php echo $instance['anchor']['name']; ?>"></div>
	<?php
		}
?>
  
  
  //JS
  function localAnchorMenu() {
	// create menu items
	jQuery(jQuery('article .anchor-local-element').get().reverse()).each(function () {
		var anchorName = jQuery(this).data('anchor-local');
		var anchorID = jQuery(this).attr('id');
		console.log(anchorName);
		jQuery(document).find('.anchor-local-menu-items').prepend('<a data-scroll class="anchor-local-menu-item" href="#' + anchorID + '">' + anchorName + '</a>');
		jQuery(document).find('#header').addClass('anchor-local-active');
	});


	// scroll to element
	jQuery(document).find('.anchor-local-menu-item').on('click', '[data-scroll]', scrollToSection);

	function scrollToSection(event) {
		event.preventDefault();
		var $section = $($(this).attr('href'));
		jQuery('html, body').animate({
			scrollTop: $section.offset().top
		}, 500);
	}

}

//Wykrywa miejsce do którego nawigujemy i wpisaną w niego nazwę nazwę, na podstwie tego tworzy menu
function isEven(value) {
	if (value%2 == 0)
		return true;
	else
		return false;
}
let input = "Hi, Human";
const vowels = ['a', 'e', 'i', 'o', 'u'];
let resultArray = [];
for (let i = 0; i <= input.length; i++){
  for (let j = 0; j < vowels.length; j++){
    if(vowels[j] === input[i]){
      if(vowels[j] === 'e'){
        resultArray.push('ee');
      } else if (vowels[j] === 'u'){
        resultArray.push('uu');
      } else{
        resultArray.push(vowels[j]);
      }
    }
  }
}
console.log(resultArray.join('').toUpperCase());
let clickMe = document.querySelector('button');

function getRandomNumber(min, max) {
  let totalEle = max - min + 1;
  let result = Math.floor(Math.random() * totalEle) + min;
  return result;
}
function createArrayOfNumber(start, end) {
  let myArray = [];
  for (let i = start; i <= end; i++) {
    myArray.push(i);
  }
  return myArray;
}
let numbersArray = createArrayOfNumber(1, 10);

clickMe.addEventListener('click', () => {
  if (numbersArray.length === 0) {
    console.log('No more random number');
    return;
  }
  let randomIndex = getRandomNumber(0, numbersArray.length - 1);
  let randomNumber = numbersArray[randomIndex];
  numbersArray.splice(randomIndex, 1);
  console.log(randomNumber);
});
//IE 10 - 11 Fixes - NESTING DOES NOT WORK
@media all and (min-width: 992px) and (-ms-high-contrast: none), (-ms-high-contrast: active) {

}

@media all and (min-width: 1200px) and (-ms-high-contrast: none), (-ms-high-contrast: active) { 

}
<! DOCKTYPE html>
<!--Take Input From the user and make a loop when the number is <10-->
<html>
    <head>
        <title>do_while loop example2</title>
    </head>
    <body>
        <center>
            <h3>
                DO_WHILE LOOP
            </h3>
        </center>
        <script>
            var a=10;
            var num = prompt("Enter The highest Range Of the number");
            do
            {
                document.write("Your value is "+a+"<br>");
                a=a+1;
            }
            while(a<=num)
        </script>
    </body>
</html>
<! DOCKTYPE html>

<!--Take input From the user and Check whether the number is odd or even-->

<html>
    <head>
        <title>
            Check Odd or even
        </title>
    </head>
    <body>
        <center>
            <h3>
                ODD OR EVEN CHECKER
            </h3>
        </center>
        <script>
            var num;
            num =prompt("Enter your Number You want to check");
            if(num%2==0)
            {
                document.write("The number is a Even Number and the number is"+num);
            }
            else
            {
                document.write("The number is a odd number and the number is"+num);
            }
        </script>
    </body>
</html>
<! DOCKTYPE html>

<html>
    <head>
        <title>
            biggest number among three distinct number
        </title>
        <body>
            <center>
            <u>
                <h2>
                    Find The Biggest Number among three different Number
                </h2>
            </u>
            </center>
            <script>
                var a;
                var b;
                var c;
                
                if(a>b & a>c);
                {
                    alert ("biggest number is " +a);
                }
                elseif (b>a & b>c);
                {
                    alert("biggest number is "+b);
                }
                elseif(c>a & c>b);
                {
                    alert("biggest number is"+c);
                }
            </script>
        </body>
    </head>
<!--Make a HTML Project using Array-->
<! DOCTYPE html>

<html>
<head>
    <title>Array</title>
</head>
<body>
    <script>
        var i,j,row,column;
        row=prompt("Enter The number of rows");
        column=prompt("Enter the number of Column");
        var arr= new Array(row);
        for(i=0;i<row;i++)
        arr[i]=new Array(column);

        for(i=0;i<row;i++){
            for(j=0;j<=column;J++)
        {
        arr[i][j]=prompt("Enter value in matrix");
        }
        }
        for(i=0;i<row;i++);{
            for(j=0;j<column;j++){
            document.write(arr[i][j]+"  ");
        }
        document.write("<br>");
        }
    </script>
</body>
</html>
--JavaScript class inheritance, get & set, array 
https://www.w3schools.com/code/tryit.asp?filename=GPICQHQJCCON
jQuery(document).ready(function($) {
    $('img[title]').each(function() { $(this).removeAttr('title'); });
});
const cipher = salt => {
    const textToChars = text => text.split('').map(c => c.charCodeAt(0));
    const byteHex = n => ("0" + Number(n).toString(16)).substr(-2);
    const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);

    return text => text.split('')
        .map(textToChars)
        .map(applySaltToChar)
        .map(byteHex)
        .join('');
}

const decipher = salt => {
    const textToChars = text => text.split('').map(c => c.charCodeAt(0));
    const applySaltToChar = code => textToChars(salt).reduce((a,b) => a ^ b, code);
    return encoded => encoded.match(/.{1,2}/g)
        .map(hex => parseInt(hex, 16))
        .map(applySaltToChar)
        .map(charCode => String.fromCharCode(charCode))
        .join('');
}
var str = "Sonic Free Games";
str = str.replace(/\s+/g, '-').toLowerCase();
console.log(str); // "sonic-free-games"
<div id="textsection">
  <div class="simpletext">
    <h1> {{ section.settings.text-box }} </h1>
    <h3> {{ section.settings.text }} </h3>
  </div>
</div>
{% schema %}
  {
    "name": "Top-splash",
    "settings": [
      {
        "id": "text-box",
        "type": "text",
        "label": "Heading",
        "default": "Title"
      },
      {
        "id": "text",
        "type": "richtext",
        "label": "Add custom text below",
        "default": "<p>Add your text here</p>"
      }
    ],
    "presets":[
        {
        "name":"Top splash",
        "category":"test"
        }
    ]
  }
{% endschema %}

{% stylesheet %}
{% endstylesheet %}

{% javascript %}
{% endjavascript %}
#index {
    .panel {
        padding: 50px 20px;
    }
    h1, h3 {
        font-size: 30px;
    }
    h2 {
        font-size: 35px;
    }
const urlString = window.location.search
const urlParameters = new URLSearchParams(urlString)

if (urlParameters.has('parameter')) {
  urlParameters.get('parameter')
}
let items = [1,25,"JavaScript",69,"css","34","keep coding","html"];
console.log(items)

//shuffle array
function shuffle(arr){
  for(let i =arr.length-1;i>0;i--){
    const j = Math.floor(Math.random() * (i+1));
    [arr[i],arr[j]] = [arr[j],arr[i]];
  }
  return arr
}
console.log(shuffle(items))

//shuffle selected index 
const  itemToShuffle = items.slice(3,7);
console.log(shuffle(itemToShuffle))

//items after shuffling item from index 3 to 7
items = [items[0],items[1],items[2],...itemToShuffle,items[7]]
console.log(items)
const arr = [26, 86, 45, 69, 25, 45]; // Taking random array
// Map function
// Defination:- it returns the new array from the base array after implementing some logic on int.
// length of the new array is always equal to length of the base array
const mapArr = arr.map((value) => value * 2);
console.log(mapArr); // [ 52, 172, 90, 138, 50, 90 ]
console.log(arr.length === mapArr.length); // true
// Filter function
// Defination:- it returns the new array from the base array only if some condition is true
// length of the new can be less than the length of the base array
const filterArr = arr.filter((value) => value > 50);
console.log(filterArr); // [ 86, 69 ]
// Reduce function
// Defination:- it returns the single value from the array.
const reduceArr = arr.reduce((accumulator, value) => accumulator + value, 0);
console.log(reduceArr); // 296
// Bonus for reduce
const pets = ["dog", "chicken", "cat", "dog", "chicken", "chicken", "rabbit"];
// lets count animals with reduce
const petCount = pets.reduce((obj, pet) => {
  obj[pet] ? obj[pet]++ : (obj[pet] = 1); // explenation:- if object has Dog in it than increase its count else add Dog and assign the value of 1
  return obj;
}, {});
console.log(petCount); // { dog: 2, chicken: 3, cat: 1, rabbit: 1 }
// CheatSheet
// map([🌽, 🐮, 🐔], cook)
// => [🍿, 🍔, 🍳]
// filter([🍿, 🍔, 🍳], isVegetarian)
// =>  [🍿, 🍳]
// reduce([🍿, 🍳], eat)
// => 💩
const p1 = new Promise((resolve, reject) => setTimeout(resolve({'foo': 'bar'}), 500));
const p2 = new Promise((resolve, reject) => setTimeout(resolve({'moe': 'hey'}), 1500));
const p3 = new Promise((resolve, reject) => setTimeout(reject(new Error('ko')), 800));
(async function() {
    const p = [p1,p2,p3];
    // Promise.allSettled waits for all promises to be done (rejected or resolved/fulfilled)
    const settledPromises = await Promise.allSettled(p);
    console.info(settledPromises); 
    /*[
        { status: 'fulfilled', value: { foo: 'bar' } },
        { status: 'fulfilled', value: { moe: 'hey' } },
        { status: 'rejected', reason: Error: ko}
    ]*/
    // Promise.all resolves if and only if all promises are resolved/fulfilled
    // Promise.all rejects if one of the promises rejects
    const okPromises = [p1,p2];
    try {
        // Promise.all(okPromises) resolves because p1 and p2 resolves and no promise rejects
        const okResolvedPromises = await Promise.all(okPromises);
        console.info('all promises resolved !', okResolvedPromises);
// Promise.all(p) won't resolve because p3 rejects
        const allResolvedPromises = await Promise.all(p);
        console.info('all promises resolved !', allResolvedPromises);
    } catch(err) {
        console.info(err); // returns Error: ko from the second Promise.all
    }
})();
// Promise takes two functions as arguments
// You call resolve when the function succeeds
const okPromise = new Promise(function(resolve, reject) {
    resolve({result: ['1','2']}) // you can pass data to the callback
  });
  
   // You call reject when it fails
   const koPromise = new Promise(function(resolve, reject) {
    reject(new Error('not found')) // you can pass data to the callback
  });
  
  // The promise rejects if you throw an error
  const throwedPromise = new Promise(function(resolve, reject) {
    throw new Error('not found') // you can pass data to the callback
  });
  
  // Promise can be created using "async" keyword
  // It resolves with returned value
  // Rejects if an error is thrown
  const asyncPromise = async function() {
    return true;
  }
  
  // You can call other promises by using .then for getting the result
  okPromise.then(function(result) {
    console.info(result) // {result: ['1','2']}
  }).catch((err) => console.info(err)) // nothing displayed
  // Use .catch for catch the error of a promise
  koPromise.then(function(result) {
    console.info(result) // nothing displayed
  }).catch((err) => console.info(err)) // Error: not found
const arr1 = ['a', 'b', 'c'];
const arr2 = ['1', '2', '3'];
// Using .concat()
console.info(arr1.concat(arr2)); // ["a","b","c","1","2","3"]
// Using spread operators
console.info([...arr1, ...arr2]); // ["a","b","c","1","2","3"]
// This works too:
console.info(['a', 'b', 'c', ...arr2]); // ["a","b","c","1","2","3"]
// Using Array.of
console.info(Array.of(...arr1, ...arr2)); // ["a","b","c","1","2","3"]
// With reduce
console.info(arr2.reduce(function(array,value) {
  array.push(value);
  return array;
}, arr1)); // ["a","b","c","1","2","3"]
const myArray = [1,2,3,4,5,6];
// Use .map() for applying a transformation on each elements
const mutipliedArray = myArray.map((element) => element*2);
console.info(mutipliedArray); // [ 2, 4, 6, 8, 10, 12 ]
// Use .reduce() for merging together each element of the array
const sumOfArray = myArray.reduce((previous, current) => previous+current);
console.info(sumOfArray); // 21
// These methods can be chained together
const sumOfMultipliedArray = myArray.map((el) => el*2).reduce((prev, cur) => prev+cur);
console.info(sumOfMultipliedArray); // 42
function handleSuccess(){}
function handleUnauthorized(){}
function handleNotFound(){}
function handleUnknownError(){}
const status = 200;
// Switch statement
switch (status) {
    case 200:
        handleSuccess()
        break
    case 401:
        handleUnauthorized()
        break
    case 404:
        handleNotFound()
        break
    default:
        handleUnknownError()
        break
}
// Equivalent using object key search in O(1) time
const hashmap = {
    200: handleSuccess,
    401: handleUnauthorized,
    404: handleNotFound,
    default: handleUnknownError
};
const hashmapResult = hashmap.hasOwnProperty(status) ? hashmap[status] : hashmap.default;
console.info(hashmapResult());
loop1: for (let i = 0; i < 4; i++) {
  loop2: for (let j = 0; j < 3; j++) {
    console.log('before')
    if (i === 1) {
      // when i equal to 1, jump out the loop2 immediately
      continue loop1
      // or can do break loop1
    }
    console.log(`i=${i}, j=${j}`)
  }
}

foo: {
  console.log('face');
  break foo;
  console.log('this will not be executed');
}
console.log('swap');

// this will log:

// "face"
// "swap" 
    <div class="custom__wrapper">
        <video src="/media/1011/filmtegner-1.mp4" class="custom__slider" autoplay loop muted controls></video>

        <ul>
            <li onclick="videoslider('/media/1011/filmtegner-1.mp4')"><video src="/media/1011/filmtegner-1.mp4"></video></li>
            <li onclick="videoslider('/media/1011/filmtegner-1.mp4')"><video src="/media/1011/filmtegner-1.mp4"></video></li>
            <li onclick="videoslider('/media/1011/filmtegner-1.mp4')"><video src="/media/1011/filmtegner-1.mp4"></video></li>
            <li onclick="videoslider('/media/1011/filmtegner-1.mp4')"><video src="/media/1011/filmtegner-1.mp4"></video></li>
            <li onclick="videoslider('/media/1011/filmtegner-1.mp4')"><video src="/media/1011/filmtegner-1.mp4"></video></li>
        </ul>
    </div>
<script>
    function videoslider(links) {
        document.querySelector(".slider").src = links;
    }
</script>

.custom__wrapper {
    width: 100%;
    height: 100vh;
    position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
}

.custom__wrapper .custom__slider {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}


.custom__wrapper ul {
    position: absolute;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 20;
}

.custom__wrapper ul li {
    list-style: none;
    cursor: pointer;
    margin: 10px;
}


.custom__wrapper ul li video {
    width: 200px;
    transition: all 0.3s;
}

.custom__wrapper ul li video:hover {
    transform: scale(1.1);
}

video {
    width: 100%;
    height: 100%;
}
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();
secretMessage.push('to', 'Program');
secretMessage[7] = 'right';
secretMessage.shift();
secretMessage.unshift('Programming');
secretMessage.splice(6, 5, 'know,');
console.log(secretMessage.join(' '));
var object1; //JSON object

for (const [key, value] of Object.entries(object1)) {
  console.log(`${key}: ${value}`);
}
loadPixels(); 
  // Since we are going to access the image's pixels too  
  img.loadPixels(); 
  for (int y = 0; y < height; y++) {
    for (int x = 0; x < width; x++) {
      int loc = x + y*width;
      
      // The functions red(), green(), and blue() pull out the 3 color components from a pixel.
      float r = red(img.pixels[loc]);
      float g = green(img.pixels[loc]);
      float b = blue(img.pixels[loc]);
      
      // Image Processing would go here
      // If we were to change the RGB values, we would do it here, 
      // before setting the pixel in the display window.
      
      // Set the display pixel to the image pixel
      pixels[loc] =  color(r,g,b);          
    }
  }
  updatePixels();
<?php echo do_shortcode("[shortcode]"); ?>
// Validates email address of course.
function validEmail(e) {
    var filter = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    return String(e).search (filter) != -1;
}
int tile = width/20;
int half = tile/2;
float size = tile/2; 

translate(tile/2, tile/2);


  for (int y=0; y<height; y+=tile) {
    for (int x=0; x<width; x+=tile) {
      pushMatrix();
      translate (x, y);
      rotate(degrees(angle));
      rect(0, 0, size, size);
      //line(x-half, y-half, x+half, y+half);
      popMatrix();
    }
  }

let list = [4, 5, 6];

for (let i in list) {
   console.log(i); // "0", "1", "2",
}

for (let i of list) {
   console.log(i); // "4", "5", "6"
}
const food = { beef: '🥩', bacon: '🥓' }
//shallow copy
1.// "Spread" => 
{ ...food }
2.// "Object.assign" => shallow copy 
Object.assign({}, food)
// deep copy when object consists nested objects and arrays
3. // "JSON" => convert to string and parse back
JSON.parse(JSON.stringify(food))
// RESULT:
// { beef: '🥩', bacon: '🥓' }
4.// deep copy by using iterator
function iterationCopy(src) {
  src = { beef: '🥩', bacon: '🥓' , num:[1,2,3,]}
  let target = {};
  for (let prop in src) {
    if (src.hasOwnProperty(prop)) {
      // if the value is a nested object, recursively copy all it's properties
      if (isObject(src[prop])) {
        target[prop] = iterationCopy(src[prop]);
      } else {
        target[prop] = src[prop];
      }
    }
  }
  return target;
}
function rand(min, max){
  min = (min == null ? Number.MIN_SAFE_INTEGER : min);
  max = (max == null ? Number.MAX_SAFE_INTEGER : max);
  return min + ((max - min) * Math.random());
}

function rand(
  min = Number.MIN_SAFE_INTEGER, 
  max = Number.MAX_SAFE_INTEGER
){
  return min + ((max - min) * Math.random());
}
import React from "react";
import { BrowserRouter as Router, Route } from 'react-router-dom';
import ReactDOM from 'react-dom';
 
const App = () => {
  return (
    <div >
        <Route exact path="/" component={Home} />
       	<Route exact path="/about" component={About} />
        <Route exact path="/contacts" component={Contacts} />
          
     </div>
  );
};
 
export default App;
 
---
import React from "react";
import ReactDOM from 'react-dom';

const App = () => {
 return (
   <div className="App">
   	<h1>React Router </h1>
   </div>
 );
};
export default App;
 - -
 
ReactDOM.render(<App />, document.getElementById("root"));
import React from "react";
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
  const App = () => {
   return (
     <div className="App">
          <h1>React Router App </h1>
     </div>
   );
  };
  export default App;
 
ReactDOM.render( 
   <Router>
      <App/>
   </Router>, 
document.getElementById("root"));
import React from "react";
import { BrowserRouter as Router, Route } from 'react-router-dom';


const App = () => {
  return (
    <div >
        <Route path="/" component={Home} />
        <Route path="/about" component={About} />
		<Route path="/contacts" component={Contacts} />

     </div>
  );
};

export default App;

  
ReactDOM.render(   
      <Router>
           <App />
      </Router>, 
document.getElementById("root"));

const Home = () => {
  return (
    <div>
      <h1>This is Our Home Page !</h1>
    </div>
  );
};
 
const About = () => {
  return (
    <div>
      <h1>This is My about Page!</h1>
    </div>
  );
};

const Contacts = () => {
  return (
    <div>
      <h1>This is My Contact Page!</h1>
    </div>
  );
};
import React from "react";
import { BrowserRouter as Router, Route } from 'react-router-dom';
import ReactDOM from 'react-dom';

const App = () => {
  return (
    <div >
        <Route path="/" component={Home} />
       	<Route path="/about" component={About} />
        <Route path="/contacts" component={Contacts} />
          
     </div>
  );
};

export default App;

  
ReactDOM.render(   
      <Router>
           <App/>
      </Router>, 
document.getElementById("root"));

const Home = () => {
  return (
    <div>
      <h1>This is Our Home Page !</h1>
    </div>
  );
};
 
const About = () => {
  return (
    <div>
      <h1>This is My about Page!</h1>
    </div>
  );
};

const Contacts = () => {
  return (
    <div>
      <h1>This is My Contact Page!</h1>
    </div>
  );
};
console.log('Hello world.')
const arr = [1,2,3,4,5];
const result  = arr.map(x=>x*2).filter(x=>x>=5)
const arr = [1,2,3]
let result = arr.forEach(val=>{
    console.log(val*2) // 2 4 6
})
console.log(result) // undefined
const arr = [1,2,3]
let result = arr.map(val=>{
    return val*2
})
console.log(result) // [2,4,6]
const match1 = 
{ 
  name : "Sachin", 
  score : 56 
};


const match2 = 
{ 
    name : "Sachin", 
    score: 53,
    balls: 32 
};



const match = {...match1, ...match2};
console.log(match) ;
 // Output -> 
             {  name: "Sachin",
                score: 53,
                balls: 32
             };
const arr = [333,1,2,11,22,3,4]
console.log(arr.sort())

arr.sort((a,b)=>a-b)

console.log(arr)
const arr = ["Apple",45,"","google",null],,,,"facebook","",69]

const removeEle = arr.filter((el)=> return el !=null && el != "")
function isEqual(arr1,arr2){
  let x = arr1.length;
  let y = arr2.lenght;
  
  //if lenght of array are not equal means array are not equal 
  if(x !=  y) return false;
  
  //sorting both array
  x.sort();
  y.sort();
  
  // Linearly compare elements
  for(let i=0;i<x;i++){
    if(x[i] != y[i]) return false
  }
  // If all elements were same.
    return true
}

let arrayOne = [3, 5, 2, 5, 2]
let arrayTwo = [2, 3, 5, 5, 2]

isEqual(arrayOne,arrayTwo) ? console.log("Matched") : console.log("Not Match")
function arrayChunk (array, size) {
  const chunked_arr = [];
  let index = 0;
  while (index < array.length) {
    chunked_arr.push(array.slice(index, size + index));
    index += size;
  }
  return chunked_arr;
}
const object = {
  keberangkatan: {
    keberangkatan1:{
      id: 1, 
      name: "Superadmin"
    },
    keberangkatan2:{
      id: 2, 
      name: "Admin"
    }
  }
}

const convertObjectToArrayObject = ({object}) => {
  const tempArray = []
  for (const property in object) {
    tempArray.push(object[property])
  }
  return tempArray
}

console.log(convertObjectToArrayObject({object: object.keberangkatan}))
const arrays = [{id: 1, name: "Superadmin"},{id: 2, name: "Admin"}]

const convertArrayObjectToObject = ({ keys, array, parentKeys }) => {
  const convert = array.reduce((obj, item, index) => Object.assign(obj, { [`${keys}${index+1}`]: item }), {});
  if(parentKeys) {
  	return {[parentKeys]: { ...convert }}
  }
  return convert
}

console.log(convertArrayObjectToObject({ keys:'keberangkatan', array: arrays, parentKeys: 'keberangkatan' }))
const fs = require('fs')

exports.download = (req, res, next) => {
  console.log('fileController.download: started')
  const path = req.body.path
  const file = fs.createReadStream(path)
  const filename = (new Date()).toISOString()
  res.setHeader('Content-Disposition', 'attachment: filename="' + filename + '"')
  file.pipe(res)
}
const appRoot = require('app-root-path')
const multer = require('multer')

const fileController = require(`${appRoot}/src/controllers/FileController.js`)
const INPUT_NAME = 'photos'

const fileStorage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, 'files')
  },
  filename: (req, file, cb) => {
    cb(null, file.originalname + '-' + (new Date()).toISOString())
  }
})

const fileFilter = (req, file, cb) => {
  if (['image/png', 'image/jpg', 'image/jpeg'].includes(file.mimetype)) {
    cb (null, true)
  } else {
    cb (null, false)
  }
}



module.exports = (app) => {
  app.use(multer({storage: fileStorage, fileFilter: fileFilter}).single('photo'))
  app.post('/upload', fileController.upload)
  app.post('/download', fileController.download)
}
<script>
import axios from 'axios'
export default {
  name: 'App',
  data () {
    return {
      serverLink: 'http://localhost:3000/upload/'
    }
  },
  methods: {
    filesChange (filename, files) {
      if (!files.length) {
        return
      }

      console.log(filename, files)
      const formData = new FormData()
      for (let i = 0; i < files.length; i++) {
        formData.append(filename, files[i], files[i].name)
      }

      axios.post(this.serverLink, formData).then(
        rsp => {
          console.log(rsp)
        }
      ).catch(err => {
        console.log(err)
      })
    }
  }
}
</script>
function verificarEmail() {
  let data = $("#email").serialize();
  $("#errorEmail").text("");
  $.ajax({
    method: "POST",
    url: '/verificarEmail',
    data: data
  })
  .done(function(respuesta) {
    if(respuesta == "Existe"){
      $("#errorEmail").text("El email ya se encuentra registrado.")
    }
   })
  .fail(function() {
    alert( "error" );
  })
}
$.ajax({ 
  type: "POST",
  data: "",
  dataType: 'json',
  url: "",
  success: function(data)
  {

  }
});
$(document).ready(function() 
{
  
});
function timeout(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

await timeout(1000); // pauses execution for 1000ms
const button = document.querySelector('#click-me');
button.addEventListener('click', (event) => {
  // Callback
  event.currentTarget.innerText = 'Hold still...';
  event.currentTarget.setAttribute("disabled", "");
});
const button = document.querySelector('#click-me');
button.addEventListener('click', (event) => {
  console.log(event);
});
const elements = document.querySelectorAll(CSS_SELECTOR);
const element = document.querySelector(CSS_SELECTOR);
Object.filter = function( obj, predicate) {
    let result = {}, key;

    for (key in obj) {
        if (obj.hasOwnProperty(key) && !predicate(obj[key])) {
            result[key] = obj[key];
        }
    }

    return result;
};
[{"id":"5d281009.e0ad3","type":"tab","label":"Aveva - Estándar","disabled":false,"info":""},{"id":"f1a0742b.b8c8a8","type":"SE_Aveva_Insight","z":"5d281009.e0ad3","name":"SEAvevaInsight","version":"2.1.0","useProxy":"no","url":"https://online.wonderware.eu/apis/upload/datasource","proxy":"","timeout":"120","logging":"1","loggingLevel":"error","fileSize":"10","sizeUnit":"MB","x":550,"y":60,"wires":[["53ec1f13.6136e"]]},{"id":"2ff99cf8.8c2be4","type":"SE_Modbus-Read","z":"5d281009.e0ad3","name":"SEModbusRead","version":"3.0.0","dataType":"HoldingRegister","adr":"1000","quantity":"12","rate":"1","rateUnit":"s","logging":"1","loggingLevel":"error","server":"7c2d00be.f0a75","alltags":"[{\"address\":\"1000\",\"tag\":\"MachineState\",\"type\":\"UINT\",\"isEnabled\":true},{\"address\":\"1001\",\"tag\":\"UtilReason\",\"type\":\"UINT\",\"isEnabled\":true},{\"address\":\"1002\",\"tag\":\"EquipmentAutomationValues\",\"type\":\"UDINT\",\"isEnabled\":true},{\"address\":\"1003\",\"tag\":\"\",\"type\":\"\",\"isEnabled\":false},{\"address\":\"1004\",\"tag\":\"DispositionReasons\",\"type\":\"UDINT\",\"isEnabled\":true},{\"address\":\"1005\",\"tag\":\"\",\"type\":\"\",\"isEnabled\":false},{\"address\":\"1006\",\"tag\":\"ProductionCounterMaquinawizard.GP1\",\"type\":\"REAL\",\"isEnabled\":true},{\"address\":\"1007\",\"tag\":\"\",\"type\":\"\",\"isEnabled\":false},{\"address\":\"1008\",\"tag\":\"ProductionCounterMaquinawizard.WP1\",\"type\":\"REAL\",\"isEnabled\":true},{\"address\":\"1009\",\"tag\":\"\",\"type\":\"\",\"isEnabled\":false},{\"address\":\"1010\",\"tag\":\"ProductionCounterMaquinawizard.RP1\",\"type\":\"REAL\",\"isEnabled\":true},{\"address\":\"1011\",\"tag\":\"\",\"type\":\"\",\"isEnabled\":false}]","x":100,"y":60,"wires":[["979a707c.68f3d"]]},{"id":"53ec1f13.6136e","type":"debug","z":"5d281009.e0ad3","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","x":790,"y":60,"wires":[]},{"id":"979a707c.68f3d","type":"function","z":"5d281009.e0ad3","name":"Data Cyclic or Event","func":"/***Descripción***\nSe envían datos cuando:\n- Cambia la Utilization Reason \n- Cada X tiempo\n*********************/\n//===Parametros======\nlet timeBlink = 60000; //Tiempo en ms cada cuanto se realiza el envío de datos\n//===================\n\nvar data = {};\nlet sendData = false;\nvar newDate = new Date();\nvar newStamp = newDate.getTime();\n//node.warn(newStamp);\nvar stampBlink = flow.get('stampBlink')||0;\nnode.warn(\"DiferenciaTiempos:\"+(stampBlink-newStamp));\n\nif ((newStamp)>stampBlink){\n    sendData = true;\n//     node.warn('SendDataCyclic: '+sendData )\n} \n\n// initialise the counter to 0 if it doesn't exist already\nvar nowUtilReason = msg.payload.data.UtilReason.value;\nvar pastUtilReason = flow.get('pastUtilReason')||0;\ndata = msg.payload;\nnode.warn('Now: '+nowUtilReason +', Past: '+pastUtilReason);\nif (nowUtilReason != pastUtilReason) {\n//    node.warn('Send Data');\n    sendData = true;\n    pastUtilReason = nowUtilReason;\n    flow.set('pastUtilReason',pastUtilReason);\n}\n\n//node.warn('sendData:'+sendData);\nif (sendData === true) {\n    stampBlink = newStamp + timeBlink;\n    flow.set('stampBlink',stampBlink);\n    msg.payload = data;\n    sendData = false;\n    node.warn(\"envío info\");\n} else {\n    msg = null;\n}\nreturn msg;","outputs":1,"noerr":0,"x":330,"y":60,"wires":[["f1a0742b.b8c8a8"]]},{"id":"7c2d00be.f0a75","type":"SE_Modbus-Client","name":"modbus","clienttype":"tcp","unitid":"1","bufferCommands":"1","tcpHost":"192.168.1.252","tcpPort":"502","tcpType":"DEFAULT","serialPort":"/dev/ttyUSB","serialType":"RTUBuffered","serialBaudrate":"19200","serialDatabits":"8","serialStopbits":"1","serialParity":"none","serialConnectionDelay":"100","commandDelay":100,"clientTimeout":10000,"reconnectTimeout":2000}]
function animationInterval(ms, signal, callback) {
  // Prefer currentTime, as it'll better sync animtions queued in the
  // same frame, but if it isn't supported, performance.now() is fine.
  const start = document.timeline
  ? document.timeline.currentTime
  : performance.now();

  function frame(time) {
    if (signal.aborted) return;
    callback(time);
    scheduleFrame(time);
  }

  function scheduleFrame(time) {
    const elapsed = time - start;
    const roundedElapsed = Math.round(elapsed / ms) * ms;
    const targetNext = start + roundedElapsed + ms;
    const delay = targetNext - performance.now();
    setTimeout(() => requestAnimationFrame(frame), delay);
  }

  scheduleFrame(start);
}
var dd               = lead.getAttr('alarmDD')*1; // + дней
var hh               = lead.getAttr('alarmHH')*1; // + часов 
var mm               = lead.getAttr('alarmMM')*1; // + минут
var utc              = lead.getAttr('utc');
var summerTimeOffset = lead.getAttr('summerTimeOffset'); 
var serverTimeOffset = 3; // Часовой пояс сервера (Москва) UTC(3)
var ms               = 60 * 60 * 1000; // количеством миллисекунд в 1 часе

/////////////////////////////////////////////////////////////////////////////
// 1. Текущая дата и время относительно сервера (Москва), в миллисекундах
/////////////////////////////////////////////////////////////////////////////

var serverDatetime = new Date(Date.now());

var dateString =
    serverDatetime.getFullYear() + "-" +
    ("0" + (serverDatetime.getMonth()+1)).slice(-2) + "-" +
    ("0" + serverDatetime.getDate()).slice(-2) + " " +
    ("0" + serverDatetime.getHours()).slice(-2) + ":" +
    ("0" + serverDatetime.getMinutes()).slice(-2);

lead.setAttr('serverDatetime', serverDatetime);
lead.setAttr('serverDatetimeAsText', dateString);

/////////////////////////////////////////////////////////////////////////////
// 2. Текущая дата и время пользователя по его местному часовому поясу
/////////////////////////////////////////////////////////////////////////////

// Отнимаем сдвиг на московское время, чтобы привести все к UTC(0)
// И потом добавляем сдвиг на часовой пояс пользователя и летнее время
var currentLocalDatetime = new Date(
          serverDatetime 
        - (serverTimeOffset * ms) 
        + utc * ms 
        + summerTimeOffset * ms
);

dateString =
    currentLocalDatetime.getFullYear() + "-" +
    ("0" + (currentLocalDatetime.getMonth()+1)).slice(-2) + "-" +
    ("0" + currentLocalDatetime.getDate()).slice(-2) + " " +
    ("0" + currentLocalDatetime.getHours()).slice(-2) + ":" +
    ("0" + currentLocalDatetime.getMinutes()).slice(-2);

lead.setAttr('currentLocalDatetime', currentLocalDatetime);
lead.setAttr('currentLocalDatetimeAsText', dateString);

/////////////////////////////////////////////////////////////////////////////
// 3. Расчитываем время будильника в часовом поясе пользователя
/////////////////////////////////////////////////////////////////////////////

var localAlarmDatetime = new Date (
          currentLocalDatetime                         // текущее местное время
        - currentLocalDatetime.getHours() * 60 * 1000  // отнимаем часы,
        - currentLocalDatetime.getMinutes()            // минуты
        - currentLocalDatetime.getSeconds()            // и cекунды, т.е. теперь это 00:00
        + 24 * dd * ms                                 // добавляем дни, если надо
);

// Устанавливем время будильника
localAlarmDatetime.setHours(hh);
localAlarmDatetime.setMinutes(mm);
localAlarmDatetime.setSeconds(0);
  
dateString = 
    localAlarmDatetime.getFullYear() + "-" +
    ("0" + (localAlarmDatetime.getMonth()+1)).slice(-2) + "-" +
    ("0" + localAlarmDatetime.getDate()).slice(-2) + " " +
    ("0" + localAlarmDatetime.getHours()).slice(-2) + ":" +
    ("0" + localAlarmDatetime.getMinutes()).slice(-2);

lead.setAttr('localAlarmDatetime', localAlarmDatetime);
lead.setAttr('localAlarmDatetimeAsText', dateString);

///////////////////////////////////////////////////////////////////////////////////
// 4. Расчитываем время будильника в часовом поясе сервера для установки триггера
///////////////////////////////////////////////////////////////////////////////////

var d = new Date(
        localAlarmDatetime
        - utc * ms 
        - summerTimeOffset * ms
        + (serverTimeOffset * ms)    
);

var runTriggerAt = 
    d.getFullYear() + "-" +
    ("0" + (d.getMonth()+1)).slice(-2) + "-" +
    ("0" + d.getDate()).slice(-2) + " " +
    ("0" + d.getHours()).slice(-2) + ":" +
    ("0" + d.getMinutes()).slice(-2) + ":00";
                                              
lead.setAttr('runTriggerAt', runTriggerAt);
$().ready(function() {
  $('[type="file"]').change(function() {
    var fileInput = $(this);
    if (fileInput.length && fileInput[0].files && fileInput[0].files.length) {
      var url = window.URL || window.webkitURL;
      var image = new Image();
      image.onload = function() {
        alert('Valid Image');
      };
      image.onerror = function() {
        alert('Invalid image');
      };
      image.src = url.createObjectURL(fileInput[0].files[0]);
    }
  });
});
const arr = array.slice().sort((a, b) => b.time - a.time)
javascript:(function(s){try{s=document.selection.createRange().text}catch(_){s=document.getSelection()}prompt('',document.title+" "+'\n'+location+'\n'+s)})()
javascript:(function(s){try{s=document.selection.createRange().text}catch(_){s=document.getSelection()}prompt('','\n'+location+'\n'+s)})()
// methods:
insertSomething: function(insert) {
  const self = this;
  var tArea = this.$refs.yourTextarea;
  // filter:
  if (0 == insert) {
    return;
  }
  if (0 == cursorPos) {
    return;
  }

  // get cursor's position:
  var startPos = tArea.selectionStart,
    endPos = tArea.selectionEnd,
    cursorPos = startPos,
    tmpStr = tArea.value;

  // insert:
  self.txtContent = tmpStr.substring(0, startPos) + insert + tmpStr.substring(endPos, tmpStr.length);

  // move cursor:
  setTimeout(() => {
    cursorPos += insert.length;
    tArea.selectionStart = tArea.selectionEnd = cursorPos;
  }, 10);
}
console.log('one', 'two')
input[type="text"] {
    /* Flexibility */
    box-sizing: border-box;
    width: 100%;

    /* Styling */
    padding: .4em .55em;
    font-size: inherit;
    font-family: inherit;
    color: inherit;
    border: 0;
    border-radius: .25em;
    outline: none
}
// Of course, before that, you should install @babel/plugin-proposal-optional-chaining
// npm i -D @babel/plugin-proposal-optional-chaining


// in nuxt.config.js
{
  // ...
  build: {
    // ....
    babel: {
      plugins: [
        '@babel/plugin-proposal-optional-chaining'
      ]
    }
  }
}


// Example object
const macAyres = {
  tours: {
    nearMe: {
      sanFrancisco: {
        date: 'Sun Oct 27',
        location: 'The Regency Ballroom',
        cost: '30.00',
      },
    },
  }
}



// 1. Ternary Operator to Check for null/undefined
const concertLocation = (macAyres.tours && 
  						 macAyres.tours.nearMe &&
						 macAyres.tours.nearMe.sanJose) 
	? macAyres.tours.nearMe.sanJose.location 
	: undefined;



// 2. Oliver Steele’s Nested Object Access Pattern
const concertLocation = (macAyres.tours.nearMe.sanJose || {}).location;

/* Explanation: 
As the || operator breaks return the truthy value encountered, the above expression would return macAyres.tours.nearMe.sanJose if it is not null/undefined, otherwise {}.
In this case, we will be accessing location from an empty object, and not from undefined, so we will avoid getting the error.
*/



// 3. Array Reduce
const paths = ['tours', 'nearMe', 'sanJose', 'location'];
const location = paths.reduce((object, path) => {
    return (object || {})[path]; // Oliver Steele's pattern
}, macAyres)




// 4. Try/Catch Helper Function With ES6 Arrow Function
function getSafe(fn, defaultVal) {
    try {
        return fn();
    } catch (e) {
        return defaultVal;
    }
}

// use it like this
getSafe(() => obj.a.lot.of.properties);

// or add an optional default value
getSafe(() => obj.a.lot.of.properties, 'nothing');
const fetchText = async (url) => {
        const response = await fetch(url);
        return await response.text();
        console.log(text)
      }
    	fetchText();
useEffect(() => {
  requestPets();
}, []);

async function requestPets() {
  const res = await fetch(API_URL);
  const json = await res.json();
  setPets(json.pets)
}
// Async function example:
async function getCurrencies() {
  // Use fetch to get data from API
  // and assign it to a variable:
  const data = await fetch('https://currencyapi.net/api/v1/rates?key=7zq3xkh2qeZcnvFhfyDyFlvqx4EmQ7R3N1qq')
  // Convert the response to JSON
  // and assign it to a variable:
  const json = await data.json()

  // Log the JSON to console:
  console.log(json)
}
const newCandy = new Candy();
newCandy();
        data.map((item) => {
            const propertyName = item.productName;

            return (<div className="flex-container card" key={item._id}>
                <div className="content">
                    <p>{propertyName}</p>
                </div>
            </div>)
        })
const method1 = () => console.log('Does something');
const method2 = () => console.log('Does another thing');
const method3 = () => console.log('Does entirely other thing');
 
const switchObj = {
  a: method1,
  b: method2,
  c: method3
};
 
const init = (option) => {
	console.log('instead of switch case, use an object');
  	console.log(switchObj[option]());
}
 
init('a');
​//Search a value with incorrect spaces.. 

var input = 'gu ara nteed rate';
var table = 'core_company';
var field = 'name';

var searchName = input.replace(/\s/g, '').toLowerCase();
var gr = new GlideRecord(table);
gr.addEncodedQuery(field + 'ISNOTEMPTY');
gr.query();
while (gr.next()) {
  	var fieldString = gr.getValue(field).replace(/\s/g, '').toLowerCase();
 
    if (fieldString.indexOf(searchName) != -1)
        gs.info('FOUND: "' + gr[field].getDisplayValue() + '"');
}
/*
Example:

2021-03-15T18:05:40.674Z: FOUND: "Guaranteed Rate Insurance"
2021-03-15T18:05:40.677Z: FOUND: "Guaranteed Rate, Inc2"
2021-03-15T18:05:40.678Z: FOUND: "Guaranteed Rate, Inc."
2021-03-15T18:05:40.680Z: FOUND: "Guaranteed Rate, Inc"
2021-03-15T18:05:40.682Z: FOUND: "Guaranteed Rate Affinity"

*/
!function(window){
  var $q = function(q, res){
        if (document.querySelectorAll) {
          res = document.querySelectorAll(q);
        } else {
          var d=document
            , a=d.styleSheets[0] || d.createStyleSheet();
          a.addRule(q,'f:b');
          for(var l=d.all,b=0,c=[],f=l.length;b<f;b++)
            l[b].currentStyle.f && c.push(l[b]);

          a.removeRule(0);
          res = c;
        }
        return res;
      }
    , addEventListener = function(evt, fn){
        window.addEventListener
          ? this.addEventListener(evt, fn, false)
          : (window.attachEvent)
            ? this.attachEvent('on' + evt, fn)
            : this['on' + evt] = fn;
      }
    , _has = function(obj, key) {
        return Object.prototype.hasOwnProperty.call(obj, key);
      }
    ;

  function loadImage (el, fn) {
    var img = new Image()
      , src = el.getAttribute('data-src');
    img.onload = function() {
      if (!! el.parent)
        el.parent.replaceChild(img, el)
      else
        el.src = src;

      fn? fn() : null;
    }
    img.src = src;
  }

  function elementInViewport(el) {
    var rect = el.getBoundingClientRect()

    return (
       rect.top    >= 0
    && rect.left   >= 0
    && rect.top <= (window.innerHeight || document.documentElement.clientHeight)
    )
  }

    var images = new Array()
      , query = $q('img.lazy')
      , processScroll = function(){
          for (var i = 0; i < images.length; i++) {
            if (elementInViewport(images[i])) {
              loadImage(images[i], function () {
                images.splice(i, i);
              });
            }
          };
        }
      ;
    // Array.prototype.slice.call is not callable under our lovely IE8 
    for (var i = 0; i < query.length; i++) {
      images.push(query[i]);
    };

    processScroll();
    addEventListener('scroll',processScroll);

}(this);
const app = require('express')()
const port = 3000

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

let rand = Math.random()
rand < 0.5 ? gender = 0 : gender = 1
let emoji = `${gender ? '👩‍💼' : '👨‍💼'}`

app.listen(port, () => {
  console.log(`listening on http://localhost:${port}`)
})
javascript:(d=>{var css=`:root{background-color:#f1f1f1;filter:invert(1) hue-rotate(180deg)}img:not([src*=".svg"]),picture,video{filter: invert(1) hue-rotate(180deg)}`,style,id="dark-mode",ee=d.getElementById(id);if(null!=ee)ee.parentNode.removeChild(ee);else {style = d.createElement('style');style.type="text/css";style.id=id;if(style.styleSheet)style.styleSheet.cssText=css;else style.appendChild(d.createTextNode(css));(d.head||d.querySelector('head')).appendChild(style)}})(document)
const apiData = () => {
    fetch(API_URL)
      .then((res) => {
        return res.json()
    }).then((data) => {
        fetchedData(data)
    })
}

fetchedData = (apiData) => {
  console.log(apiData)
}
let arr = [
    { name:"string 1", value:"this", other: "that" },
    { name:"string 2", value:"this", other: "that" }
];

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);
let cities = [
    {name: 'Los Angeles', population: 3792621},
    {name: 'New York', population: 8175133},
    {name: 'Chicago', population: 2695598},
    {name: 'Houston', population: 2099451},
    {name: 'Philadelphia', population: 1526006}
];

let bigCities = cities.filter(city => city.population > 3000000);
console.log(bigCities);

/* ES5
let bigCities = cities.filter(function (e) {
    return e.population > 3000000;
});
*/

Code language: JavaScript (javascript)
    isNumber(evt) {
      evt = evt ? evt : window.event;
      let charCode = evt.which ? evt.which : evt.keyCode;
      if (
        charCode > 31 &&
        (charCode < 48 || charCode > 57) &&
        charCode !== 46
      ) {
        evt.preventDefault();
      } else {
        return true;
      }
    },
Make a hook on "eventDidMount" : link

an search in arg.el for the item.

arg.el.find(".fc-title")  // jQuery, geht aber auch ohne
get the height

.height()  // jQuery, geht aber auch ohne
Summary:

eventDidMount:function(argE) { 
    h = arg.el.find(".fc-title").height(); 
    if(typeof(h) != "undefined") {
       if (h > 20) {
       // ... your code
       }
    }
    return (argE.event._def.title;); // dont forget the reason for this hook
},  // 
add_filter( 'style_loader_src',  'sdt_remove_ver_css_js', 9999, 2 );
add_filter( 'script_loader_src', 'sdt_remove_ver_css_js', 9999, 2 );

function sdt_remove_ver_css_js( $src, $handle ) 
{
    $handles_with_version = [ 'style','general' ]; // <-- Adjust to your needs!
    if ( strpos( $src, 'ver=' ) && ! in_array( $handle, $handles_with_version, true ) )
        $src = remove_query_arg( 'ver', $src );
    return $src;
}
const languages = {
  english: "50%",
  spanish: "100%",
  japanese: "what a weeb lol",
};

function getLanguages({ english, spanish, japanese, chinese = "0%" }) {
  console.log(`
    ${english}
    ${spanish}
    ${japanese}
    ${chinese}
    `);
}

getLanguages(languages);
Math.floor(Math.random() * 6) + 1;
function toggleScrollLock(open) {
    var offset = window.scrollY;
    var body = document.querySelector('body');

    if (open) {
        // Fix the body when menu is open
        body.classList.add('fixed');
        body.style.top = `-${offset}px`;
    } else {
        // Scroll back to original position upon close
        const scrollY = document.body.style.top;
        body.classList.remove('fixed');
        body.style.top = '';
        window.scrollTo(0, parseInt(scrollY || '0') * -1);
    }
}
const { DateTime } = require('luxon')
const pluginRss = require('@11ty/eleventy-plugin-rss')
const syntaxHighlight = require('@11ty/eleventy-plugin-syntaxhighlight')
const pluginTOC = require('eleventy-plugin-nesting-toc')
const eleventyNavigationPlugin = require('@11ty/eleventy-navigation')
const times = x => f => {
  if (x > 0) {
    f()
    times (x - 1) (f)
  }
}

// use it
times (3) (() => console.log('hi'))

// or define intermediate functions for reuse
let twice = times (2)

// twice the power !
twice (() => console.log('double vision'))
const test = test;
var columns=['a','b']
var data = [{a:'John',b:'Smith'},{a:'Sam',b:'Malone'}]

var d1=columns.map(c => {
  return ` <td>
      <table>
        <tr><th>${c}</th></tr>
        ${data.map(r => ` <tr><td>${ r[c]}</td></tr>`).join('')}
       
      </table>
    </td>`
})
var table1=`<table>
  <tr>
   ${d1.join('')}
    
  </tr>
</table>`;
document.getElementById('app').innerHTML=table1;
$(document).ready(function() {

  

  var $scene = $(".scene"),

      $content = $(".content"),

      $back = $(".back"),

      $backBgs = $(".back__bg"),

      $front = $(".front"),

      $frontBgs = $(".front__bg"),

      $menuBlock = $(".menu__block"),

      $svgPath = $(".menu__block-svgPath"),

      animating = false,

      menuActive = false,

      menuAnimTime = 600,

      blockAnimTime = 00,
15
      $sliderCont = $(".menu-slider__content"),

      curSlide = 1,

      sliderXDiff = 0,

      curPage = 1,

      nextPage = 0,
(function() {

  function $$(selector, context) {

    var context = context || document;

    var elements = context.querySelectorAll(selector);

    var nodesArr = [].slice.call(elements);

    return nodesArr.length === 1 ? nodesArr[0] : nodesArr;

  };

​

  var $status = $$('.dl-status');

  var $statusNumbers = $$('.dl-status__numbers');

​

  var $dlSVG = $$('.dl-svg');

​

  var $circle = $$('.dl-svg__circle');

  var $arrMain = $$('.dl-svg__arrow-main');

  var $arrSides = $$('.dl-svg__arrow-side');

  var $rotater = $$('.dl-svg__rotater');
function insertText(data) {
	var cm = $(".CodeMirror")[0].CodeMirror;
	var doc = cm.getDoc();
	var cursor = doc.getCursor(); // gets the line number in the cursor position
	var line = doc.getLine(cursor.line); // get the line contents
	var pos = {
		line: cursor.line
	};
	if (line.length === 0) {
		// check if the line is empty
		// add the data
		doc.replaceRange(data, pos);
	} else {
		// add a new line and the data
		doc.replaceRange("\n" + data, pos);
	}
}
  const target = useRef<HTMLDivElement>(null);

  const listenScrollEvent = (event) => {
    const toLeft = event.deltaY < 0 && target.current.scrollLeft > 0;
    const toRight =
      event.deltaY > 0 &&
      target.current.scrollLeft <
        target.current.scrollWidth - target.current.clientWidth;

    if (toLeft || toRight) {
      event.preventDefault();
      event.stopPropagation();

      target.current.scrollLeft += event.deltaY;
    }
  };

  return (
    <div ref={target} onWheel={listenScrollEvent}>
const target = document.querySelector('div')

target.addEventListener('wheel', event => {
  const toLeft  = event.deltaY < 0 && target.scrollLeft > 0
  const toRight = event.deltaY > 0 && target.scrollLeft < target.scrollWidth - target.clientWidth

  if (toLeft || toRight) {
    event.preventDefault()
    event.stopPropagation()
    
    target.scrollLeft += event.deltaY
  }
})
function full_stack_developer() {
    full_stack_developer();
}
console.clear();

​

setTimeout(function(){

  document.querySelector('input[type="checkbox"]').setAttribute('checked',true);

},0);

/*

​

// Javascript was initially used, but wasn't really necessary. Javascript droppped, but left here for archival purposes.

​
10
var todoTemplate = function(id){ 

  return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 200 25" class="todo__icon">

    <defs>

      <mask id="myMask${id}" maskUnits="userSpaceOnUse" x="0" y="0">

        <g stroke="#FFF" fill="none">

          <path class="todo__line" d="M21 12.3h8"/>
16
          <path class="todo__box" d="M21 12.7v5c0 1.3-1 2.3-2.3 2.3H8.3C7 20 6 19 6 .7V7.3C6 6 7 5 8.3 5h10.4C20 5 21 6 21 7.3v5.4"/>
17
          <path class="todo__check" d="M10 13l2 2 5-5"/>
$('.burger, .overlay').click(function(){

  $('.burger').toggleClass('clicked');

  $('.overlay').toggleClass('show');

  $('nav').toggleClass('show');

  $('body').toggleClass('overflow');

});
const navTabs = document.querySelectorAll("#nav-tabs > a");

navTabs.forEach((tab) => {

  tab.addEventListener("click", () => {

    navTabs.forEach((tab) => {

      tab.classList.remove("active");

    });

    tab.classList.add("active");

  });

});

​
// Get a reference to the <path>

var path = document.querySelector('#star-path');

​

// Get length of path... ~7px in this case
5
var pathLength = path.getTotalLength();

​
7
// Make very long dashes (the length of the path itself)

path.style.strokeDasharray = pathLength + ' ' + pathLength;

​

// Offset the dashes so the it appears hidden entirely

path.style.strokeDashoffset = pathLength;

​

// Jake Archibald says so

// https://jakearchibald.com/2013/animated-line-drawing-svg/

path.getBoundingClientRect();

​

// When the page scrolls...
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'})
 
    }
const fs = require('fs');
const JSONToFile = (obj, filename) =>
  fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));

JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'
function Foo() {
  this.a = () => 1;
  this.b = () => 2;
}
Foo.prototype.c = () => 3;
functions(new Foo()); // ['a', 'b']
functions(new Foo(), true); // ['a', 'b', 'c']
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; }); 
const apiData = () => {
    fetch(API_URL)
      .then((res) => {
        return res.json()
    }).then((data) => {
        fetchedData(data)
    })
}

fetchedData = (apiData) => {
  console.log(apiData)
}
Not every case you can replace a looping method for the short one, but if it does then do it.
Instead of:
let names = [‘Amy’, ‘James, ‘David’, ‘John’];
for (let i = 0; i < names.length; i++) {}
Do this:
let names = [‘Amy’, ‘James, ‘David’, ‘John’];
for (let name of names) {}
In case the indexes matter:
for (let [index, name] of names.entries()) {}
const NotFoundPage = () => {
  return (
    <h1>This is a test</h1>
  )
}

export default NotFoundPage
console.log("hello world");
const handleSubmit = (e: any) => {
    e.preventDefault()
    props.history.push('/mypath') // указывает путь куда напралять после подтвердения формы
}

<form onSubmit={handleSubmit}>
  <button type='submit'>Submit form</button>
</form>
hello = () => {
  return "Hello World!";
}
var hello = "world";
print(hello);
const idGenerator = () => {
        setId(Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000)
};
            this.get("http://127.0.0.1:5000/v1/todos", () => ({
                id: 1,
                records: [
                    { id: 1, name: "Walk the dog" },
                    { id: 2, name: "Take out the trash" },
                    { id: 3, name: "Work out" },
                ],
            }))
const scale = (num, in_min, in_max, out_min, out_max) => {
  return (num - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
var filtered = [...mySet].filter((x) => x > 3) // [4, 5]
function merge(...objects) {
  let masterObj = {}

  // iterate over `objects` merging each
  // into `masterObj` to generate flattened
  // object
  for (let i = 0; i < objects.length; i++) {
    let obj = objects[i]
    for (let key in obj) masterObj[key] = obj[key]
  }

  return masterObj
}

let merged = merge(...objectsList)

// output:
// {count:5, delay:2000, early:false, message:'Hello'}
console.log(merged)
const manipulateList = (list) => {
  // defensively copy list
  const copiedList = [...list]

  // do something with copiedList
}
const notify = (msg, { type = 'info', timeout, close = true } = {}) => {
  // display notification
}

notify('Hi!')
notify('Hi!', { type: 'error' })
notify('Hi!', { type: 'warn', close: false })
/**
   * Convert image to Base64 format
   */
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
      return Promise.resolve(reader.result)
    });
  }

// await getBase64($('input[name=file]')[0].files[0]).then(
    //   data => {
    //     base64 = data;
    //   }
    // );
import { Directive, ElementRef, Renderer } from '@angular/core';

@Directive({
    selector: '[appChbgcolor]'
})
export class ChangeBgColorDirective {

    constructor(private el: ElementRef, private renderer: Renderer) {
        this.ChangeBgColor('red');
    }

    ChangeBgColor(color: string) {

        this.renderer.setElementStyle(this.el.nativeElement, 'color', color);
    }
}
<head>
    <script src="video.js"></script>
    <script src="vectorly-videojs.js"> </script>
</head>
<body>
    
    <video id="my-video" class="video-js" data-setup="{}" src="video.mp4" ></video>
  
    <script>
        videojs.registerPlugin('vectorlyPlugin', vectorly.videoJSPlugin);

        const player = videojs('my-video');

        player.vectorlyPlugin({width: 1280, height: 720}); // Upscale to 720p (from 240p)
    </script>
</body>
const myArray = [1,2,3,1,5,8,1,2,9,4];
const unique = [...new Set(myArray)]; // [1, 2, 3, 5, 8, 9, 4]

const myString = ["a","b","c","a","d","b"];
const uniqueString = [...new Set(myString)]; //["a", "b", "c", "d"]
new GlideQuery('sys_user')
    .where('last_name', 'Luddy')
    .selectOne('first_name')
    .ifPresent(function (user) {
       gs.info(user.first_name);
   });
// Fred
// Find user if they exist, otherwise return user with first_name 'Nobody'
var user = new GlideQuery('sys_user')
    .where('last_name', 'Luddy')
    .selectOne('first_name')
    .orElse({ first_name: 'Nobody' });

// Find user, otherwise throw an Error that the user couldn't be found
var user = new GlideQuery('sys_user')
    .where('last_name', 'Luddy')
    .selectOne('first_name')
    .get(); // this method can throw if no record is found

// Does a given user exist? Assign boolean to userExists
var userExists = new GlideQuery('sys_user')
   .where('last_name', 'Luddy')
    .selectOne('first_name')
    .isPresent();
window.location.href = '...';
$.ajax({
	type:"POST",
	data:sendstring,
	dataType:'json',
	url:"",
	success:function(data)
	{

    }
});	
if (window.confirm("Alert text goes here?"))
const user = {
  id: 3,
  name: 'Ron',
}

const updatedUser = { ...user, isLoggedIn: true }

console.log(updatedUser)
var dataset = ee.ImageCollection('COPERNICUS/S2_SR')
                  .filterDate('2021-01-01', '2021-02-12')
                  .filterBounds(Zone)
                  .filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',20))
                  .map(rescale);
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/nprogress.css" />

<script src="https://cdn.rawgit.com/rikmms/progress-bar-4-axios/0a3acf92/dist/index.js"></script>


<img id="img">

<script>

loadProgressBar();

const url = 'https://fetch-progress.anthum.com/30kbps/images/sunrise-baseline.jpg';

function downloadFile(url) {
  axios.get(url, {responseType: 'blob'})
    .then(response => {
      const reader = new window.FileReader();
      reader.readAsDataURL(response.data); 
      reader.onload = () => {
        document.getElementById('img').setAttribute('src', reader.result);
      }
    })
    .catch(error => {
      console.log(error)
    });
}

downloadFile(url);

</script>
map.addLayer({
    'id': '3d-buildings',
    'source': 'composite',
    'source-layer': 'building',
    'filter': ['==', 'extrude', 'true'],
    'type': 'fill-extrusion',
    'minzoom': 15,
    'paint': {
        'fill-extrusion-color': '#666',
        'fill-extrusion-height': ['interpolate', ['linear'], ['zoom'], 15, 0, 15.05, ['get', 'height']],
        'fill-extrusion-base': ['interpolate', ['linear'], ['zoom'], 15, 0, 15.05, ['get', 'min_height']],
        'fill-extrusion-opacity': 0.9,
    }
});
(function() {
    var aa = document.querySelectorAll("input[type=checkbox]");
    for (var i = 0; i < aa.length; i++){
      if (!aa[i].checked) {
        aa[i].click();
        }
    }
})()
const fs = require('fs');

// Create a readable stream in chunks inside buffer
// HighWaterMark => the size of a chunck
let readable = fs.createReadStream(_dirname + '/path.txt', 
                         { encoding: 'utf8', highWaterMark: 32 * 1024 });

// Writable stream
let writable = fs.createWriteStream(_dirname + '/pathCopy.txt');

// Stream is an event emitter 
readable.on('data', chunk => {
    writable.write(chunk);
})
jaimes-mbp:SMR jaimemontoya$ brew tap mongodb/brew
Updating Homebrew...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
No changes to formulae.

==> Tapping mongodb/brew
Cloning into '/usr/local/Homebrew/Library/Taps/mongodb/homebrew-brew'...
remote: Enumerating objects: 86, done.
remote: Counting objects: 100% (86/86), done.
remote: Compressing objects: 100% (76/76), done.
remote: Total 145 (delta 41), reused 21 (delta 10), pack-reused 59
Receiving objects: 100% (145/145), 30.18 KiB | 2.16 MiB/s, done.
Resolving deltas: 100% (68/68), done.
Tapped 6 formulae (33 files, 83.0KB).
jaimes-mbp:SMR jaimemontoya$ brew install mongodb-community@4.2
==> Installing mongodb-community from mongodb/brew
==> Downloading https://fastdl.mongodb.org/osx/mongodb-macos-x86_64-4.2.3.tgz
######################################################################## 100.0%
==> Caveats
To have launchd start mongodb/brew/mongodb-community now and restart at login:
  brew services start mongodb/brew/mongodb-community
Or, if you don't want/need a background service you can just run:
  mongod --config /usr/local/etc/mongod.conf
==> Summary
🍺  /usr/local/Cellar/mongodb-community/4.2.3: 21 files, 304.3MB, built in 1 minute 54 seconds
jaimes-mbp:SMR jaimemontoya$ brew services start mongodb-community@4.2
==> Tapping homebrew/services
Cloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-services'...
remote: Enumerating objects: 88, done.
remote: Counting objects: 100% (88/88), done.
remote: Compressing objects: 100% (47/47), done.
remote: Total 691 (delta 31), reused 69 (delta 25), pack-reused 603
Receiving objects: 100% (691/691), 192.79 KiB | 1.68 MiB/s, done.
Resolving deltas: 100% (270/270), done.
Tapped 1 command (39 files, 266.3KB).
==> Successfully started `mongodb-community` (label: homebrew.mxcl.mongodb-community)
jaimes-mbp:SMR jaimemontoya$ ps aux | grep -v grep | grep mongod
jaimemontoya     17763   0.1  0.2  5544164  38300   ??  S     8:11AM   0:00.65 /usr/local/opt/mongodb-community/bin/mongod --config /usr/local/etc/mongod.conf
jaimes-mbp:SMR jaimemontoya$ 
{
  "scripts": {
    "build": "tsc --project ./",
    "start:dev": "nodemon src/server.ts",
    "start:prod": "node dist/server.js"
  }
}
import React, { useState } from "react";

import PropTypes from "prop-types";

const App = () => {
  const initialAge = 3;
  const initialSalary = 24000;

  const [age, setAge] = useState(initialAge);
  const [salary, setSalary] = useState(initialSalary);

  const incrementAge = () =>
    setAge((prevAge) => {
      setAge(prevAge + 1);
    });

  const resetAge = () => {
    setAge(initialAge);
  };

  const decrementAge = () => {
    setAge((prevAge) => {
      setAge(prevAge - 1);
    });
  };

  const incrementSalary = () => {
    setSalary((prevSalary) => {
      setSalary(prevSalary + 5000);
    });
  };
  const resetSalary = () => {
    setSalary(initialSalary);
  };
  const decrementSalary = () => {
    setSalary((prevSalary) => {
      setSalary(prevSalary - 100);
    });
  };

  return (
    <React.Fragment>
      <MemoizedComponentOne text="Age" age={age} />
      <Button
        handleClick={() => {
          incrementAge();
        }}>
        Increment Age
      </Button>
      <Button
        handleClick={() => {
          resetAge();
        }}>
        Reset Age
      </Button>
      <Button
        handleClick={() => {
          decrementAge();
        }}>
        Decrement Age
      </Button>
      <MemoizedComponentTwo text="Salary" salary={salary} />
      <Button
        handleClick={() => {
          incrementSalary();
        }}>
        Increment Salary
      </Button>
      <Button
        handleClick={() => {
          resetSalary();
        }}>
        Reset Salary
      </Button>
      <Button
        handleClick={() => {
          decrementSalary();
        }}>
        Decrement Salary
      </Button>
    </React.Fragment>
  );
};

export default App;

function ComponentOne({ text, age }) {
  return (
    <>
      <p>
        {text} - {age}
      </p>
    </>
  );
}
export const MemoizedComponentOne = React.memo(ComponentOne);

ComponentOne.propTypes = {
  text: PropTypes.string,
  age: PropTypes.number,
};
function ComponentTwo({ text, salary }) {
  return (
    <div>
      <p>
        {text} - {salary}
      </p>
    </div>
  );
}

ComponentTwo.propTypes = {
  text: PropTypes.string,
  salary: PropTypes.number,
};

export const MemoizedComponentTwo = React.memo(ComponentTwo);

const Button = ({ handleClick, children }) => {
  return <button onClick={handleClick}>{children}</button>;
};

Button.propTypes = {
  children: PropTypes.string,
  handleClick: PropTypes.func,
};

export const MemoizedButton = React.memo(Button);
import React, { Component, useRef } from "react";

import PropTypes from "prop-types";

export default class App extends Component {
  constructor(props) {
    super(props);

    this.myref = React.createRef();
    this.myrefSecondInstance = React.createRef();
    this.childref = React.createRef();

    this.state = {
      defaultOrNew: "default",
      firstNameDefault: "Arhan",
      lastNameDefault: "Kamra",
      firstName: this.myref.value,
    };
  }

  static propTypes = {
    prop: PropTypes,
  };

  componentDidMount() {
    this.myref.current.focus();
    this.childref.current.me();
  }

  handleClick = () => {
    this.myref.current.focus();
  };

  handleClickSecondInstance = () => {
    this.myrefSecondInstance.current.focus();
  };

  handleClickBlur = () => {
    this.myref.current.blur();
  };

  handleClickBlurSecondInstance = () => {
    this.myrefSecondInstance.current.blur();
  };

  changeName = () => {
    this.setState(() => {
      return {
        defaultOrNew: "new",
        firstNameDefault: this.myref.current.value,
        lastNameDefault: this.myrefSecondInstance.current.value,
        firstName: this.myref.current.value,
        lastName: this.myrefSecondInstance.current.value,
      };
    });
  };

  render() {
    return (
      <div className="app">
        <input
          type="text"
          onChange={this.changeName}
          defaultValue={this.state.firstNameDefault}
          ref={this.myref}
        />
        <input
          type="text"
          onChange={this.changeName}
          defaultValue={this.state.lastNameDefault}
          ref={this.myrefSecondInstance}
        />
        <button onClick={this.handleClick}>Focus input</button>
        <button onClick={this.handleClickBlur}>Remove focus</button>
        <button onClick={this.handleClickSecondInstance}>Focus inputSecondInstance</button>
        <button onClick={this.handleClickBlurSecondInstance}>RemoveSecondInstance focus</button>
        <p>
          Hi my <strong>{this.state.defaultOrNew}</strong> name is {this.state.firstNameDefault}{" "}
          {this.state.middleNameDefault} {this.state.lastNameDefault}
        </p>
        <Child ref={this.childref} />
      </div>
    );
  }
}

class Child extends Component {
  me = () => {
    console.log("sophisticated coder");
    window.alert("xyz abc");
  };

  render() {
    return <div>{4 + 4}</div>;
  }
}
export function Child() {
  const inputRef = useRef();
  console.log(inputRef.current);

  return (
    <div>
      <input type="text" defaultValue="default value" ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>Focus</button>
    </div>
  );
}
	
var item = {name: "tom", text: "tasty"}
var array = [{}]
if (!array.find(o => o.name === 'tom' && o.text === 'tasty'))
    array.push(item)
var arrayObj = [{name:"bull", text: "sour"},
    { name: "tom", text: "tasty" },
    { name: "tom", text: "tasty" }
]
var index = arrayObj.findIndex(x => x.name=="bob"); 
// here you can check specific property for an object whether it exist in your array or not

index === -1 ? arrayObj.push({your_object}) : console.log("object already exists")
 
function FizzBuzz(val1, val2, range) {
    //Init the Array
    let returnArray = [];
    //Set the first value to 0
    returnArray[0] = 0;
    
    //Do fizz buzz from 1 to range. Perform modulus on each number.
    //Use a ternary to determine the value. 
    for (let i = 1; i <= range; i++) {
        returnArray[i] = ((i % val1 == 0 ? 'Fizz' : '') + (i % val2 == 0 ? 'Buzz' : '') || i);
    }
    //Return the Array
    return returnArray;
}
    /* return content of input field to variable text */
var text = document.getElementById("text");

/* return button to variable btn */
var btn = document.getElementById("btn");

/* call function on button click */
btn.onclick = function() {
  text.select();    
  document.execCommand("copy");
}
const collator = new Intl.Collator(undefined, {
    usage: 'sort',
    numeric: true
})

const simple = ['a1', 'a12', 'a2']
simple.sort(collator.compare)
// => ['a1', 'a2', 'a12']

const objects = [{"id": "a1"}, {"id": "a12"}, {"id": "a2"}]
const by = (key) => (a, b) => collator.compare(a[key], b[key])
objects.sort(by('id'))
// => [{id: 'a1'}, {id: 'a2'}, {id: 'a12'}]
function loadScript(src, attrs = {}) {
  if (typeof document !== 'undefined') {
    const script = document.createElement('script')
    script.async = true
    script.defer = true
    Object.keys(attrs).forEach(attr => script.setAttribute(attr, attrs[attr]))
    script.src = src
    document.body.appendChild(script)
  }
}
sudo forever start --sourceDir /opt/bitnami/projects/nesk_back -c "npm run prod" /

function getWebviewContent(uri) {
return `<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel='stylesheet' href='`+ uri + `' /> //This is the addition
    <title>Example Webview</title>
</head>
<body>
 <h1>This works!</h1>
 //Add some custom HTML here
   </body>
   </html>`;
}
var readline = require("readline");
var rl = readline.createInterface({input: process.stdin, output: process.stdout});

var program = function(){
    rl.question("type question", function(answer) {
        switch (answer){
            case "option 1":
                //action 1;
                break;
            case "exit option":
            	//previous action
            	return rl.close();
            default:
                //default action
        }
        program();
    });
}

program();
stripTags: (input) => {
        return input.replace(/<(?:.|\n)*?>/gm, '')
    }
truncate: (str, len) => {
        if (str.length > len && str.length>0) {
            let new_str = str + ' '
            new_str = str.substr(0, len)
            new_str = str.substr(0, new_str.lastIndexOf(' '))
            new_str = new_str.length > 0 ? new_str : str.substr(0, len)
            return new_str + '...'
        }
        return str
    }
const isValidJSON = string => {
  try {
    JSON.parse(string);
    return true;
  } catch (error) {
    return false;
  }
};
let check1 = isValidJSON(‘{“title”: “javascript”, “price”: 14}’); // true
let check2 = isValidJSON(‘{“title”: “javascript”, “price”: 14, subtitle}’); // false
const images = Array.from(document.querySelectorAll('.stretch img'));
images.map((img) => {
	img.onload = function() {
		let height = img.closest('.elementor-widget-wrap').offsetHeight
  		img.style = 'height: ' + height + 'px; object-fit: cover'
	}
})
key={`${button.text}-${button.bootstrapWidth}-${i}`}
//longhand
if (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') {
    //logic
}
//shorthand
if (['abc', 'def', 'ghi', 'jkl'].includes(x)) {
   //logic
}
var obj = {
    "0": [{
      "category": "A",
      "index": 0,
      "property": "Name",
      "value": "Bob"
    }],
    "1": [{
      "category": "A",
      "index": 1,
      "property": "Name",
      "value": "Jessica"
    }]
}

console.log(Object.values(obj).flat())

/*
Client callable script include used for filtering sys_user lists
to identify duplication email users
name: duplicateEmail
active: true
client callabe: true
*/
function duplicateEmail() {
    var xx = new GlideAggregate('sys_user');
    xx.addAggregate('COUNT', 'email');
    xx.addHaving('COUNT', 'email', '>', '1');
    xx.query();
    var answer = new Array();
    while (xx.next()) {
        answer.push(xx.getValue('email'));
    }
    return answer;
}
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;
// Examples
celsiusToFahrenheit(15);    // 59
celsiusToFahrenheit(0);     // 32
celsiusToFahrenheit(-20);   // -4
fahrenheitToCelsius(59);    // 15
fahrenheitToCelsius(32);    // 0
const average = (...args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
const goToTop = () => window.scrollTo(0, 0);
goToTop();
// Result: will scroll the browser to the top of the page
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: will return true if user is on an Apple device
const elementIsInFocus = (el) => (el === document.activeElement);
elementIsInFocus(anyElement)
// Result: will return true if in focus, false if not in focus
const toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);
// Examples
toFixed(25.198726354, 1);       // 25.1
toFixed(25.198726354, 2);       // 25.19
toFixed(25.198726354, 3);       // 25.198
toFixed(25.198726354, 4);       // 25.1987
toFixed(25.198726354, 5);       // 25.19872
toFixed(25.198726354, 6);       // 25.198726
const timeFromDate = date => date.toTimeString().slice(0, 8);
console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); 
// Result: "17:30:00"
console.log(timeFromDate(new Date()));
// Result: will log the current time
const isEven = num => num % 2 === 0;
console.log(isEven(2));
// Result: true
console.log(isEven(3));
// Result: false
const isBrowserTabInView = () => document.hidden;
isBrowserTabInView();
// Result: returns true or false depending on if tab is in view / focus
const reverse = str => str.split('').reverse().join('');
reverse('hello world');     
// Result: 'dlrow olleh'
const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 0, 11)));
// Result: true (Monday)
console.log(isWeekday(new Date(2021, 0, 10)));
// Result: false (Sunday)
const randomBoolean = () => Math.random() >= 0.5;
var arr1 = [{name: "lang", value: "English"},{name: "age", value: "18"}];
var arr2 = [{name : "childs", value: '5'}, {name: "lang", value: "German"}];

Array.prototype.push.apply(arr1,arr2); 

console.log(arr1);  // final merged result will be in arr1
const days = [
  'Sun',
  'Mon',
  'Tue',
  'Wed',
  'Thu',
  'Fri',
  'Sat'
]