How can i modify indexing in a single object in javascript

I have an object list to store indexes just like that:

const initialIndexes = {
  0: [0,1,2],
  1: [0,1]
}

At this point I have a highlightedResultIndex variable. It gives an index like this:

highlightedResultIndex = 0 - case 1
highlightedResultIndex = 4 - case 2
highlightedResultIndex = 2 - case 3
...

And I finally try to get the following results by highlightedResultIndex

For the case 1:

result = {
 0: 0, // index from initialIndexes
 1: -1
}

For the case 2:

result = {
  0: -1,
  1: 1  // index from initialIndexes
}

For the case 3:

result = {
 0: 2  // index from initialIndexes
 1: -1
}

Maybe there is an easy method or there may be a certain algorithm for this, but I didn’t know how to research it so I wanted to write it here. I would be glad if you help.

Json read with javascript in input

I would like to do an input and when we start to write I want it to search in a Json file.
The Json file has cities and when we start to write a city i want differents proposition thanks to the Json file.
Have you got a solution.

javascript code running pefectly on codepen, but nothing happening on offline local server

enter image description hereThis issue is troubling me for a long time, the script should highlight the element for a few seconds, which is working on codepen but nothing is happening when I’m running it on the offline server through vs code, what could be the reason, my os is ( windows 7), chrome is the latest version, and so does vs code. Beginner here. Thanks
P.s-Not just this but code but some more scripts are not working(only on the localhost server).

javascript

const image = document.getElementById("c4");
let timeoutID;
document.querySelectorAll(".side-nav button").forEach(item => item.addEventListener("click", dance));

function dance() {
  image.classList.add('highlight');
  timeoutID = setTimeout(() => { 
    image.classList.remove('highlight');
    clearTimeout(timeoutID);
  }, 1000)
} 

CSS

.highlight {
  box-shadow: 0 4px 8px 0 rgba(218, 51, 119, 0.4), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
  animation: dance infinite linear 0.5s;
}

@keyframes dance {
  0% {
    transform: rotate(5deg);
  }
  25% {
    transform: rotate(-5deg);
  }
  50% {
    transform: rotate(5deg);
  }
  75% {
    transform: rotate(-5deg);
  }
  100% {
    transform: rotate(5deg);
  }
}
.side-nav {
  display: flex;
  flex-direction: column;
  margin-top: 54px;
  background: rgba(51, 51, 51,1);
  width: 75px;
  height: 657px;
  justify-content: space-around;
  align-items: stretch;
  line-height: 23px;
  position: fixed;
  border: 1px solid rgba(255, 51, 153,0.4);
}

.side-nav button{
  flex-grow: 1;
  display: flex;
  justify-content: center;
  align-items: center;
  text-decoration: none;
  background-color: #333;
  color: white;
  flex-wrap: wrap;
  text-align: center;
  margin: 5px;
  border: 1px solid transparent;
}

.side-nav button.active {
  background: #9999ff;
  color: black;
}

.side-nav button:hover:not(.active) {
 background: #555;
 border: 1px solid rgba(255, 51, 153,1);
 color: pink;
}

HTML

<div class="side-nav">
<button href="#" style="order:3">2k</button>
<button href="#" style="order:2">4k</button>
<button href="#" style="order:4">1080p</button>
<button href="#C4" style="order:1">8k</button>
</div>

<div class="row">

<div class="column">
<img src="https://images.pexels.com/photos/3990301/pexels-photo-3990301.jpeg?auto=compress&cs=tinysrgb&h=750&w=1260" id="c4">
<img src="../pics/pexels-alina-vilchenko-4550659.jpg" id="c5" >

</div>

Getting “Content value must be at least one character in length.” in Cloudflare Worker

