Change Button’s color twice when it’s clicked

I’m trying to create a button whose change background color (to green) when it is cliked. But when it is cliked againg the button returns to the original background color (from orange).

var btn1 = document.getElementById("btn-1")

if (btn1.style.backgroundColor = "orange") {
        btn1.addEventListener("click", function () {
        btn1.style.backgroundColor = "green"
    })
} else {btn1.addEventListener("click", function () {
    btn1.style.backgroundColor = "orange"
})
    }

Could you help me? Thx!

I’m trying to create a button whose change background color (to green) when it is cliked. But when it is cliked againg the button returns to the original background color (from orange).

TypeScript: Error instance for `util.promisify(chpro.execFile)`

import chpro from 'node:child_process';
const execFile = util.promisify(chpro.execFile);

try {
  await execFile(
    'doesnotexist',
  );
} catch (error) {
  // 'error' is of type 'unknown'.ts(18046)
  console.log(error.stderr);
}

How do I properly do a error instanceof X here to so that error is not of type unknown? And so that it contains the stderr?

The relevant file for the type is from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/node/child_process.d.ts but I cannot deduct from that what to do.

It might be that this typing is missing?

Set value of input control from input_group

I am using a trying to set this input control using $input_group.find('input'); but it is not getting set. Is this the correct way to use find and then set the value of the input control or is there anyway to do this?

            var $container = $('#gridrow-field-container');
            var template = $('#gridrow-template-input-group').get(0);

            $(item.MeetingPollingPartsValues).each((indexPartsValues, PartsValues) => {
                var $input_group = $(template.content.cloneNode(true));
                var inputControl = $input_group.find('input');
                inputControl.val(PartsValues.QuestionValue);

                console.log(inputControl);

                console.log($input_group);
                $container.append($input_group);
                $('input_group').val(PartsValues.QuestionValue);
            });


 <template id="gridrow-template-input-group">
         <div class='row mb-3' id='newrowItem_1'>
            <div class="input-group">
               <input type='text' id='fieldrowItem_1' name='name[]' class='form-control fieldrowItem mb-3' placeholder="Row 1" data-value="0" >
               <span  id='spanrowItem_1' class="input-group-addon" style="cursor:pointer;"  onclick="RemoveRow(this)"  >
                  <i class="fa fa-remove" style="color:#CDCDCD"></i>
              </span>
         </div>
         /div>
 </template>

Why do I get duplicative messages to my content script only when I have the options page opened in another tab in my Chrome Extension?

Manifest V3 Chrome Extension duplicating messages to content script when options page is open.

I am working on my first V3 Chrome Extension (pretty much done in fact). I’ve realized I have an annoying bug causing duplicative messages to be sent to my content script only when I have the options page opened in another (or multiple) tab(s). I have an event listener on tabs.Updated in my service worker that is sending a message to my content script on a very strict filtering rule. This is working as intended just fine, BUT if I have the options page open in another tab, my content script receives 2 messages instead of one. If I have 2 options pages open, I get 3 messages etc.

When inspecting the console of the background script it only shows one message sending. When inspecting an options page, I see the same message in background plus an additional message being sent. I tried tracking this down but not getting any hits that are applicable, and it doesn’t appear that I have multiple instances of background running concurrently when I look at my service worker in Chrome Dev Tools. Option page sends messages to

manifest

"manifest_version": 3,
    "icons": {
        "16": "images/favicon.ico",
        "192": "images/icon-192-maskable.png",
        "512": "images/icon-512-maskable.png"
    },
    "action": {
        "default_title": "Target Site Dev Tools",
        "default_icon": "images/icon-512-maskable.png",
        "default_popup": "pages/popup.html"
    },
    "options_page": "pages/options.html",
    "permissions": [
        "activeTab",
        "identity",
        "storage",
        "webRequest"
    ],
    "background": {
        "service_worker": "scripts/background.js",
        "type": "module"
    },
    "content_scripts": [
        {
            "css": [
                "css/contentScript.css"
            ],
            "matches": [
                "https://Target-Site.com/*"
            ],
            "js": [
                "scripts/contentScript.js"
            ],
            "run_at": "document_end"
        }
    ],
    "host_permissions": [
        "https://app.Target-Site.com/Target/*",
        "https://api.Target-Site.com/2.0/*"
    ],
    "web_accessible_resources": [
        {
            "resources": [
                "images/*.*",
                "injectedHTML/*.html"
            ],
            "matches": [
                "https://app.Target-Site.com/*"
            ]
        }
    ]
}

