Iterator Behavior: Internal Sorting Disregards Original Indexes [duplicate]

A curious issue has recently piqued my interest, leaving me scratching my head. When dealing with a provided list that is pre-sorted, such as:

  "000": "000",
  "001": "001",
  "002": "002",
  "003": "003",
  "107": "107",
  "108": "108"

or

  "000": "000 - Roy",
  "001": "001 - James",
  "002": "002 - Ben",
  "003": "003 - Nathan",
  "107": "107 - George",
  "108": "108 - Silus"

and attempting to iterate through it using a standard iterator (for our case, Forof), an unexpected behavior arises. Consider the following snippet:

const items = {

  "000": "000",
  "001": "001",
  "002": "002",
  "003": "003",
  "107": "107",
  "108": "108"

}
for (const key in items) {
  if (key) {
    console.log("The Item Yahh", items[key]);
  }

}

Surprisingly, the very first index utilized by the iterator is 107, despite the expectation that it should start with 000. According to ECMAScript specifications, this deviation shouldn’t occur.

This begs the question: why does the iterator sort in ascending numerical order where 1 precedes 0? This behavior contrasts sharply with observations made when iterating over an array of strings:

const items = [

  "000",
  "001",
  "002",
  "003",
  "107",
  "108"

]
for (const key in items) {
  if (key) {
    console.log("Yahh an Array Item", items[key]);
  }

}

In this case, the order remains intact. What could be causing this inconsistency in behavior?

Get Google Drive apps script onItemsSelectedTrigger to execute every time a file is selected

Google Drive onItemsSelectedTrigger only executes once for each file selected and displays a cached response the second and subsequent times the file is selected, have to change folder or refresh UI for it to execute again. Want a solution to have it execute every time a file is selected (need to check file version against external system to guide users).

Running this example and continuously clicking two different files, the execution logs shows onItemsSelectedTrigger only executes twice, the first time each file was selected.

appsscript.json:

