I want to build a Custom React Select component where I can have a checkbox in front of the option and Select All option with intermidate property

I am building a react component where I want a input field with the dropdown , when I type in field a dropdown open and each option have checkbox in front of it and when a user check the checkbox , it value is stored in input filed along with close icon.It also have select All option which will be shown intermediate sign when fewer is selected and checked when all are selected.I want this functionality to work properly as I am facing several problem.I am building this component to work with formik form and dropdown open on select on formSelect dropdown

Here is my Code.

 import React, { useState, useEffect, useRef, ReactNode } from 'react'
import { FieldFeedbackLabel } from '../../../../_metronic/partials/controls';
interface MultiSelectComponentProps {
    name: string;
    label: string;
    required: boolean;
    type: string
    id: string;
    field: {
        name: string;
        value: any;
        onChange: (event: any) => void;
        onBlur: (event: any) => void;
    };
    form: {
        touched: { [name: string]: boolean };
        errors: { [name: string]: string };
        setFieldValue: (field: string, value: any, shouldValidate?: boolean) => void;

    };
    allowMultiSelect: boolean;
    withFeedbackLabel?: boolean;
    customFeedbackLabel?: string;
    options: string[];
    onChange: (selectedOptions: string[]) => void;
}
const getFieldCSSClasses = (touched: boolean, errors: string): string => {
    const classes = ["form-control form-control-lg form-control-solid mb-3"];

    if (touched && errors) {
        classes.push("is-invalid");
    }

    if (touched && !errors) {
        classes.push("is-valid");
    }

    return classes.join(" ");
};
export default function MultiSelectDropdown({ name,
    label,
    required,
    id,
    field,
    type = 'select',
    form: { touched, errors, setFieldValue },
    withFeedbackLabel = true,
    customFeedbackLabel,
    options,
    onChange,
    allowMultiSelect = true,
    ...props
}: MultiSelectComponentProps) {
    const [selectedOptions, setSelectedOptions] = useState<string[]>([]);
    const [searchTerm, setSearchTerm] = useState<string>('');
    const [filteredOptions, setFilteredOptions] = useState<string[]>(options);
    const [selectAll, setSelectAll] = useState(false);
    const divRef = useRef<HTMLDivElement | null>(null);
    const indetSetter = React.useCallback((el: any) => {
        if (el && selectedOptions.length && !selectAll) {
            el.indeterminate = true;
            el.checked = false
        }else if(el &&(selectAll||selectedOptions.length ===filteredOptions.length)){
            el.indeterminate = false;
            el.checked = true
        }
    }, [selectedOptions,selectAll,filteredOptions.length]);
    const toggleOption = (option: string) => {
        const isSelected = selectedOptions.includes(option);

        if (isSelected) {
            setSelectedOptions(selectedOptions.filter((item) => item !== option));
        } else {
            if (allowMultiSelect) {
                setSelectedOptions([...selectedOptions, option]);
            } else {
                setSelectedOptions([option]);
            }
        }
        setSelectAll(false)
    };
    const handleSelectAllChange = () => {
        if (selectAll) {
            setSelectedOptions([]);
        } else {
            setSelectedOptions([...filteredOptions]);
        }
        setSelectAll(!selectAll);
    };

    const renderSelectedOptions = () => {
        if (selectedOptions.length === 0) {
            return null;
        }

        return (
            <div className="selected-option">
                {selectedOptions.map((option) => (
                    <span key={option} className="selected-option">
                        {option}
                        <span
                            className="remove-option"
                            onClick={() => toggleOption(option)}
                        >
                            &#10005;
                        </span>
                    </span>
                ))}
            </div>
        );
    };

    const handleSearchChange = () => {
        const searchText = divRef.current?.textContent
        if (searchText) {
            setSearchTerm(searchText);
        } else {
            setSearchTerm('')
        }

    };
    useEffect(() => {
        const filtered = options.filter((option) =>
            option.toLowerCase().includes(searchTerm.toLowerCase())
        );
        setFilteredOptions(filtered);
    }, [searchTerm, options]);
    useEffect(() => {
        setFieldValue(field.name, selectedOptions)
    }, [selectedOptions])
    return (
        <>
            <div className="multi-select-dropdown">
                {label && <label className="fw-bold fs-6">Select {label}</label>}
                {required && <span style={{ color: "red" }}>*</span>}
{/* eslint-disable-next-line jsx-a11y/no-static-element-interactions */}
                <div
                    className="editable-div form-control form-control-lg form-control-solid mb-3"
                    contentEditable="true"
                    ref={divRef}
                    onInput={handleSearchChange}
                >
                    <div className="selected-options"
                        contentEditable="false"

                    >{renderSelectedOptions()}</div>


                </div>
                <input
                    type='hidden'
                    name={field.name}
                    className={getFieldCSSClasses(touched[field.name], errors[field.name])}
                    value={selectedOptions}
                />


                {searchTerm && (
                    <>
                        <div className="dropdown-options dropdown-content">
                            {allowMultiSelect && (<>
                                <div className="dropdown-header">
                                    <input
                                        type="checkbox"
                                        ref={indetSetter}
                                         checked={selectAll||selectedOptions.length===filteredOptions.length}
                                        onChange={handleSelectAllChange}
                                    /><span>Select All</span>
                                </div>
                            </>)}

                            {filteredOptions.map((option) => (
                                <div key={option} className="option">
                                    <input
                                        type="checkbox"
                                        value={option}
                                        checked={selectedOptions.includes(option)}
                                        onChange={() => toggleOption(option)}
                                    />
                                    <span className='dropdown-option-value'>{option}</span>
                                </div>
                            ))}
                        </div>
                    </>
                )}
            </div>
            {withFeedbackLabel && (
                <FieldFeedbackLabel
                    error={errors[field.name]}
                    touched={touched[field.name]}
                    label={label}
                    type={type}
                    customFeedbackLabel={customFeedbackLabel}
                />
            )}
        </>
    )
}