So, I am creating a Cloudflare worker to send an email through an HTML form. Below is the JS code that I am using(I modified it a bit from the CF blog to use an HTML form instead to send an email).

    addEventListener("fetch", event => {
    event.respondWith(handleRequest(event.request))
})
let body = {};
async function handleRequest(request) {
    let content = "just drop if it fails...okay ?";
    for( var i of request.headers.entries() ) {
        content += i[0] + ": " + i[1] + "n";
    }
     
    let send_request = new Request("https://api.mailchannels.net/tx/v1/send", {
        "method": "POST",
        "headers": {
            "content-type": "application/json",
        },
        "body": JSON.stringify({
            "personalizations": [
                { "to": [ {"email": body.email,
                        "name": body.name}]}
            ],
            "from": {
                "email": "[email protected]",
                "name": "Amara Silva",
            },
            "subject": body.subject,
            "content": [{
                "type": "text/plain",
                "value": body.message,
            }],
        }),
    });
        let respContent = "";
        // only send the mail on "POST", to avoid spiders, etc.
    if( request.method == "POST" ) {
    
    const formData = await request.formData();
        for (const entry of formData.entries()) {
                      body[entry[0]] = entry[1];
              }
        //fls = JSON.parse(JSON.stringify(body));

        const resp = await fetch(send_request);
        const respText = await resp.text();
 
        respContent = resp.status + " " + resp.statusText + "nn" + respText + body.name; 
    }
 
    let htmlContent = "<html><head></head><body><pre>" +
        '</pre><p>Click to send message: <form method="post">Name: <input type="text" name="name"/><br>Email: <input type="text" name="email"/><br>Sub: <input type="text" name="subject"/><br>Msg: <input type="text" name="message"/><br><input type="submit" value="Send"/></form></p>' +
        "<pre>" + respContent + "</pre>" +
        "</body></html>";
    return new Response(htmlContent, {
        headers: { "content-type": "text/html" },
    })
}

The problem is that it working if I hardcode the values but if supply them dynamically from the JSON variable then it’s not working. I am keep getting 404 error with “”Content value must be at least one character in length.”” in the response. I am a beginner in JS…how should I fix this?

D3 v3 nodes distance missing

I am pretty confused regarding the following behavior. The D3v3 forced graph below shows 4 nodes, with at least one link to another node. I dont know why, but the distance between the nodes is broken as I got more than 3 nodes. Even if distance and charge are set.

        var width = window.innerWidth,
            height = window.innerHeight;

        var svg = d3.select("body").append("svg")
            .attr("width", width)
            .attr("height", height)
            .call(d3.behavior.zoom().on("zoom", function() {
                svg.attr("transform", "translate(" + d3.event.translate + ")" + "scale(" + d3.event.scale + ")")
            }))
            .append("g")

        var defs = svg.append("defs")

        const arc = d3.svg.arc()
            .innerRadius(80 + 10)
            .outerRadius(80 + 10)
            .startAngle(-Math.PI)
            .endAngle(Math.PI)

        defs.append("path")
            .attr("id", "curvedLabelPath")
            .attr("d", arc())  

        ////////////////////////
        // outer force layout

        var outerData = {
            "nodes": [
                { "id": "A" }, 
                { "id": "B" },
                { "id": "C" },
                { "id": "D" }
            ],
            "links": [
                { "source": 0, "target": 1},
                { "source": 1, "target": 2},
                { "source": 2, "target": 0},
                { "source": 3, "target": 0}
            ]
        };

        var outerLayout = d3.layout.force()
            .size([width, height])
            .charge(-1000)
            .gravity(0.85)
            .distance(500)
            .links(outerData.links)
            .nodes(outerData.nodes)
            .start();

        var outerLinks = svg.selectAll("g")
            .data(outerData.links)
            .enter().append("g")
            .attr("cursor", "pointer")
            //.attr("class", "g.outerLink")

        var outerLine = outerLinks
            .append("path")
            .attr("id", function (_, i) {
                return "path" + i
            })
            .attr("stroke", "black")
            .attr("opacity", 0.75)
            .attr("stroke-width", 3)
            .attr("fill", "transparent")
            .attr("cursor", "default")

        var outerNodes = svg.selectAll("g.outer")
            .data(outerData.nodes, function (d) { return d.id; })
            .enter()
            .append("g")
            .attr("class", "outer")
            .attr("id", function (d) { return d.id; })
            .call(outerLayout.drag()
                .on("dragstart", function () {
                    d3.event.sourceEvent.stopPropagation();
                })
            )
            .attr("cursor", "pointer")

        outerNodes
            .append("circle")
            .style("fill", "whitesmoke")
            .style("stroke", "black")
            .style("stroke-width", 3)
            .attr("r", 80);

        outerNodes
            .append("text")
            .append("textPath")
            .attr("href", "#curvedLabelPath")
            .attr("text-anchor", "middle")
            .attr("startOffset", "25%")
            .attr("font-size", "30px")
            .attr("cursor", "pointer")
            .text(function (d) {
                return d.id
            })

        outerLayout
            .on("tick", function() {
                outerLine.attr("d", function (d) {
                    var dx = (d.target.x - d.source.x),
                        dy = (d.target.y - d.source.y),
                        dr = Math.sqrt(dx * dx + dy * dy);
                    return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y;
                });

                outerNodes
                    .attr("transform", function (d) { return "translate(" + d.x + "," + d.y + ")"; });
            })    
    body {
        background: whitesmoke,ยด;
        overflow: hidden;
        margin: 0px;
    }
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>D3v3 forces</title>
    <!-- d3.js framework -->
    <script src="https://d3js.org/d3.v3.js"></script>
