How can I call unscoped functions in eval without using “this”

This works:

import isValidDocument from './isValidDocument'

class Test {
  constructor() {
    Object.assign(this, { isValidDocument})
  }

  execute(person) {
    const evalResult = eval('this.isValidDocument(person)')
    console.log("Eval Result:", evalResult)
  }
}

but this doesn’t:

// ...
execute(person) {
  const evalResult = eval('isValidDocument(person)')
  console.log("Eval Result:", evalResult)
}
// ...

Basically, i want to be able to call the functions without using the this keyword.

How can I achieve that?


If you want context

I have rules (js expressions) stored in a database and i need it to execute them dinamically, the functions are fixed but the expressions can change.

Expression example: isValidDocument(person) && person.age > 18

The user will be able to change the expressions.

Yeah, i know about the security issue and i also accept suggestions to isolate the env. Currently, the expressions are made using blocks on the frontend and then the backend converts them to actual javascript statements, but the plan is to allow the user to create his own expressions directly.

how can i show image from json file to html

Hi i want to take the image from the json file and put it into my html table. right now it gives me the error: GET c:fakepathFULLSCALE.jpeg net::ERR_UNKNOWN_URL_SCHEME. i want to show the image beside the pris. look at the image attached to see how it looks nowhtml page
Please help me, it’s an exam project

this is my code:

varer.js

document.addEventListener("DOMContentLoaded", (event) => {
  document.getElementById("form").addEventListener("submit", (event) => {
    event.preventDefault();

    const varer = document.getElementById("varer").value;
    const pris = document.getElementById("pris").value;
    const billede = document.getElementById("billede").value

    const opretVare = {
      varer: varer,
      pris: pris,
      billede: billede
    };

    fetch("http://localhost:8200/varer/createvarer", {
        method: "POST",
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(opretVare),
      })
      //converter det til Json
      .then((response) => response.json())
      .catch(() => {
        window.alert("Der skete en fejl");
      });
  });
});


async function getGoods() {
  const response = await fetch("http://localhost:8200/varer/getproducts")
  const result = await response.json()
  return result
}

async function deleteGoods(id) {
  const response = await fetch("http://localhost:8200/varer/delete" + id, { 
    method: 'DELETE'
  })
  const result = await response.json()
  return result
}

function renderTable(goods) {
    const table = document.getElementById('varerTable');
    let tableHtml = `
      <tr>
        <th>Varekategori</th>
        <th>Pris</th>
        <th>Billede</th>
      </tr>`;
    for (const row of goods){
      tableHtml += `
        <tr>
          <td>${row.varer}</td>
          <td>${row.pris}</td>
          <td><img src="${row.billede}" style="height:100px;width000px;"</td>
          <td><button onclick = "handleDelete"(${row.id})"> Delete </button></td>
          <td><button onclick ="toDo"> Edit </button></td>
        </tr>
      `;
    }
    table.innerHTML = tableHtml;
}

async function handleDelete(id) {
  try {
    await deleteGoods(id)
    const goods = await getGoods()
    renderTable(goods)
  } catch(err) {
    console.error(err)
  }  
}

async function handleLoad() {
  try {
    const goods = await getGoods()
    renderTable(goods)
  } catch(err) {
    console.error(err)
  }  
} 
document.getElementById("clickMe").addEventListener('click', handleLoad);


//vis alle varene på siden
  router.get("/getproducts", (req, res) =>{
    res.status(200).json(products)
    console.log(products)
   })

varer.json

[{"varer":"mælk","pris":"10","billede":"C:\fakepath\FULLSCALE.jpeg"}]

“FindMany” is picked up as undefined in prisma query

I want to do a query on this table called SRCMembers using the following code

const members = await db.sRCMembers.findMany()

i’m importing Prisma through the db file as such

import db from "db"

and this exact syntax is working on auto generated models such as ‘user’

const members = await db.user.findMany()

but when I run that code I get and error that says

‘TypeError: Cannot read properties of undefined (reading ‘findMany’)’

the following is the schema.prisma model

model SRCMembers {
  id            Int     @id @default(autoincrement())
  studentNumber String
  name          String
  surname       String
  age           String
  branch        String  @default("1st year")
  email         String
  course        String?
  year          String?

}

the code editor picks up the ‘findMany’ and even gives hints on it.
but when executed it is then undefined.

when I log SRCMembers I get this

