Snippets Collections
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) { 

}
var siteURL = "http://" + top.location.host.toString();

var $internalLinks = $("a[href^='"+siteURL+"'], a[href^='/'], a[href^='./'], a[href^='../'], a[href^='#']");
<! 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]);
    }
  });
});
array = 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++){
        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'
]
const months = [
  'January',
  'February',
  'March',
  'April',
  'May',
  'June',
  'July',
  'August',
  'September',
  'October',
  'November',
  'December'
]
npm i typescript @types/node @types/react --save-dev
// SHA

function sha256(plain: any) {
  // returns promise ArrayBuffer
  const encoder = new TextEncoder();
  const data = encoder.encode(plain);
  return window.crypto.subtle.digest('SHA-256', data);
}

function base64urlencode(a: any) {
  // Convert the ArrayBuffer to string using Uint8 array.
  // btoa takes chars from 0-255 and base64 encodes.
  // Then convert the base64 encoded to base64url encoded.
  // (replace + with -, replace / with _, trim trailing =)
  // @ts-ignore
  return btoa(String.fromCharCode.apply(null, new Uint8Array(a)))
    .replace(/\+/g, '-')
    .replace(/\//g, '_')
    .replace(/=+$/, '');
}

export async function pkceChallengeFromVerifier(v: any) {
  const hashed = await sha256(v);
  return base64urlencode(hashed);
}
/* note sure wy but Google fonts do not display on some Mac.
Here is your solution. Just add "!important" and you will be good to go */



        h1 {
            font-family: 'Montserrat', serif !important;
        }
var express = require('express');
var app = express();

app.get('/', function (req, res) {
    res.send('<b>My</b> first express http server');
});

// 1) Add a route that answers to all request types
app.route('/article')
.get(function(req, res) {
    res.send('Get the article');
})
.post(function(req, res) {
    res.send('Add an article');
})
.put(function(req, res) {
    res.send('Update the article');
});

// 2) Use a wildcard for a route
// answers to : theANYman, thebatman, thesuperman
app.get('/the*man', function(req, res) {
    res.send('the*man');
});

// 3) Use regular expressions in routes
// responds to : batmobile, batwing, batcave, batarang
app.get(/bat/, function(req, res) {
    res.send('/bat/');
});

app.use(function(req, res, next) {
    res.status(404).send("Sorry, that route doesn't exist. Have a nice day :)");
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000.');
});
// will need a HTML page with "root"

import React from "react";
import ReactDOM from "react-dom";

const date = new Date();
const currentTime = date.getHours();
const currentMins = date.getMinutes();

let greeting;

const customSyle = {
  color: ""
};

if (currentTime < 12) {
  greeting = "good morning";
  customSyle.color = "red";
} else if (currentTime < 18) {
  greeting = "good evening";
  customSyle.color = "blue";
} else {
  greeting = "good night";
  customSyle.color = "puprle";
}

ReactDOM.render(
  <h1 className="heading" style={customSyle}>
    {currentTime + ":" + currentMins + " " + greeting}
  </h1>,

  document.getElementById("root")
);
(() => {
let d = new Date()
let year = d.getFullYear().toString()
let month = d.getMonth() < 9 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
let date = d.getDate() < 10 ? '0' + d.getDate() : d.getDate().toString()
let hour = d.getHours() < 10 ? '0' + d.getHours() : d.getHours().toString()
let minutes = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes().toString()
let seconds = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds().toString()
let day
switch (d.getDay()) {
  case 0:
      day = "sunday"
  break
   case 1:
     day = "monday"
   break
   case 2:
     day = "tuesday"
     break
   case 3:
     day = "wednesday"
     break
   case 4:
     day = "thursday"
     break
   case 5:
     day = "friday"
     break
   case 6:
     day = "saturday"
     break
    default:
    day = ''
  }
return {
  formattedDate: d.toLocaleString().split(", ")[0],
  formattedTime: d.toLocaleString().split(" ")[1],
  day,
  yyyy: year,
  mm: month,
  dd: date,
  hh: hour,
  mm: minutes,
  ss: seconds,
  timestamp:[year, month, date, hour, minutes].join(''),
  timestampA:[year, month, date, hour, minutes].join("-"),
  timestampB: `y${year}m${month}d${date}h${hour}m${minutes}s${seconds}`
}
})()

app.get('/:id/tracker.png', function(request, response, next) {
    var emailId = request.param.id;
    var buf = new Buffer([
        0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x01, 0x00, 0x01, 0x00,
        0x80, 0x00, 0x00, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x2c,
        0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x02,
        0x02, 0x44, 0x01, 0x00, 0x3b
    ]);
    response.set('Content-Type', 'image/png');
    response.end(buf, 'binary');
    db.findOne({ id: emailId }, function(error, email) {
        if(error) return next(error);
        app.emit('event:opened', email);
    });
});

app.on('event:opened', function(email) {
    console.log('Email was opened');
    console.log(email.to);
    console.log(email.subject);
});
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
// instead of
if (accessible) {
console.log(“It’s open!”);
}
// use
accessible && console.log(“It’s open!”);
const robotFactory = (model, mobile) => {
return {
model: model,
mobile: mobile,
beep(){
  console.log('Beep Boop');
}
}
};
// parameters and entered in an order, check robotFactory const.
const tinCan = robotFactory('P-500', true);
tinCan.beep();
console.log(tinCan);
const person = {
  _age: 37,
  set age(newAge){
    if (typeof newAge === 'number'){
      this._age = newAge;
    } else {
      console.log('You must assign a number to age');
    }
  }
};

/*
We can perform a check for what value is being assigned to this._age.
When we use the setter method, only values that are numbers will reassign this._age
There are different outputs depending on what values are used to reassign this._age.

*/
const robot = {
  _model: '1E78V2',
  _energyLevel: 100,
  get energyLevel(){
    if(typeof this._energyLevel === 'number') {
      return 'My current energy level is ' + this._energyLevel
    } else {
      return "System malfunction: cannot retrieve energy level"
    }
  }
};

console.log(robot.energyLevel);





/*
Getters can perform an action on the data when getting a property.
Getters can return different values using conditionals.
In a getter, we can access the properties of the calling object using this.
The functionality of our code is easier for other developers to understand.
*/
const example = {
  name: 'mark',
  color: 'red',
  giveDetails(){
    console.log(`${this.example} is a ${this.color} something.`)
  }
}
const user = {
name: "joe",
age: 32,
occupation: "Web Developer"

};

for (const [key, value] of Object.entries(user)) {
console.log(`${key} => ${value}`);
}
const example = {
  model: '1E78V2',
  energyLevel: 100,
provideInfo() {
return `I am ${this.model} and my current energy level is ${this.energyLevel}.`  
}
};
console.log(example.provideInfo());
const input = 'dude whats up yo';
const vowels = ['a', 'e', 'i', 'u', 'o'];
let resultArray = [];


for (let i=0; i< input.length; i++){
/* prints each item in array
console.log(input[i]);
 prints index of each item in array
console.log(i);
*/

for(let j=0; j<vowels.length; j++){
  if(input[i]===vowels[j]){
    if(input[i]==='e'){
      resultArray.push('ee')
    }
    else if (input[i]==='u'){
      resultArray.push('uu');
    }
    else{
      resultArray.push(input[i]);
    }
  }
}
}
console.log(resultArray.join('').toUpperCase());
const xArray = ["1' 2", "3", "4", "5"];

for (let i = 0; i < xArray.length; i++){
  console.log(xArray[i]);
  if (xArray[i] === '4'){
    break;
  }
}

console.log("Sample code");
//HMTL

<div class="container">

 <div id="a" class="box">Div A</div>
<div id="b" class="box">Div B</div>
<div id="c" class="box">Div C</div>
<div id="d" class="box">Div D</div>
<div id="e" class="box">Div E</div>
<div id="f" class="box">Div F</div>

</div>


//CSS
body {
  font-family: arial;
  font-weight: 600;
  color: white;
  font-size: 2em;
}
.container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  padding: 10%;
  text-align: center;
  grid-gap: 40px;
}

.box {
   background-color: green;
   padding: 20px;
  
}

#a {


}

#a:hover {
     grid-column: 1 / 4;
     grid-row: 1/6;
}

#a:hover ~ #b {
    background: #ccc;
        grid-column: 4;
}

#a:hover ~ #c {
    background: #ccc;
        grid-column: 4;
}

#a:hover ~ #d {
    background: #ccc;
            grid-column: 4;

}

#a:hover ~ #e {
    background: #ccc;
            grid-column: 4;

}

#a:hover ~ #f {
    background: #ccc;
            grid-column: 4;

}

#b:hover {
     grid-column: 1 / 4;
     grid-row: 1/6;
}

#b:hover ~ #a {
    background: #ccc;
        grid-column: 4;
}

#b:hover ~ #c {
    background: #ccc;
        grid-column: 4;
}

#b:hover ~ #d {
    background: #ccc;
            grid-column: 4;

}

#b:hover ~ #e {
    background: #ccc;
            grid-column: 4;

}

#b:hover ~ #f {
    background: #ccc;
            grid-column: 4;

}
document.getElementsByTagName('video')[0].requestPictureInPicture();
 const ageSum = ages.reduce(function(total, age) {
   return total + age;
 }, 0);
 const sortedCompanies  = companies.sort(function(c1, c2) {
   if(c1.start > c2.start) {
     return 1;
   } else {
    return -1;
   }
 });

 const sortedCompanies = companies.sort((a, b) => (a.start > b.start ? 1 : -1));

// Sort ages
 const sortAges = ages.sort((a, b) => a - b);
 const companyNames = companies.map(function(company) {
   return company.name;
 });
    //? GETTER - GET All Technologies sorted by Date Modified
    allTechnologiesDateSorted(state) {
      return state.allTechnologies.sort((a,b) => (a.dateModified.split("-").join("") < b.dateModified.split("-").join("") ? 1 : -1));
    },
var Number = prompt("Insert number between 0 and 100");

 if (0<Number<50){
       console.log("Low value");
}else if(50<=Number<100){
       console.log("High value");
}else{
       console.log("not a valid number");
}
let nodeCounter = 1;

function addChild() {
    let p = document.createElement("p");
    p.setAttribute('class', 'pnode');
    p.innerHTML = `new node created #${nodeCounter}`;
    document.getElementById("div1").appendChild(p);
    nodeCounter++;
}
let nodeCounter = 1;

function addChild() {
    let p = document.createElement("p");
    p.setAttribute('class', 'pnode');
    p.innerHTML = `new node created #${nodeCounter}`;
    document.getElementById("div1").appendChild(p);
    nodeCounter++;
}
// Example Arrays
let filterArrayB = ['aa', 'ab', 'ac', 'ad', 'ae', 'af', 'ag']
let filterArrayA = ['aa', 'ab', 'ac', 'ae', 'af', 'ag']

