Allow input type number only a number/float between 0-1

I want to have an input number that allows any float between 0-1 including both whole numbers. But it’s proving quite tricky just getting the backspace to actually delete a numbers as it comes as NaN

I got this:

const [rate, setRate] = useState<number>(0)

const addRate = (num: number) => {
  if (typeof num !== 'number') {
    setRate(0)
  } else {
    setRate(num)
  }
}

...
<input
  type='number'
  value={rate}
  onChange={e => addRate(parseFloat(e.target.value)}
/>

How to fix Duplicate class errors between react-native-webrtc and react-native-voximplant

For over a week I have been trying to fix this error and I have not been able to figure it out how to fix it. I used react-native-voximplant to build P2P video calling following a tutorial, but I wanted to extend it with conference call/live broadcast like Zoom or MS Teams, but as soon as I installed react-native-webrtc I got the duplicate error. When I uninstall react-native-webrtc my app works fine. But I really want to use react-native-webrtc to achieve it not react-native-voximplant.
So how do I overcome this duplicate error? Thanks in advance for your kind help.

Here’s the screenshort of the error messages:
enter image description here

callback function (arrow) and class method in TimeOut

I want to trigger 2 functions with a unique timeOut.
The following works fine

    setTimeout(function() {
      function1(); // runs first
      function2(); // runs second
    }, 1000)

But in my case, I have a class method and an callback (arrow function).
It looks like this (minimalized):

    class Timer {
      constructor(callback) {
        this.active = false;
        this.callback = callback;
      }

      cancel() {
        this.active = false;
      }

      set() {
        this.active = true;
        this.timeOut = setTimeout( function() {
          this.cancel();
          this.callback; // HERE is my problem. doesn't run, not casted as a function
        }, 1000)
      }

I get the following error Expected an assignment or function call and instead saw an expression.
Any trick to fix that?

missing key and values in Objects in Javascript

I’m JavaScript beginner.

I got one Object from an API like

data= {
key1: “v1”
key2: “v2”
key3: “v3”
}

the above value is returned when I debug it like

console.log(data), 

I wanna use v3 value, but when I tried to get it like below, “Undefined” came. expected result is “v3”

var v3 = data.key3;

am able to get v1 and v2 values, but v3 failed.
Also, if i debug it like

console.log(JSON.stringfy(data));

the returned value is

{key1: "v1"
    key2: "v2"}

I am wondering why thiskind of missing key and value is occuring..
If you have any suggestions, please let me know it.

Thanks

“TypeError: Cannot set properties of undefined (setting ‘next’)”

Input: Given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

Input & Output Illustration (open for understanding)

var addTwoNumbers = function(l1, l2) {
let carry = 0,
    sum = 0;
let runningNode = new ListNode(0, null);
let headNode = runningNode;

while (l1 !== null || l2 !== null) {

    sum = l1 != null ? l1.val : 0 + l2 != null ? l2.val : 0 + carry;
    carry = 0;
    // Error is in below line it states "TypeError: Cannot set properties of undefined (setting 'next')" 
    runningNode.next = ListNode(sum % 10, null)
    runningNode = runningNode.next;
    //How to fix it?
    if (l1) {
        l1.next;
    }
    if (l2) {
        l2.next;
    }
}

if (carry) {
    runningNode.next = ListNode(carry);
}

return headNode;

};

Sequelize: Append key value to Javascript collection

Good morning everyone!

I’m developing an application with Node.js and Angular, and I’m getting a little stuck lately.

I need to append a custom key -> value to an existing query result collection.

This is the function I have:

exports.findAll = (req, res) => {
    Project.findAll({
            include: [{
                all: true,
                include: [{
                    all: true
                }]
            }]
        })
        .then(data => {
            data.forEach(
                (project) => {
                        // <-------- HERE GOES THE APPEND
                }
            );
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message: err.message || "Error retrieving projects"
            });
        });
};

Description:

After getting the result from the model query, I iterate over each result (aka Project).

Then, what I need to do is append a key -> value pair to that very Project.

