how to bind a name value to a for loop using moment-timezone

i have a list of time zones been populated as a query as follows

async load(){

this.usertimezones= await this.query(gets my query result)
}

this is what the usertimezones looks like

0:{userId: '0b8502d0-0b65-4092-bc4e-5c491acc7771', timezone: 'Africa/Bamako', isActive: true, id: '69c6051b-5b8b-43cf-b771-7884b6eb5c01'}
1: {userId: '0b8502d0-0b65-4092-bc4e-5c491acc7771', timezone: 'America/Araguaina', isActive: true, id: 'b609808d-3002-422a-810c-8d3e17c972bc'}

so for each timezone i pass it as follows

    async load(){
    
    this.usertimezones= await this.query(gets my query result)
this.usertimezones.forEach(x => {
            let test = Mo().tz(x.timezone).format('MMMM Do YYYY, h:mm a');
            console.log(test);
        })
    }

and then the output is as follows

March 15th 2022, 7:53 pm
March 15th 2022, 4:53 pm

however now i cant tell which one it belongs to, how do i add the timezone name to it and push it to an array so it looks like

Africa/Bamako March 15th 2022, 7:53 pm
  America/Araguaina  March 15th 2022, 4:53 pm

JavaScript why cannot select the elements

I’m sure I’ve make a mistake but I can’t figure it out…