// This only works if there is a 1 item difference 
compare = (a,b) => {
  let inBoth = []
  let missingItem = []
  a.forEach(item => {
    for (let i=0; i<b.length; i++){
      if (item == b[i]){
        inBoth.push(item) 
        if (i == b.length) return
      } 
      if (a.length < b.length) {
        b.forEach(item => {
          if (!a.includes(item)){
            missingItem = item
          }
        })
      } else {
          a.forEach(item => {
          if (!b.includes(item)){
            missingItem = item
          }
        })
      }
      
    }
  })
  return missingItem
}

compare(filterArrayA, filterArrayB)
import React from 'react';
import ReactDOM from 'react-dom';

class MyForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = { username: '' };
  }
  myChangeHandler = (event) => {
    this.setState({username: event.target.value});
  }
  render() {
    return (
      <form>
      <h1>Hello {this.state.username}</h1>
      <p>Enter your name:</p>
      <input
        type='text'
        onChange={this.myChangeHandler}
      />
      </form>
    );
  }
}

ReactDOM.render(<MyForm />, document.getElementById('root'));
    // Make a request for a user with a given ID
  axios.get('/user?ID=12345')
    .then(function (response) {
      // handle success
      console.log(response);
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    })
     .then(function () {
      // always executed
    }); 


 // Optionally the request above could also be done as
  axios.get('/user', {
      params: {
        ID: 12345
      }
    })
    .then(function (response) {
      console.log(response);
    })
    .catch(function (error) {
      console.log(error);
    })
    .then(function () {
      // always executed
    }); 

  // Want to use async/await? Add the `async` keyword to your outer function/method.
   async function getUser() {
    try {
      const response = await axios.get('/user?ID=12345');
      console.log(response);
    } catch (error) {
      console.error(error);
    }
  } 


document.onmouseover = function(event){
    var elem = event.target;

    if (elem.id !== 'menu4IMDBlink' && elem.parentNode.id !== "menu4IMDBlink" && document.getElementById("menu4IMDBlink")) {
        document.getElementById("menu4IMDBlink").remove();
    }

    if ((elem.tagName == 'A' || elem.parentNode.tagName == 'A') && elem.className !== "menu_link") {
        var elemHref = elem.tagName == 'A' ?  elem.href : elem.parentNode.href;
        var matchArr = elemHref.match(/\/tt(\d+)[\/\?]/);

        if (matchArr && matchArr[1] && !document.getElementById("menu4IMDBlink")) {
            var menuDiv = document.createElement("div");
            menuDiv.id = "menu4IMDBlink";
            menuDiv.style.zIndex = 6999;
            menuDiv.style.position = "fixed";
            menuDiv.style.backgroundColor = "#EEE";

            var rect = elem.getBoundingClientRect();
            var menuTop = rect.top + rect.height;
            menuDiv.style.top = menuTop + "px"
            menuDiv.style.left = rect.left + "px";
            
            var a = document.createElement("a");
            a.href = "https://www.imdb.com/title/tt" + matchArr[1] + "/episodes?season=-1"
            a.target = "_blank";
            a.innerText = "episodes";
            a.className = "menu_link";
            menuDiv.appendChild(a);
            
            menuDiv.innerHTML += "&nbsp;";
            a = document.createElement("a");
            a.href = "https://opensubtitles.org/uk/search2?IMDBID=" + matchArr[1];
            a.target = "_blank";
            a.innerText = "subs";
            a.className = "menu_link";
            menuDiv.appendChild(a);
            
            menuDiv.innerHTML += "&nbsp;";
            a = document.createElement("a");
            a.href = "https://rarbgmirror.org/torrents.php?imdb=tt" + matchArr[1];
            a.target = "_blank";
            a.innerText = "rarbg";
            a.className = "menu_link";
            menuDiv.appendChild(a);

            document.body.appendChild(menuDiv);
        }
    }
}
// in gastby-browser.js
exports.shouldUpdateScroll = ({
  routerProps: { location },
  getSavedScrollPosition,
}) => {
  const { pathname } = location
  // list of routes for the scroll-to-top-hook
  const scrollToTopRoutes = [`/privacy-policy`, `/page-2`]
  // if the new route is part of the list above, scroll to top (0, 0)
  if (scrollToTopRoutes.indexOf(pathname) !== -1) {
    window.scrollTo(0, 0)
  }

  return false
}
JSON.stringify(obj, null, “\t”);
const hello = (name = mandatory()) => { return console.log(`Hello: ${name}!`)};
hello(’Rick’);
const a = '';
const b = "";
const c = null;
const d = undefined;
const e = NaN;
const f = false;
const g = 1;

console.log(!!a); 
console.log(!!b);
console.log(!!c);
console.log(!!d);
console.log(!!e);
console.log(!!f);
console.log(!!g);
let names= ['Evelyn', 'Harper', 'Jackson', 'Avery', 'Jack', 'Eleanor', 'Carter'];
const chooseName = () =>{
	let randomName = names[Math.floor(Math.random() * names.length)];
	return randomName;
}
console.log('Random name:', chooseName(names));
const removeDuplicatesFromArray = arr => [...new Set(arr)];
removeDuplicatesFromArray([1,1,2,3,4,4,4,true,true,'foo','foo']);
const fetch_retry = async (url, options, n) => {
    try {
       response = await fetch(url, options);
       if (response === 200) {
         return response;
       }else{
         throw new Error(response)
       }
    } catch(err) {
      //.1      
      if (n === 1) throw err;
   
      //2.
      response = await fetch_retry(url, options, n - 1);
      if (response === 200) {
         return response;
      }else{
         throw new Error(response)
      }
    }
};
let response = fetch_retry("/someUrl/json", options, 10);
const fetch_retry = async (url, options, n) => {
    let error;
    for (let i = 0; i < n; i++) {
        
        try {
            response = await fetch(url, options);
            if (response === 200) {
               return response;
            }else{
               throw new Error(response)
            }
        } catch (err) {
           error = err;     
           //1.           
           if (i + 1 === n) throw err;
        }
    }
    throw error;
};
let response = fetch_retry("/someUrl/json", options, 10);
const prefersReducedMotion = window.matchMedia('(prefers-reduced-motion)');

const reduceMotionChanges = () => {
  if (pefersReducedMotion.matches) {
    // Handle reduced motion
  }
}

prefersReducedMotion.addListener(reduceMotionChanges)
// NOTE - See Vue Date Filter for best example - this is 'Vue Date Filter 2'
// which may be helpful in a different way
// the other one accounts for time zone

import DateFilter from './filters/date'
// require('firebase/firestore')
// import { firestorePlugin } from 'vuefire';
// import { db } from './components/fbConfig.js';

Vue.config.productionTip = false;

export const port = () => '3000';
let app = '';

