Send recorded video using getUserMedia through form without using FormData

I have a form where users can record themselves with their webcam using getUserMedia, and I need to send the file they record to another page before saving the file to the server.

My question is what would be the best way to do that? So far I’ve generated a blob of the video, how do I send this through my form to the next page so I can access the file and then store it on the server?

Currently I’m generating the blob like so, which works:

let videoURL = window.URL.createObjectURL(blob, {autoRevoke: false});

But I’m not sure how I can send this file as part of the form’s POST request without using AJAX and FormData. Is it even possible or am I approaching this incorrectly?

Why is my mongoose query with $gt combined with $size not working?

here is my mongoose query(and the router):

router.get('/reportsRegular', function(req,res,next){
  Question.find({reports: {$size: {$gt: 0}}, checked: false}).sort({reports: -1}).limit(20).exec(function(err,results){
    console.log(results)
    res.render('reports', {type: 'regular', user: req.user, reports: results})
  })

and it seems there is a problem with the first find condition, when I remove the $gt to 1 instead it works, but it wont work in cases with more then one, so I need to use $gt.
here is an example JSON document that should work but does not get found:

  {
    _id: new ObjectId("6212e77aa1e98ae3282a61e6"),
    title: 'TOMATOOOOOO',
    text: '<p>AAAAAAAAAAAAAAAA</p>',
    authorUsername: 'SweetWhite',
    dateCreated: 2022-02-21T01:14:34.901Z,
    answers: [],
    likes: [ 0 ],
    dislikes: [ 0 ],
    tag: 'Languages',
    views: [ 1, 'SweetWhite' ],
    reports: [ 'SweetWhite' ],
    checked: false,
    reportsNested: [],
    __v: 0
  }

it should get found since the size of the reports array is bigger then zero, and the checked value is false.
What am I doing wrong?

Thanks!

Randomly generate += or -= javascript

Hi i am trying to assign either += or -= to an object position.
Firstly I have random math choosing a number:

var min = 9;
 var max = 11;
 var pos = Math.floor(Math.random() * (max - min + 1)) + min;

I am trying to add the out come of pos to this._target.position.z and this._target.position.x but I want it to be randomly either added or subtracted

so the random out come should be for the Z position should be either:

this._target.position.z += pos;

or

this._target.position.z -= pos;

and then for the X position should be either:

this._target.position.x += pos;

or

this._target.position.x -= pos;

thanks in advance.

“this” not working inside deep watcher with Vue JS 3 and TypeScript

I am having some troubles trying to use “this” in a deep watcher. It seems like inside the deep watcher, the word this points to the context of the object watcher and it is not able to get an attribute declared in the data() function. My script tag looks like this:

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "App",
  data() {
    return {
      totalPrice: 0,
      cart: new Array<any>()
    };
  },
  watcher: {
    cart: {
      handler(cart: Array<any>) {
        this.totalPrice = cart.reduce((prev, curr) => {
          const prevPrice = prev.price || prev;
          const prevQuantity = prev.quantity || 1;
          return prevPrice * prevQuantity + curr.price * curr.quantity;
        }, 0);
      },
      deep: true
    },
  },
});
</script>

So, when I do npm run serve I get this error in console:

