Understanding JQuery syntax, nested selector

Today for the first time i have read a way of write JQuery query that i don’t understand.

var $this = $(this);
$('.note-codable', $('#'+$this.attr('id')).siblings('.note-editor')).bind('keyup', function() {
        $this.html(this.value);
    });

The code is taken from this post :
https://github.com/summernote/summernote/issues/94#issuecomment-421834080

What i don’t understand is the apparently nested query i mean, i know what this mean :

$('.note-codable')

And i know what this mean :

$('#'+$this.attr('id')).siblings('.note-editor')

But the combination of the two (with nesting) is completely unclear to me, and i mean :

$('.note-codable', $('#'+$this.attr('id')).siblings('.note-editor'))

So i am asking the meaning of the last piece of code above

How to compare two strings and delete diffencies- Make anagrams

I know this is topic which is already here on stackoverflow, but these approaches are the ones I do not want to follow as I do not understand them, so it’s wasting of time to just copy it.

I am pretty new in Javascript and I would like to ask you for help with anagrams. I am working on tasks from HackerRank and there is one with anagram.

Currently I have created few approaches which I think can lead to correct result, but it’s not finished and I feel lost after hours of searching for good looking solution.

Here is solution 1: I think this would work, but there is an issue with counting, it will return me 1 as only letter “C” is in the both strings, but what I want to return 2 as there were two “C” letters. Is there a way how I can achieve it ?

function makeAnagram(a, b) {
let count  =  0;
arrayA = Array.from(a);
arrayB = Array.from(b);
const try3 = try1.concat(try2);   
            let sameLetters = arrayA.filter(item => arrayB.includes(item))
            {
                count++;
            }
            console.log(sameLetters);
            console.log(count);
            
    count =  (try3.length - sameLetters2.length);
}
console.log(makeAnagram("cde", "abc"));

The next solution was with for cycles, but probably this is not enough and not correct

function makeAnagram(a, b) {
let count = 0;
let deleted = 0;  
for(let i = 0; i < a.length; i++)
{
    for(let j = 1; j < b.length; j++)
    {
        if(arrayA[i] == arrayB[i])
        {
            count++;
        }
        else
        {
            deleted++;
        }
    }
}

And the last solution I was trying and seems to me like a good solution is:

function makeAnagram(a, b) {
const array2 = [...a.split(""), ...b.split("")]
console.log(array2);
const something = array2.reduce((acc, letter) => array2.includes(letter) ? [] : [...acc, letter],[])
    }
}

Thank you

How to remove window eventListener in React component?

This peace of code shows user mouse coordinates, it works properly.

But I also want to remove event handler by clicking the STOP button. Unfortunately, this seems to be wrong somehow because event handler still tracking and changing position even after clicking the button:

import { useEffect, useState } from 'react'

function MouseCords() {
    const [position, setPosition] = useState({ x: 0, y: 0 })

    function mouseMoveHandler(event) {
        setPosition({
            x: event.clientX,
            y: event.clientY
        })
    }

    useEffect(() => {
        window.addEventListener('mousemove', mouseMoveHandler)
    }, [])

    return (
        <div>
            <pre>
                x: {position.x}
                <br />
                y: {position.y}
            </pre>
            <button
                onClick={() =>
                    window.removeEventListener('mousemove', mouseMoveHandler)
                }
            >
                STOP
            </button>
        </div>
    )
}

I guess there might be a problem with context, but I am not sure what to do to solve it.

By the way, this is React component and I am using it in App.js like this:

import MouseCords from './components/MouseCords'

function App() {
    return (
        <div>
            <MouseCords />
        </div>
    )
}

export default App