{
  findUnique: [Function (anonymous)],
  findFirst: [Function (anonymous)],
  findMany: [Function (anonymous)],
  create: [Function (anonymous)],
  createMany: [Function (anonymous)],
  delete: [Function (anonymous)],
  update: [Function (anonymous)],
  deleteMany: [Function (anonymous)],
  updateMany: [Function (anonymous)],
  upsert: [Function (anonymous)],
  count: [Function (anonymous)],
  aggregate: [Function (anonymous)],
  groupBy: [Function (anonymous)]
}

along with prisma as the ORM I am making use of BlitzJS

why is the findMany undefined and what can I do about it?

Why does defining URL separately cause this seemingly unrelated error?

Webpack v5 has built-in support for web workers, initialized in the following format:

const worker = new Worker(new URL("./worker.js", import.meta.url));

While working on a Next.js (with webpack v5) project, I noticed that a slight variation of the above breaks down:

const url = new URL("./worker.js", import.meta.url);
const worker = new Worker(url);

This leads to the following error on the browser console:

SyntaxError: import declarations may only appear at top level of a module

which occurs because (and only when) I’m importing something in the worker file.

Here’s a minimal reproduction of the above. Instructions to run and the lines to look at are in the README.

Why does this happen? How does defining the worker URL in a separate variable change things?

router.push with query parameters leads to localhost:8080/?categoryId=2. Why is there a slash before the query parameter?

I am using the router like this:

router.push({ name: 'home', query: { categoryId: category.id } })

And my route looks like this:

{
    path: '/',
    name: 'Home',
    component: Home
},

Is it normal for the URL to have a slash before the query parameter? Even if it doesn’t matter functionality wise, I feel like localhost:8080?categoryId=2 looks better than localhost:8080/?categoryId=2 and was wondering if I could somehow remove the slash?

Tampermonkey run script every 10s

I’m trying to build a script that runs every 10seconds and sends a GM_notification. But I dont receive any notification. What’s wrong?

// ==UserScript==
// @name        _Notification test
// @grant       GM_notification
// @require     http://code.jquery.com/jquery-1.12.4.min.js
// ==/UserScript==

setTimeout(function() {

GM_notification ( {title: 'foo', text: '42'} );

}, 1000);

reorganizing data columns Snowflake using stored procedure

Using stored procdeure in Snowflake I am trying to change the columns order for a part of the data table.

Here is my table

column1 column2 column3 column4    column5
---------------------------------------------
Year   Country  Name    City
2020    US      Briand   NY
2021    US      John     LA
2021    UK      Mark     London

City   Name    Year      Country      Age
Paris  Jacques  2017      FR          55
Madrid Juan     2015      ES          25
Dublin Steven   2018      IE          37

So there is 5 differents structures in the same table.
All 5 structures doesn’t have the same number of columns but the column name can be match and missing column can be fill with null values. Moreover there is a blank row between each different data structure.
The output should be :

Year      Country     City     Name          Age
-------------------------------------------------
2020        US        NY        Briand       Null
2021        US        LA        John         Null
2021        UK        London    Mark         Null
2017        FR        Paris     Jacques      55
2015        ES        Madrid    Juan         25
2018        IE        Dublin    Steven       37

So I thought that the only way is to do a stored procedure but I have no idea how it works and if it is possible to resolve my problem this way.

CREATE OR REPLACE PROCEDURE proc_columns_matching()
returns string
language javascript
as
$$
var sql = "select * from countries_pp";
var statement1 = snowflake.createStatement( {sqlText: pp} );
var result_set1 = statement1.execute();

while(result_set1.next() != ''){
var column1= result_set1.getColumnValue(1)
}

return column1;
$$
;

CALL proc_smart_impulse();

So I tried to identify the blank cell to split the table but I am stuck here.

why does useReducer run twice?

i have a problem.
im creating a shop cart using react js.
i have a component called Header and a component for contextProvider. in contextProvider i have a useReducer.
my problem is with these two components. when i click on a product, it normally add just one product to cart. it is ok and i want this. but the problem is here that when i click on cart icon, a modal card will be on screen and if i close that modal card them add a product to cart, the product will be added to cart two times!! i know what line of code cause this error but i dont know why it happens! the problem is with the state in Header component. if i remove and add that in context component, it will work normally. but why?? if you need anything else with my codes, tell me. here is my codes:
my context:

        import React, { useReducer, useState } from "react";

