Get the index(es) of the max value in a 2-dimensional array

Most of what I’ve been developing recently has been data and API oriented. I’m getting pulled into some programming that requires matrix math, which I am new at.

I am trying to understand how to get the coordinates of the max value(s) in a 2d array.

let arr = [[0, 0, 1, 0, 0, 1], [0, 1, 0, 2, 0, 0], [0, 0, 2, 0, 0, 1], [0, 1, 0, 3, 0, 0], [0, 0, 0, 0, 4, 0]]

let maxIndexes = Math.max(arr /* unsure how to accomplish this */)
console.log(maxIndexes)
// expected result: [5,5]

Javascript loading error: Cannot read properties of null (reading ‘appendChild’) [duplicate]

I have set up a project on codesandbox, but it throws an error:Cannot read properties of null (reading ‘appendChild’)

bpmnjs project on codesandbox

TypeError
Cannot read properties of null (reading 'appendChild')
BpmnPropertiesPanelRenderer.attachTo
https://3gvxbk.csb.app/node_modules/bpmn-js-properties-panel/dist/index.esm.js:2354:15
eval
https://3gvxbk.csb.app/node_modules/bpmn-js-properties-panel/dist/index.esm.js:2335:14
invokeFunction
https://3gvxbk.csb.app/node_modules/diagram-js/lib/core/EventBus.js:204:13
EventBus._invokeListener
https://3gvxbk.csb.app/node_modules/diagram-js/lib/core/EventBus.js:130:19
EventBus._invokeListeners
https://3gvxbk.csb.app/node_modules/diagram-js/lib/core/EventBus.js:119:24
EventBus.fire
https://3gvxbk.csb.app/node_modules/diagram-js/lib/core/EventBus.js:94:24
Modeler.Diagram
https://3gvxbk.csb.app/node_modules/diagram-js/lib/Diagram.js:54:24
Modeler.BaseViewer._init
https://3gvxbk.csb.app/node_modules/bpmn-js/lib/BaseViewer.js:257:24
Modeler.BaseViewer
https://3gvxbk.csb.app/node_modules/bpmn-js/lib/BaseViewer.js:23:8
Modeler.BaseModeler
https://3gvxbk.csb.app/node_modules/bpmn-js/lib/BaseModeler.js:12:27
new Modeler
https://3gvxbk.csb.app/node_modules/bpmn-js/lib/Modeler.js:72:28
$csb$eval
/app/index.js:19:18
  16 | 
  17 | var container = $("#js-drop-zone");
  18 | 
