Cannot read properties of undefined (reading ‘off’) when calling removeLayer() in a for loop

Say I have the following code:

var streets = L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');

var yearLayers = {};
yearLayers['1877'] = L.tileLayer('https://terrafrost.sfo2.digitaloceanspaces.com/maps/austin/v2/1877/{z}/{x}/{y}.png');
  
var map = L.map('map', {
    center: [30.267222, -97.743056],
    zoom: 13,
  layers: [streets]
});

layerControl = L.control.layers().addTo(map);
layerControl.addBaseLayer(streets, 'Streets');
layerControl.addOverlay(yearLayers['1877'], '1877');

layerControl.removeLayer(yearLayers['1877']);

/*
var years = ['1877'];
for (var i = 0; i < years; i++) {
    year = years[i];
    layerControl.removeLayer(yearLayers[year]);
}
*/

That code runs without issue but, if I comment out the layerControl.removeLayer(yearLayers['1877']); and uncomment out the for loop I get this error:

Uncaught TypeError: Cannot read properties of undefined (reading 'off')
    at i.removeLayer (Control.Layers.js:142:9)
    at whatever:x:y

https://jsfiddle.net/q7rkzjLp/2/ shows what I mean. Well, more specifically, that link shows the error.

https://jsfiddle.net/q7rkzjLp/1/ shows it code without the for loop running without issue.

So why am I getting this error and what can I do to fix it?

How to create a download button to download images from URL? [duplicate]

I wanted to download an image from the response url, I am getting from backend API. However, I do not know, when I create a button, it automatically clicks each time, I refresh the browser. Why thus strange behaviour is happening?

let downloadBtn = document.querySelector(".downloadImageBtn");
downloadBtn.addEventListener("click", downloadImage(href));

//Function to download AI generated Image
function downloadImage(hreference){
  const anchorElement = document.createElement('a');
  anchorElement.href = hreference;
  anchorElement.download = "ai-image.png";

  document.body.appendChild(anchorElement);
  anchorElement.click();

  document.body.removeChild(anchorElement);
  window.URL.revokeObjectURL(hreference);
}

Get datetime in specific timezone [duplicate]

I need to get the current date from a specific time zone. I already tried a lot but nothing works. Why is this not working?:

import { toDate } from "date-fns-tz";

function createDateInTimeZone(timezone) {
    console.log(timezone);
    // Get the current date and time in UTC
    const now = new Date();

    // Convert the current date and time to the specified time zone
    const dateInTimeZone = toDate(now, { timeZone: timezone });

    return dateInTimeZone;
}

createDateInTimeZone('utc'); //Tue Nov 21 2023 14:34:34 GMT+0100 (Central European Standard Time)

I would expect something like: Tue, 21 Nov 2023 13:34:34 GMT

Converting date to tick when the date has a time as 00:00:00 results in previous days tick

I have a date as Sun Oct 01 2023 00:00:00 GMT+0530 (India Standard Time) which i’m trying to convert to the time tick as below

 const startDates =  ((dateDetails['start']* 10000) + 621355968000000000)   

the above conversion works perfectly when the time part of date is not 00:00:00, but in case it is 00:00:00 it creates a time tick of previous date,so by using the above conversion formula I get time tick as ‘638316954000000000’

But when checked if the timetick(638316954000000000) generated a proper date or not using online converter https://www.datetimetoticks-converter.com/ the date recieved was 30/09/2023 18:30:00.

The expected conversion to time tick should be 638317152000000000 , got this value from the same online converter mentioned above https://www.datetimetoticks-converter.com/.

What should be the fix for the issue, because if we add secs or mins to date that would be wrong so what doing that how to get expected tick value in case if time is 00:00:00

why the async statement invalid in javascript

I have declared the async before function,but it still notice that The ‘await’ operator can only be used in an ‘async’ function

