how to create a chart with a callback function for the x-axis if the values are numbers?

I try to create a line-chart with numbers for the x-axis (the ‘kw’ value), but it only works if the value is in string format. I use a callback function to add a string to the value in the legend. How can I create the chart with numbers from the data and add a string to it for the legend?
I hope you can see in my example what I mean.

With String:

var dString = [{
    kw: '1',
    wert: 120
  },
  {
    kw: '2',
    wert: 125
  },
  {
    kw: '3',
    wert: 110
  }
];

var dNumber = [{
    kw: 1,
    wert: 120
  },
  {
    kw: 2,
    wert: 125
  },
  {
    kw: 3,
    wert: 110
  }
];


dia(dString, 'dia');
dia(dNumber, 'dia2');


function dia(d, id) {
  var configDia = {
    data: {
      datasets: [{
        type: 'line',
        label: 'Ist',
        data: d,
        parsing: {
          xAxisKey: 'kw',
          yAxisKey: 'wert'
        }
      }]
    },
    options: {
      scales: {
        x: {
          ticks: {
            display: true,
            callback: function(value, index, ticks) {
              return `KW ${this.getLabelForValue(value)}`;
            }
          }
        },
        y: {
          ticks: {
            callback: function(value, index, ticks) {
              return value + '%';
            }
          }
        }
      }
    }
  };

  var ctx = document.getElementById(id);
  var myChart = new Chart(ctx, configDia);
}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.min.js"></script>
<canvas id="dia"></canvas>
<canvas id="dia2"></canvas>

Form check prevent from submiting even when everything is ok

i have a problem with my form, i ran it through the form checker and even when everything is successful it still won’t submit. i tried to change it a lot of times and im not sure how to keep the code like that instead of one function that will return on form submit.

const form = document.getElementById('form');
const username = document.getElementById('username');
const email = document.getElementById('email');
const password = document.getElementById('password');
const password2 = document.getElementById('password2');
const genderSelected = document.getElementById('select');
//Show input error messages
function showError(input, message) {
  const formControl = input.parentElement;
  formControl.className = 'form-control error';
  const small = formControl.querySelector('small');
  small.innerText = message;
}

//show success colour
function showSucces(input) {
  const formControl = input.parentElement;
  formControl.className = 'form-control success';
}

//check email is valid
function checkEmail(input) {
  const re = /^(([^<>()[]\.,;:s@"]+(.[^<>()[]\.,;:s@"]+)*)|(".+"))@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}])|(([a-zA-Z-0-9]+.)+[a-zA-Z]{2,}))$/;
  if (re.test(input.value.trim())) {
    showSucces(input)
  } else {
    showError(input, 'Email is not invalid');
  }
}


//checkRequired fields
function checkRequired(inputArr) {
  inputArr.forEach(function(input) {
    if (input.value.trim() === '') {
      showError(input, `${getFieldName(input)} is required`)
    } else {
      showSucces(input);
    }
  });
}


//check input Length
function checkLength(input, min, max) {
  if (input.value.length < min) {
    showError(input, `${getFieldName(input)} must be at least ${min} characters`);
  } else if (input.value.length > max) {
    showError(input, `${getFieldName(input)} must be les than ${max} characters`);
  } else {
    showSucces(input);
  }
}

//get FieldName
function getFieldName(input) {
  return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}

// check passwords match
function checkPasswordMatch(input1, input2) {
  if (input1.value !== input2.value) {
    showError(input2, 'Passwords do not match');
  }
}

//check if selected a gender
function checkSelect(option) {
  if (select.value)
    showSucces(option);
  else
    showError(option, 'Please select a gender');
}



//Event Listeners
form.addEventListener('submit', function(e) {
  e.preventDefault();

  checkRequired([username, email, password, password2, genderSelected]);
  checkLength(username, 3, 15);
  checkLength(password, 6, 25);
  checkEmail(email);
  checkPasswordMatch(password, password2);
  checkSelect(genderSelected);
});
@import url('https://fonts.googleapis.com/css?family=Open+Sans&display=swap');
 :root {
  --succes-color: #2ecc71;
  --error-color: #e74c3c;
}