By now, I’d like to do something like this:

exports.findAll = (req, res) => {
    Project.findAll({
            include: [{
                all: true,
                include: [{
                    all: true
                }]
            }]
        })
        .then(data => {
            data.forEach(
                (project) => {
                    project.cat = "miaw";
                }
            );
            res.send(data);
        })
        .catch(err => {
            res.status(500).send({
                message: err.message || "Error retrieving projects"
            });
        });
};

This try hasn’t made any changes in my JSON collection, and I don’t know how to accomplish it neither.

Could someone give me some help?
I’ve searched everywhere but couldn’t find anything useful.

Thank you so much!

How can I remove a node import from the resulting JS when compiling with tsc?

I am trying to generate JS code with the following tsconfig.json

{
  "compilerOptions": {

    /* Language and Environment */
    "target": "es2016",                                  /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
    "lib": ["ES2019","dom"],                                        /* Specify a set of bundled library declaration files that describe the target runtime environment. */

    /* Modules */
    "module": "esnext",                                /* Specify what module code is generated. */
     "moduleResolution": "node",                       /* Specify how TypeScript looks up a file from a given module specifier. */
     "baseUrl": "./",                                  /* Specify the base directory to resolve non-relative module names. */

    /* JavaScript Support */
     "allowJs": true,                                  /* Allow JavaScript files to be a part of your program. Use the `checkJS` option to get errors from these files. */

    /* Emit */
     "outDir": "./dist/",                                   /* Specify an output folder for all emitted files. */
     "noEmit": true,                                   /* Disable emitting files from a compilation. */

    /* Interop Constraints */
     "isolatedModules": true,                          /* Ensure that each file can be safely transpiled without relying on other imports. */
     "allowSyntheticDefaultImports": true,             /* Allow 'import x from y' when a module doesn't have a default export. */
    "esModuleInterop": true,                             /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables `allowSyntheticDefaultImports` for type compatibility. */
    "forceConsistentCasingInFileNames": true,            /* Ensure that casing is correct in imports. */

    /* Type Checking */
    "strict": true,                                      /* Enable all strict type-checking options. */

    /* Completeness */
    "skipLibCheck": true                                 /* Skip type checking all .d.ts files. */
  },
  "include": ["src/**/*.ts", "src/Container.js"],
  "exclude": ["node_modules/**/*", "dist/**/*","konva/*"],
}

This configuration generates one js file in the dist directory for each TS file, this way I can mantain the file structure.

The problem is that I need to import Konva lib from npm in order to use it, and when I compile I get this import in the JS files which need this lib:

import Konva from "konva"

This raises an error because it is not a valid path. Right now I have a python script removing this line from the resulting files, but I would like to remove it because it is an extra dependency just for removing one line.

When running the website it does not have any problem because I import Konva lib from CDN.

I am pretty new to TS and I don’t know if it is possible to remove the import statement from npm modules or if I have to bundle everything together, any tip is welcome.

Thanks.

How to make channel on which the bot will send logs?

I would like to make my bot so that it sends logs to a given channel that someone will set up beforehand, for example, will enter the command set log channel <channel> and then the bot will send logs there. So far, I have only managed to do the command for which the bot will send messages to a given channel, but only after entering the channel id. Thank you in advance for help.

AFRAME I cant display informations on pictures on click

I am starting aframe and I cant display some informations (a small text) on pictures.

This is actually my code, if you could help me it would be very nice.

<html>

