Fetching a local JSON file not working having Promise issues

Hi I am trying to fetch a local JSON file I used localhost for this but the problem I am having is when I fetch it using:

const endpoint = "http://127.0.0.1:5500/appendixA.json"

const fetchedItems = fetch(endpoint)
    .then(res => res.json())
    .then(result => result.appendix_a)
    .catch(e => console.log("error: ", e))

or using async await

const fetchFunc = async () => {
     let response = await fetch(endpoint);
     let jsonResponse = await response.json()
     return jsonResponse.appendix_a;
}

So when I console.log either of them
console.log(fetchedItems)
console.log(fetchFunc())
I am not getting result as a variable array ie [ //results ]
But instead I am getting just a [Promise]

Here is a sample off the JSON file

    {
        "appendix_a": [
            {
                "id": 1,
                "stakeholder": "Commercial Director",
                "user_story": "As a user I need to be able to insert my name into the form"
            },
            {
                "id": 2,
                "stakeholder": "Commercial Director",
                "user_story": "As a user I need to be able to insert my email into the form"
            }
        ]
    }

Why is this happening as I have done res.json() on the initial .then call as well as I have done await res.json() inside the async function

Please clarify for me that.

As I plan to insert the fetch data into a ul element like this which obviously wont work because of the Promise

const ul = document.querySelector('ul');
let li = document.createElement('li');

fetchedItems.map(pa => {
        li.innerHTML = '<span>${pa.id}</span> <p>${pa.stakeholder}></p> <p>${pa.user_story}</p> '
        return ul.appendChild(li);            
});

CURD Operation using Javascript

I am new in this field.

  1. I have some problem when we refersh the webpage the table data is clear. what i want is when we refesh the page the table data is remain same.

  2. When we update the the record in the table it create new field in the localstorage. what i want is when we update field in localstorage it does not create new field only update this field.

  3. When we delete the any field in the table the localstorage data is remain same. what i want is when we delete any field in the table the corresponding field in the localstorage is also delete. Thank You

    Employee Data

    Employee Record

    Employee ID

    Enter Employee ID

    Employee Name

    Enter Employee Name

    Employee Designation

    Enter Employee Designation

    Employee Mobile Number

    Enter Employee Mobile Number

    Employee Salary

    Enter Employee Salary

    Sort By ID

    Employee ID
    Full Name
    Designation
    Mobile
    Salary
    Edit / delete

    * {
    margin: 0;
    padding: 0;
    

    }
    .table-heading {
    text-align: center;
    margin: 1% 0 1% 0;
    }
    .employpage {
    display: flex;
    flex-wrap: wrap;
    width: 76%;
    margin: auto;
    font-size: 16px;
    border: solid 2px #f1f1f1;
    -webkit-border-radius: 5px;
    -moz-border-radius: 5px;
    -ms-border-radius: 5px;
    -o-border-radius: 5px;
    border-radius: 5px;
    }
    .employpage .formdata {
    width: 40%;
    padding: 15px;
    }
    .employpage .display_table {
    padding: 15px;
    width: 52%;
    }
    .employpage .display_table table {
    border: solid 1px #ccc;
    border-collapse: collapse;
    }
    .employpage .display_table td,
    .employpage .display_table th {
    border-left: solid 1px #ccc;
    border-bottom: solid 1px #ccc;
    padding: 10px 5px;
    text-align: left;
    font-size: 13px;
    }
    .employpage .display_table td:first-child,
    .employpage .display_table th:first-child {
    border-left: none;
    }
    .employpage .display_table tr {
    border-bottom: solid 1px #ccc;
    }
    .employpage .display_table tr:last-child td {
    border-bottom: none;
    }
    .formdata form {
    display: flex;
    flex-wrap: wrap;
    background: #f1f1f1;
    padding: 15px;
    }
    .formdata form label{
    display: block;
    text-align: center;
    }
    .formdata form .employee-fields{
    width: 100%;
    margin-bottom: 10px;
    }
    .formdata form input {
    outline: none;
    width: 80%;
    display: block;
    margin: auto ;
    padding: 7px;
    box-sizing: border-box;
    outline: none;
    border: 1px solid #444;
    border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    -ms-border-radius: 4px;
    -o-border-radius: 4px;
    }
    .formdata form .error{
    text-align: center;
    margin-top: 3px;
    font-size: 14px;
    visibility: hidden;
    }
    .formdata th {
    background: #f1f1f1;
    font-size: 14px;
    font-weight: bold;
    text-align: left;
    }
    .formdata .button {
    background: #000;
    padding: 5px 10px;
    font-size: 20px;
    margin: 25px auto;
    display: table;
    color: #fff;
    width: 50%;
    border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    -ms-border-radius: 4px;
    -o-border-radius: 4px;
    }
    .formdata .button:hover {
    cursor: pointer;
    }
    td {
    font-family: “Roboto-Regular”;
    font-size: 11px;
    text-align: center !important;
    }
    .edt {
    color: #0000ff;
    cursor: pointer;
    }
    .dlt {
    color: #ff0000;
    cursor: pointer;
    }
    .sort-table {
    display: block;
    background-color: transparent;
    width: 50%;
    margin: auto;
    padding: 5px 0;
    border: 1px solid #4169e1;
    color: #4169e1;
    border-radius: 4px;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    -ms-border-radius: 4px;
    -o-border-radius: 4px;
    }
    .sort-table:hover {
    background-color: #4169e1;
    color: #fff;
    cursor: pointer;
    }

    var selectedRow = null;
    var btn = document.querySelector(“.button”)
    btn.addEventListener(“click”, employdata);
    function employdata() {
    let empID = document.getElementById(’empID’).value.trim();
    let empName = document.getElementById(’empname’).value.trim();
    let empDes = document.getElementById(’empdes’).value.trim();
    let empMob = document.getElementById(’empmob’).value.trim();
    let empSal = document.getElementById(’empsal’).value.trim();
    if(empID === ”){
    document.getElementById(‘id-error’).style.visibility = “visible”;
    document.getElementById(’empID’).style.border = “2px solid red”;
    return false;
    }
    if(empName === “”){
    document.getElementById(‘name-err’).style.visibility = “visible”;
    document.getElementById(’empname’).style.border = “2px solid red”;
    return false;
    }
    if(empDes === “”){
    document.getElementById(‘des-err’).style.visibility = “visible”;
    document.getElementById(’empdes’).style.border = “2px solid red”;
    return false;
    }
    if(empMob === “”){
    document.getElementById(‘mob-err’).style.visibility = “visible”;
    document.getElementById(’empmob’).style.border = “2px solid red”;
    return false;
    }
    if(empSal === ”){
    document.getElementById(‘sal-err’).style.visibility = “visible”;
    document.getElementById(’empsal’).style.border = “2px solid red”;
    return false;
    }
    else{
    alert(‘Data Added Succesfully’);
    // return true;
    }
    var ax = read_Input_Value();
    if (selectedRow == null) {
    create_Tr_Td(ax);
    remove_input_value()
    }
    else {
    updatefunc(ax);
    remove_input_value();
    selectedRow = null;
    }
    }
    function read_Input_Value() {
    var redemp = {}
    redemp[“empID”] = document.querySelector(‘.empID’).value
    redemp[“ename”] = document.querySelector(“.empname”).value;
    redemp[“des”] = document.querySelector(“.designation”).value;
    redemp[“mob”] = document.querySelector(“.mobile”).value;
    redemp[“salary”] = document.querySelector(“.empsalary”).value;
    let user_records = new Array();
    user_records = JSON.parse(localStorage.getItem(“users”)) ? JSON.parse(localStorage.getItem(“users”)) : []
    user_records.push({
    “EmpID”: redemp[“empID”],
    “Name”: redemp[“ename”],
    “Designation”: redemp[“des”],
    “Mobile”: redemp[“mob”],
    “Salary”: redemp[“salary”]
    })
    localStorage.setItem(“users”, JSON.stringify(user_records));
    return redemp
    }
    function create_Tr_Td(x) {
    var empTable = document.querySelector(“.list”);
    var emp_tr = empTable.insertRow(empTable.length);
    var emp_td1 = emp_tr.insertCell(0);
    var emp_td2 = emp_tr.insertCell(1);
    var emp_td3 = emp_tr.insertCell(2);
    var emp_td4 = emp_tr.insertCell(3);
    var emp_td5 = emp_tr.insertCell(4);
    var emp_td6 = emp_tr.insertCell(5);
    var totalRowCount = document.querySelector(“.list tr”).length;
    emp_td1.innerHTML = x.empID;
    emp_td2.innerHTML = x.ename;
    emp_td3.innerHTML = x.des;
    emp_td4.innerHTML = x.mob;
    emp_td5.innerHTML = x.salary;
    emp_td6.innerHTML = ‘Edit / Delete’;
    }
    function remove_input_value() {
    document.querySelector(‘.empID’).value = ” “;
    document.querySelector(“.empname”).value = ” “;
    document.querySelector(“.designation”).value = ” “;
    document.querySelector(“.mobile”).value = ” “;
    document.querySelector(“.empsalary”).value = ” “;
    document.getElementById(‘id-error’).style.visibility = “hidden”;
    document.getElementById(‘name-err’).style.visibility = “hidden”;
    document.getElementById(‘des-err’).style.visibility = “hidden”;
    document.getElementById(‘mob-err’).style.visibility = “hidden”;
    document.getElementById(‘sal-err’).style.visibility = “hidden”;
    }
    function onEdit(y) {
    selectedRow = y.parentElement.parentElement;
    document.querySelector(‘.empID’).value = selectedRow.cells[0].innerHTML;
    document.querySelector(“.empname”).value = selectedRow.cells[1].innerHTML;
    document.querySelector(“.designation”).value = selectedRow.cells[2].innerHTML;
    document.querySelector(“.mobile”).value = selectedRow.cells[3].innerHTML;
    document.querySelector(“.empsalary”).value = selectedRow.cells[4].innerHTML;
    }
    function updatefunc(redemp) {
    selectedRow.cells[0].innerHTML = redemp.empID;
    selectedRow.cells[1].innerHTML = redemp.ename;
    selectedRow.cells[2].innerHTML = redemp.des;
    selectedRow.cells[3].innerHTML = redemp.mob;
    selectedRow.cells[4].innerHTML = redemp.salary;
    }
    function onDelete() {
    if (confirm(‘Are you sure to delete this record ?’)) {
    var selectdelete = document.querySelector(“a.dlt”);
    selectdelete = selectdelete.parentElement.parentElement.remove(0);
    }
    }
    function sortTable() {
    var table, rows, switching, i, x, y, shouldSwitch;
    table = document.getElementById(“employeeList”);
    switching = true;
    while (switching) {
    switching = false;
    rows = table.rows;
    for (i = 1; i < (rows.length – 1); i++) {
    shouldSwitch = false;
    x = rows[i].getElementsByTagName(“TD”)[0];
    y = rows[i + 1].getElementsByTagName(“TD”)[0];
    if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
    shouldSwitch = true;
    break;
    }
    }
    if (shouldSwitch) {
    rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
    switching = true;
    }
    }
    }