I’m new in JavaScript, I had wrote this python code. I want this code in javaScript. Please try to use same approach as mine in below code

        '''
# I'm new in JavaScript, I had wrote this python code. I want this code in  javaScript. Please try to use same approach as mine in below code. 
    jsondict = {
          "rules": [
            {
              "id": "case_channel",
              "type": "string",
              "field": "case_channel",
              "input": "text",
              "value": "Web Self Service",
              "operator": "equal"
            },
            {
              "id": "classification_l3",
              "type": "string",
              "field": "classification_l3",
              "input": "text",
              "value": "Callback request",
              "operator": "equal"
            },
            {
              "id": "classification_l4",
              "type": "string",
              "field": "classification_l4",
              "input": "text",
              "value": "Year End Option Change",
              "operator": "equal"
            },
            {
              "id": "bo_table_title",
              "type": "string",
              "field": "bo_table_title",
              "input": "text",
              "value": "Callback request from Ask Assegai",
              "operator": "equal"
            },
            {
              "rules": [
                {
                  "id": "wrkgrp_name",
                  "type": "string",
                  "field": "wrkgrp_name",
                  "input": "text",
                  "value": "External Employee Workgroup",
                  "operator": "equal"
                },
                {
                  "id": "wrkgrp_name",
                  "type": "string",
                  "field": "wrkgrp_name",
                  "input": "text",
                  "value": "Year End Product Review Case Workgroup",
                  "operator": "equal"
                }
              ],
              "condition": "OR"
            }
          ],
          "valid": True,
          "condition": "AND"
        }
        
        def test(jsn):
            names = []
            for x in jsn['rules']:
                if x.get('condition'):
                    names.append(test(x))
        
                else:
                    names.append(x['field'] +" "+ x['operator'] +" "+ x['value'])
        
            condition = " "+ jsn['condition'] +" "
            return "(IF "+ condition.join(names) +")"
        
        print(test(jsondict))

OUTPUT – (IF case_channel equal Web Self Service AND classification_l3 equal Callback request AND classification_l4 equal Year End Option Change AND bo_table_title equal Callback request from Ask Assegai AND (IF wrkgrp_name equal External Employee Workgroup OR wrkgrp_name equal Year End Product Review Case Workgroup))

    '''

Checking a Calculator display has one number in the innerHTML string

I’m working on a calculator with vanilla JavaScript. I’m trying to make an if statement to find out whether the current result displayed has only one number left in the string. If this is true I want to make sure when the user clicks the delete button the current display returns to the default display instead of having no numbers in the string. I hope I explained this properly. How would I go about making this check.

const numberButtons = document.querySelectorAll("[data-number]");
const operationButtons = document.querySelectorAll("[data-operation]");
const allClearButton = document.querySelector("[data-reset]");
const deleteNumberButton = document.querySelector("[data-delete]");
const equalsButton = document.querySelector("[data-equals]");
const DISPLAY_RESULT = "0";

const ADDITION = "+";
const MULTIPLICATION = "X";
const DIVISION = "รท";
const SUBTRACTION = "-";

/// Gets the number of the display whatever the theme is.
let currentResult = document.querySelectorAll(
    ".current-result__1,.current-result__2,.current-result__3"
);

let firstNumber = "";
let secondNumber = "";
let currentOperator = "";

let numberPattern = new RegExp(/[0-9]/);


const deleteNumber = () => {
    let newDisplayedResult = currentResult[0].innerHTML.slice(0, -1);

    if (numberPattern.test(newDisplayedResult)) {
        currentResult[0].innerHTML = DISPLAY_RESULT;
    }
    if (firstNumber !== "" && currentOperator !== "") {
        secondNumber = newDisplayedResult;
        currentResult[0].innerHTML = newDisplayedResult;
    } else {
        firstNumber = newDisplayedResult;
        currentResult[0].innerHTML = newDisplayedResult;
    }
};

Typescript error message ‘,’ expected.ts(1005)

