table element with no cell beginning in them Error

My table have thead, tbody, and tfoot, I must have 6 columns (1/2/3).

But I got Error: Table columns in range 5…6 established by element th have no cells beginning in them. From line 17, column 36; to line 18, column 26.

I had my code checked on validator.w3.org and the error was indicated at th colspan=”3″>form

 <table id="table">
      <caption>
        MinhDucHa 
      </caption>
      <thead>
        <tr >
          <th>Name</th>
          <th colspan="2">Date</th>
          <th colspan="3">Form</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Bod</td>
          <td>Jan. 13</td>
          <td>March 12</td>
          <td colspan="3">
            <form>
              <label for="bod-favorite-color">Favorite Colour:</label
              ><input type="text" id="bod-favorite-color" name="fname" />
            </form>
          </td>
        </tr>
        <tr>
          <td>Md</td>
          <td>Feb. 23</td>
          <td>March 19</td>
          <td colspan="3">
            <form>
              <label for="md-favorite-color">Favorite Colour:</label
              ><input type="text" id="md-favorite-color" name="fname" />
            </form>
          </td>
        </tr>
        <tr>
          <td>Suzy</td>
          <td>Jan. 18</td>
          <td>Dec. 24</td>
          <td colspan="3">
            <form>
              <label for="suzy-favorite-color">Favorite Colour:</label
              ><input type="text" id="suzy-favorite-color" name="fname" />
            </form>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th colspan="6">Copyright &#169;2023 Minh Duc Ha</th>
        </tr>
      </tfoot>
    </table>

i have an array of objects that i can console.log all together but when i want to access a specific element returns undefined

Hello coding a store in javascript vanilla for a assignment. im making a simple ecommerce and i create two classes (Product and ClassListProducts ) and then i consume an api. with this api i create a class product and push it to the array of ClassListProducts. i cant loop the array neither. My question is why i cant access an specific element inside the array, it returns undefined.

class Product {
  constructor(id, name) {
    this.id = id;
    this.name = name;
  }
}
class ClassListProducts {
  constructor() {
    this.lista = [];
    this.addProduct.bind();
  }

  addProduct(id, name) {
    let producto = new Product(id, name);
    this.lista.push(producto);
  }
}
const listProducts = new ClassListProducts();

fetch("https://fakestoreapi.com/products")
  .then((res) => res.json())
  .then((json) =>
    json.forEach(({ title, id }) => {
        listProducts.addProduct(id, title);
    })
  );

console.log(listProducts.lista);
console.log(listProducts.lista[0]);

screenshot of the console.log

sorry for my english.

i tried to use an api and save the products in an object and the save them in array. i want to access specifics element.

is String.includes faster than String.search?

word.includes(str) returns a boolean indicating whether or not str is included in word
word.search(str) returns a number representing the position of the first str found in word, -1 if it does not exist.

At first, I wondered why JavaScript provides both, however it’s possible to create only one method that works for both cases, returns position else returns undefined, but since both exist, so it should be for a reason, maybe String.includes is faster, or maybe, it’s just to make things clearer.

It looks like String.includes should be faster as it only checks if str exists rather than trying to find its position, however, my simple thought: to check if str exists in word the algorithm should loop through the word characters anyway (if there is something I’m missing let me know) and once str is found, it can easily retrieve its position, so String.includes couldn’t be faster.

I want to know the real difference between them and why both exist. thank you!

Javascript – Change Background Color of Div Containing Specific Text

This is my first post after lurking for years, so please excuse me if the formatting of this post is incorrect. I am currently modifying a Tampermonkey script (Firefox) that searches a webpage for a specific set of text strings (which I have predefined in the script) and highlights the text on the page once it loads. That part of the script works fine, however, now I am trying to change the background color of one of the parents.

I would like to change the background color for the entire element (div class “shop-item”) that contains the text “Item Name”:

<div class="shop-item">
  <div class="item-img" tabindex="0" style="background-image:url("URL_HERE");" border='1'>
  </div>
  <p class='item-name'>
    <b>Item Name</b>
  </p>
</div>

