How could i apply linear-gradient to element in css?

I have following code.

#trapezoid {
  border-bottom: 150px solid red;
  border-left: 10px solid transparent;
  border-right: 10px solid transparent;
  height: 0;
  width: 30px;
}
<div id='trapezoid'></div>

My question is how could I apply linear-gradient to it (the whole shape).

Background:linear-gradient will not going to work since I use border to construct the shape.

Any trick I could use?

Thanks

P.S this is not a duplicate of this answer:

How to create multi-color border with CSS?

working on a javascript quiz app and having an issue dynamically generating questions/answers

I’m trying to dynamically generate questions and answers in a quiz game. The questions/answers are held in an array of objects and are supposed to be generated one after another inside of a div. When the user clicks on an answer, then the next question is generated. For now there are 5 questions and the problem is that after the first two questions are generated, the 3rd one gets skipped over, the 4th one is generated, and then the 5th gets skipped. When I submit an answer for the second question, it appears in the console that the 2nd and 3rd question were answered, even though the 3rd question never appeared on the page.

here is the javascript-

const questions = [
    {
        question: "Where was the first attempted allied invasion of France?",
        choices: ['Normandy', 'Nice', 'Dieppe', "Bourdeaux"],
        answer: "Dieppe"

    },

    {
        question: "Which American general was in charge of the pacific campaign?",
        choices: ["George Patton", "Omar Bradley", "George Marshall", "Douglas MacArthur"],
        answer: "Douglas MacArthur"
    },

    {
        question: "When was VE day?",
        choices: ["April", "May", "June", "July"],
        answer: "May"
    },

    {
        question: "Which of these was considered the largest tank battle in history?",
        choices: ["Battle of the Bulge", "D-Day", "Kursk", "Stalingrad", "Market Garden"],
        answer: "Kursk"
    },

    {
        question: "When did the war start?",
        choices: ["1939", "1938", "1941", "1944"],
        answer: "1939"
    }

]

let questionIndex = 0;



//function to start the game//
const startGame = () => {

    $('.start-btn').hide()
    $('.game-header').hide()
    $('.container').show();

    renderQuestion()

}



const renderQuestion = () => {

    $('#question').text(questions[questionIndex].question);
    $('#answer1').text(questions[questionIndex].choices[0])
    $('#answer2').text(questions[questionIndex].choices[1])
    $('#answer3').text(questions[questionIndex].choices[2])
    $('#answer4').text(questions[questionIndex].choices[3])



    $('.btn').click(function () {
        let response = $(this).text()
        console.log(response)
        checkAnswer(response)
    })


}





//function to set the timer


//function to end the quiz


//function to save high score




const checkAnswer = (response) => {


    if (response === questions[questionIndex].answer) {
        window.alert('CORRECT!')
    } else {
        window.alert('INCORRECT!')
    }

    

    questionIndex++
    console.log(questionIndex)

    renderQuestion()

}




$('.start-btn').click(startGame)

I believe the problem has to do with the “questionIndex” variable that I declared after the question array. At the bottom of the checkAnswer function, I have questionIndex++ which is supposed to cycle through all the questions, but I’m not sure what I’m getting wrong.

and here is the html-

<body>
    <div class="timer">
        Time left
    </div>
    <div class="game-header">
        <h1>Welcome to the WWII trivia game!</h1>
        <h2>Answer all the questions before the time runs out and check your score in the end!</h2>
    </div>
    <button class="start-btn">Start!</button>
    <div class="container">
        <div id="question-container" class="hide">
            <div id="question">""</div>
            <div class="answers">
                <button id='answer1' class="btn">Answer 1</button>
                <button id='answer2' class="btn">Answer 2</button>
                <button id='answer3' class="btn">Answer 3</button>
                <button id='answer4' class="btn">Answer 4</button>
            </div>
        </div>
        <div class="controls">
            <button id="start-btn" class="start-btn btn">Start</button>
            <button id="start-btn" class="start-btn btn hide">Next</button>
        </div>

    </div>

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