I tried different react packages like react-select and multiselect-react-dropdown and other but It doesn’t fullfill all the requirement like Showing it intermidate selected checkbox

How to Implement AES-256-GCM Encryption in JavaScript (Web Browser Environment)

I’m working on a project that requires encrypting and decrypting data in the front-end using the AES GCM 256 mode. The back-end team has provided detailed documentation and a Python script for encryption and decryption. Here are the relevant details:

Encryption Steps:

  1. Construct the request as an XML document.
  2. Retrieve a 32-character private access code.
  3. Generate a 12-byte random string as the Initialization Vector (IV).
  4. Create an output buffer with the length of the input request message + 12 + 16. The first twelve bytes represent the IV, and the next sixteen bytes are the authentication tag (AES block size).
  5. Encrypt the data using an AES GCM 256 routine with the access code as the encryption key. Pass in the IV, authentication tag, and data as an array of bytes.
  6. Encode the entire buffer using base64.

Decryption Steps:

  1. Decode the buffer from base64.
  2. Retrieve the 32-character private access code.
  3. Decrypt the data using AES GCM 256 with the access code as the encryption key. Provide the IV, authentication tag, data, and an output buffer for decrypted data.
  4. The decrypted buffer should be an XML document containing the response.

Here’s the Python script provided for reference:

def encrypt(key, plain_text):
    iv = secrets.token_bytes(12)
    cipher = AES.new(key.encode('utf-8'), AES.MODE_GCM, iv)
    ciphertext, auth = cipher.encrypt_and_digest(plain_text.encode("utf-8"))
    return b64encode(iv + auth + ciphertext).decode("ascii")

def decrypt(key, encrypted_text):
    in_buffer = b64decode(encrypted_text)
    iv = in_buffer[0:12]
    auth = in_buffer[12:28]
    cipher = AES.new(key.encode('utf-8'), AES.MODE_GCM, iv)
    dec = cipher.decrypt_and_verify(in_buffer[28:], auth)
    return dec.decode('utf-8')

I’ve attempted to implement this encryption and decryption process in the front-end using various methods and libraries, including the built-in Web Crypto API and the CryptoJS library. However, I’ve encountered issues as CryptoJS doesn’t support GCM mode (reference: GitHub Issue).

Could someone please provide guidance or a code example for achieving encryption and decryption in the front-end using AES GCM 256 mode? Any help would be greatly appreciated.

Thank you!

blazor retrieving base64 string from js code which displays an image

i am using this js:

window.previewImage = (inputElem, imgElem) => {
    const url = URL.createObjectURL(inputElem.files[0]);
    imgElem.addEventListener('load', () => URL.revokeObjectURL(url), { once: true });
    imgElem.src = url;
}

with this razor file:

@inject IJSRuntime JS


<InputFile @ref="inputFile" OnChange="@ShowPreview" />
<img id="capturedImage" style="max-width:400px;max-height:400px" @ref="previewImageElem" />

    @code {
        private InputFile? inputFile;
        private ElementReference previewImageElem;
        private string base64Image = "";
    
    
        private async Task ShowPreview() => await JS.InvokeVoidAsync(
            "previewImage", inputFile!.Element, previewImageElem);
    
    
    }

this displays the images just fine, however in order to upload it to our server I need to be able to access the image from c# code and put it into a base64 string.

How can I achieve that?

Sending uploaded file from JS to Python CGI always results in ampty dictionary

I have an HTML form that has a file input element. When submitting the form, a JS function is executed which checks if the uploaded file is a PDF file and is less than 10MB. All of this works correctly and the correct filesize is logged in the console.

Then the JS function sends the file to the Python server through an HTTP POST request. However, the sent file is always an empty object / dictionary. When I console.log(file); before it is sent, all the file data is logged but when I look at the Network tab in the inspector, it’s just an empty object / dictionary:

enter image description here

However, when I change my HTML form so it sends the data directly to the Python CGI script without calling the JS function first, it works perfectly.

Here’s my HTML code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="./js/new.js"></script>

    <title>test</title>
  </head>
  <body>
    <script></script>
    <header>
      <h1>File upload test</h1>
    </header>
    <main>
      <fieldset>
        <form
          action="javascript:addFile()"
          id="DataForm"
        >
          <div>
            <label for="file_contract">contract:</label
            ><input
              type="file"
              accept="application/pdf"
              id="file_contract"
              name="file_contract"
            />
          </div>
          <button type="button" class="outlined" onclick="cancel()">
            Annuleer
          </button>

          <input type="submit" value="Bewaar" />
        </form>
      </fieldset>
    </main>
    <script>
      function cancel() {
        const host = window.location.host;
        const redirectUrl = `http://${host}`;
        window.location.replace(redirectUrl);
      }
    </script>
  </body>
</html>

JavaScript code:

async function addFile() {
  const formData = new FormData(document.forms["DataForm"]);
  // get uploaded files
  // Function to check and append a file to the formData
  function handleFileUpload(fileInputId) {
    console.log("uploading file...");
    const fileInput = document.getElementById(fileInputId);
    const file = fileInput.files[0];

    // Check if a file is selected

    // Ensure the file is a PDF
    if (file.type === "application/pdf") {
      console.log(`filesize = ${file.size}`);
      // 10MB in bytes
      formData.append(fileInputId, fileInput.files[0]);
    }

    return true;
  }

  // Handle each file upload separately
  if (!handleFileUpload("file_contract")) {
    console.log("form submission prevented");
    return false; // Prevent form submission
  }

  const data = {
    answers: Object.fromEntries(formData),
  };

  console.log(data["answers"]["file_contract"]);

  try {
    const response = await fetch("../../cgi-bin/addRecord.py", {
      method: "POST",
      headers: {
        "Content-type": "application/json; charset=UTF-8",
      },
      body: JSON.stringify(data),
    });

    const responseData = await response.json();

    if (responseData.hasOwnProperty("status")) {
      if (responseData["status"] === "failed") {
        // session is invalid / expired
        alert("Login sessie vervallen. Log opnieuw in.");
      } else if (responseData.status === "success") {
        const host = window.location.host;
        const redirectUrl = `http://${host}`;
        console.log("redirecting... (commented out)");
        // window.location.replace(redirectUrl);
      } else {
        alert(
          "Fout bij het opslaan. Probeer het nog eens of contacteer Sandra."
        );
      }
    }
  } catch (error) {
    console.error(error);
    alert("Fout bij het opslaan. Probeer het nog eens of contacteer Sandra.");
  }
}

Python CGI:

#!/usr/bin/env python3

import cgi
import hashlib
import json
import os
import sys
import logging

# Get the absolute path of the current script
dirname = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