Why I cannot select the elements with class name test by `querySelectorAll?

I’m getting an error: cannot read properties of undefined, but the elements are definitely defined because when I type content in the console, it shows the nodeList…

const content = document.querySelectorAll('.test');

content.classList.add('hide-content');
.Content {
  width: 180px;
  height: 90px;
  background-color: green;
}

.hide-content {
  display: none
}
<div class="Content"></div>
<div class="Content test"></div>
<div class="Content test"></div>

page remembers last api call & re-calls on re-open

I have a Vue3 site designed to hold embedded tableau dashboards. When a user clicks a link on the menu page, a page opens that’s basically an empty shell. With the link’s props, I fetch a tableau token, construct the api call, and populate a div with the response. Starting a week ago, the site’s doing something new, and it’s happening the same on Chrome, Firefox, and Safari.

This is what happens now: the user clicks a menu link, frame page opens with requested report. If they return to menu and click new link, the frame page re-opens and immediately the page fires the api call from the previous visit. (There’s nothing in Store or cookies that saves the url the page constructs on-the-fly, so I’m not even sure where the browser is getting the full url for that re/call.) Since tableau’s tokens expire in seconds, this re/call fails — meanwhile, the page continues, constructing the new (correct) url+token and retrieving the requested dashboard.

So in the embed div, now there’s one dashboard reporting an error b/c the token expired — and if the user scrolls past that, they’ll see a second dashboard in the div, and this is the one they actually requested.

On top of all that, this ghost api call doesn’t change. If the first call was for reportA, and the user leaves-and-returns for reportB, the frame page calls reportA at the top. If the user leaves-and-returns now requesting reportC, the frame page still calls reportA at the top — and it’ll keep doing that even if the user revisits with a reportA request. The only way to clear it is by refreshing the page (and then it just starts all over again).

For now, I’m weaseling around the issue like so:

    created() {
      if (this.$cookie.getCookie('redo')) {
        console.log('B) remove cookie');
        this.$cookie.removeCookie('redo');
      } else {
        console.log('A) set cookie');
        this.$cookie.setCookie('redo', true);
        location.reload();
      }

Which is less of a solution and more of an unhappy hack to plug the dam while I figure out where all the water came from. What’s especially weird is when I backed up to a commit from before the problem first appeared, the site still does the ghost call. I’ve broken a lot of sites in a lot of crazy ways in my years, but I’ve never run into a case like this, and I haven’t the first clue how to solve it, because I haven’t the first clue what’s causing it.

Any and all help is greatly appreciated. /tears hair

close popup by clicking outside of it in foreach functions

i’ve created a sample project with a card slider, inside this slider i’ve created a foreach functions that open a popup when the card is clicked, with some information.

the problem is that i can’t find a way to close popup if i click outside of the popup elements.

here a reproducible example:
https://jsfiddle.net/7hg4y9ro/

my function:

const cards = document.querySelectorAll('.cards')

cards.forEach((card => {

    const getName = card.querySelector('.footer-left')
    const getPrice = card.querySelector('.footer-right')

    function showPopup() {
        const el = document.getElementById('cards-container');
        const popup = document.createElement('div')
        popup.setAttribute('class', 'card-popup')

        popup.innerHTML = '' +
            '<div class="close-card-popup" id="close-card-popup">&times;</div>' +
            '<p class="card-popup-text">Il prezzo di ' + getName.innerText + ' Γ¨ di:</p>' +
            '<p class="card-popup-price">' + getPrice.innerText + ' €' +
            '<div class="card-popup-center"><button class="card-popup-button">Acquista il prodotto</button></div>'

        const overlay = document.createElement('div')
        overlay.setAttribute('class', 'overlay')
        el.appendChild(overlay)
        el.appendChild(popup)

    }

    card.addEventListener('click', showPopup)

}))

JavaScript not returning the correct data in console

Below is the input code I wrote and the output it gives. I’m starting now in JavaScript, can you guys help? Thanks πŸ™‚

var time = new Date()
var timenow = 0
console.log(${time.getHours}:${time.getMinutes})

Info: Start process (15:49:59)
function getHours() { [native code] }:function getMinutes() { [native code] }
Info: End process (15:49:59)

Debugger is not working in visual studio code

I am using vs code. And I am creating a websocket example. When I am writing this app I felt a need of opening debugger but when I start debugging it doesn’t work.
Buttons of debugger are not working. To clarify this I am uploading an image
Debugger’s button

And the repl of debug console is also not working. Any help will we greatly appreciated. Thanks to whole stack overflow community

Is there an inverse function to toLocaleDateString? (ie. can I feed in 15-Mar-2022 and have it understood for purposes of math?)

To expand on the title:

Our intranet uses dates in the format of 15-Mar-2022. I’m trying to determine the number of days a given date is from today. I’m working in UI.Vision (*see note at bottom), so there’s a bit of mixed-code here, but this is what I’m trying:

const date1 = new Date(${dateToday}); const date2 = new Date(${line[0]}); const diffTime = Math.abs(date2 - date1); const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); return diffDays;

where ${dateToday} and ${line[0]} are both dates (strings) in the format mentioned above.

I get “invalid date”.

I briefly thought I could fix it by doing something like this first:

const string = ${line[0]}; const arr = string.split("-"); return arr

(which UI.Vision would then take on as an array called, for example, dateArray)

And then using ${dateArray[0]} as the Day, ${dateArray[1]} as Month and ${{dateArray[2]} as the Year and then feeding it in as so:

const date = new Date(${dateArray[2]}, ${dateArray[1]}, ${dateArray[0]});

But then the issue is that ${dateArray[1]} is going to be “Mar” when the Date() function is going to expect ‘2’ (0-based index of the numeric months).

So I don’t think I’m getting anywhere.

I suppose I could painstakingly associate each 3-character month with its numeric cousin, but I really don’t want to do that in UI.Vision (it is slow enough without adding an additional 12 lines on each of hundreds of iterations!). I can probably construct it into a javascript 1-liner, which would be ok… but I wondered if there was an easier/better way. Something like the opposite of what toLocaleDateString does. My Google-fu found nothing though.

Thank you.

  • UI-Vision is an RPA extension that I use at work where I have very limited ability to install things. Recommending I use an alternative tool is not an option. UI-Vision utilizes Javascript, but I’m limited to one-liners that return a value. That returned value can be a string or an array of strings.

getting Typescript error TS2304 : cannot find name ”customType”

i have a custom type called JWTSubject

and when trying to compile i get this error

error TS2304: Cannot find name 'JWTSubject'

my tsconfig.json looks like so;


{
      "compilerOptions": {
            "target": "es2016" ,
            "module": "commonjs" ,
            "rootDir": "./src" ,
            "typeRoots": [
                  "./@types",
                  "./node_modules/@types"
            ] ,         
            "outDir": "./dist" ,
            "removeComments": true ,
            "esModuleInterop": true ,
            "forceConsistentCasingInFileNames": true ,
            "strict": true,
            "skipLibCheck": true,
      },
      "include": ["./src", "./@types"],
      "exclude": [".git", "node_modules"]
}


my file structure looks like so;

β”œβ”€β”€β”€src
β”‚  
β”œβ”€β”€β”€@typesβ”œβ”€β”€ global.d.ts
β”‚         β”‚
β”‚         └── custom ── index.d.ts              
β”‚
β”œβ”€β”€β”€tsconfig.json
β”‚ 

global.d.ts looks like ;


import IUser from "../src/interfaces/IUser";

declare global {
      export type JWTSubject = {
            _id: IUser["_id"];
            username: IUser["username"];
      };
}


Web component – how does a child element access custom component class functions and vars?

Within a custom component defined with <template> and <slot> tags, a child element can get the parent element that is the custom component, and then use this element reference to access class defined vars and functions.

However, how can a child element know which element is the custom component?

The template itself is contained in a shadow DOM. When rendering a custom component on the page, this shadow DOM is cloned and attached into the custom component as its host.

Elements that are slotted in to the custom component however can’t seem to tell the node tree it is attached to came from a shadow DOM node that was cloned, and can’t tell which element in the current DOM tree is the top level custom component unless it iterates through each parentNode to check if they have a shadowRoot.

What is the way to let a child element inside a custom component access the custom component’s class variables and functions?

Problem when creating a map using Google Maps Picker API with React

I have problem error “checkout:1 Uncaught (in promise) peΒ {message: ‘Map: Expected mapDiv of type HTMLElement but was passed null.’, name: ‘InvalidValueError’, stack: ‘Errorn at new pe (https://maps.googleapis.com/m…tp://localhost:3000/static/js/bundle.js:60908:19)’}”

Anyone can help?
My code

import React, { useState, useEffect } from 'react';
import { useNavigate } from "react-router-dom";
import { useDispatch, useSelector } from 'react-redux';
import { useCart } from "react-use-cart";
import { getWarehouseLocation } from "../../redux/action/product-action";
import { getProvince, getCityByProvID, getNearestWarehouse } from "../../redux/action/location-action";
import NumberFormat from "react-number-format";
import MapPicker from 'react-google-map-picker'

// ========== GOOGLE MAPS PICKER API ==============
const DefaultLocation = { lat: 10, lng: 106};
const DefaultZoom = 10;

function Checkout () {
    // ======= GOOGLE MAPS PICKER API ==========
    const [defaultLocation, setDefaultLocation] = useState(DefaultLocation);

    const [location, setLocation] = useState(defaultLocation);
    const [zoom, setZoom] = useState(DefaultZoom);

    function handleChangeLocation (lat, lng){
        setLocation({lat:lat, lng:lng});
    }
    
    function handleChangeZoom (newZoom){
        setZoom(newZoom);
    }

    function handleResetLocation(){
        setDefaultLocation({ ... DefaultLocation});
        setZoom(DefaultZoom);
    }

    const [origin, setOrigin] = useState(null);
    const [destination, setDestination] = useState(null);
    const [weight, setWeight] = useState(0);

    const dispatch = useDispatch();
    const {
        isEmpty,
        cartTotal,
        totalUniqueItems,
        items,
        updateItemQuantity,
        removeItem,
        emptyCart
    } = useCart();
    
    const { warehouse, province, loadingProv, city, nearestWarehouse } = useSelector(state => {
        return {
            warehouse : state.warehouse.data,
            province: state.location.province,
            loadingProv: state.location.loadingProv,
            city: state.location.city,
            nearestWarehouse: state.location.nearestWarehouse
        }
    });

    useEffect(() => {
        dispatch(getWarehouseLocation());
        dispatch(getProvince());
        if ("geolocation" in navigator) {
            console.log("Available");
        } else {
            console.log("not")
        }

        navigator.geolocation.getCurrentPosition((position) => {
            console.log("Latitude is :", position.coords.latitude);
            console.log("Longtitude is :", position.coords.longitude);
        });

        let totalWeight = 0;
        for (let i = 0; i < items.length; i++) {
            totalWeight += parseInt(items[i].weight) * parseInt(items[i].quantity);
        }
        setWeight(totalWeight);
        console.log(warehouse)
        console.log(nearestWarehouse)
    }, []);

    const renderCheckoutItem = () => {
        return (
            items.map((item, idx) => {
                return (
                    <tr className="rem1" key={idx}>
                        <td className="invert text-center">{ idx + 1 }</td>
                        <td className="invert-image">
                            <a href="single.html">
                                <img style={{ width: 120 }} src={`http://localhost:3000/images/products/${item.image}`} alt=" " className="img-responsive"/>
                            </a>
                        </td>
                        <td className="invert">{ item.name }</td>
                        <td className="invert text-center">
                            { item.quantity }
                        </td>
                        <td className="invert text-right">
                            <NumberFormat
                                thousandsGroupStyle="thousand"
                                value={item.price}
                                prefix="Rp. "
                                decimalSeparator="."
                                displayType="text"
                                type="text"
                                thousandSeparator={true}
                                allowNegative={true} /> 
                        </td>
                        <td className="invert text-right">
                            <NumberFormat
                                thousandsGroupStyle="thousand"
                                value={item.itemTotal}
                                prefix="Rp. "
                                decimalSeparator="."
                                displayType="text"
                                type="text"
                                thousandSeparator={true}
                                allowNegative={true} /> 
                        </td>
                        <td className="invert text-center">
                            <div className="rem">
                                <div className="close1">
                                    <button className='btn btn-danger'>
                                        <span className="fas fa-trash-alt"></span>
                                        &nbsp; Remove
                                    </button>
                                </div>
                            </div>

                        </td>
                    </tr>
                )
            })
        )
    }

    const renderBasketCheckout = () => {
        return (
            items.map((item, idx) => {
                return (
                    <li className='d-flex justify-content-between mb-3 text-muted' key={idx}>
                        <span>{ item.name } <i> - </i>{ item.quantity }</span>
                        <span>
                            <NumberFormat
                                thousandsGroupStyle="thousand"
                                value={item.itemTotal}
                                prefix="Rp. "
                                decimalSeparator="."
                                displayType="text"
                                type="text"
                                thousandSeparator={true}
                                allowNegative={true} /> 
                        </span>
                    </li>
                )
            })
        )
    }

    const renderWarehouse = () => {
        return (
            warehouse.map((item, idx) => {
                return (
                    <li key={idx}>
                        Warehouse Name: {item.warehouse_name}
                        <button onClick={ () => checkOngkir(item.city_id) }>Check Ongkir</button>
                    </li>
                )
            })
        )
    }

    const renderOngkirResult = () => {
        // return (
        //     <>
        //         <h5>{ongkir.name}</h5>
        //         {
        //             ongkir.costs.map((item, idx) => {
        //                 return (
        //                     <div key={idx}>
        //                         <p>{item.service}</p>
        //                         <span>Description: {item.description}</span>
        //                         <span>Cost: { item.cost[0].value }</span>
        //                         <p></p>
        //                     </div>
        //                 )
        //             })
        //         }
        //     </>
        // )
    }

    const renderProvince = () => {
        if (province.length) {
            return province.map((item, idx) => <option value={ item.province_id } key={idx}>{ item.province }</option> )
        }
    }

    const renderCity = () => {
        if (city.length) {
            return city.map((item, idx) => <option value={ item.city_id } key={ idx }>{ item.city_name }</option>)
        }
    }

    const setCityByProvID = (id) => {
        dispatch(getCityByProvID(id))
    }

    const checkOngkir = () => {
        dispatch(getNearestWarehouse({ destination: destination }));
    }

    const navigate = useNavigate();
    return (
        <section className="banner-bottom-wthreelayouts py-lg-5 py-3">
            <div className="container">
                <div className="inner-sec-shop px-lg-4 px-3">
                    <h3 className="tittle-w3layouts my-lg-4 mt-3">Checkout </h3>
                    <div className="checkout-right">
                        <h4>Your shopping cart contains:
                            <span>{ items.length } Products</span>
                        </h4>
                        <table className="timetable_sub table table-bordered">
                            <thead className='bg-dark text-white'>
                                <tr>
                                    <th className='text-center'>SL No.</th>
                                    <th>Product</th>
                                    <th>Product Name</th>
                                    <th className='text-center'>Quantity</th>
                                    <th className='text-right'>Price</th>
                                    <th className='text-right'>Total Price</th>
                                    <th className='text-center'>Remove</th>
                                </tr>
                            </thead>
                            <tbody>
                                { renderCheckoutItem() }
                            </tbody>
                        </table>
                    </div>
                    <div className="checkout-left row">
                        <div className="col-md-4 checkout-left-basket">
                            <h4 className='bg-info text-center text-white py-2'>Continue to basket</h4>
                            <ul>
                                {
                                    renderBasketCheckout()
                                }
                                <li className='d-flex justify-content-between mb-3 font-weight-bold'>
                                    <span>Total</span>
                                    <span>
                                        {
                                            <NumberFormat
                                                thousandsGroupStyle="thousand"
                                                value={cartTotal}
                                                prefix="Rp. "
                                                decimalSeparator="."
                                                displayType="text"
                                                type="text"
                                                thousandSeparator={true}
                                                allowNegative={true} /> 
                                        }
                                    </span>
                                </li>
                            </ul>
                            <div className="warehouse-group mt-4">
                                <h4 className='bg-info text-center text-white py-2'>Warehouse List</h4>
                                <ul className="warehouse-list" style={{ listStyle: 'none' }}>
                                    { renderWarehouse() }
                                </ul>
                                <div className="ongkir-result">
                                    { renderOngkirResult() }
                                </div>
                            </div>
                        </div>
                        <div className="col-md-8 address_form">
                            <h4>Add a new Details</h4>
                            <form className="creditly-card-form agileinfo_form">
                                <section className="creditly-wrapper wrapper">
                                    <div className="information-wrapper">
                                        <div className="first-row form-group">
                                            <div className="controls">
                                                <label className="control-label">Full name: </label>
                                                <input className="billing-address-name form-control" type="text" name="name" placeholder="Full name" />
                                            </div>
                                            <div className="card_number_grids">
                                                <div className="card_number_grid_left">
                                                    <div className="controls">
                                                        <label className="control-label">Mobile number:</label>
                                                        <input className="form-control" type="text" placeholder="Mobile number" />
                                                    </div>
                                                </div>
                                                <div className="card_number_grid_right">
                                                    <div className="controls">
                                                        <label className="control-label">Landmark: </label>
                                                        <input className="form-control" type="text" placeholder="Landmark" />
                                                    </div>
                                                </div>
                                                <div className="clear"> </div>
                                            </div>
                                            <div className="controls">
                                                <label className="control-label">Full Address : </label>
                                                <input className="form-control" type="text" placeholder="Full Address" />
                                            </div>
                                            <div className="controls">
                                                <label className="control-label">Province : </label>
                                                <select className="form-control option-w3ls" onChange={ (event) => setCityByProvID(event.target.value) }>
                                                    <option>Select Your Country</option>
                                                        { renderProvince() }
                                                </select>
                                            </div>
                                            <div className="controls">
                                                <label className="control-label">City : </label>
                                                <select className="form-control option-w3ls" onChange={ (event) => setDestination(event.target.value) }>
                                                    <option>Select Your City</option>
                                                        { renderCity() }
                                                </select>
                                            </div>
                                            <div className="controls">
                                                <label className="control-label">Postal Code : </label>
                                                <input className="form-control" type="text" placeholder="Postal Code" />
                                            </div>
                                            <button onClick={handleResetLocation}>Reset Location</button>
                                            <div>
                                                <label>Latitute:</label><input type='text' value={location.lat} disabled/>
                                                <label>Longitute:</label><input type='text' value={location.lng} disabled/>
                                                <label>Zoom:</label><input type='text' value={zoom} disabled/>
                                                
                                                <MapPicker defaultLocation={defaultLocation}
                                                    zoom={zoom}
                                                    mapTypeId="roadmap"
                                                    style={{height:'700px'}}
                                                    onChangeLocation={handleChangeLocation} 
                                                    onChangeZoom={handleChangeZoom}
                                                    apiKey='MY_KEY'/>
                                           </div>
                                        </div>
                                        {/* <button className="submit check_out btn btn-block btn-dark" onClick={ () => navigate('/payment')}>Make a Payment</button> */}
                                    </div>
                                </section>
                            </form>
                            <button className="submit check_out btn btn-block btn-warning" onClick={ () => checkOngkir() }>Cek ongkir dulu yuk</button>
                        </div>

                        <div className="clearfix"> </div>

                    </div>

                </div>

            </div>
        </section>
    )
}