Vue.use(VueRouter);
Vue.use(store);
Vue.filter('date', DateFilter)
export default (value) => {
  const date = new Date(value)
  if (!value) return ""
  else return date.toLocaleString(['en-US'], {month: 'short', day: '2-digit', year: 'numeric'})

  // THE DATE MAY BE OFF DUE TO TIME ZONES - USE toLocaleDateString and add a timezone to prevent that
  // as long as time isn't being used, this is the better option:
  return date.toLocaleDateString(['en-US'], {month: 'short', day: '2-digit', year: 'numeric', timeZone: 'UTC'})

}
function isValid(str){
 return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
export const addParensToFormatAreaCode = (phone?: string) => {
  const phoneParts = phone?.split("-");
  if (phoneParts !== undefined && phoneParts[0] !== "") {
    const phoneJoin: string = `(${phoneParts[0]}) ${phoneParts[1]}-${phoneParts[2]}`;
    return phoneJoin;
  }
  return strings.DEFAULT;
};
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Array Methods</h2> 
​
<h2>shift()</h2>
​
<p>The shift() method removes the first element of an array (and "shifts" all other elements to the left):</p>
​
<p id="demo1"></p>
<p id="demo2"></p>
​
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo1").innerHTML = fruits;
fruits.shift();
document.getElementById("demo2").innerHTML = fruits;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Array Methods</h2> 
​
<h2>join()</h2>
​
<p>The join() method joins array elements into a string.</p>
​
<p>It this example we have used " * " as a separator between the elements:</p>
​
<p id="demo"></p>
​
<script>
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Expressions</h2>
​
<p>Expressions compute to values.</p>
​
<p id="demo"></p>
​
<script>
document.getElementById("demo").innerHTML = 5 * 10;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Arrays</h2>
​
<p id="demo"></p>
​
<script>
var cars = ["Saab", "Volvo", "BMW"];
document.getElementById("demo").innerHTML = cars;
</script>
​
</body>
</html>
​
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Numbers</h2>
​
<p>If you add two numeric strings, the result will be a concatenated string:</p>
​
<p id="demo"></p>
​
<script>
var x = "10";
var y = "20";
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
​
</body>
</html>
​
​
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Numbers</h2>
​
<p>If you add two numbers, the result will be a number:</p>
​
<p id="demo"></p>
​
<script>
var x = 10;
var y = 20;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
​
</body>
</html>
​
​
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript String Properties</h2>
​
<p>The length property returns the length of a string:</p>
​
<p id="demo"></p>
​
<script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var sln = txt.length;
document.getElementById("demo").innerHTML = sln;
</script>
​
</body>
</html>
​
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Strings</h2>
​
<p id="demo"></p>
​
<script>
var x = "John Doe";  // String written inside quotes
document.getElementById("demo").innerHTML = x;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<button onclick="document.getElementById('demo').innerHTML=Date()">The time is?</button>
​
<p id="demo"></p>
​
</body>
</html>
​
const StyledMotionComponent = styled(motion.div)`

  /* ----- styles go here ----- */

`
 {"countries":[
    {
        "name":"USA",

        "grandfathers":[
            {
                "gFName":"Steve",
                "grandfathersKid":[
                    {
                        "gFKName": "Linda",
                        "kid": [{
                            "name": "Steve JR", 
                            "friends": [{
                                "name": "Kriss|John|Martin|Steven"
                            }]
                        }
                        ]
                    }

                ]
            }
        ]
    }
]}
function countdown(i) {
    console.log(i)  if (i <= 1) {  // base case
        return;
    } else {     // recursive case
        countdown(i - 1);
    }
}

countdown(5);    // This is the initial call to the function.
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Functions</h2>
​
<p>This example calls a function which performs a calculation and returns the result:</p>
​
<p id="demo"></p>
​
<script>
var x = myFunction(4, 3);
document.getElementById("demo").innerHTML = x;
​
function myFunction(a, b) {
  return a * b;
}
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>The += Operator</h2>
​
<p id="demo"></p>
​
<script>
var x = 10;
x += 5;
document.getElementById("demo").innerHTML = x;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Operators</h2>
​
<p>x = 5, y = 2, calculate z = x + y, and display z:</p>
​
<p id="demo"></p>
​
<script>
var x = 5;
var y = 2;
var z = x + y;
document.getElementById("demo").innerHTML = z;
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h1 id="myH"></h1>
<p id="myP"></p>
​
<script>
/*
The code below will change
the heading with id = "myH"
and the paragraph with id = "myP"
*/
document.getElementById("myH").innerHTML = "JavaScript Comments";
document.getElementById("myP").innerHTML = "My first paragraph.";
</script>
​
</body>
</html>
​
<!DOCTYPE html>
<html>
<body>
​
<h2>JavaScript Comments</h2>
​
<p id="demo"></p>
​
<script>
var x = 5;    // Declare x, give it the value of 5
var y = x + 2;  // Declare y, give it the value of x + 2 
// Write y to demo:
document.getElementById("demo").innerHTML = y;
</script>
​
​
</body>
</html>
​
var clearTable = function(tableId) {
  var tableToClear = document.getElementById(tableId);
  while (tableToClear.rows.length > 1) {
    tableToClear.deleteRow(1);
  }
}
var buildTable = function(tableId, tData) {
  var tableRef = document.getElementById(tableId);
  tData.forEach(dataObj => {
    var row = tableRef.insertRow(1);
    Object.values(dataObj).forEach(val => {
      var dataColumn = document.createElement("td");
      dataColumn.innerHTML = val;
      row.appendChild(dataColumn);
    });
  });
}
`Pomoci zpětné uvozovky vytvoříte speciální řetězec, který lze psát na více 
 řádků a dají se do něj vkládat výrazy ${ 1+2 }, proměnné ${ x+y }, pole ${ seznam[0] },
 objekty ${ uzivatelske.jmeno } a dokonce ihned volané funkce ${ function() { return x+y; }() } 
 nebo metody ${ "sidon".toUpperCase() }.`
function pow(x, n) {
  return (n == 1) ? x : (x * pow(x, n - 1));
}
      {arr.map(({ what ever you want to get from map }) => (
        <div>
			code goes here to display through html elements
        </div>
      ))}
const myObject= {
  'Age': '25',
  'Gender': 'Male',
  'Nationality': 'Australian'
};

const myMap = new Map(Object.entries(myObject)); //object to map
const anotherObject = Object.fromEntries(myMap) // map to object
const collectionName = 'databases' // this is my collection name
const ref = firebase.firestore().collection(collectionName);
ref.onSnapshot((snapshot) => {
  snapshot.forEach((doc) => {
    const data = doc.data();
    // ...
  });
});
alert( Boolean("0") ); // true
alert( Boolean(" ") ); // spaces, also true (any non-empty string is true)
<!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
	
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
	
    <!-- U Chen CSS -->
	<link rel="stylesheet" href="homeStyle.css">
	
	<!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
	
	<!-- Font Awesome Icons -->
	<script src="https://kit.fontawesome.com/a076d05399.js"></script>
add_action('wp_head', 'add_gtm');

function add_gtm() {
	?>
	{{INSERT SCRIPT HERE}}
<?
}

add_action( 'wp_body_open', 'add_gtm_no_script' );

function add_gtm_no_script() {
	?>
	{{INSERT SCRIPT HERE}}
<?
}
<button type="submit" id="customers_filter" onclick="checkWhetherTheTableContainsSearchResults()"
                                class="btn filter-button d-inline-block ml-3">
                                Filter
                            </button>
                            
<input id="search-hidden-input" hidden name="searchValue">

<script>
function checkWhetherTheTableContainsSearchResults() {
        let search = location.search.substring(1)
            searchInputElement = document.getElementById('search-hidden-input');
        
        if(search != '') {
            searchInputElement.setAttribute('value', search);
        }
    }
</script>
    
// If the filter is to work on search results, the original search parameter has to be passed into the request array.
        // Thus, the request array will return more than one parameter 
        // AND
        // one of the parameters will be searchValue
        // WHICH
        // will contain the entire search parameter (key + value)

        if ((count($request->all()) > 1) && (isset($request->searchValue))) {
            if (strpos($request->searchValue, '=')) {
                $string = $request->searchValue;
                $array = explode('=', $string);
                $request->searchValue = $array[1];
            }
        }
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
  <span *ngIf="!changeText">Hide</span>
  <span *ngIf="changeText">Show</span>
</div>
(?:\d\s*)?[A-Z]?[a-z]+\s*\d+(?:[:-]\d+)?(?:\s*-\s*\d+)?(?::\d+|(?:\s*[A-Z]?[a-z]+\s*\d+:\d+))?
numbers.forEach((number, index, array) => {
    console.log(array);
});

numbers.forEach((number, index) => {
    console.log('Index: ' + index + ' Value: ' + number);
});
numbers.forEach(function(number) {
    console.log(number);
});

numbers.forEach(function() {
    // code
});
const str = 'To be, or not to be, that is the question.' 

console.log(str.includes('To be'))        // true
console.log(str.includes('question'))     // true
console.log(str.includes('nonexistent'))  // false
console.log(str.includes('To be', 1))     // false
console.log(str.includes('TO BE'))        // false
console.log(str.includes(''))             // true
function sayHi(phrase, who) {
  alert( phrase + ', ' + who );
}

setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John
var tables = [
    { "art":"A","count":"0","name":"name1","ean":"802.0079.127","marker":"null","stammkost":"A","tablename":"IWEO_IWBB_01062015" },
    { "art":"A","count":"0","name":"2","ean":"657.7406.559","marker":"null","stammkost":"A","tablename":"IWEO_IWBB_02062015" }
];

tables.forEach(function(table) {
    var tableName = table.name;
    console.log(tableName);
});
function tick() {
  //get the mins of the current time
  var mins = new Date().getMinutes();
  if (mins == "00") {
    alert('Do stuff');
  }
  console.log('Tick ' + mins);
}

setInterval(tick, 1000);
console.log("entering try-catch statement");

try {
  console.log("entering try block");
  throw "thrown message";
  console.log("this message is never seen");
}
catch (e) {
  console.log("entering catch block");
  console.log(e);
  console.log("leaving catch block");
}
finally {
  console.log("entering and leaving the finally block");
}

console.log("leaving try-catch statement");
fruits.forEach(function(item, index, array) {
  console.log(item, index)
})
// Apple 0
// Banana 1
if (array.includes(value) === false) array.push(value);
function intDiv(a,b)
{
var result = a/b;
if(result>=0)
return Math.floor(result);
else
return Math.ceil(result);
}

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

const numbers = num1.concat(num2, num3);

console.log(numbers); 
// results in [1, 2, 3, 4, 5, 6, 7, 8, 9]
const letters = ['a', 'b', 'c'];
const numbers = [1, 2, 3];

letters.concat(numbers);
// result in ['a', 'b', 'c', 1, 2, 3]
function example(…) {
    return condition1 ? value1
         : condition2 ? value2
         : condition3 ? value3
         : value4;
}

// Equivalent to:

function example(…) {
    if (condition1) { return value1; }
    else if (condition2) { return value2; }
    else if (condition3) { return value3; }
    else { return value4; }
}
// BASH
mkdir src
mkdir build
touch src/index.ts
touch .gitignore
touch README.md
tsc -y
npm init -y
npm install nodemon concurrently @types/express --save-dev

// package.json
...
"scripts": {
  "start:build": "tsc -w",
  "start:run": "nodemon ./build/index.js",
  "start": "concurrently npm:start:*"
},
...

// tsconfig.json
...
"outDir": "./build",
"rootDir": "./src",
...

// .gitignore
node_modules
*.env

// README.md
### Start
```bash
npm run start
```

// src/index.ts
import express from 'express'
const port = 3000
const app = express()

console.log("Hello, World!!!")

logSomething("This is a string that I'm logging")

app.listen(port, () => {
  console.log(`Listening on port ${port}`)
})
//capitalize only the first letter of the string. 
function capitalizeFirstLetter(string) {
    return string.charAt(0).toUpperCase() + string.slice(1);
}
//capitalize all words of a string. 
function capitalizeWords(string) {
    return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};
var array = [267, 306, 108];
var largest = Math.max.apply(Math, array); // 306
var date, daytoset; // given: a Date object and a integer representing the week day

var currentDay = date.getDay();
var distance = daytoset - currentDay;
date.setDate(date.getDate() + distance);
let rand = Math.random()
rand < 0.5 ? gender = 0 : gender = 1
this.name = `${gender ? '👩‍💼' : '👨‍💼'} ${faker.name.firstName(gender)} ${faker.name.lastName(gender)}`
import * as Yup from 'yup';

validationSchema: Yup.object({
  password: Yup.string().required('Password is required'),
  passwordConfirmation: Yup.string()
     .oneOf([Yup.ref('password'), null], 'Passwords must match')
});
const fs = require('fs');
const path = require('path');
const dirPath = path.join(__dirname, '/pictures');

fs.mkdirSync(dirPath);
const bookModule = (function() {
  // private
  let title = ‘JavaScript’;
  let price = 15;
  // public
  return {
    printTitle: function () {
      console.log(title);
    }
  }
})();
bookModule.printTitle(); // JavaScript
const utils = (function () {
  let instance;
  
  function initialize() {
    return {
      sum: function (a, b) {
        return a + b;
      }
    };
  }
  return {
    getInstance: function () {
      if (!instance) {
        instance = initialize();
      }
      return instance;
    }
  };
})();
let sum = utils.getInstance().sum(3, 5); // 8
function Book(title, price) {
  this.title = title;
  this.price = price;
  this.printTitle = () => console.log(this.title);
}
function BookPrototype(prototype) {
  this.prototype = prototype;
  this.clone = () => {
    let book = new Book();
    book.title = prototype.title;
    book.price = prototype.price;
    
    return book;
  };
}
let sampleBook = new Book(‘JavaScript’, 15);
let prototype = new BookPrototype(sampleBook);
let book = prototype.clone();
book.printTitle();
// Using {} to create empty objects:
let person = {};
// Using Object() to create empty objects:
let person = new Object();
// Using function constructor:
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.showName = () => console.log(this.name);
}
let person = new Person(‘Amy’, 28);
person.showName();
function getBook(bookId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let book = {
        title: ‘JavaScript’,
        authorId: ‘123’
      }
    
      resolve(book);
    }, 500);
  });
}
function getAuthor(authorId) {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      let author = {
        name: ‘Amy’,
        age: 28
      }
      resolve(author);
    }, 500);
  });
}
async function fetchData() {
  let book = await getBook(2020);
  let author = await getAuthor(book.authorId);
  console.log(author)
}
fetchData(); // { name: ‘Amy’, age: 28 }
const copyToClipboard = str => {
  const el = document.createElement('textarea');
  el.value = str;
  el.setAttribute('readonly', '');
  el.style.position = 'absolute';
  el.style.left = '-9999px';
  document.body.appendChild(el);
  const selected =
    document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false;
  el.select();
  document.execCommand('copy');
  document.body.removeChild(el);
  if (selected) {
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(selected);
  }
};

// Example
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
const getURLParameters = url =>
  (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
    (a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
    {}
  );

// Examples
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}
const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';

// Example
detectDeviceType(); // "Mobile" or "Desktop"
const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

// Example
scrollToTop();
const getScrollPosition = (el = window) => ({
  x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
  y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop
});