Hi All . Help me get value from the table , Using cucmber test cases . I am getting error .get using AsMap

enter image description here@And(“Click Test Box and Verify”)
public void Click_Test_Box_and_Verify(DataTable ClickTestBoxandVerify ) throws Throwable {
Thread.sleep(3000);
driver.findElement(By.xpath(“//*[@id=”item-0″]/span”)).click();

    // " Test Box and Verify":// Test Field 
    
    Map<String, String> ClickTestBoxandVerifyList = ClickTestBoxandVerify.asMap(String.class, String.class);
    
    
    // "Full Name":// Test Field 
    element = driver.findElement(By.xpath("//*[@id="userName"]"));
    element.clear();
    element.sendKeys(ClickTestBoxandVerify.get);
            
    

}enter image description here

Why browsers send get request instead of post request in my React project that uses Redux?

I have a dispatch in one of my components that calls by form submission:

const handleSubmit = (values) => {
    dispatch(resetPassActionCreator(values.email));
  };

and this is resetPassActionCreator function:

export const resetPassActionCreator = username => dispatch => {
    const url = PASSWORD_RESET_GET_EMAIL;
    dispatch(
        apiCallBegan({
            url,
            method: "POST",
            onStart: passwordResetSlice.actions.resetPassword.type,
            onSuccess: passwordResetSlice.actions.resetPasswordSuccess.type,
            onError: passwordResetSlice.actions.resetPasswordFail.type,
            data: {
                username,
            },
        })
    );
};

and I check the url and it does not have ‘/‘ at the end.
can anyone tell me why the browser sends get request instead of post?

AWS Lambda read-only file system error failed to create directory with Docker image

Problem

Docker image compiles successfully, however fails when ran from Lambda because of its read only file system.

Summary

Luminati-proxy has a docker integration for their proxy manager. I copied over their docker file and appended it to my own docker file for pushing out a script to AWS Lambda. The building of the docker image was successful, but when pushed off to Lambda, it failed because of a read only file system error:

Failed to create directory /home/sbx_user1051/proxy_manager: [code=EROFS] Error: EROFS: read-only file system, mkdir '/home/sbx_user1051'
2022-02-28 19:37:22.049 FILE (8): Failed to create directory /home/sbx_user1051/proxy_manager: [code=EROFS] Error: EROFS: read-only file system, mkdir '/home/sbx_user1051' 

Analysis

Upon examining the trackback, the error is focused on the proxy_manager installation and fails with directory changes (mkdir, mk_work_dir …). These changes are made within the .js files of the GitHub which is pulled from the docker file as the proxy_manager installation. Obviously the only mutable directory on Lambda is the /tmp directory, but is there a workaround for getting this set up without resorting to putting everything under the /tmp directory as it wipes itself upon runtime? Reinstalling a proxy_manager each run is not at all ideal

Answer?

Could this be as simple as setting environment stipulations such as:

ENV PATH=...
ENV LD_LIBRARY_PATH=...

If so, I how should they be configured? I am adding the docker file below for quick reference:

FROM node:14.18.1
RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add - 
    && sh -c 'echo "deb [arch=amd64] http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list' 
    && apt-get update 
    && apt-get install -y google-chrome-stable fonts-ipafont-gothic fonts-wqy-zenhei fonts-thai-tlwg fonts-kacst fonts-freefont-ttf 
      --no-install-recommends 
    && rm -rf /var/lib/apt/lists/*

USER root
RUN npm config set user root
RUN npm install -g [email protected]
RUN npm install -g @luminati-io/luminati-proxy
ENV DOCKER 1
CMD ["luminati", "--help"]

I appreciate the insight!

text string must be rendered within a text component

I’m getting this error I read some ways to fix it , but nothing worked

<View style={styles.container}>
        <StatusBar
          backgroundColor="transparent"
          translucent
          barStyle={theme.dark ? 'light-content' : 'light-content'}
        />
        {open ? (
          <DateTimePicker
            style={{width: '100%', margin: 5}}
            mode="date"
            value={date}
            dateFormat="day month year"
            display="calendar"
            onChange={handleDate}
          />
        ) : (
          <Button
            style={{margin: 5}}
            color="#17E5C2"
            onPress={() => {
              setOpen(true);
            }}>
            Filtrar por data
          </Button>
        )}
        {Object.values(JSON.parse(route.params.paramKey).message).map(item =>
          Object.values(item.createdAt[0]).filter(actualDate =>
            actualDate.includes(dateFilter) ? (
              <Card mode="outlined" key={uuidv4()}>
                <Title>{item?.createdAt[0].value}</Title>
                <Button
                  style={{alignItems: 'flex-start'}}
                  color="#17E5C2"
                  icon={
                    infoVisible
                      ? 'arrow-up-bold-outline'
                      : 'arrow-down-bold-outline'
                  }
                  mode="outlined"
                  onPress={() => {
                    handleInfo();
                  }}>
                  Ver detalhes
                </Button>
                {delete item._id}
                {Object.keys(item).map(data => (
                  <Card.Content
                    key={uuidv4()}
                    style={infoVisible ? {display: 'flex'} : {display: 'none'}}
                    accessible={false}>
                    <Paragraph style={{fontWeight: 'bold'}}>{data}</Paragraph>
                    <Paragraph>{item[data][0]?.value}</Paragraph>
                  </Card.Content>
                ))}
                <Card.Actions>
                  <Button color={'#17E5C2'}>Edit</Button>
                </Card.Actions>
              </Card>
            ) : (
              console.log('NO ACTUAL DATA')
            ),
          ),
        )}
      </View>

The error appear’s when I choose a date that has data.
I tried to put console.log besids react child , and when I put it appears to me the data.
So I tought the error could be in my react childs.

I tried to fix my jsx conditional , but not worked , also tried to remove some commas , but also not worked,
and I tried to use <> </> at the top and the end , but also not worked

I tried the entire day so…. it’s been dificulty , I want some tips about how to fix it.

Vite / Jest / React-Testing

I am tryng to learn testing in React application with Jest; my application uses Vite as a module bundler. The issue is, everytime i run tests i get the following error:

I dont know what i have to do

Terminal error
> [email protected] test
> jest

 FAIL  src/test/App.test.jsx
  ● Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to 
enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript      
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

    Details:

    SyntaxError: C:UsersTomasDesktopreact-testsrctestApp.test.jsx: Support for the experimental syntax 'jsx' isn't currently enabled (8:30):

       6 |
       7 | test("renders content", ()=>{
    >  8 |     const component = render(<App></App>)
         |                              ^
       9 |     console.log(component)
      10 | })

    Add @babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
    If you want to leave it as-is, add @babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.

      at Parser._raise (node_modules/@babel/parser/src/parser/error.js:150:45)
      at Parser.raiseWithData (node_modules/@babel/parser/src/parser/error.js:145:17)
      at Parser.expectOnePlugin (node_modules/@babel/parser/src/parser/util.js:214:18)
      at Parser.parseExprAtom (node_modules/@babel/parser/src/parser/expression.js:1238:16)
      at Parser.parseExprSubscripts (node_modules/@babel/parser/src/parser/expression.js:682:23)
      at Parser.parseUpdate (node_modules/@babel/parser/src/parser/expression.js:662:21)
      at Parser.parseMaybeUnary (node_modules/@babel/parser/src/parser/expression.js:633:23)
      at Parser.parseMaybeUnaryOrPrivate (node_modules/@babel/parser/src/parser/expression.js:388:14)        
      at Parser.parseExprOps (node_modules/@babel/parser/src/parser/expression.js:398:23)
      at Parser.parseMaybeConditional (node_modules/@babel/parser/src/parser/expression.js:356:23)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        1.379 s
Ran all test suites.

Package.json

{
  "name": "react-test",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview",
    "test": "jest"
  },
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2"
  },
  "jest": {
    "verbose": true,
    "testEnvironment": "jsdom",
    "transform": {
      "^.+\.(js|jsx)$": "babel-jest"
    },
    "moduleFileExtensions": [
      "js",
      "jsx"
    ],
    "moduleNameMapper": {
      "\.(gif|ttf|eot|svg|png)$": "<rootDir>/test/__mocks__/fileMock.js",
      "\.(css|less|sass|scss)$": "identity-obj-proxy"
    }
  },
  "devDependencies": {
    "@babel/plugin-syntax-jsx": "^7.16.7",
    "@testing-library/jest-dom": "^5.16.2",
    "@testing-library/react": "^12.1.3",
    "@types/jest": "^27.4.1",
    "@vitejs/plugin-react": "^1.0.7",
    "jest": "^27.5.1",
    "vite": "^2.8.0"
  }
}

App.test.jsx

import React from "react";
import "@testing-library/jest-dom/extend-expect"
import { render } from "@testing-library/react";
import App from "../App.jsx";


test("renders content", ()=>{
    const component = render(<App></App>)
    console.log(component)
})

To complete post:

Software Testing is a method to check whether the actual software product matches expected requirements and to ensure that software product is Defect free. It involves execution of software/system components using manual or automated tools to evaluate one or more properties of interest. The purpose of software testing is to identify errors, gaps or missing requirements in contrast to actual requirements.

Some prefer saying Software testing definition as a White Box and Black Box Testing. In simple terms, Software Testing means the Verification of Application Under Test (AUT). This Software Testing course introduces testing software to the audience and justifies the importance of software testing.

Thanks for helping!

react – not able to setValue for input box

I am making 2 otp input in my application.

In Input.tsx, I am using react-otp-input for the otp functionality
if

    <OtpInput
      value={"abcde"}
      ...
      numInputs={5}
    />

The UI of react-otp-input will be
enter image description here

Now the problem is, when I try to change the value of otp, it throws error

Cannot set properties of undefined (setting 'value')

How can I fix it?

Input.tsx

import React, { useState } from "react";
import OtpInput from "react-otp-input";

type InputPropType = {
  value: string;
  setValue: (event: string) => void;
};

function Input(props: InputPropType): JSX.Element {
  const { value, setValue } = props;
  return (
    <OtpInput
      value={value}
      onChange={(e: string) => {
        setValue(e);
      }}
      numInputs={5}
    />
  );
}

export default Input;

App.tsx

import React, { useState } from "react";

import Input from "./Input";

export default function App() {
  type InputValueType = {
    id: number;
    value: string;
  };
  const [inputValues, setInputValues] = useState<Array<InputValueType>>([
    { id: 0, value: "" },
    { id: 1, value: "" }
  ]);

  const InputGroup = () => {
    let numOfInputs: number = 2;
    var rows: Array<any> = [];
    for (var i = 0; i < numOfInputs; i++) {
      let inputValue: InputValueType = inputValues[i];
      rows.push(
        <Input
          key={inputValue.id}
          value={inputValue.value}
          setValue={(event: string) => {
            let inputValuesTemp = inputValues;
            inputValuesTemp[i]["value"] = event;
            setInputValues(inputValuesTemp);
          }}
        />
      );
    }
    return <>{rows}</>;
  };

  return (
    <div className="App">
      <InputGroup />
    </div>
  );
}

Codesandbox
https://codesandbox.io/s/react-typescript-forked-s38ck9?file=/src/App.tsx:0-918

Regular expression not giving me expected result

I am wanting to sort an array using regular expression such that after the array is sorted, all the dishes are included in results including both matched and unmatched ones. Currently only few matched ones are in the sorted array. If I have two words to be search in regular expression then it should search all the two words independently and finally get the matched items as well as unmatched items. If i search for ‘Fish CUrry’ then it should look for both words independently and get the results and also add all the unmatched results at the end of sorted array. Here unmatched is ‘Biryani’ and all other are matched.

let allDishes =     [
        {
            "DishId": 66,
            "DishName": "Fish CUrry",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 65,
            "DishName": "Fish CUrry Masala",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 64,
            "DishName": "Chilli Fish CUrry Masala",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 63,
            "DishName": "Mutton CUrry",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 62,
            "DishName": "Biryani",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        }
    ]

Below is the code that I have written:

let value = 'Fish CUrry';
let regex = new RegExp(`^${value}`, `i`);
const sortedArr = allDishes 
                 .filter(x=>regex.test(x.DishName))
                 .sort((a, b) =>a.DishName.localeCompare(b.DishName));

Current result from above code is below:

[
    {
        "DishId": 66,
        "DishName": "Fish CUrry",
        "DateCreated": "2021-10-21T11:19:28.000Z",
    },
    {
        "DishId": 65,
        "DishName": "Fish CUrry Masala",
        "DateCreated": "2021-10-21T11:19:28.000Z",
    }
]

Expected sorted result needed should look like below:

[
        {
            "DishId": 66,
            "DishName": "Fish CUrry",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 65,
            "DishName": "Fish CUrry Masala",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 64,
            "DishName": "Chilli Fish CUrry Masala",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 63,
            "DishName": "Mutton CUrry",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        },
        {
            "DishId": 62,
            "DishName": "Biryani",
            "DateCreated": "2021-10-21T11:19:28.000Z",
        }
    ]

Unity WebGL Build Particle System Error On Safari

So I have a small web game that I made recently, and decided to try it out in Safari. Every other browser works (Chrome, Firefox, Edge), but a few seconds (seemingly random) after an on screen particle system starts playing, the whole game crashes. Obviously disabling particles isn’t an option. Any ideas?

An error occurred running the Unity content on this page. See your browser JavaScript console for more info. The error was:
RuntimeError: Out of bounds memory access (evaluating 'asm[name].apply(null, arguments)')
<?>.wasm-function[OptimizedPolynomialCurve::Evaluate(math::_float4 const&) const]@[wasm code]
<?>.wasm-function[Evaluate(MinMaxCurve const&, math::_float4 const&, math::_float4 const&)]@[wasm code]
<?>.wasm-function[ParticleSystem::UpdateModulesPreSimulationIncremental(ParticleSystemUpdateData const&, ParticleSystemParticles&, unsigned long, unsigned long, math::_float4 const&, bool)]@[wasm code]
<?>.wasm-function[ParticleSystem::Update1b(ParticleSystemUpdateData&, int)]@[wasm code]
<?>.wasm-function[ParticleSystem::UpdateFunction(ParticleSystemUpdateData*)]@[wasm code]
<?>.wasm-function[ParticleSystem::BeginUpdateAll()]@[wasm code]
<?>.wasm-function[ParticleSystem::InitializeClass()::PreLateUpdateParticleSystemBeginUpdateAllRegistrator::Forward()]@[wasm code]
<?>.wasm-function[ExecutePlayerLoop(NativePlayerLoopSystem*)]@[wasm code]
<?>.wasm-function[ExecutePlayerLoop(NativePlayerLoopSystem*)]@[wasm code]
<?>.wasm-function[MainLoop()]@[wasm code]
<?>.wasm-function[dynCall_v]@[wasm code]
wasm-stub@[wasm code]
81288@[native code]
@http://localhost:55812/Build/dev.framework.js:1043:25
browserIterationFunc@http://localhost:55812/Build/dev.framework.js:8963:17
callUserCallback@http://localhost:55812/Build/dev.framework.js:7153:7
runIter@http://localhost:55812/Build/dev.framework.js:7214:20
Browser_mainLoop_runner@http://localhost:55812/Build/dev.framework.js:7128:27

Wicket Adding a draggable DialogBox with user defined tetarea, textbox and button

I am pretty new to Apache Wicket. I was able to get a home page, a form accepting inputs and then final success page where all accepted inputs are displayed. When this success page loads, there is a button. I would like to show a draggable dialog box with a textbox or a text area with when the button is clicked. I was trying to execute the JQuery extensions for wicket. But not able to get it on to my success page. It always complains for wicket id or component not exist and errors related based on what has been written on the java code or added to the markup html file. Here is the code to call the draggable dialogbox i created..Yes I wrote the wicket:extend for subclass. Still very confusing to me..please help.

This code is inside the AjaxButton Click...
HomePanel homepanel = new HomePanel("homepanel");
homepanel.setOutputMarkupId(true);
homepanel.setOutputMarkupPlaceholderTag(true); //tried removing it
homepanel.getMarkupId(true);  //just for trial i put here
homepanel.setVisible(true); 
add(homepanel);
homepanel.setVisible(true);
target.add(homepanel); 

Using apache wicket version 8.x
What am I do do. I am tapped out and no other way as my search also returns same thing .. any help.. thanks for the same.

console.log script returns “Wrong channel!”

I’m setting up a Discord bot, and I want it to send a message to the main channel of my server when I type node .. I typed:

client.on('ready', () => {
  const Channel = client.channels.cache.get('<My.General.Channel.ID#>');
  if (!Channel) return console.log('Wrong channel!');
  else Channel.send('I am here');
});

I get “Wrong channel!”. I should just insert the channel ID number, right? I’ve directly pasted from Discord’s “Copy ID” and still get a problem.

node.js puppeteer “document is not defined”

I am attempting to try click a button using code without an id or class, but my terminal always responds with:

document.getElementsByTagName("Accept Cookies");
    ^

ReferenceError: document is not defined

This is my code:

const puppeteer = require('puppeteer');

const product_url = "https://www.nike.com/launch"

async function givePage() {
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    return page;
}

async function acceptCookies(page) {
    await page.goto(product_url);
    const btn = await page.waitForSelector('#cookie-settings-layout > div > div > div > 
div:nth-child(3) > div.ncss-col-md-6.ncss-col-sm-12.mb5-sm > button')
    await btn.click()
}

async function notifyMe(page) {
    await page.goto(product_url);
    document.querySelector("button[type="submit"]").click("Notify Me");
}

async function checkout() {
    var page = await givePage();
    await acceptCookies(page);
    await notifyMe(page);
}

checkout();

What did I do wrong and how can I fix this?

Firebase createUserProfileDocument() is returning undefined

As the title says, the createUserProfileDocument() method from firebase is returning undefined for some reason, therefore, it’s throwing an error on my broswer’s console.

The error that is being thrown is: App.js:23 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'onSnapshot') at App.js:23:1

Please find the code below:

import './App.css';
import { connect } from 'react-redux';
import { Switch, Route } from 'react-router-dom';
import HomePage from './pages/homepage/homepage.component';
import ShopPage from './pages/shop/shop.component';
import Header from './components/header/header.componet';

import { auth, createUserProfileDocument } from './firebase/firebase.utils';
import SignInAndSignUpPage from './pages/sign-in-and-sign-up/sign-in-and-sign-up.component';
import { setCurrentUser } from './redux/user/user.actions';

class App extends React.Component {
    unsubscribeFromAuth = null;

    componentDidMount() {
        const { setCurrentUser } = this.props;

        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
                console.log(userRef);
                userRef.onSnapshot((snapshot) => {
                    setCurrentUser({
                        id: snapshot.id,
                        ...snapshot.data(),
                    });
                });
            }
            setCurrentUser(userAuth);
        });
    }

    componentWillUnmount() {
        this.unsubscribeFromAuth();
    }

    render() {
        return (
            <div className='App'>
                <Header />
                <Switch>
                    <Route exact path='/' component={HomePage} />
                    <Route exact path='/shop' component={ShopPage} />
                    <Route
                        exact
                        path='/signin'
                        component={SignInAndSignUpPage}
                    />
                </Switch>
            </div>
        );
    }
}

const mapDispatchToProps = (dispatch) => ({
    setCurrentUser: (user) => dispatch(setCurrentUser(user)),
});

export default connect(null, mapDispatchToProps)(App);

The portion of code related to my error is the following:

componentDidMount() {
        const { setCurrentUser } = this.props;

        this.unsubscribeFromAuth = auth.onAuthStateChanged(async (userAuth) => {
            if (userAuth) {
                const userRef = await createUserProfileDocument(userAuth);
                console.log(userRef);
                userRef.onSnapshot((snapshot) => {  // This is Line 23......
                    setCurrentUser({
                        id: snapshot.id,
                        ...snapshot.data(),
                    });
                });
            }
            setCurrentUser(userAuth);
        });
    }

I console.logged(userRef) as you can see, and it returns undefined. This is my first experience with firebase so I am not sure where the error is.

I googled and found an answer here in stackoverflow which is alike to my issue: TypeError: Cannot read properties of undefined (reading ‘onSnapshot’)

However, that problem is specifically related to how the developer was passing the method as an array and not a method, which does not help my situation.

Please don’t downvote my question in case of finding it wrong, please suggest edits instead, since I am kind of new to stackoverflow and a complete noob to firebase.

Thanks a lot in advance for your help!