Snippets Collections
function SendEmail(){
  var emailRange = SpreadsheetApp.getActiveSpreadsheet()
    .getSheetByName("HLP REQUESTS").getRange("K:K");

  var emailAddress = emailRange.getValues()
    .flat()           // convert a 2d array into a flat array
    .filter(String)   // remove empty elements from the array
    .pop();           // get the last element from the array

  var message = 'A request has been submitted for professional learning related to an HLP you champion.  Please check the Design Team Notes document in case follow-up is required.';
  var subject = 'HLP Request for Professional Learning';

  MailApp.sendEmail(emailAddress, subject, message);
}
function onplayssoun(snd) {

  $('audio').stop(); //Останавливаем все аудио
  var audio = new Audio(); // Создаём новый элемент Audio
  audio.src = snd; // Указываем путь к звуку "клика"
  audio.autoplay = true; // Автоматически запускаем
  var audio = $('audio')[0];
  $(document).click(function() {
    audio.play();
  });

}
// main.js
 import { convertCurrency } from './obeserver.js';
//form the export default
 import someName from './obeserver.js';


//observer.js
const url = 'https://test.com';

export const convertCurrency = (EUR) => {
   return EUR * 0.9;
 };

export default url;
function myIncludes(element) {
    const isThisArray = Array.isArray(this)
    if (isThisArray) {
        for (let i = 0; i < this.length; i++){
            if (this[i] === element) {
                return true;
            }
        }
    } else {
        for (let i = 0; i < this.length; i++){
            if (this[i] === element[0]) {
                for (let j = 1; j < element.length; j++){
                    if (this[i + j] !== element[j]) {
                        return false
                    }
                }
                return true;
            }
        }
    }
    return false; 
}
//HTML
<div class="slider">
        <div class="slide"><img src="img/img-1.jpg" alt="Photo 1" /></div>
        <div class="slide"><img src="img/img-2.jpg" alt="Photo 2" /></div>
        <div class="slide"><img src="img/img-3.jpg" alt="Photo 3" /></div>
        <div class="slide"><img src="img/img-4.jpg" alt="Photo 4" /></div> 
</div>


//CSS
/* SLIDER */
.slider {
  max-width: 100rem;
  height: 50rem;
  margin: 0 auto;
  position: relative;

  /* To hide unwanted .slide */
  overflow: hidden;
}

.slide {
  position: absolute;
  top: 0;
  width: 100%;
  height: 50rem;

  display: flex;
  align-items: center;
  justify-content: center;

  /* THIS creates the animation! */
  transition: transform 1s;
}


//JS
//Slider
const slides = document.querySelectorAll('.slide');
const btnLeft = document.querySelector('.slider__btn--left');
const btnRight = document.querySelector('.slider__btn--right');

// Set a current slide to begin with
let currentSlide = 0;
//Set a maximum number of slides else number will be infite
const maxSlide = slides.length;

const goToSlide = slide => {
  //Change position for each slide
  slides.forEach((s, i) => {
    //e. currentSlide 1: 100 * (0 - 1) = -100% each item slides left
    s.style.transform = `translateX(${100 * (i - slide)}%)`;
  });
};

//Show slide on position 0
goToSlide(0);

//Next slide
const nextSlide = () => {
  //Reset the value once we reach max
  currentSlide === maxSlide - 1
    ? (currentSlide = 0)
    : //Increase by one everytime we click 'next'
      currentSlide++;

  goToSlide(currentSlide);
};

const prevSlide = () => {
  //If it is in position 0 then by pressing prev go to the last slide
  currentSlide === 0 ? (currentSlide = maxSlide - 1) : currentSlide--;
  goToSlide(currentSlide);
};

btnRight.addEventListener('click', nextSlide);
btnLeft.addEventListener('click', prevSlide);

//Handle keyboar event left-right
document.addEventListener('keydown', function (e) {
  if (e.key === 'ArrowRight') nextSlide();
  //Also with short-circuting
  e.key === 'ArrowLeft' && nextSlide();
});
//HTML
<img 
src="img/digital-lazy.jpg"
data-src="img/digital.jpg"
alt="Computer"
class="features__img lazy-img" 
/>

//CSS
.lazy-img {
  filter: blur(20px);
}

//Lazy loading Images
const imgTargets = document.querySelectorAll('img[data-src]');

const loadImage = (entries, observer) => {
  const [entry] = entries;

  if (!entry.isIntersecting) return;

  //Replace src with data-src
  entry.target.src = entry.target.dataset.src;
  //Remove lazy-img class after img has been loaded
  entry.target.addEventListener('load', function () {
    entry.target.classList.remove('lazy-img');
  });

  observer.unobserve(entry.target);
};

const imgObserver = new IntersectionObserver(loadImage, {
  root: null,
  threshold: 0,
  rootMargin: '200px',
});

imgTargets.forEach(img => imgObserver.observe(img));
//Menu Fade Animation
const handleHover = function (e) {
  if (e.target.classList.contains('nav__link')) {
    const link = e.target;
    const siblings = link.closest('.nav').querySelectorAll('.nav__link');
    const logo = link.closest('.nav').querySelector('img');

    siblings.forEach(el => {
      if (el !== link) el.style.opacity = this;
    });
    logo.style.opacity = this;
  }
};