> 19 | var bpmnModeler = new BpmnModeler({
     |                  ^
  20 |   container: "#js-canvas",
  21 |   propertiesPanel: {
  22 |     parent: "#js-properties-panel"
View compiled
▶ 10 stack frames were collapsed.

It seemed that the page isn’t rendered when the js code is executing. I also want to put the code into document ready function through this post, but it doesnt work at all:

uncaught-typeerror-cannot-read-property-appendchild-of-null

Could someone make any suggestions here, Thanks

Try use brew install gmp and brew install gnupg and im getting a Error

I am very new to this command terminals so please if anyone can dumb it down for me what I am supposed to do. I signed up for a coding boot camp and they are requiring I install these packages I am using a 2022 MacBook Pro with a Apple M1 Pro chip

allen@Alls-MacBook-Pro ~ % brew install gmp
Error: Cannot install in Homebrew on ARM processor in Intel default prefix (/usr/local)!
Please create a new installation in /opt/homebrew using one of the
"Alternative Installs" from:
https://docs.brew.sh/Installation
You can migrate your previously installed formula list with:
brew bundle dump

Webpage responding differently to javascript .click() than a normal mouse click

When I click on a particular element on a webpage using multiple different variants of the .click() event e.g. document.querySelectorAll(selector)[pos].dispatchEvent(new MouseEvent('click', {{ bubbles: true, cancelable: true, view: window }})); or document.querySelectorAll(selector)[pos].click() the webpage doesn’t load the corresponding page properly, in fact some of these events used to work a few days ago but now don’t work anymore and even if I send a reload request using javascript to the page it doesn’t show the expected dynamic elements and responsive code. Instead it just shows a blank result where I expected information. It requires me sending a manual click event using my own mouse and clicking on the reload for the corresponding dynamic code to reappear.

Is there a way to properly and fully simulate a mouse click using javascript such that it is indistinguishable from a normal click? I’ve tried a few MouseEvents but perhaps I’m just configuring them wrong, or the webpage is responding differently to console executed commands.

Running scripts with content pulled from local storage with innerHTML

I’ve been playing around with web development and wanted to create a basic application which allows users to enter html into a text area, which is saved in local storage, then later inserted into a document element with .innerHTML.

Minimum working example:

HTML

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>Prototyping</title>
</head>
<body>

    <!--- Using bootstrap v. 5.2.0 --->
    <form>
        <label for="content"></label>
        <textarea class="form-control" id="content"></textarea>
    </form>

    <div id="displayContent"></div>

    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
            integrity="sha384-pprn3073KE6tl6bjs2QrFaJGz5/SUsLqktiwsUTF55Jfv3qYSDhgCecCxMW52nD2"
            crossorigin="anonymous"></script>
    <script src="index.js"></script>
</body>
</html>

JavaScript

const userInput = document.getElementById('content');
const displayInput = document.getElementById('displayContent')

userInput.addEventListener('input', (event) => {
    localStorage.setItem(event.target.id, event.target.value);
    displayInput.innerHTML = localStorage.getItem(event.target.id);
});

Now I was concerned that using .innerHTML would allow users to inject js code <script>alert('HAHA')</script>. However, scripts fail to run. Or at least with my limited knowledge of HTML, I cannot get a script to run. This is what I want, but I don’t understand why. When inspecting the page, I will see the <script>. Is this because localStorage converts the input into strings? What is happening that prevents the script from running?

Dart compareTo() sometimes returns different result than javascript localeCompare()

I’m looking for a javascript function that compares two strings in a “standard” way, or at least in the same way it does in dart.

I have this code in dart that give two strings it checks which is the largest and creates a single string separated by a “-” with the largest string in front.

//dart code
void main() {
  String currentUserId = "bbijdF7zKgR7jOIAs7Ka86jwdRu1";
  String peerId = "UVvUo4xCM4N4TtiFWL5B6vOFzN53";
  String groupChatId = "";
  if (currentUserId.compareTo(peerId) > 0) {
    groupChatId = '$currentUserId-$peerId';
  } else {
    groupChatId = '$peerId-$currentUserId';
  }
  print(groupChatId);
}

The print will return bbijdF7zKgR7jOIAs7Ka86jwdRu1-UVvUo4xCM4N4TtiFWL5B6vOFzN53

So far no problem.

Now I should replicate this code in javascript and I found the localeCompare link function which should do the same thing as compareTo() link in dart. But this is not the case since, in the case of the two strings, they have different results.

//js code
var currentUserId = "bbijdF7zKgR7jOIAs7Ka86jwdRu1";
var peerId = "UVvUo4xCM4N4TtiFWL5B6vOFzN53";
var groupChatId = "";
if (currentUserId.localeCompare(peerId.id) > 0) {
  groupChatId = `${currentUserId}-${peerId}`
} else {
  groupChatId = `${peerId}-${currentUserId}`
}
console.log(groupChatId)

The print will return UVvUo4xCM4N4TtiFWL5B6vOFzN53-bbijdF7zKgR7jOIAs7Ka86jwdRu1

There are rare cases in which they give two different results, but this is precisely the problem. Is there any function in javascript that behaves like the compareTo in dart?

If anyone could explain to me why these two functions sometimes differ in the result I would be very grateful

How can we pass object as a parameter to a function name in Object value?

I want to pass an object to a function which is a value of another object. Is this possible, how can we do that? I can pass a string easily and a variable as a string. But, cannot pass as an object.

I have 2 objects like:

var test1 = "qwerty";
var test2 = { qwerty: "sdaf" };

I want to pass these objects as a parameter to an object value like the below.

var props = {
   event: `backdropEvent("${test}")`,
}
function backdropEvent(e){
 console.log(e)
}

When I tried to pass test1 I get it as a string. How can I pass the test2 object?

var test1 = "qwerty";
var test2 = { qwerty: "sdaf" };

var props = {
   event: `backdropEvent("${test2}")`,
}

function backdropEvent(e){
 console.log(e)
}

function testFn(){
testFn2(props);
}

function testFn2(e){
var x = Function(e.event);
x();
}
<button onclick="testFn()"> click me </button>

Scrape data in local storage to get specific information from it such as (key, value and extra)

I don’t know how to make this code give me the key, value and extra information in local-storage of a specific website in JS. I am beginner in JS and I been stuck in this phase for so long. I have tried some codes with changing them but always gave me error.

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch()
  const page = await browser.newPage()
  await page.goto('https://www.google.com/')

  const returnedCookie = await page.cookies();  
  console.log(returnedCookie)

  await page.waitForTimeout( 10000 );
  const localStorageData = await page.evaluate(() => {
    let json = {};
    for (let i = 0; i < localStorage.length; i++) {
      const key = localStorage.key(i);
      json[key] = localStorage.getItem(key);
    }
    return json;
  });

  console.log(localStorageData)

  await browser.close()
})()

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.goto('https://www.com/')

const returnedCookie = await page.cookies();  
console.log(returnedCookie)

await page.waitForTimeout( 10000 );
const localStorageData = await page.evaluate(() => {
let json = {};
for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  json[key] = localStorage.getItem(key);
}
return json;
});

