Below Function in my Chrome Extension returns undefined instead of true/false [duplicate]

I’ve created below function to check duplicate object in my chrome extension project. But It is returning undefined. True or False is expected.

function checkDuplicate(obj){
    chrome.storage.local.get("savedContent", (savedContent) => {
        savedContent.savedContent.forEach((item) => {
            if(item.link === obj.link) {
                console.log('duplicateFound', true);
                return true;
            }
        })
        return false;
    });
}

How can I recreate this scrollbox?

I want to recreate the “try-it” section on this website: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior. I have a similar aspect of this I want to use but I’m trying to understand how the scrollbox links in that website does not move the entire webpage.

I tried to recreate something similar to this but when I click the links it moves the entire webpage then goes to the desired section on the scrollbox.

Copy flourish studio bar chart race names

I created a bar chart race for sample in flourish studio website that following is link of my chart:

https://public.flourish.studio/visualisation/15565937/

Now I want to copy all left side country names in a text file.
Note that some names appear during chart changes and I want to collect all names that available in this bar chart.

Do you have any idea to do this?
note that I don’t request free script or code, I need only idea and help to create my script. for example I want to know that what programming language can do this and how?

Error in SSO in Microsoft Teams React App

So I am making Microsoft Teams Tab with React, and there is required of SSO

I have gone through many video and article about SSO in teams Tab, but I go confused, I some video they say SSO required both client and server side for SSO, but there is JS library for SSO which run only on client side and completes the SSO, but this method not work, when open in Teams Tab.
But work on web page open in browser directly.

I go through video and articles about SSO but nothing helps, I need article how to do SSO in Teams Tab with React

Firebase Firestore doc.data() doesn’t return anything

I’m implementing a firebase function that takes metadata from a store in firestore, then get all files of that store folder in storage and compares this data with the one stored in the metadata. If some condition applies it sends an email to indicate that theres a possible incident to attend.

It was working just fine. However, since I added the Firebase trigger mail extension it crashed. Now, when I call the doc.data() function in order to get the data from a document, it returns empty, and I can’t get the files count from storage anymore.

This is the code I use atm:

const db = getFirestore();
const bucket = getStorage().bucket();

exports.checkSanity = onSchedule(
  { schedule: "every 1 minutes", memory: "4GiB" },
  async (event) => {
    const subwayRef = db.collection("subway");
    const snapshot = await subwayRef.get();

    logger.log("snapshot: ", snapshot);

    const docs = [];

    snapshot.forEach((doc) => {
      docs.push(doc);
      logger.log("doc: ", doc);
    });

    // array of stores to notify
    let toNotifyFail = [];
    let toNotifySuccess = [];
    for (const doc of docs) {
      const data = doc.data();
      logger.log("data: ", data);

      const {
        id,
        name,
        openHour,
        closeHour,
        status,
        notified,
        lastTotalCount,
      } = data;

      const docRef = db.collection("subway").doc(id);

      logger.log("[INFO] Showing stores configs");
      logger.log(
        `${doc.id} => ${data.name}, ${data.openHour}, ${data.closeHour}, ${data.status}, ${data.notified}, ${data.notified_at}, ${data.lastTotalCount}`
      );

      logger.log("before");
      // get last bucket total count
      const [files] = await bucket.getFiles({ prefix: `${name}` });
      logger.log("after...");

      logger.log(`${name} => contains ${files.length}`);

      if (lastTotalCount != 0) {
        // get current hour
        const date = new Date();
        if (
          true /*date.getHours() >= openHour && date.getHours() < closeHour*/
        ) {
          if (!notified && lastTotalCount == files.length) {
            // update store
            await docRef.update({
              notified: true,
              notified_at: date.toString(),
              status: "paused",
            });

            // add to notifications email
            toNotifyFail.push(`<li>${name}</li>`);
          }

          // store back to normal
          if (notified && lastTotalCount < files.length) {
            // update store
            await docRef.update({
              notified: false,
              notified_at: date.toString(),
              status: "capturing",
            });

            toNotifySuccess.push(`<li>${name}</li>`);
          }
        }
      }

      await docRef.update({
        lastTotalCount: files.length,
      });
    }

    // notify
    if (toNotifyFail.length > 0) {
      await db.collection("mail").add({
        to: ["***", "****"],
        message: {
          subject: "Nuevo fallo detectado en subway-counting",
          text: "Se ha detectado un nuevo fallo en una o mas tiendas",
          html: `Las siguientes tiendas han dejado de enviar datos: <br> <ul>${toNotifyFail.join()}</ul>`,
        },
      });
    }

    if (toNotifySuccess.length > 0) {
      await db.collection("mail").add({
        to: ["***", "***"],
        message: {
          subject: "Nuevo fix en subway-counting",
          text: "Una o mas tiendas han vuelto a funcionar con normalidad",
          html: `Las siguientes tiendas han vuelto a enviar datos: <br> <ul>${toNotifySuccess.join()}</ul>`,
        },
      });
    }
  }
);

