How to extract text parts from a large project?

I need to implement a new language on a website that was written in one language (for example, in English). Now I need to add the ability to change the language on the site, for example, choosing between English and Spanish or any other language.

My idea is to create a table in the database that contains “key,” “language 1,” “language 2.” Initially, when the site loads, I download all the records from the table and create a method in each parent component; this file will be used in all child components. The principle of this method is simple: before rendering the page, this method will be called in every place where there is a key. The key is the name of the variable that will replace the static text in the HTML or JS code.

Method:

babelfishTranslate(text) {
  if (this.wordReplacements[text]) {
    return this.wordReplacements[text];
  } else {
    return text;
  }
}

Example:

<div class="align-items-center align-items-md-end d-flex justify-content-between">
  <h5 class="fw-bold">
    {{ $root.babelfishTranslate(incipitdata.titolo || "incipit1") }}, {{ nomeAzienda }}
  </h5>
  <div class="d-flex gap-3 align-items-center">
    <div class="d-flex gap-3">
      <div>{{ $root.babelfishTranslate("incipit2") }}</div>
      <switcher 
        :idvalore="'modalitaPrivacy'" 
        :name="'modalitaPrivacy'" 
        :valore="modalitaPrivacy" 
        v-on:settavalore="settaValore" 
        :key="'modalitaPrivacy' + aggiornaSwitcher"
      />
    </div>
    <div
      v-tooltip="$root.babelfishTranslate('incipit3')"
      class="nascondiSeMobile"
      :key="aggiornaTooltip"
    >
      <button class="fs-2 btn btn-aggiungi color-custom" @click="vaiInModalitaModifica">
        <i class="fa-duotone fa-gear"></i>
      </button>
    </div>
  </div>
</div>

$root.babelfishTranslate(‘incipit2’) calls the babelfishTranslate method, which looks in the global variable where there is a translation if the key has the value ‘incipit2’, and replaces it with the user’s chosen language.

Table:

Key English Italian
incipit2 Privacy mode Modalità Privacy

But there is a problem with all of this. Replacing all the written static text with these “keys,” variables that I will later record in the table with translations for “language 1” and “language 2.”

How can I find all the text in my project? If I wrote the project in Vue 2, using the Options API, and all the HTML code is written inside the “template” variable. Also, it needs to take into account full phrases, for example, “Welcome [username], do you want to add [product name] to the cart?”

How do I install NestJS on macOS 15 without these errors?

npm error code EACCES
npm error syscall rename
npm error path /usr/local/lib/node_modules/@nestjs/cli
npm error dest /usr/local/lib/node_modules/@nestjs/.cli-seuz8ewr
npm error errno -13
npm error Error: EACCES: permission denied, rename ‘/usr/local/lib/node_modules/@nestjs/cli’ -> ‘/usr/local/lib/node_modules/@nestjs/.cli-seuz8ewr’
npm error at async Object.rename (node:internal/fs/promises:782:10)
npm error at async moveFile (/usr/local/lib/node_modules/npm/node_modules/@npmcli/fs/lib/move-file.js:30:5)
npm error at async Promise.allSettled (index 0)
npm error at async [reifyPackages] (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/reify.js:325:11)
npm error at async Arborist.reify (/usr/local/lib/node_modules/npm/node_modules/@npmcli/arborist/lib/arborist/reify.js:142:5)
npm error at async Install.exec (/usr/local/lib/node_modules/npm/lib/commands/install.js:150:5)
npm error at async Npm.exec (/usr/local/lib/node_modules/npm/lib/npm.js:207:9)
npm error at async module.exports (/usr/local/lib/node_modules/npm/lib/cli/entry.js:74:5) {
npm error errno: -13,
npm error code: ‘EACCES’,
npm error syscall: ‘rename’,
npm error path: ‘/usr/local/lib/node_modules/@nestjs/cli’,
npm error dest: ‘/usr/local/lib/node_modules/@nestjs/.cli-seuz8ewr’
npm error }
npm error
npm error The operation was rejected by your operating system.
npm error It is likely you do not have the permissions to access this file as the current user
npm error
npm error If you believe this might be a permissions issue, please double-check the
npm error permissions of the file and its containing directories, or try running
npm error the command again as root/Administrator.
npm error A complete log of this run can be found in: /Users/johnnysmad/.npm/_logs/2024-10-03T14_42_51_289Z-debug-0.log
johnnysmad@MacBook-Air-de-Joao ecommerce %