//Passing "argument" into handler
nav.addEventListener('mouseover', handleHover.bind(0.5));
nav.addEventListener('mouseout', handleHover.bind(1));
const contract = caver.contract.create(
  erc721Abi,
  '0xae7572e91540e025cdd88bf0b996b67e2d353c7c'
);
const eventList = await contract
.getPastEvents('Transfer', {
  fromBlock: '102232648',
  toBlock: 'latest',
})
.then((events) => {
  console.log(events);
}
string_parameterize = function (str1) {
    return str1.trim().toLowerCase().replace(/[^a-zA-Z0-9 -]/, "").replace(/\s/g, "-");
};
console.log(string_parameterize("Robin Singh from USA."));


protect_email = function (user_email) {
    var avg, splitted, part1, part2;
    splitted = user_email.split("@");
    part1 = splitted[0];
    avg = part1.length / 2;
    part1 = part1.substring(0, (part1.length - avg));
    part2 = splitted[1];
    return part1 + "...@" + part2;
};

console.log(protect_email("robin_singh@example.com"));


abbrev_name = function (str1) {
    var split_names = str1.trim().split(" ");
    if (split_names.length > 1) {
        return (split_names[0] + " " + split_names[1].charAt(0) + ".");
    }
    return split_names[0];
};
console.log(abbrev_name("Robin Singh"));


sudo apt-get install -y gconf-service libasound2 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgcc1 libgconf-2-4 libgdk-pixbuf2.0-0 libglib2.0-0 libgtk-3-0 libnspr4 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 ca-certificates fonts-liberation libappindicator1 libnss3 lsb-release xdg-utils wget libgbm-dev
import java.util.ArrayList;

class Playlist {
  
  public static void main(String[] args) {
    ArrayList<String> desertIslandPlaylist = new ArrayList <String>();

    desertIslandPlaylist.add("Moon");
    desertIslandPlaylist.add("Let it All Workout");
    desertIslandPlaylist.add("Can't Get Close");
    desertIslandPlaylist.add("Lord I Need You");
    desertIslandPlaylist.add("Feel");
    desertIslandPlaylist.add("24 hours");
    desertIslandPlaylist.add("Bad News");
    desertIslandPlaylist.add("Pure Souls");
    desertIslandPlaylist.add("Come To Life");

     //System.out.println(desertIslandPlaylist);
    // System.out.println(desertIslandPlaylist.size());
     desertIslandPlaylist.remove("Bad News");
     desertIslandPlaylist.remove("Pure Souls");
     desertIslandPlaylist.remove("Feel");
     desertIslandPlaylist.remove("Lord I Need You");
     //System.out.println(desertIslandPlaylist.size());
//Get the indices of the songs you want to swap.
    int indexA = desertIslandPlaylist.indexOf("Let it All Workout");
    int indexB = desertIslandPlaylist.indexOf("Moon");
    //Create a temporary variable to store the value of song a. (We’ll call the songs a and b here.)
    String tempA = "Let it All Workout";
    //Rewrite the value at the index of a to the value of b.

    desertIslandPlaylist.set(indexA, "Moon");
    desertIslandPlaylist.set(indexB, "Let it All Workout");

    System.out.println(desertIslandPlaylist.size());
    System.out.println(desertIslandPlaylist);
  }
  
}
// componente html
<!-- Imagen -->
  <el-form-item 
    label="Imagen" 
    prop="imagen"
  >
  <el-upload 
    class="avatar-uploader" 
    action="" 
    drag 
    :auto-upload="false" 
    :show-file-list="false"
    :multiple="false" 
    :on-change="onUploadChange" 
    accept=".jpeg, .png, .jpg, .gif, .svg"
   >
     <img 
        v-if="imageUrl" 
        :src="imageUrl" 
        class="avatar" 
    />
    <div 
    	v-else 
   	 	class="el-upload__text"
    >
      Suelta tus archivos aquí o
        <em>haz clic para cargar</em>
    	<p>Sólo archivos .jpeg, .png, .jpg, .gif, .svg</p>
    	</div>
    	<!-- <el-icon v-else class="avatar-uploader-icon"></el-icon> -->
   </el-upload>
</el-form-item>

// codigo js
onUploadChange(file) {
      this.imageUrl = URL.createObjectURL(file.raw);
      this.form.imagenNueva = file.raw;
    },

data(){
      imageUrl: null,
}
moneda(x){
    return x.toLocaleString('es-AR');
},
const session = require('express-session');

const SequelizeStore = require('connect-session-sequelize')(session.Store);

const sess = {
  secret: 'Super secret secret',
  cookie: {},
  resave: false,
  saveUninitialized: true,
  store: new SequelizeStore({
    db: sequelize
  })
};

app.use(session(sess));
<script type="text/javascript">
        $(function() {
            $("#techSkill").change(function() {
                if ($(this).val() == "X") {
                    $("#techBox1").show();
                } else {
                    $("#techBox1").hide();
                }
            });
        });
        
        $(function() {
            $("#techSkill").change(function() {
                if ($(this).val() == "Y") {
                    $("#techBox2").show();
                } else {
                    $("#techBox2").hide();
                }
            });
        });
        

        $(function() {
            $("#techSkill").change(function() {
                if ($(this).val() == "Z") {
                    $("#techBox3").show();
                } else {
                    $("#techBox3").hide();
                }
            });
        });
        
        
        // validation

        function validateForm() {
            var natsid = document.forms["student_registration"]["natsid"];
            var techBox1 = document.forms["student_registration"]["techBox1"];
            var techBox2 = document.forms["student_registration"]["techBox2"];
            var techBox3 = document.forms["student_registration"]["techBox3"];
            var comSk = document.forms["student_registration"]["comSk"];
            var leadSk = document.forms["student_registration"]["leadSk"];
            var mulSk = document.forms["student_registration"]["mulSk"];
            var timeSk = document.forms["student_registration"]["timeSk"];
            var analSk = document.forms["student_registration"]["analSk"];
            var posiSk = document.forms["student_registration"]["posiSk"];
            var att = document.forms["student_registration"]["att"];
            var batch = document.forms["student_registration"]["batch"];

            var avg = (parseInt(comSk.value) + parseInt(leadSk.value) + parseInt(mulSk.value) + parseInt(timeSk.value) + parseInt(analSk.value) + parseInt(posiSk.value)) / 9;
            console.log(avg)
            if (natsid.value == "") 
            {
                document.getElementById("natsid_error").innerText = "Please enter your Registered NATS ID";
                return;
            }
            if (natsid.value.length != 16) {
                document.getElementById("natsid_error").innerText = "Please enter your Registered Sixteen Digit NATS ID";
                return;
            }
            document.getElementById("natsid_error").innerText = "";

            if (techBox1.value < 8) {
                document.getElementById("tech_error").innerText = "You are not Eligible";
                document.forms["student_registration"]["Submit"].disabled = true
                return;
            }
            if (techBox2.value < 8) {
                document.getElementById("tech_error").innerText = "You are not Eligible";
                document.forms["student_registration"]["Submit"].disabled = true
                return;
            }
            if (techBox3.value < 8) {
                document.getElementById("tech_error").innerText = "You are not Eligible";
                document.forms["student_registration"]["Submit"].disabled = true
                return;
            }
            



            if (avg > 8) {
                document.getElementById("form_error").innerText = ""
                document.forms["student_registration"]["Submit"].disabled = false
            } else {
                document.forms["student_registration"]["Submit"].disabled = true
                document.getElementById("form_error").innerText = "You are not Eligible"
                return;
            }
            if (parseInt(att.value) < 80) {
                document.getElementById("form_error").innerText = "You are not Eligible";
                document.forms["student_registration"]["Submit"].disabled = true
                return;
            } else {
                document.getElementById("form_error").innerText = ""
                document.forms["student_registration"]["Submit"].disabled = false
            }
        }
    </script>
// CSS
.blog-home-section{padding:0 0 70px;}
.blog-home-section .blog-clm{width: 100%;}
.blog-home-section .card-blog{float: left;margin:75px 10px 12px;width:calc(33.33% - 20px)!important;border:0;border-radius:6px;color:rgba(0,0,0,0.87);background:#fff;box-shadow:0 2px 2px 0 rgb(0 0 0 / 14%),0 3px 1px -2px rgb(0 0 0 / 20%),0 1px 5px 0 rgb(0 0 0 / 12%);}

//JS
$('#load-data').isotope({
  itemSelector: '.card-blog',
  masonry: {
    // use outer width of grid-sizer for columnWidth
    columnWidth: '.card-blog'
  }
});
                              
// Script
                              
<script src="https://unpkg.com/isotope-layout@3/dist/isotope.pkgd.min.js"></script>
jQuery('img').each(function($){
            var $img = jQuery(this);
            var imgID = $img.attr('id');
            var imgClass = $img.attr('class');
            var imgURL = $img.attr('src');

            jQuery.get(imgURL, function(data) {
                // Get the SVG tag, ignore the rest
                var $svg = jQuery(data).find('svg');

                // Add replaced image's ID to the new SVG
                if(typeof imgID !== 'undefined') {
                    $svg = $svg.attr('id', imgID);
                }
                // Add replaced image's classes to the new SVG
                if(typeof imgClass !== 'undefined') {
                    $svg = $svg.attr('class', imgClass+' replaced-svg');
                }

                // Remove any invalid XML tags as per http://validator.w3.org
                $svg = $svg.removeAttr('xmlns:a');

                // Replace image with new SVG
                $img.replaceWith($svg);

            }, 'xml');

        });
//Select html elements
const labelDays = document.querySelector('.days');
const labelHours = document.querySelector('.hours');
const labelMinutes = document.querySelector('.minutes');
const labelSeconds = document.querySelector('.seconds');

//Calc how many milliseconds left
const calcTimeLeft = () => {
  const futureDate = new Date('January 1, 2023 00:00:00').getTime();
  const today = new Date().getTime();

  //Milliseconds Left
  const millisecondsLeft = futureDate - today;

  //How time works
  const second = 1000;
  const minute = second * 60;
  const hour = minute * 60;
  const day = hour * 24; //milliseconds

  //Calculate time left
  const calcDays = Math.floor(millisecondsLeft / day);
  const calcHours = Math.floor((millisecondsLeft % day) / hour);
  const calcMinutes = Math.floor((millisecondsLeft % hour) / minute);
  const calcSeconds = Math.floor((millisecondsLeft % minute) / second);

  //Update UI
  labelDays.textContent = calcDays;
  labelHours.textContent = calcHours.toString().padStart(2, '0');
  labelMinutes.textContent = calcMinutes.toString().padStart(2, '0');
  labelSeconds.textContent = calcSeconds.toString().padStart(2, '0');
};

setInterval(calcTimeLeft, 1000);
function scrollBanner() {
      jQuery(document).on('scroll', function(){
      var scrollPos = jQuery(this).scrollTop();
        jQuery('.home_banner').css({
          'top' : (scrollPos/4)+'px',
        });
      });    
      }
scrollBanner(); 


// With out function


jQuery(document).ready(function(){
	
	jQuery(window).on('scroll', function(){
		var scrollTop = jQuery(window).scrollTop();
		jQuery('.home_banner').css({'top': (scrollTop/4) +'px'});
		
	});
});
const calcDaysPassed = (date1, date2) =>
  Math.round(Math.abs((date2 - date1) / (1000 * 60 * 60 * 24)));

const day1 = calcDaysPassed(new Date(2037, 3, 14), new Date(2037, 3, 24));

//(1000 * 60 * 60 * 24) 1000milliseconds/sec 60sec/min 60min/hour 24hours/day
//Math.abs we use so that it doesn't matter which date is used first (remove -)
//Math.floor to remove decimals that occur if hours and minutes are included
import java.util.ArrayList;

class ToDos {
    
  public static void main(String[] args) {
    
    // Sherlock
    ArrayList<String> sherlocksToDos = new ArrayList<String>();
    
    sherlocksToDos.add("visit the crime scene");
    sherlocksToDos.add("play violin");
    sherlocksToDos.add("interview suspects");
    sherlocksToDos.add("listen to Dr. Watson for amusement");
    sherlocksToDos.add("solve the case");
    sherlocksToDos.add("apprehend the criminal");
    
    sherlocksToDos.remove("visit the crime scene");
    
    // Calculate to-dos until case is solved:
    System.out.println(sherlocksToDos.indexOf("solve the case"));
      
    // Change the value printed:
    System.out.println("PRINT THE ANSWER HERE");

  }
  
}
import java.util.ArrayList;

class ToDos {
    
  public static void main(String[] args) {
    
    // Sherlock
    ArrayList<String> sherlocksToDos = new ArrayList<String>();
    
    sherlocksToDos.add("visit the crime scene");
    sherlocksToDos.add("play violin");
    sherlocksToDos.add("interview suspects");
    sherlocksToDos.add("solve the case");
    sherlocksToDos.add("apprehend the criminal");
    
    // Poirot
    ArrayList<String> poirotsToDos = new ArrayList<String>();
    
    poirotsToDos.add("visit the crime scene");
    poirotsToDos.add("interview suspects");
    poirotsToDos.add("let the little grey cells do their work");
    poirotsToDos.add("trim mustache");
    poirotsToDos.add("call all suspects together");
    poirotsToDos.add("reveal the truth of the crime");
    
    // Remove each to-do below:
    sherlocksToDos.remove("visit the crime scene");
    poirotsToDos.remove("visit the crime scene");
     sherlocksToDos.remove("play violin"); 
    System.out.println(sherlocksToDos.toString() + "\n");
    System.out.println(poirotsToDos.toString());
  }
  
}
import java.util.ArrayList;

class ToDos {
    
  public static void main(String[] args) {
    
    // Sherlock
    ArrayList<String> sherlocksToDos = new ArrayList<String>();
    
    sherlocksToDos.add("visit the crime scene");
    sherlocksToDos.add("play violin");
    sherlocksToDos.add("interview suspects");
    sherlocksToDos.add("solve the case");
    sherlocksToDos.add("apprehend the criminal");
    
    // Poirot
    ArrayList<String> poirotsToDos = new ArrayList<String>();
    
    poirotsToDos.add("visit the crime scene");
    poirotsToDos.add("interview suspects");
    poirotsToDos.add("let the little grey cells do their work");
    poirotsToDos.add("trim mustache");
    poirotsToDos.add("call all suspects together");
    poirotsToDos.add("reveal the truth of the crime");
    
    // Set each to-do below:
    sherlocksToDos.set(1, "listen to Dr. Watson for amusement");
    poirotsToDos.set(3, "listen to Captain Hastings for amusement");
    
    System.out.println("Sherlock's to-do list:");
    System.out.println(sherlocksToDos.toString() + "\n");
    System.out.println("Poirot's to-do list:");
    System.out.println(poirotsToDos.toString());
  }
  
}import java.util.ArrayList;

class ToDos {
    
  public static void main(String[] args) {
    
    // Sherlock
    ArrayList<String> sherlocksToDos = new ArrayList<String>();
    
    sherlocksToDos.add("visit the crime scene");
    sherlocksToDos.add("play violin");
    sherlocksToDos.add("interview suspects");
    sherlocksToDos.add("solve the case");
    sherlocksToDos.add("apprehend the criminal");
    
    // Poirot
    ArrayList<String> poirotsToDos = new ArrayList<String>();
    
    poirotsToDos.add("visit the crime scene");
    poirotsToDos.add("interview suspects");
    poirotsToDos.add("let the little grey cells do their work");
    poirotsToDos.add("trim mustache");
    poirotsToDos.add("call all suspects together");
    poirotsToDos.add("reveal the truth of the crime");
    
    // Set each to-do below:
    sherlocksToDos.set(1, "listen to Dr. Watson for amusement");
    poirotsToDos.set(3, "listen to Captain Hastings for amusement");
    
    System.out.println("Sherlock's to-do list:");
    System.out.println(sherlocksToDos.toString() + "\n");
    System.out.println("Poirot's to-do list:");
    System.out.println(poirotsToDos.toString());
  }
  
}
import java.util.ArrayList;

class ToDos {
    
  public static void main(String[] args) {
    
    // Sherlock
    ArrayList<String> sherlocksToDos = new ArrayList<String>();
    
    sherlocksToDos.add("visit the crime scene");
    sherlocksToDos.add("play violin");
    sherlocksToDos.add("interview suspects");
    sherlocksToDos.add("solve the case");
    sherlocksToDos.add("apprehend the criminal");
    
    // Poirot
    ArrayList<String> poirotsToDos = new ArrayList<String>();
    
    poirotsToDos.add("visit the crime scene");
    poirotsToDos.add("interview suspects");
    poirotsToDos.add("let the little grey cells do their work");
    poirotsToDos.add("trim mustache");
    poirotsToDos.add("call all suspects together");
    poirotsToDos.add("reveal the truth of the crime");
    
    System.out.println("Sherlock's third to-do:");
    // Print Sherlock's third to-do:
    System.out.println(sherlocksToDos.get(2));
    
    System.out.println("\nPoirot's second to-do:");
    // Print Poirot's second to-do:
    
    System.out.println(poirotsToDos.get(1));
  }
  
}
import java.util.ArrayList;

class ToDos {
    
  public static void main(String[] args) {
    
    // Sherlock
    ArrayList<String> sherlocksToDos = new ArrayList<String>();
    
    sherlocksToDos.add("visit the crime scene");
    sherlocksToDos.add("play violin");
    sherlocksToDos.add("interview suspects");
    sherlocksToDos.add("solve the case");
    sherlocksToDos.add("apprehend the criminal");
    
    // Poirot
    ArrayList<String> poirotsToDos = new ArrayList<String>();
    
    poirotsToDos.add("visit the crime scene");
    poirotsToDos.add("interview suspects");
    poirotsToDos.add("let the little grey cells do their work");
    poirotsToDos.add("trim mustache");
    poirotsToDos.add("call all suspects together");
    poirotsToDos.add("reveal the truth of the crime");
    
    // Print the size of each ArrayList below:
    System.out.println(sherlocksToDos.size());
     System.out.println(poirotsToDos.size()); 
    // Print the name of the detective with the larger to-do list:
    System.out.println("Poirot");
  }
  
}
import java.util.ArrayList;

class ToDos {
    
  public static void main(String[] args) {
    
    ArrayList<String> toDoList = new ArrayList<String>();
    String toDo1 = "Water plants";

    // Add more to-dos here:
    String toDo2 = "Mow Lawn";
    String toDo3 = "Make bed";   
    
    // Add to-dos to toDoList
    toDoList.add(toDo1);
    toDoList.add(toDo2);
    toDoList.add(toDo3);
    System.out.println(toDoList);
      
    
  }
  
}
// import the ArrayList package here:
import java.util.ArrayList;

class ToDos {
  
  public static void main(String[] args) {
    
    // Create toDoList below:
    ArrayList<String> toDoList = new ArrayList<String>();
    
  }
  
}
import java.util.Arrays;

public class Classroom {
  
  public static void main(String[] args){
    String[] students = {"Sade", "Alexus", "Sam", "Koma"};
     double[] mathScores = new double[4];
     mathScores[0] = 94.5;
     mathScores[2] = 76.8;
     System.out.println("The number of students in the class is "+ students.length+".");
  }
}
import java.util.Arrays;

public class Newsfeed {
  
  String[] topics;
  
  public Newsfeed(String[] initialTopics) {
		topics = initialTopics;
  }
  
  public static void main(String[] args) {
		Newsfeed feed;
    if (args[0].equals("Human")) {
      
      //topics for a Human feed:
      String[] humanTopics = {"Politics", "Science", "Sports", "Love"};
			feed = new Newsfeed(humanTopics);
      
    } else if(args[0].equals("Robot")) {
      
      //topics for a Robot feed:
      String[] robotTopics = {"Oil", "Parts", "Algorithms", "Love"};
      feed = new Newsfeed(robotTopics);
      
    } else {
      String[] genericTopics = {"Opinion", "Tech", "Science", "Health"};
      feed = new Newsfeed(genericTopics);
    }
        
    System.out.println("The topics in this feed are:");
    System.out.println(Arrays.toString(feed.topics));
  }
}
import java.util.Arrays;

public class Newsfeed {
  
  String[] topics = {"Opinion", "Tech", "Science", "Health"};
  int[] views = {0, 0, 0, 0};
  
  public Newsfeed(){

  }
    
  public String[] getTopics(){
    return topics;
  }
  
  public int getNumTopics(){
    return topics.length;
  }
  
  public static void main(String[] args){
    Newsfeed sampleFeed = new Newsfeed();
    
    System.out.println("The number of topics is "+ sampleFeed.getNumTopics());
   
  }
}
import java.util.Arrays;

public class Newsfeed {
  
  String[] topics = {"Opinion", "Tech", "Science", "Health"};
  int[] views = {0, 0, 0, 0};
  String[] favoriteArticles;
  
  public Newsfeed(){
    // Initialize favoriteArticles here:
    favoriteArticles = new String[10];
  }
  
  public void setFavoriteArticle(int favoriteIndex, String newArticle){
    // Add newArticle to favoriteArticles:
    
    favoriteArticles[favoriteIndex] = newArticle;
  }
    
  public static void main(String[] args){
    Newsfeed sampleFeed = new Newsfeed();
    
    sampleFeed.setFavoriteArticle(2, "Humans: Exterminate Or Not?");
    sampleFeed.setFavoriteArticle(3, "Organic Eye Implants");
    sampleFeed.setFavoriteArticle(0, "Oil News");
    
    System.out.println(Arrays.toString(sampleFeed.favoriteArticles));
  }
}
import java.util.Arrays;

public class Newsfeed {
  
  String[] topics = {"Opinion", "Tech", "Science", "Health"};
  int[] views = {0, 0, 0, 0};
  
  public Newsfeed(){

  }
    
  public String[] getTopics(){
    return topics;
  }
  
  public String getTopTopic(){
    
    return topics[0];
  }
  
  public void viewTopic(int topicIndex){
    views[topicIndex] = views[topicIndex] + 1;
  }

  public static void main(String[] args){
    Newsfeed sampleFeed = new Newsfeed();
    
    System.out.println("The top topic is "+ sampleFeed.getTopTopic());
    
    sampleFeed.viewTopic(1);
    sampleFeed.viewTopic(1);
    sampleFeed.viewTopic(3);
    sampleFeed.viewTopic(2);
    sampleFeed.viewTopic(2);
    sampleFeed.viewTopic(1);
    
    System.out.println("The " + sampleFeed.topics[1] + " topic has been viewed " + sampleFeed.views[1] + " times!"); 
  }
}
// import the Arrays package here:
import java.util.Arrays;
public class Newsfeed {
  
  
  public Newsfeed(){
    
  }
    
  public String[] getTopics(){
    String[] topics = {"Opinion", "Tech", "Science", "Health"};
    return topics;
  }
  

  public static void main(String[] args){
    Newsfeed sampleFeed = new Newsfeed();
    String[] topics = sampleFeed.getTopics();
    System.out.println(Arrays.toString(topics));
  }
}
public class Newsfeed {
  
  
  public Newsfeed(){
    
  }
  
  // Create getTopics() below:
  public String[] getTopics(){
    String[] topics = {"Opinion", "Tech", "Science", "Health"};
    return topics;
  }

  public static void main(String[] args){
    Newsfeed sampleFeed = new Newsfeed();
    
    String[] topics = sampleFeed.getTopics();
    System.out.println(topics);
    
  }
}
public class Continents {
	public static void main(String[] args) {
    int continent = 1;

    switch(continent){

      case 1:
      System.out.println("North America: Mexico City, Mexico");
      break;
        case 2:
      System.out.println("South America: Sao Paulo, Brazil");
      break;
        case 3:
      System.out.println("Europe: Moscow, Russia");
      break;
        case 4:
      System.out.println("Africa: Lagos, Nigeria");
      break;
        case 5:
      System.out.println("Asia: Shanghai, China");
      break;
        case 6:
      System.out.println("Australia: Sydney, Australia");
      break;
        case 7:
      System.out.println("Antarctica: McMurdo Station, US");
      break;
      default:
      System.out.println("Undefined continent!");


    }

		

	}
}
public class CarLoan {
  
	public static void main(String[] args) {
   int carLoan = 10000;
  int loanLength = 3;
  int interestRate =5;
  int downPayment = 2000;

	 if (loanLength <= 0 || interestRate <= 0){
    System.out.println("Error! You must take out a valid car loan.");
  }else if ( downPayment>= carLoan){
     System.out.println("The car can be paid in full.");
  }else{
    int remainingBalance = carLoan - downPayment;
    int months = loanLength *12;
    int monthlyBalance = remainingBalance / months;
    int interest = (monthlyBalance * interestRate)/100;
    int monthlyPayment = monthlyBalance + interest;
    System.out.println(monthlyPayment);
  }

	}
}
public class Reservation {
  int guestCount;
  int restaurantCapacity;
  boolean isRestaurantOpen;
  boolean isConfirmed;
  
  public Reservation(int count, int capacity, boolean open) {
    if (count < 1 || count > 8) {
      System.out.println("Invalid reservation!");
    }
    guestCount = count;
		restaurantCapacity = capacity;
		isRestaurantOpen = open;
  }  
  
  public void confirmReservation() {
    if (restaurantCapacity >= guestCount && isRestaurantOpen) {
      System.out.println("Reservation confirmed");
      isConfirmed = true;
    } else {
      System.out.println("Reservation denied");
			isConfirmed = false;
    }
  }
  
  public void informUser() {
    // Write conditional here
  if (!isConfirmed){
    System.out.println("Unable to confirm reservation, please contact restaurant.");
  }else{
    System.out.println("Please enjoy your meal!");
  }
  }
  
  public static void main(String[] args) {
    Reservation partyOfThree = new Reservation(3, 12, true);
    Reservation partyOfFour = new Reservation(4, 3, true);
    partyOfThree.confirmReservation();
    partyOfThree.informUser();
    partyOfFour.confirmReservation();
    partyOfFour.informUser();
  }
}
public class Reservation {
  int guestCount;
  int restaurantCapacity;
  boolean isRestaurantOpen;
  boolean isConfirmed;
  
  public Reservation(int count, int capacity, boolean open) {
    // Write conditional statement below
     if (count<1 || count>8) {
  System.out.println("Invalid reservation!");
}
    
    guestCount = count;
		restaurantCapacity = capacity;
		isRestaurantOpen = open;
  }  
  
  public void confirmReservation() {
    if (restaurantCapacity >= guestCount && isRestaurantOpen) {
      System.out.println("Reservation confirmed");
      isConfirmed = true;
    } else {
      System.out.println("Reservation denied");
			isConfirmed = false;
    }
  }
  
  public void informUser() {
    System.out.println("Please enjoy your meal!");
  }
  
  public static void main(String[] args) {
    Reservation partyOfThree = new Reservation(3, 12, true);
    Reservation partyOfFour = new Reservation(4, 3, true);
    partyOfThree.confirmReservation();
    partyOfThree.informUser();
    partyOfFour.confirmReservation();
    partyOfFour.informUser();
  }
}
public class Reservation {
  int guestCount;
  int restaurantCapacity;
  boolean isRestaurantOpen;
  boolean isConfirmed;
  
  public Reservation(int count, int capacity, boolean open) {
    guestCount = count;
		restaurantCapacity = capacity;
		isRestaurantOpen = open;
  }  
  
  public void confirmReservation() {
    /* 
       Write conditional
       ~~~~~~~~~~~~~~~~~
       if restaurantCapacity is greater
       or equal to guestCount
       AND
       the restaurant is open:
         print "Reservation confirmed"
         set isConfirmed to true
       else:
         print "Reservation denied"
         set isConfirmed to false
    */
   if (restaurantCapacity>= guestCount && isRestaurantOpen) {
  System.out.println("Reservation confirmed");
  isConfirmed = true;
}else{
  System.out.println("Reservation denied");
  isConfirmed = false;
}

  }
  
  public void informUser() {
    System.out.println("Please enjoy your meal!");
  }
  
  public static void main(String[] args) {
    Reservation partyOfThree = new Reservation(3, 12, true);
    Reservation partyOfFour = new Reservation(4, 3, true);
    partyOfThree.confirmReservation();
    partyOfThree.informUser();
    partyOfFour.confirmReservation();
    partyOfFour.informUser();
  }
}
/**
 *
 * @param {Date} dateObject
 */

//Formatting Dates
function formateDate(dateObject) {
  const parts = {
    date: dateObject.getDate(),
    month: dateObject.getMonth() + 1,
    year: dateObject.getFullYear(),
    hour: dateObject.getHours() % 12 || 12,
    minute: dateObject.getMinutes().toString().padStart(2, '0'),
    amOrPm: dateObject.getHours() < 12 ? 'AM' : 'PM',
  };

  return `${parts.date}/${parts.month}/${parts.year} ${parts.hour}:${parts.minute} ${parts.amOrPm}`;
}

const myDate = new Date();
const myDateFormatted = formateDate(myDate);

console.log(myDateFormatted);

//INTERNATINALIZING DATES new Intl.DateTimeFormat().format(date)

// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat

const currentDate = new Date();
labelDate.textContent = new Intl.DateTimeFormat('de-DE').format(currentDate);

//Using options
let options = { weekday: 'long' //'short' 'narrow', 
               year: 'numeric',
               month: 'long' //'2-digit',
               day: 'numeric',
               hour: 'numeric',
               minute: 'numeric',
               second: 'numeric',
               hour12: false, 
              };

//Instead of manually setting the language 'de-DE' you can also detect the user's browser preferred language
const localLanguage = navigator.language;

console.log(new Intl.DateTimeFormat(localLanguage, options).format(currentDate));
// → "Donnerstag, 20. Dezember 2012 - 17:29:01"
// __tests__/helpers.test.js

const { format_date, format_plural } = require('../utils/helpers');


test('format_date() returns a date string', () => {
  const date = new Date('2020-03-20 16:12:03');

  expect(format_date(date)).toBe('3/20/2020');
});

========================

// /utils/helpers.js

module.exports = {
  format_date: (date) => {
    return `${new Date(date).getMonth() + 1}/${new Date(date).getDate()}/${new Date(date).getFullYear()}`;
  },
};
public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  
  public Order(boolean filled, double cost, String shippingMethod) {
		if (cost > 24.00) {
      System.out.println("High value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
      System.out.println("Shipping cost: " + calculateShipping());
    } else {
      System.out.println("Order not ready");
    }
  }
  
  public double calculateShipping() {
    double shippingCost;
	 	// declare switch statement here
    switch (shipping) {

      case "Regular":
        shippingCost = 0;
        break;
      case "Express":    
        shippingCost = 1.75;
        break;
      default:
        shippingCost = .50; 
    }
    
    return shippingCost;
 	}
  
  public static void main(String[] args) {
    // do not alter the main method!
    Order book = new Order(true, 9.99, "Express");
    Order chemistrySet = new Order(false, 72.50, "Regular");
    
    book.ship();
    chemistrySet.ship();
  }
}
public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  String couponCode;
  
  public Order(boolean filled, double cost, String shippingMethod, String coupon) {
		if (cost > 24.00) {
      System.out.println("High value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
    couponCode = coupon;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
      System.out.println("Shipping cost: " + calculateShipping());
    } else {
      System.out.println("Order not ready");
    }
  }
  
  public double calculateShipping() {
    if (shipping.equals("Regular")) {
      return 0;
    } else if (shipping.equals("Express")) {
      // Add your code here
      if (couponCode.equals("ship50")) {
        return 0.85;
      } else {
        return 1.75;
      }
    } else {
      return .50;
    }
 	}
  
  public static void main(String[] args) {
    // do not alter the main method!
    Order book = new Order(true, 9.99, "Express", "ship50");
    Order chemistrySet = new Order(false, 72.50, "Regular", "freeShipping");
    
    book.ship();
    chemistrySet.ship();
  }
}
public class Order {
  boolean isFilled;
  double billAmount;
  String shipping;
  
  public Order(boolean filled, double cost, String shippingMethod) {
		if (cost > 24.00) {
      System.out.println("High value item!");
    }
    isFilled = filled;
    billAmount = cost;
    shipping = shippingMethod;
  }
  
  public void ship() {
    if (isFilled) {
      System.out.println("Shipping");
      System.out.println("Shipping cost: " + calculateShipping());
    } else {
      System.out.println("Order not ready");
    }
  }
  
  public double calculateShipping() {
	 	// declare conditional statement here
    if (shipping.equals("Regular")) {
      return 0;
    } else if (shipping.equals("Express")) {
      return 1.75;
    } else {
      return .50;
    }
 	}
  
  public static void main(String[] args) {
    // do not alter the main method!
    Order book = new Order(true, 9.99, "Express");
    Order chemistrySet = new Order(false, 72.50, "Regular");
    
    book.ship();
    chemistrySet.ship();
  }
}
import { useEffect, useMemo, useRef, useState } from 'react'
import { useWeb3React } from '@web3-react/core'
import Web3 from 'web3'

import { defaultEVMNetworkId } from '@contracts/networks'

import { web3NoAccountInstances } from '@utils/web3'

export const useWeb3 = () => {
  const { library, chainId } = useWeb3React()
  const web3NoAccount = useMemo(
    () =>
      web3NoAccountInstances[
        chainId ? chainId.toString() : defaultEVMNetworkId
      ],
    [chainId]
  )
  const refChainId = useRef(chainId)
  const refWeb3 = useRef(library)
  const [web3, setweb3] = useState(library ? new Web3(library) : web3NoAccount)

  useEffect(() => {
    if (library !== refWeb3.current || chainId !== refChainId.current) {
      setweb3(library ? new Web3(library) : web3NoAccount)
      refWeb3.current = library
      refChainId.current = chainId
    }
  }, [chainId, library, web3NoAccount])

  return web3
}
import { isMobile } from 'react-device-detect'
import { useWeb3 } from '@firestarter-private/firestarter-library'
import { UnsupportedChainIdError, useWeb3React } from '@web3-react/core'

import { injected, walletconnect } from '@/connectors'

export const useWalletConnect = (): { onClickWallet: () => void } => {
  const web3 = useWeb3()
  const { activate } = useWeb3React()

  const onClickWallet = () => {
    if (isMobile) {
      // if the connector is walletconnect and the user has already tried to connect, manually reset the connector
      if (
        // @ts-ignore
        walletconnect.walletConnectProvider?.wc?.uri
      ) {
        walletconnect.walletConnectProvider = undefined
      }
      activate(walletconnect, undefined, true).catch((error) => {
        if (error instanceof UnsupportedChainIdError) {
          activate(walletconnect) // a little janky...can't use setError because the connector isn't set
        }
      })
      // @ts-ignore
      web3.setProvider(window.ethereum)
    } else {
      activate(injected)
    }
  }

  return { onClickWallet }
}
let mediaQuery = window.matchMedia("(min-width: 768px)");
if (mediaQuery.matches) {
                // destop
            } else {
                // mobile
            }
// Homepage.Handlebars
<ol class="post-list">
  {{#each posts as |post|}}
  <li>
    {{> post-info post}}
  </li>
  {{/each}}
</ol>
---
//Post-info.Handlebars (partial)
<article class='post'>
  <div class='title'>
    <a href='{{post_url}}' target='_blank'>{{title}}</a>
    <span>({{post_url}})</span>
  </div>
  <div class='meta'>
    {{vote_count}}
    point(s) by
    {{user.username}}
    on
    {{created_at}}
    |
    <a href='/post/{{id}}'>{{comments.length}} comment(s)</a>
  </div>
</article>
{{#if value}}
<div>
	This content will only display if "value" is truthy
</div>
{{/if}}

---

{{#if loggedIn}}
        <button id="logout" class="btn-no-style">logout</button>
{{else}}
        <a href="/login">login</a>
{{/if}}
// Javascript
async function signupFormHandler(event) {
  event.preventDefault();
  const username = document.querySelector('#username-signup').value.trim();
  const email = document.querySelector('#email-signup').value.trim();
  const password = document.querySelector('#password-signup').value.trim();
  if (username && email && password) {
    const response = await fetch('/api/users', {
      method: 'post',
      body: JSON.stringify({
        username,
        email,
        password,
      }),
      headers: { 'Content-Type': 'application/json' },
    });
    if (response.ok) {
      console.log(response);
    } else {
      alert(response.statusText);
    }
  }
}
async function loginFormHandler(event) {
  event.preventDefault();
  const email = document.querySelector('#email-signup').value.trim();
  const password = document.querySelector('#password-signup').value.trim();
  if (email && password) {
    const response = await fetch('/api/users/login', {
      method: 'post',
      body: JSON.stringify({
        email,
        password,
      }),
      headers: { 'Content-Type': 'application/json' },
    });
    if (response.ok) {
      document.location.replace('/')
    } else {
      alert(response.statusText);
    }
  }
}
document.querySelector('.signup-form').addEventListener('submit', signupFormHandler);
document.querySelector('.login-form').addEventListener('submit', loginFormHandler);


<!-- HTML -->

<form class='login-form'>
  <div>
    <label for='email-login'>email:</label>
    <input type='text' id='email-login' />
  </div>
  <div>
    <label for='password-login'>password:</label>
    <input type='text' id='password-login' />
  </div>
  <div>
    <button type='submit'>login</button>
  </div>
</form>
<form class='signup-form'>
  <div>
    <label for='username-signup'>username:</label>
    <input type='text' id='username-signup' />
  </div>
  <div>
    <label for='email-signup'>email:</label>
    <input type='text' id='email-signup' />
  </div>
  <div>
    <label for='password-signup'>password:</label>
    <input type='text' id='password-signup' />
  </div>
  <div>
    <button type='submit'>login</button>
  </div>
</form>
<script src="/javascript/login.js"></script>
<ol class="post-list">
  {{#each posts as |post|}}
  <li>
    <article class="post">
      <div class="title">
        <a href="{{post.post_url}}" target="_blank">{{post.title}}</a>
        <span>({{post.post_url}})</span>
      </div>
      <div class="meta">
        {{post.vote_count}} point(s) by {{post.user.username}} on
        {{post.created_at}}
        |
        <a href="/post/{{post.id}}">{{post.comments.length}} comment(s)</a>
      </div>
    </article>
  </li>
  {{/each}}
</ol>
public class Order {
  
  public static void main(String[] args) {
    
    double itemCost = 30.99;
    
    // Write an if-then statement:
   if (itemCost > 24.00) {
 
  System.out.println("High value item!");
 
} 
    
  }
  
}

/// if else example

public class Order {
  
  public static void main(String[] args) {
    
    boolean isFilled = false;
    
    // Write an if-then-else statement:
       if (isFilled) {
 
  System.out.println("Shipping");
 
} else{
  System.out.println("Order not ready");
}
    
  }
  
}
// breaks url string into array
    const id = window.location.toString().split('/') [
        // grab last item in array 
        window.location.toString().split('/').length - 1 
    ];
// breaks url string into array
    const id = window.location.toString().split('/') [
        // grab last item in array 
        window.location.toString().split('/').length - 1 
    ];
public class Droid{
//instance fields
int batteryLevel;
String name;

//constructor method
public Droid(String droidName){
  name = droidName;
  batteryLevel = 100;
}

//tostring method
public String toString(){
  return "hello, I'm the droid: " + name;
}

//peform task method 
public void performTask(String task){
System.out.println(name+" is performing task: "+ task);
 batteryLevel = batteryLevel - 10;
}

// method to print energy levels

public void energyReport(){
  System.out.println(batteryLevel);
}

//public main method
public static void main(String[] args){
 
Droid Codey = new Droid("Codey");
System.out.println(Codey);
Codey.performTask("Dancing");
Codey.energyReport();
}





}
///a calculator class the performs simple math.
public class Calculator{

public Calculator(){

}

public int add(int a,int b){
return a +b;
}

public int subtract(int a,int b){
return a - b;
}

public int multiply(int a,int b){
return a * b;
}

public int divide(int a,int b){
return a / b;
}

public int modulo(int a,int b){
return a % b;
}

public static void main(String[] args){

Calculator myCaculator = new Calculator();
System.out.println(myCaculator.add(5,7));
System.out.println(myCaculator.subtract(45,11));
}
}
public class SavingsAccount {
  
  int balance;
  
  public SavingsAccount(int initialBalance){
    balance = initialBalance;
  }
  
  public void checkBalance(){
    System.out.println("Hello!");
    System.out.println("Your balance is "+balance);
  }
  
  public void deposit(int amountToDeposit){
    balance = amountToDeposit + balance;
    System.out.println("You just deposited " + amountToDeposit);
  }
  
  public int withdraw(int amountToWithdraw){
    balance = balance - amountToWithdraw;
    System.out.println("You just withdrew " + amountToWithdraw);
    return amountToWithdraw;
  }
  
  public String toString(){
    return "This is a savings account with " + balance + " saved.";
  }
  
  public static void main(String[] args){
    SavingsAccount savings = new SavingsAccount(2000);
    
    //Check balance:
    savings.checkBalance();
    
    //Withdrawing:
    savings.withdraw(300);
    
    //Check balance:
    savings.checkBalance();
    
    //Deposit:
    savings.deposit(600);
    
    //Check balance:
    savings.checkBalance();
    
    //Deposit:
    savings.deposit(600);
    
    //Check balance:
    savings.checkBalance();
    
    System.out.println(savings);
  }       
}
public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    double newPrice = price + priceToAdd;
    price = newPrice;
  }
  
  // get price with tax method
  public double getPriceWithTax(){
    double tax = 0.08;
    double totalPrice = price + price*tax;
    return totalPrice;
  }

  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);
    Store cookieShop = new Store("Cookies", 5);
    System.out.println(lemonadeStand);
    System.out.println(cookieShop);
  }
  //toString() method
  public String toString(){
       return "This store sells "+ productType +" at a price of "+price+".";
   }
}
public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    double newPrice = price + priceToAdd;
    price = newPrice;
  }
  
  // get price with tax method
  public double getPriceWithTax(){
    double totalPrice = price+price *0.08;
    return totalPrice;
  }
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);
  double lemonadePrice = lemonadeStand.getPriceWithTax();
  System.out.println(lemonadePrice);
  }
}
public class Store {
  // instance fields
  String productType;
  double price;
  
  // constructor method
  public Store(String product, double initialPrice) {
    productType = product;
    price = initialPrice;
  }
  
  // increase price method
  public void increasePrice(double priceToAdd){
    double newPrice = price + priceToAdd;
    price = newPrice;
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade", 3.75);
    lemonadeStand.increasePrice(1.5);
    System.out.println(lemonadeStand.price);
  }
}
public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // advertise method
  public void advertise() {
    String message = "Selling " + productType + "!";
		System.out.println(message);
  }
  //greet customer method
  public void greetCustomer(String customer){
    System.out.println("Welcome to the store, " + customer + "!");
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade");
    lemonadeStand.greetCustomer("Mike");
  }
}
public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // advertise method
  public void advertise() {
		System.out.println("Selling " + productType + "!");
    System.out.println("Come spend some money!");
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("Lemonade");
    Store Cookies = new Store("Oreos");

    lemonadeStand.advertise();
    Cookies.advertise();
  }
}
public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // advertise method
  public void advertise(){
    System.out.println("Come spend some money!");
    System.out.println("Selling " + productType + "!");
  }
  // main method
  public static void main(String[] args) {
    
  }
}
window.open('https://www.codexworld.com', '_blank');
import React from 'react';
import {
  BrowserRouter, Routes, Route,
} from 'react-router-dom';
import AdminRoutes from './admin/adminRoutes';

const routes = () => (
  <BrowserRouter>
    <AdminRoutes />
    <Routes>
      <Route path="/home" element="User template" />
      <Route path="/" element="Login Template" />
      <Route path="/register" element="Register Template" />
    </Routes>
  </BrowserRouter>
);

export default routes;
<!DOCTYPE html>
<html>
<body>
  <p>클릭하세요. 클릭한 곳의 좌표가 표시됩니다.</p>
  <em class="message"></em>
  
  <script>
  function showCoords(e) { // e: event object
    const msg = document.querySelector('.message');
    msg.innerHTML =
      'clientX value: ' + e.clientX + '<br>' +
      'clientY value: ' + e.clientY;
  }
  addEventListener('click', showCoords); // 참조하는게 없으면 기본 window 전역 객체
  </script>
</body>
</html>
public class Dog {
  String breed;
  boolean hasOwner;
  int age;
  
  public Dog(String dogBreed, boolean dogOwned, int dogYears) {
    System.out.println("Constructor invoked!");
    breed = dogBreed;
    hasOwner = dogOwned;
    age = dogYears;
  }
  
  public static void main(String[] args) {
    System.out.println("Main method started");
    Dog fido = new Dog("poodle", false, 4);
    Dog nunzio = new Dog("shiba inu", true, 12);
    boolean isFidoOlder = fido.age > nunzio.age;
    int totalDogYears = nunzio.age + fido.age;
    System.out.println("Two dogs created: a " + fido.breed + " and a " + nunzio.breed);
    System.out.println("The statement that fido is an older dog is: " + isFidoOlder);
    System.out.println("The total age of the dogs is: " + totalDogYears);
    System.out.println("Main method finished");
  }
}
public class Store {
  // instance fields
  String productType;
  int inventoryCount;
  double inventoryPrice;
  
  // constructor method
  public Store(String product,int count,double price) {
    productType = product;
    inventoryCount = count;
    inventoryPrice = price;
  }
  
  // main method
  public static void main(String[] args) {
    Store cookieShop = new Store("cookies",12, 3.75);
   
  }
}
public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // main method
  public static void main(String[] args) {
    Store lemonadeStand = new Store("lemonade");
    System.out.println(lemonadeStand.productType);
    
  }
}
public class Store {
  // instance fields
  String productType;
  
  // constructor method
  public Store(String product) {
    productType = product;
  }
  
  // main method
  public static void main(String[] args) {
    
    
  }
}
public class Store {
  // declare instance fields here!
    String productType;
  
  // constructor method
  public Store() {
    System.out.println("I am inside the constructor method.");
  }
  
  // main method
  public static void main(String[] args) {
    System.out.println("This code is inside the main method.");
    
    Store lemonadeStand = new Store();
    
    System.out.println(lemonadeStand);
  }
}
public class Store {
  
  // new method: constructor!
  public Store() {
    System.out.println("I am inside the constructor method.");
  }
  
  // main method is where we create instances!
  public static void main(String[] args) {
    System.out.println("Start of the main method.");
    
    // create the instance below
    Store lemonadeStand = new Store(); 
    // print the instance below
    System.out.println(lemonadeStand);
  }
}
// 단순 함수 호출

// 1. 일반 함수 범위에서 호출
function outside() {
    console.log(this); // this는 window

    // 2. 함수 안에 함수가 선언된 내부 함수 호출
    function inside() {
        console.log(this); // this는 window
    }
    inside();
}
outside();

// 객체의 메소드(Method)

// 1. 객체 또는 클래스 안에서 메소드를 실행한다면 this는 Object 자기 자신
var man = {
    name: 'john',
    hello: function() {
        // 2. 객체이므로 this는 man을 가리킴
        console.log('hello ' + this.name);
    }
}
man.hello(); // 3. hello john

