Number is not incrementing by 1 in JavaScript

I have this code where if the opacity is less than or equal to 0, the message number is suppose to go up by 1, but when I run the code, the message number increases by 77 or 152 or 66, etc. Could you help me?
My code:

//variables
var x = 0;
var opacity = 0;
var messageNumber = 0;
var talk1 = ["hello", "welcome to idle ball", "potato"];
var lol = 1;


//set opacity to 1
function opacitySet1(speed) {
  document.getElementById("talk").style.opacity = opacity;
  opacity += speed;
}

//set opacity to 0
function opacitySet0(speed) {
  document.getElementById("talk").style.opacity = opacity;
  opacity -= speed;
}


function IntervalManager(flag, animate, time, para1) {
  if (flag) {
    var intervalSet = setTimeout(animate, time, para1)
  }
}


function IntervalManagerII(flag, animate, time, para1) {
  if (flag) {
    var intervalSetII = setTimeout(animate, time, para1)
  }
}

//to delay time
function nothing() {}


function message(startPart) {
  document.getElementById("talk").innerHTML = messageNumber;
  if (opacity >= 0 && lol == 0) {
    setTimeout(nothing, 1);
    IntervalManagerII(true, opacitySet0, 300, 0.005);
    IntervalManager(false)
  }
  if (opacity <= 1 && lol == 1) {
    IntervalManager(true, opacitySet1, 300, 0.005);
    IntervalManagerII(false)
  }
  if (opacity <= 0) {
    lol = 1;
    IntervalManagerII(false);
    messageNumber += 1;
  } //this is the part that is not working
  if (opacity >= 1) {
    lol = 0;
    IntervalManager(false);
  }
};

setInterval(function() {
  message(0)
});

Uncaught TypeError: window.initialize is not a function on older gmaps api

I’ve inherited a site and picking through some of the console errors i see… the “Uncaught TypeError: window.initialize is not a function” is coming from the google maps api, i am not knowledgeable in javascript so im not sure whats going on at all. Here’s the code that calls the map…

    <script> window.mapalldata=<?php echo json_encode($map_data)?>;</script>