async function Refresh(regListResult) {
    $(".dfxContent").each(function (index) {
        if (index >= 13 && index < 37) {
            var regComment = $(this).nextAll().eq(4).html();
            if (-1 !== regComment.indexOf("1")) {
                // 在这里加一个读通道位置的函数
                var chnPlace = ChnPlaceGet(a, b, c);
                await new Promise(resolve => setTimeout(resolve, 1000));
                var chnPlaceData = '两者应匹配,' + chnPlace;
                RefreshAnother(Data, index);
                $(this).html(a + b + c);
            }
        }
    });
}

How can I make the statement valid?

Custom api endpoint in strapi4 returning 404 not found error

I am building a strapi application with javascript where I have to fetch some data from an external api. For my use case, I have to create a custom strapi api endpoint, which responds with the fetched data when hit. I do not want to create the api against any content type. I just want an endpoint for my above use case. Here is the code for the files I have been working with:

//.src/api/lpv-banner-data/controllers/lpv-banner-data.js

'use strict';

module.exports = {
  async fetchData (ctx, next){
    try{
      const data = await strapi.service("api::lpv-banner-data.lpv-banner-data").fetchData();
      console.log(data);
      ctx.body("data", data);
    }
    catch(err){
      ctx.badRequest("Post report controller error", err);
    }
  } 
};

//.src/api/lpv-banner-data/routes/lpv-banner-data.js

module.exports = {
  routes: [
    {
      method: 'GET',
      path: '/',
      handler: 'lpv-banner-data.fetchData', 
      config: {
        policies: [],
        middlewares: [],
      },
    },
  ],
  prefix: 'lpv-banner-data',
  controller: 'lpv-banner-data',
};
//.src/api/lpv-banner-data/services/lpv-banner-data.js


'use strict';
const axios = require('axios');

module.exports = {
    fetchData: async ()=> {
        try{
            const response = await axios.get(`https://api-endpoint`);
            const data = response.data;
            const propertyTypesData = await getPropertyTypes.json();
            return propertyTypesData;
        }catch(err){
            return err;
        }
    }
};

The external api gives a response. I have tried defining the entire fetch logic in the controller. But the results were same. There were no middlewares written for the above usecase. Note that I cannot write this api against any already built content types or cannot create a new content type. Is there a way to achieve this?

Issue with Babel Aliases and Import Paths

I am encountering an issue with Babel aliases and import paths in my Node.js project. The project directory structure is as follows:

ProjectRoot
├── Backend
│   ├── src
│   │   ├── core
│   │       └── foo.js
│   ├── .babelrc
│   └── index.js
└── other_project_files_and_directories

I am trying to import a variable from foo.js using Babel aliases in my index.js file:

import { temp } from '@core/foo.js';

Here is the content of my .babelrc file:

{
    "presets": [
        [
            "@babel/preset-env",
            {
                "targets": {
                  "node": "current"
                }
            }
        ]
    ],
    "plugins": [
        [
            "module-resolver",
            {
                "root": [
                    "./src"
                ],
                "alias": {
                    "@core": "./src/core"
                }
            }
        ]
    ]
}

However, I am encountering the following error:

Cannot find package '@core/foo.js' imported from <local_directories>/ProjectRoot/Backend/index.js 
code: 'ERR_MODULE_NOT_FOUND'

additional information:
babel-plugin-module-resolver version is: 5.0.0

Chrome extension reload secondary tab on event

I’m trying to reload a tab on user interaction, but can’t figure out a solution.

I know chrome.tabs.reload(); is the function to trigger a reload

and that document.getElementById("...").addEventListener("click") is able to detect user interaction, but I can’t get them to work alongside each other.

.for example in the case I had tab1 which is currently navigated to google.com on clicking search I want to trigger a event that reloads tab2 but I can only seem to inject a trigger event on loaded pages via content_scripts but content_scripts isn’t able to access chrome.tabs.reload().

Attempt #1

manifest.json