// 3. 일반 함수 welcome을 선언
function welcome() {
    // 4. 여기서 this는 전역 객체 Window이므로, 만약 실행시키면 undefined가 뜸
    console.log('welcome ' + this.name);
}

// 5. man 객체의 welcome 속성에 일반 함수 welcome을 추가
man.welcome = welcome;

// 6. welcome이 man 객체에서 호출되었으므로 welcome john이 출력됨
man.welcome();

// 7. man 객체의 thanks 속성에 함수를 선언
man.thanks = function () {
    // 8. man.thanks()를 호출하면 thanks john이 출력
    console.log('thanks ' + this.name);
}

// 8. 이 함수를 객체 외부에서 참조
var thankYou = man.thanks;

// 9. 객체 외부이므로 this가 Window 객체가 되어서 thanks (undefined)가 출력
thankYou();

// 10. 그럼 또 다른 객체에서 이 함수를 호출하면 어떻게 될까?
women = {
    name: 'barbie',
    thanks: man.thanks // 11. man.thanks 함수를 women.thanks에 참조
}

// 12. this가 포함된 함수가 호출된 객체가 women이므로 thanks barbie가 출력
women.thanks();

// 메소드 내에 함수 선언

var man = {
    name: 'john',
    // 1. 이것은 객체의 메소드
    hello: function() {
        // 2. 객체의 메소드 안에서 함수를 선언하는 것이니까 내부 함수
        function getName() {
            // 3. 여기서 this가 무엇을 가리키고 있을까?
            return this.name;
        }
        console.log('hello ' + getName()); // 4. 내부 함수를 출력시키고
    }
}
man.hello(); // 메소드를 실행시키면 undefined가 뜬다! this는 Window였던 것

// call(), apply(), bind()

// 1. 이것은 객체의 메소드
var man = {
    name: 'john',
    // 2. 객체의 메소드 안에서 함수를 선언하는 것이니까 내부 함수
    hello: function() {
        function getName() {
            // 3. 여기서 this가 무엇을 가리키고 있을까?
            return this.name;
        }
        // 4. 이번에는 call()을 통해 현재 문맥에서의 this(man 객체)를 바인딩해주었다
        console.log('hello ' + getName.call(this));
    }
}

// 이번에는 메소드를 실행시키면 john가 뜬다!
// this가 man 객체로 바인딩 된 것을 확인할 수 있다
man.hello();

// 콜백 함수

// 1. 콜백함수
var object = {
    callback: function() {
        setTimeout(function() {
            console.log(this); // 2. this는 window
        }, 1000);
    }
}

// 생성자

// 1. 클래스 역할을 할 함수 선언
function Man () {
    this.name = 'John';
}

// 2. 생성자로 객체 선언
var john = new Man();

// 3. this가 Man 객체를 가리키고 있어 이름이 정상적으로 출력된다
john.name; // => 'John'

// class 이용

// 1. Class Man 선언
class Man {
    constructor(name) {
        this.name = name;
    }
    hello() {
        console.log('hello ' + this.name)
    }
}

// 2. 생성자 실행
var john = new Man('John');
john.hello(); // 3. hello John 출력

// 화살표 함수(Arrow function)

// 1. 화살표 함수
var obj = {
    a: this, // 2. 일반적인 경우 this는 window,
    b: function() {
      console.log(this) // 3. 메소드의 경우 this는 객체
    },
    c: () => {
        console.log(this)
        // 4. 화살표 함수의 경우 정적 컨텍스트를 가짐, 함수를 호출하는 것과 this는 연관이 없음
        // 5. 따라서 화살표 함수가 정의된 obj 객체의 this를 바인딩하므로 this는 window
    }

}

obj.b() // 6. obj
obj.c() // 7. window
const addNewGoalHandler = (newGoal) => {
    // if the update of the states doesnt depend from the previous one
    setTask(task.concat(newGoal));
  	//also works setTodos([...todos, newTodo]);
    // setTask((prevtask) => {
    //   // if your state depends from the previous one
    //   return prevtask.concat(newGoal);
    // });
  };
function sendNotification() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var cell = ss.getActiveCell().getA1Notation();
  var row = sheet.getActiveRange().getRow();
  var cellvalue = ss.getActiveCell().getValue().toString();
  var recipients = "me@gmail.com";
  var message = '';
  if(cell.indexOf('G')!=-1){ 
    message = sheet.getRange('D'+ sheet.getActiveCell().getRowIndex()).getValue()
  }
  var subject = 'Update to '+sheet.getName();
  var body = sheet.getName() + ' has been updated. Visit ' + ss.getUrl() + ' to view the changes on row: «' + row + '». New comment: «' + cellvalue + '». For message: «' + message + '»';
  MailApp.sendEmail(recipients, subject, body);
};
let regex = new RegExp('[a-z0-9]+@[a-z]+\.[a-z]{2,3}');

let testEmails = ["notanemail.com", "workingexample@email.com", "another_working@somethingelse.org", "notworking@1.com"];

testEmails.forEach((address) => {
    console.log(regex.test(address))
});
function onEdit(e) {
  var editedSheet = e.source.getActiveSheet();
  var editedCell = e.range;
  var row = editedCell.getRow();
  var col = editedCell.getColumn();
  
  var ySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("APPROVE PURCHASE");

  //Check if edit is done in Sheet "X_input"
  if(editedSheet.getName()=="APPROVE PURCHASE"){
    //copy modified cell to Y_output sheet
    ySheet.getRange(row,col).setValue(e.value);


    //check if modified cell is within B2:Y61 range and send an email
   if(row>=2 && row<=1000 && col==9 && col==9)
   
   
   {
      //Send email
     var subject = "Sheet: "+editedSheet.getName();
      var message = "Cell "+editedCell.getA1Notation()+" was modified from '"+e.oldvalue+"' to '"+e.value+"'";
      MailApp.sendEmail("ashwani.kumar1@meenakshipolymers.com",subject,message);
    }
  }
 
}
function onEdit(e) {
  var editedSheet = e.source.getActiveSheet();
  var editedCell = e.range;
  var row = editedCell.getRow();
  var col = editedCell.getColumn();
  
  var ySheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Y_output");

  //Check if edit is done in Sheet "X_input"
  if(editedSheet.getName()=="X_input"){
    //copy modified cell to Y_output sheet
    ySheet.getRange(row,col).setValue(e.value);


    //check if modified cell is within B2:Y61 range and send an email
    if(row>=2 && row<=61 && col>=2 && col<=25){
      //Send email
     var subject = "Sheet: "+editedSheet.getName();
      var message = "Cell "+editedCell.getA1Notation()+" was modified from '"+e.oldvalue+"' to '"+e.value+"'";
      MailApp.sendEmail("ronoel@google.com",subject,message);
    }
  }
 
}
package org.launchcode.java.demos.collections;

import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class HashMapGradebook {

   public static void main(String[] args) {

      HashMap<String, Double> students = new HashMap<>();
      Scanner input = new Scanner(System.in);
      String newStudent;

      System.out.println("Enter your students (or ENTER to finish):");

      // Get student names and grades
      do {

         System.out.print("Student: ");
         newStudent = input.nextLine();

         if (!newStudent.equals("")) {
            System.out.print("Grade: ");
            Double newGrade = input.nextDouble();
            students.put(newStudent, newGrade);

            // Read in the newline before looping back
            input.nextLine();
         }

      } while(!newStudent.equals(""));

      // Print class roster
      System.out.println("\nClass roster:");
      double sum = 0.0;

      for (Map.Entry<String, Double> student : students.entrySet()) {
         System.out.println(student.getKey() + " (" + student.getValue() + ")");
         sum += student.getValue();
      }

      double avg = sum / students.size();
      System.out.println("Average grade: " + avg);
   }
}
//Notice how a HashMap called students is declared on line 11:
HashMap<String, Double> students = new HashMap<>();
//Here, <String, Double> defines the data types for this map’s <key, value> pairs. Like the ArrayList, when we call the HashMap constructor on the right side of the assignment, we don’t need to specify type.

//We can add a new item with a .put() method, specifying both key and value:
students.put(newStudent, newGrade);
package org.launchcode.java.demos.collections;

import java.util.Scanner;

public class ArrayGradebook {

   public static void main(String[] args) {

      // Allow for at most 30 students
      int maxStudents = 30;

      String[] students = new String[maxStudents];
      double[] grades = new double[maxStudents];
      Scanner input = new Scanner(System.in);

      String newStudent;
      int numStudents = 0;

      System.out.println("Enter your students (or ENTER to finish):");

      // Get student names
      do {
         newStudent = input.nextLine();

         if (!newStudent.equals("")) {
            students[numStudents] = newStudent;
            numStudents++;
         }

      } while(!newStudent.equals(""));

      // Get student grades
      for (int i = 0; i < numStudents; i++) {
         System.out.print("Grade for " + students[i] + ": ");
         double grade = input.nextDouble();
         grades[i] = grade;
      }

      // Print class roster
      System.out.println("\nClass roster:");
      double sum = 0.0;

      for (int i = 0; i < numStudents; i++) {
         System.out.println(students[i] + " (" + grades[i] + ")");
         sum += grades[i];
      }

      double avg = sum / numStudents;
      System.out.println("Average grade: " + avg);
   }

}
ArrayList<String> planets = new ArrayList<>();

planets.add("Mercury");
planets.add("Venus");
planets.add("Earth");
planets.add("Mars");
planets.add("Jupiter");
planets.add("Saturn");
planets.add("Uranus");
planets.add("Neptune");
// Get student names
do {
   newStudent = input.nextLine();

   if (!newStudent.equals("")) {
      students.add(newStudent);
   }

} while(!newStudent.equals(""));


// for -each Get student grades
for (String student : students) {
   System.out.print("Grade for " + student + ": ");
   Double grade = input.nextDouble();
   grades.add(grade);
}
// Print class roster
System.out.println("\nClass roster:");
double sum = 0.0;

for (int i = 0; i < students.size(); i++) {
   System.out.println(students.get(i) + " (" + grades.get(i) + ")");
   sum += grades.get(i);
}
package org.launchcode.java.demos.collections;

import java.util.ArrayList;
import java.util.Scanner;

public class ArrayListGradebook {

   public static void main(String[] args) {

      ArrayList<String> students = new ArrayList<>();
      ArrayList<Double> grades = new ArrayList<>();
      Scanner input = new Scanner(System.in);
      String newStudent;

      System.out.println("Enter your students (or ENTER to finish):");

      // Get student names
      do {
         newStudent = input.nextLine();

         if (!newStudent.equals("")) {
            students.add(newStudent);
         }

      } while(!newStudent.equals(""));

      // Get student grades
      for (String student : students) {
         System.out.print("Grade for " + student + ": ");
         Double grade = input.nextDouble();
         grades.add(grade);
      }

      // Print class roster
      System.out.println("\nClass roster:");
      double sum = 0.0;

      for (int i = 0; i < students.size(); i++) {
         System.out.println(students.get(i) + " (" + grades.get(i) + ")");
         sum += grades.get(i);
      }

      double avg = sum / students.size();
      System.out.println("Average grade: " + avg);
   }
}
<script type="application/ld+json">
    {
        "@context": "https://schema.org",
        "@type": "Accommodation",
        "name": "{{class - name}}",
        "description": {{id - description}},
        "occupancy": {
            "@type": "QuantitativeValue",
            "minValue": 1,
            "maxValue": "{{id - maximumAttendeeCapacity}}"
        },
        "numberOfBedrooms": "{{id - numberOfBedroom}}",
        "petsAllowed": "{{Oppslagstabell - petsAllowed}}",
        "telephone": "{{class - telephone}}",
        "address": {
            "@type": "Place",
            "containedInPlace": "{{id - containedInPlace}}",
            "geo": "{{id - geo}}",
//          "hasMap": " variabel for hasMap",
            "logo": "https://www.norgesbooking.no/ImageGen.ashx?image=/media/3567/logo3.png",
            "smokingAllowed": "false"
        }
    }
</script>
<script>
  var m = document.createElement('meta'); 
  m.name = 'description'; 
  m.content = '{{Variabel - Tekst fra nettsiden}}'; 
  document.head.appendChild(m);
  console.log("Har lagt inn dynamisk meta-beskrivelse");
</script>
insertAdjacentHTML(position, text)
import { useEffect, useState } from "react";

function getProfileData() {
  return JSON.parse(localStorage.getItem('profile'));
}

export default function useProfileData() {
  const [profile, setProfile] = useState(getProfileData());

  useEffect(() => {
    function handleChangeStorage() {
      setProfile(getProfileData());
    }

    window.addEventListener('storage', handleChangeStorage);
    return () => window.removeEventListener('storage', handleChangeStorage);
  }, []);

  return profile;
}
window.addEventListener('storage', () => setValue(localStorage.getItem(key)));
DROP DATABASE IF EXISTS `sql_invoicing`;
CREATE DATABASE `sql_invoicing`; 
USE `sql_invoicing`;

SET NAMES utf8 ;
SET character_set_client = utf8mb4 ;