</head>

</html>

I am aware force setup is different in v4 and higher, still regarding my opinion some features are handled better in v3. I would be glad if an D3 expert could either help or explain those behaviour.

using theme.spacing inside theme definition

I have the following theme setup:

export const themeDefault = createTheme({
  themeName: 'Default (Mortgage Hub)',
  spacing: 4,
  ...typography,
  palette,
  components: {
    MuiButton: {
      styleOverrides: {
        root: {
          paddingLeft: theme.spacing(12),
          paddingRight: theme.spacing(4),
          border: '10px',
        },
      },
    },
  },
})

And I would like to use theme.spacing inside however, of course. Theme is not defined yet. I have tried to use makeStyles & useTheme however these are hooks. So of course they will not work.

Are you able to supply styleOverrides once the theme has been indicated?

Print an array from a function inside Angular HTML

I’m doing an app where I print some cars (I receive them from the database) and in one column I have one string with multiple tags that are divided by commas, I made a function to receive that as an array of words and then print each word for make tags, but I don’t really know how to call the function or how to do it because it’s repeating multiple times when it shouldn’t do that.

<!-- Category Card -->
<div *ngFor="let car of cars" class="col-md-4">
  <div class="card-image-overlay m-auto" id="tags">
    {{separar(car?.tags)}}
  </div>
</div>

Then the code of the function “separar”:

public separar(string) {
  var palabras = [];
  palabras = string.split(",");
  for (var i = 0 ; i < palabras.length ; i++) {
    document.getElementById("tags").innerHTML +=
      ("<span class='card-detail-badge'>" + palabras[i] + "</span>");
  }
}

I’m getting this:

enter image description here

and it should only print 3 times those tags.

Probably is a mistake very easy but Im new to angular and my teacher doesn’t know why it doesn’t work. ๐Ÿ™

Simplfication of function requested [closed]

Is there a quick/elegant equivalent in TypeScript for this?

foo (len : number, str : string) : string
{
    let ret : string = "";
    for (let i = 0; i < len; i++)
    {
        ret += (i + 1) + str;
    }
    return ret;
}



foo (3, "x");     // result: 1x2x3x
foo (4, "baz");   // result: 1baz2baz3baz4baz

Mabe there is some ArrayOf, map, lambda, … but I am not very good in that.

Javascript – get current folder of HTA

I have an old solution (not created by me ..) which works like this:

  • Double click on a HTA which is stored at the internal network
  • it calls Internet Explorer which displays a “dialogue” (the HTA)
  • I select a XML file with HTA
  • I press the button “Check” which calls a Javascript-file to check the XML
  • Report the result in HTA

Usually it works as described, but now a new user on the old PC has problems:
It does not find the JS-file.

In the HTA there is the snippet