And the error I get from the logger is:

Error: Value for argument "documentPath" is not a valid resource path. Path must be a non-empty string.
    at entryFromArgs (/workspace/node_modules/firebase-functions/lib/logger/index.js:130:19)
    at Object.error (/workspace/node_modules/firebase-functions/lib/logger/index.js:116:11)
    at httpFunc (/workspace/node_modules/firebase-functions/lib/v2/providers/scheduler.js:71:20)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Most surely because I’m not sending any value as prefix to the storage, or the id to set the docs ref, since data is empty as doc.data() is not returning anything.

Any clue on why this is happening now? Any help would be much appreciated!

UPDATE: this is what I get from the logs:

INFO 2023-11-19T05:43:00.503799Z snapshot: QuerySnapshot { _query: CollectionReference { _firestore: Firestore { _settings: [Object], _settingsFrozen: true, _serializer: [Serializer], _projectId: 'photo-capture-11c8e', _databaseId: '(default)', registeredListenersCount: 0, bulkWritersCount: 0, _backoffSettings: [Object], _clientPool: [ClientPool], _gax: [Object] }, _queryOptions: QueryOptions { parentPath: [ResourcePath], collectionId: 'subway', converter: [Object], allDescendants: false, filters: [], fieldOrders: [], startAt: undefined, endAt: undefined, limit: undefined, limitType: undefined, offset: undefined, projection: undefined, kindless: false, requireConsistency: true }, _serializer: Serializer { createReference: [Function (anonymous)], createInteger: [Function (anonymous)], allowUndefined: false }, _allowUndefined: false }, _readTime: Timestamp { _seconds: 1700372580, _nanoseconds: 490801000 }, _size: 5, _materializedDocs: null, _materializedChanges: null, _docs: [Function (anonymous)], _changes: [Function (anonymous)] }
INFO 2023-11-19T05:43:00.504023Z doc: QueryDocumentSnapshot { _fieldsProto: { closeHour: { integerValue: '23', valueType: 'integerValue' }, notified: { booleanValue: false, valueType: 'booleanValue' }, name: { stringValue: 'subway-merced', valueType: 'stringValue' }, openHour: { integerValue: '7', valueType: 'integerValue' }, notified_at: { stringValue: '', valueType: 'stringValue' }, status: { stringValue: 'capturing', valueType: 'stringValue' }, lastTotalCount: { integerValue: '0', valueType: 'integerValue' } }, _ref: DocumentReference { _firestore: Firestore { _settings: [Object], _settingsFrozen: true, _serializer: [Serializer], _projectId: 'photo-capture-11c8e', _databaseId: '(default)', registeredListenersCount: 0, bulkWritersCount: 0, _backoffSettings: [Object], _clientPool: [ClientPool], _gax: [Object] }, _path: QualifiedResourcePath { segments: [Array], projectId: 'photo-capture-11c8e', databaseId: '(default)' }, _converter: { toFirestore: [Function: toFirestore], fromFirestore: [Function: fromFirestore] } }, _serializer: Serializer { createReference: [Function (anonymous)], createInteger: [Function (anonymous)], allowUndefined: false }, _readTime: Timestamp { _seconds: 1700372580, _nanoseconds: 490801000 }, _createTime: Timestamp { _seconds: 1700372192, _nanoseconds: 562519000 }, _updateTime: Timestamp { _seconds: 1700372192, _nanoseconds: 562519000 } }
INFO 2023-11-19T05:43:00.504232Z doc: QueryDocumentSnapshot { _fieldsProto: { closeHour: { integerValue: '19', valueType: 'integerValue' }, notified: { booleanValue: false, valueType: 'booleanValue' }, name: { stringValue: 'subway-tenderini', valueType: 'stringValue' }, openHour: { integerValue: '9', valueType: 'integerValue' }, notified_at: { stringValue: '', valueType: 'stringValue' }, lastTotalCount: { integerValue: '0', valueType: 'integerValue' }, status: { stringValue: 'capturing', valueType: 'stringValue' } }, _ref: DocumentReference { _firestore: Firestore { _settings: [Object], _settingsFrozen: true, _serializer: [Serializer], _projectId: 'photo-capture-11c8e', _databaseId: '(default)', registeredListenersCount: 0, bulkWritersCount: 0, _backoffSettings: [Object], _clientPool: [ClientPool], _gax: [Object] }, _path: QualifiedResourcePath { segments: [Array], projectId: 'photo-capture-11c8e', databaseId: '(default)' }, _converter: { toFirestore: [Function: toFirestore], fromFirestore: [Function: fromFirestore] } }, _serializer: Serializer { createReference: [Function (anonymous)], createInteger: [Function (anonymous)], allowUndefined: false }, _readTime: Timestamp { _seconds: 1700372580, _nanoseconds: 490801000 }, _createTime: Timestamp { _seconds: 1700372408, _nanoseconds: 635977000 }, _updateTime: Timestamp { _seconds: 1700372408, _nanoseconds: 635977000 } }
INFO 2023-11-19T05:43:00.504424Z doc: QueryDocumentSnapshot { _fieldsProto: { closeHour: { integerValue: '20', valueType: 'integerValue' }, notified: { booleanValue: false, valueType: 'booleanValue' }, openHour: { integerValue: '10', valueType: 'integerValue' }, notified_at: { stringValue: '', valueType: 'stringValue' }, ' name': { stringValue: 'subway-mall-del-centro', valueType: 'stringValue' }, lastTotalCount: { integerValue: '0', valueType: 'integerValue' }, status: { stringValue: 'capturing', valueType: 'stringValue' } }, _ref: DocumentReference { _firestore: Firestore { _settings: [Object], _settingsFrozen: true, _serializer: [Serializer], _projectId: 'photo-capture-11c8e', _databaseId: '(default)', registeredListenersCount: 0, bulkWritersCount: 0, _backoffSettings: [Object], _clientPool: [ClientPool], _gax: [Object] }, _path: QualifiedResourcePath { segments: [Array], projectId: 'photo-capture-11c8e', databaseId: '(default)' }, _converter: { toFirestore: [Function: toFirestore], fromFirestore: [Function: fromFirestore] } }, _serializer: Serializer { createReference: [Function (anonymous)], createInteger: [Function (anonymous)], allowUndefined: false }, _readTime: Timestamp { _seconds: 1700372580, _nanoseconds: 490801000 }, _createTime: Timestamp { _seconds: 1700372324, _nanoseconds: 62497000 }, _updateTime: Timestamp { _seconds: 1700372324, _nanoseconds: 62497000 } }
INFO 2023-11-19T05:43:00.504649Z doc: QueryDocumentSnapshot { _fieldsProto: { closeHour: { integerValue: '22', valueType: 'integerValue' }, notified: { booleanValue: false, valueType: 'booleanValue' }, name: { stringValue: 'subway-subcentro', valueType: 'stringValue' }, openHour: { integerValue: '7', valueType: 'integerValue' }, notified_at: { stringValue: '', valueType: 'stringValue' }, status: { stringValue: 'capturing', valueType: 'stringValue' }, lastTotalCount: { integerValue: '0', valueType: 'integerValue' } }, _ref: DocumentReference { _firestore: Firestore { _settings: [Object], _settingsFrozen: true, _serializer: [Serializer], _projectId: 'photo-capture-11c8e', _databaseId: '(default)', registeredListenersCount: 0, bulkWritersCount: 0, _backoffSettings: [Object], _clientPool: [ClientPool], _gax: [Object] }, _path: QualifiedResourcePath { segments: [Array], projectId: 'photo-capture-11c8e', databaseId: '(default)' }, _converter: { toFirestore: [Function: toFirestore], fromFirestore: [Function: fromFirestore] } }, _serializer: Serializer { createReference: [Function (anonymous)], createInteger: [Function (anonymous)], allowUndefined: false }, _readTime: Timestamp { _seconds: 1700372580, _nanoseconds: 490801000 }, _createTime: Timestamp { _seconds: 1700162127, _nanoseconds: 183785000 }, _updateTime: Timestamp { _seconds: 1700163583, _nanoseconds: 355554000 } }
INFO 2023-11-19T05:43:00.504812Z doc: QueryDocumentSnapshot { _fieldsProto: { name: { stringValue: 'subway-los-militares', valueType: 'stringValue' }, lastTotalCount: { integerValue: '0', valueType: 'integerValue' }, notified: { booleanValue: false, valueType: 'booleanValue' }, status: { stringValue: 'capturing', valueType: 'stringValue' }, closeHour: { integerValue: '19', valueType: 'integerValue' }, openHour: { integerValue: '8', valueType: 'integerValue' }, notified_at: { stringValue: '', valueType: 'stringValue' } }, _ref: DocumentReference { _firestore: Firestore { _settings: [Object], _settingsFrozen: true, _serializer: [Serializer], _projectId: 'photo-capture-11c8e', _databaseId: '(default)', registeredListenersCount: 0, bulkWritersCount: 0, _backoffSettings: [Object], _clientPool: [ClientPool], _gax: [Object] }, _path: QualifiedResourcePath { segments: [Array], projectId: 'photo-capture-11c8e', databaseId: '(default)' }, _converter: { toFirestore: [Function: toFirestore], fromFirestore: [Function: fromFirestore] } }, _serializer: Serializer { createReference: [Function (anonymous)], createInteger: [Function (anonymous)], allowUndefined: false }, _readTime: Timestamp { _seconds: 1700372580, _nanoseconds: 490801000 }, _createTime: Timestamp { _seconds: 1700369879, _nanoseconds: 916393000 }, _updateTime: Timestamp { _seconds: 1700370052, _nanoseconds: 698090000 } }
INFO 2023-11-19T05:43:00.505032Z data:

Prevent XMLSerializer to escape special chars in script tags

I am trying to make a script that will generate an html page embedding scripts. I build the document in memory then serialize it with XMLSerializer.serializeToString. Problem: script tags don’t receive a special treatment and “a = 5 < 3” becomes “a = 5 < 3;” which triggers an error when I open the generated html (a JavaScript error saying Lt doesn’t exist).

I tried to add a CDATA section manually (with createTextNode but with the code of the CDATA in it) but it doesn’t work (the serializer ignores it and escape characters). I tried to use the built-in method to create a CDATA section (createCDATASection or something like that) but I get an error saying this isn’t supported for html documents.

How to tell the serializer not to escape special characters for script tags ? It’s fine to do it for other tags but this one (and style too) is special.

I think it’s a trivial problem but I have been stuck on it for hours.

I think I am missing something.
I would REALLY like to avoid using a third party library.

Thanks in advance.

let nums=[3,1,100]; console.log(nums.sort()) this return [ 1, 100, 3 ] why?


var longestPalindrome = function (s) {
    let pal = [], p = [],n = [];
    s = s.split('');
    for (i = 0; i < s.length-1; i++) {
        p[0]= s[i];
        for (j = i + 1; j < s.length; j++) {
                p.push(s[j]);
                 n = p
                if(isPalindrom(n) == 0){
                    if(pal.length < p.length){
                        pal = [];
                        console.log(p, pal)
                        pal = p;
                        
                    }
                } 
        }
        p = [];
    }
    console.log(pal)
    return pal;
};