const Context = React.createContext({
  allAddedToCart: 0,
  productsList: [],
  addToCart: () => {},
  initializeProductList: (product) => {},
/*   open: false,
  setOpen: (open) => {}, */
});

export const ContextProvider = (props) => {
/* const [open, setOpen] = useState(false); */
  const [productsState, dispatchProducts] = useReducer(
    (prevState, action) => {
      if (action.type === "add_to_cart") {
        prevState.products_list.forEach((element, index) => {
          console.log(index);
          if (element.id === action.id) {
            element.number++;
            element.allPrice += element.price;
            console.log("finished");
          }
        });
        return {
          allAddedToCart: prevState.allAddedToCart + 1,
          products_list: prevState.products_list,
        };
      } else if (action.type === "initialize_list") {
        return {
          allAddedToCart: prevState.allAddedToCart,
          products_list: [...prevState.products_list, action.product],
        };
      }
    },
    {
      allAddedToCart: 0,
      products_list: [],
    }
  );
  return (
    <Context.Provider
      value={{
        allAddedToCart: productsState.allAddedToCart,
        productsList: productsState.products_list,
        addToCart: (id) => {
          console.log("add me to the cart");
          dispatchProducts({ type: "add_to_cart", id: id });
        },
        initializeProductList: (product) => {
          dispatchProducts({ type: "initialize_list", product: product });
        },
/*         open: open,
        setOpen: (open) => {
          setOpen(open);
        } */
      }}
    >
      {props.children}
    </Context.Provider>
  );
};

export default Context;

my Header component:

import { useContext, useState } from "react";
import ReactDOM from "react-dom";
import Context from "../context/context";
import styles from "../styles/Header.module.css";
import CartModal from "./CartModal";

const Header = (props) => {
    const ctx = useContext(Context)
    const [open, setOpen] = useState(false);

  return (
    <header className={styles.header}>
      {open ? ReactDOM.createPortal(<CartModal close={() => {setOpen(false)}} />, document.getElementById("modal_place")) : ""}
      <h1 className={styles.title}>a react shopping cart project</h1>
      <a href="/" onClick={(e) => {e.preventDefault(); setOpen(true)}}>
        <i className={`fas fa-shopping-cart ${styles.cart}`}></i>
        <span className={styles.added_products_number}>{ctx.allAddedToCart}</span>
      </a>
    </header>
  );
};

export default Header;

thanks for helping 🙂

How to change dynamically path color in Cesium Viewer

I want to dynamically change the color of my gps path that I put in a czml file depending on the speed of my path. 0% speed = blue, 100%= red.My path which is fixed in blue

Here is my code which displays the viewer :

var viewer = new Cesium.Viewer("cesiumContainer", { terrainProvider: Cesium.createWorldTerrain(), baseLayerPicker: false, shouldAnimate: true, });
viewer.dataSources.add(Cesium.CzmlDataSource.load(tabToCzml)).then(function (ds) {
            viewer.trackedEntity = ds.entities.getById("path");
        });

Currently the color of the path is defined in the czml file as :

"path": { "material": { "polylineOutline": { "color": { "rgba": [255, 255, 255, 200] }, "outlineColor": { "rgba": [0, 173, 253, 200] }, "outlineWidth": 5 } }, "width": 6, "leadTime": 0, "trailTime": 100000, "resolution": 5 } }

Get location redirect url from jquery ajax statuscode 401

I currently have the below code and need to get the location parameter to redirect to. How do I grab it with the statusCode setup?

Ajax Call