{
  "manifest_version": 3,
  "name": "Hello Extensions",
  "description": "Base Level Extension",
  "version": "1.0",
  "content_scripts": [
    {
      "matches": ["*://*.google.com/*"],
      "js": ["reload.js"]
    }
  ]
}

reload.js

document.getElementByClassName("gNO89b").addEventListener("click", function() {
    chrome.tabs.reload();
});

if I replace chrome.tabs.reload(); in reload.js with alert('example'); it works as expected, but chrome.tabs.reload(); won’t trigger.

how to run external libs functions inside iOS and Android in React Native?

I want to integrate stream datafeed for charting library. Stream will be communicated with msgpack (like a JSON). I need to decode and encode sended message and received data. Here is the explanation how whole process going on:
Checking platform base for rendering html:

const uri =
  Platform.OS === 'ios'
    ? './charting_library/index.html'
    : 'file:///android_asset/index.html';

I am trying to inject libraries encode and decode functions that we need inside charting library. Here is the injected value and necessary functions:

import {encode, Decoder} from '@msgpack/msgpack';
...
const encodeHandler = (value: any): Uint8Array => {
  const encoded = encode(value);
  return encoded;
};
...
const runFirst = `
    window.addEventListener('DOMContentLoaded', () => initOnReady('${symbol}', ${encodeHandler}, ${decodeHandler}), false);
  `;

        <WebView
          ref={ref => (webViewRef.current = ref)}
          source={{uri}}
          injectedJavaScriptBeforeContentLoaded={runFirst}
          ...otherProps
        /> 

Once I call normal JS functions in the html that I pass like that way, it is working properly. But I can not call library specific functions. How to solve that?

Angular applications, express.js server, sending an email via form on the front-end side

Error sending message:
Object { headers: {…}, status: 500, statusText: “Internal Server Error”, url: “http://localhost:3000/invia-email”, ok: false, name: “HttpErrorResponse”, message: “Http failure response for http://localhost:3000/send-email: 500 Internal Server Error”, error: “Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more atn535 5.7.8 https: //support.google.com/mail/?p=BadCredentials cm42-20020a170906f5aa00b009ff8f199f21sm1832983ejd.19 – gsmtp” } error in console. chatgpt tells me “Less secure login: If you are using a Gmail account, you may need to enable “Less secure login” in your Gmail account. Go to this page and make sure “Less secure app login” is enabled.” Do you know a trick?

server.js const express = require('express');
const nodemailer = require('nodemailer');
const app = express();
const port = 3000;  // Puoi scegliere la porta che preferisci

// Middleware per consentire la comunicazione con il front-end
app.use(express.json());

// Configura il trasportatore Nodemailer (sostituisci con le tue informazioni)
const transporter = nodemailer.createTransport({
  service: 'gmail',
  auth: {
    user: '[email protected]',
    pass: '123456',
  },
});

// Definisci la rotta per l'invio delle email
app.post('/invia-email', (req, res) => {
  const { destinatario, oggetto, testo } = req.body;

  const mailOptions = {
    from: '[email protected]',
    to: destinatario,
    subject: oggetto,
    text: testo,
  };

  transporter.sendMail(mailOptions, (error, info) => {
    if (error) {
      return res.status(500).send(error.toString());
    }
    res.status(200).send('Email inviata con successo: ' + info.response);
  });
});

// Avvia il server sulla porta specificata
app.listen(port, () => {
  console.log(`Server in ascolto sulla porta ${port}`);
});

component angular import { Component } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-contatti',
  templateUrl: './contatti.component.html',
  styleUrls: ['./contatti.component.css']
})
export class ContattiComponent {
  constructor(private http: HttpClient) {}