* {
  box-sizing: border-box;
}

.wrapper {
  width: 400px;
  max-width: 100%;
  box-sizing: border-box;
  padding: 25px;
  margin: 8% auto 0;
  position: relative;
}

.container {
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
  width: 400px;
}

h2 {
  text-align: center;
  margin: 0 0 20px;
}

.form {
  padding: 30px 40px;
}

.form-control {
  margin-bottom: 10px;
  padding-bottom: 20px;
  position: relative;
}

.form-control label {
  color: #777;
  display: block;
  margin-bottom: 5px;
}

.form-control input {
  border: 2px solid #f0f0f0;
  border-radius: 4px;
  display: block;
  width: 100%;
  padding: 10px;
  font-size: 14px;
}

.form-control input:focus {
  outline: 0;
  border-color: #777;
}

.form-control.success input {
  border-color: var(--succes-color);
}

.form-control.error input {
  border-color: var(--error-color);
}

.form-control small {
  color: var(--error-color);
  position: absolute;
  bottom: 0;
  left: 0;
  visibility: hidden;
}

.form-control.error small {
  visibility: visible;
}

.form button {
  cursor: pointer;
  background-color: #3498db;
  border: 2px solid #3498db;
  border-radius: 4px;
  color: #fff;
  display: block;
  padding: 10px;
  font-size: 16px;
  margin-top: 20px;
  width: 100%;
}

form {
  border: 0px solid black;
  display: inline-block;
  text-align: left;
}

body {
  margin: 50px 0px;
  padding: 0px;
  text-align: center;
  align-items: center;
  justify-content: center;
  min-height: 100vh;
  margin: 0;
  background-color: lightblue;
}

.nav {
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
  display: inline;
  resize: horizontal
}

label,
input[type="text,password,date"] {
  display: block;
  width: 150px;
  float: left;
  margin-bottom: 10px;
}

input[type="radio"] {
  display: block;
  width: 25px;
  float: left;
  margin-bottom: 10px;
}

label {
  text-align: right;
  width: 75px;
  padding-right: 20px;
}

br {
  clear: left;
}

h1 {
  color: black;
  text-align: center;
  font-size: xx-large;
}

.button {
  text-align: center;
  margin: auto;
  display: inline-block;
  padding: 5px 15px;
  font-size: 18px;
  cursor: pointer;
  text-align: center;
  text-decoration: none;
  outline: none;
  color: black;
  background-color: white;
  border: none;
  border-radius: 15px;
  box-shadow: 0 9px #999;
}

.button:hover {
  background-color: black;
  color: white;
}

.button:active {
  background-color: black;
  color: white;
  box-shadow: 0 5px #666;
  transform: translateY(4px);
}

p {
  font-family: verdana;
  font-size: 20px;
}

#wrapper {
  width: 30%;
  margin: 50px auto;
  padding: 50px;
  background: #D7FBFF;
}

.textInput {
  border: none;
  height: 28px;
  margin: 2px;
  border: 1px solid #6B7363;
  font-size: 1.2em;
  padding: 5px;
  width: 95%;
}

.textInput:focus {
  outline: none;
}

.btn {
  width: 98.6%;
  border: none;
  margin-top: 5px;
  color: white;
  background-color: #3b5998;
  border-radius: 5px;
  padding: 12px;
}

ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  overflow: hidden;
  background-color: #333;
}

li {
  float: left;
  border-right: 1px solid #bbb;
}

li a {
  display: block;
  color: white;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
}

li a:hover:not(.active) {
  background-color: #111;
}

.active {
  background-color: #04AA6D;
}

output {
  display: inline;
}

.customizedBox {
  border: 1px solid #111;
  width: 500px;
  height: 400px;
}

select {
  width: 280px;
  height: 40px;
  padding: 10px;
  margin: auto;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: 1;
  border: none;
}
<div class="nav">
  <ul>
    <li><a href="HomePage.aspx">Home</a></li>
    <li><a href="MemesOverTheYears.aspx">Memes Over The Years</a></li>
    <li><a href="Profile.html">Profile</a></li>
    <li><a href="About.aspx">About</a></li>
  </ul>