// Example
getScrollPosition(); // {x: 0, y: 200}
document.querySelectorAll('body a').forEach((val) => {
  let linkCheck = new RegExp('/' + window.location.host + '/')
  if (!linkCheck.test(val.href)) {
	let currentRel = val.getAttribute('rel')
    val.setAttribute('target', '_blank')
	if (currentRel) {
		val.setAttribute('rel', 'noreferrer noopener ' + val.getAttribute('rel'))
	} else {
		val.setAttribute('rel', 'noreferrer noopener')
	}
  }
})


//Replace 'body a' with desired selector
// filterProperty i.e. 'id' or 'name'
function GetDuplicates(array, filterProperty) {
	//lookup with our intended filter to get the duplicates by a given property
    const lookup = array.reduce((a, e) => {
        a[e.filterProperty] = ++a[e.filterProperty] || 0;
        return a;
    }, {});
    
    let duplicates = array.filter(e => lookup[e.filterProperty]);
    
    return duplicates;
}
// filterProperty i.e. 'id' or 'name'
function GetUniqueItems(array, filterProperty) {
	return array
    .map(e => e['filterProperty'])
    .map((e, i, final) => final.indexOf(e) === i && i)
    .filter(obj=> array[obj])
    .map(e => array[e]);
}
    <Router>
        <div className="app">
            <GlobalContextProvider>
                <Header />
                <Switch>
                    <Route path="/CodeSystem" component={PageCodeSystem} />
                    <Route path="/ValueSet" component={PageValueSet} />
                    <Route path="/RefSets" component={PageRefSets} />
                    <Route path="/" exact component={HomePage} />
                </Switch>
            </GlobalContextProvider>
        </div>
    </Router>
var points = [40, 100, 1, 5, 25, 10];
points.sort((a,b) => a-b)
import { useNetInfo } from '@react-native-community/netinfo';

const useAppNetworkInfo = () => {
  const netInfo = useNetInfo();
  const count = useRef(0);
  const isConnected = useRef(false);
  useEffect(() => {
    if (count.current > -1) {
      if (netInfo?.isConnected && netInfo?.isInternetReachable) {
        if (!isConnected.current) {
          if (count.current > 2) {
            Toast.success(i18next.t('global.onlineAlert', 10));
          }
        }
        const socket = GlobalLib.SocketClient.get();
        if (socket && typeof socket.open === 'function') {
          socket.open();
        }
        isConnected.current = true;
      } else {
        if (isConnected.current) {
          Toast.offline(i18next.t('global.offlineAlert', 10));
        }
        isConnected.current = false;
      }
    }
    count.current = count.current + 1;
  }, [netInfo]);
};
import { useEffect, useRef } from 'react';
import { useSelector } from 'react-redux';

const useAppSocket = () => {
  const token = useSelector(selectAccessToken());
  const user = useSelector(selectUser());
  const { set: setChatAccount } = useSharedValue(
    AppConstants.sharedValueKey.CHAT_ACCOUNT,
    {},
  );
  const socket = useRef(null);
  useEffect(() => {
    if (user && token) {
      socket.current = new SocketClient({
        userId: user.id,
        userIdentityName: user.identityName,
        token: token,
        onSocketError: () => {},
        onChatInfo: setChatAccount,
      });
      GlobalLib.SocketClient.set(socket.current);
    }
  }, [token, user, setChatAccount]);

  return {
    get: GlobalLib.SocketClient.get,
    socket,
  };
};
import { useCallback, useEffect } from 'react';
import { useDispatch, useSelector, useStore } from 'react-redux';
import { combineReducers } from 'redux';

// add to store object
// const reducerMap = {
// };
// store.reducerMap = reducerMap;
//


const useSharedValue = (key, defaultValue) => {
  const reducer = useCallback(
    (state = defaultValue, action) => {
      switch (action.type) {
        case `SHARED_VALUE_ACTION_KEY/${key}`:
          return action.payload.value;

        default:
          return state;
      }
    },
    [key, defaultValue],
  );
  const action = useCallback(
    value => ({
      type: `SHARED_VALUE_ACTION_KEY/${key}`,
      payload: { value },
    }),
    [key],
  );
  const selector = useCallback(() => state => state[key] || defaultValue, [
    defaultValue,
    key,
  ]);

  const store = useStore();
  useEffect(() => {
    if (store?.reducerMap) {
      store.replaceReducer(
        combineReducers({
          ...store.reducerMap,
          [key]: reducer,
        }),
      );
      store.reducerMap[key] = reducer;
    }
  }, [store, reducer, key]);

  const data = useSelector(selector());
  const dispatch = useDispatch();
  const set = useCallback(value => dispatch(action(value)), [dispatch, action]);

  return {
    data,
    set,
  };
};
import { useCallback, useRef, useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';

/**
 * @description Get me API hook. Perform the get me API call when component mounted
 * @returns {Object}
 */
const useLogout = () => {
  const dispatch = useDispatch();
  const token = useSelector(selectAccessToken());
  const Loading = useRef(GlobalLib.Loading.get());
  const callLogout = useCallback(async () => {
    try {
      Loading.current.show();
      await ApiLib.authApi.postApiV1AuthLogout(
        UtilLib.getAuthorizationHeaders(token),
      );
      dispatch(updateAccessToken(null));
      dispatch(updateUser({}));
      NavigationServiceLib.reset(screens.Launch);
    } catch (error) {
    } finally {
      Loading.current.hide();
    }
  }, [dispatch, token]);
  return {
    logout: callLogout,
  };
};
import { useCallback, useRef, useState } from 'react';
import { useAsync } from 'react-async';
import SplashScreen from 'react-native-splash-screen';

/**
 * @description Get me API hook. Perform the get me API call when component mounted
 * @returns {Object}
 */
const useGetMe = () => {
  const dispatch = useDispatch();
  const token = useSelector(selectAccessToken());
  const lastCallInstance = useRef(null);
  const getUserProfile = useCallback(
    async ({ accessToken }) => {
      if (lastCallInstance.current) {
        clearTimeout(lastCallInstance.current);
      }
      const cancelToken = setTimeout(async () => {
        try {
          const { data } = await ApiLib.accountApi.getApiV1AccountsMe(
            UtilLib.getAuthorizationHeaders(accessToken),
          );
          SplashScreen.hide();
          dispatch(updateUser(data?.data));
          await UtilLib.delay(1000);
          NavigationServiceLib.reset(screens.Main);
        } catch (error) {
          await UtilLib.delay(1000);
          SplashScreen.hide();
          NavigationServiceLib.reset(screens.Login);
        }
      }, 1000);
      lastCallInstance.current = cancelToken;
    },
    [dispatch],
  );
  useAsync({ promiseFn: getUserProfile, accessToken: token, watch: token });
};
var scrollToTopBtn = document.querySelector(".scrollToTopBtn")

var rootElement = document.documentElement

​

function handleScroll() {

  // Do something on scroll

  var scrollTotal = rootElement.scrollHeight - rootElement.clientHeight

  if ((rootElement.scrollTop / scrollTotal ) > 0.0) {
8
    // Show button

    scrollToTopBtn.classList.add("showBtn")

  } else {

    // Hide button

    scrollToTopBtn.classList.remove("showBtn")

  }

}

​

function scrollToTop() {

  // Scroll to top logic

  rootElement.scrollTo({

    top: 0,

    behavior: "smooth"

  })

}

scrollToTopBtn.addEventListener("click", scrollToTop)
1. Number 
2. String
3. Boolean
4. Undefined
5. Null
6. Symbol (new in ECMAScript 6)
7. Object


!==
===
>=
<=
>
<


var
let (new in ECMAScript 6)
const (new in ECMAScript 6)


if
else
else if
ternary operator
switch


&&
||
!


var a = function name() {}
function name() {}
return
() => (fat arrow function — new in ECMAScript 6)


Array
Object


or
while
do 
forEach (new in ECMAScript 5) 
forin (new in ECMAScript 5) 
forof (new in ECMAScript 5)


LET and CONST variables 
Hoisting variables (LET and CONST) 
Arrow => function short hand 
Arrow functions and THIS
Function default parameter values
Object literals short hand
Rest … operator 
Spread … operator 
For Of Loop
Template literals
Destructing arrays[ ] with default parameters
Destructing {Objects} with alias
// Get wrapper
const get = async (url, callback) => {   
  const response = await fetch(url)   
  const status = await response.status      
  if (callback) callback[status](await response.json()) 
}  
// Get usage based callback
get(url, {   
  200: body => doSomething,   
  401: body => showSignInModal,   
  403: body => redirectToSafeArea,   
  422: body => showModalWithInstruction 
})
// GET Request.
fetch('https://api.github.com/users/rich-harris')
  // Handle success
  .then(response => response.json())  // convert to json
  .then(json => console.log(json))    // print data to console
  .catch(err => console.log('Request Failed', err)); // Catch errors
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

list.insertAdjacentHTML('beforebegin', myDiv);
image.src = 'http://placekitten.com/200/300';
image.width = 250;
image.classList.add('cute');
image.alt = 'Cute Kitten';
var scale = Math.min( 
  availableWidth / contentWidth, 
  availableHeight / contentHeight 
);
<script>
  import Toggle from "svelte-toggle@1.0.0";

  let toggled = false;
</script>

<svelte:head>
	<!-- override REPL button margin rule -->
	<style>button{margin:0}</style>
</svelte:head>
        
<Toggle
  label="My toggle label"
  switchColor="#eee"
  toggledColor="#24a148"
  untoggledColor="#fa4d56"
  on="On"
  off="Off"
  bind:toggled />
<Input
     placeholder="Flight name"
     size="large"
     value={this.state.someVal || ''}
     onChange={this.onChange}
   />
onChange = (e) => {
  this.setState({someVal: e.target.value})
}
var repoNameEl = document.querySelector('#repo-name');
var issueContainerEl = document.querySelector('#issues-container');
var limitWarningEl = document.querySelector('#limit-warning');

var getRepoName = function () {
  // Where is this value coming from?
  // TODO: from the URL and returns a string.  
  var queryString = document.location.search;
  //splits string into array.
  var repoName = queryString.split('=')[1];//takes second element of array/repor name

  if (repoName) {
    repoNameEl.textContent = repoName;

    getRepoIssues(repoName);  //calls repo issues for that repo
  } else {
    // Under what condition will this run?
    // TODO: Write your answer here 
    document.location.replace('./index.html');
  }
};

var getRepoIssues = function (repo) {
  var apiUrl = 'https://api.github.com/repos/' + repo + '/issues?direction=asc';

  fetch(apiUrl).then(function (response) {
    if (response.ok) {
      response.json().then(function (data) {
        displayIssues(data);

        // What is this checking for? Under what condition will this be `true`?
        // TODO: link is a response from the github there are more than 30 issues.
        if (response.headers.get('Link')) {
          displayWarning(repo);
        }
      });
    } else {
      document.location.replace('./index.html');
    }
  });
};

var displayIssues = function (issues) {
  // Is there a difference between this and `!issues.length`?
  // TODO: Write your answer here
  if (issues.length === 0) {
    issueContainerEl.textContent = 'This repo has no open issues!';
    return;
  }

  for (var i = 0; i < issues.length; i++) {
    var issueEl = document.createElement('a');
    issueEl.classList = 'list-item flex-row justify-space-between align-center';
    issueEl.setAttribute('href', issues[i].html_url);
    issueEl.setAttribute('target', '_blank');

    var titleEl = document.createElement('span');
    titleEl.textContent = issues[i].title;
    issueEl.appendChild(titleEl);

    var typeEl = document.createElement('span');

    if (issues[i].pull_request) {
      typeEl.textContent = '(Pull request)';
    } else {
      typeEl.textContent = '(Issue)';
    }

    issueEl.appendChild(typeEl);

    issueContainerEl.appendChild(issueEl);
  }
};

// What does this function do?
// TODO: if 'link' is returned, this runs to create a link to the issues.
var displayWarning = function (repo) {
  limitWarningEl.textContent = 'To see more than 30 issues, visit ';

  var linkEl = document.createElement('a');
  linkEl.textContent = 'GitHub.com';
  linkEl.setAttribute('href', 'https://github.com/' + repo + '/issues');
  linkEl.setAttribute('target', '_blank');

  // Where does this appear on the page?
  // TODO: appends it to the bottom of the page
  limitWarningEl.appendChild(linkEl);
};

getRepoName();
var buttonClickHandler = function (event) {
  // What is `event.target` referencing?
  // TODO: Write your answer here
  var language = event.target.getAttribute('data-language');
 //event target uses get attribute from the 
  // Why is this `if` block in place?
  // TODO: Write your answer here
  if (language) {
    getFeaturedRepos(language);

    repoContainerEl.textContent = '';
  }
};
var buttonClickHandler = function (event) {
  // What is `event.target` referencing?
  // TODO: Write your answer here
  var language = event.target.getAttribute('data-language');
 //event target uses get attribute from the 
  // Why is this `if` block in place?
  // TODO: Write your answer here
  if (language) {
    getFeaturedRepos(language);

    repoContainerEl.textContent = '';
  }
};
const findLastIndex = (array, predicate) => {
    let l = array.length;
    while (l--) {
        if (predicate(array[l], l, array)) {
            return l;
        }
    }

    return -1;
};
<!-- beforebegin -->
<p>
  <!-- afterbegin -->
  foo
  <!-- beforeend -->
</p>
<!-- afterend -->

beforeBtn.addEventListener('click', function() {
  var tempDiv = document.createElement('div');
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement('beforebegin', tempDiv);
  }
  setListener(tempDiv);
});