CREATE TABLE `payment_methods` (
  `payment_method_id` tinyint(4) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`payment_method_id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `payment_methods` VALUES (1,'Credit Card');
INSERT INTO `payment_methods` VALUES (2,'Cash');
INSERT INTO `payment_methods` VALUES (3,'PayPal');
INSERT INTO `payment_methods` VALUES (4,'Wire Transfer');

CREATE TABLE `clients` (
  `client_id` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` char(2) NOT NULL,
  `phone` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`client_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `clients` VALUES (1,'Vinte','3 Nevada Parkway','Syracuse','NY','315-252-7305');
INSERT INTO `clients` VALUES (2,'Myworks','34267 Glendale Parkway','Huntington','WV','304-659-1170');
INSERT INTO `clients` VALUES (3,'Yadel','096 Pawling Parkway','San Francisco','CA','415-144-6037');
INSERT INTO `clients` VALUES (4,'Kwideo','81674 Westerfield Circle','Waco','TX','254-750-0784');
INSERT INTO `clients` VALUES (5,'Topiclounge','0863 Farmco Road','Portland','OR','971-888-9129');

CREATE TABLE `invoices` (
  `invoice_id` int(11) NOT NULL,
  `number` varchar(50) NOT NULL,
  `client_id` int(11) NOT NULL,
  `invoice_total` decimal(9,2) NOT NULL,
  `payment_total` decimal(9,2) NOT NULL DEFAULT '0.00',
  `invoice_date` date NOT NULL,
  `due_date` date NOT NULL,
  `payment_date` date DEFAULT NULL,
  PRIMARY KEY (`invoice_id`),
  KEY `FK_client_id` (`client_id`),
  CONSTRAINT `FK_client_id` FOREIGN KEY (`client_id`) REFERENCES `clients` (`client_id`) ON DELETE RESTRICT ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `invoices` VALUES (1,'91-953-3396',2,101.79,0.00,'2019-03-09','2019-03-29',NULL);
INSERT INTO `invoices` VALUES (2,'03-898-6735',5,175.32,8.18,'2019-06-11','2019-07-01','2019-02-12');
INSERT INTO `invoices` VALUES (3,'20-228-0335',5,147.99,0.00,'2019-07-31','2019-08-20',NULL);
INSERT INTO `invoices` VALUES (4,'56-934-0748',3,152.21,0.00,'2019-03-08','2019-03-28',NULL);
INSERT INTO `invoices` VALUES (5,'87-052-3121',5,169.36,0.00,'2019-07-18','2019-08-07',NULL);
INSERT INTO `invoices` VALUES (6,'75-587-6626',1,157.78,74.55,'2019-01-29','2019-02-18','2019-01-03');
INSERT INTO `invoices` VALUES (7,'68-093-9863',3,133.87,0.00,'2019-09-04','2019-09-24',NULL);
INSERT INTO `invoices` VALUES (8,'78-145-1093',1,189.12,0.00,'2019-05-20','2019-06-09',NULL);
INSERT INTO `invoices` VALUES (9,'77-593-0081',5,172.17,0.00,'2019-07-09','2019-07-29',NULL);
INSERT INTO `invoices` VALUES (10,'48-266-1517',1,159.50,0.00,'2019-06-30','2019-07-20',NULL);
INSERT INTO `invoices` VALUES (11,'20-848-0181',3,126.15,0.03,'2019-01-07','2019-01-27','2019-01-11');
INSERT INTO `invoices` VALUES (13,'41-666-1035',5,135.01,87.44,'2019-06-25','2019-07-15','2019-01-26');
INSERT INTO `invoices` VALUES (15,'55-105-9605',3,167.29,80.31,'2019-11-25','2019-12-15','2019-01-15');
INSERT INTO `invoices` VALUES (16,'10-451-8824',1,162.02,0.00,'2019-03-30','2019-04-19',NULL);
INSERT INTO `invoices` VALUES (17,'33-615-4694',3,126.38,68.10,'2019-07-30','2019-08-19','2019-01-15');
INSERT INTO `invoices` VALUES (18,'52-269-9803',5,180.17,42.77,'2019-05-23','2019-06-12','2019-01-08');
INSERT INTO `invoices` VALUES (19,'83-559-4105',1,134.47,0.00,'2019-11-23','2019-12-13',NULL);

CREATE TABLE `payments` (
  `payment_id` int(11) NOT NULL AUTO_INCREMENT,
  `client_id` int(11) NOT NULL,
  `invoice_id` int(11) NOT NULL,
  `date` date NOT NULL,
  `amount` decimal(9,2) NOT NULL,
  `payment_method` tinyint(4) NOT NULL,
  PRIMARY KEY (`payment_id`),
  KEY `fk_client_id_idx` (`client_id`),
  KEY `fk_invoice_id_idx` (`invoice_id`),
  KEY `fk_payment_payment_method_idx` (`payment_method`),
  CONSTRAINT `fk_payment_client` FOREIGN KEY (`client_id`) REFERENCES `clients` (`client_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_payment_invoice` FOREIGN KEY (`invoice_id`) REFERENCES `invoices` (`invoice_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_payment_payment_method` FOREIGN KEY (`payment_method`) REFERENCES `payment_methods` (`payment_method_id`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `payments` VALUES (1,5,2,'2019-02-12',8.18,1);
INSERT INTO `payments` VALUES (2,1,6,'2019-01-03',74.55,1);
INSERT INTO `payments` VALUES (3,3,11,'2019-01-11',0.03,1);
INSERT INTO `payments` VALUES (4,5,13,'2019-01-26',87.44,1);
INSERT INTO `payments` VALUES (5,3,15,'2019-01-15',80.31,1);
INSERT INTO `payments` VALUES (6,3,17,'2019-01-15',68.10,1);
INSERT INTO `payments` VALUES (7,5,18,'2019-01-08',32.77,1);
INSERT INTO `payments` VALUES (8,5,18,'2019-01-08',10.00,2);


DROP DATABASE IF EXISTS `sql_store`;
CREATE DATABASE `sql_store`;
USE `sql_store`;

CREATE TABLE `products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `quantity_in_stock` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `products` VALUES (1,'Foam Dinner Plate',70,1.21);
INSERT INTO `products` VALUES (2,'Pork - Bacon,back Peameal',49,4.65);
INSERT INTO `products` VALUES (3,'Lettuce - Romaine, Heart',38,3.35);
INSERT INTO `products` VALUES (4,'Brocolinni - Gaylan, Chinese',90,4.53);
INSERT INTO `products` VALUES (5,'Sauce - Ranch Dressing',94,1.63);
INSERT INTO `products` VALUES (6,'Petit Baguette',14,2.39);
INSERT INTO `products` VALUES (7,'Sweet Pea Sprouts',98,3.29);
INSERT INTO `products` VALUES (8,'Island Oasis - Raspberry',26,0.74);
INSERT INTO `products` VALUES (9,'Longan',67,2.26);
INSERT INTO `products` VALUES (10,'Broom - Push',6,1.09);


CREATE TABLE `shippers` (
  `shipper_id` smallint(6) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`shipper_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `shippers` VALUES (1,'Hettinger LLC');
INSERT INTO `shippers` VALUES (2,'Schinner-Predovic');
INSERT INTO `shippers` VALUES (3,'Satterfield LLC');
INSERT INTO `shippers` VALUES (4,'Mraz, Renner and Nolan');
INSERT INTO `shippers` VALUES (5,'Waters, Mayert and Prohaska');


CREATE TABLE `customers` (
  `customer_id` int(11) NOT NULL AUTO_INCREMENT,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `birth_date` date DEFAULT NULL,
  `phone` varchar(50) DEFAULT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` char(2) NOT NULL,
  `points` int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (`customer_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `customers` VALUES (1,'Babara','MacCaffrey','1986-03-28','781-932-9754','0 Sage Terrace','Waltham','MA',2273);
INSERT INTO `customers` VALUES (2,'Ines','Brushfield','1986-04-13','804-427-9456','14187 Commercial Trail','Hampton','VA',947);
INSERT INTO `customers` VALUES (3,'Freddi','Boagey','1985-02-07','719-724-7869','251 Springs Junction','Colorado Springs','CO',2967);
INSERT INTO `customers` VALUES (4,'Ambur','Roseburgh','1974-04-14','407-231-8017','30 Arapahoe Terrace','Orlando','FL',457);
INSERT INTO `customers` VALUES (5,'Clemmie','Betchley','1973-11-07',NULL,'5 Spohn Circle','Arlington','TX',3675);
INSERT INTO `customers` VALUES (6,'Elka','Twiddell','1991-09-04','312-480-8498','7 Manley Drive','Chicago','IL',3073);
INSERT INTO `customers` VALUES (7,'Ilene','Dowson','1964-08-30','615-641-4759','50 Lillian Crossing','Nashville','TN',1672);
INSERT INTO `customers` VALUES (8,'Thacher','Naseby','1993-07-17','941-527-3977','538 Mosinee Center','Sarasota','FL',205);
INSERT INTO `customers` VALUES (9,'Romola','Rumgay','1992-05-23','559-181-3744','3520 Ohio Trail','Visalia','CA',1486);
INSERT INTO `customers` VALUES (10,'Levy','Mynett','1969-10-13','404-246-3370','68 Lawn Avenue','Atlanta','GA',796);


CREATE TABLE `order_statuses` (
  `order_status_id` tinyint(4) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`order_status_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `order_statuses` VALUES (1,'Processed');
INSERT INTO `order_statuses` VALUES (2,'Shipped');
INSERT INTO `order_statuses` VALUES (3,'Delivered');


CREATE TABLE `orders` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `customer_id` int(11) NOT NULL,
  `order_date` date NOT NULL,
  `status` tinyint(4) NOT NULL DEFAULT '1',
  `comments` varchar(2000) DEFAULT NULL,
  `shipped_date` date DEFAULT NULL,
  `shipper_id` smallint(6) DEFAULT NULL,
  PRIMARY KEY (`order_id`),
  KEY `fk_orders_customers_idx` (`customer_id`),
  KEY `fk_orders_shippers_idx` (`shipper_id`),
  KEY `fk_orders_order_statuses_idx` (`status`),
  CONSTRAINT `fk_orders_customers` FOREIGN KEY (`customer_id`) REFERENCES `customers` (`customer_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_orders_order_statuses` FOREIGN KEY (`status`) REFERENCES `order_statuses` (`order_status_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_orders_shippers` FOREIGN KEY (`shipper_id`) REFERENCES `shippers` (`shipper_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `orders` VALUES (1,6,'2019-01-30',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (2,7,'2018-08-02',2,NULL,'2018-08-03',4);
INSERT INTO `orders` VALUES (3,8,'2017-12-01',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (4,2,'2017-01-22',1,NULL,NULL,NULL);
INSERT INTO `orders` VALUES (5,5,'2017-08-25',2,'','2017-08-26',3);
INSERT INTO `orders` VALUES (6,10,'2018-11-18',1,'Aliquam erat volutpat. In congue.',NULL,NULL);
INSERT INTO `orders` VALUES (7,2,'2018-09-22',2,NULL,'2018-09-23',4);
INSERT INTO `orders` VALUES (8,5,'2018-06-08',1,'Mauris enim leo, rhoncus sed, vestibulum sit amet, cursus id, turpis.',NULL,NULL);
INSERT INTO `orders` VALUES (9,10,'2017-07-05',2,'Nulla mollis molestie lorem. Quisque ut erat.','2017-07-06',1);
INSERT INTO `orders` VALUES (10,6,'2018-04-22',2,NULL,'2018-04-23',2);


CREATE TABLE `order_items` (
  `order_id` int(11) NOT NULL AUTO_INCREMENT,
  `product_id` int(11) NOT NULL,
  `quantity` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`order_id`,`product_id`),
  KEY `fk_order_items_products_idx` (`product_id`),
  CONSTRAINT `fk_order_items_orders` FOREIGN KEY (`order_id`) REFERENCES `orders` (`order_id`) ON UPDATE CASCADE,
  CONSTRAINT `fk_order_items_products` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `order_items` VALUES (1,4,4,3.74);
INSERT INTO `order_items` VALUES (2,1,2,9.10);
INSERT INTO `order_items` VALUES (2,4,4,1.66);
INSERT INTO `order_items` VALUES (2,6,2,2.94);
INSERT INTO `order_items` VALUES (3,3,10,9.12);
INSERT INTO `order_items` VALUES (4,3,7,6.99);
INSERT INTO `order_items` VALUES (4,10,7,6.40);
INSERT INTO `order_items` VALUES (5,2,3,9.89);
INSERT INTO `order_items` VALUES (6,1,4,8.65);
INSERT INTO `order_items` VALUES (6,2,4,3.28);
INSERT INTO `order_items` VALUES (6,3,4,7.46);
INSERT INTO `order_items` VALUES (6,5,1,3.45);
INSERT INTO `order_items` VALUES (7,3,7,9.17);
INSERT INTO `order_items` VALUES (8,5,2,6.94);
INSERT INTO `order_items` VALUES (8,8,2,8.59);
INSERT INTO `order_items` VALUES (9,6,5,7.28);
INSERT INTO `order_items` VALUES (10,1,10,6.01);
INSERT INTO `order_items` VALUES (10,9,9,4.28);

CREATE TABLE `sql_store`.`order_item_notes` (
  `note_id` INT NOT NULL,
  `order_Id` INT NOT NULL,
  `product_id` INT NOT NULL,
  `note` VARCHAR(255) NOT NULL,
  PRIMARY KEY (`note_id`));

INSERT INTO `order_item_notes` (`note_id`, `order_Id`, `product_id`, `note`) VALUES ('1', '1', '2', 'first note');
INSERT INTO `order_item_notes` (`note_id`, `order_Id`, `product_id`, `note`) VALUES ('2', '1', '2', 'second note');


DROP DATABASE IF EXISTS `sql_hr`;
CREATE DATABASE `sql_hr`;
USE `sql_hr`;


CREATE TABLE `offices` (
  `office_id` int(11) NOT NULL,
  `address` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` varchar(50) NOT NULL,
  PRIMARY KEY (`office_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `offices` VALUES (1,'03 Reinke Trail','Cincinnati','OH');
INSERT INTO `offices` VALUES (2,'5507 Becker Terrace','New York City','NY');
INSERT INTO `offices` VALUES (3,'54 Northland Court','Richmond','VA');
INSERT INTO `offices` VALUES (4,'08 South Crossing','Cincinnati','OH');
INSERT INTO `offices` VALUES (5,'553 Maple Drive','Minneapolis','MN');
INSERT INTO `offices` VALUES (6,'23 North Plaza','Aurora','CO');
INSERT INTO `offices` VALUES (7,'9658 Wayridge Court','Boise','ID');
INSERT INTO `offices` VALUES (8,'9 Grayhawk Trail','New York City','NY');
INSERT INTO `offices` VALUES (9,'16862 Westend Hill','Knoxville','TN');
INSERT INTO `offices` VALUES (10,'4 Bluestem Parkway','Savannah','GA');



CREATE TABLE `employees` (
  `employee_id` int(11) NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `job_title` varchar(50) NOT NULL,
  `salary` int(11) NOT NULL,
  `reports_to` int(11) DEFAULT NULL,
  `office_id` int(11) NOT NULL,
  PRIMARY KEY (`employee_id`),
  KEY `fk_employees_offices_idx` (`office_id`),
  KEY `fk_employees_employees_idx` (`reports_to`),
  CONSTRAINT `fk_employees_managers` FOREIGN KEY (`reports_to`) REFERENCES `employees` (`employee_id`),
  CONSTRAINT `fk_employees_offices` FOREIGN KEY (`office_id`) REFERENCES `offices` (`office_id`) ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `employees` VALUES (37270,'Yovonnda','Magrannell','Executive Secretary',63996,NULL,10);
INSERT INTO `employees` VALUES (33391,'D\'arcy','Nortunen','Account Executive',62871,37270,1);
INSERT INTO `employees` VALUES (37851,'Sayer','Matterson','Statistician III',98926,37270,1);
INSERT INTO `employees` VALUES (40448,'Mindy','Crissil','Staff Scientist',94860,37270,1);
INSERT INTO `employees` VALUES (56274,'Keriann','Alloisi','VP Marketing',110150,37270,1);
INSERT INTO `employees` VALUES (63196,'Alaster','Scutchin','Assistant Professor',32179,37270,2);
INSERT INTO `employees` VALUES (67009,'North','de Clerc','VP Product Management',114257,37270,2);
INSERT INTO `employees` VALUES (67370,'Elladine','Rising','Social Worker',96767,37270,2);
INSERT INTO `employees` VALUES (68249,'Nisse','Voysey','Financial Advisor',52832,37270,2);
INSERT INTO `employees` VALUES (72540,'Guthrey','Iacopetti','Office Assistant I',117690,37270,3);
INSERT INTO `employees` VALUES (72913,'Kass','Hefferan','Computer Systems Analyst IV',96401,37270,3);
INSERT INTO `employees` VALUES (75900,'Virge','Goodrum','Information Systems Manager',54578,37270,3);
INSERT INTO `employees` VALUES (76196,'Mirilla','Janowski','Cost Accountant',119241,37270,3);
INSERT INTO `employees` VALUES (80529,'Lynde','Aronson','Junior Executive',77182,37270,4);
INSERT INTO `employees` VALUES (80679,'Mildrid','Sokale','Geologist II',67987,37270,4);
INSERT INTO `employees` VALUES (84791,'Hazel','Tarbert','General Manager',93760,37270,4);
INSERT INTO `employees` VALUES (95213,'Cole','Kesterton','Pharmacist',86119,37270,4);
INSERT INTO `employees` VALUES (96513,'Theresa','Binney','Food Chemist',47354,37270,5);
INSERT INTO `employees` VALUES (98374,'Estrellita','Daleman','Staff Accountant IV',70187,37270,5);
INSERT INTO `employees` VALUES (115357,'Ivy','Fearey','Structural Engineer',92710,37270,5);


DROP DATABASE IF EXISTS `sql_inventory`;
CREATE DATABASE `sql_inventory`;
USE `sql_inventory`;


CREATE TABLE `products` (
  `product_id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `quantity_in_stock` int(11) NOT NULL,
  `unit_price` decimal(4,2) NOT NULL,
  PRIMARY KEY (`product_id`)
) ENGINE=InnoDB AUTO_INCREMENT=11 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
INSERT INTO `products` VALUES (1,'Foam Dinner Plate',70,1.21);
INSERT INTO `products` VALUES (2,'Pork - Bacon,back Peameal',49,4.65);
INSERT INTO `products` VALUES (3,'Lettuce - Romaine, Heart',38,3.35);
INSERT INTO `products` VALUES (4,'Brocolinni - Gaylan, Chinese',90,4.53);
INSERT INTO `products` VALUES (5,'Sauce - Ranch Dressing',94,1.63);
INSERT INTO `products` VALUES (6,'Petit Baguette',14,2.39);
INSERT INTO `products` VALUES (7,'Sweet Pea Sprouts',98,3.29);
INSERT INTO `products` VALUES (8,'Island Oasis - Raspberry',26,0.74);
INSERT INTO `products` VALUES (9,'Longan',67,2.26);
INSERT INTO `products` VALUES (10,'Broom - Push',6,1.09);


 NEW VARIABLE = ARRAY TO ADD.reduce((accumulator, value) => {
  return accumulator + value;
}, 0);
var validate = function(e) {
  var t = e.value;
  e.value = (t.indexOf(".") >= 0) ? (t.substr(0, t.indexOf(".")) + t.substr(t.indexOf("."), 3)) : t;
}
public static void main(String [] args) {
   for (int i = 0; i < 10; i++ ) {
      System.out.println(i);
   }
}
//output 0-9
for (start clause; stop clause; step clause) {
   statement1
   statement2
   ...
}
   //If you want to start at 100, stop at 0 and count backward by 5, the loop is written as:
   for (int i = 100; i >= 0; i -= 5) {
   System.out.println(i);
}
///for each-loop----Java also provides a syntax to iterate over any sequence or collection, such as an Array:
  public static void main(String [] args) {
   int nums[] = {1, 1, 2, 3, 5, 8, 13, 21};

   for (int i : nums) {
      System.out.println(i);
   }
}
  //This loop version also works with a String, where we can convert the String to an Array of characters:
  String msg = "Hello World";

for (char c : msg.toCharArray()) {
   System.out.println(c);
}
  //Java also supports the while loop, or indefinite loop. A while loop in Java:
  public static void main(String [] args) {
   int i = 0;
   while (i < 3) {
      i++;
   }
}
  //Java adds an additional, if seldom used, variation of the while loop called the do-while loop. The do-while loop is very similar to while except that the condition is evaluated at the end of the loop rather than the beginning. This ensures that a loop will be executed at least one time. Some programmers prefer this loop in some situations because it avoids an additional assignment prior to the loop.
  public static void main(String [] args) {
   do {
      System.out.println("Hello, World");
   } while (false);
}
  //There are instances where you may want to terminate a loop if a given condition is met. In these instances, the break statement comes in handy. For example, say you want to loop through an Array of integers to search for a given value. Once that number is found, you want to quit the loop. You can do the following:
  public class testBreak {

   public static void main(String [] args) {
      int[] someInts = {1, 10, 2, 3, 5, 8, 10};
      int searchTerm = 10;
      for (int oneInt : someInts) {
         if (oneInt == searchTerm) {
            System.out.println("Found it!");
            break;
         }
      }
   }
}
//In the code above, instead of the for loop iterating through all the integers in the array, it will stop after it finds the first matching instance. So once it finds the first 10 in the array, it prints “Found it!” and then terminates the loop. If the break statement weren’t there, the loop would continue and when it found the second 10, it would print “Found it!” a second time.


//The continue statement is similar to, but importantly different from, the break statement. Like break, it interrupts the normal flow of control of the loop. But unlike break, the continue statement only terminates the current iteration of the loop. So the loop will continue to run from the top (as long as the boolean expression that controls the loop is still true) after a continue statement. Here is an example:

public class testContinue {

   public static void main(String [] args) {
      int[] someInts = {1, 10, 2, 3, 5, 8, 10};
      int searchTerm = 10;
      for (int oneInt : someInts) {
         if (oneInt == searchTerm) {
            System.out.println("Found it!");
            continue;
         }
         System.out.println("Not here");
      }
   }
}
/*The above program will print “Not here” on every iteration of the for loop except where the number has been found. So the output looks like this:
Not here
Found it!
Not here
Not here
Not here
Not here
Found it!
Because of the continue statement, the final print statement in the for loop is skipped. If the continue statement weren’t there, the output would look like this instead (notice the extra “Not here” printouts):
Not here
Found it!
Not here
Not here
Not here
Not here
Not here
Found it!
Not here
if (condition) {
   statement1
   statement2
   ...
}
   ///if else
   if (condition) {
   statement1
   statement2
   ...
} else {
   statement1
   statement2
   ...
}
   //else if
    import java.util.Scanner;

 public class ElseIf {
     public static void main(String args[]) {
         Scanner in = new Scanner(System.in);
         System.out.println("Enter a grade: ");
         int grade = in.nextInt();
         if (grade < 60) {
             System.out.println('F');
         } else if (grade < 70) {
             System.out.println('D');
         } else if (grade < 80) {
             System.out.println('C');
         } else if (grade < 90) {
             System.out.println('B');
         } else {
             System.out.println('A');
         }
     }
 }
     public class DayPrinter {
   public static void main(String[] args) {
      Scanner in = new Scanner(System.in);
      System.out.println("Enter an integer: ");
      int dayNum = in.nextInt();

      String day;
      if (dayNum == 0) {
        day = "Sunday";
      } else if (dayNum == 1){
        day = "Monday";
      } else if (dayNum == 2){
        day = "Tuesday";
      } else if (dayNum == 3){
        day = "Wednesday";
      } else if (dayNum == 4){
        day = "Thursday";
      } else if (dayNum == 5){
        day = "Friday";
      } else if (dayNum == 6){
       day = "Saturday";
      } else {
       day = "Int does not correspond to a day of the week";
      }
      System.out.println(day);
   }
}
  
package org.launchcode.java.studios.areaofacircle;

import java.util.Scanner;

public class Area {
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a radius");
        double radius = input.nextDouble();
        double area = 3.14 * radius * radius;

        System.out.println("Area of circle is :" + area);
    }
}


////Here it is with an if/else statement for negative numbers
package org.launchcode.java.studios.areaofacircle;

import java.util.Scanner;

public class Area {
    public static void main(String[] args)
    {
        Scanner input = new Scanner(System.in);
        System.out.println("Enter a radius");
        double radius = input.nextDouble();
        double area = 3.14 * radius * radius;
        if (radius < 0){
            System.err.println("Radius must be a positive int.");
            //System.exit(status:1);
        }else {
            System.out.println("Area of circle is :" + area);
        }


    }
}
const newSpan = document.createElement('span');
const price = document.createTextNode('but');

newSpan.appendChild(price);

const addedSpan = document.querySelector(".price_varies");
addedSpan.appendChild(newSpan);

newSpan.classList.add(0, 'money');
$(document).ready(function() {
  var fileTypes = ['jpg', 'jpeg', 'png', 'tiff', 'tif', 'pdf']; //acceptable file types
  $("input:file").change(function(evt) {
    var parentEl = $(this).parent();
    $(this).parent().find("img.preview").remove();
    $(this).parent().find("canvas.preview").remove();
    var tgt = evt.target || window.event.srcElement,
      files = tgt.files;
    // FileReader support
    if (FileReader && files && files.length) {
      var fr = new FileReader();
      var extension = files[0].name.split('.').pop().toLowerCase();
      var tif = false;
      var pdf = false;
      if (extension == "tiff" || extension == "tif")
        tif = true;
      fr.onload = function(e) {
        success = fileTypes.indexOf(extension) > -1;
        if (success) {
          if (tif) {
            //Using tiff.min.js library - https://github.com/seikichi/tiff.js/tree/master
            console.debug("Parsing TIFF image...");
            //initialize with 100MB for large files
            Tiff.initialize({
              TOTAL_MEMORY: 100000000
            });
            var tiff = new Tiff({
              buffer: e.target.result
            });
            var tiffCanvas = tiff.toCanvas();
            $(tiffCanvas).css({
              "max-width": "100px",
              "width": "100%",
              "height": "auto",
              "display": "block",
              "padding-top": "10px"
            }).addClass("preview");
            $(parentEl).append(tiffCanvas);
          }  else {
            console.debug("render immmm");
            $(parentEl).append('<img src="' + fr.result + '" class="preview"/>');
          }
        }

      }

      fr.onloadend = function(e) {
        console.debug("Load End");
      }
      if (tif)
        fr.readAsArrayBuffer(files[0]);
      else
        fr.readAsDataURL(files[0]);
    }
    // Not supported
    else {
      // fallback -- perhaps submit the input to an iframe and temporarily store
      // them on the server until the user's session ends.
    }
  });
});
public class BankAccount {
  	public static void main(String[] args){
      double balance = 1000.75;
      double amountToWithdraw = 250;
      
      double updatedBalance = balance - amountToWithdraw;
      double amountForEachFriend = updatedBalance/3;
      boolean canPurchaseTicket = amountForEachFriend >= 250;
      System.out.println(canPurchaseTicket);
      
      System.out.println("I gave each friend "+amountForEachFriend+"...");
    }       
}
String username = "PrinceNelson";
System.out.println("Your username is: " + username);

int balance = 10000;
String message = "Your balance is: " + balance;
System.out.println(message);

public class Zoo {
  	public static void main(String[] args){
      int animals = 12;
      String species = "zebra";
      System.out.println("Our zoo has " + animals+" "+ species+"s!");
    }       
}
String person1 = "Paul";
String person2 = "John";
String person3 = "Paul";
 
System.out.println(person1.equals(person2));
// Prints false, since "Paul" is not "John"
 
System.out.println(person1.equals(person3));
// Prints true, since "Paul" is "Paul"
public class PlusAndMinus {
	public static void main(String[] args) {   
		int zebrasInZoo = 8;
    int giraffesInZoo = 4;
    int animalsInZoo = zebrasInZoo + giraffesInZoo;
    System.out.println(animalsInZoo);
    int numZebrasAfterTrade = zebrasInZoo - 2;
    System.out.println(numZebrasAfterTrade);
	}
}
public class Mess {
	public static void main(String[] args) {   
		int year = 2001;
    String title = "Shrek";
    char genre = 'C';
    double runtime = 1.58;
    boolean isPG = true;
	}
}
<div className="mx-auto container flex items-center" id="nav">
                <div className="w-full pt-2 p-4">
                    <div className="mx-auto md:p-6 md:w-1/2">
                        <div className="flex flex-wrap justify-between">
                            <h1 className="text-2xl text-orange-500 hover:text-orange-500 transition duration-500 p-4">
                                <i className="fas fa-sign-in-alt fa-fw fa-lg"></i>
                                Sign-in
                            </h1>
                            <a
                                href="#home"
                                className="mt-8 text-orange-400 hover:text-orange-600 transition duration-500"
                            >
                                <svg
                                    className=" w-6 h-6 inline-block align-bottom"
                                    fill="none"
                                    stroke-linecap="round"
                                    stroke-linejoin="round"
                                    stroke-width="2"
                                    stroke="currentColor"
                                    viewBox="0 0 24 24"
                                >
                                    <path d="M3 12l2-2m0 0l7-7 7 7M5 10v10a1 1 0 001 1h3m10-11l2 2m-2-2v10a1 1 0 01-1 1h-3m-6 0a1 1 0 001-1v-4a1 1 0 011-1h2a1 1 0 011 1v4a1 1 0 001 1m-6 0h6"></path>
                                </svg>
                                Back to Home
                                <i className="fas fa-chevron-circle-left fa-fw"></i>
                            </a>
                        </div>

                        <div className="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4">
                            <form method="POST" action="#login">
                                <div className="mb-8">
                                    <label
                                        for="username"
                                        className="block text-gray-700 text-sm font-bold mb-2"
                                    >
                                        <span className="text-red-500">
                                            &nbsp;*
                                        </span>
                                        username
                                    </label>
                                    <div className="mt-1 relative rounded-md shadow-sm">
                                        <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
                                            <svg
                                                className="h-5 w-5 text-gray-400"
                                                fill="none"
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                stroke="currentColor"
                                                viewBox="0 0 24 24"
                                            >
                                                <path d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path>
                                            </svg>
                                        </div>
                                        <input
                                            id="username"
                                            className="block pr-10 shadow appearance-none border-2 border-orange-100 rounded w-full py-2 px-4 text-gray-700 mb-3 leading-tight focus:outline-none focus:bg-white focus:border-orange-500 transition duration-500 ease-in-out"
                                            placeholder="you@example.com"
                                        />
                                    </div>
                                    <strong className="text-red-500 text-xs italic">
                                        username is require
                                    </strong>
                                </div>

                                <div className="mb-8">
                                    <label
                                        for="password"
                                        className="block text-gray-700 text-sm font-bold mb-2"
                                    >
                                        <span className="text-red-500">
                                            &nbsp;*
                                        </span>
                                        Password
                                    </label>
                                    <div className="mt-1 relative rounded-md shadow-sm">
                                        <div className="absolute inset-y-0 right-0 pr-3 flex items-center pointer-events-none">
                                            <svg
                                                className="h-5 w-5 text-gray-400"
                                                fill="none"
                                                stroke-linecap="round"
                                                stroke-linejoin="round"
                                                stroke-width="2"
                                                stroke="currentColor"
                                                viewBox="0 0 24 24"
                                            >
                                                <path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"></path>
                                            </svg>
                                        </div>
                                        <input
                                            name="password"
                                            id="password"
                                            type="text"
                                            className="block pr-10 shadow appearance-none border-2 border-orange-100 rounded w-full py-2 px-4 text-gray-700 mb-3 leading-tight focus:outline-none focus:bg-white focus:border-orange-500 transition duration-500 ease-in-out"
                                        />
                                    </div>
                                </div>

                                <div className="mb-6">
                                    <div className="flex items-center justify-between">
                                        <div>
                                            <label
                                                className="block text-gray-500 font-bold"
                                                for="remember"
                                            >
                                                <input
                                                    className="ml-2 leading-tight"
                                                    type="checkbox"
                                                    id="remember"
                                                    name="remember"
                                                />
                                                <span className="text-sm">
                                                    remember me
                                                </span>
                                            </label>
                                        </div>
                                        <div>
                                            <a
                                                className="font-bold text-sm text-orange-500 hover:text-orange-800"
                                                href="#password-request"
                                            >
                                                forgot password
                                            </a>
                                        </div>
                                    </div>
                                </div>

                                <div className="mb-4 text-center">
                                    <button
                                        className="transition duration-500 bg-orange-500 hover:bg-orange-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline"
                                        type="submit"
                                    >
                                        Login
                                    </button>
                                </div>
                                <hr />
                                <div className="mt-8">
                                    <p className="text-sm">
                                        no account
                                        <a
                                            className="font-bold text-sm text-orange-500 hover:text-orange-800"
                                            href="#register"
                                        >
                                            sign up
                                        </a>
                                    </p>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
const input = document.querySelector('input')
//Add space e.g 1234 5678 9012
input.innerHTML = input.value.replace(/\d{4}(?=.)/g, '$& ');
<input onkeydown="return /[a-z]/i.test(event.key)" >
  
//allow WHITE space as well
<input onkeydown="return /[a-z\s]/i.test(event.key)" >
public class HelloYou {
  public static void main(String[] args) {
    System.out.println("Hello Maria!");
    
  }
}
//.print keeps it on the same line 
public class HideAndSeek {
  public static void main(String[] args) {
    System.out.println("Let's play hide and seek.");
System.out.print("Three...");
System.out.print("Two...");
System.out.println("One...");
System.out.println("Ready or not, here I come!");

  }
}
git filter-branch --force --index-filter 'git rm --cached --ignore-unmatch <FILE_NAME>' --prune-empty --tag-name-filter cat -- --all
String staticVariable = "dog";
char charVariable = 'd';
function getNewData() {
  //deleting triggers
  var triggers = ScriptApp.getProjectTriggers();    
  for (var i = 0; i < triggers.length; i++) {
    if (triggers[i].getHandlerFunction()=='getNewData'){
      ScriptApp.deleteTrigger(triggers[i]);
    }
  }  
  //max running time = 5.5 min
  var MAX_RUNNING_TIME = 330000;
  var startTime= (new Date()).getTime();
  //get cache
  var cache = CacheService.getUserCache();
  var downloaded =JSON.parse(cache.get('downloaded'));  
  var compared =JSON.parse(cache.get('compared'));
  //start
  if (downloaded==1 && compared!=1){
    //folder
    var Folder = DriveApp.getFoldersByName('theFolder').next();
    var FolderId = licitacionesFolder.getId();
    //call old_spreadsheet
    var searchFor ="fullText contains 'sheet_old' and '" + FolderId + "' in parents";  
    var files = DriveApp.searchFiles(searchFor); 
    var old_file = files.next();  
    var old_spreadsheet = SpreadsheetApp.openById(old_file.getId());
    var old_sheet = old_spreadsheet.getSheets()[0];
    var old_array = old_sheet.getDataRange().getValues();
    //call spreadsheet
    var searchFor ="fullText contains 'sheet' and '" + FolderId + "' in parents";  
    var files = DriveApp.searchFiles(searchFor); 
    var file = files.next();  
    var spreadsheet = SpreadsheetApp.openById(old_file.getId());
    var sheet = spreadsheet.getSheets()[0];
    var array = sheet.getDataRange().getValues();
    Logger.log(array.length+'::'+old_array.length); 
    // Column
    var searchString = 'NAME';
    var RC = getColumn(array,searchString);    
    var Row = RC.Row;
    var Column = RC.Column;
    var RC = getColumn(old_array,searchString);    
    var Row_old = RC.Row;
    var Column_old = RC.Column;    
    Logger.log(Row_old+':::'+Column_old+'\n'+Row+':::'+Column);      
    //compare 
    var diff_index =JSON.parse(cache.get('diff_index'));
    var row_ind =JSON.parse(cache.get('row_ind'));  
    var Roww =JSON.parse(cache.get('Row'));  
    if (diff_index==null){var diff_index = [];}
    if (row_ind==null){var row_ind = 0;}
    if (Roww==null){var Roww = Row;}    
    Logger.log(row_ind+'\n'+Roww);    
    for (var i=Roww;i<array.length;i++){  
      var currTime = (new Date()).getTime();
      if(currTime - startTime >= MAX_RUNNING_TIME){
        Logger.log((currTime - startTime)/(1000*60));
        Logger.log(i+'::'+row_ind);
        cache.putAll({'diff_index': JSON.stringify(diff_index),'row_ind': JSON.stringify(row_ind),'Row': JSON.stringify(i-1)},21600);   
        ScriptApp.newTrigger('getNewData').timeBased().after(2 * 60 * 1000).create();
        return;
      } else {
        Logger.log(i);
        var existe = ArrayLib.indexOf(old_array, Column_old, array[i][Column]);
        if (existe==-1){      
          Logger.log(row_ind+'!!!');
          diff_index[row_ind]=i;
          row_ind++;          
        }
      }
    }    
    cache.putAll({'diff_index': JSON.stringify(diff_index),'Row': JSON.stringify(Row),'compared': JSON.stringify(1)},21600);
  } else {
    Logger.log('file not downloaded yet or already compared');
  }
}

function getColumn(array,searchString){
  for (var i = 0; i < array.length; i++) {    
    for (var j = 0; j < array[i].length; j++) {    
      if (array[i][j] == searchString) {
        var Row = i+1;
        var Column = j;
        break;
      }      
    }
    if (Row != undefined){
      break;
    }
  }
  return {Row: Row, Column: Column};
}
var siblings = n => [...n.parentElement.children].filter(c=>c!=n)
import React from 'react';
import { PhotoStory, VideoStory } from './stories';

const components = {
    photo: PhotoStory,
    video: VideoStory
};

function Story(props) {
    // Correct! JSX type can be a capitalized variable.
    const SpecificStory = components[props.storyType];
    return <SpecificStory story={props.story} />;
}
if (wasThatTrue) {
    return "Yes, that was true";
  }
  return "No, that was false";
function nextInLine(arr, item) {
  // Only change code below this line
  arr.push(item);
  const removed = arr.shift();
  return removed;
  return item;
  // Only change code above this line
}

// Setup
const testArr = [1, 2, 3, 4, 5];

// Display code
console.log("Before: " + JSON.stringify(testArr));
console.log(nextInLine(testArr, 6));
console.log("After: " + JSON.stringify(testArr));
const credential = await navigator.credentials.get({
    publicKey: publicKeyCredentialRequestOptions
});

pos = linear(index,1,10,0,1);
thisComp.layer("PATH").mask("Mask 1").maskPath.pointOnPath(pos, t = time);
// all items 
var arr = [
  {id: 'a1', value: 1}, 
  {id: 'a2', value: 2}, 
  {id: 'a3', value: 2}, 
  {id: 'b1', value: 1}, 
  {id: 'a1', value: 2},  
  {id: 'a2', value: 3}
]

var filtered = []

// We want mantain the duplicated item with highest value
arr.forEach( item => {
  const some = arr.find(x => {if (x.id === item.id && x.value > item.value && !duplicated.includes(x)) {return x}})
	 
	if (some) {
		duplicated.push(some)
	} else if (!duplicated.includes(item)) {
    duplicated.push(item)
  }
})

console.log(filtered)
// [
//   {id: 'a1', value: 2}, 
//   {id: 'a2', value: 3}, 
//   {id: 'a3', value: 2}, 
//   {id: 'b1', value: 1}
// ]
const [date, time] = formatDate(new Date()).split(' ');
console.log(date); // 👉️ 2021-12-31
console.log(time); // 👉️ 09:43

// ✅ Set Date input Value
const dateInput = document.getElementById('date');
dateInput.value = date;

// 👇️️ "2021-12-31"
console.log('dateInput value: ', dateInput.value);

// ✅ Set time input value
const timeInput = document.getElementById('time');
timeInput.value = time;

// 👇️ "09:43"
console.log('timeInput value: ', timeInput.value);

// ✅ Set datetime-local input value
const datetimeLocalInput = document.getElementById('datetime-local');
datetimeLocalInput.value = date + 'T' + time;

// 👇️ "2021-12-31T10:09"
console.log('dateTimeLocalInput value: ', datetimeLocalInput.value);

// 👇️👇️👇️ Format Date as yyyy-mm-dd hh:mm:ss
// 👇️ (Helper functions)
function padTo2Digits(num) {
  return num.toString().padStart(2, '0');
}

function formatDate(date) {
  return (
    [
      date.getFullYear(),
      padTo2Digits(date.getMonth() + 1),
      padTo2Digits(date.getDate()),
    ].join('-') +
    ' ' +
    [
      padTo2Digits(date.getHours()),
      padTo2Digits(date.getMinutes()),
      // padTo2Digits(date.getSeconds()),  // 👈️ can also add seconds
    ].join(':')
  );
}

// 👇️ 2022-07-22 08:50:39
console.log(formatDate(new Date()))

// 👇️ 2025-05-04 05:24
console.log(formatDate(new Date('May 04, 2025 05:24:07')))
const profile = {
  name: 'John',
  age: ''
};

const emptyProfile = _.values(profile).every(_.isEmpty);

console.log(emptyProfile); // returns false
/ CSS /
.reveal{position:relative;transform:translateX(200px);opacity:0;transition:1s all ease;}
.reveal.active{transform:translateX(0);opacity:1;}

/ JavaScript /

function reveal() {
  var reveals = document.querySelectorAll(".reveal");

  for (var i = 0; i < reveals.length; i++) {
    var windowHeight = window.innerHeight;
    var elementTop = reveals[i].getBoundingClientRect().top;
    var elementVisible = 150;

    if (elementTop < windowHeight - elementVisible) {
      reveals[i].classList.add("active");
    } else {
      reveals[i].classList.remove("active");
    }
  }
}

window.addEventListener("scroll", reveal);
<div id="slide-out-widget-area" class="slide-out-from-right" style="padding-top: 71.4px; padding-bottom: 71.4px;">
            <div class="inner-wrap">
                <div class="inner">

                    <div class="off-canvas-menu">
                        <?php
                        wp_nav_menu( array (
                            'theme_location' => 'header',
                            'container'      => '',
                            'menu_class'     => 'menu',
                        ) );
                        ?>
                    </div>
                </div>
            </div>
            <div id="slide-out-widget-area-bg" class="slide-out-from-right solid material-open"></div>
            <!-- <div class="close-btn">
                <span class="close-wrap">
                    <span class="close-line close-line1"></span>
                    <span class="close-line close-line2"></span> 
                </span>
            </div> -->
        </div>
        <div class="occu-health-wrapper">
            <div id="top"><a class="menulinks"><i></i></a></div>
		</div>
                                    
       <style>
		@media (max-width:767px){
    header#header {padding: 20px 0 0;background: transparent;}
    .header-top {border-bottom: none;}
    .head-wrapper {height: 98px;}
    .head-wrapper.fixed-header a.menulinks {top: 30px;right: 20px;}
    .head-wrapper.fixed-header ul.mainmenu {top: 98px;left: 0;width: 100%;}
    .logo-col {flex: 0 0 110px;}
    .head-btn-col {flex: 0 0 calc(100% - 150px);justify-content: flex-end;padding-right: 0px;padding-left: 0;}
    .mobile-open div#slide-out-widget-area {min-width: 78vw;width: 78vw;margin: 0 0 0 auto;padding-left: 50px;padding-right: 50px;display: block;}
    .mobile-open .inner-wrap{position:absolute;top:50%;transform:translate(-50%,-50%);left: 70%;display:flex;align-items:center;justify-content:center;}
    .off-canvas-menu .menu{display:flex;flex-direction:column;justify-content:center;align-items:center;width:200px;margin-bottom:10px;}
    .inner-wrap .off-canvas-menu .nav-btns{display:flex;flex-direction:column;align-items:center;justify-content:center;}
    .mobile-open div#slide-out-widget-area-bg{background:var(--primary-color);opacity:1;height:100vh;width:100vw;z-index:-1;position:absolute;top:0;left:0;}
    .mobile-open .occu-health-wrapper{transform:scale(0.84) translateX(-93vw) translateZ(0)!important;position:absolute;top:0;left:40%;height:100vh;overflow:hidden;transition:transform 0.5s;width:100%;}
    div#top .menulinks{display:none;justify-content:end;height:50px;z-index:99;width:100%;}
    .mobile-open div#top .menulinks {display: flex;}
    div#slide-out-widget-area {display: none;}
    .occu-health-wrapper{transition:transform 0.5s;top:auto;height:100vh;}
    .mobile-open .occu-health-wrapper{transform:scale(0.84) translateX(-93vw) translateZ(0)!important;position:absolute;top:0;left:40%;height:100vh;overflow:hidden;transition:transform 0.5s;width:100%;}
    .mobile-open .occu-health-wrapper {left: 25%;}
    .mobile-open div#top{padding:10px 0;background:white;display:flex;justify-content:end;height:inherit;}
    ul#menu-header-menu li > a{color:var(--white);}
    ul#menu-header-menu {list-style: none;padding: 0;}
    .off-canvas-menu{width:200px;}
    .off-canvas-menu .btn-wrapper{display:flex;align-items:center;justify-content:flex-start;margin-top:10px;}
    .off-canvas-menu a.btn{display:inline-flex;padding:10px;width:50px;height:50px;background:var(--white);margin-right:10px;}
    .off-canvas-menu a.btn svg{color:var(--primary-color);width:30px;height:30px;}
    .off-canvas-menu a.btn:last-child{margin:0;}
    .off-canvas-menu ul#menu-header-menu li{margin-bottom:10px;width: 100%;}

/*Nav*/
    .menulinks{display:block;top:30px;right:20px;z-index:999999;}
    .mobile-open a.menulinks {display: none;}
    ul.mainmenu{text-align:left;position:absolute;top:98px;padding:0;right:0;width:100%;background:#000;display:none !important;z-index:9999999;}
    ul.mainmenu>li>a:after{content:none;}
    ul.mainmenu>li>a:hover:after{content:none;}
    ul.mainmenu>li{float:left;width:100%;padding:0px;margin:0;border-top:1px solid rgba(255,255,255,0.2);position:relative;}
    ul.mainmenu>li:first-child{border:none;}
    ul.mainmenu>li>a:link,ul.mainmenu>li>a:visited{padding:10px 15px;font-size:16px;float:left;width:100%;border:none;text-align:left;color:#fff;}
    ul.mainmenu>li>a:hover{background:rgba(255,255,255,0.2);}
    a.menulinks i{display:inline;position:relative;top: 0;right: 0;margin-left:0;-webkit-transition-duration:0s;-webkit-transition-delay:.2s;-moz-transition-duration:0s;-moz-transition-delay:.2s;transition-duration:0s;transition-delay:.2s;}
    a.menulinks i:before,a.menulinks i:after{position:absolute;content:'';left:0;}
    a.menulinks i,a.menulinks i:before,a.menulinks i:after{width:35px;height:4px;background-color:#000;display:inline-block;}
    a.menulinks i:before{transform: translateY(-10px);-webkit-transition-property:margin,-webkit-transform;-webkit-transition-duration:.2s;-webkit-transition-delay:.2s,0;}
    a.menulinks i:after{transform: translateY(10px);-webkit-transition-property:margin,-webkit-transform;-webkit-transition-duration:.2s;-webkit-transition-delay:.2s,0;}
    .mobile-open a.menulinks i{background-color:rgba(0,0,0,0.0);-webkit-transition-delay:.2s;-webkit-box-shadow:0px 1px 1px rgba(0,0,0,0);-moz-box-shadow:0px 1px 1px rgba(0,0,0,0);box-shadow:0px 1px 1px rgba(0,0,0,0);}
    .mobile-open a.menulinks i:before{margin-top:0;-webkit-transform:rotate(45deg);-ms-transform:rotate(45deg);transform:rotate(45deg);-webkit-transition-delay:0,.2s;-webkit-box-shadow:0px 1px 1px rgba(0,0,0,0);-moz-box-shadow:0px 1px 1px rgba(0,0,0,0);box-shadow:0px 1px 1px rgba(0,0,0,0);}
    .mobile-open a.menulinks i:after{margin-top:0;-webkit-transform:rotate(-45deg);-ms-transform:rotate(-45deg);transform:rotate(-45deg);-webkit-transition-delay:0,.2s;-webkit-box-shadow:0px 1px 1px rgba(0,0,0,0);-moz-box-shadow:0px 1px 1px rgba(0,0,0,0);box-shadow:0px 1px 1px rgba(0,0,0,0);}
    ul.mainmenu>li>a.current:after{display:none;}
    ul.mainmenu ul{position:relative;top:auto;left:auto;float:left;width:100%;}
    ul.mainmenu ul li{position:relative;}
    ul.mainmenu ul li a{padding:8px 15px 8px 25px;color:#fff;}
    a.child-triggerm{display:block!important;cursor:pointer;position:absolute!important;top:0px;right:0px;width:50px!important;min-width:50px!important;height:38px!important;padding:0!important;border-left:1px dotted rgba(255,255,255,.20);}
    a.child-triggerm:hover{text-decoration:none;color:#f00;}
    a.child-triggerm span{position:relative;top:50%;margin:0 auto!important;-webkit-transition-duration:.2s;-moz-transition-duration:.2s;transition-duration:.2s;}
    a.child-triggerm span:after{position:absolute;content:'';}
    a.child-triggerm span,a.child-triggerm span:after{width:10px;height:1px;background-color:#fff;display:block;}
    a.child-triggerm span:after{-webkit-transform:rotate(-90deg);-ms-transform:rotate(-90deg);transform:rotate(-90deg);-webkit-transition-duration:.2s;-moz-transition-duration:.2s;transition-duration:.2s;}
    a.child-triggerm.child-open span:after{-webkit-transform:rotate(-180deg);-ms-transform:rotate(-180deg);transform:rotate(-180deg);-webkit-transition-duration:.2s;-moz-transition-duration:.2s;transition-duration:.2s;}
    a.child-triggerm.child-open span{-webkit-transform:rotate(180deg);-ms-transform:rotate(180deg);transform:rotate(180deg);-webkit-transition-duration:.2s;-moz-transition-duration:.2s;transition-duration:.2s;}
    a.child-triggerm:hover span,a.child-triggerm:hover span:after{background-color:#f00;}
    .logo-col a > img {max-width: 110px;height: 70px;object-fit: contain;}
    .head-btn-col a.btn:last-of-type {margin-right: 0;display: none;}
    .contact-col ul, .keep-col ul {margin: 0 0 0 15px;}
    .footer-logo-col {width: 100%;}
}

@media (max-width: 567px) {
    .head-btn-col {flex: 0 0 calc(100% - 110px);justify-content: end;padding-right: 38px;padding-left: 5px;}
    .head-btn-col .btn {width: 40px;height: 40px;margin-right: 5px;}
    ul.mainmenu {top: 143px;display: none !important;}
    .head-wrapper.fixed-header ul.mainmenu {top: 144px;}
    .services-col {margin-bottom: 15px;margin-top: 15px;}
    .contact-col {margin-bottom: 15px;display: flex;flex-direction: column;align-items: center;width: 100%;}
    .footer .services-col .footer-links ul {text-align: center;margin: 0;}
    .contact-col ul, .keep-col ul {margin: 0 0 0px 0;text-align: center;}
    .keep-col {width: 100%;}
    .footer .services-col span, .footer .contact-col span, .footer .keep-col span {padding-left: 0;padding-bottom: 15px;font-size: 22px;justify-content: center;}
    .footer .row {justify-content: center;}
    .footer-logo-col {width: 100%;text-align: center;}
    .contact-col ul, .keep-col ul {margin: 0 0 0 0;}
    .logo-col a > img {max-width: 90px;}
    .mobile-open .inner-wrap {left: 75%;}
    .head-wrapper.fixed-header a.menulinks{top:30px;right:10px;}
}

@media (max-width: 350px) {
    .logo-col{flex:0 0 90px;}
    .head-btn-col {flex: 0 0 calc(100% - 90px);padding-right: 28px;}
    .menulinks{top:30px;right:20px;}
    .head-wrapper.fixed-header a.menulinks{top:30px;right:5px;}
}
	</style>
                                                      
<script>
      jQuery(document).ready(function (jQuery) {
    jQuery('.mainmenu li:has(ul)').addClass('parent');
    jQuery('.mainmenu').before('<a class="menulinks"><i></i></a>');
    jQuery('a.menulinks').click(function () {
        jQuery(this).next('ul').slideToggle(250);
        jQuery('body').toggleClass('mobile-open');
        jQuery('.mainmenu li.parent ul').slideUp(250);
        jQuery('a.child-triggerm').removeClass('child-open');
        return false;
    });
    jQuery('.mainmenu li.parent > ul').before('<a class="child-triggerm"><span></span></a>');
    jQuery('.mainmenu a.child-triggerm').click(function () {
        jQuery(this).parent().siblings('li').find('a.child-triggerm').removeClass('child-open');
        jQuery(this).parent().siblings('li').find('ul').slideUp(250);
        jQuery(this).next('ul').slideToggle(250);
        jQuery(this).toggleClass('child-open');
        return false;
    });</script>
const form = document.getElementById('form');
 
form.addEventListener('submit', function(event) {

  event.preventDefault();
 
  const uploadElement = document.getElementById('file'); // Select file input element
  const file = uploadElement.files[0]; // Selects file at position 0 (for single file)
 
  const payload = new FormData(); // Sending in FormData object will set headers
  payload.append('CV', file, 'CV.pdf'); // Appends file to FormData object
 
  fetch('https://httpbin.org/post', { // Endpoint is a test API
    method: "POST", // or "PUT"
    body: payload,
  })
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.log(err))
});
fetch('https://reqres.in/api/users', { // Endpoint is a test API
    method: "POST", // or "PUT"
    headers: {
        'Content-type': 'application/json'
    },
    body: JSON.stringify(
        { name: "Captain Anonymous"}
    )
});
const txt = `Watch me as I get typed out before your very eyes using JavaScript's setInterval() function.`;
const outputEl = document.getElementById('target-element');
const speed = 50;

// Keeps track of character being typed:
let i = 0;

// Types a new character every 50 milliseconds to outputEl
const timerId = setInterval(() => {
    outputEl.innerHTML += txt.charAt(i);
    i++;
    if (i === txt.length) {
      clearInterval(timerId);
    }
  },speed);
select 
	wr.start_datetime,
	wr.end_datetime,
	wr.object_id,
	wr.reserved_by_user,
	wr.reserved_for_user,
	wr.reservation_hash,
	wo.object_name as objectName,
	wo.object_type as objectType
from wmt_reservations wr

left join wmt_objects wo 
	on wr.object_id = wo.object_id and wr.org = wo.org and wr.org_path = wo.org_path

left join wmt_reservation_guests wrg 
	on wrg.reservation_id = wr.id

where wr.org = 'okku' and wr.org_path = '/demo' and wr.cancelled_at is null and wr.visible_to_others is true
UNION all
select DISTINCT on
	(wo2.regular_user)
	wr2.start_datetime,
	wr2.end_datetime,
	wr2.object_id,
	wr2.reserved_by_user,
	wr2.reserved_for_user,
	wr2.reservation_hash,
	wo2.object_name as objectName,
	wo2.object_type as objectType
from wmt_objects wo2

left join wmt_reservations wr2
	on wr2.org = wo2.org and wr2.org_path = wo2.org_path 
where wo2.regular_user is not null
const
    myProxy = new Proxy({}, {
        get: function(obj, prop) {
            return 42;
        }
    }),
    { value } = myProxy;

console.log(myProxy.value);
console.log(value);
const redisClient = require('redis')
const logger = require('../services/Logger')

const ENV = process.env.ENV ? process.env.ENV : 'DEV'

class Redis {
    constructor() {
        this.client = redisClient.createClient({
            url: process.env.REDIS_URL
        })

        // create connection
        this.client.connect()
        logger.info(`Redis connection opened`)
        // get some connection diagnostics
        this.client
            .sendCommand(['CLIENT', 'LIST'])
            .then(list => {
                const clients = list.split('\n')
                logger.info(
                    `Redis client count: ${
                        clients.filter(x => x?.length > 0).length
                    }`
                )
            })
            .catch(err => logger.error(err))
    }

    /**
     * Stores key value pair in redis
     * @param {String} key
     * @param {String} value JSON stringified value
     */
    async put(key, value, ttl) {
        const options = {}
        if (ttl) {
            options.EX = ttl
        }
        await this.client.set(
            `${ENV}:${key}`,
            JSON.stringify(value),
            options
        )
    }

    /**
     * Get redis data by key
     * @param {String} key
     * @returns
     */
    async get(key) {
        // logger.info(`getting redis key: ${ENV}:${key}`)
        let data = await this.client.get(`${ENV}:${key}`)

        data = data ? JSON.parse(data) : undefined
        if (data && Object.keys(data).length === 0) data = undefined

        if (!data) {
            logger.info(`Redis cache miss on key ${ENV}:${key}`)
        }
        return data
    }

    /**
     * Remove cache entry
     * @param {String} key
     */
    async clear(key) {
        await this.client.del(`${ENV}:${key}`)
        logger.info(`Redis key: ${key} deleted`)
    }

    /**
     * Delete keys in wild card fashion
     * @param {String} pattern Example: h?llo, h*llo
     */
    async deleteKeysViaWildCardPattern(pattern) {
        logger.info(`Deleting redis keys for pattern: ${pattern}`)
        let cursorIndex = '0'
        let running = true
        do {
            const { cursor, keys } = await this.client.scan(
                cursorIndex,
                {
                    MATCH: `${ENV}:${pattern}`
                }
            )
            logger.info(`Deleting redis keys: ${keys}`)
            // Delete redis key
            keys.forEach(async key => {
                await this.client.del(`${key}`)
                logger.info(`Redis key: ${key} deleted`)
            })

            // update cursor
            cursorIndex = cursor

            // loop control variable
            if (!cursor) running = false
        } while (running)
    }

    /**
     * Set expiry time of the key in milliseconds
     * @param {*} key
     * @param {*} expiryTime
     */
    async setKeyExpireTime(key, expiryTime) {
        await this.client.expire(`${ENV}:${key}`, expiryTime)
    }

    async quit() {
        await this.client?.quit()
    }
}

module.exports = new Redis()
import { useState, useEffect } from "react";

export function useScroll() {
  const [lastScrollTop, setLastScrollTop] = useState(0);
  const [bodyOffset, setBodyOffset] = useState(
    document.body.getBoundingClientRect()
  );
  const [scrollY, setScrollY] = useState(bodyOffset.top);
  const [scrollX, setScrollX] = useState(bodyOffset.left);
  const [scrollDirection, setScrollDirection] = useState();

  const listener = e => {
    setBodyOffset(document.body.getBoundingClientRect());
    setScrollY(-bodyOffset.top);
    setScrollX(bodyOffset.left);
    setScrollDirection(lastScrollTop > -bodyOffset.top ? "down" : "up");
    setLastScrollTop(-bodyOffset.top);
  };

  useEffect(() => {
    window.addEventListener("scroll", listener);
    return () => {
      window.removeEventListener("scroll", listener);
    };
  });

  return {
    scrollY,
    scrollX,
    scrollDirection
  };
}
const useScrollFadeIn = () => {
  const dom = useRef();
  
  const handleScroll = useCallback(([entry]) => {
      const { current } = dom;
    	
    	if(entry.isIntersecting) {
        // 원하는 이벤트를 추가 할 것
      }
    }, []);
  
  useEffect(() => {
    let observer;
    const { current } = dom;
    
    if (current) {
      observer = new IntersectionObserver(handleScroll, { threshold: 0.7 });
      observer.observe(current);
      
      return () => observer && observer.disconnect();
    };
  }, [handleScroll]);
  
    return {
    ref: dom,
  };
}
// 스크롤이 내려가고 올라오는지 확인해주는 핸들러
  const handleScroll = useCallback(
    (e) => {
      // 현재위치와 이전 위치의 차를 계산한다.
      const diff = e.target.scrollTop - prevY
      if (diff > 0) {
        console.log('내려가는중')
        // 헤더를 보여줄지 말지 set
        setIsHeaderShow(false)
      } else if (diff < 0) {
        console.log('올라가는중')
        setIsHeaderShow(true)
      }
      setPrevY(e.target.scrollTop)
    },
    [prevY]
  )
// 스크롤이 멈췄는지 확인해주는 핸들러
  const stopScroll = useCallback((e) => {
    console.log('🥎🥎🥎멈춤', e.target.scrollTop)
    // 스크롤이 가장 끝까지 올라가면 헤더보임.
    // 스크롤이 멈추면 헤더안보임
    if (e.target.scrollTop === 0) {
      setIsHeaderShow(true)
    } else {
      setIsHeaderShow(false)
    }
  }, [])
  // 스크롤의 위 아래 이동감지는 쓰로틀이 이용
  const throttleScroll = useThrottle(handleScroll, 300)
  // 스크롤의 멈춤은 디바운스를 이용한다.(디바운스가 마지막 그룹의 이벤트를 노티해준다는 특성이용)
  const debounceScroll = useDebounce(stopScroll, 1500)
  const scrollDetectHandler = useCallback(
    (...e) => {
      throttleScroll(...e)
      debounceScroll(...e)
    },
    [prevY]
  )
  // DOM 제어시 useLayoutEffect를 사용하는게 성능상 좋음.
  useLayoutEffect(() => {
    if (scrollRef.current) {
      scrollRef.current.addEventListener('scroll', scrollDetectHandler)
    }
    return () => {
      if (!scrollRef.current) return
      scrollRef.current.removeEventListener('scroll', scrollDetectHandler)
    }
  }, [prevY])
function find_csa(arr, subarr, from_index) {
    var i = from_index >>> 0,
        sl = subarr.length,
        l = arr.length + 1 - sl;

    loop: for (; i<l; i++) {
        for (var j=0; j<sl; j++)
            if (arr[i+j] !== subarr[j])
                continue loop;
        return i;
    }
    return -1;
}
const btn = document.querySelector('button');

function random(number) {
  return Math.floor(Math.random() * (number+1));
}

btn.addEventListener('click', () => {
  const rndCol = `rgb(${random(255)}, ${random(255)}, ${random(255)})`;
  document.body.style.backgroundColor = rndCol;
});
import React, {useState, useEffect} from 'react';

const App = () => {
  const [loading, setLoading] = useState(false);
  
  useEffect(() => {
    setLoading(true);
    setTimeout(() => {
      setLoading(false);
    }, 2000);
  }, []);
  
  return(
    <div>
      // ...
    </div>
  )
}

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

const App = () => {
  const inputRef = useRef(null)
  
  useEffect(()=>{
    inputElRef.current.focus()
  }, [])
  
  return(
    <div>
      <input type="text" ref={inputRef} />
    </div>
  )
}

export default App;
const result = useMemo(() => expensivesunction(input), [input]);
function getObjectKeyByValue ( obj value ){
	return Object.keys(obj).find(key => obj[key] === value)
}

const myObject = {
  "key1" : "value 1",
  "key2" : "value 2"
}

const myKey = getObjectKeyByValue ( myObject , "value 2")

console.log ( myKey )
//print key2

class Astronaut {
   name: string;
   constructor(firstName: string, lastName: string) {
      this.name = firstName + " " + lastName;
   }
   greet() {
      return "Hello, " + this.name;
   }
}

let Bob = new Astronaut("Bob","Smith");
//
//You may remember the this and new keywords from working with classes in JavaScript. Earlier in the chapter, we also noted that when declaring variables in TypeScript, we have to specify the type of value. The same applies to function parameters, as you can see in the constructor.

class Panthera {
   roar: string;
   constructor(currentRoar: string) {
      this.roar = currentRoar;
   }
}

class Tiger extends Panthera {
   stripes: boolean = true;

}

let tigger = new Tiger("loud");
console.log(tigger.roar);
console.log(tigger.stripes);
     function myFunction(a: number, b?:number): number {
             if (typeof b !== 'undefined'){
                     return a+b+5;
                  } else {
                          return a+5;
                  }
          }

console.log(myFunction(1,2));
console.log(myFunction(1));
console.log(myFunction(3,5));
console.log(myFunction(3));
8
6
13
8
//Arrays in TypeScript must contain values of the same type. When declaring an array, the type needs to be declared.
let arrayName: number[] = [10,9,8];
//What if the array needs to hold values of different types? Now, we need a tuple. A tuple is a special structure in TypeScript that can hold as many values as needed of different types.

let tupleName: [number, string, number];

tupleName = [10, "9", 8];


// JS=let cargoHold = ['oxygen tanks', 'space suits', 'parrot', 'instruction manual', 'meal packs', 'slinky', 'security blanket'];

let cargoHold: string[] = ['oxygen tanks', 'space suits', 'parrot', 'instruction manual', 'meal packs', 'slinky', 'security blanket'];

//JS=
let element1 = ['hydrogen', 'H', 1.008];
let element2 = ['helium', 'He', 4.003];
let element26 = ['iron', 'Fe', 55.85];

//TS=
let element1: [string, string, number];
element1 = ['hydrogen', 'H', 1.008];

let element2: [string, string, number];
element2 = ['helium', 'He', 4.003];

let element26: [string, string, number];
element26 = ['iron', 'Fe', 55.85];
// In JavaScript, we have:

let spaceShuttleName = "Determination";
let shuttleSpeed = 17500;
let distancetoMars = 225000000;
let distancetoMoon = 384400;
let milesperKilometer = 0.621;

// The same declarations in TypeScript would be:

let spaceShuttleName: string = "Determination";
let shuttleSpeed: number = 17500;
let distancetoMars: number = 225000000;
let distancetoMoon: number = 384400;
let milesperKilometer: number = 0.621;
const items = json
const replacer = (key, value) => value === null ? '' : value 
const header = Object.keys(items[0])
const csv = [
  header.join(','), // header row first
  ...items.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n')

console.log(csv)
$.ajax({
  type: "GET",
  url: "/ccstoreui/v1/orders?fields=orderId,",
  dataType: 'json',
  headers: {
    "Authorization": "Bearer " + ccRestClient.tokenSecret
  },
  success: function (){
      console.log('success')
  }
}, function (reponse){
    console.log(response)
});
(function (d) {
    var w = d.documentElement.offsetWidth,
        t = d.createTreeWalker(d.body, NodeFilter.SHOW_ELEMENT),
        b;
    while (t.nextNode()) {
        b = t.currentNode.getBoundingClientRect();
        if (b.right > w || b.left < 0) {
            t.currentNode.style.setProperty('outline', '1px dotted red', 'important');
            console.log(t.currentNode);
        }
    };
}(document));
<html>
   <head>
      <title>Launch Status</title>
      <script>
         window.addEventListener("load", function() {
            fetch("https://handlers.education.launchcode.org/static/weather.json").then( function(response) {
               response.json().then( function(json) {
                  const div = document.getElementById("weather-conditions");
                  // Add HTML that includes the JSON data
                  div.innerHTML = `
                     <ul>
                        <li>Temp ${json.temp}</li>
                        <li>Wind Speed ${json.windSpeed}</li>
                        <li>Status ${json.status}</li>
                        <li>Chance of Precip ${json.chanceOfPrecipitation}</li>
                     </ul>
                  `;
               });
            });
         });
      </script>
   </head>
   <body>
      <h1>Launch Status</h1>
      <h3>Weather Conditions</h3>
      <div id="weather-conditions">
         <!-- Weather data is added here dynamically. -->
      </div>
   </body>
</html>
const PORT = 8000
const axios = require('axios')
const cheerio = require('cheerio')
const express = require('express')

const app = express()

const url = 'https://www.theguardian.com/us'

axios(url)
    .then(response => {
       const html = response.data 
       const $ = cheerio.load(html)
       const articles = [

       ]
       $('.fc-item__title', html).each(function() {
        const title = $(this).text()
        const url = $(this).find('a').attr('href')
        articles.push({
           title,
           url 
        }) 

    })
    console.log(articles)
}).catch(err => console.log(err) )

app.listen(PORT, () => console.log('server running on PORT 8000'))
{
  "name": "project",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "start": "nodemon index.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^0.27.2",
    "cheerio": "^1.0.0-rc.12",
    "express": "^4.18.1",
    "nodemon": "^2.0.19",
    "npx": "^10.2.2"
  }
}
$ uglifyjs file1.js file2.js ... --compress --mangle --output out.min.js
function jump(hashString){
    var url = location.href;                //Save the URL without hash part.
    location.href = "#" + hashString;       //Jump to target anchor (by id).
    history.replaceState(null,null,url);    //If you don't like hashes restore url.
}
<script>
   window.addEventListener("load", function() {
      let form = document.querySelector("form");
      form.addEventListener("submit", function(event) {
         let usernameInput = document.querySelector("input[name=username]");
         let teamName = document.querySelector("input[name=team]");
         if (usernameInput.value === "" || teamName.value === "") {
            alert("All fields are required!");
            // stop the form submission
            event.preventDefault();
         }
      });
   });
</script>
<form action="https://handlers.education.launchcode.org/request-parrot" method="post">
   <label>Operation Code:
   <!-- includes empty value "Select One" option -->
   <select name="operation">
      <option value="">* Select One *</option>
      <option value="1">Simulation</option>
      <option value="2">Rocket Test</option>
      <option value="3">Crew Related</option>
   </select>
   </label>

   <label>Facility:
   <select name="facility">
      <option value="johnson">Johnson Space Center, TX</option>
      <option value="kennedy">Kennedy Space Center, FL</option>
      <option value="white-sands">White Sands Test Facility, NM</option>
   </select>
   </label>
   <button>Send Report</button>
</form>
<form action="https://handlers.education.launchcode.org/request-parrot" method="post">
   Flight Rating:
   <label>Rough<input type="radio" name="flightRating" value="rough"/></label>
   <label>Few Bumps<input type="radio" name="flightRating" value="fewBumps"/></label>
   <label>Smooth<input type="radio" name="flightRating" value="smooth"/></label>
   <button>Send Report</button>
</form>
<div>Activities</div>
<label>cooking<input type="checkbox" name="cooking"/></label>
<label>running<input type="checkbox" name="running"/></label>
<label>movies<input type="checkbox" name="movies"/></label>

//Multiple checkbox inputs with the SAME name attribute.

<div>Ingredients</div>
<label>Onion<input type="checkbox" name="ingredient" value="onion"/></label>
<label>Butter<input type="checkbox" name="ingredient" value="butter"/></label>
<label>Rice<input type="checkbox" name="ingredient" value="rice"/></label>
<form action="https://handlers.education.launchcode.org/request-parrot" method="post">
  <label>Email<input type="email" name="emailAddress"/></label>
  <label>Report Date<input type="date" name="reportDate"/></label>
  <label>Crew Count<input type="number"
  name="crewCount" min="1" max="10"/></label>
  <button>Send Report</button>
</form>
<form action="https://handlers.education.launchcode.org/request-parrot" method="post">
   <label>Code Name<input type="text" name="codeName"/></label>
   <label>Code Word<input type="password" name="codeWord"/></label>

   <!-- textarea must have open and closing tags -->
   <label>Mission Description<br/>
      <textarea name="description" rows="5" cols="75"></textarea>
   </label>

   <button>Send Report</button>
</form>
<form action="" method="POST">
   <label>Username <input type="text" name="username"></label>
   <label>Team Name <input type="text" name="team"></label>
   <button>Submit</button>
</form>
<form>
   <label>Username <input type="text" name="username"></label>
   <!-- clicking either of these will cause a form submission -->
   <input type="submit"/>
   <button>Submit</button>
</form>
<html>
   <head>
      <title>Form Example</title>
   </head>
   <body>
      <form>
         <label>Username <input type="text" name="username"/></label>
         <label>Team Name <input type="text" name="team" value="JavaScript"/></label>
      </form>
   </body>
</html>
let element = document.querySelector('button');

function turnButtonRed(){
  element.style.backgroundColor = 'red';
  element.style.color = 'white';
  element.innerHTML = 'Red Button';
}

element.onclick = turnButtonRed;
let elementToRemove = document.getElementById('vespa');
document.getElementById('italy-attractions').removeChild(elementToRemove);

<!DOCTYPE html>
<html>

<head>
  <title>Vacation World</title>
  <link href="style.css" type="text/css" rel="stylesheet">
</head>

<body>
 <img src="https://content.codecademy.com/courses/freelance-1/unit-2/explorer.jpeg" />
 <h1 class="title cursive capitalize" >Vacationing in Florence, Italy</h1>
 <h5>By: Ezio Auditore</h5>
 <h6 class="publish-time">Published: 2 Days Ago</h6>
 
 <p>Florence is full of fascinating places. Planning the perfect experience 'Di Firenze' involves researching reputable travel blogs, choosing the best season to travel, and being open to all that Florence has to offer.</p>
 <h2 class="destination">Florence's History</h2>
 <div class="description">A city-size shrine to the Renaissance, Florence offers frescoes, sculptures, churches, palaces, and other monuments from the richest cultural flowering the world has known. Names from its dazzling historical pastDante, Michelangelo, Galileo, Machiavelliare some of the most resonant of the medieval age. <a href="http://travel.nationalgeographic.com/travel/city-guides/florence-italy/" target="_blank">Learn More</a>.
   <h5>Top Attractions</h5>
   <ul id="italy-attractions">
     <li>Museums</li>
     <li>Bike Tours</li>
     <li>Historical Monuments</li>
     <li id="vespa">Rent a Vespa</li>
   </ul>
 </div>
</body>
  <script src="./main.js"></script>
</html>
let elementToRemove = document.getElementById('vespa');
document.getElementById('italy-attractions').removeChild(elementToRemove);
let element = document.querySelector('button');

function turnButtonRed(){
  element.style.backgroundColor = 'red';
  element.style.color = 'white';
  element.innerHTML = 'Red Button';
}

element.onclick = turnButtonRed;
let elementToRemove = document.getElementById('vespa');
document.getElementById('italy-attractions').removeChild(elementToRemove);


<!DOCTYPE html>
<html>

<head>
  <title>Vacation World</title>
  <link href="style.css" type="text/css" rel="stylesheet">
</head>

<body>
 <img src="https://content.codecademy.com/courses/freelance-1/unit-2/explorer.jpeg" />
 <h1 class="title cursive capitalize" >Vacationing in Florence, Italy</h1>
 <h5>By: Ezio Auditore</h5>
 <h6 class="publish-time">Published: 2 Days Ago</h6>
 
 <p>Florence is full of fascinating places. Planning the perfect experience 'Di Firenze' involves researching reputable travel blogs, choosing the best season to travel, and being open to all that Florence has to offer.</p>
 <h2 class="destination">Florence's History</h2>
 <div class="description">A city-size shrine to the Renaissance, Florence offers frescoes, sculptures, churches, palaces, and other monuments from the richest cultural flowering the world has known. Names from its dazzling historical pastDante, Michelangelo, Galileo, Machiavelliare some of the most resonant of the medieval age. <a href="http://travel.nationalgeographic.com/travel/city-guides/florence-italy/" target="_blank">Learn More</a>.
   <h5>Top Attractions</h5>
   <ul id="italy-attractions">
     <li>Museums</li>
     <li>Bike Tours</li>
     <li>Historical Monuments</li>
     <li id="vespa">Rent a Vespa</li>
   </ul>
 </div>
</body>
  <script src="./main.js"></script>
</html>
let newAttraction = document.createElement('li');

newAttraction.id = 'vespa';
newAttraction.innerHTML = 'Rent a Vespa';

document.getElementById('italy-attractions').appendChild(newAttraction);
let newAttraction = document.createElement('li');

newAttraction.id = 'vespa';
newAttraction.innerHTML = 'Rent a Vespa';

document.getElementById('italy-attractions').appendChild(newAttraction);
let newAttraction = document.createElement('li');

newAttraction.id = 'vespa';
newAttraction.innerHTML = 'Rent a Vespa';

document.getElementById('italy-attractions').appendChild(newAttraction);
let newAttraction = document.createElement('li');

newAttraction.id = 'vespa';
newAttraction.innerHTML = 'Rent a Vespa';

document.getElementById('italy-attractions').appendChild(newAttraction);
let newAttraction = document.createElement('li');

newAttraction.id = 'vespa';
newAttraction.innerHTML = 'Rent a Vespa';

document.getElementById('italy-attractions').appendChild(newAttraction);
let newAttraction = document.createElement('li');

newAttraction.id = 'vespa';
newAttraction.innerHTML = 'Rent a Vespa';

document.getElementById('italy-attractions').appendChild(newAttraction);
const first = document.body.children[0];
first.innerHTML = 'BROWN BEARS ARE AWESOME!';

first.parentNode.style.backgroundColor = 'beige';
document.body.style.backgroundColor = '#201F2E';

document.querySelector('.heading').style.fontFamily = 'Roboto'
document.querySelector('h1').innerHTML = 'Most popular Harry Potter characters';

document.getElementById('fourth').innerHTML = 'Professor Snape';

document.getElementsByClassName('slytherin')[0].innerHTML = 'Salazar Slytherin';

document.getElementsByTagName('li')[0].innerHTML = 'Dobby';

<html> 
 <head>
   <title>Popular Fantasy Searches</title>
 </head>
 
 <body>
   <h1 class="ranking">Top 5 Best Selling Costumes</h1>
   <ol>
     <li id="first">Harry Potter</li>
     <li id="second">Hermione Granger</li>
     <li class="slytherin" id="third">Lord Voldemort</li>
     <li class="slytherin" id="fourth">Draco Malfoy</li>
     <li id="fifth">Hagrid</li>
   </ol>
  
 </body>
 <script src="./main.js"></script>
</html>
document.body.innerHTML = '<h1>This is now the heading of the body element</h1>'
(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Textual content'})
  });
  const content = await rawResponse.json();

  console.log(content);
})();
function getObjectFromForm(formSelector) {
    document.querySelector(formSelector)
    .addEventListener("submit", e => {
        e.preventDefault();
 
        const data = Object.fromEntries(new FormData(e.target));
 
        // then do what you want with data or JSON.stringify(data)
    });
}
var c = document.createDocumentFragment();
for (var i=0; i<10000; i++) {
    var e = document.createElement("div");
    e.className = "test-div";
    c.appendChild(e);
}
document.body.appendChild(c);
function resolveAfter2Seconds() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('resolved');
    }, 2000);
  });
}

async function asyncCall() {
  console.log('calling');
  const result = await resolveAfter2Seconds();
  console.log(result);
  // expected output: "resolved"

asyncCall();
function uploadfile(file, url, success, progress){
	const ajax = new XMLHttpRequest();
	const formData = new FormData();

	if (el instanceof Element) file=file.files[0];

	formData.append('file', file);

	if (typeof progress=='function') {
		ajax.upload.addEventListener(
			'progress',
			function ProgressHandler(event){
				const p = Math.floor((event.loaded / event.total) * 100);
				progress(`${p}%`);
			}
		);
	}
	if (success) ajax.addEventListener('load', success, false);
	ajax.open('POST', url, true);
	ajax.send(formData);
}
/* css: 

.element{
    position: relative; <-- important to place effect span in element to be clicked 
}

.ripple{
    position: absolute;
    background-color:#fff;
    transform: translate(-50%,-50%);
    pointer-events: none;
    border-radius: 50%;
    animation: animate 0.5s linear infinite;   
}

@keyframes animate {
    0% {
        width: 0px;
        height: 0px;
        opacity: 0.5;
    }
    100%{
        width: 800px;
        height: 800px;
        opacity: 0; 
    }
}
*/

element.addEventListener("click", (e)=>{
    var rect = e.target.getBoundingClientRect();
    let x=e.clientX - rect.x;
    let y=e.clientY - rect.y;
    let ripples = document.createElement('span');
    ripples.className="ripple";
    ripples.style.left = x + 'px';
    ripples.style.top = y + 'px';
    e.target.appendChild(ripples);
    setTimeout(()=>{
        ripples.remove();
    }, 500);
})
var search = 'abc=foo&def=%5Basf%5D&xyz=5';

obj = JSON.parse('{"' + decodeURI(search).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g,'":"') + '"}');
create folder in your root directory assets/Fonts and add your custom fonts
you want.
create a file in root folder and called react-native.config.js
Add the following code to the file =>

module.exports = {
project: {
    ios: {},
    android: {},
},
assets: ['./assets/Fonts']
};


or 
module.exports = {
    assets: ['./assets/Fonts'],
  };


Then, run the following command in your terminal:
react-native link 

to use it declare this way in your styles:
fontFamily: 'your-font-name without extension'

If your font is Raleway-Bold.ttf then,
  fontFamily: 'Raleway-Bold'
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<title>OpenStreetMap & OpenLayers - Marker Example</title>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">
	<script src="https://openlayers.org/en/v4.6.5/build/ol.js" type="text/javascript"></script>
  
  <script>
    /* OSM & OL example code provided by https://mediarealm.com.au/ */
    var map;
    var mapLat = -33.829357;
		var mapLng = 150.961761;
    var mapDefaultZoom = 10;
    
    function initialize_map() {
      map = new ol.Map({
        target: "map",
        layers: [
            new ol.layer.Tile({
                source: new ol.source.OSM({
                      url: "https://a.tile.openstreetmap.org/{z}/{x}/{y}.png"
                })
            })
        ],
        view: new ol.View({
            center: ol.proj.fromLonLat([mapLng, mapLat]),
            zoom: mapDefaultZoom
        })
      });
    }

    function add_map_point(lat, lng) {
      var vectorLayer = new ol.layer.Vector({
        source:new ol.source.Vector({
          features: [new ol.Feature({
                geometry: new ol.geom.Point(ol.proj.transform([parseFloat(lng), parseFloat(lat)], 'EPSG:4326', 'EPSG:3857')),
            })]
        }),
        style: new ol.style.Style({
          image: new ol.style.Icon({
            anchor: [0.5, 1],
            src: "http://vps1.dyndns.info:8051/markers/svg/map-marker-blue.svg"
          })
        })
      });

      map.addLayer(vectorLayer); 
    }


  </script>
</head>
<body onload="initialize_map(); add_map_point(-33.8688, 151.2093);">
  <div id="map" style="width: 100vw; height: 100vh;"></div>
</body>
</html>
openWindowWithPost("http://my.url.address/path", {
    param1: "value1",
    param2: "value2",
    //:
});

function openWindowWithPost(url, data) {
    var form = document.createElement("form");
    form.target = "_blank";
    form.method = "POST";
    form.action = url;
    form.style.display = "none";

    for (var key in data) {
        var input = document.createElement("input");
        input.type = "hidden";
        input.name = key;
        input.value = data[key];
        form.appendChild(input);
    }
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
}
function xhrSuccess () { this.callback.apply(this, this.arguments); }

function xhrError () { console.error(this.statusText); }

function loadFile (sURL, fCallback /*, argumentToPass1, argumentToPass2, etc. */) {
  var oReq = new XMLHttpRequest();
  oReq.callback = fCallback;
  oReq.arguments = Array.prototype.slice.call(arguments, 2);
  oReq.onload = xhrSuccess;
  oReq.onerror = xhrError;
  oReq.open("get", sURL, true);
  oReq.send(null);
}
Usage:

function showMessage (sMsg) {
  alert(sMsg + this.responseText);
}

loadFile("message.txt", showMessage, "New message!\n\n");
var url = new URL("",location);

console.log(url.host); // ip address or hostname:port number
console.log(url.protocol); // protocol
console.log(url.hostname); // ip address or hostname
console.log(url.port); // port number
console.log(url.origin); // protocol://ip address or hostname:port number

console.log(url.pathname); // /current path/
<script src="https://apps.elfsight.com/p/platform.js" defer></script>
<div class="elfsight-app-9a17642b-0849-44c7-af61-94872a45af4b"></div>
//<button type="button">Beep!</button>

function beep() {
    var snd = new  Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");  
    snd.play();
}


document.getElementsByTagName("button")[0].addEventListener("click",    beep);
var inAppBrowserRef = cordova.InAppBrowser.open("http://www.mypage.com", "_blank");
inAppBrowserRef.addEventListener("message", function (params){
    if(params.data.action === "myNativeMethod"){
        // Call your native method
        myApp.myNativeMethod();
    }
});


//Then in the webpage being loaded into the InappBrowser you'd send the message:

<button id="myButton">Press me</button>
<script type="text/javascript">
    document.getElementById("myButton").addEventListener("click", function(){
        var message = {action: "myNativeMethod"};
        webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));
    }, false);
</script>

//If you don't have direct control over the page being loaded into the InappBrowser, you could inject the code to send the message:

inAppBrowserRef.executeScript({ 
    code: '\
        document.getElementById("myButton").addEventListener("click", function(){\
            var message = {action: "myNativeMethod"};\
            webkit.messageHandlers.cordova_iab.postMessage(JSON.stringify(message));\
        }, false);\
    '
});
/*
at: plugins/cordova-plugin-fcm/scripts/fcm_config_files_process.js
Now change the file like this:
*/

// change
var strings = fs.readFileSync("platforms/android/res/values/strings.xml").toString();
// to
var strings = fs.readFileSync("platforms/android/app/src/main/res/values/strings.xml").toString();

// AND

//change
fs.writeFileSync("platforms/android/res/values/strings.xml", strings);

//to
fs.writeFileSync("platforms/android/app/src/main/res/values/strings.xml", strings);

/*After that, copy the google-services.json file to the following directories:

platforms/android/google-services.json
platforms/android/app/google-services.json  */
(function (window) {

    function _registerEvent(target, eventType, cb) {
        if (target.addEventListener) {
            target.addEventListener(eventType, cb);
            return {
                remove: function () {
                    target.removeEventListener(eventType, cb);
                }
            };
        } else {
            target.attachEvent(eventType, cb);
            return {
                remove: function () {
                    target.detachEvent(eventType, cb);
                }
            };
        }
    }

    function _createHiddenIframe(target, uri) {
        var iframe = document.createElement("iframe");
        iframe.src = uri;
        iframe.id = "hiddenIframe";
        iframe.style.display = "none";
        target.appendChild(iframe);
        return iframe;
    }

    function openUriWithHiddenFrame(uri, successCb, failCb) {

        var timeout = setTimeout(function () {
            failCb();
            handler.remove();
        }, 1000);

        var iframe = document.querySelector("#hiddenIframe");
        if (!iframe) {
            iframe = _createHiddenIframe(document.body, "about:blank");
        }

        var handler = _registerEvent(window, "blur", onBlur);

        function onBlur() {
            clearTimeout(timeout);
            handler.remove();
            successCb()
        }

        iframe.contentWindow.location.href = uri;
    }

    function openUriWithTimeoutHack(uri, successCb, failCb) {

        var timeout = setTimeout(function () {
            failCb();
            handler.remove();
        }, 1000);

        var handler = _registerEvent(window, "blur", onBlur);

        function onBlur() {
            clearTimeout(timeout);
            handler.remove();
            successCb()
        }
        window.location = uri;

    }

    function openUriUsingFirefox(uri, successCb, failCb) {
        var iframe = document.querySelector("#hiddenIframe");
        if (!iframe) {
            iframe = _createHiddenIframe(document.body, "about:blank");
        }
        try {
            iframe.contentWindow.location.href = uri;
            successCb();
        } catch (e) {
            if (e.name == "NS_ERROR_UNKNOWN_PROTOCOL") {
                failCb();
            }
            else {
                successCb();
            }
        }
    }

    function openUriUsingIEInOlderWindows(uri, failCb) {
        if (getInternetExplorerVersion() === 10) {
            openUriUsingIE10InWindows7(uri, failCb);
        } else if (getInternetExplorerVersion() === 9 || getInternetExplorerVersion() === 11) {
            openUriWithHiddenFrame(uri, failCb);
        } else {
            openUriInNewWindowHack(uri, failCb);
        }
    }

    function openUriUsingIE10InWindows7(uri, successCb, failCb) {
        var timeout = setTimeout(failCb, 1000);
        window.addEventListener("blur", function () {
            clearTimeout(timeout);
        });

        var iframe = document.querySelector("#hiddenIframe");
        if (!iframe) {
            iframe = _createHiddenIframe(document.body, "about:blank");
        }
        try {
            iframe.contentWindow.location.href = uri;
            successCb()
        } catch (e) {
            failCb();
            clearTimeout(timeout);
        }
    }

    function openUriInNewWindowHack(uri, successCb, failCb) {
        var myWindow = window.open('', '', 'width=0,height=0');

        myWindow.document.write("<iframe src='" + uri + "'></iframe>");
        setTimeout(function () {
            try {
                myWindow.location.href;
                myWindow.setTimeout("window.close()", 1000);
                successCb()
            } catch (e) {
                myWindow.close();
                failCb();
            }
        }, 1000);
    }

    function openUriWithMsLaunchUri(uri, successCb, failCb) {
        navigator.msLaunchUri(uri,
            successCb,
            failCb
        );
    }

    function checkBrowser() {
        var isOpera = !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
        return {
            isOpera: isOpera,
            isFirefox: typeof InstallTrigger !== 'undefined',
            isSafari: Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0,
            isChrome: !!window.chrome && !isOpera,
            isIE: /*@cc_on!@*/false || !!document.documentMode   // At least IE6
        }
    }

    function getInternetExplorerVersion() {
        var rv = -1;
        if (navigator.appName === "Microsoft Internet Explorer") {
            var ua = navigator.userAgent;
            var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null)
                rv = parseFloat(RegExp.$1);
        }
        else if (navigator.appName === "Netscape") {
            var ua = navigator.userAgent;
            var re = new RegExp("Trident/.*rv:([0-9]{1,}[\.0-9]{0,})");
            if (re.exec(ua) != null) {
                rv = parseFloat(RegExp.$1);
            }
        }
        return rv;
    }
    window.openUriWithTimeoutHack = openUriWithTimeoutHack;
    window.protocolCheck = function (uri, successCb, failCb) {
        function successCallBack() {
            successCb && successCb();
        }
        function failCallback() {
            failCb && failCb();
        }

        if (navigator.msLaunchUri) { //for IE and Edge in Win 8 and Win 10
            openUriWithMsLaunchUri(uri, successCb, failCb);
        } else {
            var browser = checkBrowser();

            if (browser.isFirefox) {
                openUriUsingFirefox(uri, successCallBack, failCallback);
            } else if (browser.isChrome) {
                openUriWithTimeoutHack(uri, successCallBack, failCallback);
            } else if (browser.isIE) {
                openUriUsingIEInOlderWindows(uri, successCallBack, failCallback);
            } else {
                //not supported, implement please
            }
        }
    }
}(window));
//<input type="text" value="B01" id="MYINPUT">

$("#MYINPUT").select(function(e){
    var selSt=$(this)[0].selectionStart;
    var selNd=$(this)[0].selectionEnd;
    
    if (selSt<3) {
        $(this)[0].setSelectionRange(3, selNd);
    }
});

function clone(src) {
	if(!src) return null;
	return JSON.parse(JSON.stringify(src));
}
function getFilename(fullname){
    return fullname.replace(/^.*[\\\/]/, '');
}

function getFilepath(fullname){
    var fn = fullname.split('/');
    fn.pop();
    return fn.join("/");
}

var filename = fullPath.replace(/^.*[\\\/]/, '');

/*

example:

   "/home/user/myfile.js".replace(/^.*[\\\/]/, ''); 
   
   returns:  myfile.js 
   
*/
(function (global) { 

    if(typeof (global) === "undefined") {
        throw new Error("window is undefined");
    }

    var _hash = "!";
    var noBackPlease = function () {
        global.location.href += "#";

        // making sure we have the fruit available for juice (^__^)
        global.setTimeout(function () {
            global.location.href += "!";
        }, 50);
    };

    global.onhashchange = function () {
        if (global.location.hash !== _hash) {
            global.location.hash = _hash;
        }
    };

    global.onload = function () {            
        noBackPlease();

        // disables backspace on page except on input fields and textarea..
        document.body.onkeydown = function (e) {
            var elm = e.target.nodeName.toLowerCase();
            if (e.which === 8 && (elm !== 'input' && elm  !== 'textarea')) {
                e.preventDefault();
            }
            // stopping event bubbling up the DOM tree..
            e.stopPropagation();
        };          
    }

})(window);
function capitalTitle(s) {
    var preposiciones = [
      'a','al','ante','bajo','cabe','con','contra','de','del','desde','durante',
      'en','entre','hacia','hasta','mediante','para','por','según','sin',
      'so','sobre','tras','versus','via','vs','las','los','y','x','o','ó'
    ];
  
    s=capital(s);
    var r='\\s+('+preposiciones.join("|")+')\\s+';
    var reg=new RegExp(r, "ig");
  
    s = s.replace(reg, function(match) {
        return match.toLowerCase();
    });
  
    s=s.replace(/cxc/gi,'CxC');
    s=s.replace(/cxp/gi,'CxP');
    s=s.replace(/srl/gi,'SRL');
    s=s.replace(/llc/gi,'LLC');
    s=s.replace(/ars/gi,'ARS');
    return s;
}

String.prototype.toTitleCase = function () {
    return this.toLowerCase().replace(/[^\s|\'\-]+/g, function(word) {
        return word.replace(/^./, function(first) {
            return first.toUpperCase();
        });
    });
} 
function ourEvent(e) {
    e=jQuery.event.fix(e);

    //  console.log(e.which);
    
    :
    :
}
function EventHandler(arg1, arg2,...) {
    var evt = window.event || function(cx) {
    if(typeof Event!='undefined' && cx){
    	for(var ii=0; ii<cx.arguments.length; ii++)
    		if(cx.arguments[ii] instanceof Event) return cx.arguments[ii];
    		return arguments.callee(cx.caller);
    	}
    	return null;
    }(arguments.callee.caller);
    
    evt.preventDefault=evt.preventDefault||function(){evt.returnValue = false;};
    evt.stopPropagation=evt.stopPropagation||function(){evt.cancelBubble = false;};
}
body{
    font-family: verdana;
    color:gray;
    margin: 8px;
}

.str{
    color:#F0F;
}

.perc{
    color:#000;
    background-color:#FF0;
}

.comment{
    color:silver;
}

p{
    color: black;
    font-style:italic;
}

<html>
    <head>
        <title>
            test
        </title>
    </head>
    <body>
This is a way to calculate similarity % between two strings based on <a href="https://en.wikipedia.org/wiki/Levenshtein_distance">Levenshtein distance:</a><p><p><br>
    </body>
</html>

function similarity(s1, s2) {
  var longer = s1;
  var shorter = s2;
  if (s1.length < s2.length) {
    longer = s2;
    shorter = s1;
  }
  var longerLength = longer.length;
  if (longerLength === 0) {
    return 1.0;
  }
  return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}

function editDistance(s1, s2) {
  s1 = s1.toLowerCase();
  s2 = s2.toLowerCase();

  var costs = new Array();
  for (var i = 0; i <= s1.length; i++) {
    var lastValue = i;
    for (var j = 0; j <= s2.length; j++) {
      if (i == 0)
        costs[j] = j;
      else {
        if (j > 0) {
          var newValue = costs[j - 1];
          if (s1.charAt(i - 1) != s2.charAt(j - 1))
            newValue = Math.min(Math.min(newValue, lastValue),
              costs[j]) + 1;
          costs[j - 1] = lastValue;
          lastValue = newValue;
        }
      }
    }
    if (i > 0)
      costs[s2.length] = lastValue;
  }
  return costs[s2.length];
}

var $str1="Marco Antonio Piñero Lopez";
var $str2="marco antonio Pineda lópez";

var perc=Math.round(similarity($str1,$str2)*10000)/100;

var txt="The strings: <span class=\"str\">'"+$str1+"'</span> and <span class=\"str\">'"+$str2+"'</span>";
  txt+="<br>are similar <span class=\"perc\">"+perc+"%</span>";
document.write(txt);

if (navigator.onLine){
  alert('You r connected!');
} else {
  alert('No connection :(');
}
global.res= function (v){
    return new Promise(function(r){r(v);});
}
global.rej= function (v){
    return new Promise(function(r,rr){rr(v);});
}
const recurse = (rows) => _.map((rows), (row) => row.collapsed ? [row] : [row, recurse(row.children)]);

const flattenTree = tree => _.flattenDeep(recurse(tree));

const actions = new Map([
  ['1', ['processing']],
  ['2', ['fail']],
  ['3', ['fail']],
  ['4', ['success']],
  ['5', ['cancel']],
  ['default', ['other']]
])

const clickHandler = (status) => {
  let action = actions.get(status) || actions.get('default')
  sendLog(action[0])
}
var myName;
// var keyword create a variable called myName

 //you can store a value in a variable with the assignment operator (=).
var a;
a = 7;
// this code assign the value 7 to variable a.

//you can assign the value of that variable to another variable using the assignment operator.
var myVar;
myVar = 5;
var myNum;
myNum = myVar;
// now the code assign the contents of a to variable b.
                                                                   
var myName;
// var keyword create a variable called myName

 //you can store a value in a variable with the assignment operator (=).
var a;
a = 7;
// this code assign the value 7 to variable a.

//you can assign the value of that variable to another variable using the assignment operator.
var myVar;
myVar = 5;
var myNum;
myNum = myVar;
// now the code assign the contents of a to variable b.

//It is common to initialize a variable to an initial value in the same line as it is declared.
var myVar = 0;

//But you can also declare a string variable like this:
var myName = "your name";
//"your name" is called a string literal, another example 
var myFirstName = "alya"
var myLastName = "shofiyah"

                                                                   
var now = new Date();
var time = now.getTime();
var expireTime = time + 10000*36000;
now.setTime(expireTime);
document.cookie = 'cookie=ok;expires='+now.toUTCString()+';path=/';
// This is an in-line comment.
/* This is a
multi-line comment */
let geoloc = document.getElementById("theElementID");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    geoloc.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  geoloc.innerHTML = "Latitude: " + position.coords.latitude +
  "<br>Longitude: " + position.coords.longitude;
}
 
Example where to use
equalheight('.service-slider-sec .bottom-content');

equalheight = function (container) {
var currentTallest = 0,
currentRowStart = 0,
rowDivs = new Array(),
$el,
topPosition = 0;
jQuery(container).each(function () {
$el = jQuery(this);
jQuery($el).height('auto')
topPostion = $el.position().top;
if (currentRowStart != topPostion) {
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
rowDivs.length = 0; // empty the array
currentRowStart = topPostion;
currentTallest = $el.height();
rowDivs.push($el);
} else {
rowDivs.push($el);
currentTallest = (currentTallest < $el.height()) ? ($el.height()) : (currentTallest);
}
for (currentDiv = 0; currentDiv < rowDivs.length; currentDiv++) {
rowDivs[currentDiv].height(currentTallest);
}
});
}
//signature
Object.assign(target, ...sources)
var newState = Object.assign({}, state, action.state);
'use strict';
let myString = 'I am really hungry for some';
console.log(myString);

// To transform myString in UPPERCASE

let myUpperString = myString.toUpperCase();
console.log(myUpperString);

// methods have ();
// To extract the word REALLY from the myString
// first, get the location

let exactLocation = myString.search('really');

console.log(exactLocation);

// To get the word in full

let extractWordInFull = myString.substr(exactLocation, 6);
console.log(extractWordInFull);

// turning the extracted word into uppercase
let turnUpperCase = extractWordInFull.toUpperCase();
console.log(turnUpperCase);

// replacing the word in the string 
let newWord = myString.replace('really', turnUpperCase);
console.log(newWord);


let foods = ['bread', 'yam', 'rice', 'beans'];
let stringLiteral = `${myString} ${foods[0]}`;
console.log(stringLiteral);

// looping through a array together with a string
for(let i = 0; i < foods.length; i++) {
    console.log(`${myString} ${foods[i]}`)
  }

 /*  for(let eachFood of foods) { 
    console.log(`${myString} ${eachFood}`);
  } */

  for(let eachFoods of foods) { 
    console.log(`${myString} ${eachFoods}`);
  }

// to convert to an uppercase if the index of the food is an even number

 for ( let i = 0; i < foods.length; i++) { 
    if ( i % 2 === 0) { 

        let changeToUpperCase = foods[i].toUpperCase();
        console.log(`${myString} ${changeToUpperCase}`);
    }
    else { 
        console.log(`${myString} ${foods[i]}`);
    }
 }


// I CAN ALWAYS REFACTOR MY CODE
<script type = "text/javascript" >
    // JavaScript program to illustrate 
    // calculation of no. of days between two date 
  
    // To set two dates to two variables
    var date1 = new Date("06/30/2019");
var date2 = new Date("07/30/2019");
  
// To calculate the time difference of two dates
var Difference_In_Time = date2.getTime() - date1.getTime();
  
// To calculate the no. of days between two dates
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
  
//To display the final no. of days (result)
document.write("Total number of days between dates  <br>"
               + date1 + "<br> and <br>" 
               + date2 + " is: <br> " 
               + Difference_In_Days);
  
</script>
for (const key of yourArray) {
      obj[key] = whatever;
 }
function foo(x, ...args) {
  console.log(x, args, ...args, arguments);
}

foo('a', 'b', 'c', z='d')

=>

a
Array(3) [ "b", "c", "d" ]
b c d
Arguments
​    0: "a"
    ​1: "b"
    ​2: "c"
    ​3: "d"
    ​length: 4
(function() {
    const inputEls = document.querySelectorAll('input[name="product[name]"], textarea[name="product[short_description]"');
    function checkInputCharacters(input, inpuName) {
        const limit = 3; // <---max no. of lines
        const spaces = '40'; // <---max characters of each line
        const inputSpaces = '45'; // <---max characters of input
        const range = inpuName === 'product[short_description]' ? limit : inputSpaces;
        input.addEventListener('keyup', function() {
            const lines = inpuName === 'product[short_description]' ? input.value.split("\n") : input.value;
            for (let i = 0; i < lines.length; i++) {
                    if (lines[i].length <= spaces) continue;
                    let j = 0;
        
                    let space = spaces;
        
                    while (j++ <= spaces) {
                        if (lines[i].charAt(j) === " ") space = j;  
                    }
                lines[i + 1] = lines[i].substring(space + 1) + (lines[i + 1] || "");
                lines[i] = lines[i].substring(0, space);
            }

            handleInputStateColor(input, lines, range);

            if (inpuName === 'product[short_description]') {
                input.value = lines.slice(0, limit).join("\n");
            } else {
                lines.length > inputSpaces && (input.value = lines.slice(0, -(lines.length - inputSpaces)));
            }
        })
    }
    
    function handleInputStateColor(input, inputVal, limit) {
      if (inputVal.length > limit) {
            input.style.color = 'red';
            setTimeout (function(){
                input.style.color = '';
            },500);
        }
    }

    Array.prototype.forEach.call(inputEls, (el) => {
      checkInputCharacters(el, el.name);
    });
})();
const dropArea = document.getElementById('drop-area');

dropArea.addEventListener('dragover', (event) => {
  event.stopPropagation();
  event.preventDefault();
  // Style the drag-and-drop as a "copy file" operation.
  event.dataTransfer.dropEffect = 'copy';
});

dropArea.addEventListener('drop', (event) => {
  event.stopPropagation();
  event.preventDefault();
  const fileList = event.dataTransfer.files;
  console.log(fileList);
});
function readImage(file) {
  // Check if the file is an image.
  if (file.type && !file.type.startsWith('image/')) {
    console.log('File is not an image.', file.type, file);
    return;
  }

  const reader = new FileReader();
  reader.addEventListener('load', (event) => {
    img.src = event.target.result;
  });
  reader.readAsDataURL(file);
}
const switchFn = (lookupObject, defaultCase = '_default') =>
  expression => (lookupObject[expression] || lookupObject[defaultCase])();

const knownFruit = () => console.log('Known fruit');
const unknownFruit = () => console.log('Unknown fruit');

const logFruit = {
  'apples': knownFruit,
  'oranges': knownFruit,
  'default': unknownFruit
};

const fruitSwitch = switchFn(logFruit, 'default');

fruitSwitch('apples'); // Logs: 'Known fruit'
fruitSwitch('pineapples'); // Logs: 'Unknown fruit'
body {
  /* Old browsers */
  background: #141E30;
  /* Chrome 10-25, Safari 5.1-6 */
  background: -webkit-linear-gradient(-45deg, #35577D, #141E30);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
  background: linear-gradient(-45deg, #35577D, #141E30);
  margin: 0;
  padding: 0;
}

h1 {
  color: #FFF !important;
  font-size: 2em;
  padding-top: 100px;
  width: 100%;
  font-family: Georgia;
  text-align: center;
}

h2 {
  border-bottom: 1px solid rgba(255, 255, 255, 0.5);
  color: rgba(255, 255, 255, 0.5);
  font-weight: 100;
  font-size: 22px;
  line-height: 24px;
  padding-bottom: 30px;
  text-align: left;
  width: 70%;
  font-family: Georgia;
}

p {
  color: aliceblue;
  line-height: 1.3em;
  text-align: left;
  width: 100%;
  font-family: Helvetica;
  font-size: 18px;
  font-weight: bold;
}

.byline {
  font-family: Helvetica;
  color: rgba(255, 255, 255, 0.5);
  float: left;
  font-size: 14px;
  padding-left: 10px;
  text-transform: uppercase;
}

.caption {
  display: block;
  font-family: 'Playfair Display', serif;
  font-size: 14px;
  font-style: italic;
  line-height: 14px;
  margin-left: 20px;
  padding: 10px;
  position: relative;
  top: 80%;
  width: 60%;
  background-color: white;
  color: black;
}

.content {
  padding: 40px;
}

.image {
  background-image: url('https://content.codecademy.com/courses/freelance-1/unit-2/soccer.jpeg');
  background-size: cover;
  background-position: center;
  height: 300px;
}

.writer-img {
  -webkit-box-shadow: 5px 0px 5px 0px rgba(0, 0, 50, 0.97);
  -moz-box-shadow: 5px 0px 5px 0px rgba(0, 0, 50, 0.97);
  box-shadow: 5px 0px 5px 0px rgba(0, 0, 50, 0.97);
  float: left;
  width: 50px;
}
* {
  box-sizing: border-box;
}
body {
  background-color: #FFF;
  margin: 0px;
  padding: 50px 60px;
}

h1 {
  color: #004E89;
  font-family: 'Yantramanav', sans-serif;
  font-size: 50px;
  font-weight: 400;
  margin: 0;
  text-align: center;
}

h2 {
  color: #AAA;
  font-family: 'Yantramanav', sans-serif;
  font-size: 16px;
  font-weight: 100;
  letter-spacing: 2px;
  margin: 0;
  text-align: center;
  text-transform: uppercase;
}

p {
  color: #333;
  font-family: 'Yantramanav', sans-serif;
  font-size: 16px;
  font-weight: 100;
  margin: 0;
  text-align: center;
}

.actions {
  text-align: center;
  margin-top: 30px;
}

.actions a {
  background-color: #9DD1F1;
  border-radius: 3px;
  color: #004E89;
  font-family: 'Yantramanav', sans-serif;
  font-size: 16px;
  font-weight: 300;
  display: inline-block;
  margin: 10px;
  padding: 12px;
  text-align: center;
  text-decoration: none;
  text-transform: uppercase;
}

#gameboard {
  position: relative;
  text-align: center;
  top: 30px;
}

.card {
  
  border: 2px solid #9DD1F1;
  display: inline-block;
  height: 200px;
  margin-top: 4px;
  padding: 30px auto;
  text-align: center;
  width: 215px;
}

.card:hover {
  background-color: #004E89;
  border-color: #004E89;
}

.card img {
  padding-top: 40px;
}
body {
  background-color: white;
  font-family: 'Raleway', sans-serif;
}

.navigation ul {
  margin: 0;
  padding: 0;
  text-align: center;
}

.navigation li {
  font-weight: 100;
  letter-spacing: 2px;
  padding: 20px;
}

.navigation  li.logo {
  color: black;
  font-size: 18px;
  font-weight: 700;
  letter-spacing: 4px;
}

#banner {
  background-image: url("https://content.codecademy.com/courses/web-101/unit-6/htmlcss1-img_tahoe.jpeg");
  background-size: cover;
  background-position: bottom center;
  height: 700px;
  width: 100%;
}

#banner .content h1 {
  border: 3px solid white;
  position: relative;
  top: 50px;
  width: 400px;
  margin: 0 auto;
}