<head>
  <meta charset="utf-8">
  <title>360° Image Gallery</title>
  <script src="https://aframe.io/releases/1.0.4/aframe.min.js"></script>
  <script src="https://unpkg.com/aframe-event-set-component@5/dist/aframe-event-set-component.min.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/aframe-layout-component.min.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/aframe-template-component.min.js"></script>
  <script src="https://unpkg.com/[email protected]/dist/aframe-proxy-event-component.min.js"></script>

  <!-- Image link template to be reused. -->
  <script id="link" type="text/html">
    <a-entity class="link"
      geometry="primitive: plane; height: 1; width: 1"
      material="shader: flat; src: ${thumb}"
      sound="on: click; src: #click-sound"
      event-set__mouseenter="scale: 1.2 1.2 1"
      event-set__mouseleave="scale: 1 1 1"
      event-set__click="_target: #image-360; _delay: 300; material.src: ${src}"
      proxy-event="event: click; to: #image-360; as: fade"></a-entity>
  </script>

  <script id="panInfor" type="text/html">
    <a-entity class="panInfor"
      geometry="primitive: plane; height: 1; width: 1"
      material="shader: flat; src: ${thumb}"
      sound="on: click; src: #click-sound"
      event-set__mouseenter="scale: 1.2 1.2 1"
      event-set__mouseleave="scale: 1 1 1"
      event-set__click="_target: #text-informations;_delay: 300; material.src: ${src}"
      proxy-event="event: click; to: #text-informations; as: switch">
    </a-entity>
  </script>


</head>

<body>
  <a-scene>
    <a-assets>
      <img id="city" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/city.jpg" crossorigin="anonymous">
      <img id="city-thumb" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/thumb-city.jpg"
        crossorigin="anonymous">
      <img id="cubes" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/cubes.jpg" crossorigin="anonymous">
      <img id="cubes-thumb" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/thumb-cubes.jpg"
        crossorigin="anonymous">
      <img id="sechelt" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/sechelt.jpg"
        crossorigin="anonymous">
      <img id="sechelt-thumb" src="https://cdn.aframe.io/360-image-gallery-boilerplate/img/thumb-sechelt.jpg"
        crossorigin="anonymous">

      <img id="messi" src="messi.jpg" crossorigin="anonymous">
      <img id="ronaldo" src="ronaldo.jpg" crossorigin="anonymous">
      <img id="mbappe" src="mbappe.jpg" crossorigin="anonymous">

      <img id="monnet" src="monnet.jpg" crossorigin="anonymous">
      <img id="mona" src="mona.jpg" crossorigin="anonymous">
      <img id="oreille" src="oreille.jpg" crossorigin="anonymous">

      <audio id="click-sound" src="https://cdn.aframe.io/360-image-gallery-boilerplate/audio/click.ogg"
        crossorigin="anonymous"></audio>

      <a-text position="1 2 -4" rotation="0 -90 0" id="text-messi" value="Greatest Of All Times" align="center">
      </a-text>

      <a-text position="1 2 -2.5" rotation="0 -90 0" id="text-ronaldo" value="Overrated" align="center">
      </a-text>

      <a-text position="1 2 -1" rotation="0 -90 0" id="text-mbappe" value="Runs fast" align="center">
      </a-text>

      <a-text position="-4 2 -1" rotation="0 90 0" id="text-mona" value="Beautiful lady" align="center">
      </a-text>

      <a-text position="-4 2 -4" rotation="0 90 0" id="text-monnet" value="Nice bridge" align="center">
      </a-text> 

      <a-text position="-4 2 -2.5" rotation="0 90 0" id="text-oreille" value="Lost his ears" align="center"></a-text>


    </a-assets>

    <!-- 360-degree image. -->
    <a-sky id="image-360" radius="10" src="#city"
      animation__fade="property: components.material.material.color; type: color; from: #FFF; to: #000; dur: 300; startEvents: fade"
      animation__fadeback="property: components.material.material.color; type: color; from: #000; to: #FFF; dur: 300; startEvents: animationcomplete__fade">
    </a-sky>

    <!-- Image links. -->
    <a-entity id="links" layout="type: line; margin: 1.5" position="-3 1 -5">
      <a-entity template="src: #link" data-src="#cubes" data-thumb="#cubes-thumb"></a-entity>
      <a-entity template="src: #link" data-src="#city" data-thumb="#city-thumb"></a-entity>
      <a-entity template="src: #link" data-src="#sechelt" data-thumb="#sechelt-thumb"> </a-entity>
    </a-entity>

    <!--Panel footballers-->
    <a-entity id="pansInformsFootballer" layout="type: line; margin: 1.5" position="1 1 -4" rotation="0 -90 0 ">
      <a-entity template="src: #panInfor" data-src="#text-messi" data-thumb="#messi"></a-entity>
      <a-entity template="src: #panInfor" data-src="#text-ronaldo" data-thumb="#ronaldo"></a-entity>
      <a-entity template="src: #panInfor" data-src="#text-mbappe" data-thumb="#mbappe"></a-entity>
    </a-entity>

    <!--Panel works of art-->
    <a-entity id="pansInformsPaint" layout="type: line; margin: 1.5" position="-4 1 -1" rotation="0 90 0 ">
      <a-entity template="src: #panInfor" data-src="#text-mona" data-thumb="#mona"></a-entity>
      <a-entity template="src: #panInfor" data-src="#text-oreille" data-thumb="#oreille"></a-entity>
      <a-entity template="src: #panInfor" data-src="#text-monnet" data-thumb="#monnet"></a-entity>
    </a-entity>

    <a-text id="text-informations" src="#text-messi" visible="false"
      animation__click="property: visible; dur: 0; to: true; startEvents: switch" color="yellow">

    </a-text>


    <!-- Camera + cursor. -->
    <a-camera look-controls wasd-controls="acceleration:300 ">
      <a-cursor id="cursor" color="yellow"
        animation__clickreset="property: scale; to: 0.1 0.1 0.1; dur: 1; startEvents: animationcomplete__click"
        animation__fusing="property: scale; from: 1 1 1; to: 0.1 0.1 0.1; easing: easeInCubic; dur: 150; startEvents: fusing">
      </a-cursor>
    </a-camera>
  </a-scene>