afterBtn.addEventListener('click', function() {
  var tempDiv = document.createElement('div');
  tempDiv.style.backgroundColor = randomColor();
  if (activeElem) {
    activeElem.insertAdjacentElement('afterend', tempDiv);
  }
  setListener(tempDiv);
});
interface IIsObject {
  (item: any): boolean;
}

interface IObject {
  [key: string]: any;
}

interface IDeepMerge {
  (target: IObject, ...sources: Array<IObject>): IObject;
}

/**
 * @description Method to check if an item is an object. Date and Function are considered
 * an object, so if you need to exclude those, please update the method accordingly.
 * @param item - The item that needs to be checked
 * @return {Boolean} Whether or not @item is an object
 */
export const isObject: IIsObject = (item: any): boolean => {
  return (item === Object(item) && !Array.isArray(item));
};

/**
 * @description Method to perform a deep merge of objects
 * @param {Object} target - The targeted object that needs to be merged with the supplied @sources
 * @param {Array<Object>} sources - The source(s) that will be used to update the @target object
 * @return {Object} The final merged object
 */
export const deepMerge: IDeepMerge = (target: IObject, ...sources: Array<IObject>): IObject => {
  // return the target if no sources passed
  if (!sources.length) {
    return target;
  }

  const result: IObject = target;

  if (isObject(result)) {
    const len: number = sources.length;

    for (let i = 0; i < len; i += 1) {
      const elm: any = sources[i];

      if (isObject(elm)) {
        for (const key in elm) {
          if (elm.hasOwnProperty(key)) {
            if (isObject(elm[key])) {
              if (!result[key] || !isObject(result[key])) {
                result[key] = {};
              }
              deepMerge(result[key], elm[key]);
            } else {
              if (Array.isArray(result[key]) && Array.isArray(elm[key])) {
                // concatenate the two arrays and remove any duplicate primitive values
                result[key] = Array.from(new Set(result[key].concat(elm[key])));
              } else {
                result[key] = elm[key];
              }
            }
          }
        }
      }
    }
  }

  return result;
};
import { BrowserModule, BrowserTransferStateModule } from '@angular/platform-browser';
import { isDevMode, NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { ServiceWorkerModule } from '@angular/service-worker';
import { environment } from '../environments/environment';

import { AngularFireModule } from '@angular/fire';
import { AngularFireStorageModule } from '@angular/fire/storage';

import {
  AngularFireAnalyticsModule,
  DEBUG_MODE as ANALYTICS_DEBUG_MODE,
  ScreenTrackingService,
  UserTrackingService
} from '@angular/fire/analytics';

import { FirestoreComponent } from './firestore/firestore.component';

import { AngularFireDatabaseModule, URL as DATABASE_URL } from '@angular/fire/database';
import { AngularFireAuthModule } from '@angular/fire/auth';
import { AngularFirestoreModule, SETTINGS as FIRESTORE_SETTINGS } from '@angular/fire/firestore';
import { AngularFireMessagingModule } from '@angular/fire/messaging';
import { AngularFireFunctionsModule, ORIGIN as FUNCTIONS_ORIGIN } from '@angular/fire/functions';
import { AngularFireRemoteConfigModule, SETTINGS as REMOTE_CONFIG_SETTINGS } from '@angular/fire/remote-config';
import { AngularFirePerformanceModule, PerformanceMonitoringService } from '@angular/fire/performance';
import { AngularFireAuthGuardModule } from '@angular/fire/auth-guard';
import { DatabaseComponent } from './database/database.component';
import { StorageComponent } from './storage/storage.component';
import { RemoteConfigComponent } from './remote-config/remote-config.component';
import { HomeComponent } from './home/home.component';
import { AuthComponent } from './auth/auth.component';
import { MessagingComponent } from './messaging/messaging.component';

const shouldUseEmulator = () => false;

@NgModule({
  declarations: [
    AppComponent,
    StorageComponent,
    FirestoreComponent,
    DatabaseComponent,
    RemoteConfigComponent,
    HomeComponent,
    AuthComponent,
    MessagingComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'serverApp' }),
    BrowserTransferStateModule,
    AppRoutingModule,
    ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }),
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireStorageModule,
    AngularFireAnalyticsModule,
    AngularFireAuthModule,
    AngularFireDatabaseModule,
    AngularFirestoreModule.enablePersistence({ synchronizeTabs: true }),
    AngularFireMessagingModule,
    AngularFireFunctionsModule,
    AngularFireRemoteConfigModule,
    AngularFirePerformanceModule,
    AngularFireAuthGuardModule
  ],
  providers: [
    UserTrackingService,
    ScreenTrackingService,
    PerformanceMonitoringService,
    {
      provide: ANALYTICS_DEBUG_MODE,
      useFactory: () => isDevMode()
    },
    {
      provide: DATABASE_URL,
      useFactory: () => shouldUseEmulator() ? `http://localhost:9000?ns=${environment.firebase.projectId}` : undefined
    },
    { provide: FIRESTORE_SETTINGS, useFactory: () => shouldUseEmulator() ? { host: 'localhost:8080', ssl: false } : {} },
    { provide: FUNCTIONS_ORIGIN, useFactory: () => shouldUseEmulator() ? 'http://localhost:9999' : undefined },
    { provide: REMOTE_CONFIG_SETTINGS, useFactory: () => isDevMode() ? { minimumFetchIntervalMillis: 10_000 } : {} }
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}
<body onload="window.alert('Document is loaded!');">
[{value:5}, {value:10}].map(item => item.value).reduce((previousValue, currentValue) => {return previousValue + currentValue })

>> 15
var something = (function() {
    var executed = false;
    return function() {
        if (!executed) {
            executed = true;
            // do something
        }
    };
})();

something(); // "do something" happens
something(); // nothing happens
// Store an array in local storage

// The array to store
var array = [1, 2, 3];
// Store after JSON stringifying (is this a verb?) it
localStorage.setItem('myArray', JSON.stringify(array));

// Get an array from local storage

// Retrieve the array from local storage
var array = localStorage.getItem('myArray');
// Parse it to something usable in js
array = JSON.parse(array);
const useRemoteTable = ({ promiseFn, searchOption, defaultOrder, columnSchema = [] }) => {
  const [page, setPage] = useState(1);
  const [limit, setLimit] = useState(10);
  const [order, setOrder] = useState(defaultOrder);
  const [reloadTimeStamp, setTimeStamp] = useState(Date.now());

  const onChange = (onChangeNest) => (pagination, filter, sorter, ...args) => {
    if (pagination.current !== page) {
      setPage(pagination.current);
    }
    if (pagination.pageSize !== limit) {
      setPage(1);
      setLimit(pagination.pageSize);
    }
    if (!isEmpty(sorter) && sorter.column) {
      const newOrder = map(columnSchema, (item, index) =>
        index === sorter.column?.columnIndex ? sorter.order : false
      );
      setOrder(newOrder);
    } else {
      setOrder(undefined);
    }
    onChangeNest(pagination, filter, sorter, ...args);
  };

  const reload = useCallback(() => {
    setTimeStamp(Date.now());
  }, []);

  useEffect(() => {
    setPage(1);
  }, [searchOption]);

  const watchWalue = useMemo(
    () => ({
      limit,
      page,
      order,
      searchOption,
      reload: reloadTimeStamp
    }),
    [limit, order, page, reloadTimeStamp, searchOption]
  );

  const { data, error, isPending } = useAsync({
    promiseFn,
    searchOption,
    watch: watchWalue,
    pagination: {
      order: getOrderFromTableToAPI(order),
      orderField: columnSchema[findIndex(order, (i) => i)],
      skip: (page - 1) * limit,
      limit
    }
  });
  return {
    loading: isPending,
    reload,
    page,
    limit,
    error,
    data,
    order,
    onChange
  };
};
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
  return a - b;
});

console.log(numArray);
const httpPost = (url, data, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.setRequestHeader('Content-type', 'application/json; charset=utf-8');
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send(data);
};

const newPost = {
  userId: 1,
  id: 1337,
  title: 'Foo',
  body: 'bar bar bar'
};
const data = JSON.stringify(newPost);
httpPost(
  'https://jsonplaceholder.typicode.com/posts',
  data,
  console.log
); 

// Logs: {"userId": 1, "id": 1337, "title": "Foo", "body": "bar bar bar"}
const httpGet = (url, callback, err = console.error) => {
  const request = new XMLHttpRequest();
  request.open('GET', url, true);
  request.onload = () => callback(request.responseText);
  request.onerror = () => err(request);
  request.send();
};

httpGet(
  'https://jsonplaceholder.typicode.com/posts/1',
  console.log
); 