#main {
  margin: 0 auto;
  padding: 40px;
  text-align: center;
  width: 400px;
  height: 1000px;
  overflow: scroll;
}

h1 {
  color: white;
  font-size: 42px;
  font-weight: 600;
  text-align: center;
}

h2 {
  border: 1px dotted red;
  color: red;
  font-size: 14px;
  line-height: 48px;
  padding: 20px 30px;
  margin: 30px 20px;
  text-align: center;
}

h3 {
  color: red;
  font-size: 26px;
  font-weight: 700;
  padding: 20px 10px;
}

p {
  color: grey;
  font-size: 16px;
  line-height: 48px;
  margin-top: 60px;
  padding: 10px 20px;
}

.pull-quote {
  margin: 0 auto;
  width: 400px;
}

.byline {
  border-bottom: 1px solid LightGrey;
  border-top: 1px solid LightGrey;
  color: DarkGrey;
  font-size: 14px;
  font-weight: 200;
}

.share {
  border: 1px solid LightGrey;
  padding: 40px 0px;
  position: relative;
  text-align: center;
  width: 100%;
}

.share a {
  background: red;
  border: 1px solid red;
  border-radius: 3px;
  color: white;
  display: inline-block;
  margin: 10px;
  padding: 14px;
  text-decoration: none;
}

