Is there a way to transfer a 2d list from a Python file to a Javascript file and use it a 2D array and vice versa?

I was trying to figure out a way to use an entry in an Excel file in python with pandas, convert that to a 2D list, and then move that to a Javascript file so I could use it as a 2D array and integrate it into a webpage I was working on, as well as complete the reverse of that process. The part that I need help with is moving the list to the JavaScript file.

How to prevent Jest from combing results?

I currently have two jest test cases the first one passes, but the second fails because its adding the sum of the previous case to the to that one

test('Subtotal to be 386.95 & VAT to be 54.173', () => {
    cart = ["tshirt", "shoes", "jacket", "blouse", "pants"]
    expect(calculateSubTotal(cart)).toBe(386.95);
    expect(calculateVAT(cart)).toBe(54.173)
})

test('Subtotal to be 30.99 & VAT to be 4.388', () => {
    cart = ["tshirt"]
    expect(calculateSubTotal(cart)).toBe(30.99);
    expect(calculateVAT(cart)).toBe(4.338)
});
expect(received).toBe(expected) // Object.is equality

    Expected: 30.99
    Received: 417.94

What do I need to do for jest to break out of the first test and not combine the test results?

What is the proper way to POST data using javascript fetch?

I am trying to get away from jQuery and start using promises and arrow functions. Try as I might, I can’t seem to pass data to PHP using javascript fetch.