</body>

So to conclude, I’m trying to cycle through all the questions and corresponding answers in the array so that they are generated one after another in the quiz game. as of now, the 3rd and 5th questions are being omitted. Appreciate any help 🙂

Express middleware runs for every imported .js file, is this normal?

so I set up a basic express app that serves a static file from a directory named public.

The public directory contains 3 files “index.html”, “script1.js”, “script2.js”, and “script3.js”. The script files are just empty .js files.

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <h1>Middleware</h1>
  <script src="./script1.js" crossorigin="anonymous"></script>
  <script src="./script2.js" crossorigin="anonymous"></script>
  <script src="./script3.js" crossorigin="anonymous"></script>
</body>
</html>

server.js

const express = require('express')
const path = require('path')

const app = express()

app.use((req, res, next) => {
  console.log('middleware was ran', new Date())
  next()
})

app.use(express.static(path.resolve(__dirname, 'public')))

app.listen(3000, () => {
  console.log('listening on port 3000')
})

Whenever I run the server.js file and visit the ‘/’ route I get an additional “middleware was ran” output to the console for each script file that I am including. In this case my out put would be:

listening on port 3000
middleware was ran 2022-06-11T21:45:21.609Z
middleware was ran 2022-06-11T21:45:21.644Z
middleware was ran 2022-06-11T21:45:21.648Z
middleware was ran 2022-06-11T21:45:21.650Z

Why is that happening?

how to show TreeSelect Children from data that we get from backend

I have a TreeSelect and i’m using AntDesign TreeSelect For that.

Ant Design treeData look like this

const treeData = [
  {
    title: 'Node1',
    value: '0-0',
    children: [
      {
        title: 'Child Node1',
        value: '0-0-1',
      },
      {
        title: 'Child Node2',
        value: '0-0-2',
      },
    ],
  },
  {
    title: 'Node2',
    value: '0-1',
  },
];

and we have array like this which i get it from the backend.

[value – title – children tree ]

[
['1','CEO','0']
['2','A','1']
['3','B','1']
['4','C','1']
['5','Operator ','0']
['6','E','5']
['7','F','5']
['8','G','5']
]

My Code

const [data, setData] = useState([]);


 useEffect(() => {
    async function getData() {
      const { data } = await axios.post(config.apiEndPoint);
      setData(data.respon);
    }
    getData();
  }, []);


  const treeData = [] ;

  for (let i of data) {
    let x = { title: i[1], value: i[0] };
    treeData.push(x);
  }

  <TreeSelect
          value={value}
          treeData={treeData}
          placeholder="Organization Rule"
          treeDefaultExpandAll
          onChange={(value) => onChange(value, "organizationalRule")}
        />

i have no idea how to create children tree like Ant Design treeData
A-B-C should be children of CEO and E-F-G should be children of Operator
i will really appreciate some help.

Communication between inline JavaScript and Node.js

I am using Node.js and I want to send a request which contains an input value to the server when a button is pressed.

So here’s my HTML code :

<!DOCTYPE html>

<html>
    <head>
        <meta charset="utf-8">
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    </head>

    <body>
        <input id="input" action="/onclick" autocomplete="off">
        <button id="button">Send</button>
        <script>
            let input = document.getElementById('input');

            document.getElementById('button').addEventListener('click', (event) => {
                event.preventDefault();
                let value = input.value;

                if (value) {
                    let data = {};
                    data.title = 'getValue',
                    data.message = value;

                    $.ajax({
                        url:'/onclick',
                        data: JSON.stringify(data),
                        type: 'POST',
                        success: (responseData) => {
                            console.log('Success!');
                        },
                    });

                    input.value = null;
                }
            });
        </script>
    </body>
</html>

And here’s my server.js :

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});