var isPalindrom = function (arr) {
   n = arr;
    for(i=0; i<arr.length; i++){
        if(arr[i] != n[n.length-i-1]) return 1;
    }
    return 0;
}
console.log(isPalindrom(['b', 'a', 'b', 'a']))
longestPalindrome('baba')

now isPalindrom([‘b’, ‘a’, ‘b’, ‘a’]) return 1 still it pass if condition HOW???

isPalindrom works fine return correct values and also checked with if statement by putting console in that found that work fine too but i dont know how pal variable store last value [‘b’,’a’,’b’,’a’]

RxJS combining pointerdown and pointermove events

I am implementing a drag and drop of SVG Image Elements on SVG Element. The idea is when the pointerdown event is fired, and the pointermove event is fired, the selected SVG Image Element is dragged to the pointer location, until the pointerup event is fired. I am using the RxJS fromEvent creational observable.

    import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
    import { fromEvent, Observable, Subscription, Subject } from 'rxjs'
    import { RouterComponent, Router } from '../router/router.component';
    import { ToolbarComponent } from '../toolbar/toolbar.component';
    import { LinkComponent } from '../link/link.component';
    import * as d3 from 'd3';
    import { of } from 'rxjs';

    @Component({
      selector: 'app-test',
      templateUrl: './test.component.html',
      styleUrls: ['./test.component.css']
    })
    export class TestComponent implements AfterViewInit {

      @ViewChild("svg") svgElement: ElementRef<SVGSVGElement>;

      svg: SVGSVGElement;

      moveObjectPointerDown: Subscription;
      moveObjectPointerMove: Subscription;
      moveObjectPointerUp: Subscription;

      linkPointerDown: Subscription;
      linkPointerMove: Subscription;
      linkPointerUp: Subscription;

      @ViewChild(ToolbarComponent) toolbarComponent: ToolbarComponent;
      @ViewChild(RouterComponent) routerComponent: RouterComponent;
      @ViewChild(LinkComponent) linkComponent: LinkComponent;

      constructor() {
      }

      ngAfterViewInit() {
        this.svg = this.svgElement.nativeElement;

        this.subscribeMoveMode();

        this.toolbarComponent.createRouter$.subscribe(() => {
          var router = this.routerComponent.create();
          this.routerComponent.add(router);
        });

        this.toolbarComponent.createHost$.subscribe(() => {
        });
      }

      unsubscribeMoveMode(): void {
        this.moveObjectPointerDown.unsubscribe();
        this.moveObjectPointerMove.unsubscribe();
        this.moveObjectPointerUp.unsubscribe();
      }

      unsubscribeLinkMode(): void {
        this.linkPointerDown.unsubscribe();
        this.linkPointerMove.unsubscribe();
        this.linkPointerUp.unsubscribe();
      }

      subscribeMoveMode(): void {

        var selectedElement: any;
        var offsetX: number;
        var offsetY: number;

        this.moveObjectPointerDown = fromEvent(this.svg, "pointerdown").subscribe((event: any) => {
          if (event.target.classList.contains("router")) {
            selectedElement = event.target;
            let targetPositionX = selectedElement.getAttributeNS(null, 'x');
            let targetPositionY = selectedElement.getAttributeNS(null, 'y');
            let mousePositionX = event.clientX;
            let mousePositionY = event.clientY;
            let ctm = this.svg.getScreenCTM();
            mousePositionX -= ctm!.e;
            mousePositionY -= ctm!.f;
            offsetX = mousePositionX - targetPositionX;
            offsetY = mousePositionY - targetPositionY;
          }
        });

        this.moveObjectPointerMove = fromEvent(this.svg, "pointermove").subscribe((event: any) => {
          if (selectedElement) {
            let mousePositionX = event.clientX;
            let mousePositionY = event.clientY;
            let ctm = this.svg.getScreenCTM();
            mousePositionX -= ctm!.e;
            mousePositionY -= ctm!.f;
            mousePositionX -= offsetX;
            mousePositionY -= offsetY;
            selectedElement.setAttributeNS(null, 'x', mousePositionX);
            selectedElement.setAttributeNS(null, 'y', mousePositionY);

            // update position of router
            this.routerComponent.update(selectedElement.id, mousePositionX, mousePositionY);
            
            //this.routerObserver.update(selectedElement.id, selectedElement.x.baseVal.value, selectedElement.y.baseVal.value);
            for (let linkID of this.routerComponent.getById(selectedElement.id)!.links) {
              this.linkComponent.update(linkID, mousePositionX + 25 - 1, mousePositionY + 25 - 1);
            }
          }
          event.preventDefault();
        });

        this.moveObjectPointerUp = fromEvent(this.svg, "pointerup").subscribe((event: any) => {
          selectedElement = null;
        });
      }

      subscribeLinkMode(): void {
        
        var selectedLineElement: any;
        var selectedRouterElement1: any;
        var selectedRouterElement2: any;
        
        this.linkPointerDown = fromEvent(this.svg, "pointerdown").subscribe((event: any) => {     
          selectedRouterElement1 = event.target;
          if (selectedRouterElement1.classList.contains("router")) {
            var router: Router | undefined = this.routerComponent.getById(selectedRouterElement1.id);
            if (router != undefined) {
              selectedLineElement = this.linkComponent.create(router.x + 25, router.y + 25, router.x + 25, router.y + 25);
            }
          }
        });

        this.linkPointerMove = fromEvent(this.svg, "pointermove").subscribe((event: any) => {

          if (selectedLineElement) {
            let ctm = this.svg.getScreenCTM();
            var mousePositionX = event.clientX;
            var mousePositionY = event.clientY;
            mousePositionX -= ctm!.e;
            mousePositionY -= ctm!.f;
            selectedLineElement = this.linkComponent.update(selectedLineElement.id, mousePositionX - 1, mousePositionY - 1);
          }
          event.preventDefault();
        });

        this.linkPointerUp = fromEvent(this.svg, "pointerup").subscribe((event: any) => {
          if (event.target.classList.contains("router")) {
            selectedRouterElement2 = event.target;
            var r1 = this.routerComponent.getById(selectedRouterElement1.id)!;
            var r2 = this.routerComponent.getById(selectedRouterElement2.id)!;
            if (r1.connectedTo.indexOf(r2) == -1 && r2.connectedTo.indexOf(r1) == -1) {
              var newLink = this.linkComponent.create(r1.x + 25, r1.y + 25, r2.x + 25, r2.y + 25);
              this.routerComponent.addLink(r1.id, newLink.id, r2);
              this.routerComponent.addLink(r2.id, newLink.id, r1);
            }
          }

          if (selectedLineElement) {
            this.linkComponent.remove(selectedLineElement.id);
            selectedRouterElement1 = null;
            selectedRouterElement2 = null;
            selectedLineElement = null;
          }
        });
      }
    }