console.log(localStorageData)

await browser.close()
})()

Similarity comparison of two groups of numbers (js or nodejs)

There are two arrays:

var ary1 = [
    { start: 10, end: 10.9, max: 11, min: 9.9 },
    { start: 10.5, end: 10.4, max: 10.75, min: 10.3 },
    // more ....
];
var ary2 = [
    { start: 50, end: 52.8, max: 53, min: 50 },
    { start: 52.5, end: 53, max: 53.5, min: 51 },
    // more ....
];

Each item in the array is represented graphically like this:

1

Graphically represent an array:

2

This is the K-line chart (candlestick chart) of the stock.

How to compare the similarity of candlestick charts generated by two arrays?

How to expose a single entry point bundle as a library in webpack configuration

I have a webpack.config.js file defined as module.exports = function (env, args) with different entry points. Now I want to add an entry point and expose it as a library. Calling webpacked code from outside (HTML script tag) says we can do

module.exports = {
  entry: './index.js',
  output: {
    path: './lib',
    filename: 'yourlib.js',
    libraryTarget: 'var',
    library: 'EntryPoint'
  }
};

But how do I restrict this to a specific entry point.

problem setting difficulties minesweeper react

I’m building a minesweeper game with socket.io everything seems to be working fine but I have one problem I need to add difficulties before the game loads on easy mode, for example, I need to have 10 cells on medium 100 and on hard 500 I don’t understand how can I add the difficulties to the game I tried to do it with a switch statement in a function but I couldn’t do it I’ve been working on this for a long time also when I tried to do cells with 100 cells instead of 10 in Array. fill function the board seems to fail and the cells are not opening the right away and they don’t stand under each other the order fails
front code:

import React, { useState, useEffect, useRef } from "react";
import "./App.css";
import { faceSmile } from "react-icons/fa";
import socketIOClient from "socket.io-client";
const ENDPOINT = "http://127.0.0.1:4001";

function App() {
  const [bombs, setBombs] = useState([]);
  const [visited, setVisited] = useState([]);

  const [state,setState ] = useState({bombs:[], visited:[]});

  const socketRef = useRef();

  const buttonStyle = {
    width: 40,
    height: 40,
    backgroundColor: "#8888",
    color: "black",
    verticalAlign: "top",
    fontSize: "32px",
    fontFamily: "Arial, Helvetica, sans-serif;",
    borderLeft: "5px solid rgb(220,220,220)",
    borderTop: "5px solid rgb(220,220,220)",
    borderBottom: "5px solid #333",
    borderRight: "5px solid #333",
    display: "inline-block",
  };
  const visitStyle = {
    width: 48,
    height: 48,
    backgroundColor: "#555",
    color: "white",
    fontWeight: "bold",
    border: "1px solid black",
    verticalAlign: "top",
    fontSize: "32px",
    fontFamily: "Montserrat, sans-serif",
    display: "inline-block",
  };

  useEffect(() => {
    socketRef.current = socketIOClient(ENDPOINT);
    socketRef.current.on("boardUpdate", (data) => {
      console.log("boardUpdate front", data)
      setState(data);
    });

    socketRef.current.on("onLost", () => {
      alert("You lost!");
      window.location.reload();
    });

    return () => socketRef.current.disconnect();
  }, []);


  const handleFlag = (e) => {
    e.preventDefault();
    e.target.style.backgroundColor = "red";
  };

  const visitCell = (i, j) => {
    socketRef.current.emit("onclick", { i, j });
  };

  const generateBombs = () => {
    console.log("generateBombs", socketRef.current);
    socketRef.current.emit("generateBoard");
  };

  return (
    <div className="App">
      <header className="App-header">
        <div className={"title"}> REACT-SWEEPER </div>
        <i class="fa-regular fa-face-smile"></i>
        <div className={"subtext"}> </div>

        {state.bombs.map((arr, index) => (
          <div>
            {arr.map((elem, i) => (
              <div
                onContextMenu={handleFlag}
                onClick={() => visitCell(index, i)}
                style={state.visited[index][i] == 0 ? buttonStyle : visitStyle}
              >
                {state.visited[index][i] == 0
                  ? null
                  : state.bombs[index][i] == 0
                  ? ""
                  : state.bombs[index][i]}
              </div>
            ))}
          </div>
        ))}
        <button className={"generate"} onClick={() => generateBombs()}>
          New Game
          <i class="fa-regular fa-face-smile"></i>
        </button>
      </header>
    </div>
  );
}