.share a:hover {
  background: white;
  border: 1px solid red;
  color: red;
}
const string = "STANDEE CHÂN SẮT KHUNG NHÔM SANG TRỌNG SIZE 80x20CM";

function limitInputCharacters(str) {
  if (str.length > 45) return;
  return true
}

//limitInputCharacters(string)
const pipeFunctions = (...fns) =>
  fns.reduce((f, g) => (...args) => g(f(...args)));
* {
  border: 1px solid red;
}

p {
  color: green;
}

h1 {
  color: maroon;
}

.title {
  color: teal;
}

.uppercase {
  text-transform: uppercase;
}

#article-title {
  font-family: Tahoma;
}

a[href*='florence'] {
  color: lightgreen;
}

a[href*='beijing'] {
  color: lightblue;
}

a[href*='seoul'] {
  color: lightpink;
}

a:hover {
  color:darkorange;
}

.heading-background {
  background-color: aqua;
}

#publish-time {
  color: lightgray;
}

h5 {
  color: yellow;
}

.author-class {
  color: pink;
}

#author-id {
  color: cornflowerblue;
}

h2.destination {
  font-family: Tahoma;
}

.description h5 {
  color: blueviolet;
}

li h4 {
  color: gold;
}

h4 {
  color: dodgerblue;
}
h5, 
.li {
font-family: monospace;
}
h1, 
.menu {
  font-family: Georgia;
}
h2.destination {
  font-family: Tahoma;
}
/////