My question is Is there a more clever way of doing this using RxJS combination operators? As opposed to having three independent observables with locally shared variables (selectedElement, offsetX, offsetY). Can I utilize combineLatest, or withLatestFrom, or others?

How to make an element of html with position: fixed not go down beyond my footer?

I am doing a project in which on my page I have a calendar (I use FullCalendar) and to the right a section that shows a table of events that can be dragged to the calendar.

This table occupies the screen space that exists vertically, the calendar occupies more space so you have to go down to be able to see the bottom part.

I want the aforementioned table to go down when going down the page so that it is always completely visible on the right side of the screen.

So I tried the most logical thing, using the position: fixed property in CSS. However, when I do this my events table goes down as I scroll but when I get to the bottom it overlaps my footer. So I want to know how to make the table stop descending when it reaches the footer.

Not to mention that using position: fixed aligns the table to the left below the calendar, when I want it to display on the right instead.

Here is my code that shows how my page is structured.

Sorry if something is not clear, I am a Spanish speaker and I am not good at English, I am using Google Translate to help me.

<div class="container-fluid">
        <div class="row">
            <div class="col-10">
                <!--calendar-->
                <div id="Calendario1" style="margin-bottom: 1em; border: 2px solid #9e9e9e; padding:1em; border-radius: 15px;"></div>
            </div>
            <!--Table of draggable events to calendar-->
            <div class="col-2" id="seccion_predefinidos">
                <div id="external-events" style="margin-bottom: 1em; height: 500px; border: 2px solid #9e9e9e; overflow-y: scroll; padding: 1em; border-radius: 15px; padding-right: 6px;">
                    <h4 class="text-center" style="margin-bottom: 0.8em">Eventos predefinidos</h4>
                    <hr>
                    <div id="listaEventosPredefinidos">
                        <?php 
                        require("conexion.php");
                        $conexion = regresarConexion();
                        $datos = mysqli_query($conexion, "SELECT id_pred, nombre_pred, hora_inicio, hora_fin, color_texto, color_fondo FROM predefinidos");
                        $ep = mysqli_fetch_all($datos, MYSQLI_ASSOC);
                        foreach ($ep as $fila) {
                            echo "<div class='fc-event' 
                            data-nombre_pred='$fila[nombre_pred]' 
                            data-hora_inicio='$fila[hora_inicio]' 
                            data-hora_fin='$fila[hora_fin]' 
                            data-color_texto='$fila[color_texto]' 
                            data-color_fondo='$fila[color_fondo]' 
                            style='border-color:$fila[color_fondo]; color:$fila[color_texto]; background-color:$fila[color_fondo]; margin-bottom:10px; padding: 5px; border-radius: 10px; cursor: pointer;'>
                            $fila[nombre_pred] [" . substr($fila['hora_inicio'],0,5) . " a " . substr($fila['hora_fin'],0,5) . "]</div>";
                        }
                        
                        ?>                       
                    </div>
                </div>
                <div id="botonEventosPredefinidos">
                    <hr>
                    <div style="text-align: center">
                        <button type="button" id="botonEventosPredefinidos" class="btn btn-success">
                            Administrar eventos predefinidos
                        </button>
                    </div>
                </div>
                
            </div>
        </div>
    </div>