I keep getting the error message ‘,’ expected.ts(1005) when trying to dynamically render a modal on Typescript. I’m almost certainly missing a closing curly bracket somewhere but cant figure out where.

      `<div class="modalWrap">
      <h2 class="modalHeader">Shop The Look</h2>
      <div class="modalContent">${object.map((el) => 
      `<div class="prodDetails">
        <img class="prodImg" alt="prodImage" src = ${el.primaryImage.url}></img>
        <p class="prodName">${el.name}</p>
        <p class="prodPrice">${el.price.value}</p>
        <div class = "selectWrapper">
    <div class="selectNumber">
    <div class="numberWrapper"> 
  ${el.sizeOptions
    .map(
      (option) => `
      <p class="selectSize" >${option.value}</p>`
    )
    .join('')}
    </div>
    </div>
    </div>
    </div>
    </div>
    )}
    </div>`

Any help would be appreciated!

How to clear input field after submitting form and push values into array (Vanilla JS)

Onclick of the button I would like to take the values submitted and index them in the empty array. As you can see in the bottom line I have used the reset method on the form but when logging the array, all of the indexes have an empty value.

I have also used preventDefault() to stop the form from submitting, could the form tags be causing the issue?

const enteredNumbers = [];

console.log(enteredNumbers);

const form1 = document.getElementById("form1");

form1.addEventListener("submit", e => {
  e.preventDefault();
  const values = document.getElementsByName("number")[0];
  enteredNumbers.push(values);
  form1.reset();
}, true);
         <form id="form1">

                <div class="row w-100 d-flex justify-content-between div1">


                    <div class="col-12 d-flex justify-content-center">
                        <input type="number" name="number" id="number" min="1" max="100">
                    </div>

                    <div class="col-12 d-flex justify-content-center">
                        <button type="submit" form="form1" id="submit">Submit</button>
                    </div>

                </div>

            </form>

Using Video as Mask of Video with Canvas

I have been trying to create a dynamic mask from one video onto another one. Neither videos have an alpha channel (and even then it would have low support in browsers right now), so I am trying to solve the issue with canvas. I have managed to get it done in very limited cycles, but it still isn’t able to do this at a decent frame rate in my output (it hits about 20 fps and it should at least get 25/30 to appear smooth). It is actually running in Singular with other elements around it, so I need to get it more efficient.

Due to confidentiality I can’t actually share the actual videos, but one contains the alpha mask (mask.mp4) in black and white (and shades of gray in between) while the other video content can be anything that needs to be masked (video.mp4).

The code that I want to improve is actually this (assume all videos and canvas elements are 1920x1080):

const video = document.getElementById( 'video' ); // `<video src="video.mp4"></video>
const mask = document.getElementById( 'mask' ); // `<video src="mask.mp4"></video>
const buffer = document.getElementById( 'buffer' ); // <canvas hidden></canvas>
const bufferCtx = buffer.getContext( '2d' );
const output = document.getElementById( 'output' ); // <canvas></canvas>
const outputCtx = output.getContext( '2d' );

outputCtx.globalCompositeOperation = 'source-in';

function maskVideo(){
    
    // Draw the mask
    bufferCtx.drawImage( mask, 0, 0 );
    
    // Get image data
    const data = bufferCtx.getImageData( 0, 0, w, h );
     
    // Assign the grayscale value to the alpha in the image data
    for( let i = 0; i < data.data.length; i += 4 ){
    
        data.data[i+3] = data.data[i];
    
    }
    
    // Put in the data
    outputCtx.putImageData( data, 0, 0 );
    // Draw the masked video into the mask (see the globalCompositeOperation above)
    outputCtx.drawImage( video, 0, 0, w, h );

}

So my question is: is there any more efficient way of masking out black pixels from another video while both videos are running? I am currently not worried about concurrency (the difference between both streams is less than a millisecond, much less than an actual frame in the video itself). The goal is to improve framerates.

Here is the more expansive code snippet that unfortunately doesn’t work on stack overflow for obvious CORS and video hosting reasons:

const video = document.getElementById( 'video' );
const mask = document.getElementById( 'mask' );
const buffer = document.getElementById( 'buffer' );
const bufferCtx = buffer.getContext( '2d' );
const output = document.getElementById( 'output' );
const outputCtx = output.getContext( '2d' );
const fpsOutput = document.getElementById( 'fps' );
const w = 1920;
const h = 1080;

let currentError;
let FPSCount = 0;

output.width =
buffer.width = w;
output.height =
buffer.height = h;

outputCtx.globalCompositeOperation = 'source-in';