It isn’t installing at all. With sudo it completes, but it doesn’t run

Is there a way to maintain information in an iframe when i change tabs?

I have a webpage with several tabs. Inside one of them I include an iframe as a way to manage certain properties, therefore I need the data to be persistent. Each time I change to another tab and come back the Iframe reloads, losing the state of the variables. How do I make sure the iframe doesn’t unmount each time I leave the tab?

I have two files. One is a view.svelte

  import { ViewContainer } from '@marcellejs/design-system';
  export let title;
  export let url;  // Accept the URL prop
</script>

<ViewContainer {title}>
  {#if url}
    <iframe title="" src={url}  width="(parseInt(window.innerWidth) * 0.9)" height="750px" style="border: none;"></iframe>
  {/if}
</ViewContainer>

<style>
  .my-color {
    color: seagreen;
  }
</style>

and the other one is a component.js

import { Component } from '@marcellejs/core';
import View from './widget.view.svelte';

export class Widget extends Component {
    constructor(options = {}) {
        super();
        this.title = '';
        this.options = options;
        this.url = options.url || '';  // Accept a URL option to embed the webpage
    }

    mount(target) {
        const t = target || document.querySelector(`#${this.id}`);
        if (!t) return;
        this.destroy();
        this.$$.app = new View({
            target: t,
            props: {
                title: this.title,
                options: this.options,
                url: this.url  // Pass URL to the view
            }
        });
    }
}

I haven’t found anything that works within this framework.

Performance Issue with Feature Layer while using “@arcgis/core”: “=4.28.10“ Library

we were using old version of arcgis javascript api i.e. “@types/arcgis-js-api”: “4.8.0“, With this version we didn’t faced any performance issue.

Recently we upgraded “@arcgis/core”: “=4.28.10“ Library instead of “@types/arcgis-js-api”: “4.8.0“, After upgrade what we noticed:

  • In PRD, we noticed that Response from Point and Polygon AGOL Layer is very slow (Response of request is taking 30-40 sec).
  • In Latest Version of arcgis-api, response format is changed to “f=pbf” and request is going multiple time with different extent geometries.
  • In Older version, response format is “f=json” and only one request goes to fetch all data without any extent geometry.

We are showing Point and Polygon using Feature Layer “DefinationExpression” and “renderer” property. No Graphic Layer is used to show symbol on map.

Any suggestions, Is there anything which we are missing.

As of now, we used old arcgis-api only i.e. “@types/arcgis-js-api”: “4.8.0“. Since we couldn’t able to figure it out.

KML Dynamic Loading Using Google Cloud console

I have a KML which is having 40K records,It got stuck whenever I open the GE. To make the operation smooth I wanted to use the dynamic loading using MAPS Java Script API,

I saved the KML in Public server and wanted to access whenever I open. Can somebody help to write a code that will work

I have tried below code and it is giving me error:

Error: js?key=YOur-API KeY Google Maps JavaScript API has been loaded directly without loading=async. This can result in suboptimal performance.

Code:

<head>
  <title>Dynamic KML Loading in Google Maps</title>
  <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"></script>
  <script>
    function initMap() {
      var map = new google.maps.Map(document.getElementById('map'), {
        center: { lat: 37.422, lng: -122.084 },
        zoom: 12
      });
      // Load the KML file dynamically
      var kmlLayer = new google.maps.KmlLayer({
        url: 'https://your-kml-file-link.kml', // Replace this with your hosted KML URL
        map: map
      });
      // Function to update the KML file dynamically
      function updateKml(newUrl) {
        kmlLayer.setUrl(newUrl);
      }
      // Example: Automatically load a new KML after 10 seconds
      setTimeout(function() {
        updateKml('https://another-kml-file-link.kml'); // Replace with another KML URL
      }, 10000); // 10 seconds delay
    }
  </script>
</head>
<body onload="initMap()">
  <div id="map" style="width: 100%; height: 500px;"></div>
</body>
</html>````

Sending Electron window data but getting error

Hi I’m trying to convert my project from a web browser to a GUI based app with electron and I’m following this video to start my project he is using yarn but I use npm 9.2.0

At first I was not getting anything from the button when I pressed it but I saw on a comment that I could try changing

webPreferences:{
    nodeIntegration: true,
}

to

webPreferences:{
    nodeIntegration: true,
    contextIsolation: false,
    enableRemoteModule: true,
}

and then I got something … an error -_-

here is my code for now

gui.js

const { app, BrowserWindow, ipcMain } = require("electron");

let leftWindow = null;
let rightWindow = null;

const createWindows = (win, page) => {
    win = new BrowserWindow({
        width: 1024,
        height: 600,
        resizable: false,
        fullscreen: true,
        webPreferences:{
            nodeIntegration: true,
            contextIsolation: false,
            enableRemoteModule: true,
        },
    });
    win.loadFile(page)
};

app.whenReady().then(() => {
    //createWindows(leftWindow, "dash.html");
    createWindows(rightWindow, "controls.html");
});

app.on('window-all-closed', () => {
    if(process.platform !== 'darwin') {
        app.quit()
    }
})

ipcMain.on('send', (event, data) => {
    const randomStr = data + Math.random().toString(36).substring(2, 5)
    rightWindow.webContents.send('receive', randomStr)
})

render.js

const ipcRenderer = require("electron").ipcRenderer;
const test = () => {
    ipcRenderer.send("send", document.querySelector(".keyWord").value);
};

ipcRenderer.on("receive", (event, data) => {
    alert(data);
    const tempTag = document.querySelector("#temp");
    tempTag.innerText = data;
});

control.html

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Controls</title>
        <script defer src="render.js"></script>
        <link rel="stylesheet" href="./public/styles.css" />
    </head>
    <body>
        <div id="content">
            <input type="text" class="keyWord" placeholder="Enter Data">
            <button onclick="test()">Test</button>
            <h1 id="temp">Random String</h1>
        </div>
       <script type="text/jsx" src="./public/controlApp.jsx"></script>
    </body>
</html>

Error in build file (babel): ReferenceError: require is not defined in ES module scope, you can use import instead

I don’t have a very good understanding of babel or webpack. I am able to successfully build an old codebase of ours but when running the code using node ui/dist/server, I am getting an error:

ReferenceError: require is not defined in ES module scope, you can use import instead
This file is being treated as an ES module because it has a '.js' file extension and '/Users/user/code/node/myapp/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
    at Object.@babel/runtime/helpers/interopRequireDefault (file:///Users/user/code/node/myapp/ui/dist/server/index.js:19088:1)
    at __webpack_require__ (file:///Users/user/code/node/myapp/ui/dist/server/index.js:20072:40)
    at file:///Users/user/code/node/myapp/ui/dist/server/index.js:20119:30
    at ModuleJob.run (node:internal/modules/esm/module_job:234:25)
    at ModuleLoader.import (node:internal/modules/esm/loader:473:24)
    at asyncRunEntryPointWithESMLoader (node:internal/modules/run_main:123:5)

My babelrc is:

{
  "presets": [
    [
      "@babel/preset-env", {
        "targets": {
          "esmodules": true
        },
        "modules": false
      }
    ],
    ["@babel/preset-react", {
      "runtime": "automatic" 
    }]
  ],
  "sourceType": "unambiguous",
  "plugins": [
    "@babel/plugin-transform-runtime",
    "@babel/plugin-transform-modules-commonjs",
    "@babel/plugin-proposal-object-rest-spread",
    "@babel/plugin-transform-destructuring",
    "@babel/plugin-transform-parameters",
    "transform-decorators-legacy",
    "@babel/plugin-transform-class-properties",
    "syntax-dynamic-import"
  ],
  "env": {
    "development": {
      "plugins": [
        "transform-react-jsx-self"
      ]
    },
    "production": {
      "presets": [
        "react-optimize"
      ]
    },
    "test": {
      "plugins": [
        // "transform-es2015-modules-commonjs", 
        "dynamic-import-node"
      ]
    }
  }
}

I tried experimenting with the @babel/plugin-transform-modules-commonjs plugin but the error persists. The error is in a build file.

Line 20119:

var _interopRequireDefault = __webpack_require__(/*! @babel/runtime/helpers/interopRequireDefault */ "@babel/runtime/helpers/interopRequireDefault");

Line 19088:

module.exports = require("@babel/runtime/helpers/interopRequireDefault");

Package.json snippets:

"type: module"

"dependencies": {

"@babel/plugin-transform-react-jsx": "^7.25.2",
"@babel/runtime": "^7.25.0",
"babel-plugin-transform-react-jsx-self": "^6.22.0",
}

Is there a more efficient way to load and display multiple background-images in a slider

I currently have an imageslider function in JavaScript which switches out one image for another when the user clicks on media arrows .. it works fine, BUT there is a lag the first time it loads each image. My question is this… is there a more efficient way to load multiple images at the same time then hide/make visible instead of loading each image one at a time (using div background-image)? Here is the JavaScript function I am currently using…

let imageNames = [];

function slideImage(offset = 0) {
  var pc = document.querySelector(".slider");
  var imageLocation = "/image/profile/";

  let maxCount = imageNames.length - 1;

  if (typeof index === "undefined") {
    index = 0;
  } else {
    index += offset;

    if (index > maxCount) {
      index = 0;
    } else if (index < 0) {
      index = maxCount;
    }
  }

  pc.style.backgroundImage = "URL('" + imageLocation + imageNames[index] + ".webp')";
}

this.route is undefined while trying to router.navigate with route declared in the contructor and it works in all other components

i’m using router navigate and setTimeout to just get from a simple congratulation page to another component.
I did the same stuff in all the other components and it has always worked, i can’t seem to understand why in this case it doesn’t work.
Here’s the component’s ts:

import { Component, OnInit } from '@angular/core';
import { Route, Router } from '@angular/router';

@Component({
  selector: 'app-file-successfull',
  templateUrl: './file-successfull.component.html',
  styleUrls: ['./file-successfull.component.css']
})
export class FileSuccessfullComponent implements OnInit {

constructor(private route: Router) { }
   public toUpload(){
      this.route.navigate(['fileUpload']);
   }

   ngOnInit(): void {
     setTimeout(this.toUpload, 5000);
   }
 }

here’s the error i get:

ERROR TypeError: this.route is undefined
toUpload file-successfull.component.ts:13
Angular 17
ngOnInit file-successfull.component.ts:17
Angular 19
RxJS 6
Angular 20
RxJS 22

Here’s my app-routing-module:

import { Component, NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { HomepageComponent } from './components/homepage/homepage.component';
import { LoginComponent } from './components/login/login.component';
import { SubscribedComponent } from './components/subscribed/subscribed.component';
import { GoogleLandingPageComponent } from './components/google-landing-page/google-landing-page.component';
import { GoogleErrorComponent } from './components/google-error/google-error.component';
import { FileUploadComponent } from './components/file-upload/file-upload.component';
import { FileUploadErrorComponent } from './components/file-upload-error/file-upload-error.component';
import { UserHomepageComponent } from './components/user-homepage/user-homepage.component';
import { FileSuccessfullComponent } from './components/file-successfull/file-successfull.component';

const routes: Routes = [{
  path: 'home', component: HomepageComponent
},{
  path: 'login', component: LoginComponent
},{
  path: 'subscribed', component: SubscribedComponent
},{
  path: 'google', component: GoogleLandingPageComponent
},{
  path: 'googleerror', component: GoogleErrorComponent
},{
  path: 'fileUpload', component: FileUploadComponent
},{
  path: 'fileUploadError', component: FileUploadErrorComponent
},{
  path: 'userHomepage', component: UserHomepageComponent
},{
  path: 'fileSuccessfull', component: FileSuccessfullComponent
},{
  path: '**', redirectTo: 'home'
}];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I know it’s probably a stupid begginer error, but can someone help me please?

CaptureStream stops on adding Video to Fabric.js

I have a Fabric.js canvas; and I capture the mediastream which then is displayed in the video. This works fine in the start; when I add the text to the Canvas it also shows in the video. The problem is that myVideo does no longer update as soon as I start playing htmlVideo that I’ve added to the canvas.

I can see htmlVideo appear in the Canvas and it plays there, but not in myVideo. The state of myVideo is still playing but it seems like there’s no more data coming in, which makes me suspect that there’s something incorrect with the setup of the captureStream or with the rendering in requestAnimFrame

Does anyone know why?

import {
    Canvas, FabricImage, FabricText, util
} from 'fabric'

const canvas      = new Canvas('myCanvas')
const video       = document.getElementById('myVideo')
const mediaStream = canvas.getElement().captureStream(30)

video.srcObject  = mediaStream
video.play()

// Add text after 5 seconds
setTimeout(() => {
  const txt = new FabricText('Hello World', {
    fill: '#FFF',
    left: 10,
    top: 40,
  })

  canvas.add(txt)
  console.info(`Text added to canvas`)
}, 5000);

// Add video after 10 sec
setTimeout(() => {
  var htmlVideo = document.createElement('video') as HTMLVideoElement

  htmlVideo.src = 'http://html5demos.com/assets/dizzy.mp4'
  htmlVideo.width  = 480
  htmlVideo.height = 360

  var fabricImage = new FabricImage(htmlVideo, {
      left: 200,
      top: 300,
      originX: 'center',
      originY: 'center',
      objectCaching: false
  })

  canvas.add(video)

  htmlVideo.play()
  console.info(`Video added to canvas`)
}, 10000);

util.requestAnimFrame(function render() {
  canvas.renderAll()
  util.requestAnimFrame(render)
})
<canvas id="myCanvas" width="640" height="360"></canvas>
<video id="myVideo" width="640" height="360" controls playsinline></video>

Fluent UI Vertical Bar Chart refuses to show x-axis values without a separator (react, javascript)

I’m populating a bar chart with my data and no matter what I do, I can’t get the x-axis values to drop the separators. The x-axis values are supposed to be years and I can’t figure out where and how to format the date in a way that will produce the ‘2025’ result and not ‘2 025’.

enter image description here

I map through a JSON and populate the x-values with new Date(string value).getFullYear() as I only want the x-axis values to be years. If I get the date object without getting the year, I end up with ‘2025-01-01’ which I don’t want.

enter image description here

Laplacian Smooth disconnecting faces

I have implemented Laplacian smooth in JavaScript and using Three.js, but it seems to be not working as expected. Whenever I use hover and smooth over meshes, the faces are disconnecting and getting smaller and smaller. What’s wrong with this code ?

Output image of mesh after smoothing, the white circle is brush, and indices is the array which contains all the indices under the brush.

indices.forEach( index => {

    if (params.brush === 'smooth') {

      for (let i = 0; i < 3; i++) {

        const currentVector = new THREE.Vector3().fromBufferAttribute(posAttr, index);
        const nbI = neighborMap.get(index); // Get the neighbors of the current vertex
        if (!nbI || nbI.size === 0) return; // Skip if no neighbors

        const nbIAr = Array.from(nbI); // Convert neighbor Set to array

        // Initialize average position to zero
        const avgPos = new THREE.Vector3();
        const neighborCount = nbIAr.length;

        // Calculate the average position of the neighboring vertices
        nbIAr.forEach(neighborIndex => {
          const neighborPos = new THREE.Vector3().fromBufferAttribute(posAttr, neighborIndex);
          avgPos.add(neighborPos); // Accumulate neighbor positions
        });

        avgPos.divideScalar(neighborCount); // Compute the average


        // Compute the Laplacian (difference between average and current position)
        const laplacian = new THREE.Vector3().subVectors(avgPos, currentVector);



        // Update the vertex position by moving it toward the average
        const lamdaValue = 0.005
        currentVector.addScaledVector(laplacian, lamdaValue); // λ

        tempVec.copy(currentVector);

      }
    }

    posAttr.setXYZ(index, tempVec.x, tempVec.y, tempVec.z);
    normalAttr.setXYZ(index, 0, 0, 0);

  });

I have increased value of lamda and it moved the vertex far away,

How to Filter Out Incomplete Addresses in Google Maps Autocomplete

I’m working on a .NET project where I’m using Google Maps Autocomplete(JavaScript) to suggest addresses in a name maintenance screen. However, I’ve noticed that incomplete addresses are also being suggested. How can I filter out these incomplete addresses?

I tried with below sample code which Gemini AI suggested.

My Sample Code:

`const input = document.getElementById("googlePrimaryAddressAutoComplete");`    
const options = {
  fields: ["address_components", "geometry", "icon", "name"],
  componentFilter: [
    { componentLevel: google.maps.places.ComponentType.streetNumber },
    { componentLevel: google.maps.places.ComponentType.subpre },
    { componentLevel: google.maps.places.ComponentType.route },
    { componentLevel: google.maps.places.ComponentType.loca },
    { componentLevel: google.maps.places.ComponentType.postal_town },
    { componentLevel: google.maps.places.ComponentType.sublocality },
    { componentLevel: google.maps.places.ComponentType.administrative_area_level_2 },
    { componentLevel: google.maps.places.ComponentType.administrative_area_level_1 },
    { componentLevel: google.maps.places.ComponentType.country },
    { componentLevel: google.maps.places.ComponentType.postal_code },
    { componentLevel: google.maps.places.ComponentType.postal_code_suffix }
  ]
};



`const autocomplete = new google.maps.places.Autocomplete(input, options);`

Not working. Help me to correct it.

Load data from different HTML files with click event on list items

What I want to achieve:

  • Add an event listener to all hrefs in the list with class="listen".
  • When user clicks on any list item then replace the content of the div with id="SelectedText" with the content of the chosen file.
<!DOCTYPE html>
<html lang="en">
  <meta charset="utf-8">
  <title>Read file into div</title>
  <article>
    <h1>My HTMl</h1>
    <ul class = "listen">
      <li><a href="file1.html">Select file 1</a>
      <li><a href="file2.html">Select file 2</a>
      <li><a href="file2.html">Select file 2</a>
    </ul>
    <h1>Please find selected content below:</h1>
    <div id = "SelectedText">
      <p>Replace me
    </div>
    <script> magic here </script>
  </article>
<!-- Local file -->
<p>file i contains for example:
<h1>Ipsum dolor sit amet</h1>

I tried:


<!DOCTYPE html>
<html lang="nl">
<meta charset="utf-8">
<title>Test</title>
  <nav>
    <ul>
      <li><a href="#" onclick="loadDoc('/nieuws.htm'); return false;">Nieuws</a>
      <li><a href="#" onclick="loadDoc('/teams/teams.htm'); return false;">Teams</a>
      <li><a href="#" onclick="loadDoc('/links/links.htm'); return false;">Links</a>
    </ul>
  </nav>
  <main id="content">
  <p>Replace me
  </main>

with javascript function:

    <script>
    // Load external HTML document in div.
    function loadDoc(x) {
      .then((result) => {
        if (result.status != 200) { throw new Error("Bad Server Response"); }
        return result.text();
      })
      .then((content) => {
        document.getElementById("content").innerHTML = content;
      })
      .catch((error) => { console.log(error); });
    }
    </script>

But I find a solution with event-handlers more elegant.