Print a component in React: NotFoundError: Failed to execute ‘removeChild’ on ‘Node’: The node to be removed is not a child of this node

I want to print a Component using JavaScript in React ( NextJS project ) using this function from this thread.


  const print = () => {
    var printContents = document?.getElementById("div")?.innerHTML
    var originalContents = document.body.innerHTML

    document.body.innerHTML = printContents as string

    window.print()

    document.body.innerHTML = originalContents
  }

It displays the PDF Preview in the first click but when I click on the print button second time it throws this error:

`

NotFoundError: Failed to execute ‘removeChild’ on ‘Node’: The node to be removed is not a child of this node.
`

enter image description here

This is my full code :

import { Divider } from "@tremor/react"
import { useRef } from "react"
import React from "react"
import { useReactToPrint } from "react-to-print"

import { Button } from "@/components/ui/button"
import { Sheet, SheetContent, SheetHeader, SheetTrigger } from "@/components/ui/sheet"

import { BuildingInformation } from "./components/building-information"
import { EnergyEfficiency } from "./components/energy-efficiency"
import { FinancialAnalysis } from "./components/financial-analysis"
import { Intro } from "./components/Intro"
import { Modernization } from "./components/modernization"

export const DataReporting = () => {
  const print = () => {
    var printContents = document?.getElementById("div")?.innerHTML
    var originalContents = document.body.innerHTML

    document.body.innerHTML = printContents as string

    window.print()

    document.body.innerHTML = originalContents
  }

  return (
    <Sheet>
      <SheetTrigger>
        <Button variant={"ghost"}>Holen Sie sich Ihren Bericht</Button>
      </SheetTrigger>
      <SheetContent
        side={"bottom"}
        className='h-full m-auto overflow-y-auto print:overflow-y-auto sm:w-screen lg:w-fit'
      >
        <SheetHeader>
          <Button className='w-fit z-20 mr-auto bg-blue-700 hover:bg-blue-600' onClick={print}>
            Herunterladen
          </Button>
          <Divider />
        </SheetHeader>
        <div id='div'>
          <Intro />
          <BuildingInformation />
          <Modernization />
          <EnergyEfficiency />
          <FinancialAnalysis />
        </div>
      </SheetContent>
    </Sheet>
  )
}