The entire script works flawlessly, but now that I am trying to highlight additional items other than the text string, I am running into issues. This is the part of the script I’m having trouble with:

    var textnodes = document.evaluate("//body//text()", document, null,
        XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null);

    for (var i = 0; i < textnodes.snapshotLength; i++) {
    var node = textnodes.snapshotItem(i);

        if (!(node.data.match(/^s*$/))) {
        var s = " " + node.data + " ";
        changes = 0;
        var d = highlight(quoteHTML(s));
        if (changes > 0) {
            var rep = document.createElement("span");
            rep.innerHTML = d.substring(1, d.length - 1);
            node.parentNode.replaceChild(rep, node);
            node.closest("div").backgroundcolor("#1AFF00FF");
        }
        }
    }
    }

The issue lies with the last line of code:
node.closest("div").backgroundcolor("#1AFF00FF");

I’ve tried a bunch of other combinations including .parentNode, but haven’t been successful. I’m fairly new to Javascript/Tampermonkey scrpts, so any help would be much appreciated!

strip comments with markers

I am working on this Codewars problem and this is the solution I came up with. The return looks exactly like what is expected, but it’s saying it’s wrong.

This is the failed test return:
Returned ‘apples, pears
grapes
bananas’ but expected ‘apples, pears
grapes
bananas’

Am I losing it? Is it something w/ whitespace for the second line my eyes aren’t seeing?

function solution(input, markers) {
  let regex = new RegExp(markers.join("|"), "g")
  
  return input.replace(regex, "-").replace(/-(.*)/g, "").trimRight()
};

PLS HELP React Redux TypeError: Cannot add property _, object is not extensible

Pls help im genuinely going insane Ive been stuck at this error for 3 hours and I dont know whats wrong everything looks correct, so some background this website allows users to store collections of links and each collection has multipole categories and each category can have multiple entries

AddCategory Reducer
So I am using react redux and in a component when I click a button its calling the addCategory reducer, I have a Category array of objects in another file that I exported and imported in this file like this. So the
main way im doing this is I have to store the entire list of categories in another file(which I will use backend to pull the necessary categories associated to each user), and because some categories might be tied to different collections so I have a getCategories reducer that retrieve the approriate Categories based on the current collection you are in. so each time I add category I need to add to the current state as well as the Categories array in the other file
categorySlice

But for some reason It gives giving this error when i try to push the new object to the oriingal category array
ERROR

This is the category array CATEGORY ARRAY

I did some searching and I am not calling preventExtensions anywhere so is something automatically calling it? but makes sense, I tried even just copying the array by using spread operator or changing const to var nothing works, Pls help

Simple perfomace test in javascript: Why the first test tends to be slower?

The most simple and common way of testing functions performance in javascript is doing something like this:

const count = 100_000;

console.time("1");
for (let index = 0; index < count; index++) {
  // put anything here
}
console.timeEnd("1");

console.time("2");
for (let index = 0; index < count; index++) {
  // put anything here
}
console.timeEnd("2");

Put I notice that, if we put the same code in the two iterations, the first timer will give larger values than the second one. For instance:

const count = 100_000;

const object = {
  x: 1,
};

console.time("1");
for (let index = 0; index < count; index++) {
  object.x = 1;
}
console.timeEnd("1");

console.time("2");
for (let index = 0; index < count; index++) {
  object.x = 2;
}
console.timeEnd("2");

Running this 3 times, I got:

1: 1.908ms
2: 1.45ms

1: 1.856ms
2: 1.598ms

1: 1.725ms
2: 1.43ms

I run this code using Node.js v18.13.0

Why does this happen? Does this mean that this kind of performance test is bad?

‘:’ expected.ts(1005) how to fix

saw number of issues tried suggestions, so far no luck. Currently
using vsc version 1.76.2, Node 16.14.2 ts version 4.6.4 from ng version command

barChartData is

  public barChartData: ChartData<'bar'> = {
    labels: [],
    datasets: [
      {
        data: [],
        // data: [65, 59, 80, 81, 56, 55, 40],
        // backgroundColor: ['#012169', '#0073cf', '#646464', '#012169', '#0073cf', '#646464', '#012169'],
        // hoverBackgroundColor: ['#8090b4', '#80b9e7', '#919191', '#8090b4', '#80b9e7', '#919191', '#8090b4'],
      },
    ]
  };