export default Checkout;

I was stuck, please help

How to isolate duplicates by property from an array of objects

From this array of objects, I’d like to get multiple arrays containing the objects that have the same values for the “id” property:

var obj1 = { id: 1, name: "apple"};
var obj2 = { id: 2, name: "pear"};
var obj3 = { id: 3, name: "melon"};
var obj4 = { id: 4, name: "cherry"};
var obj5 = { id: 2, name: "banana"};
var obj6 = { id: 1, name: "pinapple"};
var obj7 = { id: 1, name: "peach"};
var array = [obj1, obj2, obj3, obj4, obj5, obj6, obj7];

Example of the arrays I’d like to retrieve:

[{
  id: 1,
  name: "apple"
}, {
  id: 1,
  name: "pinapple"
}, {
  id: 1,
  name: "peach"
}]

[{
  id: 2,
  name: "pear"
}, {
  id: 2,
  name: "banana"
}]

Azure Token Question About Backend Authentication

I seem to find in every part of stack overflow,
any tutorial

that azure must be log in, before I get the code to access the refresh token

const config = {
auth: {
    clientId: process.env.CLIENT_ID,
    authority: process.env.AUTHORITY,
    clientSecret: process.env.CLIENT_SECRET
},
system: {
    loggerOptions: {
        loggerCallback(loglevel, message, containsPii) {
            console.log(message);
        },
        piiLoggingEnabled: false,
        logLevel: msal.LogLevel.Verbose,
       }
   }
};
const authCodeUrlParameters = {
scopes: ["user.read","user.write"],
redirectUri: process.env.REDIRECT_URL,
};