preventing navigation if form is dirty in react-router-v6

I’m working on a react project and i want to block navigation and form reload if form on the page is dirty.
I found information about blocking the reload though.
But i’m stuck on blocking navigation
I read the documentation of react-router and found that it was easy in v5 as it gives prebuilt hooks
But how can i achieve that in v6. ?

How can I call specific Python functions from JS and Perl?

I want to be able to call some functions from my python application in JavaScript and Perl files.

Let’s say I have two Python funcions: speak(), and listen(). I want to be able to call them in Perl and JS files so I can use them in my code. I also want to be able to keep my parameters and everything else intact.

I tried making an API, but that may not have been the proper thing to do, because it didn’t work. Instead, it crashed the server I initiated. I used FastAPI to send out the two functions as endpoints, but it didn’t work.

I also took a look at Inline::Python. Since it didn’t fit my use case, I ditched my JS alternative, JSPYBridge. I think an API is the way to go, but I am just making it wrong.

I’d appreciate some code examples best, since I tend to learn better by looking at the actual implementation, or links to resources, but I would love anything.

I am using weighted average to get the data but my total score is coming 0

I have data from JSON and using weighted to total and show the top 3 scored countries. I am given the option to use to sort and arrange their preference based on that score1pref1 + score2pref2+score3*pref3 … feature but my total score is coming as 0 in all cases.