export default App;

back code with socket.io

const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server, {
  cors: {
    origins: ["*"],
  },
});

var bombs = [];
var visited = [];

io.on("connection", (socket) => {
  console.log("a user connected");

  socket.on("disconnect", () => {
    console.log("user disconnected");
  });

  socket.on("generateBoard", () => {
    generateBombs();
    console.log("generateBoard", this.bombs, this.visited);
    io.emit("boardUpdate", { bombs: this.bombs, visited: this.visited });
  });

  socket.on("onclick", (data) => {
    console.log("onclick", data);
    visitCell(data.i, data.j);

    io.emit("boardUpdate", { bombs: this.bombs, visited: this.visited });
  });
});

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

const generateBombs = () => {
  let bombArr = Array(10)
    .fill(0)
    .map((elem) => Array(10).fill(0));

  for (let i = 0; i < bombArr.length; i++) {
    let bombPos = Math.floor(Math.random() * 10);
    bombArr[i][bombPos] = "X";
  }

  for (let i = 0; i < bombArr.length; i++) {
    for (let j = 0; j < bombArr[i].length; j++) {
      if (bombArr[i][j] !== "X") {
        let sum = 0;

        if (i > 0 && bombArr[i - 1][j] == "X") sum++;
        if (i < bombArr.length - 1 && bombArr[i + 1][j] == "X") sum++;
        if (j < bombArr.length - 1 && bombArr[i][j + 1] == "X") sum++;
        if (j > 0 && bombArr[i][j - 1] == "X") sum++;
        if (i < bombArr.length - 1 && j > 0 && bombArr[i + 1][j - 1] == "X")
          sum++;
        if (
          i < bombArr.length - 1 &&
          j < bombArr.length - 1 &&
          bombArr[i + 1][j + 1] == "X"
        )
          sum++;
        if (i > 0 && j > 0 && bombArr[i - 1][j - 1] == "X") sum++;
        if (i > 0 && j < bombArr.length - 1 && bombArr[i - 1][j + 1] == "X")
          sum++;

        bombArr[i][j] = sum;
      }
    }
  }

  setBombs(bombArr);

  let cover = Array(10)
    .fill(0)
    .map((elem) => Array(10).fill(0));
  setVisited(cover);
};

const setBombs = (bombArr) => {
  this.bombs = bombArr;
};

const setVisited = (cover) => {
  this.visited = cover;
};

const Cells = (i, j) => {
  if (
    i < 0 ||
    i > this.visited.length - 1 ||
    j < 0 ||
    j > this.visited[0].length - 1 ||
    this.visited[i][j] == 1 ||
    this.bombs[i][j] == "X"
  )
    return;

    this.visited[i][j] = 1;

  setVisited([...this.visited]);
  if (this.bombs[i][j] < 1) {
    Cells(i + 1, j);
    Cells(i - 1, j);
    Cells(i, j + 1);
    Cells(i, j - 1);
  }
};

const visitCell = (i, j) => {
  if (this.bombs[i][j] == "X") {
    io.emit("onLost");
  }
  Cells(i, j);
  this.visited[i][j] = 1;
  setVisited([...this.visited]);
};

How to build node-libcurl with curl-impersonate

I’m trying to build node-libcurl with curl-impersonate
But I guess I’m unable to compile with this binding.gyp