function maskVideo(){

    if( !video.paused ){

        bufferCtx.drawImage( mask, 0, 0 );

        const data = bufferCtx.getImageData( 0, 0, w, h );

        for( let i = 0; i < data.data.length; i += 4 ){

            data.data[i+3] = data.data[i];

        }

        outputCtx.putImageData( data, 0, 0 );
        outputCtx.drawImage( video, 0, 0, w, h );

        FPSCount++;

    } else if( FPSCount ){

        fpsOutput.textContent = (FPSCount / video.duration * video.playbackRate).toFixed(2);
        FPSCount = 0;

    }

    window.requestAnimationFrame( maskVideo );

}

window.requestAnimationFrame( maskVideo );
html {
    font-size: 1vh;
    font-size: calc(var(--scale,1) * 1vh);
}
html, body {
    height: 100%;
}
body {
    padding: 0;
    margin: 0;
    overflow: hidden;
}
video {
    display: none;
}
canvas {
    position: fixed;
    top: 0;
    left: 0;
}
#fps {
    position: fixed;
    top: 10px;
    left: 10px;
    background: red;
    color: white;
    z-index: 5;
    font-size: 50px;
    margin: 0;
    font-family: Courier, monospace;
    font-variant-numeric: tabular-nums;
}
#fps:after {
    content: 'fps';
}
<video id="video" src="./video.mp4" preload muted hidden></video>
<video id="mask" src="./mask.mp4" preload muted hidden></video>
<canvas id="output"></canvas>
<canvas id="buffer" hidden></canvas>

<p id="fps" hidden></p>

Javascript is changing style of all elements instead of one

I am trying to change the background color of div one by one with an interval of 1sec
but my code changes the color of all divs after one 1sec

HTML:

<div class="container">
  <div class="bar" id="bar-1"></div>
  <div class="bar" id="bar-2"></div>
  .
  .
  <div class="bar" id="bar-100"></div>
</div>

Javascript:

for (let i = 1; i <= 100; i++) {
  let elem = document.getElementById('bar-' + i);

  setTimeout(function() {
    elem.style.backgroundColor = 'blue';
  }, 1000);
}

the server responded with a MIME type of “image/png” – HTML / JavaScript

I’m building a mario-like game with HTML and JavaScript, and now that it is almost done, i’d like to change my rectangles (the platforms) by images.

Here is my structure :

- index.html
- index.js
- index.css
- /assets/platform.png

To import my image, in my index.js I did :
import platform from './assets/platform.png'

Browser return this error :
Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of "image/png". Strict MIME type checking is enforced for module scripts per HTML spec.

I am using Live Server from VSCode.

Any help on this ?

postman scripting with static guids

I’m hoping to use Postman to generate and insert test data for an API project I’m working on. The resources in the API have foreign key constraints, so I want to be able to generate static guids for the resources, and share those IDs among all the other requests so that we can maintain the references and have valid foreign keys.

At the moment I’m generating data that I want to keep accessible to all the requests in the collection in a pre-request script at the collection level:

// set the user ID for our test user
var userId = pm.variables.replaceIn("{{$guid}}"); 
pm.collectionVariables.set("userId", userId);

// then generate a product ID
var productId = pm.variables.replaceIn("{{$guid}}"); 
pm.collectionVariables.set("productId", productId);

// create a few vendors
var vendorId1 = pm.variables.replaceIn("{{$guid}}"); 
pm.collectionVariables.set("vendorId1", vendorId1);

var vendorId2 = pm.variables.replaceIn("{{$guid}}"); 
pm.collectionVariables.set("vendorId1", vendorId1);

// etc

My thought was that I’d use the userId in all subsequent POSTs so there’d be a real user to associate a new object with, then use the vendor IDs with the product inserts, etc.

However, the pre-request script runs before each request– I think it’s re-creating all these values rather than keeping them static, so my plan to maintain integrity isn’t working.

Is there a better strategy? For example, can I capture the ID of the inserted object from the request response and pass that variable on to the next request in the workflow so that it can use that ID for the associated resources?

Node js session logout issue

I have created an Node js app,
I am creating session using

app.use(session({
  resave: true , 
  rolling: true,
  secret: '2853554111' , 
  genid: function(req) { return uuid(); },
  saveUninitialized: true
 }));

and this is how I am saving my data in session.

req.session.user=req.body.username;