Issue with select2 not searching data get from local json file with ajax call

Can’t make select2 search data from local json file. Please help.
This is what I manage to compile form the net (sniplet below). (I am not a JS programmer nor Java ☹ ).

I am working with ManageEngine Servicedesk plus so not all things work and as you can see I for example need to use “$CS.element”. The script is a part of a Forms and Rules functionality in issue template builder.

The example below almost work. It is displaying list for the select2. However, I can’t make it search.
I can select items with mouse click, but with typing I can only see that it is underlining the text in the list below search window and that is it.
Select2-Issue

$CS.element('data-field').select2({
    ajax: {
        dataType: "json",
        url: "myfilelink.json",
        results: function (res) {
            var json_data = res;
            var data = [];
            more = "true";
            for(i = 0; i < json_data.technicians.length; ++i){
                var name = json_data.technicians[i].name;
                data.push({id: i+1, text: name});
            }
            return { results: data, more: more };
        }
    }
});

How do I get the coefficients of a function of x and y in Regex?

As in I have f(x,y) = [user input] e.g. the user might input x-y+2

I’ve tried things like ([+-]?d+(.d+)?)[xX] or /(-?d+)|(-?d+)/g but a recurring issue no matter what I try is that they don’t work in edge cases. Specifically when the coefficients are 1 or -1.

Another thing is not knowing how to make sure the x term always comes first in the output array, on some things I’ve tried (as well as the rest of it not working) the output array changes around when you change x-y+2 to -y+x+2 or whatever.

The main one is the “not detecting +-1” though, I can fix the other one myself.

How to fix Firebase collection() error in Vue.js component using Firestore?

Cant connect to firebase:
my code in init.js:

import { initializeApp } from "firebase/app";
import { getFirestore } from "firebase/firestore";

const firebaseConfig = {
  apiKey:.. ,
  authDomain: ,
  projectId:..
  storageBucket: ..
  messagingSenderId: ..
  appId: ..
  measurementId:,
};


initializeApp(firebaseConfig);
const db = getFirestore();
export { db };

then in a component (I know it should be in vuex but im just trying to check it):

import { collection, addDoc } from "firebase/firestore";
import db from "../firebase/init";