// Logs: {"userId": 1, "id": 1, "title": "sample title", "body": "my text"}
const formToObject = form =>
  Array.from(new FormData(form)).reduce(
    (acc, [key, value]) => ({
      ...acc,
      [key]: value
    }),
    {}
  );

// Example
formToObject(document.querySelector('#form')); // { email: 'test@email.com', name: 'Test Name' }
const currentURL = () => window.location.href;

// Example
currentURL(); // 'https://google.com'
const detectDeviceType = () =>
  /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    ? 'Mobile'
    : 'Desktop';

// Example
detectDeviceType(); // "Mobile" or "Desktop"
const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

// Example
scrollToTop();
import java.util.Scanner;

class U1_L4_Activity_Two {
    public static void main(String[] args) {
      
       /* Write your code here */
       Scanner scan = new Scanner(System.in);
       int inches;
       int feet;
       
       System.out.println("How many inches?");
       inches = scan.nextInt();
       
       feet = inches/12;
       System.out.println(inches + "\" equals " + feet + "\'" );
       
Scanner scan = new Scanner (System.in);
        
        System.out.println("Enter a radius:");
        double r = scan.nextDouble();
        System.out.println("Circumference: " + (2*3.14*r));
        System.out.println("Area: " + 3.14*r*r);
const formatDuration = ms => {
  if (ms < 0) ms = -ms;
  const time = {
    day: Math.floor(ms / 86400000),
    hour: Math.floor(ms / 3600000) % 24,
    minute: Math.floor(ms / 60000) % 60,
    second: Math.floor(ms / 1000) % 60,
    millisecond: Math.floor(ms) % 1000
  };
  return Object.entries(time)
    .filter(val => val[1] !== 0)
    .map(([key, val]) => `${val} ${key}${val !== 1 ? 's' : ''}`)
    .join(', ');
};

// Examples
formatDuration(1001); // '1 second, 1 millisecond'
formatDuration(34325055574); // '397 days, 6 hours, 44 minutes, 15 seconds, 574 milliseconds'
router.post("/user", async (req, res) => {
  try {
    var user = new User(req.body);
    await user.save();
    res.status(200).send(user);
  } catch (error) {
    if (error.name === "ValidationError") {
      let errors = {};

      Object.keys(error.errors).forEach((key) => {
        errors[key] = error.errors[key].message;
      });

      return res.status(400).send(errors);
    }
    res.status(500).send("Something went wrong");
  }
});
const express = require('express')
const { graphqlHTTP } = require("express-graphql");
const {
  GraphQLSchema,
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
  GraphQLNonNull
} = require('graphql')
const app = express()
const port = 3000

// Sample Data
const authors = [
	{ id: 1, name: 'Dan Brown' },
	{ id: 2, name: 'J. R. R. Tolkien' },
	{ id: 3, name: 'Brent Weeks' }
]

const books = [
	{ id: 1, name: 'The Lost Symbol', authorId: 1 },
	{ id: 2, name: 'Angels and Demons', authorId: 1 },
	{ id: 3, name: 'The Davinci Code', authorId: 1 },
	{ id: 4, name: 'The Fellowship of the Ring', authorId: 2 },
	{ id: 5, name: 'The Two Towers', authorId: 2 },
	{ id: 6, name: 'The Return of the King', authorId: 2 },
	{ id: 7, name: 'The Way of Shadows', authorId: 3 },
	{ id: 8, name: 'Beyond the Shadows', authorId: 3 }
]

const BookType = new GraphQLObjectType({
  name: 'Book',
  description: 'This represents a book written by an author',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) },
    authorId: { type: GraphQLNonNull(GraphQLInt) },
    author: {
      type: AuthorType, // AuthorType is defined below the same way that BookType is defined above
      resolve: (book) => {
        return authors.find(author => author.id === book.authorId)
      }
    }
  })
})

const AuthorType = new GraphQLObjectType({
  name: 'Author',
  description: 'This represents the author of a book',
  fields: () => ({
    id: { type: GraphQLNonNull(GraphQLInt) },
    name: { type: GraphQLNonNull(GraphQLString) }
  })
})

const RootQueryType = new GraphQLObjectType({
  name: 'Query',
  description: 'Root Query',
  fields: () => ({
    books: {
      type: new GraphQLList(BookType),
      description: "List of books",
      resolve: () => books
    }
  })
})

const schema = new GraphQLSchema({
  query: RootQueryType
})



app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true
}))


app.get('/', (req, res) => {
  res.send(`<a href="http://localhost:${port}/graphql">GraphiQL</a>`)
})

// QUERY:
// 
// {
// 	books {
//     id
//   	name
//     author {
//       name
//     }
// 	}
// }

// RESULT
// 
// {
//   "data": {
//     "books": [
//       {
//         "id": 1,
//         "name": "The Lost Symbol",
//         "author": {
//           "name": "Dan Brown"
//         }
//       },
//       {
//         "id": 2,
//         "name": "Angels and Demons",
//         "author": {
//           "name": "Dan Brown"
//         }
//       }, //...
//     ]
//   }
// }

app.listen(port, () => {
  console.log(`App listening on http://localhost:${port}`)
});
const inicio = performance.now();

// Codigo a chequear 

const fin= perfomance.now();

console.log( fin - inicio );
Reset = "\x1b[0m"
Bright = "\x1b[1m"
Dim = "\x1b[2m"
Underscore = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"

FgBlack = "\x1b[30m"
FgRed = "\x1b[31m"
FgGreen = "\x1b[32m"
FgYellow = "\x1b[33m"
FgBlue = "\x1b[34m"
FgMagenta = "\x1b[35m"
FgCyan = "\x1b[36m"
FgWhite = "\x1b[37m"

BgBlack = "\x1b[40m"
BgRed = "\x1b[41m"
BgGreen = "\x1b[42m"
BgYellow = "\x1b[43m"
BgBlue = "\x1b[44m"
BgMagenta = "\x1b[45m"
BgCyan = "\x1b[46m"
BgWhite = "\x1b[47m"
import update from 'immutability-helper';

const oldArray = [
    {name: 'Stacey', age: 55},
    {name: 'John', age: 77},
    {name: 'Kim', age: 62},
];

// add an item
const newArray = update(oldArray, {$push: [
    {name: 'Trevor', age: 45},
]});

// replace an item
const itemIndex = 1; // replace *John* at index `1`
const newValue = {name: 'Kevin', age: 25};
const newArray = update(oldArray, { [itemIndex]: {$set: newValue} });

// modify an item
const itemIndex = 1; // modify *John* at index `1`
const newArray = update(oldArray, {
    [itemIndex]: {$merge, {
        age: 85, // change John's age to 85
    }}
});         