pca.getAuthCodeUrl(authCodeUrlParameters).then((response) => {
// res.redirect(response);
console.log(response);
}).catch((error) => console.log(JSON.stringify(error)));
console.log(authCodeUrlParameters);
const pca = new msal.ConfidentialClientApplication(config);
app.get('/redirect', (req, res) => {
const tokenRequest = {
    code: req.query.code,
    scopes: ["user.read"],
    redirectUri: REDIRECT_URI,
};

pca.acquireTokenByCode(tokenRequest).then((response) => {
    console.log("nResponse: n:", response);
    res.sendStatus(200);
}).catch((error) => {
    console.log(error);
    res.status(500).send(error);
});
});

getAuthCodeUrl returns a link which I would need to login to get my code
which then would I need to use to get the tokens and have my refresh token there.

but I don’t want to access the link since I’m using console not GUI,

My Mind is at the breaking point I don’t know what to do.
I just need the API for One Drive,
so I can Upload my file.

majority in the stackoverflow,
has a code that requires a refresh token

I can’t get the refresh token without accessing the link.

Any help?

best practice for nesting promises in succession

I currently have a few functions that return promises such as the below:

function action_one(){
    return new Promise((resolve, reject)->{
        ...
    });
}

I want to be able to wait on one before doing the next promise without nesting them. I had searched for some solutions, one being PromiseAll() but it does not seem to do it in order. Another solution was to do the following:

   promise.then(result =>{
       action
   }.then(result =>{
       action
   }.then(result =>{
       action
   }.then(result =>{
       action
   }.then(result =>{ etc.

which I’m not sure works for my issue but it doesn’t seem compactable.

what would be best practice in this situation?

Restricting minimum length of email ONLY for Gmail logins Regex

So, there is a task to match emails in an input agains some certain conditions. Most of them are fulfilled. All of them, actually, except one.

So, user emails have to be up to 30 characters long, but they cannot be shorter than 6 only for gmail users (the part before the @). Other types of email can have even shorter emails.

Please help me find a correct regexp!

My current one is:

^((?!.*?..)[a-zA-Z0-9.]{1,30})@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})$