How to add external js bundle in angular module

I have hello.js file with a function HelloWorld()

Angular app has lazy loaded modules module1, module2, .. moduleN

in Angular.json

 "scripts": [
              {
                "input": "src/alljs/hello.js",
                "inject": false,
                "bundleName": "lazyhello"
              },

This generates a bundle lazyhello.js in the root dir

I want to call function helloWorld() in module2 and module 3. So in module2.module.ts and module3.module2.ts I import it as –

import “../lazyhello.js”

However, it does not work. How can I import bundle lazyhello.js into the other lazy loaded angular modules?

How to use a node file to execute command to run docker container

I’m still learning how to implement docker containers into my app and I just set up a mongo container to replace MongoDB atlas and have that working with my app so far. I created a script in my package.json, "build:container": "node -e 'require("./docker-build").runContainer()'" that I want to run the container I have setup. so I also have a docker-build.js file setup but I’m not sure if what I’m trying to do is the correct way of doing this (or correct). I don’t have a docker file setup, I just ran the docker run command in my terminal

Javascript dynamic nested arrays

Tonight is not my night and it may be time to step away from the computer. I cannot for the life of me remember how to do this. I am trying to dynamically create an empty nested array based on the the length of a word. For example if the length was 7 I would want the array to look like this

Rows = [
    ['', '', '', '', '', '', ''],
    ['', '', '', '', '', '', ''],
    ['', '', '', '', '', '', ''],
    ['', '', '', '', '', '', ''],
    ['', '', '', '', '', '', ''],
    ['', '', '', '', '', '', '']
]

and if the length was 3 I would want my array to be dynamically created like this

Rows = [
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', ''],
    ['', '', '']
]

Javascript mouseover alert on div not working

Trying to get an alert to appear on mouseover, using Javascript, for a div element. I can get the div element to print in the console, but nothing else happens.

The div has some text in it, I tried changing it to activate on the text instead of the div but I still couldn’t get it to work.

   window.onload = pageReady;
    function pageReady(){
            
        var buttonBox = document.getElementById("buttonBox");
        console.log(buttonBox);
        
        function askUser(){
            alert("It worked!");}
    
        buttonBox.onmouseover = askUser;
    }

Stripe webhook best practice

After we receive the webhook, we should return 2xx response, prior of doing some additional logic in our backend.

Your endpoint must quickly return a successful status code (2xx) prior
to any complex logic that could cause a timeout. For example, you must
return a 200 response before updating a customer’s invoice as paid in
your accounting system.

They suggest here to first return successful 2xx response, and then to do additional things in our backend. They consider this as best practice so there won’t be a request timeout.

I don’t see how is this best practice, since there is an obvious possibility were our system fails in updating the database for example, and we already returned successful response. That means that Stripe will not try to re-send the webhook later, and we will lose this information since our system didn’t save it.

Are there an existing solution for this sort of problem?

How do I get the variable answerNew to loop back to the prompt screen while adding answerNew to my array in ‘myTodo’?

Basic JavaScript has proven to be tougher than teaching myself Algebra last year. With that said, my head is pounding from trying to solve the next step in my “To Do List” JavaScript prompt project.

Here is my code…

prompt(“What would you like to do: (New, List, Delete, Quit)”)
//Prompt starts our whole ‘to-do’ list function//

const New = prompt(“What would you like to add to your list?”)

//You HAVE to use ‘const’ variable in order to allow ‘New’ to produce input from the prompt().//
if (answerNew ===

let answerNew =
let myTodo = [‘Cook’, ‘Study’, ‘Work’];

… I’m trying to get the variable answerNew to loop back to the prompt screen while adding answerNew to my ‘myTodo’ array. I want the variable answerNew to be open and not defined though. Does this make sense to anybody?

get difference with previous date

I have the following JSON , how do i get difference between the previous date for num_followers for each website ?

like for website yqq on 15-02-2022 I need to get the difference between the num_followers from 14-02-2022 and update num_followers with difference value

[
    {
        "date": "2022-02-15",
        "websites": [
            {
                "website_name": "yqq",
                "num_followers": "454421"
            },
            {
                "website_name": "soundcloud",
                "num_followers": "757127"
            },
            {
                "website_name": "twitter",
                "num_followers": "21779161"
            },
            {
                "website_name": "soundcloud",
                "num_followers": "757054"
            },
            {
                "website_name": "triller",
                "num_followers": "5196"
            },
        ]
    },
    {
        "date": "2022-02-14",
        "websites": [
            {
                "website_name": "yqq",
                "num_followers": "123058219"
            },
            {
                "website_name": "triller",
                "num_followers": "5195"
            },
            {
                "website_name": "tiktok",
                "num_followers": "17100000"
            },
            {
                "website_name": "instagram",
                "num_followers": "123059626"
            },
            {
                "website_name": "tiktok",
                "num_followers": "17100000"
            },
            {
                "website_name": "tiktok",
                "num_followers": "17100000"
            },
            {
                "website_name": "soundcloud",
                "num_followers": "756956"
            },
        ]
    
    }
]

Relative import of CJS module from an eval’ed Worker in Node?

I am creating a worker from a source string like so:

import { Worker } from "worker_threads"

const w = new Worker(mySourceCode, {eval: true})

This works fine in most cases.

However, suppose I have a CommonJS module (ESM isn’t supported in eval’ed workers) that I want to import into the worker scope. Since the worker doesn’t have a source file on the disk, there is no way I can think of to make a relative import work. This is the error message I get if I try to relative import from the path of the source file of the parent thread:

node:internal/event_target:916
  process.nextTick(() => { throw err; });
                           ^
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module './c.js'
Require stack:
- /mnt/c/ME/[worker eval]
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at [worker eval]:3:20
    at Script.runInThisContext (node:vm:129:12)
    at Object.runInThisContext (node:vm:305:38)
    at node:internal/process/execution:76:19
    at [worker eval]-wrapper:6:22
    at evalScript (node:internal/process/execution:75:60)
Emitted 'error' event on Worker instance at:
    at Worker.[kOnErrorMessage] (node:internal/worker:289:10)
    at Worker.[kOnMessage] (node:internal/worker:300:37)
    at MessagePort.<anonymous> (node:internal/worker:201:57)
    at MessagePort.[nodejs.internal.kHybridDispatch] (node:internal/event_target:647:20)
    at MessagePort.exports.emitMessage (node:internal/per_context/messageport:23:28) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/mnt/c/Users/ME/[worker eval]' ]
}

Node.js v17.5.0

How can I relative import a module from a Worker?

Como gerar um erro no readFile do modulo fs? How to generate a error on readFile fs module?

Ola! Como eu conseguiria gerar um erro de leitura do arquivo, pra poder testar minha condicao de erro da linha 8?

Hi! How would I be able to generate an error reading the file, so I can test my error condition on line 8?

1  const fs = require('fs/promises');
2  
3  const TALKERS_FILE = './talker.json';
4  
5  module.exports = async (_req, res) => {
6   try {
7     const talkersFile = await fs.readFile(TALKERS_FILE, 'utf-8', (err, data) => {
8       if (err) return new Error('Ops! I cant read required file... sorry =(');
9       return (data);
10    });
11    return res.status(200).json(JSON.parse(talkersFile));
12  } catch (err) {
13    console.log(err);
14  }
15 };

talker.json =

 [   
     {
        "name": "Henrique Albuquerque",
        "age": 62,
        "id": 1,
        "talk": {
          "watchedAt": "23/10/2020",
          "rate": 5
        }
     }
  ]

Why is the findIndex method showing second occurance too?

Basically the idea is that my code chooses a random element from an array. That element is the arr[i].answer and is placed at the end of that array. Then i want to make the first occurrence of that answer as an *. I used the findIndex method as i thought that the first occurrence of my answer will become the * however both first occurrence and the last element have become an asterix.

Here is the code

arr.forEach(element => {
              arr[i].answer = arr[i].sequence[rndElement];
              arr[i].sequence[arr[i].sequence.length - 1] = arr[i].answer;

              function isFirst(element, index, array) {
                return element === arr[i].answer;
                }

                let index = arr[i].sequence.findIndex(isFirst);
                arr[i].sequence[index] = "*";

              
          });

Above is the necessary code, below is all the code for reference

const arr = [];
    const input = document.getElementById('answer').value;
    const rndElement = Math.floor(Math.random() * 6);


    function displaySeq() {
        var i = 0;
        while (arr.length < 21) {
            const rndInt = Math.floor(Math.random() * 50);
            const iterator = Math.floor(Math.random() * (8 - 3 + 1)) + 3;
          arr[i] = {
              sequence: [rndInt],
              answer: 7,
              guess: []
          };

          let j = iterator;
          while (arr[i].sequence.length < 7) {
              arr[i].sequence.push(rndInt + j);
              j+=iterator;
          }

        arr.forEach(element => {
              arr[i].answer = arr[i].sequence[rndElement];
              arr[i].sequence[arr[i].sequence.length - 1] = arr[i].answer;

              function isFirst(element, index, array) {
                return element === arr[i].answer;
                }

                let index = arr[i].sequence.findIndex(isFirst);
                arr[i].sequence[index] = "*";

              
          });
          i++;

       }  
        console.log(arr);
    }

Exit Intent in Mobile using java scrpt

I want to modify the popup plugin, where the popup doesn’t work on mobile devices.
And this is the code that calls the exit intent popup


  $(document).on('mouseleave', function (e) {

    if (e.clientY > 20) {
      return;
    }

    $('.fel-modal-parent-wrapper').each(function () {

      var $this = $(this);
      var tmp_id = $this.attr('id');
      var popup_id = tmp_id.replace('-overlay', '');
      var trigger_on = $this.data('trigger-on');
      var exit_intent = $this.data('exit-intent');

      if ('automatic' == trigger_on) {
        if (
          'yes' == exit_intent
          && FelModalPopup_canShow(popup_id)
        ) {
          FelModalPopup_show(popup_id);
        }
      }
    });
  });

Insert a Javascript Animation in a Vue app?

I want to put this raining pixels animation in my Vue app:
https://codepen.io/kme211/pen/pRzRpJ

I tried just copying the HTML, CSS and JS in their respective tags, thus template, style and script.
However, when I insert the JS in my IDE and refresh the page it turns blank.

How can I insert this animation in my Vue app? I need it as a background for my homepage.

<template>
<div class="bloks"></div>

<section>
  <p>
  Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi porta aliquet scelerisque. Donec accumsan magna vel felis volutpat dapibus. In eleifend molestie ipsum vitae fringilla. Fusce at euismod velit. Pellentesque ut lacus sed justo faucibus euismod vel id dui. Nulla ac dictum turpis. Fusce congue enim vel egestas sollicitudin. Etiam nec mi ultricies orci tincidunt pretium eu non urna.
  </p>
</section>

<section>
  <p>
  Sed eget ligula congue, dignissim nibh rutrum, congue nisl. Curabitur vehicula malesuada nulla a fringilla. Nullam nisl felis, mollis ac pellentesque et, tempus at dolor. Etiam quis purus at neque faucibus elementum sed nec sem. Integer dapibus dolor sed egestas vehicula. Mauris fringilla eleifend iaculis. Suspendisse gravida urna ac interdum fringilla. Maecenas sagittis mollis imperdiet. Aenean venenatis metus tortor, ac consequat urna faucibus eget. Pellentesque at mi malesuada, ornare eros vel, iaculis libero. Cras lacinia, nisl in volutpat volutpat, magna magna sagittis urna, ut posuere ante ligula ac lorem. Praesent iaculis ipsum et dui fermentum, non eleifend neque faucibus. Vestibulum quis urna eget eros maximus gravida.
  </p>
</section>

<section>
  <p>
  Ut commodo arcu eu leo consectetur faucibus. Donec egestas ligula id commodo vehicula. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Nam mauris nulla, gravida id ex id, egestas eleifend sem. Phasellus sit amet scelerisque nunc. Aenean laoreet iaculis malesuada. Cras et volutpat augue, eget convallis turpis. Donec accumsan lobortis dapibus. Proin scelerisque, nulla id fringilla laoreet, felis justo sollicitudin odio, eget efficitur sem metus in libero.
  </p>
</section>
</template>
<style>
:root {
  --blokColor: #495664;
}

html {
  box-sizing: border-box;
  background: #333C4A;
  font-family: Helvetica, Arial, sans-serif;
  font-size: 18px;
  color: white;
  height: 100%;
  width: 100%;
}

*, *:before, *:after {
  box-sizing: inherit;
}

section {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

p {
  padding: 2em;
  max-width: 600px;
  background: rgba(0, 0, 0, 0.4)
}

.bloks {
  width: 100%;
  height: 100%;
  z-index: -5;
  position: fixed;
  overflow: hidden;
}

.blok {
  height: 25px;
  width: 25px;
  background: #495664; // Fallback for browsers w/o CSS variable support
  background: var(--blokColor);
  position: absolute;
  transition: background 1.5s;
}

@keyframes blok {
  100% { top: 100vh; opacity: 0;  }
}
</style>
<script>
const numberOfBloks = 9,
      w = window,
      d = document,
      e = d.documentElement,
      g = d.getElementsByTagName('body')[0],
      x = w.innerWidth || e.clientWidth || g.clientWidth,
      y = w.innerHeight|| e.clientHeight|| g.clientHeight,
      bloksContainer = d.querySelector('.bloks'),
      blokColors = ['#495664', '#379956', '#F70C9B'], // Color for each section
      sections = Array.from(document.querySelectorAll('section'));

function injectCssAndMarkup() {
  const head = d.head || d.getElementsByTagName('head')[0],
        style = d.createElement('style'),
        leftValues = getLeftValues(numberOfBloks, x),
        topValues = getRandomValues(numberOfBloks, 200),
        delayValues = getRandomValues(numberOfBloks, 15);
  
  style.type = 'text/css';
  const css = getBlokCSS(numberOfBloks, y, leftValues, topValues, delayValues);
  if (style.styleSheet){
    style.styleSheet.cssText = css;
  } else {
    style.appendChild(document.createTextNode(css));
  }
  head.appendChild(style);
  bloksContainer.innerHTML = getBlokMarkup(numberOfBloks);
}

function getBlokMarkup(blokNum) {
  let bloks = [];
  for(let i = 0; i < numberOfBloks; i++) {
    bloks.push(`<div class="blok blok${i+1}"></div>`);
  }
  return bloks.join('n');
}

function getRandomValues(blokNum, maxVal) {
  let values = [];
  for(let i = 0; i < blokNum; i++) {
    values.push(Math.floor((maxVal / blokNum) * (i)));
  }
  return values.sort(function() { return 0.5 - Math.random() });
}

function getLeftValues(blokNum, screenWidth) {
  let values = [];
  for(let i = 0; i < blokNum; i++) {
    values.push(Math.floor((screenWidth / blokNum) * (i + 0.5)));
  }
  return values;
}

function getBlokCSS(blokNum, screenHeight, left, top, delay) {
  let css = [];
  for(let i = 0; i < blokNum; i++) {
    let duration = (screenHeight - (-top[i]))/50;
    css.push(`
      .blok${i+1} {
        left: ${left[i]}px;
        top: -${top[i]}px;
        animation-delay: ${delay[i]}s;
        animation: blok ${duration}s infinite;
        animation-timing-function: linear;
      }
    `);
  }
  return css.join('n');
}

// https://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

var handleScroll = debounce(function() {
    console.log(`scrollTop: ${document.body.scrollTop}`)
  const scrollTop = document.body.scrollTop;
  sections.forEach((section, i) => {
    console.log(`section ${i} | offsetTop: ${section.offsetTop}`)
    if(scrollTop >= (section.offsetTop-100)) {
      document.documentElement.style.setProperty('--blokColor', blokColors[i]);
    }
  })
}, 250);


document.addEventListener('scroll', handleScroll);
injectCssAndMarkup();
</script>