it is part of Chart.js v 3.9.1 the labels can be undefined

in vsc a popup shows

(property) ChartData<"bar", number[], unknown>.labels?: unknown[] | undefined

the event handler is where the error is happening:

  public chartClicked(e: any): void {
    this.barChartData.labels?[0];

    console.log(e);
  }

I get an error of

':' expected.ts(1005)

and when trying to build from ng serve

./src/app/components/test03/test03.component.ts:127:69 - Error: Module parse failed: Unexpected token (127:69)
File was processed with these loaders:
 * ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
 * ./node_modules/@ngtools/webpack/src/ivy/index.js
You may need an additional loader to handle the result of these loaders.
|     }
|     chartClicked(e) {
>         console.log(this.barChartData.labels ? [e.active[0].index] : );
|         console.log(e);
|     }

Error: src/app/components/test03/test03.component.ts:135:61 - error TS1005: ':' expected.

135     console.log(this.barChartData.labels?[e.active[0].index]);
                                                                ~




× Failed to compile.

how to resolve this?

Can explain what is the difference between useState and createSignal

native state management by react vs state management by solid js. What are the differences and benefits of solid js createSignal.

import React, { useState } from "react";


function App() {
    const [counter, setCounter] = useState(0);
    return (
      <div>
        <p>{counter}</p>
        <button onClick={() => setCounter((counter) => counter + 1)}>
          Click Me
        </button>
      </div>
    );
}



import React from "react";
import { createSignal } from "solid-js";

function App() {
    const [count, setCount] = createSignal(0);
    return (
      <div>
        <p>{count()}</p>
        <button onClick={() => setCount(count() + 1)}>Click Me</button>
      </div>
    );
}

// Expecting the difference between react useState and solid js createSignal and which one is better for performance and mental model

Using JavaScript to compute students marks then output the results to PHP for insertion in the database

Its part of a school management system built with php where the teacher selects a subject and a class. That generates a table where the teacher inserts the class score and exam score, the program then computes to get the total score, class average, grade, position and remarks for all students in the class. Part of the computing is handled by javascript and some by php. The results are sent to php to insert in the database.

I made different versions one with only php with countless errors after fixing them all no more errors but nothing dumps in the database.
With this version however some data gets dumped in the database like the class score and exam score but the total score, class average, position and grade have part of the script tag getting inserted.
I just need to get the computed data dumped in the database by any means necessary 🙂

“;
echo “”;
echo “Student IDStudent NameClass Score (30%)Exam Score (70%)Total Score (100%)Class AverageGradePositionRemarks”;
while ($row = $result->fetch_assoc()) {
$sid = $row[“sid”];
$fname = $row[“fname”];
$lname = $row[“lname”];
echo “$sid$fname $lname”;
echo “”;
echo “”;
echo “”;
echo “”;
echo “”;
echo “”;
echo “”;
echo “”;
}

/*Am thinking of adding a javascript id to get the values to be displayed in the table when a button is clicked*/
echo “”;

// Add a submit button to submit the form
echo “”;
echo “”;
echo “”;
echo “”;
echo “”;
echo “”;