  inviaMessaggio(formData: FormData): void {
    this.http.post('http://localhost:3000/send-email', {
      nome: formData.get('name'),
      email: formData.get('email'),
      messaggio: formData.get('message')
    }).subscribe(
      data => {
        // Gestisci la risposta dal server (potrebbe essere un messaggio di conferma, ad esempio)
        console.log(data);
      },
      error => {
        console.error('Errore durante l'invio del messaggio:', error);
      }
    );`your text`
  }

  onSubmit(event: Event): void {
    event.preventDefault();
    const formData = new FormData(event.target as HTMLFormElement);
    this.inviaMessaggio(formData);
  }
}

Encrypt a string with rsa public key in java script

static string publicKey = null;
    static string privateKey = null;
    public static void CreateOrRotate()
    {
        using (RSA rsa = RSA.Create(4096))
        {
            privateKey = rsa.ToXmlString(true);
            publicKey = rsa.ToXmlString(false);
        }
    }

    public static string GetPublicKey()
    {
        return publicKey;
    }
    public static string Encrypt(string plaintext)
    {
        using (RSA rsa = RSA.Create())
        {
            rsa.FromXmlString(publicKey);
            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(plaintext);
            byte[] encryptedData = rsa.Encrypt(dataToEncrypt, RSAEncryptionPadding.OaepSHA512);
            return Convert.ToHexString(encryptedData);
        }
    }
    public static string Decrypt(string ciphertext)
    {
        try
        {
            using (RSA rsa = RSA.Create())
            {
                rsa.FromXmlString(privateKey);
                byte[] encryptedData = Convert.FromHexString(ciphertext);
                byte[] decryptedData = rsa.Decrypt(encryptedData, RSAEncryptionPadding.OaepSHA512);
                return Encoding.UTF8.GetString(decryptedData);
            }
        }
        catch (Exception)
        {

            throw new BusinessRuleValidationException("Error while decrypting string");
        }
    }

This is the C# Code i used to encrypt / Decrypt , GetPublicKey() returns the public key to UI Side, I cannot find a way to encrypt a string with the public key, tried converting it to pem format etc, Nothing seems to work, I need the code equvalent to ` public static

string Encrypt(string plaintext)
    {
        using (RSA rsa = RSA.Create())
        {
            rsa.FromXmlString(publicKey);
            byte[] dataToEncrypt = Encoding.UTF8.GetBytes(plaintext);
            byte[] encryptedData = rsa.Encrypt(dataToEncrypt, 
            RSAEncryptionPadding.OaepSHA512);
            return Convert.ToHexString(encryptedData);
        }
    }

in Javascript

Testing async state changes in react hook with react @testing-library/react

I have a react hook, that basically maintain loading state and data state and returns its current values. On initial load fetches some data a and sets data state and loading state. Very basic stuff.
Implementation looks like this:

export const usePeopleListAPIService = ({requestQueryParams}) => {
    const apiClient = useApiClient();
    const [loadingState, setLoadingState] = React.useState<PeopleListLoadingState>('initial');
    const [data, setData] = React.useState<PeopleListData>({
        totalCount: 0,
        pageCount: -1,
        rows: [],
    });

    React.useEffect(() => {
        setLoadingState('loading');
        (async () => {
            const response = await apiClient.GET('/api/people', {
                params: {
                    query: requestQueryParams,
                },
            });

            handleResponse(response, {               
                successHandler: (data) => {
                    setLoadingState('success');
                    setData({
                        pageCount: data.pageMetadata?.totalPages ?? 0,
                        totalCount: data.pageMetadata?.totalElements ?? 0,
                        rows: data?.items ?? [],
                    });
                },
                errorHandler: () => {
                    setLoadingState('error');
                },
            });
            return;
        })();
    }, [requestQueryParams]);

    return {
        loadingState,
        data,
    };
}

Everything works fine in browser, but now I want to write unit test. I use Vitest and @testing-library/react. I also use MSW for request interception.

My test looks like this:

 const { result } = renderHook(
            () =>
                usePeopleListAPIService({ requestQueryParams}),
            {
                wrapper: ProvidersWrapper,
            }
        );