app.post('/onclick', (req, res) => {
    console.log('body: '+ JSON.stringify(req.message));
    res.send(req.message);
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

The code doesn’t throw any error (it returns Success! in browser console) but the problem is that in the Node.js shell it sends body: undefined instead of the input value.

Do you know how to fix that ?

Thanks in advance,

What does “array.length + 1” mean in JavaScript

I know how to use Javascript for loops to cycle through arrays. But I still don’t fully understand what the array.length + 1 is doing, specifically the +1 part.

When using a for loop I know it goes like this

for(let i = 0; i < array.length; i++){...}

But I’m also seeing this

for(let i = 0; i < array.length + 1; i++){...}

I previously thought that array.length + 1 was the same thing as letting i = 1 but my code hasn’t worked when doing that, for instance

for(let i = 1; i < array.length; i++)

is not the same thing as the for loop above. Can someone explain why?

Python numpy dot method to JS only for case 3×3 3×1

Python part:

Input:

 M_parent -> 
 [[ 0.93358043  0.35836795  0.        ]
 [-0.35836795  0.93358043  0.        ]
 [ 0.          0.          1.        ]]

 joint.offset ->
 [ 2.10955 -5.79594  0.     ]

Code:

M_parent.dot(joint.offset) 

Correct output:

 [-0.10764454 -6.16697125  0.        ]

Javascript part:

My simulation for case 3×3 dot 3×1

function dot3vs1(a, b) {
  var aNumRows = a.length, aNumCols = a[0].length,
    bNumRows = b.length;
  var REZ1 = 0, REZ2 = 0, REZ3 = 0;
  if(aNumRows == 3 && aNumCols == 3 &&
    bNumRows == 3) {
    for(var j = 0;j < a.length;j++) {
      // First root of 3x3 a.
      REZ1 += a[j][0] * b[j];
      REZ2 += a[j][1] * b[j];
      REZ3 += a[j][2] * b[j];
    }
    var finalRez = [REZ1, REZ2, REZ3];
    return finalRez;
  } else {
    console.error("Bad arguments for dot3vs1");
  }
}

Input is correct it is the same like python script!

Not correct Output in JS:

0: 4.046513722204759
1: -4.654981029188903
2: 0

This simple but not work for me ,
any suggestion?

three.js cube each face is a different texture

        loader.load('IMAGE', (texture) => {
          const material = new THREE.MeshBasicMaterial({
            map: texture,
          });
            var cubeGeometry = new THREE.BoxGeometry(140, 140, 140);
            var cube = new THREE.Mesh(cubeGeometry, material);
            this.add(cube);
        });

I have this code that uses one texture for every face of the cube, but how can i adapt it so each face of the cube is a different texture?

Eloquent JavaScript Chapter 4: Exercise – A list

I am having trouble converting a list of objects to array. On the second function listToArray I am trying to loop through properties and check whether the value is number or not. In case of a number I just push it to the empty array, but if it’s not then I am trying recursion with a property as an argument. I’m getting an empty array, help me please.
NOTE: No brute force solutions, please. Like, list.value and list.rest. Thank you!

function arrayToList(array) {
  let list = null;
  for (let i = array.length - 1; i >= 0; i--) {
    list = {value: array[i], rest: list};
  }
  return list;
}

function listToArray(list) {
  let array = [];
  for (let i in list) {
    if(typeof list[i] == "number") {
        array.push(list[i]);
    } else if(typeof list[i] != "number") {
        return listToArray(list[i]);
    }
  }
  return array;
}
console.log(arrayToList([10, 20]));
Result: {value: 10, rest: {value: 20, rest: null}}
console.log(listToArray(arrayToList([10, 20, 30])));
Result: []

Some trouble with PDFJS during creating extension(chromeAPI)

I have tried to create simple chrome extension to help myself download manga to ebook.
How it works – i get img sources as a string separated by space from website to extension side and split that into the table.
And now my function attached below should check every single image(page) of manga, redraw it to canvas, and recreate it again to raw img(cause its should be like that for pdfjs).

My problem:

  1. console show its skips to last file
  2. my for loop ends faster than recreate process lasts – it saves 3kb pdf (propably empty
  3. manual saving PDF file from console still not works (file is bigger – +-size of image, but wont starts – shows errors).
function preparedownloadPDF(imagelist){
    var page = 0;
    console.log(imagelist);
    var doc = new jsPDF();
    var imageArray = imagelist.split(" ");
    console.log(imageArray);
    for(var i = 0; i < imageArray.length; i++)
    {
        if(imageArray[i] != "")
        {
            pdf.getImgFromUrl(imageArray[i]);
            //pdf.generatePDF();
        }
    }
    pdf.saveFile("123.pdf")
}



var pdf = {
    page: 0,
    img: null,
    options: {orientation: 'p', unit: 'mm', format: "custom"},
    doc: new jsPDF(this.options),
    getImgFromUrl: function(base_url){
        this.img = new Image();
        this.img.src = base_url;
        console.log(this.img.src + " baseurl: "+ base_url)
        this.img.onload = function () {
            pdf.generatePDF();
        };
    }, 
    generatePDF: function(){

        //redrawing image to canvas, to later recreate this as a BASE64 string(RAW data)
        var canvas = document.createElement("canvas");
        canvas.width = this.img.width;
        canvas.height = this.img.height;

        console.log("canvas")
        console.log(canvas.width + "x" + canvas.height)

        canvas.getContext("2d").drawImage(this.img, 0, 0);

        var image = document.createElement("img");
        image.src = canvas.toDataURL();

        document.body.appendChild(image);
        
        if(this.page++ != 0)
            pdf.doc.addPage();

        pdf.doc.addImage(this.img, 10, 10);
    },
    saveFile: function(name){
        this.doc.save(name)
        this.page = 0;
    }
}

Any tips?

@

I not attach code of validation URL,etc. I use as valid phoenix-scans pl website.

Refresh an image after URL is changd by JavaScript

I have a background image which is randomly selected on session start but can be changed by a button which triggers an onclick function:

var images = new Array("assets/img/beach.jpg", "assets/img/city.jpg", "assets/img/valley.jpg", "assets/img/hills.jpg", "assets/img/rocky-beach.jpg", "assets/img/trees-lake.jpg", "assets/img/trees.jpg");


function selectImg() {
    if ("headerImage" in sessionStorage) {
        document.getElementById('headerImage').style.backgroundImage="url(" + sessionStorage.getItem("headerImage") + ")";
    } else {
        var selector = Math.floor(Math.random() * images.length);
        sessionStorage.headerImage = images[selector];
        document.getElementById('headerImage').style.backgroundImage="url(" + sessionStorage.getItem("headerImage") + ")";
    }
}

function resetImg() {
    sessionStorage.removeItem("headerImage");
    location.reload(); 
}

selectImg() is run on page load while resetImg() is what is run when the appropriately named reset button is clicked. How can I make this so rather than reloading the whole page it could just refresh the individual element to change the image – preferably without using libraries such as jQuery?

I am relatively new to JS so please excuse me if there are many things which could be improved!

Thanks in advance!

Discord.js not registering new slash commands because application names must be unique

Discord.js won’t register my commands again, despite the fact they don’t exist. I’ve verified that the commands don’t exist by running:

rest.get(Routes.applicationCommands(clientId))
    .then(data => console.log(data));

with the only response being []

The code (deploy-commands.js) looks like this:

const fs = require('node:fs');
const path = require('node:path');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { clientId, token } = require('./config.json');

const commands = [];
const commandsPath = path.join(__dirname, 'commands');
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);
    commands.push(command.data.toJSON());
}

const rest = new REST({ version: '9' }).setToken(token);

rest.put(Routes.applicationCommands(clientId), { body: commands })
    .then(() => console.log('Successfully registered application commands.'))
    .catch(console.error);

With this filetree:

discord-bot/
|-- Commands/
    |-- avatar.js
    |-- beep.js
    |-- kick.js
    |-- options-info.js
    |-- ping.js
    |-- prune.js
    |-- server.js
    |-- user-info.js
|-- node_modules
|-- config.json
|-- deploy-commands.js
|-- index.js
|-- package-lock.json
|-- package.json

HELP!