?>

          <?php 

            // If the form has been submitted, process the data
          if (isset($_POST["classscore"]) && isset($_POST["examscore"])) {
              $classscore = $_POST["classscore"];
              $examscore = $_POST["examscore"];
              $classroom = $_POST["classroom"];
              $subject = $_POST["subject"];
              $year = $_POST["year"];
              $term = $_POST["term"];

                /* this is where the computing goes down ;)*/
              // Calculate the total score for each student
              $totalscore = array();
              foreach ($classscore as $sid => $score) {
                  // Add JavaScript code to calculate the total score
                  echo "<script>var totalscore_$sid = $score + $examscore[$sid] * 0.7;</script>";
                  $totalscore[$sid] = "<script>document.write(totalscore_$sid);</script>";
              }

               /*This outputs errors js code on the page and doesn't pass to the php*/
              // Calculate the grades and remarks for each student based on their total score
              $grade = array();
              $remarks = array();
              foreach ($totalscore as $sid => $score) {
                  // Add JavaScript code to calculate the grade and remarks
                  echo "<script>
                      var score_$sid = $score;
                      if (score_$sid >= 90 && score_$sid <= 100) {
                          var grade_$sid = 1;
                          var remarks_$sid = 'Distinction';
                      } else if (score_$sid >= 80 && score_$sid <= 89.99) {
                          var grade_$sid = 1;
                          var remarks_$sid = 'Excellent';
                      } else if (score_$sid >= 75 && score_$sid <= 79.99) {
                          var grade_$sid = 2;
                          var remarks_$sid = 'Very Good';
                      } else if (score_$sid >= 70 && score_$sid <= 74.99) {
                          var grade_$sid = 3;
                          var remarks_$sid = 'Good';
                      } else if (score_$sid >= 65 && score_$sid <= 69.99) {
                          var grade_$sid = 4;
                          var remarks_$sid = 'Credit';
                      } else if (score_$sid >= 60 && score_$sid <= 64.99) {
                          var grade_$sid = 5;
                          var remarks_$sid = 'Credit';
                      } else if (score_$sid >= 55 && score_$sid <= 59.99) {
                          var grade_$sid = 6;
                          var remarks_$sid = 'Credit';
                      } else if (score_$sid >= 50 && score_$sid <= 54.99) {
                          var grade_$sid = 7;
                          var remarks_$sid = 'Pass';
                      } else if (score_$sid >= 40 && score_$sid <= 49.99) {
                          var grade_$sid = 8;
                          var remarks_$sid = 'Weak Pass';
                      } else {`your text`
                          var grade_$sid = 9;
                          var remarks_$sid = 'Fail';
                      }
                  </script>";
                  $grade[$sid] = "<script>document.write(grade_$sid);</script>";
                  $remarks[$sid] = "<script>document.write(remarks_$sid);</script>";
              }
              echo "<script>
                const average_$sid = totalscore.reduce((accumulator, currentValue) => accumulator + currentValue, 0) / totalscore.length;
              </script>";
              // Calculate the class average
              $average = array_sum($totalscore) / count($totalscore);

              // Output the class average
              echo "Class Average: " . $average . "<br>";

                /*In the database you see the positions as 1 throughout*/
              // Rank the students by total score
              arsort($totalscore);
              $position = 1;
              $prevscore = null;
              foreach ($totalscore as $sid => $score) {
                  if ($score != $prevscore) {
                      $position = array_search($score, $totalscore) + 1;
                  }

                /*had to comment this and use an unsecure version instead, couldn't bind etc. Will work on later*/

              /*$stmt = $conn->prepare("INSERT INTO exam (sid, year, term, classroom, subject, classscore, examscore, totalscore, average, grade, position, remarks) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
              $stmt->bind_param("sssssssssss", $sid, $year, $term, $classroom, $subject, $classscore[$sid], $examscore[$sid], $totalscore, $average, $grade[$sid], $position, $remarks[$sid]);
              $stmt->execute();*/

                  
                 // $conn->query($sql);
                  //$prevscore = $score;

              $sql = "INSERT INTO exam (sid,year,term,classroom,subject,classscore,examscore,totalscore,average,grade,position,remarks) VALUES ('".$sid."', '".$year."', '".$term."','".$classroom."','".$subject."','".$classscore[$sid]."','".$examscore[$sid]."','".$totalscore[$sid]."','".$average."','".$grade[$sid]."','".$position."','".$remarks[$sid]."')";
                
              $conn->query($sql);
              $prevscore = $score;

              }

        }

           ?>