<script type="application/javascript">
    iBox = [];

    jQuery(function ($) {
        var image = '<?php echo get_template_directory_uri(); ?>/assets/images/office-pin.png';
        var map = null;
        var markerArray = [];

        window.initialize = function () {
            var bounds = new google.maps.LatLngBounds();
            latitudes = [];
            longitudes = [];
            artBox = window.mapalldata;

            pindata = [];
            points = [];
            jQuery.each(artBox, function (key, val) {
                    if(latitudes.includes(val.lat) && longitudes.includes(val.lng)){
                        val.lat = val.lat + (Math.random() - 0.5) / 1500;// * (Math.random() * (max - min) + min);
                        val.lng = val.lng + (Math.random() - 0.5) / 1500;// * (Math.random() * (max - min) + min);
                    }
                    latitudes.push(val.lat)
                    longitudes.push(val.lng)
                    pindata.push({'title': val.title});
                    points.push(val);
                   

            })
            bounds.extend(new google.maps.LatLng(Math.max.apply(Math, latitudes) + 1, Math.max.apply(Math, longitudes)));
            bounds.extend(new google.maps.LatLng(Math.min.apply(Math, latitudes) - 1, Math.min.apply(Math, longitudes)));
             
            if (map == null) {
                var gmapdiv;
                gmapdiv = document.createElement('div');
                gmapdiv.id = 'level10_gmapid-canvas';
                gmapdiv.style.width = '100%';
                gmapdiv.style.height = '700px';
                document.getElementById('gmap_canvas').appendChild(gmapdiv);
                var mapOptions = {
                    zoom: 10,
                    scrollwheel: false,
                    mapTypeControl: true,
                    scaleControl: true,
                    zoomControlOptions: {style: google.maps.ZoomControlStyle.DEFAULT},
                    overviewMapControl: true,
                    center: bounds.getCenter(),
                    mapTypeId: google.maps.MapTypeId.ROADMAP
                };

                var map = new google.maps.Map(document.getElementById('level10_gmapid-canvas'), mapOptions);
            }
            if (markerArray) {
                jQuery.each(markerArray,function(key,value){
                    value.setMap(null);
                })
                markerArray = [];
            }
            var len = latitudes.length;

            jQuery.each(points, function (key, val) {
                var marker = new google.maps.Marker({
                    position: new google.maps.LatLng(parseFloat(val.lat)-0.0014, parseFloat(val.lng)),
                    map: map,
                    icon: image
                });

                markerArray.push(marker);
                window.attachMessege(map, marker, val);


            })
            var clusterStyles = [
              {
                textColor: 'white',
                url: '<?php echo get_stylesheet_directory_uri()?>/assets/images/ico-region-map.png',
                height: 85,
                width: 85
              }
            ];
            var mcOptions = {
            styles: clusterStyles,
            };
            var markerCluster = new MarkerClusterer(map, markerArray, mcOptions);

            if (len > 1) {
                map.fitBounds(bounds);
            } else {
                map.setCenter(markerArray[0].getPosition());
                map.setZoom(15);
            }
            jQuery(document).on("contentUpdate", function (e) {
                jQuery.each(iBox, function () {
                    this.hide();
                });
            });
             var ib;
            var currCenter = bounds.getCenter();
            google.maps.event.addDomListener(window, 'resize', function() {
                map.setCenter(currCenter);
            });
        }

        window.attachMessege = function (map, marker, data) {
           
            myHtml =
                '<div class="b-marker-map" >' +

                '<div class="b-box-marker">' +
                '<div class="holder">' +
                '<div class="block">' +
                '<a href="' + data.link + '" class="image">'+
                data.img +
                '</a>' +
                '<div class="info-content">' +
                '<h5>' + data.client + '</h5>'+
                '<p>' + data.title + '</p>' +
                '<p>' + data.geo + '</p>' +
                '<a href="' + data.link + '" class="link-arrow">View Project</a>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>' +
                '</div>';

            var boxText = document.createElement("div");
            boxText.innerHTML = myHtml;

            var myOptions = {
                content: boxText,
                disableAutoPan: false,
                maxWidth: 0,
                alignBottom: true,
                pixelOffset: new google.maps.Size(-65, -32),
                zIndex: null,
                closeBoxMargin: "0",
                closeBoxURL: "",
                infoBoxClearance: new google.maps.Size(1, 1),
                pane: "floatPane",
                enableEventPropagation: false,
            };

            var ib = new InfoBox(myOptions);
            iBox.push(ib);

            google.maps.event.addListener(map, "click", function (e) {
                var ib_length = iBox.length;
                for (i = 0; i < ib_length; i++) {
                    if (iBox[i].getPosition()) {
                        iBox[i].close();
                    }
                }
            });
            google.maps.event.addListener(marker, "click", function (e) {
                var ib_length = iBox.length, _pp = this.position;
                for (i = 0; i < ib_length; i++) {
                    // var curpoint = iBox[i].getPosition();
                    // if (_pp.k != curpoint.k && _pp.D != curpoint.D) {
                        iBox[i].close();
                    // }
                }
                //map.panTo(this.getPosition());
                ib.open(map, marker);
               

                
            });
            // google.maps.event.addListener(marker, "mouseout", function (e) {
            //      mouseOutsideInfowindow();
            // });



            var styles = [{"featureType":"administrative","elementType":"labels.text","stylers":[{"saturation":"-17"},{"lightness":"21"},{"gamma":"1.16"},{"weight":"2.35"}]},{"featureType":"administrative","elementType":"labels.text.fill","stylers":[{"color":"#444444"}]},{"featureType":"administrative.country","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"administrative.province","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"administrative.locality","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"administrative.neighborhood","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"landscape","elementType":"all","stylers":[{"gamma":"1"},{"lightness":"100"},{"color":"#ffffff"}]},{"featureType":"landscape.natural","elementType":"all","stylers":[{"visibility":"on"}]},{"featureType":"poi","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"all","stylers":[{"saturation":-100},{"lightness":45}]},{"featureType":"road.highway","elementType":"all","stylers":[{"visibility":"simplified"}]},{"featureType":"road.arterial","elementType":"labels.icon","stylers":[{"visibility":"off"}]},{"featureType":"transit","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#f2f2f2"},{"visibility":"on"}]}];
            var styledMap = new google.maps.StyledMapType(styles,{name: "Styled Map"});
            map.mapTypes.set('map_style', styledMap);
            map.setMapTypeId('map_style');
        }

    });

function  mouseOutsideInfowindow(){
    var ib_length = iBox.length, _pp = this.position;
    for (i = 0; i < ib_length; i++) {
        iBox[i].close();
    }
}
jQuery('.buttons a.map').on('click', function (e) {
    if( jQuery('#gmap_canvas').is(':empty') ) {    
        // jQuery('#gmap_canvas').empty();
        window.initialize();
    }
});
</script>

theres also all this code being displayed below the area that i imagine is bc of the javascript error, heres an image of it…
screenshot of code being displayed on front end

Any help would be great the client would like to not completely remove the map, as its used to search for projects, my guess based on other errors i’ve found is that its dated javascript, but like i said i dont know javascript so im not sure… heres the page https://www.level10gc.com/projects/

Thank you.

Issue while sending automatic WhatsApp message template using 360Dialog provider

I wrote a Node.js code to automatically send a WhatsApp template message(360Dialog) when it receives a incoming message. But as soon as It captures the incoming message through Webhook it continuously start sending the template message instead of just sending once.

index.js

const express = require('express');
const bodyParser = require('body-parser');
require('dotenv').config();

const webApp = express();

webApp.use(bodyParser.urlencoded({
    extended: true
}));
webApp.use(bodyParser.json());
const PORT = 3000;

webApp.get('/whatsapp', (req, res) => {
    res.send(`Hello World.!`);
});

let appServer = webApp.listen(PORT, () => {
    console.log(`Server is up and running at ${PORT}`);
});

const WA = require('./sendTemplate');

// Route for WhatsApp
webApp.post('/whatsapp', async (req, res) => {

    
    WA.sendMessage();
    
  // console.log(req.body['messages'][0]['type']);

});

sendTemplate.js

var request = require('request');

function sendMessage(){
    
var options = {
  'method': 'POST',
  'url': 'https://waba.360dialog.io/v1/messages',
  'headers': {
    'D360-API-KEY': '',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    "to": "",
    "type": "template",
    "template": {
      "namespace": "69bcc88a_fffa_4488_90ba_1957221dffa1",
      "language": {
        "policy": "deterministic",
        "code": "en"
      },
      "components": [
        {
          "type": "body",
          "parameters": [
            {
              "type": "text",
              "text": "John"
            }
          ]
        }
      ],
      "name": "welcome"
    }
  })

};
request(options, function (error, response) {
  if (error) throw new Error(error);
  console.log(response.body);
});


}
module.exports = {
    sendMessage
}


As soon as I execute node.js file it waits from an incoming message once it receives the message from the user, it starts sending the template message one after the other, instead of just sending the message once.

How can I solve this?

What’s causing and how to fix these slider scroll distance issues on mobile?

I’m trying to solve some behavioural issues on mobile (iOS 14.8.1) with product image slider elements in a Shopify Dawn2.0 theme (like a carousel, theme calls it a ‘slider’) that have a button, like below:

enter image description here

which when clicked in order to scroll, scrolls by the incorrect amount causing the edge of the next image to be cut off from view. e.g.

enter image description here

When swiping the slider (internal OS magic) it stops at the correct place, it’s just these slider element buttons which result in a scroll of the incorrect amount/to the incorrect position. It happens on mobile no matter the browser. It does not happen when viewing on desktop and shrinking browser window down to mobile size, so it’s just on mobile that it’s doing this.

The JS that’s providing this functionality is in the class sliderComponent in the onButtonClick event which can be found in assets/global.js, around line ~553:

global.js

onButtonClick(event) {
    event.preventDefault();
    const slideScrollPosition = event.currentTarget.name === 'next' ? this.slider.scrollLeft + this.sliderFirstItem.clientWidth : this.slider.scrollLeft - this.sliderFirstItem.clientWidth;
    this.slider.scrollTo({
      left: slideScrollPosition,
      behavior:'smooth'
    });
  }

A play with using window.outerWidth, as below, does not help:

const slideScrollPosition = event.currentTarget.name === 'next' ? this.slider.scrollLeft + window.outerWidth : this.slider.scrollLeft -window.outerWidth

Can anyone help me understand what the problem is here and help me find, or provide me with a solution to fix this?

Thanks in advance.

How to avoid nested forEach if it’s possible?

I want to improve my code. It’s simple javascript code where I’m fetching some data from gitlab API and I want to get gitlab groups and their members, then I want to for each member display his groups.

let accounts = []


let subGroups = await api.getSubgroups();
subGroups = subGroups.map((group) => {
    const { id, name, full_path } = group;

    return {
        id,
        name,
        full_path
    }
}) 




subGroups = subGroups.map(async (group) => {
  const { id } = group; 
  const groupMembers = await api.getGroupMembers(id);
  return { group_id: id, groupMembers };
});

subGroups = await Promise.all(subGroups);




const map = subGroups.forEach((group) => {

    group.groupMembers.forEach((member) => {
        accounts.push(member)
    })
})

I want first get the list of groups and members of group. Then make array of distinct people and then give them their group.
Please how can I remove nested foreach, is it even possible? And also I want to ask how to get only neccessary properties of member (like only name and id) to accounts array

Nextjs: create countdown OTP verify

This is my Login.tsx

{!isVerify ? (
    // Login form
) : (
    <Verify data-phoneNumber={form.phoneNumber} data-countryCode={form.countryCode} />
)}

After send mobile with user, I change isVerify to True and <Verify /> component show to user.

And this is my verify:

const runTimer = () => {
        useEffect(() => {
            const interval = setInterval(() => {
                console.log(time);
                setTime(
                    (currentTime) => {
                        if (currentTime > 0) {
                            return currentTime - 1;
                        } else {
                            setResend(false)
                            clearInterval(interval);
                            return currentTime;
                        }
                    }
                );
            }, 1000);
            return () => clearInterval(interval)
        }, [])
}

const runAgain = () => {
    runTimer()
}

return (
    <div>
        {runTimer()}
        <div onClick={(e) => runAgain(e)}>Run Again</div>
    </div>
)   

For first time my timer work fine. but for second time not work! ( if I click on run again )

Chrome extension with html2canvas: Refused to load the script ” because it violates the following Content Security Policy directive

I am trying to write a chrome extension and I want to take screenshot of certain html element of facebook page. I thought of writing html 2 canvas myself, but there already is html2canvas library. I decided to use it in my content script on Facebook page, it is giving me error saying

Refused to load the script '<URL>' because it violates the following Content Security Policy directive: "script-src 'self'". Note that 'script-src-elem' was not explicitly set, so 'script-src' is used as a fallback. 

Here is my manifest.json file:

{
     ...
    "manifest_version": 3,
    "content_scripts": [
        {
            "matches": [
                "https://*.facebook.com/*"
            ],
            "js": [
                "html2canvas.js",
                "constants.js",
                "common/jquery.js",
                "content/index.js"
            ]
        }
    ]
}

My content_script has following line. I tried console logging and it is working fine. But,

$(window).on('load', function () {

$('body').on('click', "div", async function (e) {
    const ariaLabel = $(this).attr("aria-label");
    if (ariaLabel?.startsWith(COMMENT_DIV_ARIA_LABEL)) {
        const canvas = await html2canvas($(this)?.[0]);
    }

    if (ariaLabel?.startsWith(REPLY_DIV_ARIA_LABEL)) {
        const replyLink = $(this).find("a").attr("href");
    }
})

});

I am getting back the canvas (I tried console logging, but haven’t checked its output), but it is coming with the error as mentioned above. Can anyone tell me a right way to inject the script? Or maybe even tell me what I am doing wrong?
Also, I tried adding CSP in the manifest.json file.

is there any mongoose middleware to solve error

Error: Store validation failed: address: Please add an address
at ValidationError.inspect (D:ActsStore_Locator_APInode_modulesmongooseliberrorvalidation.js:48:26)
at formatValue (node:internal/util/inspect:763:19)
at inspect (node:internal/util/inspect:340:10)
at formatWithOptionsInternal (node:internal/util/inspect:2006:40)
at formatWithOptions (node:internal/util/inspect:1888:10)
at console.value (node:internal/console/constructor:331:14)
at console.warn (node:internal/console/constructor:364:61)
at exports.addStore (D:ActsStore_Locator_APIcontrollersstores.js:33:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
errors: {
address: ValidatorError: Please add an address
at validate (D:ActsStore_Locator_APInode_modulesmongooselibschematype.js:1277:13)
at D:ActsStore_Locator_APInode_modulesmongooselibschematype.js:1260:7
at Array.forEach ()
at SchemaString.SchemaType.doValidate (D:ActsStore_Locator_APInode_modulesmongooselibschematype.js:1210:14)
at D:ActsStore_Locator_APInode_modulesmongooselibdocument.js:2723:18
at processTicksAndRejections (node:internal/process/task_queues:78:11) {
properties: [Object],
kind: ‘required’,
path: ‘address’,
value: undefined,
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: ‘Store validation failed’
}

TypeError: command is not a constructor (Discord Bot)

I am currently trying to create slash commands on my Discord Bot. However, this issue suddenly prevented the bot’s functionality entirely.

F:GitHubDiscord BotsBailey v3bot.js:89
            const c = new command();
                      ^

TypeError: command is not a constructor
    at F:GitHubDiscord BotsBailey v3bot.js:89:23
    at Array.forEach (<anonymous>)
    at F:GitHubDiscord BotsBailey v3bot.js:86:10
    at Object.<anonymous> (F:GitHubDiscord BotsBailey v3bot.js:160:3)

Here is the code:

    allFiles('./commands')
        .filter(file => file.endsWith('.js'))
        .forEach(file => {
            file = file.replace(/\/g, "/");
            const command = require(`./${file}`);
            const c = new command();
            bot.commands.set(c.name, c);
            delete require.cache[require.resolve(`./${file}`)];
        })

Entire async code:

(async () => {
    const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_PRESENCES", "GUILD_MEMBERS", "GUILD_MESSAGES", "GUILD_MESSAGE_REACTIONS", "GUILD_EMOJIS_AND_STICKERS"] });

    bot.colors = colors;
    bot.assets = assets;

    bot.commands = new Discord.Collection();

    allFiles('./utils/extenders')
        .filter(file => file.endsWith('.js'))
        .forEach(file => {
            file = file.replace(/\/g, "/")
            require(`./${file}`);
        })

    allFiles('./events')
        .filter(file => file.endsWith('.js'))
        .forEach(file => {
            file = file.replace(/\/g, "/")
            const event = require(`./${file}`);
            bot.on(file.split('/').pop().split('.')[0], event.bind(null, bot))
            delete require.cache[require.resolve(`./${file}`)];
        })

    allFiles('./commands')
        .filter(file => file.endsWith('.js'))
        .forEach(file => {
            file = file.replace(/\/g, "/");
            const command = require(`./${file}`);
            const c = new command();
            bot.commands.set(c.name, c);
            delete require.cache[require.resolve(`./${file}`)];
        })

    bot.login(credentials.token);
}

Sort the color of records based on a list of colors

I have a list of colors, I need to sort the color of the records based on this list.

I need that after selecting the last color from the list, the loop returns to the first color.

Current result:

Current result

Expected result:

Expected result

See in Sandbox!

Thanks for your help

Colors list

const colorsList = [
  "#57D9A3",
  "#00C7E6",
  "#4C9AFF",
  "#998DD9",
  "#FF8F73",
  "#FFC400",
  "#7092BE",
  "#79F2C0",
  "#79E2F2",
  "#b3D4FF",
  "#c0b6F2",
  "#FFBDAD",
  "#FFE380",
  "#B9CADF"
];

Records

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, …, 46]

Current logic

const handleColor = (index) => {
    let color;
    let idx = 0;
    if (index < 14) {
      color = colorsList[index];
    } else {
      //what logic to use?
    }
    return color;
  };
....
<Box className="App">
      <h1>Dynamic Colors sort Javascript</h1>
      <Box display="flex" alignItems="center" justifyContent="center">
        <List className={classes.colorContent}>
          {records &&
            records.map((item, index) => (
              <IconButton
                key={index}
                className={classes.colorButton}
                style={{
                  backgroundColor: handleColor(index)
                }}
              >
                <Typography variant="caption">{item}</Typography>
              </IconButton>
            ))}
        </List>
      </Box>
    </Box>

How do I import and use a NPM package to a Vue.js application?

I’ve tried to import this package to my Vue.js app, but nothing worked.

I want to use this package to translate a text content from <input> html tag.

This is the <input> in HelloWorld.vue file:

 <input class="input" placeholder="Type your text here" />

I’ve imported in main.js file with:

import "@vitalets/google-translate-api";

And looks like it worked, but how can I use the package with my <input> text content?

Can’t decrypt WhatsApp web socket data

I am trying to send serial messages using WhatsApp web socket. However, I can’t communicate with socket in any way. I can’t access incoming json data or outgoing. I couldn’t decipher the password in any way. How can I decrypt this password with Javascript? I only know c# and javascript.

HEX

enter image description here
Bas64

enter image description here

Utf 8

enter image description here

Example base64

AAC4F7TD+aM7mqjEiQNXPIh/ynCD2VEokjoepVP1C1oC31RYbnyPSfVStYwV5wtnuqA1ogQXMUeuSwOPL5sBHB5BB1SEN+ELiisZVVndoxT0P10YpHVR9K2D9KCyzzRKVaWxQ8ba2pRqJ6gBwzeK94a3XnrxmnXh5vlMUxZRUaHmyR8gnLNji66OeTz7fcljA0YbH4aaBskZeXmuWvfKV2bQlaH8Wpam6NvQS/RkXwO68diYkLH/2cRQpg==

Add a child component with N number .of times inside parent Component (based on a state value)

I want to add a child-component ColorBox in return of parent component ColorBoxContainer based on No of times there is a value in state noOfBoxes: 16. I am trying doing using for-loop but I guess the code is wrong. Can someone help me out, how to achieve this?

import React, { Component } from 'react';
import ColorBox from './ColorBox';

class ColorBoxContainer extends Component {

  constructor(props) {
    super(props);
    this.state = {
      noOfBoxes: 16
    }
  }

  render(){
    return (
      <div>
        {for(i=0;i<this.state.noOfBoxes;i++){
           <ColorBox />
        }}
      </div>
    )
  }  
}

export default ColorBoxContainer1; 

java arralist letter search

So im creating a wordguesser ai for school. It has a list of words as database and it has to guess the word that the user has in mind. Now im stuck at the part where the ai has to check which words are in the list which contain the letters and at the right location. Does anyone know a way to find the words which contain the letters guessed at the right location?