ERROR in src/App.vue:134:14
TS2339: Property 'totalPrice' does not exist on type '{ handler(cart: any[]): void; deep: boolean; }'.
    133 |       handler(cart: Array<any>) {
  > 134 |         this.totalPrice = cart.reduce((prev, curr) => {
        |              ^^^^^^^^^^
    135 |           const prevPrice = prev.price || prev;
    136 |           const prevQuantity = prev.quantity || 1;
    137 |           return prevPrice * prevQuantity + curr.price * curr.quantity;

I’m new with vue, so I’ll be happy receiving any suggestion. Thanks in advance.

Weird line bug when animating a falling sprite using JavaScript canvas

I’m trying to move a block of butter down a canvas window. Here is the code sandbox: https://codesandbox.io/s/empty-sandbox-forked-tygc5z?file=/index.html

The important code is index.js:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

window.onresize = function () {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
};

const arr = ["butter", "bread", "cheese"];
const sprites = [];
const tilesheet = new Image();

const butter1 = {
  img: tilesheet,
  sourceWidth: 24,
  sourceHeight: 60,
  sourceX: 3,
  sourceY: 2,
  vy: 0,
  timer: 0,
  x: 0,
  y: 0,
  scale: 1,
  visible: false
};
const butter2 = {
  img: tilesheet,
  sourceWidth: 33,
  sourceHeight: 60,
  sourceX: 27,
  sourceY: 2,
  vy: 0,
  timer: 0,
  x: 0,
  y: 0,
  scale: 1,
  visible: false
};
const butter3 = {
  img: tilesheet,
  sourceWidth: 24,
  sourceHeight: 60,
  sourceX: 60,
  sourceY: 2,
  vy: 0,
  timer: 0,
  x: 60,
  y: 0,
  scale: 1,
  visible: false
};
tilesheet.addEventListener(
  "load",
  () => {
    arr.forEach((_, i) => {
      const b1 = { ...butter1 };
      b1.timer = i * 62;
      sprites.push(b1);

      const b2 = { ...butter2 };
      b2.x = b1.x + b1.sourceWidth * b1.scale;
      b2.timer = b1.timer;
      sprites.push(b2);

      const b3 = { ...butter3 };
      b3.x = b2.x + b2.sourceWidth * b2.scale;
      b3.timer = b2.timer;
      sprites.push(b3);
    });
    render();
  },
  false
);
tilesheet.src = "./src/sample.png";

function render() {
  requestAnimationFrame(render);
  //console.log(arr.length, sprites.length);
  sprites.forEach((sprite, i) => {
    sprite.timer -= 0.3;

    if (sprite.timer <= 0) {
      sprite.visible = true;
    }

    if (sprite.visible) {
      sprite.vy = 0.3;
      sprite.y += sprite.vy;
    }
  });
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.fillStyle = "rgba(229, 242, 24, 1)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);
  sprites.forEach((sprite) => {
    if (sprite.visible) {
      ctx.drawImage(
        sprite.img,
        sprite.sourceX,
        sprite.sourceY,
        sprite.sourceWidth,
        sprite.sourceHeight,
        sprite.x,
        sprite.y,
        sprite.sourceWidth * sprite.scale,
        sprite.sourceHeight * sprite.scale
      );
    }
  });
}

As you can see in the code sandbox, there is a weird line appearing when the blocks of butter go down the window:
enter image description here
It is not there when the speed is 1 instead of 0.3 or when the butter is not moving.

Is there anyway I can get rid of the weird line? Thanks

How do I send a variable from Express.js backend to React.js frontend?

I am trying to send my variable ‘backEndResponse’ with its value from my Express.js backend to my React.js Frontend. I am not quite sure how to send a variable from the backend to the frontend. I have searched around and can’t find any good resources. I would appreciate any help.

Express.js Backend

 function getcookie(req) {
        var authCookie = req.headers.cookie;
        try{
        return authCookie
            .split('; ')
            .find(row => row.startsWith('Auth='))
            .split('=')[1];
        } finally {
            if (authCookie = result) {
                backEndResponse = true
                console.log(backEndResponse);
                console.log(result);
            } else {
                backEndResponse = false
                console.log(backEndResponse);
                console.log(result);
            }
        }
    }
    
    app.get('/auth', (req, res) => {
        backEndResponse
    });

Frontend React.js

let backEndResponse = null

axios.get('http://localhost:5000/auth', { withCredentials: true }).then((res) => {
        // backEndResponse
    })

const useAuth = () => {
    if (backEndResponse) {
        const authorized = {loggedIn: true}
        return authorized && authorized.loggedIn;
    } else {
        const authorized = {loggedIn: false}
        return authorized && authorized.loggedIn;
    }
};

Fastest way to clean path collisions in array of strings

This is a hard one to explain, but here goes. I need to clean an array of ‘path’ strings where if a path has sub properties it not include the top level property. but only the child properties

E.g

[
  'firstName',
  'address',
  'address.local.addressLine1',
  'address.local.addressLine2',
  'address.local',
]

Should become:

[
  'firstName',
  'address.local.addressLine1',
  'address.local.addressLine2',
  'address.local',
]

I have a fairly verbose function kind of working so far, but looking to see if there is a more elegant/better solution than this:

function cleanCollisions(array) {

        var output = [];

        // return [...new Set(array)];
        var map = array.reduce(function(set, field) {
            if (!Boolean(field)) {
                return set;
            }

            ////////////////

            var rootKey = field.split('.')[0];
            if(!set[rootKey]) {
                set[rootKey] =[];
            }

            var count = field.split('.').length -1;
            if(count) {
                set[rootKey].push(field);
            }


            return set;
        }, {})


        for(const key in map) {
            value = map[key];
            if(value.length) {
                output.push(value);
            } else {
                output.push(key);
            }
        }

        ////////////////

        return output.flat();
    }

Object destructuring default parameters get all arguments

I have a js file with an imported default options and function as below. I am trying to get all the arguments in the function, however it appears that they cannot be used.

import {defaultOptions} from "../defaults.js"

export function getConfig({
  width = defaultOptions.width,
  height = defaultOptions.height,
  fontsize = defaultOptions.fontsize
} = {}) {
   // I want to get all the arguments 
   console.log(arguments); 
}

When I call the function with no parameters like getConfig() and console.log(width) then it shows the width from the defaultOptions from the defaults.js. However the console.log(arguments) returns Arguments object with length 1 where index 0 : undefined.

Is there a way I can get all the arguments in such a function?

Split variable into several to get infos

I would like to separate this in Javascript and create variables infos1, infos2 ….

So I need a function to separate all the info.

<option value="[infos1][infos2][infos3][infos4]"></option>

var InfosInitial = $('#insert').find("option:selected").val();

var infos1 = ?;

var infos2 = ?;

Thanks you in advance !

function not passing arguments object test

I’m currently completing an assignment where I need to pass the following test

* should work on an arguments object

Here is my code.

function first (array, n) {
  var result = [];
  if (Array.isArray(array)) {
    if (n && n > 0) {
      var number = n > array.length ? array.length : n;
      for (var i=0; i < number; i++) {
        result.push(array[i]);
      }
    } else {
      result.push(array[0]);
    }
    return result;
  } else {
    return result;
  }
};

Im not sure what lines I need to ammend to make it pass this test, can anyone help me?

WHy in my recursion function the code after the if condition is repeated?

// program to count down numbers to 1
function countDown(number) {

  // display the number
  console.log(number);

  // decrease the number value
  const newNumber = number - 1;

  // base case
  if (newNumber > 0) {
    countDown(newNumber);
  }
  console.log(newNumber);
}

countDown(4); 

// output => 4 3 2 1 0 1 2 3

I can’t visualize what happens after the if condition. I mean I understand that there is “loop” with countDown(newNumber). But I don’t understand why there is the output 0 1 2 3. I know I can put an else keyword, but I’d like to understand why JS engine after finishing the recursion it prints four times console.log(newNumber).

How to import Three.js from CDN to WordPress? – Webpack

I’m trying to import three.js from CDN to WordPress but console returns: example.js:2 Uncaught Error: Cannot find module 'three'. I’m also using Webpack.

example.js:
import * as THREE from 'three'; […]

app.js: import "./example.js";

functions.php:

//wp enqueues

function example_scripts() {

    wp_enqueue_script( 'three-js', 'https://cdn.skypack.dev/[email protected]', array(), null );
    }
add_action( 'wp_enqueue_scripts', 'example_scripts' );
    
//three-js
function set_scripts_type_attribute( $tag, $handle, $src ) {
    if ( 'three-js' === $handle ) {
        $tag = '<script type="module" src="'. $src .'"></script>';
    }
    return $tag;
}
add_filter( 'script_loader_tag', 'set_scripts_type_attribute', 10, 3 );

part of webpack config:

module.exports = {
  externals: {
    THREE: 'three',
  },
};

it appears in html : <script type="module" src="https://cdn.skypack.dev/[email protected]"></script>

How do I add a nested object to an object in same schema?

I’m having a difficult time on solving this one. but before that I will show first my controller, route and schema.

Here is my controller:

module.exports.checkoutOrder = async (data) =>{

    let id = data.userId;
    

    let oTotal = await User.findById(id).then(total => total.userOrders.subtotal + total.totalAmount)

    User.findById(id).then(user=>{

        user.totalAmount.push({total,oTotal})
        return user.save().then((savedtotal,err)=>{
            if (savedtotal) {
                return savedtotal

            } else {

                return 'Failed to checkout order. Please try again'

            }

        })

})
}

here is my route:

route.get('/checkout',auth.verify,(req,res)=>{
    let token = req.headers.authorization;
    let payload = auth.decode(token)
    let isAdmin = payload.isAdmin
    let id = payload.id
    !isAdmin ? controller.checkoutOrder(id).then(result => 
        res.send(result)) 
    : res.send('Unauthorized User')

})

and the schema:

userOrders:[
            {
                productId:{
                    type: String,
                    required: [true, "ProductId is required"]
                },

                quantity:{
                    type: Number,
                    required: [true, "Quantity is required"]
                },

                subtotal:{
                    type: Number,
                    required: [true, "subtotal is required"]
                }
            }
        ],

    
                totalAmount:{
                    type: Number,
                    required: [true, "Quantity is required"]
                },

                PurchasedOn:{
                    type: Number,
                    default:  new Date()
                }
        
})

when i run a postman get, i receive this error

    let oTotal = await User.findById(id).then(total => total.userOrders.subtotal + total.totalAmount)
                                                             ^

TypeError: Cannot read properties of null (reading 'userOrders')

I’ve tried googling how objects work but without requesting from body, I cannot pull “subtotal”(i have values for subtotal) object from “userOrders” to add it to “TotalAmount”. Any tips?

“Failed to load resource: the server responded with a status of 404 (Not Found)”

I get this error message when trying to load in a JS-file in Ionic.

I made sure that the path is correct but I still end up with this response.

Error-Msg

My Index.html:

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

<head>
  <meta charset="utf-8"/>
  <title>Ionic App</title>
  <base href="/"/>
  <meta name="color-scheme" content="light dark"/>
  <meta name="viewport" content="viewport-fit=cover, width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no"/>
  <meta name="format-detection" content="telephone=no"/>
  <meta name="msapplication-tap-highlight" content="no"/>
  <script type="text/javascript" src="galerie.js"></script> <!---------------------JS-file->

  <link rel="icon" type="image/png" href="assets/icon/favicon.png"/>

  <!-- add to homescreen for ios -->
  <meta name="apple-mobile-web-app-capable" content="yes"/>
  <meta name="apple-mobile-web-app-status-bar-style" content="black"/>
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
  <link rel="manifest" href="manifest.webmanifest">
  <meta name="theme-color" content="#1976d2">
</head>

<body>
  <app-root></app-root>
  <noscript>Please enable JavaScript to continue using this application.</noscript>
</body>
</html>

I’m still new to Ionic, so I don’t really know where the problem could lie.

Find first value in array with set num difference

Given a sorted array, I am looking to find the first value in the array where the next value has an increase/difference of >=1000. In the below array, my goal is to return the value 11710, because the next value in array (13271) has a difference of >= 1000.

Sample Array

const array = [11006, 11256, 11310, 11710, 13271, 327027, 327027]

Current Code // not returning correct value

const found = array.find((element, index) => {
   console.log('element', element),
   console.log('array[index + 1]', array[index + 1])
   return Math.abs(element, array[index + 1]) >= 1000
})