if os.path.exists(f'{dirname + "/log.log"}'):
    # If it exists, open it in write mode to clear its contents
    with open(f'{dirname + "/log.log"}', 'w'):
        pass

logging.basicConfig(filename=f'{dirname + "/log.log"}', level=logging.DEBUG)


def generate_response(status, data=None):
    response = {"status": status}
    if data:
        response["data"] = data

    print("Content-Type: application/json")
    print()
    print(json.dumps(response))


def calculate_file_hash(file_data):
    # Create an MD5 hash object
    md5_hash = hashlib.md5()

    # Read the file data in chunks to efficiently handle large files
    for chunk in iter(lambda: file_data.read(4096), b''):
        md5_hash.update(chunk)

    # Return the hexadecimal representation of the MD5 hash
    return md5_hash.hexdigest()


def main():
    # read form data from HTTP POST request
    data = sys.stdin.read(int(os.environ.get('CONTENT_LENGTH', 0)))
    post_data = json.loads(data)

    answers = post_data["answers"]

    logging.debug(str(answers))

    if "file_contract" in answers:
        contract_file = answers['file_contract']
        contract_file_filename = contract_file.filename
        contract_file_hash = calculate_file_hash(contract_file.file)
        # save the file data to the werkmap
        # Save the PDF file to a folder
        contract_filename_path = os.path.join(dirname, "documenten", contract_file_hash)
        with open(contract_filename_path, 'wb') as contract_file_handle:
            contract_file_handle.write(contract_file.file.read())

    generate_response("success")


if __name__ == "__main__":
    main()

Angular PWA Not Working on iOS – Service Worker Errors

I have an Angular app that I’ve converted into a Progressive Web App (PWA) for mobile. It works perfectly fine on Android devices, but I’m encountering issues on iOS. Sometimes, the webpage doesn’t open, and the service worker console is full of errors like this: errors

Additionally, when the webpage doesn’t load, I see a blank screen with the following error:

error screen on mobile

I’ve been searching for information online, but I haven’t been able to find any solutions or similar cases. I’m not sure what might be causing these issues specifically on iOS.

Can anyone provide guidance on what could be causing these errors on iOS and how to resolve them? I’m open to suggestions and insights. Thank you in advance for your help!

Firefox takes time to fire canplaythrough event

Why firefox takes time to emmit canplaythrough event as compared to other browser with same code base and videos and sometimes does not emmit at all.

This is the code

  function loadLeftVideo() {
    video1.load();
    video1.addEventListener("canplaythrough", function () {
      console.log("Video 1 canplaythrough");
      video1Loaded = true;
    });
  }

Database table filtered autocomplete input data according to selected field

I want to show filtered data as an autocomplete input according the selected by userId in an input field. I have userId, data fields in database table. In the page, when user enters a data to an input field I want to show only this user’s data fields as an autocomplete field. How can I do this. I hope I clarified the problem.

The following code works without filtering:

 <%@ Control Language="C#" AutoEventWireup="true" 