$btnarrmem.addEventListener('click',()=>{
        let $url = "getMember.php";
        let $data = {vid: '527571'}
        $data = JSON.stringify($data);
        console.log ($data);
        fetch ($url, {
            method:'POST',
            headers :{
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=utf-8'
            },
            body:$data
        })

        .then((response)=>{
            console.log (response.text())


        })
     

The result is always

Promise {<pending>}
[[Prototype]]: Promise
[[PromiseState]]: "fulfilled"
[[PromiseResult]]: *"Notice</b>:  Undefined index: data in /mnt/development/websites/arrows/getMember.php< on line <b>7<*emphasized text**

Which means to me that PHP is not getting data.

Here is the same function written using jQuery and it works just as I want it to

let $data = {vid: '527571'}
$data = JSON.stringify($data);
console.log($data);
$('button.qrymem').click(function () {
    let $data = {vid: '527571'}
    $data = JSON.stringify($data);
    console.log ($data);
    $.post('getMember.php', {data: $data}, function ($result) {
        console.log($result);
        $divquery.text($result);
    })

})

I’d appreciate any suggestions to get me moving in the proper direction.

Array turning into object for no reason when using Redux

Im using redux to fetch orders from firebase , but after i try to use that array it says that its not an array ! i tried consoling log the type of it , and its telling me its an object , but i never changed it ! ordersArray

actions :

export const fetchOrders = () => {
  return async (dispatch) => {
    const ordersArray = [];
    const q = query(
      collection(db, "notValidatedOrders"),
      where("clientId", "==", authentication.currentUser.uid)
    );
    const querySnapshot = await getDocs(q);

    querySnapshot.forEach((doc) => {
      ordersArray.push(2);
    });

    console.log("ACTIONS", typeof ordersArray);

    dispatch({
      type: FETCH_ORDERS,
      orders: ordersArray,
    });
  };
};

Reducer :

import { FETCH_ORDERS } from "../actions/orders";

const initialState = {
  orders: [],
};

export default (state = initialState, action) => {
  switch (action.type) {
    case FETCH_ORDERS:
      return {
        orders: action.orders,
      };
  }
  return state;
};

the component that im using it in :



const orders = useSelector((state) => state.orders.orders);
 const [ordersState, setOrdersState] = useState([]);
 const [isLoading, setIsLoading] = useState(false);
 console.log(typeof orders);

 const fetchOrders = useCallback(async () => {
   setIsRefreshing(true);
   try {
     await dispatch(ordersActions.fetchOrders());
   } catch (err) {
     console.log(err.message);
   }
   setIsRefreshing(false);
 }, [setIsRefreshing, dispatch]);

 useEffect(() => {
   setIsLoading(true);
   fetchOrders()
     .then(() => {
       setOrdersState(orders);
     })
     .then(() => {
       setIsLoading(false);
     });
 }, [dispatch, fetchOrders]);

Need help on a todo list using javascript and local storage?

What do i add to my HTML and JS file in order to save values to local storage, and read them as well as load them from local storage so that they fill into the list automatically as well as adding a clear button for clearing local storage?

let addToDoButton = document.getElementById('addToDo');
let toDoContainer = document.getElementById('toDoContainer');
let inputField = document.getElementById('inputField');


addToDoButton.addEventListener('click', function(){
    var paragraph = document.createElement('p');
    paragraph.classList.add('paragraph-styling');
    paragraph.innerText = inputField.value;
    toDoContainer.appendChild(paragraph);
    inputField.value = "";
    paragraph.addEventListener('click', function(){
        paragraph.style.textDecoration = "line-through";
        paragraph.style.color = "red";
    })
    paragraph.addEventListener('dblclick', function(){
        toDoContainer.removeChild(paragraph);
    })
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <title>To Do List</title>
</head>

<body>
  <label><h1>To Do List</h1></label>
    <div class="container">
      <input id="inputField" type="text" name="todo" id="todo">
      <button id="addToDo">+</button>

      <div class="to-dos" id="toDoContainer">
      </div>
    </div>
  <script src="main.js"></script>

</body>

</html>

How to get parent object in multidementional array javascript

I have multidementional array and each object has same keys.

export const MENUS = [
    {
        "type": "main",
        "submenu": [],
        "path": "/a"
    },
    {
        "type": "main",
        "submenu": [
            {
                "type": "submenu",
                "submenu": [
                    {
                        "type": "submenu",
                        "submenu": [],
                        "path": "/b/4"
                    },
                ],
                "path": null
            },
            {
                "title": "portfolio",
                "type": "submenu",
                "path": "/b/1"
            },
            {
                "type": "menu",
                "submenu": [],
                "path": "/b/10"
            },
            {
                "type": "submenu",
                "submenu": [],
                "path": "/b/13"
            },
        ],
        "path": null
    },
    {
        "type": "main",
        "submenu": [],
        "path": "/c"
    }
]

Now, I have a key and value (path: ‘/b/1’) and I want to fetch parent object by key/value in array.

this is the result what I am looking for.

{
   "type": "main",
   "submenu" : [
     ...  // array with 4 objects
   ],
   "path": null
}

If anyone have good solution, please advice me.
Thanks.

Applesystem does not send the questions after the wanted code

So when I press the specific button it dms me and sends me the first question but after that the other 4 questions are just sent and the appsChannel.send is not considered as a function. Here is the code and screenshots so you can see the problems again.

Code from the event:

const questionSchema = require("../models/questionsconfig")
const  {
    MessageCollector,
    MessageEmbed
}= require("discord.js")

const logSchema = require("../models/setlogchannel")

module.exports = {
    name: "interactionCreate",
    once: false,
    async execute(interaction) {
        if(interaction.customId === "applybtn") {
            const questionData = await questionSchema.findOne({ guildid : interaction.guild.id })
            const q1 = questionData.q1
            const q2 = questionData.q2
            const q3 = questionData.q3
            const q4 = questionData.q4
            const q5 = questionData.q5

            const questions = [
                `${q1}`,
                `${q2}`,
                `${q3}`,
                `${q4}`,
                `${q5}`
            ];
    
            let collectCounter = 0;
            let endCounter = 0;
    
            interaction.reply({
                content: "Check your private messages!",
                ephemeral: true
            })
    
            const filter = (m) => m.member.id === interaction.member.id;
    
            const appStart = await interaction.user.send(questions[collectCounter++]);
            const channel = appStart.channel;
    
            const collector = channel.createMessageCollector(filter);
    
            collector.on("collect", () => {
                if(collectCounter < questions.length) {
                    channel.send(questions[collectCounter++])
                } else {
                    channel.send({
                        content: "Your application has been sent!"
                    });
                    collector.stop("fulfilled");
                }
            });
            const logchData = await logSchema.findOne({ guildid: interaction.guild.id })
            const chid = logchData.channelid
            const appsChannel = chid;
            collector.on('end', (collected, reason) => {
                if(reason === 'fulfilled') {
                 let index = 1;
                 const mappedResponses = collected
                 .map((msg) => {
                     return `${index++}) ${questions[endCounter++]}n-> ${msg.content}`
                })
                    .join('nn');
    
                    const embed = new MessageEmbed()
                    .setTitle("New applyication!")
                    .setDescription(mappedResponses)
                    .setColor("RED")
                    .setTimestamp()

                appsChannel.send({
                   embeds:   
                 })
                
            }
        })
        }
    }
}

And here are the screenshots from the errors mentioned above:enter image description here

Javascript for split address into house number and street name issue with streetname

I am using this below code in Jmeter to split address, but I am not getting street name fully as Dry Pine Bay Rd, it is returning on Dry Pine Bay, Rd is not returning. Can someone please help me in fixing this code or providing me working code in Javascript

var split = address.split(" ");
var number = split[0];
var name = split[1];
for (var i = 2; i < split.length - 1; i++)
name += " " + split[i];
var type = split[split.length - 1];
log.info("varhouseno" +number)
log.info("varstreetName" +name)
Result: varhouseno = 4860. 
varstreetName =Dry Pine Bay ( Not getting full street name here missing Rd at the end)```


what does it mean to mention the original array after an else operator?

I am studying by looking at different answers for question in freecodecamp and I came across this one that I can’t figure out the last part:

function steamrollArray(arr) {
    const flat = [].concat(...arr);
    return flat.some(Array.isArray) ? steamrollArray(flat) : flat;
  }
  
  console.log(steamrollArray([[3, [[4]]]]));

Why does it say “flat” after the “else :”, like what does that mean?
It just mention the original array, there is nothing going on like .push() or other methods.

edit text in a span with java script

I am new to JS and websites in general. How can I edit the text “Delta” and “Math” in this class? So far I can only get to them with:

document.querySelector(".navbar-brand")

image of the class

I couldn’t copy the class, so I added an image of it.

basic calculator in js [closed]

it is basic code of calculator which has built on javascript, html , css so i need to know it’s working hot it’s work if anyone knows please tell me

“use strict”;

    var input = document.getElementById('input'), // input/output button
  number = document.querySelectorAll('.numbers div'), // number buttons
  operator = document.querySelectorAll('.operators div'), // operator buttons
  result = document.getElementById('result'), // equal button
  clear = document.getElementById('clear'), // clear button
  resultDisplayed = false; // flag to keep an eye on what output is displayed

// adding click handlers to number buttons
for (var i = 0; i < number.length; i++) {
  number[i].addEventListener("click", function(e) {

    // storing current input string and its last character in variables - used later
    var currentString = input.innerHTML;
    var lastChar = currentString[currentString.length - 1];

    // if result is not diplayed, just keep adding
    if (resultDisplayed === false) {
      input.innerHTML += e.target.innerHTML;
    } else if (resultDisplayed === true && lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷") {
      // if result is currently displayed and user pressed an operator
      // we need to keep on adding to the string for next operation
      resultDisplayed = false;
      input.innerHTML += e.target.innerHTML;
    } else {
      // if result is currently displayed and user pressed a number
      // we need clear the input string and add the new input to start the new opration
      resultDisplayed = false;
      input.innerHTML = "";
      input.innerHTML += e.target.innerHTML;
    }

  });
}

// adding click handlers to number buttons
for (var i = 0; i < operator.length; i++) {
  operator[i].addEventListener("click", function(e) {

    // storing current input string and its last character in variables - used later
    var currentString = input.innerHTML;
    var lastChar = currentString[currentString.length - 1];

    // if last character entered is an operator, replace it with the currently pressed one
    if (lastChar === "+" || lastChar === "-" || lastChar === "×" || lastChar === "÷") {
      var newString = currentString.substring(0, currentString.length - 1) + e.target.innerHTML;
      input.innerHTML = newString;
    } else if (currentString.length == 0) {
      // if first key pressed is an opearator, don't do anything
      console.log("enter a number first");
    } else {
      // else just add the operator pressed to the input
      input.innerHTML += e.target.innerHTML;
    }

  });
}

// on click of 'equal' button
result.addEventListener("click", function() {

  // this is the string that we will be processing eg. -10+26+33-56*34/23
  var inputString = input.innerHTML;

  // forming an array of numbers. eg for above string it will be: numbers = ["10", "26", "33", "56", "34", "23"]

in this line i m confused what does it mean kindly do let me know if you can
var numbers = inputString.split(/+|-|×|÷/g);

  // forming an array of operators. for above string it will be: operators = ["+", "+", "-", "*", "/"]
  // first we replace all the numbers and dot with empty string and then split

here is also confusion
var operators = inputString.replace(/[0-9]|./g, “”).split(“”);

  console.log(inputString);
  console.log(operators);
  console.log(numbers);
  console.log("----------------------------");

  // now we are looping through the array and doing one operation at a time.
  // first divide, then multiply, then subtraction and then addition
  // as we move we are alterning the original numbers and operators array
  // the final element remaining in the array will be the output
and here is also i m not understanding this piece of code.
  var divide = operators.indexOf("÷");
  while (divide != -1) {
    numbers.splice(divide, 2, numbers[divide] / numbers[divide + 1]);
    operators.splice(divide, 1);
    divide = operators.indexOf("÷");
  }

  var multiply = operators.indexOf("×");
  while (multiply != -1) {
    numbers.splice(multiply, 2, numbers[multiply] * numbers[multiply + 1]);
    operators.splice(multiply, 1);
    multiply = operators.indexOf("×");
  }

  var subtract = operators.indexOf("-");
  while (subtract != -1) {
    numbers.splice(subtract, 2, numbers[subtract] - numbers[subtract + 1]);
    operators.splice(subtract, 1);
    subtract = operators.indexOf("-");
  }

  var add = operators.indexOf("+");
  while (add != -1) {
    // using parseFloat is necessary, otherwise it will result in string concatenation :)
    numbers.splice(add, 2, parseFloat(numbers[add]) + parseFloat(numbers[add + 1]));
   `enter code here` operators.splice(add, 1);
    add = operators.indexOf("+");
  }

  input.innerHTML = numbers[0]; // displaying the output

  resultDisplayed = true; // turning flag if result is displayed
});

//i have understand all of this but 
var numbers = inputString.split(/+|-|×|÷/g); line is confusing me
var operators = inputString.replace(/[0-9]|./g, "").split(""); also this line

var divide = operators.indexOf("÷");`enter code here` //here also do let me know if anyone can solve this
  while (divide != -1) {
    numbers.splice(divide, 2, numbers[divide] / numbers[divide + 1]);
    operators.splice(divide, 1);
    divide = operators.indexOf("÷");
  }

I tried everything with git

can someone please help I’ve tried to push my code to GitHub for hours now no success my git tells me “error failed to push some refs to https//github.com…” and when I try to commit it tells me another git process seems to be running in this repository”so I looked up and people say try typing in “rm -f .git/index.lock” which I did I even tried all of em commands not only that one from all sorts of commands it just kept spamming me the same message I started trying to run git from visual studio maybe I’d do something with that I even deleted it and re installed git not sure what to do anymore I tried everything I can’t even find the file index.lock but only index so I don’t know what to do plz help tried everything. Thank you

Generate clean short unique ID from MongoDB object id

I’m working on a MERN patient monitoring system app, which requires generating unique patient ID for each patient. MongoDB object IDs are not user friendly for real time applications. So how can I modify an ID like this, “6260156170355cbf6ec668g4” to display on the frontend as a clean, short unique patient ID for each patient?

Also is there is any way to generate unique sequential IDs from object IDs?

Passing props with React+ Typesscript + React Redux

I have one app that uses react, react-redux, now I am converting it into typescrypt, but it is very complicated. I have this:

Login.tsx

....
import ValidationErrors from 'components/ValidationErrors'
import { useAppDispatch, useAppSelector } from 'store/hooks';

function Login() {
    
    ...
    ...
    const errors = useAppSelector(state =>state.error) 

    return (        
        <div className="login">                     
           ....
            { errors.errors.length &&                                             
                <ValidationErrors errors={errors} />                    
            }
         ...
         </div>
      )
}
   

components/ValidationErrors.tsx

    import React from 'react';
    import Errors from 'interfaces/Errors';
    
    function ValidationErrors( {errors}: Errors ) {            
        return (                
            <div>
                <div className="font-medium text-red-600">{errors.message}</div>                
                <ul className="mt-3 list-disc list-inside text-sm text-red-600">
                    {Object.keys(errors.errors).map(function (key, index) {                        
                        return <li key={index}>{errors.errors[key]}</li>;
                    })}
                </ul>
            </div>        
        );
    }

export default ValidationErrors

interfaces/Errors.ts

export default interface Errors {
    message:string | null,
    errors: {
        [key:string]:string[]        
    }
}

This is the json format that backend send when there is an error:

{
“message”:”The given data was invalid.”,
“errors”: {
“email”: [“These credentials do not match our records.”]
} }

I get 2 typescript errors:

{Object.keys(errors.errors).map(function (key, index) {
return {errors.errors[key]}; })}

(parameter) key: string Element implicitly has an ‘any’ type because
index expression is not of type ‘number’.ts(7015)

and here:

<ValidationErrors errors={errors} />

(property) Errors.errors: {
[key: string]: string[]; } Type ‘Errors’ is not assignable to type ‘{ [key: string]: string[]; }’. Index signature for type ‘string’ is
missing in type ‘Errors’.ts(2322) Errors.ts(3, 5): The expected type
comes from property ‘errors’ which is declared here on type
‘IntrinsicAttributes & Errors’

This is the error reducer: store/reducers/errorReducer.ts

import Errors from 'interfaces/Errors'
import {Action, ActionType} from 'store/types'

const initialState: Errors = {
    message: null,
    errors: {
        '':['']
    }   
}

export const errorReducer = (state : Errors = initialState, action: Action): Errors =>{
    switch(action.type){
        case ActionType.SET_ERROR:          
            return {
                message: action.payload.message,
                errors: action.payload.errors
            }                   
        default:
            return state
    }
} 

and this my global reducer: store/reducers/index.ts

import {combineReducers} from 'redux'
...
...
import {errorReducer} from './errorReducer'


const rootReducer = combineReducers({
    .....
    error: errorReducer
})

export type RootState = ReturnType<typeof rootReducer>;
export default rootReducer;

And this is my store: store/store.ts

import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit';
import reducer from './reducers'

export const store = configureStore({
    reducer
});

export type AppDispatch = typeof store.dispatch;
export type RootState = ReturnType<typeof store.getState>;
export type AppThunk<ReturnType = void> = ThunkAction<
  ReturnType,
  RootState,
  unknown,
  Action<string>
>;

Typescript looks really complicated, too many configurations and changes, What I am doing wrong? thanks.