/*At a glance it seems to be outputting to the html instead of Javascript.

I used an unsecure query to see if the data gets dumped that had something in there alright just not the computed data at least the position seems to work.

How to render a sprite in Three.JS?

I am starting out with Three.JS and simply trying to render a sprite. However, I haven’t been able to get a basic sprite to render. In my example below, I have a simple 200×200 canvas which I am attempting to fill with a 200×200 sprite on the screen, and allow the upper left to be the 0,0 point, instead of the center. But the (red) sprite never shows up — instead only the yellow background. Can sprites be independently rendered, or do they need to be associated with something else? I was unable to find a basic working example of just a sprite being rendered.

https://jsfiddle.net/CodeVirtue/4wv8tj57/

const canvas = document.getElementById('main');
const body = document.getElementById('body');

const w = 100;
const h = 100;

const scene = new THREE.Scene();
const camera = new THREE.OrthographicCamera(0, 0, w, h, 0, 1000);
const renderer = new THREE.WebGLRenderer({canvas});

scene.background = new THREE.Color(0xffff00);
renderer.setSize(w, h);
const sprite = createSprite(w, h);
scene.add(sprite);
camera.lookAt(w / 2, h / 2, 0);

function createSprite(w, h) {
  const material = new THREE.SpriteMaterial({ color: 0xff0000 });
  const sprite = new THREE.Sprite(material);
  sprite.position.set(w / 2, h / 2, 0);
  sprite.scale.set(w, h, 1);
  return sprite;
}

function animate() {
  requestAnimationFrame(animate);
  renderer.render(scene, camera);
}
animate();
body {
  margin: 0;
  padding: 0;
  border: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/110/three.js"></script>
<body id="body">
  <canvas id="main"></canvas>  
</body>

TypeError: connection.execute is not a function

Why do I get this error when I call my API from postman?

http://localhost:4000/api/employees/employees1

This is my error looks like.

TypeError: connection.execute is not a function
    at getQuestion1 (C:UsersejOneDriveDesktopOJTsddapicontrollersemployeepart_1_question.js:28:48)
    at Layer.handle [as handle_request] (C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterlayer.js:95:5)
    at next (C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterroute.js:144:13)
    at Route.dispatch (C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterroute.js:114:3)
    at Layer.handle [as handle_request] (C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterlayer.js:95:5)
    at C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterindex.js:284:15
    at Function.process_params (C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterindex.js:346:12)
    at next (C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterindex.js:280:10)
    at Function.handle (C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterindex.js:175:3)
    at router (C:UsersejOneDriveDesktopOJTsddapinode_modulesexpresslibrouterindex.js:47:12)

that is my end point I used, and this is my backend looks like.

Here is my database wherein I export it.

Db.js

const mysql2 = require(‘mysql2/promise’);

const connection = mysql2.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'admin',
  database: 'sdd_crud',
});

module.exports = connection;

After that I call it to my Part_Js

Part_1.js

const connection = require('../../DB/db.js');

 const getQuestion1 = async (req,res) =>{
    const query = "SELECT * FROM studentsquestionpart1"

    try {
        const [rows, field] = await connection.execute(query)
        res.status(200).json(rows)
    } catch (error) {
        res.status(400).json(error)
    }
}
module.exports = {getQuestion1 }

This is my router.js, I can call it but gave me an error

router.js

router.get('/employees1/', getQuestion1)

index.js

const express = require('express');
const cors = require('cors');
const employeeQuestion = require('./routes/employee/part_1_question.js');

const app = express()
app.use(cors());
app.use(express.json());

app.get('/', (req,res) =>{
    res.send("Hello World")
})

app.use('/api/employees', employeeQuestion)



app.listen(4000, () =>{
    console.log(`Website is running at port http://localhost:${4000}`)
})

How do I fix this error?

Hide border of overlaying divs

Say I have these two div’s

overlaying divs

.el-2 {
  position: absolute;
  left: 40px;
  top: 20px;
}

div {
  border: 1px solid black;
  width: 50px;
  height: 25px;
}
<div class="el-1">
</div>
<div class="el-2">
</div>

How can I make them look like this?

Overlayed divs

Doesn’t matter if we somehow merge them together or use SVGs

Can you create a saved search to NULL values of specific transaction types on a Customer’s open balance?

I am trying to create a save search in NetSuite for our AR team that only displays journal entry transactions that are part of a customer’s current balance. I’ve gotten so far with the results but having trouble to ensure that it is only capturing journal entries that is part of the customer’s current balance (the most important part). I’m trying to find a way to either filter out results of other transactions that is matching the current balance (i.e. Invoice) or how to exactly account for journal entries part of the customer’s balance.

I was expecting with this formula that it would capture any matching amounts of the Invoice and Customer’s balance and NULL the Customer from the results.

CASE WHEN {debitamount} = {customer.balance} AND {type} = ‘Invoice’ THEN {name} IS NULL ELSE {name} END