</div>
<!-- partial:index.partial.html -->
<div class="wrapper">
  <div class="container">
    <form id="form" class="form">
      <h2>Register With Us</h2>
      <div class="form-control">
        <label for="username">Username</label>
        <input type="text" id="username" placeholder="Enter Username">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="email">Email</label>
        <input type="text" id="email" placeholder="Enter email">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="password">Password</label>
        <input type="password" id="password" placeholder="Enter password">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="password2">Confirm Password</label>
        <input type="password" id="password2" placeholder="Enter password again">
        <small>Error Message</small>
      </div>
      <div class="form-control">
        <label for="gender">Gender</label> <br/>
        <select id="select">
          <option value="">Choose an option</option>
          <option value="Male">Male</option>
          <option value="female">Female</option>
          <option value="other">Other</option>
        </select>
        <small>Error Message</small>
      </div>
      <button type="submit">Submit</button>
    </form>
  </div>
</div>
<br /><br /><br /><br />
<span>Allready have an account?<a href="LogIn.aspx">Log In</a></span>

Can’t use chrome.runtime.getPackageDirectoryEntry in service work with the manifest v3 Chrome Extension standard

In manifest v2, I’ve used chrome.runtime.getPackageDirectoryEntry in the background script to list all the files within a subfolder that came with the extension to realize a specific design feature.

Now that Google is forcing me to migrate my extension from manifest v2 standard to manifest v3, I tried to do the same feature using the chrome.runtime.getPackageDirectoryEntry method but chrome would simply report this error:

Uncaught TypeError: chrome.runtime.getPackageDirectoryEntry is not a function

Can anyone help with this please?
or provide an alternative method for me to list all the filenames in a specified subfolder that would be shipped within the extension?

Find x-axis location to make an element move