async addQuestion() {
      const colRef = collection(db, "Questions");
      console.log(colRef);

and i get:
Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore
FirebaseError: Expected first argument to collection() to be a CollectionReference, a DocumentReference or FirebaseFirestore

in firestore a have a collection namde Questions

I tried all diffrent ways and i dont really understand where is a problem?

I tried all diffrent ways and i dont really understand where is a problem?

No loader is configured for “.html” files: index.html Vitejs

Greetings I have problem. I am using Visual studio 2022 and created two projects there for one solution. One for back-end (ASP.NET) and the second one for fron-end (vuejs and vite). So here starts the problem. I used npm create vue@3 command to create vue project. And its launched fine , but when I did same thing in folder of front-end in my sln project vite throws error what it can not find index.html file

Error:   Failed to scan for dependencies from entries:
  D:/Projects/C#/DAINIS/vueapp/index.html

  X [ERROR] No loader is configured for ".html" files: index.html

    <stdin>:1:7:
      1 │ import "D:/Projects/C#/DAINIS/vueapp/index.html"
        ╵        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~


    at failureErrorWithLog (D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:1638:15)
    at D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:1050:25
    at runOnEndCallbacks (D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:1473:45)
    at buildResponseToResult (D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:1048:7)
    at D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:1060:9
    at new Promise (<anonymous>)
    at requestCallbacks.on-end (D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:1059:54)
    at handleRequest (D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:725:19)
    at handleIncomingPacket (D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:747:7)
    at Socket.readFromStdout (D:ProjectsC#DAINISvueappnode_modulesesbuildlibmain.js:675:7)

Just in case I did not changed project it is as is.
Project structure
Error dump example

I tried solutions found here and here in stack overflow but still no luck

Nest.js empty Body for form data

I have a simple controller, in this controller I have this endpoint

@Post('/temp')
async asdf(
  @Body() form: Record<string, string>,
  @Res({ passthrough: true }) response: Response,
) {
  this.logger.debug(JSON.stringify(form));
  await response.json({ ok: true, form: JSON.stringify(form) });
}

When I try to POST some form data on it, using cURL or the browser, the object form is empty.

Example:

curl -X POST http://localhost:4000/mycontroller/temp -H "Content-Type: application/x-www-form-urlencoded" -d "param1=value1&param2=value2"

Results in

{“ok”:true,”form”:”{}”}

Other controllers work; I can’t see any difference between my controller and the endpoint to others.

What I’m doing wrong or missing?

Why does the Canvas context’s save/restore method fail to remove a rectangle?

HTML Canvas context’s save/restore method not working.

There is a simple example of drawing a rectangle on canvas an then trying to restore the previous state, which actually does not work. What am I doing wrong with this ?

Am I stupid or something ?

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');

// Draw red rectangle
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 50, 50);

// Save the current state
ctx.save();

// Add blue rectangle
ctx.fillStyle = 'blue';
ctx.fillRect(70, 10, 50, 50);

// Restore the saved state
ctx.restore();  // this should remove blue rectangle
canvas {
  border: 1px solid black
}
<canvas id="canvas" width="200" height="200"></canvas>

Service class and Rxjs subject in Angular for reactivity

I’m new to Angular and I’m trying to learn a few things.
I made a system for login/register where a user can login or register. I’m trying now to make a way to persist the user to be logged in on refresh by checking if he has a token in the localStorage.

I did that, but, my question for you is that:

I have a authService that has a property userFetched: boolean = false. I inject the authService in the app.component.ts and inside the app component I have ngOnInit where I send a simple post request to the backend to verify the token (if he has), then if all ok, I set this.authService.userFetched = true from within app component.

Then in my app.component.html it seems to reflect the changes, also in other components as well. It seems to be reactive when the value changes/update.

Is this a good approach or should I use Subject using Rxjs?

// app.component.ts

import { Component, OnInit } from "@angular/core";
import { AuthService } from "./services/auth.service";

@Component({
    selector: "app-root",
    templateUrl: "./app.component.html",
    styleUrls: ["./app.component.css"],
})
export class AppComponent implements OnInit {
    constructor(protected authService: AuthService) {}

    ngOnInit(): void {
        console.log("called");
        console.log("called with:", this.authService.userFetched);
    }
}

// app.component.html

<div>User fetched: {{ authService.userFetched }}</div>
<app-navigation></app-navigation>
<router-outlet></router-outlet>


// AuthService

import { Injectable, OnInit } from "@angular/core";
import { Observable, of, throwError } from "rxjs";
import { HttpClient, HttpErrorResponse, HttpHeaders } from "@angular/common/http";
import { catchError } from "rxjs/operators";

interface User {
    id: number;
    name: string;
    email: string;
}

interface UserCredentials {
    name: string;
    password: string;
}

@Injectable({
    providedIn: "root",
})
export class AuthService implements OnInit {
    public userFetched: Boolean = false;

    constructor(private http: HttpClient) {}
}

// rest of the code...

Intl.NumberFormat() for currency PGK, it is showing PGK as narrow symbol instead of K

The Intl.NumberFormat for currency PGK, it is showing PGK as narrow symbol instead of K
What can I do to fix this?

I cannot replace the Intl.NumberFormat function and I cannot add additional code after the function is called, I can only change the the arguments.

const number = 123456.789;

console.log(new Intl.NumberFormat('en', { style: 'currency', currency: 'PGK', currencyDisplay: "narrowSymbol", }).format(number));
// Expected output: "K 123.456,79"
// Output: "PGK 123.456,79"

console.log(new Intl.NumberFormat('en', { style: 'currency', currency: 'MMK', currencyDisplay: "narrowSymbol", }).format(number));
// Output: "K 123.456,79"

Cannot Get EJS Files to Render in HTML: What’s Going Wrong?

I can’t render my EJS files as HTML. Every time I try to access my EJS file, I get a “Cannot GET /store.html” response.

if (process.env.NODE_ENV !== 'production') {
    require('dotenv').config()
}

const stripeSecretKey = process.env.STRIPE_SECRET_KEY
const stripePublicKey = process.env.STRIPE_PUBLIC_KEY

const express = require('express')
const path = require('path')
const app = express()
const fs = require('fs')
const stripe = require('stripe')(stripeSecretKey)

app.set('views', path.join(__dirname, 'views'))
app.set('view engine', 'ejs')
app.use(express.json())
app.use(express.static('public'))

app.get('/store', (req, res) => {
fs.readFile('items.json', (error, data) => {
    if (error) {
        res.status(500).end()
    } else {
        res.render('store.ejs', {
            items: JSON.parse(data)
        })
    }
})
})

app.listen(3000)

I would like to know what I should do?

Origin error when using postMessage from parent to iframe (Failed to execute ‘postMessage’ on ‘DOMWindow’)

I’m trying to make two React Apps communicate by sending messages containing stringified objects.

The parent (http://localhost:3000) sends a message through postMessage like so:

    let iframe = document.querySelector("iframe")

    useEffect(() => {
        if (!!localStorageObject && !!iframe) {
            iframe?.contentWindow?.postMessage(localStorageObject, "http://localhost:3001")
        }
    }, [localStorageObject, iframe])

    // ...file and start of return

   <iframe
       style={{minHeight: window.outerHeight, width: '100%', border: "none"}}
       referrerPolicy="strict-origin-when-cross-origin"
       src={myUrlWithParams}
       title="App"
       allow="clipboard-write"
       id={"iframe"}
   />

The iFrame (http://localhost:3001) does not recieve the message, at least not immediatly (I have to wait for a react soft refresh for the logs to show up).

The error thrown at first is:

Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('http://localhost:3001') does not match the recipient window's origin ('http://localhost:3000').

Amcharts integration using Javascript in Twig file

I’m attempting to use amCharts in my Twig file, but I’m facing issues with parsing the code. Regardless of what I try, the charts don’t seem to work. However, when I place my code outside of the JavaScript loop, I can see that the data is being retrieved correctly.
But I couldn’t do this between tags. No results are returned.

<div id="kt_charts_widget_15_chart" class="min-h-auto ps-4 pe-6 mb-3 h-350px"></div>
<script>
    var KTChartsWidget15 = {
        init: function () {
            var e = am5.Root.new("kt_charts_widget_15_chart");
            if (e) {
                var t,
                    a = function () {
                        t = am5.Root.new(e);
                        t.setThemes([am5themes_Animated.new(t)]);

                        var salesData = [
                            {% for data in getLastDays %}
                            {
                                country: {{ data.sales_date }},
                                visits: {{ data.total_sales }},
                                icon: "https://www.amcharts.com/wp-content/uploads/flags/united-states.svg",
                                columnSettings: { fill: am5.color(KTUtil.getCssVariableValue("--bs-primary")) },
                            },
                            {% endfor %}
                        ];

                        var l = t.container.children.push(am5xy.XYChart.new(t, { panX: !1, panY: !1, layout: t.verticalLayout }));

                        var r = l.xAxes.push(
                            am5xy.CategoryAxis.new(t, {
                                categoryField: "country",
                                renderer: am5xy.AxisRendererX.new(t, { minGridDistance: 30 }),
                                bullet: function (e, t, a) {
                                    return am5xy.AxisBullet.new(e, {
                                        location: 0.5,
                                        sprite: am5.Picture.new(e, {
                                            width: 24,
                                            height: 24,
                                            centerY: am5.p50,
                                            centerX: am5.p50,
                                            src: a.dataContext.icon,
                                        }),
                                    });
                                },
                            })
                        );

                        r.get("renderer").labels.template.setAll({ paddingTop: 20, fontWeight: "400", fontSize: 10, fill: am5.color(KTUtil.getCssVariableValue("--bs-gray-500")) });
                        r.get("renderer").grid.template.setAll({ disabled: !0, strokeOpacity: 0 });
                        r.data.setAll(salesData);

                        var o = l.yAxes.push(am5xy.ValueAxis.new(t, { renderer: am5xy.AxisRendererY.new(t, {}) }));
                        o.get("renderer").grid.template.setAll({ stroke: am5.color(KTUtil.getCssVariableValue("--bs-gray-300")), strokeWidth: 1, strokeOpacity: 1, strokeDasharray: [3] });
                        o.get("renderer").labels.template.setAll({ fontWeight: "400", fontSize: 10, fill: am5.color(KTUtil.getCssVariableValue("--bs-gray-500")) });

                        var i = l.series.push(am5xy.ColumnSeries.new(t, { xAxis: r, yAxis: o, valueYField: "visits", categoryXField: "country" }));
                        i.columns.template.setAll({ tooltipText: "{categoryX}: {valueY}", tooltipY: 0, strokeOpacity: 0, templateField: "columnSettings" });
                        i.columns.template.setAll({ strokeOpacity: 0, cornerRadiusBR: 0, cornerRadiusTR: 6, cornerRadiusBL: 0, cornerRadiusTL: 6 });
                        i.data.setAll(salesData);
                        i.appear();
                        l.appear(1000, 100);
                    };

                am5.ready(function () {
                    a();
                });
            }
        },
    };

    "undefined" != typeof module && (module.exports = KTChartsWidget15);

    KTUtil.onDOMContentLoaded(function () {
        KTChartsWidget15.init();
    });
</script>