'variables': {
    # Comma separated list
    'curl_include_dirs%': '/home/sonisins/live/hehe/install/include',
    'curl_libraries%': '/home/sonisins/live/hehe/install/lib',
    'curl_static_build%': 'false',
    'curl_config_bin%': '/home/sonisins/live/hehe/install/bin/curl-config',
    'node_libcurl_no_setlocale%': 'false',
    'node_libcurl_cpp_std%': '<!(node <(module_root_dir)/scripts/cpp-std.js)',
    'macos_universal_build%': 'false',
  },

Here’s my folder struct incase if something feels missing
enter image description here

React component displaying but returning NaN from custom hook

I am building an app with React/Remix, fly.io for deployment. I have a countdown component and custom hook built in React. I have a custom useCountdown hook with the following code:

import { useEffect, useState } from 'react';

const useCountdown = (targetSeconds) => {
    const [countDown, setCountDown] = useState(targetSeconds);

    useEffect(() => {
        const interval = setInterval(() => {
            setCountDown(targetSeconds);
        }, [targetSeconds]);

        return () => clearInterval(interval);
    }, [])

    return getReturnValues(countDown);
};

const getReturnValues = (countDown) => {
    const seconds = Math.floor((countDown % (1000 * 60)) / 1000);

    return seconds;
}

export default { useCountdown }

A CountdownTimer component with the following code:

import React from 'react';
import DateTimeDisplay from './DateTimeDisplay';
import { useCountdown } from '../hooks/useCountdown';

const ExpiredNotice = () => {
    return (
        <div className="expired-notice">
            <span>Expired!!!</span>
            <p>Please select a future date and time.</p>
        </div>
    );
};

const ShowCounter = ({ seconds }) => {
    return (
        <div className="show-counter">
                <DateTimeDisplay value={seconds} type={'Seconds'} isDanger={false} />
        </div>
    );
};

const CountdownTimer = ({ targetSeconds }) => {
    const [seconds] = useCountdown(targetSeconds);

    if (seconds <= 0) {
        return <ExpiredNotice />;
    } else {
        return (
            <ShowCounter
                seconds={seconds}
            />
        );
    }
};

export default CountdownTimer;

Finally, a DateTimeDisplay component with the following code:

import React from 'react';

const DateTimeDisplay = ({ value, type, isDanger }) => {
    return (
        <div className={isDanger ? 'countdown danger' : 'countdown'}>
            <p>{value}</p>
            <span>{type}</span>
        </div>
    );
};

export default DateTimeDisplay;

And I display it on index:

import Canvas from '../components/Canvas'
import Drawer from '../components/Drawer'
import LeftToolbox from '../components/LeftToolbox'
import CountdownTimer from '../components/CountdownTimer';

export default function App() {
    let seconds = 90
  return (
      <div className="overscroll-contain overflow-y-hidden h-screen w-screen">
          <div className="flex items-center justify-center h-screen w-screen bg-slate-800 z-40">
              <LeftToolbox />
              <div className="min-w-[320px] max-w-[640px] position absolute border border-[1rem] border-red-400 rounded-lg">
                  <CountdownTimer targetSeconds={seconds} />
                  <Drawer />
                  <Canvas />
                </div>
          </div>
      </div>
  )
}

The component displays, however instead of displaying an integer within the countdown component, it displays NaN and, in the console, it throws this error:

Warning: Received NaN for the `children` attribute. If this is expected, cast the value to a string.
    at p
    at div
    at DateTimeDisplay (http://localhost:3000/build/routes/index-AU5NYGLP.js:173:26)
    at div
    at ShowCounter (http://localhost:3000/build/routes/index-AU5NYGLP.js:204:22)
    at CountdownTimer (http://localhost:3000/build/routes/index-AU5NYGLP.js:213:25)
    at div
    at div
    at Drawer (http://localhost:3000/build/routes/index-AU5NYGLP.js:227:72)
    at div
    at div
    at div
    at App
    at RemixRoute (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:2523:3)
    at Outlet (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:730:26)
    at body
    at html
    at App
    at RemixRoute (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:2523:3)
    at Routes2 (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:2506:7)
    at Router (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:734:15)
    at RemixCatchBoundary (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:1019:10)
    at RemixErrorBoundary (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:944:5)
    at RemixEntry (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:2403:12)
    at RemixBrowser (http://localhost:3000/build/_shared/chunk-PXAPBAZS.js:3081:27)