// remove an item
const itemIndex = 0; // delete *Stacey* at index `0`
const newArray = update(oldArray, {$splice: [[itemIndex, 1]] } });
<html lang="en">
	<head>
		<!--using external files-->
		<?php require('import.html') ?>
		
		<title>U Chen Daily | Home</title>
	</head>
	<style>
		@media only screen and (min-width: 893px) {
		.card-img-top{
		width: 100%;
		height: 15vw; 
		object-fit: cover;
		}
		}
		
		.card-body{
		background: #1f52a3;
		}
		
		.card-footer{
		background: #1f52a3;
		}
		
		.h5{
		color: #1f52a3;
		}
		
		.card-text{
		font-size: 12px;
		}
	</style>
	<body class="bg-light">
		<!--using external files-->
		<?php require('header.php'); ?>
		<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">
			<ol class="carousel-indicators">
				<li data-target="#carouselExampleCaptions" data-slide-to="0" class="active"></li>
				<li data-target="#carouselExampleCaptions" data-slide-to="1"></li>
				<li data-target="#carouselExampleCaptions" data-slide-to="2"></li>
			</ol>
			<div class="carousel-inner">
				<div class="carousel-item active">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>First slide label</h5>
						<p>Nulla vitae elit libero, a pharetra augue mollis interdum.</p>
					</div>
				</div>
				<div class="carousel-item">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>Second slide label</h5>
						<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
					</div>
				</div>
				<div class="carousel-item">
					<img src="https://via.placeholder.com/1500x550" class="d-block w-100" alt="...">
					<div class="carousel-caption d-none d-sm-block">
						<h5>Third slide label</h5>
						<p>Praesent commodo cursus magna, vel scelerisque nisl consectetur.</p>
					</div>
				</div>
			</div>
			<a class="carousel-control-prev" href="#carouselExampleCaptions" role="button" data-slide="prev">
				<span class="carousel-control-prev-icon" aria-hidden="true"></span>
				<span class="sr-only">Previous</span>
			</a>
			<a class="carousel-control-next" href="#carouselExampleCaptions" role="button" data-slide="next">
				<span class="carousel-control-next-icon" aria-hidden="true"></span>
				<span class="sr-only">Next</span>
			</a>
		</div>
		<!--4 latest news START-->
		<div class="container-fluid bg-light" style="padding: 40px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-6">
					<h5 style="color: #1f52a3;">Latest News</h5>
				</div>
				
				<div class="col-6 d-flex justify-content-end">
					<a href="" class="btn btn-link font-weight-bold" style="color: #1f52a3;">MORE NEWS <i class="fas fa-angle-double-right" style="font-size: 18px;"></i></a>
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 latest news END-->
		<!--4 nation news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">Nation News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="Nation" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php	
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 nation news END-->
		<!--4 world news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">World News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="World" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 world news END-->
		<!--4 entertainment news START-->
		<div class="container-fluid bg-light" style="padding: 20px 0 0; margin-bottom: 40px;">
			<div class="row" style="margin: 0 50px;">
				<div class="col-sm">
					<h5 style="color: #1f52a3;">Entertainment News</h5>
				</div>
				<div class="col-sm">
				</div>
				<div class="col-sm">
				</div>
			</div>
			
			<div class="card-deck" style="margin: 10px 50px;">
				<?php
					$dbc = mysqli_connect('localhost', 'root', '');	//connect database
					mysqli_select_db($dbc, 'news');	//select database
					
					$query = 'SELECT * FROM news WHERE news_category="Entertainment" ORDER BY news_datetime DESC LIMIT 4';
					$runQuery = mysqli_query($dbc, $query);
				?>
				<!--news card START-->
				<?php
					if($runQuery){
						foreach($runQuery as $row){
						?>
						<div class="card mb-4">
							<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id'] ?>">
								<img class="card-img-top" 
								src="<?php 
									if(empty($row['news_image'])){
										echo 'https://via.placeholder.com/350x250';
										}else{
										echo $row['news_image'];
									}
								?>" alt="Card image cap">
							</a>
							<div class="card-body">
								<a href="/205CDE/Assignment/news.php?id=<?php echo $row['news_id']; ?>">
									<h5 class="card-title text-uppercase text-light d-md-none d-lg-block">
										<?php 
											if(strlen($row['news_title']) > 50){
												echo substr($row['news_title'], 0, 50).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
									<h5 class="card-title text-uppercase text-light d-none d-md-block d-lg-none">
										<?php 
											if(strlen($row['news_title']) > 106){
												echo substr($row['news_title'], 0, 106).'...';
												}else{
												echo $row['news_title'];
											}
										?>
									</h5>
								</a>
							</div>
							<div class="card-footer border-0">
								<div class="row">
									<div class="col-6 card-text text-light text-uppercase"><i class="fas fa-hashtag"></i>
										<?php echo $row['news_category']; ?>
									</div>
									<div class="col-6 card-text text-light text-right text-uppercase"><i class="far fa-clock"></i>
										<?php echo date('d-M-Y', strtotime($row['news_datetime']));?>
									</div>
								</div>
							</div>
						</div>
						<div class="w-100 d-none d-sm-block d-lg-none"><!-- wrap every 2 on sm--></div>
						<?php
						}
						}else{
						echo "ERROR! No record found!";
					}
					mysqli_close($dbc);
				?>
				<!--news card END-->
			</div>
		</div>
		<!--4 entertainment news END-->
		<!--using external files-->
		<?php require('footer.html'); ?>
	</body>
</html>				
let request = obj => {
    return new Promise((resolve, reject) => {
        let xhr = new XMLHttpRequest();
        xhr.open(obj.method || "GET", obj.url);
        if (obj.headers) {
            Object.keys(obj.headers).forEach(key => {
                xhr.setRequestHeader(key, obj.headers[key]);
            });
        }
        xhr.onload = () => {
            if (xhr.status >= 200 && xhr.status < 300) {
                resolve(xhr.response);
            } else {
                reject(xhr.statusText);
            }
        };
        xhr.onerror = () => reject(xhr.statusText);
        xhr.send(obj.body);
    });
};


request({url: "employees.json"})
    .then(data => {
        let employees = JSON.parse(data);
        let html = "";
        employees.forEach(employee => {
            html += `
                <div>
                    <img src='${employee.picture}'/>
                    <div>
                        ${employee.firstName} ${employee.lastName}
                        <p>${employee.phone}</p>
                    </div>
                </div>`;
        });
        document.getElementById("list").innerHTML = html;
    })
    .catch(error => {
        console.log(error);
    });
var image = new Image();
var base64 = 'iVBORw0K...'
image.src = `data:image/png;base64,${base64}`;
document.body.appendChild(image);
fetch(%27https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits%27)
  .then(response => response.json())
  .then(commits => alert(commits[0].author.login));
window.scrollTo(0,document.body.scrollHeight);
new Date(date).toISOString().split('T')[0]
<!DOCTYPE html>
<html>
<body>
​
<h2>My First JavaScript</h2>
​
<button type="button"
onclick="document.getElementById('demo').innerHTML = Date()">
Click me to display Date and Time.</button>
​
<p id="demo"></p>
​
</body>
</html> 
​
var touchmoved;
$('button').on('touchend', function(e){
    if(touchmoved != true){
        // button click action
    }
}).on('touchmove', function(e){
    touchmoved = true;
}).on('touchstart', function(){
    touchmoved = false;
});
function User(name) {
  this.name = name;
  this.isAdmin = false;
}

let user = new User("Jack");
function User(name, age) {
  return {
    name,
    age,
  }
};

let user = User("Tom", 23);
// Cell.js
import React, { Component } from 'react';

export default class Cell extends Component {

  render() {
    const cellSize = {
      width: this.props.size,
      height: this.props.size
    }

    return (
      <div style={cellSize}>
      </div>
    );
  }
}
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Select box event</title>
<script type="text/javascript">
    function swapImage(hash) {
        document.getElementById('imageSwap').src = hash + '.jpg';
    }
</script>
</head>
<body>

<div id="builder_image">
    <img src="rw_blue.jpg" id="imageSwap" alt="" />
</div>

<select name="option3" onchange="swapImage(this.options[selectedIndex].label)">
    <option value="No thanks" selected="selected" label="rw_blue">No thanks</option>
    <option value="Blue" label="rw_blue">Blue</option>
    <option value="Black" label="rw_black">Black</option>
    <option value="Red" label="rw_red">Red</option>
</select>

</body>
</html>
<script type="text/javascript">
function test()
{
    alert(window.document.pic.src);
     //alert msg print like http://localhost/test/pic1.png
    if (document.pic.src=='http://localhost/test/pic1.png'){

document.pic.src='pic2.png';
} 
else if (document.pic.src=='http://localhost/test/pic2.png'){

document.pic.src='pic1.png';
}
}
</script>
<img src="pic1.png" name="pic" onclick="test()"/>
var delayInMilliseconds = 1000; //1 second

setTimeout(function() {
  //your code to be executed after 1 second
}, delayInMilliseconds);
Promise
  .all([ p1, p2, p3 ])
  .then(([ v1, v2, v3 ]) => {
    // Values always correspond to the order of promises,
    // not the order they resolved in (i.e. v1 corresponds to p1)
  });

Promise
  .race([ p1, p2, p3 ])
  .then(val => {
    // val will take the value of the first resolved promise
  });
  
 // Promise.all() turns an array of promises into a promise of an array.
 // If any promise is rejected, the error will pass through.
 // Promise.race() passes throuh the first settled promise.
test('the data is peanut butter', () => {
  expect.assertions(1);
  return fetchData().then(data => {
    expect(data).toBe('peanut butter');
  });
});
test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done();
  }

  fetchData(callback);
});
const pages = Array.prototype.slice.call(document.querySelectorAll('a.page-numbers'))
pages.map((page, index) => {
  const oldUrl = page.getAttribute('href')
  const patt = /\/[0-9]{1,2}\//;
  const result = oldUrl.match(patt)
  const result2 = '/page' + result
  const url = oldUrl.replace(result, result2)
  page.setAttribute('href', url)
});
//The ready event occurs after the HTML document has been loaded
$(document).ready(function () {
    
});

// The onload event occurs later, when all content (e.g. images) also has been loaded.
$(window).load(function() {
    SearchAction(); // used to autoload a grid    
});
{
    "name": "Highlight some phrases",
    "description": "Hightlight some pre defined text after page loads",
    "version": "0.1",
    "permissions": [
        "tabs","<all_urls>"
    ],
    "browser_action": {
        "default_icon": "icon.png"
    },
    "content_scripts": [
        {
        "matches": [
            "http://*/*",
            "https://*/*"
            ],
        "js": ["content.js"],
        "run_at": "document_end"    // Pay attention to this line
        }
    ], 
    "manifest_version": 2
}
const target = { a: 1, b: 2 };
const source = { b: 4, c: 5 };

const returnedTarget = Object.assign(target, source);

console.log(target);
// expected output: Object { a: 1, b: 4, c: 5 }

console.log(returnedTarget);
// expected output: Object { a: 1, b: 4, c: 5 }
render() {
  const elements = ['one', 'two', 'three'];

  const items = []

  for (const [index, value] of elements.entries()) {
    items.push(<li key={index}>{value}</li>)
  }

  return (
    <div>
      {items}
    </div>
  )
}

////////// or:

render: function() {
  const elements = ['one', 'two', 'three'];
  return (
    <ul>
      {elements.map((value, index) => {
        return <li key={index}>{value}</li>
      })}
    </ul>
  )
}
/*
Disapproved Extensions Report Script.
This scripts generates an email if there are some non-removed disapproved extensions.
Disapproval reasons are taken from PLACEHOLDER_FEED_ITEM_REPORT.
Check the nameMapping veriable below for the list of supported extensions.
Email message could also include a long list of dissaproved remarketing feed items, so adjust settings to skip this if necessary.

Developed by Dmytro Bulakh, 2020, bulakh@ppchead.com
*/


// SCRIPT SETIINGS:

// EMAIL:  add recipients emails, like ['john@doe.com', 'doe@john.com']
// If there are no emails, like [] , the script would only log the report
var EMAIL = ['john@doe.com']

// SKIP DYNAMIC REMARKETING: set to true to skip remarketing feed items report or false otherwise

var SKIP_DYNAMIC_REMARKETING = true

function main() {

  // PlaceholderType mapping as of API version v201809 (https://developers.google.com/adwords/api/docs/appendix/placeholders)
  var nameMapping = {
    "1": "Sitelink",
    "2": "Call",
    "3": "App",
    "7": "Location",
    "30": "Affiliate location",
    "17": "Callout",
    "24": "Structured snippet",
    "31": "Message",
    "35": "Price",
    "38": "Promotion",
    "10": "Ad customizers",
    "12": "Dynamic remarketing item: Education",
    "13": "Dynamic remarketing item: Flights",
    "14": "Dynamic remarketing item: Custom Feed",
    "15": "Dynamic remarketing item: Hotels",
    "16": "Dynamic remarketing item: Real estate",
    "17": "Dynamic remarketing item: Travel",
    "19": "Dynamic remarketing item: Local",
    "20": "Dynamic remarketing item: Jobs"
  }

  var query = "SELECT PlaceholderType, DisapprovalShortNames, FeedId, FeedItemId, AttributeValues, Status " +
    "FROM PLACEHOLDER_FEED_ITEM_REPORT " +
    "WHERE DisapprovalShortNames != '' " +
    "AND Status != REMOVED " +
    "DURING TODAY"

  var report = AdsApp.report(query)
  var rows = report.rows(), values = [], iterator = {}, reasons = {}, total = 0
  var unknownTypes = {}
  while (rows.hasNext()) {
    var row = rows.next()
    if (SKIP_DYNAMIC_REMARKETING && nameMapping[row.PlaceholderType] && nameMapping[row.PlaceholderType].match('Dynamic')) continue
    row.ExtensionType = nameMapping[row.PlaceholderType]
    total++
    if (!row.ExtensionType) {
      if (!unknownTypes[row.PlaceholderType]) unknownTypes[row.PlaceholderType] = 0.0
      unknownTypes[row.PlaceholderType]++
      continue
    }
    iterator[row.ExtensionType] = iterator[row.ExtensionType] || []
    iterator[row.ExtensionType].push({
      'id': row.FeedItemId,
      'attr': row.AttributeValues,
      'status': row.Status
    })
    reasons[row.FeedItemId] = row.DisapprovalShortNames
    if (values.indexOf(row.DisapprovalShortNames) == -1) {
      values.push(row.DisapprovalShortNames)
    }
  }
  if (total < 1) {
    Logger.log('found no dissaproved extensions')
    return 'no dissaproved'
  }

  var message = ''
  for (var type in iterator) {
    message += '\n>>' + type + ': ' + (iterator[type].length) + ' disapproved extensions:\n'
    Logger.log('there are %s disapproved %s extensions:', iterator[type].length, type)
    var typeMessage = iterator[type].map(function (item) {
      var reason = JSON.parse(reasons[item.id])[0].split('\t')[0]
      return 'reason: ' + reason + ' (id:' + item.id + ')\n' + flat(JSON.parse(item.attr))
    })
    message += typeMessage.join('\n') + '\n'
  }
  Logger.log(message)

  if (EMAIL && EMAIL.length && EMAIL.length > 0) { 
    MailApp.sendEmail(EMAIL, 'Disapproved Extensions Report for ' + AdsApp.currentAccount().getName(), message)
  }
}