"drive": {
      "onItemsSelectedTrigger": {
        "runFunction": "onDriveItemsSelected"
      }

code.gs:

function onDriveItemsSelected(e) {
  console.log(e)
  let card = CardService
    .newCardBuilder()
    .setHeader(
      CardService.newCardHeader()
        .setTitle(e.drive.activeCursorItem.title)
    )
  return card.build()
}

Adding setStateChanged(true) didn’t make a difference, although I’m not sure I was using it correctly:

const actionResponse = CardService.newActionResponseBuilder()
      .setNotification(notification)
      .setStateChanged(true);

Not getting styles while generating pdf from html

I am using pdfKit and html-to-text for generating pdfs from html. The problem currently is, styles from html are not reflecting in pdf. I am open for both type of solutions, if problem can be solved with these packages or we have to change.

const PDFDocument = require("pdfkit");
const {convert} =require('html-to-text');
const {PassThrough}=require("stream");
const generateCombinedCertificatePDFBuff = (context, compiledHTML) => {
  return new Promise(async (resolve, reject) => {
    try {
      const doc = new PDFDocument();
      const buffer = [];
      const stream = new PassThrough();

      doc.pipe(stream);
      doc.text(convert(compiledHTML));
      doc.end();

      stream.on("data", (chunk) => buffer.push(chunk));
      stream.on("end", () => resolve(Buffer.concat(buffer)));
      stream.on("error", (err) => reject(err));
    } catch (err) {
      console.log(err);
      reject(err);
    }
  });
};

Note: I am shifting from puppeteer (due to the huge time it is taking), i have also tried html-pdf (having some styling issues in it too), don’t recommend these.

Listen for any User-Action on a Webapp

I have a web based HMI and this is constantly turned on at the machine basically. I need to poll data from a PLC, for which i use exponential backoff with a growing delay. I suspect that this delay will rise over the period where no one is using the machine/HMI. But the moment someone is using the hmi i want to poll data and reset the delay. How can i achieve this globally in angular?

What is the angular way of doing this (if there is), or what is a good place to implement a listener?

In the name text field box French language characters i want to include for French user but getting invalid characters error in JS file

In the project that i am working on i want to add enhancement feature where user can add there French name in the first name field.
I want to include all the special characters for French, Rather then adding all the characters unicode i am finding a way where in minimum code i can include all the French characters.
Please find below JS code validation for First Name.

var firstNameRegex  = /^[a-zA-Zu3000u3400-u4DBFu4E00-u9FFF-'s]{1,45}$/;

I tried for 5 special characters like this

var firstNameRegex  = /^[a-zA-Z.u3000u3400-u4DBFu4E00-u9FFFu0105u0107u0119u0142u0144u00f3u015bu017au017c-'s]{1,45}$/;

But to include all the characters unicode separately seems bit lengthy
Does anyone has any idea how to include all the French Characters with an ease code.
Thanks in Advance

Extracting Data from Excel Cells Derived from Complex Calculations Across Multiple Sheets

I’m encountering a challenge in extracting data from an Excel cell that derives its value from complex calculations spanning multiple sheets. The data source involves calculated fields from various tables, making the extraction process intricate. How can I efficiently extract this data? Specifically, I need to retrieve information from an Excel cell whose value originates from calculated fields across different sheets. Any insights or methods to streamline this extraction process would be greatly appreciated.

I’ve experimented with OpenXML, Close XML, and JavaScript libraries for data extraction. While these tools effectively retrieve data from straightforward formulas and text, they struggle when confronted with large and intricate Excel formulas, often resulting in “#Num” errors as output.

Sequelize findAll function doesnt exist

I’m making a project with Sequelize and I’m stuck on this step. The problem is that when i load http://localhost:3000/hygro and try to run hygro.js i get this error in return

TypeError: hygroData.findALL is not a function
at C:Userseddyghygrometerrouteshygro.js:5:19
at Layer.handle [as handle_request] (C:Userseddyghygrometernode_modulesexpresslibrouterlayer.js:95:5)
at next (C:Userseddyghygrometernode_modulesexpresslibrouterroute.js:144:13)
at Route.dispatch (C:Userseddyghygrometernode_modulesexpresslibrouterroute.js:114:3)
at Layer.handle [as handle_request] (C:Userseddyghygrometernode_modulesexpresslibrouterlayer.js:95:5)
at C:Userseddyghygrometernode_modulesexpresslibrouterindex.js:284:15
at Function.process_params (C:Userseddyghygrometernode_modulesexpresslibrouterindex.js:346:12)
at next (C:Userseddyghygrometernode_modulesexpresslibrouterindex.js:280:10)
at expressInit (C:Userseddyghygrometernode_modulesexpresslibmiddlewareinit.js:40:5)
at Layer.handle [as handle_request] (C:Userseddyghygrometernode_modulesexpresslibrouterlayer.js:95:5)

im really lost on what to do, im newer to javascript. Im working on this for my classes and its just been very furstrating for me

heres my structure:
(i didnt include my libs folder it included setup things, im not sure if its necessary, if needed i can show it.)

package.json

{
  "name": "hygrometer",
  "version": "1.0.0",
  "description": "This will be the api for my hyrgometer data",
  "main": "app.js",
  "scripts": {
    "start": "node app.js",
    "test": "node test.js"
  },
  "author": "Eddy Gallegos",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.1",
    "consign": "^0.1.6",
    "express": "^4.18.2",
    "sequelize": "^6.37.1",
    "sqlite3": "^5.1.7"
  }
}

db.js

const fs = require("fs");
const path = require("path");
const Sequelize = require("sequelize");

let db = null;

module.exports = app => {
    if (!db){
        const config = app.libs.config;
        const sequelize = new Sequelize(
            config.database,
            config.username,
            config.password,
            config.params
        );
        db = {
            sequelize,
            Sequelize,
            models: {}
        };
        const dir = path.join(__dirname,"models");
        fs.readdirSync(dir).forEach(file => {
            const modelDir = path.join(dir, file);
            const model = require(modelDir)(sequelize,Sequelize.DataTypes);
            db.models[model.name]= model;
        });
        Object.keys(db.models).forEach(key => {
            db.models[key].options.classMethods.associate(db.models);
        });
    }
    return db;
};

app.js

const express =  require("express");
const consign = require ("consign");

const app = express();


consign()
    .include("libs/config.js")
    .then("db.js")
    .then("libs/middlewares.js")
    .then("routes")
    .then("libs/boot.js")
    .into(app);

routes/hygro.js

module.exports = app => {
    const hygroData = app.db.models.Readings;
    app.get("/hygro", (req,res) => {
        hygroData.findALL({}).then(data => {
            res.json({data:data});
    })
    });
}

models/locations.js

module.exports = (sequelize, DataType) => {
    const Locations = sequelize.define("Locations", {
        id: {
            type: DataType.INTEGER ,
            primaryKey: true,
            autoIncrement: true
        },
        name: {
            type: DataType.TEXT,
            unique: true,
            allowNull: false,
            validate: {
                notEmpty: true
        }
         },
         street: {
            type: DataType.TEXT,
            allowNull: false,
            validate : {
                notEmpty: true
            }

         },
         city: {
            type: DataType.TEXT,
            allowNull: false,
            validate:{
                notEmpty: true
            }
         },
         state: {
            type: DataType.TEXT,
            allowNull: false,
            validate:{
                notEmpty: true
            }
         },
         zip: {
            type: DataType.TEXT,
            allowNull: false,
            validate:{
                notEmpty: true
            }
         } 
    }, {
        classMethods: {
            associate: (models) => {
                Locations.hasMany(models.Readings);
            }
        }
    });
    return Locations;
}

models/readings.js

module.exports = (sequelize, DataType) => {
    const Readings = sequelize.define("Readings",{
        id: {
            type: DataType.INTEGER ,
            primaryKey: true,
            autoIncrement: true
        },
        date: {
            type: DataType.TEXT,
            allowNull: false,
            validate: {
                notEmpty: true
        }
         },
         temperature: {
            type: DataType.INTEGER,
            allowNull: false,
            validate : {
                notEmpty: true
            }

         },
         humidity: {
            type: DataType.INTEGER,
            allowNull: false,
            validate:{
                notEmpty: true
            }
         }
         
    }, {
        classMethods: {
            associate: (models) => {
                Readings.belongsTo(models.Locations);
            }
        }
    });
    return Readings;
}

How to insert the ng-template into dynamically added external element in Angular.?

I have following ng template in html file

<ng-template #myradio>
        <p-radioButton name="test" value="server1" [(ngModel)]="type"></p-radioButton>
        <p-radioButton name="test" value="server2" [(ngModel)]="type"></p-radioButton>
        <label class="server">Select the server
</ng-template>

And on page load another one external component will be loaded, onclick of the external component button, dialog will be loaded on the screen. And I want to insert above ng-template inside the dialog box

So, to attach the custom onclick and insert the viewchild I have added the following code,

export TestClass implements AfterViewInit{
    @ViewChild('myradio') myradio;
    typer= "server1";


    ngAfterViewInit(){
      document.querySelector('#external-div-element').addEventListener('click', () => {
              console.log("attached click");
              setTimeout(() => {
                      document.querySelectorAll('#external-div-element .p-grid')[2].appendChild(myradio);
              }, 500);
      });
    }
}

but the appendchild is not adding the element to the external dialog.

Spaces around ‘=’ in HTML tags for readability vs browser behavior [closed]

I’m writing HTML code and I’m wondering about the best practice for using spaces around tags and attributes. While I know browsers often ignore these spaces, is it better to include them for readability, or can I omit them entirely?

<script src='script.js'></script>
 

and

<script src = 'script.js'></script>

Are there any cases where extra spaces might cause problems?
I’d appreciate any insights on how to balance readability with browser behavior when it comes to spacing in HTML

What did you try?

I tried writing HTML code with spaces around the tags and attributes, like this: <script src="script.js"></script>.
I also tried omitting the spaces, like this: <script src='script.js'></script>.
I tested both versions in a web browser to see if they displayed differently.

What were you expecting?
I expected both versions of the code (with and without spaces) to display the same way in the browser.
However, I wanted to confirm if there’s any functional difference or potential issues with omitting spaces for readability purposes

Can we add span element by changing DOM in react website which updating every 2 seconds?

I want to know if it is possible to add elements to a website that already has React built in and is updating often. When I tried to buil it, when the data updated and the element I had added has been removed , and I received an error in the console.

Uncaught Error: Minified React error #418 ;

Uncaught Error: Minified React error #422

so i gone through many solution but didnt work any so i want to know is it possible to add element in DOM which changes frequently

i tried with mutation observer in that i did like whenever mutation obeserver find changes in data it adding element again but didnt works !!!!!!!!!!!

for this one first time i can see the element added for just 2 seconds after it has removed when data is upaded

Run tampermonkey userscript on non existing page?

I want to run a tampermonkey script on a non existing page in firefox (“Page not found” – default page). The typical method I use to inject a payload like this does not work:

window.addEventListener('load', function()
{
  setTimeout(init, 2000);
});

Of course, the load event might never be triggered, even if the firefox shows a default page “Server not found”. I mean there is HTML content on it, so I figured it might be possible, as it is sort of a page. I tried to only use setTimeout(init, 2000);, but this also did not run the code. I tried both individually:

// @match        http://not.existing.yahoo.com/
// @match        https://not.existing.yahoo.com/

Although the URL bar shows http://not.existing.yahoo.com/, it does not execute my code. The syntax is okay – it is just a console.log for reference. The page is a different one actually but for data protection I used this to hide the actual “userspace”. I run it on my companys domain, which I do not want to reveal. I mean, yahoo.com would propably return some page, But this is not what I want.

I do not want to create a webserver to run javascript, that I regularly want to run. If find it however very sketchy to load an actually existing page and overwrite the page, just to run a local javascript. And yes, I have a usecase, where a notejs server or similar is not an option. I actually need to run it directly in this browser window. I am using firefox for reference.

Just for reference, this is my init function:

async function init()
{
  console.log("TEST");
}

Did anyone ever pull this off – running a userscript in tampermonkey without an actually existing page?

What should be the Type of parameter “data” for constructor of a Class in Typescript

This is my code:

export class People {
    name: string;
    age: number;
    constructor(data: any) {
        this.name = data.name;
        this.age = data.age;
    }
}

I keep getting error for using any. What should be the type of data so that I won’t get any error?

I know I can also do:

export class People {
    name: string;
    age: number;
    constructor(name: string, age: number) {
        this.name = name;
        this.age = age;
    }
}

But I want this model to be used by any JSON say suppose a JSON fetched from server so that I can do:

const data = await fetchData();
const person = new Person(data)

What changes should I do to keep using the model for any object and also remove all the typescript errors?

I tried changing the type to : object , but then I get error on data.name and data.age

CSS – How to push element from right to left

I am using TailwindCSS.

I have 2 elements on the right. A span and an input
enter image description here
enter image description here

                      <div className="flex items-center justify-end text-2xl">
                        <span className="">CA$</span>
                        <input
                          type="number"
                          id="amount"
                        />
                      </div>

Current Behaviour

When I type in <input/>, part of the input is not visible in the UI.

Expected Behaviour

The input text should be completely visible. If there are lots of text, keep pushing <span/> from right to left, just like below.
enter image description here

.Set not updating value

Im trying to change my url params value,I have attated my code below.

let Pageurl = new URLSearchParams(window.location.search);
let Queryparam = Pageurl.get('paramsType');
window.onload = function() {
if(document.getElementById(paramsType)){
shiftContent(Queryparam);
} else {
window.location.search = '?' + 'paramsType=params';
}
};

* function shiftContent(newParam) {
  Pageurl.set('paramsType', newParam);
  }*


Here, the .set function now working, they didn’t change the paramsType value.

I try to changes my Queryparams value.