When I am using inputs instead of sort it is working as expected.
https://codepen.io/kunalvijan/pen/eYxVZwM

But after moving it to sort I am getting a total score always 0. Any help!

Attaching the code for ref.

var sortable = new Sortable(document.getElementById('sortableList'), {
      animation: 150,
      onUpdate: function (evt) {
        // Automatically assign priorities based on the new order
        var items = evt.from.children;
        for (var i = 0; i < items.length; i++) {
          var item = items[i];
          item.dataset.priority = i + 1;
        }
      }
    });

    function calculateAndDisplay() {
      var userPreferences = {};

      // Collect priorities from the sorted list
      var items = document.getElementById('sortableList').children;
      for (var i = 0; i < items.length; i++) {
        var item = items[i];
        userPreferences[item.dataset.id] = parseInt(item.dataset.priority);
      }

      console.log("User Preferences: ", userPreferences);

      var countriesData = [
        {
          "Country": "USA",
          "Employment Rate": 5.10,
          "University Rankings": 37.78,
          "Tuition Fees": 9.30,
          "PR and Settlement Opportunities": 6.06,
          "Graduate Pay Scales": 6.63,
          "Spouse Work Rights": 3.85,
          "Cost of Living": 7.58,
          "Cultural Fit": 5.41,
          "Safety and Security": 3.49,
          "Quality of Life": 4.65 
        },
        {
          "Country": "UK",
          "Employment Rate": 5.20,
          "University Rankings": 12.22,
          "Tuition Fees": 8.63,
          "PR and Settlement Opportunities": 4.55,
          "Graduate Pay Scales": 5.42,
          "Spouse Work Rights": 6.41,
          "Cost of Living": 6.72,
          "Cultural Fit": 5.41,
          "Safety and Security": 4.65,
          "Quality of Life": 4.65
        }
      ];

      var totalScores = [];

      for (var i = 0; i < countriesData.length; i++) {
        var countryData = countriesData[i];
        var totalScore = 0;

        for (var attribute in userPreferences) {
          if (countryData.hasOwnProperty(attribute)) {
            var attributeWeight = countryData[attribute] * userPreferences[attribute];
            totalScore += attributeWeight;
          }
        }

        console.log(countryData);

        totalScores.push({ "Country": countryData.Country, "TotalScore": totalScore });
      }

      totalScores.sort((a, b) => b.TotalScore - a.TotalScore);

      console.log("Sorted Total Scores: ", totalScores);

      // Display the results on the same page
      var resultsContainer = document.getElementById("resultsContainer");
      resultsContainer.innerHTML = "<h2>Top 3 Results</h2>";

      // Display the top 3 countries
      for (var j = 0; j < Math.min(3, totalScores.length); j++) {
        resultsContainer.innerHTML += "<p>" + totalScores[j].Country + " - Total Score: " + totalScores[j].TotalScore.toFixed(2) + "</p>";
      }
    }
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>
<div id="sortableList">
    <div data-id="employmentRate">Employment Rate</div>
    <div data-id="universityRankings">University Rankings</div>
    <div data-id="tuitionFees">Tuition Fees</div>
    <div data-id="prOpportunities">PR and Settlement Opportunities</div>
    <div data-id="graduatePayScales">Graduate Pay Scales</div>
    <div data-id="spouseWorkRights">Spouse Work Rights</div>
    <div data-id="costOfLiving">Cost of Living</div>
    <div data-id="culturalFit">Cultural Fit</div>
    <div data-id="safetyAndSecurity">Safety and Security</div>
    <div data-id="qualityOfLife">Quality of Life</div>
  </div>
    <button type="button" onclick="calculateAndDisplay()">Submit</button>

  <div id="resultsContainer"></div>

node.js – Handling Large Data Areas With Growing Sizes

I’m working on a fairly large “full stack” node project. This project could
contain a few large data areas, the size of which could fluctuate over time.
One example is logging information (I want to keep the logging info private
and not use any system logging files). This logging info could grow beyond
the maximum size of what node can handle, and I need to determine how to
handle this.

One method I’m considering is to monitor the size of the logging info
and at a certain point write it to a file, then null the area in node,
and continue logging while monitoring the size. This would mean that I
would need to manage the process so a user’s disk space doesn’t get exhausted.

How do others handle this type of scenario?