</body>

</html>

The aim of my code is just to display informations when I click on the pictures/paints.

The part where the changes is the code from the tutorial of aframe “360 image gallery”.
I wanted to display informations on pictures, retrieving the code of the tutorial but it doesnt work…

Thank you

decrease speed scrolling site on MacOs

please help me with next question: I have landing page consist off 6 slides. Scrolling on a Mac OS (Chrome, Safari) touchpad is very fast. from 1 slide immediately jumps to through several other slides (different every time). How can this situation be fixed?
Thank you

Render a new Fieldarray only if there’s a previous field using Formik

I want to achieve the following using Formik and Fieldarray.

I want to render a new input field whenever the user starts writing in the current input field.
so I want to eliminate the button.

so instead of having a (+) button to add a new field:

feild1

I want to have it like this:

field2

I tried to do it using variant.length > 1 but it’s not what I want because it will add a new field every time the length of variant is larger than one, and I want it only for the previous field array.

I wrote this code so far

 const handleSubmit = async (e) => {
    e.preventDefault();
    let formValues = ref.current.values;
    console.log('Form Data received', formValues);
    let formData = new FormData();
    formData.append('name', formValues.name);
    for (let key in formValues.variants) {
      formData.append(
        'variants[key].variantName',
        formValues.variants[key].variantName
      );
    }

    await axios.post('http://localhost:4000/variants', formValues);
  };

  return (
    <div>
      <div>
        <h1 className="mb-2">products details</h1>
        <div>
          {data &&
            data.map((variant) => (
              <div
                key={variant.id}
                className="flex  appearance-none border  font-sans w-80 my-1  p-2 bg-white"
              >
                <h1 className="p-1">{`${variant.name}: `}</h1>

                {variant.variants &&
                  variant.variants.map((subVar) => (
                    <span
                      className="mx-2 rounded-full h-10 w-10 p-1 bg-buttonsColor text-white"
                      key={subVar.id}
                    >
                      {subVar.variantName}
                    </span>
                  ))}
              </div>
            ))}
        </div>
      </div>
      <Formik
        initialValues={initialValues}
        innerRef={ref}
        validateOnChange={false}
      >
        {(formik) => {
          return (
            <Form
              id="productForm"
              name="productForm"
              enctype="multipart/form-data"
              onSubmit={handleSubmit}
            >
              <div className="font-sans py-2">add product details</div>
              <div className="py-2">
                <Field
                  className="shadow appearance-none border font-sans rounded  px-4 py-2 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                  type="text"
                  name="name"
                  placeholder="variant name"
                />
                <FieldArray name="variants">
                  {(fieldArrayProps) => {
                    const { push, remove, form } = fieldArrayProps;
                    const { values } = form;
                    const { variants } = values;
                    return (
                      <div>
                        {variants.map((variant, index) => (
                          <div key={`variant-${index}`}>
                            <Field
                              className="shadow font-sans appearance-none border rounded   px-4 py-2 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
                              type="text"
                              name={`variants[${index}].variantName`}
                              placeholder="variant type"
                            />

                            <button
                              type="button"
                              className="bg-buttonsColor hover:bg-maincolor h-10 w-10 mr-2 font-extrabold text-2xl text-white rounded-full focus:outline-none  focus:shadow-outline"
                              onClick={() =>
                                push({ id: uuid(), variantName: '' })
                              }
                            >
                              +
                            </button>
                            {index > 0 && (
                              <button
                                type="button"
                                className="bg-buttonsColor hover:bg-maincolor h-10 w-10 mr-2 font-extrabold text-2xl text-white rounded-full focus:outline-none  focus:shadow-outline"
                                onClick={() => remove(index)}
                              >
                                -
                              </button>
                            )}
                          </div>
                        ))}
                      </div>
                    );
                  }}
                </FieldArray>
              </div>
              <div
                style={{ display: 'flex', 'justify-content': 'space-between' }}
              >
                <button
                  className="bg-buttonsColor font-sans hover:bg-maincolor text-black font-bold py-2 px-4 rounded-lg focus:outline-none  focus:shadow-outline"
                  type="submit"
                  onClick={(e) => {
                    handleSubmit(e);
                    getData();
                  }}
                  disabled={!formik.isValid}
                >
                  save
                </button>
              </div>
            </Form>
          );
        }}
      </Formik>

How to increase and deacrease the qty in session

Please someone help!!!!!!!!!!!!

This is my Html and app.js file code

<button class="h-6 pl-2" id="plus" data-plus-id="<%= pizza.item._id %>"><i class="fa fa-plus"
                                aria-hidden="true"></i></button>

   This is how get id of pizza:


const plus = document.querySelectorAll("#plus")


     function plusQty(inc) {
            axios
                .post("/plus-qty", inc)
                .then(() => {
                    new Noty({
                        type: 'success',
                        timeout: 1000,
                        text: 'qty inc',
                        progressBar: false,
                        killer: true,
        
                    }).show();
        
                    setTimeout(() => {
                        window.location.assign("/cart");
                    }, 2000);
        
        
                })
                .catch((err) => {
                    console.log(err);
                });
        }
        
        
        plus.forEach((btn) => {
            btn.addEventListener("click", (e) => {
                let inc = btn.getAttribute("data-plus-id");
                plusQty(inc)
            //    console.log(incre)
            });
        });




 > Getting id in controller.js


       increase(req, res) {
                let cart = req.session.cart;
                let item_id = Object.keys(req.body)[0];
                let listItem = cart.items[item_id];
    
               
                // if (cart.totalQty == 0) {
                //     delete req.session.cart;
    
                //     return res.redirect("/cart");
                // }
    
                // return res.json({
                //     totalQty: req.session.cart.totalQty,
                // });
    
    
            }
    
        }

{{“user”:”61efd0ad66dc3aa50486254b”},”cart”:{“items”:{“61dc28da966c28ed6fb9e631”:{“item”:{“_id”:”61dc28da966c28ed6fb9e631″,”pizzaname”:”new peppy paneer”,”image”:”image_1641922230086_new_peppy_paneer.webp”,”price”:199,”size”:”small”,”__v”:0,”des”:”Flavorful trio of juicy paneer, crisp capsicum with spicy red paprika”},”qty”:1}},”totalQty”:1,”totalPrice”:199}}