<ul class='main-list'>
  <li> ... </li>
  <li> ... </li>
  <li> ... </li>
</ul>

.main-list li {
 
}

.description h5 {
  color: blueviolet;
}
///
p:hover {
  color: darkorange;;
}
<h1 id='large-title'> ... </h1>

#large-title {
 font-family: cursive;
}
//attributes
[href*='florence'] {
  color: lightgreen;
}
//<h1 class='title'>Top Vacation Spots</h1>
.title {
 color: teal;
}
//allows you to add two effects <h1 class='title uppercase'>

.uppercase {
  text-transform: uppercase;
}
p {
  color: green;
}

h1 {
  color: maroon;
}
* { 
  font-family: Verdana;
}
* { 
  border: 1px solid red;
}
const parent = document.querySelector(".parent");
const child = document.querySelector(".child");

// grandparent.addEventListener("click", e => {
//     console.log("Grandparent capture")
// }, { capture: true })  // it gives the hierarchy

grandparent.addEventListener("click", e => {
    console.log("Grandparent bubble")
}, { once: true })  // will run the code once 
// parent.addEventListener("click", e => {
//     e.stopPropagation() // none of the bubbles or capture occur 
//     console.log("Parent capture")
// }, { capture: true })
parent.addEventListener("click", sayhi)
setTimeout(() => {  // removes the event at a given time
    parent.removeEventListener("click", sayhi)
}, 2000)

// child.addEventListener("click", e => {
//     console.log("Child capture")
// }, { capture: true })
child.addEventListener("click", e => {
    console.log("Child bubble")
})
function sayhi() {   // creat a separate function
    console.log('Hi!')
}



const divs = document.querySelectorAll('div');
divs.forEach(div => {
    div.addEventListener('click', () => {
        console.log("inamo")
    })
})

addGlobalEventListener('click', 'div', e => {
    console.log('gago')
})
function addGlobalEventListener(type, selector, callback) {
    document.addEventListener(type, e => {
        if (e.target.matches(selector)) callback(e)
    })
}

const newDiv = document.createElement("div")
newDiv.style.width = '100px';
newDiv.style.height = '100px';
newDiv.style.backgroundColor = 'orange';
// newDiv.addEventListener('click', () => {
//     console.log('inamo')
// })
document.body.append(newDiv);

document.addEventListener("DOMContentLoaded", function(){
// make it as accordion for smaller screens
if (window.innerWidth > 992) {

	document.querySelectorAll('.navbar .nav-item').forEach(function(everyitem){

		everyitem.addEventListener('mouseover', function(e){

			let el_link = this.querySelector('a[data-bs-toggle]');

			if(el_link != null){
				let nextEl = el_link.nextElementSibling;
				el_link.classList.add('show');
				nextEl.classList.add('show');
			}

		});
		everyitem.addEventListener('mouseleave', function(e){
			let el_link = this.querySelector('a[data-bs-toggle]');

			if(el_link != null){
				let nextEl = el_link.nextElementSibling;
				el_link.classList.remove('show');
				nextEl.classList.remove('show');
			}


		})
	});

}
// end if innerWidth
}); 
// DOMContentLoaded  end
<!DOCTYPE html>

<html>
  <head>
    <title>Everyday with Isa</title>

    </head>
    <body>
      <h1>An Insider’s Guide to <a href="https://en.wikipedia.org/wiki/New_York_Fashion_Week" target="_blank">NYFW</a></h1>
      <img src =https://content.codecademy.com/courses/learn-html/elements-and-structure/image-one.jpeg>
      <p>NYFW can be both amazingly fun & incredibly overwhelming, especially if you’ve never been. Luckily, I’m here to give you an insider’s guide and make your first show a pleasurable experience. By taking my tips and tricks, and following your gut, you’ll have an unforgettable experience!
         </p>
      <h2>Getting Tickets & Picking the Shows</h2>
      <img src =https://content.codecademy.com/courses/learn-html/elements-and-structure/image-two.jpeg>
      <p>If you’re lucky or connected you can get an invite, sans the price tag. But I wasn’t so lucky or connected my first 2 years so I’m here to help you out. First, plan out which shows are most important to you and make a schedule and this is a biggie: SET A BUDGET. If you’re worrying about blowing your cash the whole time you won’t have fun. Then check out prices, days, and times and prioritize the designers you want to see most. Lastly, purchase your tickets and get excited!
         </p>
      <h2>Dressing for the Shows</h2>
      <img src =https://content.codecademy.com/courses/learn-html/elements-and-structure/image-three.jpeg>
      <p>Always be true to your own sense of style, if you don’t you’ll be uncomfortable the whole time and it will show. Remember, NYFW is about expressing yourself and taking in what the designers have chosen to express through their new lines. Also it’s important to wear shoes you’ll be comfortable in all day. Obviously you want to look good, but you’ll be on your feet all day long, so be prepared.”
        </p>
   
      </body>
  <img src =https://content.codecademy.com/courses/learn-html/elements-and-structure/profile.jpg>
  <h3>by Isabelle Rodriguez | 1 day ago</h3>
  <h4>Related Content</h4>
   <ul>
      <li>How To Style Boyfriend Jeans</li>
      <li>When Print Is Too Much</li>
      <li>The Overalls Trend</li>
      <li>Fall’s It Color: Blush</li>
    </ul>
    <div id="contact">
    <p><strong>email</strong>: isa@fashionblog.com | <strong>phone</strong>: 917-555-1098 | <br /><br /><strong>address</strong>: 371 284th St, New York, NY, 10001</p>
  </div>
<!DOCTYPE html>
<html>

<head>
  <title>Brown Bears</title>
</head>

<body>
  <a href="./index.html">Brown Bear</a>
  <a href="./aboutme.html">About Me</a>
  <h1>The Brown Bear</h1>
  <ul>
       <li><a href="#introduction">Introduction</a></li>
      <li><a href="#habitat">Habitat</a></li>
      <li><a href="#media">Media</a></li>

 </ul>
  <div id="introduction">
    <h2>About Brown Bears</h2>
    <p>The brown bear (<em>Ursus arctos</em>) is native to parts of northern Eurasia and North America. Its conservation status is currently <strong>Least Concern</strong>.<br /><br /> There are many subspecies within the brown bear species, including the
      Atlas bear and the Himalayan brown bear.</p>
    <a href="https://en.wikipedia.org/wiki/Brown_bear" target="_blank">Learn More</a>
    <h3>Species</h3>
    <ul>
      <li>Arctos</li>
      <li>Collarus</li>
      <li>Horribilis</li>
      <li>Nelsoni (extinct)</li>
    </ul>
    <h3>Features</h3>
    <p>Brown bears are not always completely brown. Some can be reddish or yellowish. They have very large, curved claws and huge paws. Male brown bears are often 30% larger than female brown bears. They can range from 5 feet to 9 feet from head to toe.</p>
  </div>
  <div id="habitat">
    <h2>Habitat</h2>
    <h3>Countries with Large Brown Bear Populations</h3>
    <ol>
      <li>Russia</li>
      <li>United States</li>
      <li>Canada</li>
    </ol>
    <h3>Countries with Small Brown Bear Populations</h3>
    <p>Some countries with smaller brown bear populations include Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India, Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and Uzbekistan.</p>
  </div>
  <div id="media">
    <h2>Media</h2>
    <a href="https://en.wikipedia.org/wiki/Brown_bear" target="_blank"><img src="https://content.codecademy.com/courses/web-101/web101-image_brownbear.jpg"/></a>
    <video src="https://content.codecademy.com/courses/freelance-1/unit-1/lesson-2/htmlcss1-vid_brown-bear.mp4" height="240" width="320" controls>Video not supported</video>
  </div>