CodeFile="AutoCompleteParameterTextBox.ascx.cs"       Inherits="AutoCompleteParameterTextBox" %> 
<script type="text/javascript">
jQuery(function ($) {
    try {
        if ($('script[src="/Assets/js/jquery-ui-1.10.4.custom.min.js"]').length == 0) {
            var s = document.createElement("script");
            s.type = "text/javascript";
            s.src = "/Assets/js/jquery-ui-1.10.4.custom.min.js";
            $("body").append(s);
        }
        if ($('link[href="/Assets/css/jquery-ui.min.css"]').length == 0) {
            $("head").append('<link rel="stylesheet" href="/Assets/css/jquery-ui.min.css" 
 type="text/css" />');
        }
    }
    catch (err) {
    }
});

function CallServer() {
    <%=PostBackScript%>
}

function stripNonAlphaNumeric(string) {
    var r = string.toLowerCase();
    r = r.replace(new RegExp("[^A-z0-9şŞıİçÇöÖüÜĞğ.,-/() ]", 'g'), "");
    return r;
}

var initAutoComplete
    = (function () {
        $(function () {
            $("#<%=txt.ClientID%>").autocomplete({
                source: function (request, response) {
                    var hiddenInputValueName = $("#<%=hdnRadioId.ClientID %>").val();
                    if (hiddenInputValueName) {
                        var inputValue = $('input[name$="' + hiddenInputValueName + 
     '"]:checked').val();
                        if (inputValue) request.term = inputValue + '-' + request.term;
                        else {
                            $("#<%=txt.ClientID%>").val('');
                            return false;
                        }
                    }

                    var host = "";

                    if (window.location.hostname == "localhost") {
                        host = '<%=GetBaseUrl()%>';
                    }
                    else {
                        host = window.location.protocol + "//" + window.location.host;
                    }
                    var parametertable = '<%=ParameterTable%>';

                    if ((hiddenInputValueName && request.term.substr(2).trim() === '') || 
    (!hiddenInputValueName && request.term.trim() === '')) response(null);
                    else {
                        $.ajax({
                            url: host + "/api/parameterapi/" + parametertable + "/" +

    stripNonAlphaNumeric(request.term),
                            dataType: "json",
                            success: function (data) {
                                response($.map(data, function (item) {
                                    return {
                                        label: item.Aciklama,
                                        value: item.KayitNo
                                    }
                                }));
                            }
                        });
                    }
                },
                autoFill: true,
                minLength: 3,
                delay: 300,
                select: function (event, ui) {
                    $("#<%=txt.ClientID %>").val(ui.item.label);
                    $("#<%=hdn.ClientID %>").val(ui.item.value.toString());
                    CallServer();
                    return false;
                },
                focus: function (event, ui) {
                    $("#<%=txt.ClientID %>").val(ui.item.label);
                    return false;
                },
                change: function (event, ui) {
                    $("#<%=hdn.ClientID %>").val(ui.item ? ui.item.value : "");
                },
                open: function () {
                    $(this).removeClass("ui-corner-all").addClass("ui-corner-top");
                },
                close: function () {
                    $(this).removeClass("ui-corner-top").addClass("ui-corner-all");
                },
                error: function (response) {
                    alert(response.responseText);
                },
                failure: function (response) {
                    alert(response.responseText);
                }
            }).blur(function () {
                //$(this).autocomplete("close");
            }).data("ui-autocomplete")._renderItem = function (ul, item) {
                var newText = String(item.label).replace(
                    new RegExp(this.term, "gi"),
                    "<span class='ui-state-highlight'>$&</span>");

                return $("<li></li>")
                    .data("item.autocomplete", item)
                    .append("<a>" + newText + "</a>")
                    .appendTo(ul);
            };
        });
    });

    if (undefined === window.Sys) {
        initAutoComplete();
    }
    else {
          Sys.Application.add_load(function (s, e) {
            initAutoComplete();
        });
       }
  </script>
  <asp:TextBox runat="server" ID="txt" CssClass="input-xlarge"></asp:TextBox>
  <asp:Label runat="server" ID="lblRequired" CssClass="REQUIRED" Text="*" Visible="false" />
  <asp:HiddenField runat="server" ID="hdn" />
  <asp:HiddenField runat="server" ID="hdnParameterTable" />
  <asp:HiddenField runat="server" ID="hdnRadioId" />
  <span><small>
    <asp:Label runat="server" ID="lbl">Üç Harf Giriniz.</asp:Label></small></span>

Click event gets removed when clicking button – Vue / Vuetify

I am creating a dialog with Vuetify. The button should open a dialog and that’s basically that. It’s also possible to close the dialog after finishing business. When closing the dialog in development, we can just open the dialog again. But in production environment, we cannot open the dialog more than once.

I have found the cause, or at least what I believe to be the cause of this; The click event gets removed from the DOM/Window when clicking the button the first time – ONLY in production.

This is not happening in development environment.

I had an idea, that some of the old code in our project is doing something, but can’t seem to find the culprit…

So I wanted to hear you out, if this has ever happened to anyone before? 🙂

Our tech is:

  • Vue 2
  • Vuetify 2.7
  • some old jQuery

Let me know if you need some more code.

Modal container:

<template>
  <div>
    <v-tooltip left>
      <template #activator="{ on, attrs }">
        <v-btn
          class="o-page-sidebar__button create-project__button"
          color="#009688"
          dark
          depressed
          tile
          v-bind="attrs"
          v-on="on"
          @click="triggerModal(undefined)"
        >
          <v-icon size="16">
            fal fa-clipboard-list
          </v-icon>
        </v-btn>
      </template>
      <span>{{ translations.title }}</span>
    </v-tooltip>

    <CreateProjectModal
      v-if="showModal"
      v-bind="$attrs"
      v-model="showModal"
      :translations="translations"
      @hasEditedProject="handleHasEditedProject"
      @hasCreatedProject="handleHasCreatedProject"
    />
  </div>
</template>

<script>
export default {
  data() {
    return {
      showModal: false,
    };
  },
  methods: {
    triggerModal(eventObject) {
      if (eventObject == undefined) {
        eventObject = {};
      }

      const localStorageValue = localStorage.useNewCreateProjectDialog != undefined ? localStorage.useNewCreateProjectDialog == 'true' : true;

      const openRequest = {
        Type: eventObject.type,
        ProjectID: eventObject.projectID,
        OfferID: eventObject.offerID,
        DebtorID: eventObject.debtorID,
        FitterID: eventObject.fitterID,
        ManagerID: eventObject.managerID,
        PlanningStartDate: eventObject.planningStartDate,
        PlanningEndDate: eventObject.planningEndDate
      };

      this.notification.show = false;

      if (localStorageValue) {
        const type = eventObject.type ? eventObject.type : 'CreateProject';

        openRequest.Type = this.openProjectDialogEnum.find(x => x.Name == type)?.Name;

        this.$store.dispatch('setOpenRequest', openRequest);

        this.$store.dispatch('setHasInitializedFields', {
          'MainProjectID': false,
          'OfferID': false,
          'ProjectDebtorID': openRequest.Type != 'EditProject',
          'ProjectGroupID': openRequest.Type != 'EditProject'
        });

        this.showModal = true;
      }
    }
}
</script>

Modal component:

<template>
  <v-dialog
    v-model="show"
    :class="{ 'new-create-project' : show }"
    fullscreen
    :retain-focus="false"
    hide-overlay
    persistent
    no-click-animation
    height="100vh"
    transition="dialog-bottom-transition"
    @keydown.esc="confirmClose"
  >
    {{ ... }}
  </v-dialog>
</template>

<script>
export default {
  props: {
    value: {
      type: Boolean,
      default: false
    },
  },
  computed: {
    show: {
      get() {
        return this.value;
      },
      set(value) {
        if (!value) {
          this.$store.dispatch('setNotifications', []);
          this.$store.dispatch('setSelectedDebtor', null);
          this.$store.dispatch('emptyErrors');
        }

        this.$store.dispatch('resetProjectData');
        this.$emit('input', value);
      }
    },
  }
}
</script>

How to call the update function from service_worker inside a chrome extension?

I have absolutely no experience in JS, but I have a task to write an extension for Chrome that would go to the site every 10 min and inform if I have new messages.

I have a popup.html in which I include a JS file with a refresh() function that goes to the site and if there are new messages there changes the div with id=text to a link. This part works.
Now I created a service_worker in which I pasted the code that prints “alarm” to the console every minute. This works too.

How can I make the service_worker call the refresh function, which will update the div?

I couldn’t import it. I tried to copy the function into the service_worker file, but it turned out that there was no access to the window and DOMParser.

Inside popup.js there is code that responds to button clicks. Do you need to generate something similar using service_worker so that refresh() is executed from there?

manifest.json

{
  "manifest_version": 3,
  "background": {
    "service_worker": "worker.js",
    "type": "module"
  },
  "action": {
    "default_popup": "popup.html"
  },
    "permissions": [
        "alarms"
    ],
    "host_permissions": [
    "*://example.com/*",    
  ]
}

popup.html

<html>
  <script type="module" src="popup.js"></script>
  <body>
    <div style="width:300px;padding:0;">
      <button type="button" id="button">Refresh</button>
      <div id='text' style="width:300px;padding:20 0 20;">
      </div>
    </div>
  </body>
</html>

popup.js

function loadXMLDoc(myurl, cb) 
{
   var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
    xhr.onreadystatechange = function()
    {
        if (xhr.readyState == 4 && xhr.status == 200)
        {
            if (typeof cb === 'function') cb(xhr.responseText);
        }
    }
   xhr.open("GET", myurl, true);
   xhr.send();

}

function refresh()
{
    loadXMLDoc('http://example.com/', function(responseText) {
//many staff here
        document.getElementById("text").innerHTML = echo
    });
}

window.onload = async () => {
    document.getElementById('button').onclick = () => {
            refresh()
        };
    };

worker.js

chrome.alarms.onAlarm.addListener(a => {
  console.log('Alarm! Alarm!', a);
});

chrome.runtime.onInstalled.addListener(() => {
  chrome.alarms.get('alarm', a => {
    if (!a) {  
      chrome.alarms.create('alarm', {periodInMinutes: 1});
    }
  });
});

My Nodejs function is returning an Undefined instead of a value

`

function summation(num, args=0) {

    let value = args;
    value += num;
    num -= 1;
    if(num == 0){
        return value;
    }
    summation(num, value);

}
console.log(summation(3));

the function summation is sort of a factorial that calculates numbers from 1 to num and adds them to total.
The function calls itself and keeps adding the subsequent numbers from zero to the provided number until its zero, then it returns value.
if I pass 3 into the function, the function should return 6 however, im getting an undefined. I used a breakpoint in vs code to check what exactly the function is doing, and 6 is actually stored in value at the last point however, the 6 suddenly turns into an undefined right on the return statement.

This condition will always return ‘false’ since JavaScript compares objects by reference, not value, what does this mean in the current Scenario?

in TS 4.9.3 and angular 15 application, i have a service function isEmpty() with following snippet of code.

    static isEmpty(value: any): boolean {
        if (value === null || value === undefined || value === {} || value === []) { 
            return true;
        }
    }

and it generates This condition will always return 'false' since JavaScript compares objects by reference, not value. issue for conditions value === {} and value === [].

I want to decode aes encrypted data in Javascript in python in aws

I have a Javascript-AES encrypted value that I want to decode in python with cryptography library how can I do that?
I tried it with pycrypto library by adding it as layer but the import fails with some .so error. Later, I figured that pycrypto has become obsolete.
Can someone help me decrypt the following value “U2FsdGVkX1+i0YtqcKW4tsI3witHU65dqIkgYGptHT0=” in python so it can be used in lambda aws.

Issue with Firestore doc function inside a forEach loop

I’m currently working on a project that involves moving data from one Firestore collection to another using JavaScript and the Firebase SDK. I’ve encountered an issue when trying to use the doc function inside a forEach loop.

Here’s a simplified version of the code I’m using:

// Import necessary Firebase libraries and initialize Firebase app

async function moveData() {
const db = getFirestore(app);
const sourceCollectionRef = collection(db, 'sourceCollection');
const targetCollectionRef = collection(db, 'targetCollection');

const querySnapshot = await getDocs(sourceCollectionRef);

querySnapshot.forEach(async (doc) => {
const docId = doc.id;
const targetDocRef = doc(targetCollectionRef, docId); // This line doesn't work

    // Some logic to manipulate data
    
    // Attempt to set data to targetDocRef
    await setDoc(targetDocRef, /* modified data */);

});
}

The issue I’m facing is that the doc function doesn’t seem to work inside the forEach loop. I’m receiving an error saying that doc is not a function.

I’ve tried various approaches, including defining targetDocRef outside of the loop and passing docId as a parameter to it, but I still face the same issue.

What I Tried:

  1. Inside the forEach loop, I attempted to use the doc function to create a reference to a document in Firestore’s target collection.
  2. I passed the targetCollectionRef and the docId as arguments to the doc function, expecting it to return a reference to the target document.
  3. I then attempted to use setDoc to set data to the target document.

I was expecting that this code would create a reference to the target document for each document in the source collection and allow me to set data to the target documents.

However, I encountered an issue where the doc function inside the forEach loop was not recognized, and I received an error saying that doc is not a function.

I’m looking for an alternative solution or insights on how to correctly reference documents inside a loop in Firestore using JavaScript and the Firebase SDK.

Dom to image and wordpress upload

I have a php file in my wordpress theme folder, along with its script js, which on load generates an image. It also downloads the image to the device.
I would like also the image generated, to be uploaded in wordpress uploads folder, or other folder in order to use this afterwards, for other purposes
Any ideas how to manage this?