I’m trying to make an element move backward on the X axis when the user presses “a”. However, I don’t know how to make it move farther every time the users presses that key :(. I’m new to JS

document.addEventListener("keypress", function (e) {
  let moveBy = 20;
  if (e.key === "a") {
    moveBy++;
    element.style.webkitTransform = `translateX(-${moveBy}px)`;
  }
}

Thank you!

Property * does not exist on type typeof * – static parent method

React Native, TypeScript code JS(non-TS) ORM module:

Parent BaseModel:

export default class BaseModel {
  static createTable() {
    ...
  }
  ...

My model of Animal does NOT redefine the method, it’s just defined as:

export default class Animal extends BaseModel { ...

Now this code await Animal.createTable(); actually works, but VSCode TypeScript checker gives following error in code:

Property 'createTable' does not exist on type 'typeof Animal'.ts(2339)

Is this the editor/checker issue? Or should the JS/TS code be defined somehow better?

CSS, JS Mousedown Getting Stuck During Drag Event

I’m working on the Etch-a-Sketch project from The Odin Project and I’m trying to make it so that my grid element (‘div’ in this case) changes color when my cursor is over it and while my mouse is down.

The code I have now works, however, there’s an issue with the mousedown portion where it will get intermittently stuck down. It seems to occur during an accidental drag event. I’ll notice a hand drag icon appear on my cursor and then all the other grid elements I mouseover will change color regardless of the mousedown condition.

Is there a way to turn off just the ‘draggable’ portion of a ‘div’ or is there another workaround I should be considering?

const grid = document.querySelector('.grid');
grid.addEventListener('mouseover', colorGrid);

let mousedown = false;
grid.addEventListener('mousedown', function(){
    mousedown = true;
});

grid.addEventListener('mouseup', function(){
    mousedown = false;
});


function colorGrid(e){
    if(mousedown) e.target.style.backgroundColor = markerColor.value;

}

.grid {
    display: grid;
    grid-template: repeat(var(--columns-row), 1fr) / repeat(var(--columns-row), 1fr);
    border: solid black 1px;
    width: 100%;
}

.grid div {
    border: 1px dotted lightgrey;
    background-color: var(--bgColor);
 }

 .grid div:hover {
    background-color: var(--color);
 }

Trying to use var as img src in JSX

I’m working on a react project and I have a situation where I need the src attribute for an img tag to be a variable. The relevant parts of the code look something like this:

import React, { useState, useEffect } from 'react';

// topics is already defined and is a js object

const allTopics = topics.map(topic => {
        url = topic['image_url'];
        return (
            <Grid item key={ topic['topic_id'] } item xs={4}>
                <div class='img-wrapper'>
                    <img id='topicpreview' src={url} alt="loading" />
                    <h1>{topic['topic_name']}</h1>
                </div>
            </Grid>
        );
    });

return (
<div style={{ padding: '0', margin: '0', border: '1px solid black', width: '100%', height: '60%', overflow: 'hidden', display: 'inline-block' }} text-align='center'>
                <Grid container>
                    {allTopics}
                </Grid>
            </div>
    );

The image path exists and points to a valid file and I’ve console logged the url to make
sure it’s the same path. However, it doesn’t find the image and ends up printing the “Loading” alternate text instead. I’m not sure what’s going wrong, so any help would be appreciated!

javascript how to get the web page get Session variable

I’m trying to a Session variable in javascript.

I have tried a number of post suggestions without success unfortinately.

I see this example all over the place.

    var userName = '<%= Session["UserName"] %>'

However that is not working, at least for me. What I am trying to do is as below.

    var qrdataString = "<qr-code data=" + "XL" + ' <%= Session["style"] %>'  + "></qr-code>";
    document.getElementById("styleqr").innerHTML = qrdataString; 

Using Single quotes where they appear above just returns the string as

    <%=Session["xUID"]%>   in the alert that I use to show me the returned value

Using Double quotes give me either – unexpected token: string literal – or unexpected token identifier.

Thanks

Method Tracers for New Relic in Nodejs

As the new relic docs are not very rich in providing examples. I wondered how I can use Method Tracers in Node Js for New Relic ?.
I want to make a common method that can be used for this purpose.

For example

ApplyMethodTracer (className, MethodNameOfClass) this method should apply method tracer for the given method of the given class.

expected spy to have been called at least once but was never called

How to fix this error –

AssertError: expected spy to have been called at least once but was never called

describe('subscribe()', () => {
    let subscription: subscriptionType;
    let eventCallbackSpy: SinonSpy = Sinon.spy();
    let track : Track;
    let videoTrack: MediaStreamTrack;

    describe('track mute event & publisher', () => {
      const mockDeviceAudio = {
        ID: '47dd6c612bb77e7992cb8f026b660c59648e8105baf4c569f96d226738add9a4',
        groupId: '99782d7b13f331947c1a9865b27cf7eabffbfd48cfe21ab99867d101c6d7b4d0',
        kind: DeviceKinds.AUDIO_INPUT,
        label: 'Fake Audio Input 1',
        mediaDeviceInfo: null,
      };

      const mockDeviceVideo = {
        ID: '47dd6c612bb77e7992cb8f026b660c59648e8105baf4c569f96d226738add9a4',
        groupId: '99782d7b13f331947c1a9865b27cf7eabffbfd48cfe21ab99867d101c6d7b4d0',
        kind: DeviceKinds.VIDEO_INPUT,
        label: 'Fake Video Input 1',
        mediaDeviceInfo: null,
      };

      before(async () => {
        [videoTrack] = (await navigator.mediaDevices.getUserMedia({video: true})).getVideoTracks();
        track = new Track(videoTrack as MediaStreamTrack);
        setupMediaTrackMocks();
        subscription = await track.subscribe('track:mute', eventCallbackSpy);
      });

      after(() => {
        resetMediaTrackMocks();
      });

      it('should have subscribe, track mute event available', () => {
        expect(subscription.listener.method).to.be.equal(eventCallbackSpy);
        expect(subscriptions.events['track:mute'].get(subscription.listener.id)).to.be.equal(eventCallbackSpy);
      });

      it('should have track object from the library (instanceof Track)', async () => {
        eventCallbackSpy = Sinon.spy();
        subscriptions.events['track:mute'].set(subscription.listener.id, eventCallbackSpy);
        Sinon.assert.called(eventCallbackSpy);
        console.log("log ", eventCallbackSpy.getCall(0));
        expect(eventCallbackSpy.getCall(0).args[0].action);
        // making sure track object from the library(instanceof Track)
        expect(eventCallbackSpy.getCall(0).args[0].track).to.be.an.instanceof(Track);
      });

This test is given error –

track mute event & publisher
        ✖ should have track object from the library (instanceof Track)
          Chrome Headless 93.0.4577.0 (Mac OS 10.15.7)
        AssertError: expected spy to have been called at least once but was never called

This is my subscribe –

async subscribe(eventName: string, listener: () => void): Promise<subscription> {
    const subscriptionListener = {
      id: uuidv4(),
      method: listener,
    };
  
    subscriptions.events[eventName].set(subscriptionListener.id, subscriptionListener.method);
    const thisEventListeners = subscriptions.events[eventName];
  
    switch (eventName) {
      case 'track:mute': {
        if (thisEventListeners.size === 1) {
          this.#mediaStreamTrack.onmute = (event) => {
            // using arrow function which should bind to this from outer scope track
            trackMutePublisher(event, this);
          }
        } 
        break;
      }
  
      default:
        break;
    }
  
    return new Promise((resolve) => {
      resolve({
        type: eventName,
        listener: subscriptionListener,
      });
    });
  }

In Test I am trying to check Sinon.assert.called(eventCallbackSpy); but still it’s giving the error expected spy to have been called at least once but was never called

Please help me.

ReactJs Download Excel Error : We found problem with content

I have below code to call api which returns bytes for excel.

When I convert bytes to excel online , file looks good.

But , When I call api through react js with below code , it gives me error –

We found a problem with content in <file.xlsx>. Do you want to recover
as mych as we can?

 agent.ExcelExport(data,{
responseType:"arraybuffer"
})
.then((res:any)=>{
const url= window.URL.createObjectURL( new Blob([res.data],{type:"application/x-msdownload"}));
const link=document.createElement('a');
link.href=url;
link.setAttribute('download','filename.xlsx');
link.click();
window.URL.revokeObjectURL(url);

I can see , Api getting hit clearly and responding with expected data. While opening file , its giving error.

.NET Core Api is returning –

return File(excelbytes,”application/x-msdownload”,”filename.xlsx”);

How to set custom x, y position of Electron Menu when using BrowserWindow.fromWebContents

I’m using contextBridge and contextIsolation to create a custom context menu on click and I’m using this example from the docs: https://github.com/electron/electron/blob/main/docs/api/menu.md#render-process

// renderer
window.addEventListener('contextmenu', (e) => {
  e.preventDefault()
  ipcRenderer.send('show-context-menu')
})

ipcRenderer.on('context-menu-command', (e, command) => {
  // ...
})

// main
ipcMain.on('show-context-menu', (event) => {
  const template = [
    {
      label: 'Menu Item 1',
      click: () => { event.sender.send('context-menu-command', 'menu-item-1') }
    },
    { type: 'separator' },
    { label: 'Menu Item 2', type: 'checkbox', checked: true }
  ]
  const menu = Menu.buildFromTemplate(template)
  menu.popup(BrowserWindow.fromWebContents(event.sender))
})

This works but the context menu appears right under the mouse. I want to supply a custom x and y. In the docs for menu.popup, I can set an x and y property like this:

menu.popup({
  window: /* my window object /*,
  x: /* x position */,
  y: /* y position */,
})

But I don’t know how to add these properties to the object that I get back from BrowserWindow.fromWebContents(event.sender).

I tried these options:

menu.popup({ ...BrowserWindow.fromWebContents(event.sender), x, y } );
// or
const window = BrowserWindow.fromWebContents(event.sender);
menu.popup({ window, x, y });

and I get this error

Error processing argument at index 1, conversion failure from 
at EventEmitter.a.popup (node:electron/js2c/browser_init:81:3188)

It seems like electron doesn’t like converting the results from BrowserWindow.fromWebContents(event.sender) into an object.

I also tried this, but get the same error.

const window = BrowserWindow.fromWebContents(event.sender);
window.x = x;
window.y = y;
menu.popup(window);

Thanks for the help