// Helper function for displaying extensions
function flat(record) {
  var s = []
  for (var key in record) {
    if (key > 3) {
      s.push('...')
      break
    }
    var val = record[key].join ? record[key].join(',') : record[key]
    s.push(val)
  }
  return s.join('\n')
}
/******************************************
* ETA vs RSA Test
* @version: 1.0
* @author: Naman Jindal (Optmyzr)
* March 2, 2020
*******************************************/

var LOOKBACK_DAYS = 30; // Number of Days to look back for stats
var EMAILS = ['example@example.com']; // Array of Emails separated by comma
var CAMPAIGN_NAME_CONTAINS = ''; // Case Insensitive
var CAMPAIGN_NAME_DOES_NOT_CONTAIN = ''; // Case Insensitive


// Do not edit anything below this line

function main() {
  
  var DATE_RANGE = getAdWordsFormattedDate(LOOKBACK_DAYS, 'yyyyMMdd') + ',' + getAdWordsFormattedDate(1, 'yyyyMMdd');
  
  var adMap = {}, agMap = {};
  var query = [
    'SELECT Id, AdGroupId, AdType, Status FROM AD_PERFORMANCE_REPORT',
    'WHERE CampaignStatus = ENABLED and AdGroupStatus = ENABLED',
    'and AdType IN [RESPONSIVE_SEARCH_AD, EXPANDED_TEXT_AD]',
    CAMPAIGN_NAME_CONTAINS ? 'and CampaignName CONTAINS_IGNORE_CASE "' + CAMPAIGN_NAME_CONTAINS + '"' : '',
    CAMPAIGN_NAME_DOES_NOT_CONTAIN ? 'and CampaignName DOES_NOT_CONTAIN_IGNORE_CASE "' + CAMPAIGN_NAME_DOES_NOT_CONTAIN + '"' : '',
    'DURING', DATE_RANGE
  ].join(' ');
  
  var rows = AdsApp.report(query, {'includeZeroImpressions': false }).rows();
  while(rows.hasNext()) {
   var row = rows.next();
    var key = [row.AdGroupId, row.Id].join('-');
    adMap[key] = row.AdType;
    
     if(!agMap[row.AdGroupId] ) { 
       agMap[row.AdGroupId] = {
         'Responsive search ad': 0, 'Expanded text ad': 0
       }; 
     }
    
    if(row.Status == 'enabled') {
     agMap[row.AdGroupId][row.AdType]++;
    }
  }
  
  
  var agIds = Object.keys(agMap)
  var initMap = {
    'ETA': 0, 'RSA': 0,
    'Responsive search ad': { 'Impressions': 0, 'Clicks': 0, 'Conversions': 0, 'Cost': 0, 'ConversionValue': 0 } ,
    'Expanded text ad': { 'Impressions': 0, 'Clicks': 0, 'Conversions': 0, 'Cost': 0, 'ConversionValue': 0 } 
  };
    
  var statsMap = {};
  var query = [
    'SELECT',
    'Query, CampaignName, AdGroupName, AdGroupId, CreativeId, Impressions, Clicks, Conversions, Cost, ConversionValue',
    'FROM SEARCH_QUERY_PERFORMANCE_REPORT',
    'WHERE CampaignStatus = ENABLED and AdGroupStatus = ENABLED',
    CAMPAIGN_NAME_CONTAINS ? 'and CampaignName CONTAINS_IGNORE_CASE "' + CAMPAIGN_NAME_CONTAINS + '"' : '',
    CAMPAIGN_NAME_DOES_NOT_CONTAIN ? 'and CampaignName DOES_NOT_CONTAIN_IGNORE_CASE "' + CAMPAIGN_NAME_DOES_NOT_CONTAIN + '"' : '',
    agIds.length < 10000 ? 'and AdGroupId IN [' + agIds.join(',') + ']' : '',
    'DURING', DATE_RANGE
  ].join(' ');
  
  var rows = AdsApp.report(query, {'includeZeroImpressions': false }).rows();
  while(rows.hasNext()) {
   var row = rows.next();
    var adKey = [row.AdGroupId, row.CreativeId].join('-');
    var adType = adMap[adKey];
    if(!initMap[adType]) {
      continue; 
    }
    
    var agRow = agMap[row.AdGroupId];
    if(!agRow) {
      agRow = { 'Responsive search ad': 0, 'Expanded text ad': 0 }
    }
    
    var key = [row.Query, row.AdGroupName, row.CampaignName].join('!~!');
    
    if(!statsMap[key]) {
      statsMap[key] = JSON.parse(JSON.stringify(initMap));
    }
    
    statsMap[key]['ETA'] = agRow['Expanded text ad'];
    statsMap[key]['RSA'] = agRow['Responsive search ad'];
    
    row.Impressions = parseFloat(row.Impressions);
    row.Clicks = parseFloat(row.Clicks);
    row.Cost = parseFloat(row.Cost.toString().replace(/,/g, ''));
    row.Conversions = parseFloat(row.Conversions.toString().replace(/,/g, ''));
    row.ConversionValue = parseFloat(row.ConversionValue.toString().replace(/,/g, ''));
    
    statsMap[key][adType].Impressions += row.Impressions;
    statsMap[key][adType].Clicks += row.Clicks;
    statsMap[key][adType].Cost += row.Cost;
    statsMap[key][adType].Conversions += row.Conversions;
    statsMap[key][adType].ConversionValue += row.ConversionValue;
  }
  
  var output = [];
  var results = {
    'rsa':  { 'incrementalClicks': 0, 'incrementalConversions': 0 },
    'all':  { 'incrementalClicks': 0, 'incrementalConversions': 0 }
  }
  
  for(var key in statsMap) {
    var row = statsMap[key];
    var out =  key.split('!~!');
    out.push(row['ETA'], row['RSA']);
    
    var rsaRow = row['Responsive search ad']; 
    rsaRow.Ctr = rsaRow.Impressions > 0 ? rsaRow.Clicks / rsaRow.Impressions : 0;
    rsaRow.CPI = rsaRow.Impressions > 0 ? rsaRow.Conversions / rsaRow.Impressions : 0;
    rsaRow.CPA = rsaRow.Conversions > 0 ? rsaRow.Cost / rsaRow.Conversions : 0;
    rsaRow.Cpc = rsaRow.Clicks > 0 ? rsaRow.Cost / rsaRow.Clicks : 0;
    rsaRow.ROAS = rsaRow.Cost > 0 ? rsaRow.ConversionValue / rsaRow.Cost : 0;
    
    out.push(rsaRow.Impressions, rsaRow.Clicks, rsaRow.Conversions, rsaRow.Ctr, rsaRow.CPI, rsaRow.Cost, rsaRow.CPA, rsaRow.ROAS);
    
    var etaRow = row['Expanded text ad'];
    etaRow.Ctr = etaRow.Impressions > 0 ? etaRow.Clicks / etaRow.Impressions : 0;
    etaRow.CPI = etaRow.Impressions > 0 ? etaRow.Conversions / etaRow.Impressions : 0;
    etaRow.CPA = etaRow.Conversions > 0 ? etaRow.Cost / etaRow.Conversions : 0;
    etaRow.Cpc = etaRow.Clicks > 0 ? etaRow.Cost / etaRow.Clicks : 0;
    etaRow.ROAS = etaRow.Cost > 0 ? etaRow.ConversionValue / etaRow.Cost : 0;
    
    out.push(etaRow.Impressions, etaRow.Clicks, etaRow.Conversions, etaRow.Ctr, etaRow.CPI, etaRow.Cost, etaRow.CPA, etaRow.ROAS);
    
    var incrementalClicks = rsaRow.Impressions * (rsaRow.Ctr - etaRow.Ctr);
    var incrementalConversions = rsaRow.Impressions * (rsaRow.CPI - etaRow.CPI);
    var incrementalCost = rsaRow.Clicks * (rsaRow.Cpc - etaRow.Cpc);
    
    var recommendation = '';
    if(row['ETA'] == 0) {
      recommendation = 'Test ETAs';
    } else if(row['RSA'] == 0) {
      recommendation = 'Test RSAs';
    } else if(incrementalConversions > 0) {
      recommendation = 'SKAG query with existing RSA';
    } else if(incrementalConversions < 0) {
      recommendation = 'SKAG query with existing ETA';
    } else if(etaRow.Impressions == 0) {
      recommendation = 'Test ETAs';
    } else if(rsaRow.Impressions == 0) {
      recommendation = 'Test RSAs';
    } 
    
    if(row['ETA'] == 0 && etaRow.Impressions == 0) {
      results['rsa'].incrementalClicks += incrementalClicks;
      results['rsa'].incrementalConversions += incrementalConversions;
    }
    
    if(etaRow.Impressions > 0 && rsaRow.Impressions > 0) {
      results['all'].incrementalClicks += incrementalClicks;
      results['all'].incrementalConversions += incrementalConversions;
    }
    
    out.push(incrementalClicks, incrementalConversions, incrementalCost, recommendation);
    
    output.push(out);
  }
  
  if(!output.length) {
    Logger.log('No Data found');
    return;   
  }
  
  var TEMPLATE_URL = 'https://docs.google.com/spreadsheets/d/1AAk_Vsdq0LezvezOarzhOzVXsQq5BN-EKMRtGX-eDVQ/edit';
  var template = SpreadsheetApp.openByUrl(TEMPLATE_URL);
  
  var now = getAdWordsFormattedDate(0, 'MMM d, yyyy')
  var name = AdsApp.currentAccount().getName() + ' - ETA vs RSA (' + now + ')';
  var ss = template.copy(name);
  var reportUrl = ss.getUrl();
  Logger.log('Report URL: ' + reportUrl);
  ss.addEditors(EMAILS);
  
  ss.getSheets()[0].getRange(3,1,output.length,output[0].length).setValues(output);
  
  sendEmail(results, reportUrl);
}

function sendEmail(results, reportUrl) {
  var sub = AdsApp.currentAccount().getName() + ' - ETA vs RSA Test Report';
  var msg = 'Hi,\n\nPlease find below summary of latest test results:\n';
  
  var rsaResults = results['rsa'];
  if(rsaResults.incrementalClicks > 0) {
    msg += 'You got ' + Math.round(rsaResults.incrementalClicks) + 'more clicks and ' + Math.round(rsaResults.incrementalConversions)  + ' more convversions from queries that only triggered with RSA ads.\n';
  }
  
  var change = ''
  if(results['all'].incrementalConversions > 0) {
    change = 'gained';
  } else if(results['all'].incrementalConversions < 0) {
    change = 'lost';
  }
  
  if(change) {
    msg += 'For queries that showed both RSA and ETA ads, you ' + change + ' ' + Math.round(results['all'].incrementalConversions) + ' conversions.\n';
  }
  
  msg += '\n\n' + reportUrl;
  msg +- '\n\nThanks';
  
  MailApp.sendEmail(EMAILS.join(','), sub, msg);
}

function getAdWordsFormattedDate(d, format){
  var date = new Date();
  date.setDate(date.getDate() - d);
  return Utilities.formatDate(date,AdWordsApp.currentAccount().getTimeZone(),format);
}
 Save