</body>

</html>
<body>
  <h1>The Brown Bear</h1>
  <div id="introduction">
    <h2>About Brown Bears</h2>
    <p>The brown bear (<em>Ursus arctos</em>) is native to parts of northern Eurasia and North America. Its conservation status is currently <strong>Least Concern</strong>.<br /><br /> There are many subspecies within the brown bear species, including the Atlas bear and the Himalayan brown bear.</p>
    <h3>Species</h3>
    <ul>
      <li>Arctos</li>
      <li>Collarus</li>
      <li>Horribilis</li>
      <li>Nelsoni (extinct)</li>
    </ul>
    <h3>Features</h3>
    <p>Brown bears are not always completely brown. Some can be reddish or yellowish. They have very large, curved claws and huge paws. Male brown bears are often 30% larger than female brown bears. They can range from 5 feet to 9 feet from head to toe.</p>
  </div>
  <div id="habitat">
    <h2>Habitat</h2>
    <h3>Countries with Large Brown Bear Populations</h3>
    <ol>
      <li>Russia</li>
      <li>United States</li>
      <li>Canada</li>
    </ol>
    <h3>Countries with Small Brown Bear Populations</h3>
    <p>Some countries with smaller brown bear populations include Armenia, Belarus, Bulgaria, China, Finland, France, Greece, India, Japan, Nepal, Poland, Romania, Slovenia, Turkmenistan, and Uzbekistan.</p>
  </div>
  <div id="media">
    <h2>Media</h2>
    <img src="https://content.codecademy.com/courses/web-101/web101-image_brownbear.jpg" alt="A Brown Bear"/>
        <video src="https://content.codecademy.com/courses/freelance-1/unit-1/lesson-2/htmlcss1-vid_brown-bear.mp4" width="500" height="500" controls>Video not supported</video>
  </div>
</body>
const num = 5;
console.log(scale(num, 0, 10, -50, 50)); // 0
console.log(scale(num, -20, 0, -100, 100)); // 150
function scale (number, inMin, inMax, outMin, outMax) {
    return (number - inMin) * (outMax - outMin) / (inMax - inMin) + outMin;
}
let getA = a => a*a;
console.log(getA(2))
 
var b = 5 // outside the scope 
let square = () => {return b*b};
console.log(square())

// inside the scope
let square = (b) => {return b*b};
console.log(square(9))

let double = function(b){
    return b*b
};
console.log(double(10))
.accordion-item {
	background-color: #f4f4f6;
}

.accordion-header {
	display: flex;
	align-items: center;
	cursor: pointer;
}

.accordion-header::before {
	content: '+';
	font-size: 3.5rem;
	margin-right: 20px;
}

.active-header::before {
	content: '-';
}

.accordion-content {
	max-height: 0;
	overflow: hidden;
	transition: 1s ease max-height;
	font-size: 1.5rem;
}
const accordionHeaders = document.querySelectorAll('.accordion-header');

accordionHeaders.forEach((accordionHeader) => {
	accordionHeader.addEventListener('click', () => {
		accordionContent = accordionHeader.nextElementSibling;
		const height = accordionContent.scrollHeight;

		accordionHeader.classList.toggle('active-header');

		if (accordionHeader.classList.contains('active-header')) {
			accordionContent.style.maxHeight = `${height}px`;
		} else {
			accordionContent.style.maxHeight = '0px';
		}
	});
});
//This will reload the hidden page when the user rotates the device.

jQuery(window).on("orientationchange",function(){
  
    if(screen.availHeight < screen.availWidth){
        //alert("chng");
          jQuery( ".h-main-body" ).css( "display", "none" );
          var newLine = "\r\n"
          var msg = "Please Don't use Landscape!"
          msg += newLine;
          msg += "(Turn your phone)";
          msg += newLine;
          msg += "and wait a seconds,";   
          // msg += newLine;
          // msg += "for the page to reload.";   
          alert(msg);
      }
      else{
        jQuery( ".h-main-body" ).css( "display", "block" );
         //location.reload();
      }
 
});
form.find('[next-step-button]').on('click', function (e) {
  if (currentStep < nextStep && form.valid()) {
    gotoStep(nextStep)
  } else if (nextStep < currentStep ) {
    gotoStep(nextStep)
  }
})
Tag Name	Code	             		Definition

Bold	<b>	       		When surrounding text, makes that text bold.

Emphasis	<em>		When surrounding text, makes that text italic.

Hyperlink	<a>			Creates hyperlinks.

Image	<img>			Denotes images.

Break	<br>			A single line break.

Paragraph	<p>			Creates a paragraph in text.

Section	<span>			Makes a section in text.

Division	<div>		Defines an area of the page.

Form	    <form>			Creates a form for user input.

Unordered List	<ul>	Creates an unordered list.

Ordered List	<ol>	Creates an ordered list.

List element	<li>	Denotes an element of the list. This tag is used for both ordered and unordered lists.

Table	<table>	Creates a table on the page.

Heading Level One	<h1>	Creates a heading in the text.
<!DOCTYPE html>
<html>
   <head>
      <title>My Web Page</title>
      content
   </head>
   <body>
      content
   </body>
</html>
cd
$ cd Desktop/
cd takes a directory name as an argument, and switches into that directory.

cd ..
$ cd ..
$ cd ../..
To move up one directory, use cd ... Here, cd .. navigates up from jan/memory/ to jan/.

ls
$ ls
2014  2015  hardware.txt
ls lists all files and directories in the working directory

mkdir
$ mkdir media
mkdir takes in a directory name as an argument, and then creates a new directory in the current working directory. Here we used mkdir to create a new directory named media/.

pwd
$ pwd
/home/ccuser/workspace/blog
pwd prints the name of the working directory

rm
$ rm waterboy.txt
rm deletes files. Here we remove the file waterboy.txt from the file system.
function getMeta(url, callback) {
    var img = new Image();
    img.src = url;
    img.onload = function() { callback(this.width, this.height); }
}
getMeta(
  "http://snook.ca/files/mootools_83_snookca.png",
  function(width, height) { alert(width + 'px ' + height + 'px') }
);
document.addEventListener("DOMContentLoaded", function()
        {
            $("img").each(function()
            {
                $(this).attr("data-src",$(this).attr("src"));
                $(this).attr("src",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=');
            });
            var $lazy_elements = $('img');
            var $window = $(window);
            function check_if_in_view()
            {
                var window_height = $window.height();
                var window_top_position = $window.scrollTop();
                var window_bottom_position = (window_top_position + window_height);
                $.each($lazy_elements, function()
                {
                    var $lazy_element = $(this);
                    var lazy_element_height = $lazy_element.outerHeight();
                    var lazy_element_top_position = $lazy_element.offset().top;
                    var lazy_element_bottom_position = (lazy_element_top_position + lazy_element_height);
                    //check to see if this current container is within viewport
                    if ((lazy_element_bottom_position >= window_top_position) && (lazy_element_top_position <= window_bottom_position))
                    {
                        if($lazy_element.attr('data-src'))
                        {
                            $lazy_element.attr("src",$lazy_element.attr('data-src'));
                        }
                    }
                });
            }
            $window.on('scroll resize', check_if_in_view);
            $window.trigger('scroll');
});
class School {
  constructor(name,level,numberOfStudents) {
    this._name = name;
    this._level = level;
    this._numberOfStudents = numberOfStudents ;
  }
  
  get name() {
    return this._name;
  }
  
  get level() {
    return this._level;
  }
  get numberOfStudents() {
    return this._numberOfStudents;
  }
  set numberOfStudents(value){
    if(value.isNaN()){
      console.log('Invalid input: numberOfStudents must be set to a Number.')
    }
    else{
      this._numberOfStudents = value;
    }
  }
  quickFacts(){
    console.log(`${this.name} educates ${this.numberOfStudents} students at the ${this.level} school level.`)
  }
static
pickSubstituteTeacher(substituteTeachers){
  const randInt = Math.floor(Math.random()*
  substituteTeachers.length);
  return substituteTeachers[randInt];
}

};


class PrimarySchool extends School {
 constructor(name,numberOfStudents,pickupPolicy) {
   super(name, 'primary',numberOfStudents);
   this._pickupPolicy = pickupPolicy;
  
 }
 get pickupPolicy() {
    return this._pickupPolicy;
  }
  
}

class HighSchool extends School {
 constructor(name,numberOfStudents,sportsTeams) {
   super(name, 'High',numberOfStudents);
   this._sportsTeams = sportsTeams;
  
 }
 get sportsTeams() {
    return this._sportsTeams;
  }
  
}


const lorraineHansbury = new PrimarySchool('Lorraine Hansbury',514,'Students must be picked up by a parent, guardian, or a family member over the age of 13.');

lorraineHansbury.quickFacts();

const sub = 
School.pickSubstituteTeacher(['Jamal Crawford', 'Lou Williams', 'J. R. Smith', 'James Harden', 'Jason Terry', 'Manu Ginobli']);
console.log(sub);


const alSmith = new HighSchool('Al E. Smith',415,['Baseball', 'Basketball', 'Volleyball', 'Track and Field']);

console.log(alSmith.sportsTeams);

class Media {
  constructor(title) {
    this._title = title;
    this._isCheckedOut = false;
    this._ratings = [] ;
  }
  
  get title() {
    return this._title;
  }
  
  get isCheckedOut() {
    return this._isCheckedOut;
  }
  get ratings() {
    return this._ratings;
  }
  set isCheckedOut(value){
    this._isCheckedOut = value;
  }
  toggleCheckOutStatus(){
    this.isCheckedOut = !this.isCheckedOut;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
  getAverageRating(){
let ratingsSum = 
this.ratings.reduce((accumulator,rating) =>
accumulator + rating);
return ratingsSum/ this.ratings.length;
  }
  addRating(value){
    this.ratings.push(value);
  }
}

class Book extends Media {
 constructor(author,title,pages) {
   super(title);
   this._author = author;
   this._pages = pages;
 }
 get author() {
    return this._author;
  }
  get pages() {
    return this._pages;
  }
}
class Movie extends Media {
 constructor(director,title,runTime) {
   super(title);
   this._director = director;
   this._runTime = runTime;
 }
 get director() {
    return this._director;
  }
  get runTime() {
    return this._runTime;
  }
}

const historyOfEverything = new Book('Bill Bryson','A Short History of Nearly Everything',544);
historyOfEverything.toggleCheckOutStatus();
console.log(historyOfEverything.isCheckedOut);
historyOfEverything.addRating(4);
historyOfEverything.addRating(5);
historyOfEverything.addRating(5);


console.log(historyOfEverything.getAverageRating());

const speed = new Movie('Jan de Bont','Speed',116)
speed.toggleCheckOutStatus();
console.log(speed.isCheckedOut);
speed.addRating(1);
speed.addRating(1);
speed.addRating(5);
 console.log(speed.getAverageRating());
https://github.com/timstuyckens/chromeextensions-knockoutjs
class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  static generatePassword() {
    const randomNumber = Math.floor(Math.random()*5);
    return randomNumber;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
  constructor(name, certifications) {
    super(name);
    this._certifications = certifications;
  } 
  
  get certifications() {
    return this._certifications;
  }
  
  addCertification(newCertification) {
    this.certifications.push(newCertification);
  }
}

const nurseOlynyk = new Nurse('Olynyk', ['Trauma','Pediatrics']);
nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays);
nurseOlynyk.addCertification('Genetics');
console.log(nurseOlynyk.certifications);
class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
  constructor(name, certifications) {
    super(name);
    this._certifications = certifications;
  } 
  
  get certifications() {
    return this._certifications;
  }
  
  addCertification(newCertification) {
    this._certifications.push(newCertification);
  }
}

const nurseOlynyk = new Nurse('Olynyk', ['Trauma','Pediatrics']);
nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays);
nurseOlynyk.addCertification('Genetics');
console.log(nurseOlynyk.certifications);
class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
 constructor(name, certifications) {
   super(name);
   this._certifications = certifications;
 } 
}

const nurseOlynyk = new Nurse('Olynyk', ['Trauma','Pediatrics']);
nurseOlynyk.takeVacationDays(5);
console.log(nurseOlynyk.remainingVacationDays)
function XO(str) {
  nbx = 0;
  nbo = 0;
  let array = str.split('');
  for(i = 0; i < array.length; i++) {
    if (array[i] == 'x' | array[i] == 'X') { nbx++; }
    if (array[i] == 'o' | array[i] == 'O') { nbo++; }
  }
  if (nbo == nbx && nbx == 0) { return true; }
  else if (nbo == nbx && nbx != 0) { return true; }
  else { return false; }
}
function solution(str){
  return str.split('').reverse().join('');  
}
 if(window.matchMedia("(max-width: 620px)").matches){

	//Code Here
       
    } else{

	// Code Here
      
    }
class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

class Nurse extends HospitalEmployee {
  constructor(name,certifications) {
    super(name);
    //super(remainingVacationDays);
    this._certifications = certifications;
  }
}
const nurseOlynyk = new Nurse('Olynyk', ['Trauma', 'Pediatrics']); 
console.log(nurseOlynyk._certifications);
class HospitalEmployee {
  constructor(name) {
    this._name = name;
    this._remainingVacationDays = 20;
  }
 
  get name() {
    return this._name;
  }
 
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }   
 
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
} 
class Surgeon {
  constructor(name, department) {
    this._name = name;
    this._department = department;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
  
  get department() {
    return this._department;
  }
  
  get remainingVacationDays() {
    return this._remainingVacationDays;
  }
  
  takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }
}

const surgeonRomero = new Surgeon('Francisco Romero', 'Cardiovascular');
const surgeonJackson = new Surgeon('Ruth Jackson', 'Orthopedics');
console.log(surgeonRomero.name);

surgeonRomero.takeVacationDays(3);
console.log(surgeonRomero.remainingVacationDays)
class Surgeon {
  constructor(name, department) {
    this._name = name;
    this._department = department;
    this._remainingVacationDays = 20;
  }
    get name() {
    return this._name;
  }
    get department() {
    return this._department;
  }
    get remainingVacationDays() {
    return this._remainingVacationDays;
  }
   takeVacationDays(daysOff) {
    this._remainingVacationDays -= daysOff;
  }



}


const surgeonRomero = new Surgeon('Francisco Romero', 'Cardiovascular');
const surgeonJackson = new Surgeon('Ruth Jackson', 'Orthopedics');
class Surgeon {
  constructor(name, department) {
    this.name = name;
    this.department = department;
  }
}

const surgeonRomero = new Surgeon('Francisco Romero','Cardiovascular'); // Create new surgeon instance
console.log(surgeonRomero.name); 

const surgeonJackson = new Surgeon('Ruth Jackson','Orthopedics'); // Create new surgeon instance
console.log(surgeonJackson.name); 
document.addEventListener("DOMContentLoaded", function()
        {
            $("img").each(function()
            {
                $(this).attr("data-src",$(this).attr("src"));
                $(this).attr("src",'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=');
            });
            var $lazy_elements = $('img');
            var $window = $(window);
            function check_if_in_view()
            {
                var window_height = $window.height();
                var window_top_position = $window.scrollTop();
                var window_bottom_position = (window_top_position + window_height);
                $.each($lazy_elements, function()
                {
                    var $lazy_element = $(this);
                    var lazy_element_height = $lazy_element.outerHeight();
                    var lazy_element_top_position = $lazy_element.offset().top;
                    var lazy_element_bottom_position = (lazy_element_top_position + lazy_element_height);
                    //check to see if this current container is within viewport
                    if ((lazy_element_bottom_position >= window_top_position) && (lazy_element_top_position <= window_bottom_position))
                    {
                        if($lazy_element.attr('data-src'))
                        {
                            $lazy_element.attr("src",$lazy_element.attr('data-src'));
                        }
                    }
                });
            }
            $window.on('scroll resize', check_if_in_view);
            $window.trigger('scroll');
});
jQuery(window).scroll(function() {
   var hT = jQuery('div#shopify-section-template--16081634984157__165209878371807727').offset().top,
       hH = jQuery('div#shopify-section-template--16081634984157__165209878371807727').outerHeight(),
       wH = jQuery(window).height(),
       wS = jQuery(this).scrollTop();
   if (wS > (hT+hH-wH)){
       console.log('H1 on the view!');
   }
});
<!DOCTYPE HTML>
<html>
<head>
<style>
#div1 {
  width: 350px;
  height: 70px;
  padding: 10px;
  border: 1px solid #aaaaaa;
}
</style>
<script>
function allowDrop(ev) {
  ev.preventDefault();
}

function drag(ev) {
  ev.dataTransfer.setData("text", ev.target.id);
}

function drop(ev) {
  ev.preventDefault();
  var data = ev.dataTransfer.getData("text");
  ev.target.appendChild(document.getElementById(data));
}
</script>
</head>
<body>

<p>Drag the W3Schools image into the rectangle:</p>

<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69">

</body>
</html>
// for young people
const youngPeople = users.filter((person) => {
  return person.age <= 15;
});

//for senior people
const seniorPeople = users.filter((person) => person.age >= 50);

console.log(seniorPeople);
console.log(youngPeople); 
let singleUser = users.map((user)=>{
  //let's add the firstname and lastname together
  let fullName = user.firstName + ' ' + user.lastName;
  return `
    <h3 class='name'>${fullName}</h3>
    <p class="age">${user.age}</p>
  `
});
function addName (time, name){
  return new Promise ((resolve, reject) => {
    if(name){
      setTimeout(()=>{
        console.log(name)
        resolve();
      },time)
    }else{
      reject('No such name');
    }
  })
}

addName(2000, 'Joel')
  .then(()=>addName(2000, 'Victoria'))
  .then(()=>addName(2000, 'John'))
  .then(()=>addName(2000, 'Doe'))
  .then(()=>addName(2000, 'Sarah'))
  .catch((err)=>console.log(err))
const promise = new Promise((resolve, reject) => {  
    let condition;
    
    if(condition is met) {    
        resolve('Promise is resolved successfully.');  
    } else {    
        reject('Promise is rejected');  
    }
});
<!DOCTYPE html>
<html>
<body>

<p>Click the button to get your coordinates.</p>

<button onclick="getLocation()">Try It</button>

<p id="demo"></p>

<script>
var x = document.getElementById("demo");

function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition, showError);
  } else { 
    x.innerHTML = "Geolocation is not supported by this browser.";
  }
}

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}

function showError(error) {
  switch(error.code) {
    case error.PERMISSION_DENIED:
      x.innerHTML = "User denied the request for Geolocation."
      break;
    case error.POSITION_UNAVAILABLE:
      x.innerHTML = "Location information is unavailable."
      break;
    case error.TIMEOUT:
      x.innerHTML = "The request to get user location timed out."
      break;
    case error.UNKNOWN_ERROR:
      x.innerHTML = "An unknown error occurred."
      break;
  }
}
</script>

</body>
</html>
// A Modal with input in it, that receives focus when it is mounted and displayed on screen

// child component
import {useEffect} from "react"

export const Modal =({forwardedRef}) =>{
  useEffect(()=> {
    // adding the focus() to the ref when component is mounting
    forwardedRef.current?.focus()
  },[forwardedRef])

  return(
    <div>
      <label htmlFor="email">Add your email:</label>
      <input type="email" name="email" id="email" ref={forwardedRef}/>
    </div>
  )
}

// parent component
import {useRef, useState} from "react"
import {Modal} from "./Modal"

export default function App() {
  const [isModalOpened, setIsModalOpened] = useState(false)
  const inputRef = useRef()

  function handleModal(){
    setIsModalOpened(!isModalOpened)
  }
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <h2>Start editing to see some magic happen!</h2>
      <button type="button" onClick={handleModal}>
  		{isModalOpened === true ? "Close modal" : "Open modal"}
	</button>

      {isModalOpened && <Modal forwardedRef={inputRef}/>}
    </div>
  );
}

// Parent component will receive as props the values or functions set for the ref on the child component
// child component
import {forwardRef} from "react"

export const Button = forwardRef(({...props}, ref) => {
return <button ref={ref} id="buttonId-js" {...props}>Button</button>
})

// parent component
import {useRef} from "react"
import { Button } from "./Button";

export default function App() {
const buttonRef = useRef()
return (
<div className="App">
    <h1>Hello CodeSandbox</h1>
    <h2>Start editing to see some magic happen!</h2>
    <Button ref={buttonRef} onClick={()=> console.log(buttonRef.current.id)}
        />
</div>
);
}

// buttonRef.current gives access nodes and DOM, allowing to change the component
// useRef should be used in uncontrolled components - those ones that are not handled by React states or handle functions
<!DOCTYPE html> 
<html> 
<body> 

<div style="text-align:center"> 
  <button onclick="playPause()">Play/Pause</button> 
  <button onclick="makeBig()">Big</button>
  <button onclick="makeSmall()">Small</button>
  <button onclick="makeNormal()">Normal</button>
  <br><br>
  <video id="video1" width="420">
    <source src="mov_bbb.mp4" type="video/mp4">
    <source src="mov_bbb.ogg" type="video/ogg">
    Your browser does not support HTML video.
  </video>
</div> 

<script> 
var myVideo = document.getElementById("video1"); 

function playPause() { 
  if (myVideo.paused) 
    myVideo.play(); 
  else 
    myVideo.pause(); 
} 

function makeBig() { 
    myVideo.width = 560; 
} 

function makeSmall() { 
    myVideo.width = 320; 
} 

function makeNormal() { 
    myVideo.width = 420; 
} 
</script> 

<p>Video courtesy of <a href="https://www.bigbuckbunny.org/" target="_blank">Big Buck Bunny</a>.</p>

</body> 
</html>
'01/Jan/'||substr(:oarsdate,8,2)
// encode to scape spaces
const esc = encodeURIComponent;
const url = 'https://maps.googleapis.com/maps/api/geocode/json?';
const params = { 
    key: "asdkfñlaskdGE",
    address: "evergreen avenue",
    city: "New York"
};
// this line takes the params object and builds the query string
const query = Object.keys(params).map(k => `${esc(k)}=${esc(params[k])}`).join('&')
const res = await fetch(url+query);
const googleResponse = await res.json()
function my_acf_repeater($atts, $content='') { 

extract(shortcode_atts(array( "field" => null,

"sub_fields" => null,

"post_id" => null

), $atts));

if (empty($field) || empty($sub_fields)) {

// silently fail? is that the best option? idk

return "";

}

$sub_fields = explode(",", $sub_fields);

​

$_finalContent = '';

if( have_rows($field, $post_id) ):

while ( have_rows($field, $post_id) ) : the_row();

 $_tmp = $content;

foreach ($sub_fields as $sub) {

$subValue = get_sub_field(trim($sub));

$_tmp = str_replace("%$sub%", $subValue, $_tmp);

}

 $_finalContent .= do_shortcode( $_tmp );

endwhile;

else :  

$_finalContent = "$field does not have any rows";

endif;

return $_finalContent;

}

add_shortcode("acf_repeater", "my_acf_repeater");
function countBy(x, n) {
  let z = [];
  for(i = 1; i <= n; i++) {
    z.push(x * i);
  }
  return z;
}
FOR LOOPS
for (inital expression; condition; increment) {
statements
}
use (i)for index
for (let i = 10; i >= 1; i--) {
    if (i % 2 !== 2) console.log(i)
}
 

FOR IN LOOPS
const device = {
    brand: 'Acer',
    model: 'TMP12-322',
    specs: {
        ram: 8,
        rom: 256
    }
}
for (key in device.specs) {
    console.log(key, device.specs[key])
}

// LOOP CONTROL
for (let i = 1; i <= 10; i++) {
    if (i == 5)
        // the counting will stop less than 5
        break;
    console.log(i)
}
<html>
<title>Tic Tac Toe</title>
<head>
  <link rel="stylesheet" type="text/css" href="css/style.css" />
  <script type="text/javascript" src="js/app.js"></script>
</head>
<body onload="startGame();">
  <h1>Tic Tac Toe</h1>
  <h2>By Irsyad</h2>
  <div id ="message"><h3> messages will go here<h3></div>
  <div>
    <a href="javascript:startGame();">Restart</a>
  </div>
  <table>
    <tr>
      <td id="s1" class="square" onclick="nextMove(this);"></td>
      <td id="s2" class="square" onclick="nextMove(this);"></td>
      <td id="s3" class="square" onclick="nextMove(this);"></td>
    </tr>
    <tr>
      <td id="s4" class="square" onclick="nextMove(this);"></td>
      <td id="s5" class="square" onclick="nextMove(this);"></td>
      <td id="s6" class="square" onclick="nextMove(this);"></td>
    </tr>
    <tr>
      <td id="s7" class="square" onclick="nextMove(this);"></td>
      <td id="s8" class="square" onclick="nextMove(this);"></td>
      <td id="s9" class="square" onclick="nextMove(this);"></td>
    </tr>
  </table>
</body>
</html>
<!DOCTYPE html>
<html>
<body>

<h2>Use of The class Attribute in JavaScript</h2>
<p>Click the button to hide all elements with class name "city":</p>
<button onclick="myFunction()">Hide elements</button>

<p>Click the button to show all elements with class name "city":</p>
<button onclick="myFunction2()">Show elements</button>

<h2 class="city">London</h2>
<p>London is the capital of England.</p>

<h2 class="city">Paris</h2>
<p>Paris is the capital of France.</p>

<h2 class="city">Tokyo</h2>
<p>Tokyo is the capit