but after sometime I am getting undefined value of user in session, and this is hapenning very frequently,
Not sure what is wrong with the code.

This is how my app.js looks like

var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var bodyParser = require('body-parser');
var uuid = require("uuidv4");
var app = express();
var login = require('./routes/login-admin');
var adminHome = require('./routes/adminHome');
var pmLogin = require('./routes/pmLogin');
var pmHome = require('./routes/pmHome');
var confirmEmail = require('./routes/confirmEmail');

app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.static('public'));
app.use(logger('dev'));
//app.use(express.json());
app.use(express.json({limit: '5120mb'}));
//app.use(bodyParser.json())
app.use(bodyParser.json({ limit: '5120mb' }))
app.use(express.urlencoded({limit: '5120mb', extended: false }));

// view engine setup
app.use(session({
  resave: true , 
  rolling: true,
  secret: '2853554111' , 
  genid: function(req) { return uuid(); },
  saveUninitialized: true
 }));

app.use('/', indexRouter);
//app.use('/', login);
app.use('/users', usersRouter);
app.use('/login-admin', login);
app.use('/adminHome', adminHome);
app.use('/login', Login);
app.use('/Home', Home);
app.use('/confirmEmail', confirmEmail);

When Row is removed from table all subsequent rows are removed

I found a strange bug while testing the remove function on my tables. When building an HTML Form. Lets say there are 5 rows.

When I delete row 3 there are now 4 rows visible to the user. In the when I console.log(#partTable tr).length the table has 4 rows.

When I console.log the contents of the table I see rows 1, 2, 4, and 5. But when the viewModel gets the table, as part of the post action, the viewModel will only contain 1 and 2.

That missing row must break the code of the table when it gets submitted and ends the table rows where there is a form of null in the middle. Here is my code.

First is the code for adding rows to the table followed by the function that removes a row from that table.

    $("body").on("click", "#btnAdd", function () {
        //Reference
        var counter = $("#tblPart tr").length - 1;
        var txtName = $(`#patz${counter}`);
        var quant = $(`#quantz${counter}`);



        // Build
        var first = `<tr> <td class="rowIndex"> <input name='PartNumberModel[${counter}].SubPartNumber' type = 'text' required = "required"  /></td> `;
        var third = `<td><input name= 'PartNumberModel[${counter}].SubQuantity' type= 'number', min='0'  /></td>`;
        var removeButton = "<td><input type= 'button', onclick='Remove(this)', value = 'Remove' /></td>  </tr>";

        ////Add Row.
        var markup = first + third + removeButton;
        $("#tblPart tbody").append(markup);
                    console.log(markup);


    });


    function Remove(button) {
        //Determine the reference of the Row using the Button.
        var row = $(button).closest("TR");
 
        var name = $("TD", row).eq(0).html();



        if (confirm("Do you want to delete: " + name)) {
            //Get the reference of the Table.
            var table = $("#tblPart")[0];

            //Delete the Table row using it's Index.
            table.deleteRow(row[0].rowIndex);

        }
    };

Here is the code for the HTML portion of the table that gets the rows added to it.

        <div class="row justify-content-center">
            <div class="form-group col-md-6">
                <input type="button" value="Add" class="button is-primary" id="btnAdd" />
                <table id="tblPart" style="table-layout:fixed; width:100%;">
                    <thead>
                        <tr>
                            <th>
                                Part Number
                            </th>
                            <th>
                                Quantity
                            </th>
                            <th>
                                Remove Row
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        @for (var i = 0; i < Model.PartNumberModel.Count(); i++)
                        {
                            <tr>
                                <td>
                                    @Html.TextBoxFor(modelItem => Model.PartNumberModel[i].SubPartNumber, new { id = $"patz{i}", required = "required" })
                                </td>
                                <td>
                                    @Html.TextBoxFor(modelItem => Model.PartNumberModel[i].SubQuantity, new { type = "number", min = "0", id = $"quantz{i}", required = "required" })
                                </td>
                                <td>
                                    <input type='button' onclick='Remove(this)' value='Remove' />
                                </td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>

Thank you for any help you’re able to offer.