    await waitFor(() => {
        expect(result.current.data).toEqual({
            totalCount: peopleEndpointResponse.pageMetadata.totalElements,
            pageCount: peopleEndpointResponse.pageMetadata.totalPages,
            rows: peopleEndpointResponse.items,
        });
    });

    await waitFor(() => {
        expect(result.current.loadingState).toEqual('success');
    });

While the first assertion passes without problems there is some problem with the second one. It never passes and there appears to be lot of rerendering happening. The state itself appears to be set accordingly inside the hook, but the return value of loadingState does not change over time in this testing environment. How is this possible ?

I use version 14.1.2 of @testing-library/react and version 0.34.6 o vitest

Thanks for any advice.

GSAP fade on scroll

I am trying to create a fade out animation using GSAP Scroll Trigger, where the page first scrolls across the X axis of the title before scrolling up and fading out, for the most part i have it working but the title only fades to about 50%, I have tried messing around with duration and scrub but to be honest, I am a bit lost. any help/info will be appreciated.

Here is the GSAP JavaScript and Vue/HTML code:


//___________________________________________________ Title Scrolling
    const titles = document.querySelector('.titles')

    function getScrollAmount() {
      let titlesWidth = titles.scrollWidth
      return -(titlesWidth - window.innerWidth)
    }

    const tween = gsap.to('.titles', {
      x: getScrollAmount,
      duration: 3,
      ease: 'none'
    })
    const scrollOut = gsap.fromTo(
      '.titles',
      {
        ease: 'none',
        opacity: 1
      },
      {
        ease: 'none',
        opacity: 0
      }
    )

    ScrollTrigger.create({
      trigger: '.titleWrapper',
      start: 'top top',
      end: () => `+=${getScrollAmount() * -1}`,
      pin: true,
      animation: tween,
      scrub: 1,
      invalidateOnRefresh: true,
      markers: false
    })

    ScrollTrigger.create({
      trigger: '.titleWrapper',
      start: 'bottom bottom',
      end: '140%',
      scrub: 0,
      animation: scrollOut,
      markers: true
    })






<div class="titleWrapper isolate">
      <div class="titles w-fit h-screen bg-white flex flex-nowrap flex-none items-center">
        <h1
          class="firstTitle z-40 w-screen text-black flex justify-center font-black headerSizing tracking-tighter cursor-default select-none translate-y-[15vh]"
        >
          fName
        </h1>
        <h1
          class="secondTitle text-black w-fit flex justify-center z-40 font-medium headerSizing tracking-tighter cursor-default select-none translate-y-[15vh] pl-40 pr-64"
        >
          sName
        </h1>
      </div>
    </div>

I have played around with GSAP but failed to get anything working so far.

Getting error “NativeModule: AsyncStorage is null” while using jest.test

I get this error while using jest.test. How can I fix it?

FAIL  __tests__/App.test.js

● Test suite failed to run

[@RNC/AsyncStorage]: NativeModule: AsyncStorage is null.

To fix this issue try these steps:

  • Uninstall, rebuild and restart the app.

  • Run the packager with `--reset-cache` flag.

  • If you are using CocoaPods on iOS, run `pod install` in the `ios` directory, then rebuild and re-run the app.

  • Make sure your project's `package.json` depends on `@react-native-async-storage/async-storage`, even if you only depend on it indirectly through other dependencies. CLI only autolinks native modules found in your `package.json`.

  • If this happens while testing with Jest, check out how to integrate AsyncStorage here: https://react-native-async-storage.github.io/async-storage/docs/advanced/jest

If none of these fix the issue, please open an issue on the GitHub repository: https://github.com/react-native-async-storage/async-storage/issues

  4 | //   AsyncStorage
  5 | // } from 'react-native';
> 6 | import AsyncStorage from '@react-native-async-storage/async-storage'
    | ^