....    
ID="objHTML"
.....
<script language="JavaScript">
var instpfad=objHTML.commandLine;
var instpfad=instpfad.substr(0,instpfad.lastIndexOf('\'));
instpfad=instpfad.replace('"',''); //allf. " am Anfang entfernen
//alert(instpfad);

Every working PC returns the path of the network-folder where the HTA and the JS are stored; just the “bad PC” returns nothing and later it displays “Cannot find c:foobar.js”

  • We checked the access of the user to the network – it’s OK
  • We checked the security settings of IE – it’s OK

Any ideas what’s wrong?

How to start this nodejs (hapijs ) API project ,alone without docker?

I am working on a Nodejs -Hapijs project. This project have a “Make” file to start the

project, but the project will start in docker , I can not debug the API also the project

will start as a whole ( API + UI ) in docker.

I tried to start the API independently but could not do it.

Here is the API file structure , package.json file Image od API folder structure

"scripts": {
    "build": "npm run clean && .tsc",
    "clean": "rm -rf ./dist",
    "lint": "tslint -p ./tsconfig.json -c ./tslint.json",
    "lint-serve": "npm run lint & npm run serve",
    "serve": "node ./index.js",
    "start": "if [[ $NODE_ENV == "production" ]]; then npm run serve; else npm run watch; fi",
    "test": "jest --verbose --coverage --detectOpenHandles",
    "test:watch": ".jest --verbose --watchAll",
    "watch": "tsc-watch --onSuccess "npm run lint-serve""

This is the package.json file (scripts part).This project is written in typescript, I can give you more required details , I am not sure what information I should add other than this .

THINGS I HAVE TRIED

  1. npm start

Any help

application sign-on issues using angular-google-gapi and Google platform.js script

Our application is deployed on GCP (Google Cloud). It uses Google based authentication. Recently since 25th Feb 22 , we have been observing sign in issues
When we hit the developer console on chrome , we see below error
Error is : bundle.js:17014 Type Error: Cannot read properties of undefined (reading ‘setApiKey’)

The error line then points to below api :

This api is further calling Google platform.js script which opens the Google sign in page (the user puts his/her email and then they log in to app post authentication).

This issue is intermittent e.g. it happens for 20 mins and then we clear the chache and cookies and then it goes away but then it comes back again. This workaround does not even work in all attempts and hit and trail works. Not sure what is happening here.

Need help creating a dynamic selection using jquery

Trying to make a dynamic selection using jquery and requesting data from a server side script using a url.

So i want to request data from a URL to populate my selector.

enter code here <script type="text/javascript">

$(document).ready(function(){
$("button").click(function(){
   
$.get("CountryData.php"), (function(data, status){
    alert("Data: " + data + "nStatus: " + status);
  });
});

});“

This is what ive been trying but as a first time user of jquery im baffled

How to access to initialised app with firebase admin

In Next.js application I’m trying to create api where I can do some stuff with firebase-admin but I always get an error that app already initialised

Error: The default Firebase app already exists. This means you called initializeApp() more than once without providing an app name as the second argument. In most cases you only need to call initializeApp() once. But if you do want to initialize multiple apps, pass a second argument to initializeApp() to give each app a unique name.

I understand why I get this error. Because I already initialise this app in my session files. But I can’t find documentation how to use it in another place like API. So how to use initialised app? Or there is another solution?

Code where I get an error (my API file):

import { initializeApp } from 'firebase-admin/app'
import { getAuth } from 'firebase-admin/auth'
const app = initializeApp()

export default function handler (request, response) {
  const { email } = request.body
  if (request.method === 'POST') {
    const actionCodeSettings = {
      url: process.env.NEXT_PUBLIC_DOMAIN
    }

    getAuth(app)
      .generateEmailVerificationLink(email, actionCodeSettings)
      .then((link) => {
        return response.status(200).json({ status: 'OK', email, link })
      })
      .catch((error) => {
        return response.status(200).json({ status: 'OK', email, error })
      })
  } else {
    return response.status(400).json({ status: 'Bad request' })
  }
}

And my sessions files:
initFirebase.js

import { initializeApp } from 'firebase/app'
import { getFirestore } from 'firebase/firestore'

const config = {
  apiKey: process.env.NEXT_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.NEXT_PUBLIC_FIREBASE_STORAGE_BUCKET
}

const app = initializeApp(config)
const db = getFirestore()

export { app, db }

firebaseAdmin.js

import * as admin from 'firebase-admin'

const firebasePrivateKey = process.env.FIREBASE_PRIVATE_KEY_ID
if (!admin.apps.length) {
  admin.initializeApp({
    credential: admin.credential.cert({
      projectId: process.env.FIREBASE_PROJECT_ID,
      clientEmail: process.env.FIREBASE_CLIENT_EMAIL,
      privateKey: firebasePrivateKey.replace(/\n/g, 'n')
    })
  })
}
export const verifyIdToken = (token) => {
  return admin
    .auth()
    .verifyIdToken(token)
    .catch((error) => {
      throw error
    })
}

Javascript change variable to targeted id

I have a dot navigation system with a slider I created. All the dots have the id of a number (1, 2, 3, 4) and when you click a dot I want the variable count to change to the ID of the dot, but I have no idea how I can get the ID.

    let tgt = event.target;
    let cur = tgt.querySelectorAll('.CDot')

This code shows me the right element of the dot that I need the ID of.

    console.log(cur.id)
    control.count = cur.id;

I tried doing something like this, but it’s undefined. I tried alot, but I can’t seem to get the id of the element. Does anybody know the right way?