$.ajax({
                url: url,
                data: (def.data ? (def.convertToJson ? JSON.stringify(def.data) : def.data) : ''),
                type: def.type,
                dataType: def.dataType,
                cache: def.cache,
                contentType: def.contentType,
                statusCode: {
 401: function (response) {
                        debugger
                        window.location = GET LOCATION URL FROM RESPONSE
                    }}

Response Parameter

response.getAllResponseHeaders()

‘access-control-allow-headers: Origin, X-Requested-With, Content-Type,
Acceptrnaccess-control-allow-origin: *rncache-control:
privaterncontent-length: 58rncontent-type: text/htmlrndate: Mon,
06 Dec 2021 16:51:23 GMTrnlocation:
https://localhost:44360/store?storeorganizationid=24917#/login?returnurl=https%3a%2f%2flocalhost%3a44360%2fstore%2faccount%3fstoreorganizationid%3d24917%26_%3d1638809474810rnserver:
Microsoft-IIS/10.0rnx-aspnet-version:
4.0.30319rnx-aspnetmvc-version: 5.2rnx-exposure-server: EastUS2rnx-exposure-sport: Basketballrnx-powered-by:
ASP.NETrnx-sourcefiles:
=?UTF-8?B?RjpcTXkgV2Vic1xCYXNrZXRiYWxsVG91cm5hbWVudHNcTmV3UmVnaXN0cmF0aW9uXFdlYnNpdGVzXFRvdXJuYW1lbnRzXHN0b3JlXGFjY291bnQ=?=rnx-ua-compatible:
IE=Edge,chrome=1rn’

How to show options from flexdatalist plugin

I’m new to using the flexdatalist javascript plugin.
What I am trying to do is to display the content of the datalist when a value is set by default on the input like viewing all options as soon as entering the page.
By typing characters in the input, the change event is correctly triggered but when i set a default value on the input, even if the datalist has options it doesn’t show anything.

This is the flexdalist initialization:

$('#search').flexdatalist({
    "noResultsText": 'No result for "{keyword}"'
});

Is there a way to show the datalist using javascript or jquery?

Importing and using vanila JS functions in React component

I am very new to react.js and JavaScript, so apologies in advance. I’m trying to integrate https://diagrams.net into other webpage using the file that’s directly given by diagrams.net here:

https://github.com/jgraph/drawio-integration/blob/master/diagram-editor.js?fbclid=IwAR1FMViVLW3Tba8RqMOUJtv16vIvPPycLYyu4rEtRTbuhbyztlrLXu5UyHo.

So as it can be seen in this example here: http://jgraph.github.io/drawio-integration/javascript.html, when the user double clicks on the diagram, they should be redirected to diagrams.net web and draw their own diagram.

The problem is that my web is currently built on React, and all the diagrams.net is built on vanilla JS. By inspecting the example above, they apparently use:

<img 
style="cursor:pointer;" 
title="Click to edit image" 
onclick="DiagramEditor.editElement(this);" 
src="data:image/png;base64,iVBORw0...

in the HTML to display the image of the diagram. I’ve tried to change it to react-like by changing it to:

<img alt="Click to edit image" 
onClick={EditDiagram.DiagramEditor.editElement(this)}
src="data:image/png;base64,iVBORw0..."/>

and importing the JavaScript file by import * as EditDiagram from "../components/workarea/workarea-diagram-editor";, but it is returning TypeError: Cannot read properties of undefined (reading 'editElement').

I’ve also tried using dangerouslySetInnerHTML like this:

<div
dangerouslySetInnerHTML={{
__html:
"<img style='cursor:pointer;' 
title='Click to edit image' onclick='DiagramEditor.editElement(this);' 
src='data:image/png;base64,iVBORw0...'/>",
}}/>

but this way, that DiagramEditor.editElement(this) cannot be accessed that way.

I’ve been trying to get this to work for past 12 hours, but just can’t get it to work. Is there any way to make this work?

Thank you so much.

Below is the React code that the JavaScript is being added on.

const WorkArea = () => {
  const router = useRouter();
  const formik = useFormik({
    initialValues: {
      scenario: "This is scenario",
    },
    validationSchema: Yup.object({
      scenario: Yup.string().max(255).required("Scenario is required"),
    }),
    onSubmit: () => {
      router.push("/");
    },
  });

  const [countList, setCountList] = useState([0]);
  //   const [inputList, setInputList] = useState([]);

  const AddScenario = () => {
    let countArr = [...countList];
    let counter = countArr.slice(-1)[0];
    counter++;
    countArr.push(counter);
    setCountList(countArr);
  };

  const DeleteScenario = () => {
    let countArr = [...countList];
    let counter = countArr.slice(-1)[0];
    counter--;
    countArr.pop(counter);
    setCountList(countArr);
  };

  //   const onAddBtnClick = (event) => {
  //     setInputList(inputList.concat(<SetScenario key={inputList.length} />));
  //   };

  return (
    <>
      <Head>
        <title>Work Area | Cybersecurity Requirements Generator</title>
      </Head>
      <Box
        component="main"
        sx={{
          alignItems: "center",
          display: "flex",
          flexGrow: 1,
          minHeight: "100%",
        }}
      >
        <Container maxWidth="xl">
          <NextLink href="/projects" passHref>
            <Button component="a" startIcon={<ArrowBackIcon fontSize="small" />}>
              Back to Projects
            </Button>
          </NextLink>
          <form onSubmit={formik.handleSubmit}>
            <Box sx={{ my: 3 }}>
              <Typography color="textPrimary" variant="h4">
                Use Case Diagram
              </Typography>
              <Typography color="textSecondary" gutterBottom variant="body2">
                Make your own diagram!
              </Typography>
            </Box>

            <Box
              sx={{
                py: 2,
              }}
            >
              {/* <div
                dangerouslySetInnerHTML={{
                  __html:
                    "<img style='cursor:pointer;' title='Click to edit image' onclick='DiagramEditor.editElement(this);' src='data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAA9CAYAAACJM8YzAAADT3RFWHRteGZpbGUAJTNDbXhmaWxlJTIwaG9zdCUzRCUyMmVtYmVkLmRpYWdyYW1zLm5ldCUyMiUyMG1vZGlmaWVkJTNEJTIyMjAyMS0wMS0xMVQxMCUzQTQxJTNBMzQuMjQ4WiUyMiUyMGFnZW50JTNEJTIyNS4wJTIwKE1hY2ludG9zaCUzQiUyMEludGVsJTIwTWFjJTIwT1MlMjBYJTIwMTFfMV8wKSUyMEFwcGxlV2ViS2l0JTJGNTM3LjM2JTIwKEtIVE1MJTJDJTIwbGlrZSUyMEdlY2tvKSUyMENocm9tZSUyRjg3LjAuNDI4MC44OCUyMFNhZmFyaSUyRjUzNy4zNiUyMiUyMGV0YWclM0QlMjJtNXI1QVhFdDE3eWx2WWlEWXo5UyUyMiUyMHZlcnNpb24lM0QlMjIxNC4xLjklMjIlMjB0eXBlJTNEJTIyZW1iZWQlMjIlM0UlM0NkaWFncmFtJTIwaWQlM0QlMjJlbVlSU0REUmtEUDJZZDNFWnkzciUyMiUyMG5hbWUlM0QlMjJQYWdlLTElMjIlM0VqWkxOVG9Rd0VJQ2ZwbGV6MEloNkZkZjE0Z2tUejVXT3ROblNrbElXOE9sdDdWUm9OaVplWU9hYjZmd1RXdmZMeWJKQnZCb09pcFFIdmhENlJNcXlxS283JTJGd3RramVTV1BrVFFXY2tqT215Z2tWJTJCQUx4T2RKSWNSV1VUT0dPWGtrTVBXYUEydHl4aXoxc3k1MjZkUmVkYUJkWkI1Qk5DMFRGM1RkOG1kaVBTJTJCckRiJTJCQXJJVEtYTlJZWDhmckQxMzFrd2E4Mm1qSVZwNmxzSmdEYU5nM013N1JJJTJ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FqejWtP/w8LAAUFxcLOal7fjp06fiXpRtdXUVeXl5yM3NRWtrKywtLWFhYYHo6GiEhITg8ePHWFpaQm9vLzIzM8WiffjwIV6+fImkpCT8/PlTzKkc7+bmpimrY/c/dZBXVlZgaGgojLx586YwTgktLS0N1tbWKCgoQGRkpDBubW0Nly5dOhSyuv3HxsZE+jw9PfHt2zcBmdJM193f9m+3BCsrKwtTU1NQKBQizXSczMzMIDU1Fe/evUNZWRkcHR3x9u1bENTOzs4TbffHpXyqINN2rTy337x5gytXrohXPJSQy8vLhbG0RVIjEJR4BweHQyGr25+KPToK6JgwMjISc9Eu8TvIlGA6Kn5ttCucPXsW4eHhAq6trS1iY2Nx9+7dE5/pOgF5f3V9GGQCSom7cOEC+vr6BAT6uaqq6lDI6vYnCJQ8OkNppwgLCxMJ/B3k5ORkvHr1Cj09PeLam5ubGBkZgYeHBz5+/IiLFy/ix48faGhoQExMjCgsx8fHOcn/BpkqW29vbwwNDYmEEAQqwJqamg6FrG7/gIAAAYWOgcHBQXENGpuSkqIyb3Nzs6gX6HGwq6tLFFuvX78WYKlQe/LkifiOzmhnZ2fQQlheXhbFGM07PT29N54mpp3gxo0bQsufbKdqu/4dZHrGpOdkSlldXZ2ovmlbfP78Oby8vA5A1qR/W1ubAEONCjt6vCMAtJhcXFz25iZIrq6u4rp0BtOWTsUgNbqf6upqXL16VRSL9Knc+umeS0pKBGTleJrbwMAALS0tuH79+p9k/P98q5EAbmxsHDiLj3JKnf70HE4QbGxsRCG1sLAAU1NTlccomp8esajYUwKkflRH2Nvb48yZM3u3QAUj/QHHzs5OFJLK9uv4P0r378n/kyRrQxhf4x8HGLIEq4EhM2QJHJBAIieZIUvggAQSOckMWQIHJJDISWbIEjgggUROMkOWwAEJJHKSGbIEDkggkZPMkCVwQAKJnGSGLIEDEkjkJDNkCRyQQCInmSFL4IAEEjnJDFkCBySQqJJkCfRKK1GhUOz+BbaftLWDFNYjAAAAAElFTkSuQmCC'/>",
                }}
              /> */}

              <img
                alt="Click to edit image"
                onClick={EditDiagram.DiagramEditor.editElement(this)}
                src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHkAAAA9CAYAAACJM8YzAAADT3RFWHRteGZpbGUAJTNDbXhmaWxlJTIwaG9zdCUzRCUyMmVtYmVkLmRpYWdyYW1zLm5ldCUyMiUyMG1vZGlmaWVkJTNEJTIyMjAyMS0wMS0xMVQxMCUzQTQxJTNBMzQuMjQ4WiUyMiUyMGFnZW50JTNEJTIyNS4wJTIwKE1hY2ludG9zaCUzQiUyMEludGVsJTIwTWFjJTIwT1MlMjBYJTIwMTFfMV8wKSUyMEFwcGxlV2ViS2l0JTJGNTM3LjM2JTIwKEtIVE1MJTJDJTIwbGlrZSUyMEdlY2tvKSUyMENocm9tZSUyRjg3LjAuNDI4MC44OCUyMFNhZmFyaSUyRjUzNy4zNiUyMiUyMGV0YWclM0QlMjJtNXI1QVhFdDE3eWx2WWlEWXo5UyUyMiUyMHZlcnNpb24lM0QlMjIxNC4xLjklMjIlMjB0eXBlJTNEJTIyZW1iZWQlMjIlM0UlM0NkaWFncmFtJTIwaWQlM0QlMjJlbVlSU0REUmtEUDJZZDNFWnkzciUyMiUyMG5hbWUlM0QlMjJQYWdlLTElMjIlM0VqWkxOVG9Rd0VJQ2ZwbGV6MEloNkZkZjE0Z2tUejVXT3ROblNrbElXOE9sdDdWUm9OaVplWU9hYjZmd1RXdmZMeWJKQnZCb09pcFFIdmhENlJNcXlxS283JTJGd3RramVTV1BrVFFXY2tqT215Z2tWJTJCQUx4T2RKSWNSV1VUT0dPWGtrTVBXYUEydHl4aXoxc3k1MjZkUmVkYUJkWkI1Qk5DMFRGM1RkOG1kaVBTJTJCckRiJTJCQXJJVEtYTlJZWDhmckQxMzFrd2E4Mm1qSVZwNmxzSmdEYU5nM013N1JJJTJCRTF0WVlGNlYlMkJxVUdGc2VZVGUlMkY3RGlpV1BiazFOcEZvdGFQZXZDS21KQzFNVHhuZ1RjZ3d1NGNQQ0ZtQjB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+fImkpCT8/PlTzKkc7+bmpimrY/c/dZBXVlZgaGgojLx586YwTgktLS0N1tbWKCgoQGRkpDBubW0Nly5dOhSyuv3HxsZE+jw9PfHt2zcBmdJM193f9m+3BCsrKwtTU1NQKBQizXSczMzMIDU1Fe/evUNZWRkcHR3x9u1bENTOzs4TbffHpXyqINN2rTy337x5gytXrohXPJSQy8vLhbG0RVIjEJR4BweHQyGr25+KPToK6JgwMjISc9Eu8TvIlGA6Kn5ttCucPXsW4eHhAq6trS1iY2Nx9+7dE5/pOgF5f3V9GGQCSom7cOEC+vr6BAT6uaqq6lDI6vYnCJQ8OkNppwgLCxMJ/B3k5ORkvHr1Cj09PeLam5ubGBkZgYeHBz5+/IiLFy/ix48faGhoQExMjCgsx8fHOcn/BpkqW29vbwwNDYmEEAQqwJqamg6FrG7/gIAAAYWOgcHBQXENGpuSkqIyb3Nzs6gX6HGwq6tLFFuvX78WYKlQe/LkifiOzmhnZ2fQQlheXhbFGM07PT29N54mpp3gxo0bQsufbKdqu/4dZHrGpOdkSlldXZ2ovmlbfP78Oby8vA5A1qR/W1ubAEONCjt6vCMAtJhcXFz25iZIrq6u4rp0BtOWTsUgNbqf6upqXL16VRSL9Knc+umeS0pKBGTleJrbwMAALS0tuH79+p9k/P98q5EAbmxsHDiLj3JKnf70HE4QbGxsRCG1sLAAU1NTlccomp8esajYUwKkflRH2Nvb48yZM3u3QAUj/QHHzs5OFJLK9uv4P0r378n/kyRrQxhf4x8HGLIEq4EhM2QJHJBAIieZIUvggAQSOckMWQIHJJDISWbIEjgggUROMkOWwAEJJHKSGbIEDkggkZPMkCVwQAKJnGSGLIEDEkjkJDNkCRyQQCInmSFL4IAEEjnJDFkCBySQqJJkCfRKK1GhUOz+BbaftLWDFNYjAAAAAElFTkSuQmCC"
              />

              {/* <Tester /> */}
            </Box>
            <Box sx={{ my: 3 }}>
              <Typography color="textPrimary" variant="h4">
                Scenario
              </Typography>
              <Typography color="textSecondary" gutterBottom variant="body2">
                Enter scenarios
              </Typography>
            </Box>

            <SetScenario countList={countList} />
            <Box
              sx={{
                alignItems: "center",
                display: "flex",
                ml: -1,
              }}
            ></Box>
            {Boolean(formik.touched.policy && formik.errors.policy) && (
              <FormHelperText error>{formik.errors.policy}</FormHelperText>
            )}
            <Box
              sx={{
                py: 2,
                display: "flex",
                justifyContent: "flex-end",
                justifyContent: "space-between",
              }}
            >
              <Box>
                <Button
                  color="primary"
                  disabled={formik.isSubmitting}
                  size="large"
                  variant="contained"
                  onClick={AddScenario}
                  sx={{
                    marginRight: 1,
                  }}
                >
                  Add Row
                </Button>
                <Button
                  color="primary"
                  disabled={formik.isSubmitting}
                  size="large"
                  variant="contained"
                  onClick={DeleteScenario}
                >
                  Delete Row
                </Button>
              </Box>

              <NextLink href="/requirements" passHref>
                <Button
                  color="primary"
                  disabled={formik.isSubmitting}
                  size="large"
                  type="submit"
                  variant="contained"
                >
                  Submit
                </Button>
              </NextLink>
            </Box>
          </form>
        </Container>
      </Box>
    </>
  );
};

WorkArea.getLayout = (page) => <DashboardLayout>{page}</DashboardLayout>;
export default WorkArea;

Text nodes vs Text nodes within Elements – Why do some come with quotes in Chrome

I am trying to produce a match to the output from Chrome Devtools (Elements) view, but I can’t see why some elements on the Chrome view read <P>Lorem ipsum</P> and some read <P>"Lorem Ipsum"</P> as both are text nodes within an element.

I have a demonstrator that shows the problem (both coming out as quoted – see Lorem1 and Lorem5)

var _TAG = 1;
var _TEXT = 3;
var _COMMENT = 8;
// ----------------------------------------------------------
function dge(id) {
  return document.getElementById(id);
}
// ----------------------------------------------------------
function getVisibleHTML(tx) {
  return tx.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
// ----------------------------------------------------------
function getTracePart(node) {
  if (node.nodeType == _TEXT) {
    if (node.nodeValue.trim() != '') return '<text>&quot;' + node.nodeValue + '&quot;</text>';
    else return '';
  }
  if (node.nodeType == _TAG) return getVisibleHTML(node.outerHTML);
  if (node.nodeType == _COMMENT) return '<BR><comment>&lt;--' + (node.nodeValue) + '--&gt;</comment><BR>';
  return 'NODE TYPE ' + node.nodeType;
}
// ----------------------------------------------------------
function write(tx) {
  dge('trace').innerHTML += tx;
}
// ----------------------------------------------------------
function doWalkTree(container) {
  for (var c = 0; c < container.childNodes.length; c++) {
    var child = container.childNodes[c];
    if (child.nodeType == _TAG) {
      write('<BR>&lt;' + child.tagName + '&gt;');
      doWalkTree(child);
      if (child.tagName != 'BR') write('&lt;/' + child.tagName + '&gt;');
      write('<BR>');
    } else write(getTracePart(child));
  }
}
// ----------------------------------------------------------

doWalkTree(dge('test'));
div,p, ul {
    border:solid 1px red;
    margin:10px;
    padding:10px;
}
span {
    border-radius:9px;
    padding:2px 8px 2px 8px;
    margin:5px;
    background-color:#e9e9e9;
    display:inline-block;
}
text {
   color:#77c592;
}
comment {
    color:#8facdd;
}
<div id='test'>

  <p>Lorem1 ipsum <b>dolor</b></p>

  <br>Lorem2 ipsum dolor

  <p><!--test-->Lorem3 ipsum dolor</p>

  Lorem4 ipsum dolor
  
  <p>Lorem5 ipsum dolor</p>
</div>

<hr>

<h5>Post Normalized result trace....</h5>
<div id='trace'></div>

I also have a demo running on jsfiddle (https://jsfiddle.net/Abeeee/3ts74boa/95/) but any assistance would be great.

Thanks

Compare 2 Arrays of Objects

I want to compare 2 Arrays of Objects to find the object or objects which is not matched.
In the example below it should output {label: 'Addition', type: 'address', name: 'address_4', defaultValue: 'test'} as this Object is not matched.

const A = [{
    label: 'Street Name',
    type: 'address',
    name: 'address_1',
    defaultValue: 'test1'
  },
  {
    label: 'House Number',
    type: 'address',
    name: 'address_2',
    defaultValue: '1563l1'
  },
  {
    label: 'Addition',
    type: 'address',
    name: 'address_3',
    defaultValue: 'ABC684'
  }
]

const B = [{
    label: 'Street Name',
    type: 'address',
    name: 'address_1',
    defaultValue: 'test1'
  },
  {
    label: 'House Number',
    type: 'address',
    name: 'address_2',
    defaultValue: '1563l1'
  },
  {
    label: 'Addition',
    type: 'address',
    name: 'address_3',
    defaultValue: 'ABC684'
  },
  {
    label: 'Addition',
    type: 'address',
    name: 'address_4',
    defaultValue: 'test'
  }
]

let difference = currentSet.filter((page1) => !newSet.find(page2 => page1.name === page2.name))

This does not work. It outputs an empty Array. What I’m doing wrong?

How to enable bulk amount of option values in html selection drop down box?

Does anyone know a way to enable all the times in this selection box without having to go through them with “document.getElementById”. There are about 30 of these, for all the times.

In the live code, the option values (times) can be disabled depending on a date selection, so at the start of the function (onchange event) it enables them all for use again (and disables per date selected).

<select name="time" id="time">
<option value="N/A">Select</option>
<option value="12:00pm" id="12:00pm">12:00pm</option>
<option value="12:15pm" id="12:15pm">12:15pm</option>
<option value="12:30pm" id="12:30pm">12:30pm</option>
<option value="12:45pm" id="12:45pm">12:45pm</option>
<option value="13:00pm" id="13:00pm">13:00pm</option>
<option value="13:15pm" id="13:15pm">13:15pm</option>
<option value="13:30pm" id="13:30pm">13:30pm</option>
<option value="13:45pm" id="13:45pm">13:45pm</option>
<option value="14:00pm" id="14:00pm">14:00pm</option>
</select>

<script>
var select = document.getElementById('date');
select.onchange = SetClosed;
window.onload = SetClosed;

function SetClosed(){
document.getElementById("12:00pm").disabled = false;
document.getElementById("12:15pm").disabled = false;
document.getElementById("12:30pm").disabled = false;
document.getElementById("12:45pm").disabled = false;
document.getElementById("13:00pm").disabled = false;
document.getElementById("13:15pm").disabled = false;
document.getElementById("13:30pm").disabled = false;
document.getElementById("13:45pm").disabled = false;
document.getElementById("14:00pm").disabled = false;
}
</script>

i have tried this to replace the large amounts of “getElementById”, but no joy:

document.querySelectorAll('input[name="time"]').forEach(element => {element.removeAttribute("disabled");});

The code works using ID’s of course, but was hoping there could be a way to reduce the code down a bit.