UnhandledPromiseRejectionWarning when deploying Twilio Video server

I am following Twilio’s documentation for starting a live video application.

I set up the application but when I try to deploy it with npm run serverless:deploy:

it returns this error:

(node:1198) UnhandledPromiseRejectionWarning: Error: Authenticate
    at ServicePage.Page.processResponse (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/twilio/lib/base/Page.js:156:11)
    at ServicePage.Page (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/twilio/lib/base/Page.js:16:22)
    at new ServicePage (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/twilio/lib/rest/serverless/v1/service.js:417:30)
    at Function.<anonymous> (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/twilio/lib/rest/serverless/v1/service.js:251:24)
    at Promise_then_fulfilled (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/q/q.js:766:44)
    at Promise_done_fulfilled (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/q/q.js:835:31)
    at Fulfilled_dispatch [as dispatch] (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/q/q.js:1229:9)
    at Pending_become_eachMessage_task (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/q/q.js:1369:30)
    at RawTask.call (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/asap/asap.js:40:19)
    at flush (/Users/zorgan/Desktop/twilio-live-interactive-video-main/node_modules/asap/raw.js:50:29)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:1198) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:1198) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

I believe this snippet in Twilio’s code is causing the problem:

/**
 * Creates a new promise, waits for this promise to be resolved, and informs
 * either the fullfilled or rejected handler of the result. Whatever result
 * comes of the fulfilled or rejected handler, a value returned, a promise
 * returned, or an error thrown, becomes the resolution for the promise
 * returned by `then`.
 *
 * @param fulfilled
 * @param rejected
 * @returns {Promise} for the result of `fulfilled` or `rejected`.
 */
Promise.prototype.then = function Promise_then(fulfilled, rejected, ms) {
    var self = this;
    var deferred = defer();

    var _fulfilled;
    if (typeof fulfilled === "function") {
        _fulfilled = function Promise_then_fulfilled(value) {
            try {
                deferred.resolve(fulfilled.call(void 0, value));
            } catch (error) {
                deferred.reject(error);
            }
        };
    } else {
        _fulfilled = deferred.resolve;
    }

    var _rejected;
    if (typeof rejected === "function") {
        _rejected = function Promise_then_rejected(error) {
            try {
                deferred.resolve(rejected.call(void 0, error));
            } catch (newError) {
                deferred.reject(newError);
            }
        };
    } else {
        _rejected = deferred.reject;
    }

    this.done(_fulfilled, _rejected);

    if (ms !== void 0) {
        var updateEstimate = function Promise_then_updateEstimate() {
            deferred.setEstimate(self.getEstimate() + ms);
        };
        this.observeEstimate(updateEstimate);
        updateEstimate();
    }

    return deferred.promise;
};

Should I edit this code directly and if so how could I fix the unhandled promise?

Is css and html files necessary?

Given javascript can manipulate with the DOM tree and do all sort of things, I wonder why dont we just use one javascript instead to replace html and css files? Is that possible?

If that is possible, why are we still sticking to use html and css files still? Is it because historical reason?

Express GET request not reloading page

I’m trying to send the client the next HTML page (create.html) as a response to a GET request (fired by button) using fetch. I am purposely trying to avoid using a form due to formatting issues and potential future scaling issues. The code registers that the request is sent, received, and is responded to with the file but it simply does not reload the page with it. *res.redirect does also not work. I’ve attached my code bellow.
JavaScript:

app.get('/', function(req, res) {
    console.log(`[00]: Get request recieved at '/'`);
    res.sendFile('public/start.html' , { root : __dirname});
})

app.get('/login', function(req, res) {
    console.log(`[01]: Get request recieved at '/login'`);
    res.sendFile('public/login.html' , { root : __dirname});
})
app.get('/create', function(req, res) {
    console.log(`[02]: Get request recieved at '/create'`);
    res.sendFile('public/create.html' , { root : __dirname});
})

HTML:

<html>
    <head>
        <meta charset="utf-8">
        <title>HOME PAGE</title>
    </head>
    <body>
        <h1 id='title'>Welcome User!</h1>
        <h2>Select an option bellow!</h2>
        
        <button id="btnToLogin">Login</button>
        <button id="btnToCreate">Create Account</button>

        <p>-ADMIN PANEL-</p>
        <button id="btnDisplay">Display Database</button>
        <button id="btnTruncate">Truncate Database</button>
        <p id='displayText' >[displayText]: Nothing seems to be here...</p>
        
        <script src="start.js"></script> 
    </body>

</html>

HTML JavaScript:

// Gets elements from start.html
var btnToLogin = document.getElementById('btnToLogin');
var btnToCreate = document.getElementById('btnToCreate');
var btnDisplay = document.getElementById('btnDisplay');
var btnTruncate = document.getElementById('btnTruncate');
var displayText = document.getElementById('displayText');

btnToLogin.addEventListener('click', function() { fetch('/login', { method: 'GET' }) });
btnToCreate.addEventListener('click', function() { fetch('/create', { method: 'GET'}) });

I’ve cut out most of my code, just unnecessary for the problem I believe. Everything is required properly and server is set up. And incase it matters i’ve attached a picture of the file structure. Thanks.
File Structure

How to improve my add class to element functions

I want to write a vanilla js function that have the same function as in jQuery addClass() function. I have wrote these code below.

function checkType(value){ //get type of target
    var name = "";
    var type = value.split("");
    for(var i=1; i<type.length; i++){
        name = name + type[i];
    }
    if(type[0] == "#"){ //if id
        return document.getElementById(name);   //return id
    }else if(type[0] == "."){ //if class
        return document.getElementsByClassName(name); //return class
    }else{
        return null;
    }
}

function classesToArray(value){ 
    if(value != null){
        value = value.split(" ");
        return value;
    }
    return [];
}

function addClass(target, value) {
    var element = checkType(target);
    var classes = classesToArray(value);
    if(element != null){
        classes.forEach(function(classItem){
            if(element.length){
                for(var i = 0; i < element.length; i++){
                    element[i].className += " " + classItem;
                }
            }else{
                element.className += " " + classItem;
            }
        });
    }
}

So the way to use it is as below

addClass('.elementIdName','nameOfClassToAdd');    //target Id if begin with .
addClass('#elementClassName','nameOfClassToAdd'); //target className if begin with #

addClass('.elementIdName', 'nameOfClass1 nameOfClass2'); //you can also add multiple class names

The code works. But I know there’s a lot of room to improve it. I’d really appreciate if someone can show me the ropes on what should i look for to improve this. Thanks

Modal not getting opened on clicking the image of gallery component

I’m trying to open a model when I click on the image component in gallery. Here I’m not getting the “flagImage” variable updated in onPress method of TouchableOpacity or the modal component is not getting the updated value of “flagImage” when onPress of TouchableOpacity changes its value. I need help here. The modal doesn’t open at all whenever I touch the image component. It just does nothing 🙁 Below is the code for gallery.component.js:

import React from 'react';
import { View, Image, ScrollView, TouchableOpacity, Modal, Text } from 'react-native';
import styles from './cameraStyles';

export default ({captures=[], flagImage=true}) => (
    <ScrollView 
        horizontal={true}
        style={[styles.bottomToolbar, styles.galleryContainer]} 
    >
        {captures.map(({ uri }) => (
            <View style={styles.galleryImageContainer} key={uri}>
                <TouchableOpacity 
                    onPress={()=> {
                        flagImage = !flagImage;
                        console.log('Touch: "'+flagImage+'"');          
                    }}
                >
                    <Image source={{ uri }} style={styles.galleryImage}/>
                </TouchableOpacity>
                <Modal visible={flagImage} onPress={() => {console.log('Modal: "'+flagImage+'"');flagImage = !flagImage;}} onRequestClose={() => flagImage = ! flagImage}>
                      <View>
                            <Image source={{ uri }} style={styles.galleryImageLarge}/> 
                      </View>
                </Modal>
            </View>
        ))}
    </ScrollView>
);    

How to get VSCode to recognize BabylonJS for code-completion and hints?

I suspect it is because I am using plain Javascript, but the BabylonJS CDN is Typescript.

I have tried with the CDN in my HTML and also by wgetting/storing the babylon.js minified version locally.

Both work just fine and I can load my project in the browser.

But I cannot seem to get VSCode to recognize the BABYLON instance. It also doesn’t suggest methods as I type etc.

Is there a way to get VSCode to recognize BabylonJS?

enter image description here

JS question “i dont know why i am getting a different answer”

let a = 10;

let b = “20”;

let c = 80;

console.log(–c + +b + –a * +b++ – +b * a + –a – +true);

**I think I should get 108 then multiple it by -1 then multiple it by 16 which should result in -1728 however I am getting an answer of 97!!!!

how is that possible?

when I broke the problem into 3 pieces (–c + +b + –a)(+b++ – +b)(a + –a – +true) the computer agreed with me that the first part should be 108 then -1.

I need help guys. someone explain it to me, please.

THANKS**

How to generate a lines inside of vue-accordion on each checkbox click in Vuejs?

data: function () {
    return {
      show: false,
    };
  },
  methods: {
    toggleItem: function () {
      this.show = !this.show;
    },
  },
  <div class="wrapper">
    <div class="accordion">
      <input type="checkbox" @click="toggleItem" />

      <h2 class="title">
        <slot name="title"></slot>
      </h2>
    </div>
    <div v-show="show" class="content">
      <slot name="content"></slot>
    </div>
  </div>

I want to generate a lines like below, inside of the vue-accordion. every time. When ever user click on each checkbox separately.

So to achieve like above, do i need any other plugins or with css can i achieve that.

Working code snippet:- https://codesandbox.io/s/vue-accordion-component-forked-vwpi8?file=/src/components/Accordion.vue

generate lines like this

JavaScript Two Sum Debugging (n time complexity)

I am trying to achieve n-time-complexity for a two sum function via utilization of hashes in JavaScript. I’ve come up with the code below, but for some reason it does not capture all of the paired indices. The function is supposed to return pairs of indices of integers in an array that add up to zero.

Array.prototype.twoSumHash = function () {
    let newArr = [];
    const hash = {};
    this.forEach((ele, idx) => {
        if (hash[ele * -1]) {
            const pair = [hash[ele * -1], idx];
            newArr.push(pair);
        }
        hash[ele] ? hash[ele].push(idx) : hash[ele] = idx;
    });
    return newArr;
};

console.log([1, -1, 2, 3, 4, -2].twoSumHash());

This function only seems to return the 2 and -2 ([2,5]), but not the 1 and -1 ([0, 1]). Please help, and thank you!

Visual Studio Code built in JavaScript IntelliSense not working

Visual studio code built in JavaScript IntelliSense, debugging, formatting not working.
I’ve tried many solutions but didn’t work. I also reinstalled VS Code but it didn’t fix the issue. Guide me how to fix this problem.

setting.json file code

{
  "workbench.startupEditor": "newUntitledFile",
  "editor.wordWrap": "on",
  "php.executablePath": "C:/xampp/php/php.exe",
  "php.validate.executablePath": "C:/xampp/php/php.exe",
  "workbench.editor.untitled.hint": "hidden",
  "security.workspace.trust.untrustedFiles": "open",
  "editor.linkedEditing": true,
  "liveServer.settings.donotShowInfoMsg": true,
  "workbench.iconTheme": "material-icon-theme",
  "editor.minimap.enabled": false,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "window.restoreFullscreen": true,
  "files.exclude": {
    "**/.git": false
  },
  "emmet.triggerExpansionOnTab": true,
  "emmet.includeLanguages": {
    "vue-html": "html",
    "vue": "html",
    "javascript": "javascriptreact"
  },
  "zenMode.centerLayout": false,
  "liveSassCompile.settings.generateMap": false,
  "liveSassCompile.settings.formats": [
    {
      "format": "nested",
      "extensionName": ".css",
      "savePath": "/css"
    }
  ],
  "json.maxItemsComputed": 25000,
  "liveServer.settings.donotVerifyTags": true,
  "workbench.colorTheme": "Winter is Coming (Dark Blue - No Italics)",
  "bracket-pair-colorizer-2.depreciation-notice": false,
  "emmet.showSuggestionsAsSnippets": true,
  "editor.suggestSelection": "first",
  "vsintellicode.modify.editor.suggestSelection": "automaticallyOverrodeDefaultValue"
}

Get updated node list after manipulating the DOM

I’m trying to click on either the 0th index of the node list, and move that item down after its next sibling. Or the 2nd index and move that above its previous sibling which I’ve working for the first go:

https://i.gyazo.com/8918c506d526a8dd2f77602c65d68c2a.mp4

However once I’ve clicked these two elements I believe their positions as far as my JavaScript is concerned is still the same. So I end up getting a console error:

Uncaught TypeError: Cannot read properties of null (reading 'after')

This is my JS currently. As you can see I’m moving the elements up and down depending on index:

export const reviewsUtil = () => {
    const allReviewCards = document.querySelectorAll('.reviews__cardInner');
const allDescriptions = document.querySelectorAll('.reviews__descWrapper');

allReviewCards.forEach((e, index) => {
    e.addEventListener('click', (review) => {
        if (review.target.classList.contains('inactive')) {

            //Get's all reviews that aren't the clicked and hides them
            allDescriptions.forEach(desc => {
                desc.classList.add('reviews__infoInactive');
                desc.style.removeProperty('display');
            });

            //Loops through all instances and removes the active class
            allReviewCards.forEach(e => {
                e.classList.remove('active');
                e.classList.add('inactive');
                e.nextElementSibling.classList.remove('reviews__infoActive');
            })

            //Set's clicked as active
            review.target.style.removeProperty('display');
            review.target.classList.remove('inactive');
            review.target.classList.add('active');

            //Set's clicked review text as active
            e.nextElementSibling.classList.add('reviews__infoActive');
            e.nextElementSibling.style.removeProperty('display');

            if (index === 0) {
                e.parentElement.nextElementSibling.after(review.target.parentElement);
            } else if (index === 2) {
                index = 1;
                e.parentElement.previousElementSibling.before(review.target.parentElement);
            }
            
        }
    })
  })
}

export default reviewsUtil;

What I’d like to try and achieve is potentially having an updated list returned to me once the DOM has been manipulated. Is there a way I can monitor this or is my approach somewhat off?

Any help greatly appreciated.

Create and implement (in any programming language) an algorithm to manage passwords

Create and implement (in any programming language) an
algorithm to manage passwords. This program must:

  1. Step 1 – store the user password
    a. Request a password from the user(s)
    b. The user enters his password
    c. The program generates a random salt for each user.
    d. It adds the salt (at the middle) to the user’s password
    and the hash the password + salt and stores the hashed
    password and the salt to a file (may store the user’s
    name or ID if any).
  2. Step 2 – verify the password
    a. Request the user password
    b. Read the saved salt, add it to password and hash salt +
    password.
    c. Compare the result obtained with the stored hash. If
    they are the same the user is authenticated.

HTML FORM – setting form action on javascript

i’ve been having a problem where i have a form in which several entities within an unordered list are displayed, a name and a button dinamically with vanilla javascript. The problem is, im changing the action value from the html form, from javascript this so i can add an id that i get in a JSON from a http request so i can manipulate a specific object, but it doesnt send the “delete” request, which is actually a post request that im managing from my server side correctly (tested in postman and works like a charm), but when calling from the front-end it stops working. Here are my html and script.

PANEL.HTML

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

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- <meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'"> -->
    <link rel="stylesheet" type="text/css" href="css/panel-style.css">
    <script defer src="panel-script.js"></script>
    <title>Panel de Control</title>
</head>

<body>
    <header>
        <img src="assets/mrvapeslogo.png" alt="mrvapes logo">
        <a href="index.html"></a>
    </header>
    <section>
        <form id="files-form" accept-charset="UTF-8" enctype="multipart/form-data" action="#" autocomplete="off" method="POST" onsubmit="return validate(this);">
            <label for="user">Banners Activos</label><br/>
            <ul id="files-container">

            </ul>
        </form>
        <form accept-charset="UTF-8" enctype="multipart/form-data" action="http://localhost:3000/banner" autocomplete="off" method="POST" target="_blank">
            <div class="container">
                <div class="button-wrap">
                    <!-- <label class="button" for="upload">Subir</label> -->
                    <input type="text" id="name" placeholder="Nombre de Archivo" value="" name="name" required>
                    <input id="image" name="file" value="Subir" placeholder="Subir Archivo" type="file" required>
                    <button id="upload" value="post-request" type="submit">Enviar</button>
                    <!-- <input id="upload" type=" submit " value="Enviar " onclick="submit() "> -->
                </div>
            </div>
        </form>
    </section>
</body>

PANEL-SCRIPT.JS

const list = document.getElementById("files-container");
const filesForm = document.getElementById("files-form");

fetch('http://localhost:3000/banner')
    .then(response => response.json())
    .then(json => {
        console.log(json)
        console.log(json.message)
        for (let i = 0; i < json.message.length; i++) {
            var item = `<li>${json.message[i].name}
                            <button id="delete-button" onclick="deleteButton('${json.message[i].name}','${json.message[i]._id}')">Borrar</button>
                        </li>`;
            list.innerHTML += item;
        }
    });

function deleteButton(name, id) {
    var answer = confirm(`Seguro que deseas borrar ${name}?`);
    if (answer) {
        filesForm.action = `http://localhost:3000/banner/${id}`;
        alert('Borrado Correctamente!');
        window.location.reload(true);
    } else {
        validate();
    }
}

function validate() {
    return false
}

HAPPY HOLIDAYS! 😀

CSP preventing image from rendering

I am using the Polaris library to render a component that emits image markup like:

<img class="Polaris-VideoThumbnail__PlayIcon" src="data:image/svg+xml;base64,PHN2Zy....">

This triggers a Content Security Directive issue that precludes the image from rendering. I’ve tried applying a number of policies but have not found one that works when the app is deployed.

Presently the policy is applied via a meta tag like:

<meta http-equiv="Content-Security-Policy" content="img-src 'self' data: https:; script-src *.twimg.com *.twitter.com 'self' 'unsafe-inline'; style-src *.twimg.com *.twitter.com 'self' 'unsafe-inline'">

This works locally – even if I fudge my HOSTS file to use a non-localhost URL to emulate an external request. But when I deploy my app the play icon is broken and I get:

Refused to load the image 'data:image/svg+xml;base64,PHN2ZyB...' because it violates the following Content Security Policy directive: "default-src https: 'unsafe-eval' 'unsafe-inline'". Note that 'img-src' was not explicitly set, so 'default-src' is used as a fallback.

The issue is presently manifesting itself at https://witty-ocean-02e42dd0f-168.eastus2.azurestaticapps.net/vaccineinfo

When I enter the contents of my meta tag into the CSP evaluator, I get:

img-src All Good

Why is my browser (Chrome) complaining that img-src isn’t set on my deployed instance?

Why is code giving error if I try to access the array returned by str.split(), immediately in next line

Why does it happen that the below code throws the error Uncaught ReferenceError: Cannot access 'arr' before initialization

function swap(str,a,b){
    let arr = str.split("")
    [arr[a],arr[b]] = [arr[b],arr[a]]
    return arr.join("")
}
swap("abcde",2,4) // throws error "Uncaught ReferenceError: Cannot access 'arr' before initialization"

But as soon as I insert any dummy statement between line 2 and 3, surprisingly code starts to work

function swap(str,a,b){
    let arr = str.split("")
    23456; // this could be anything like a variable declaration, or any valid javascript statement
    [arr[a],arr[b]] = [arr[b],arr[a]]
    return arr.join("")
}
swap("abcde",2,4) // returns "abedc" as expected

I am surprised to see why does this even work now ? It should have given error in both the cases, or should have worked in both cases.
I’m sure that in the 1st case, split is not finishing it’s work till the time line 3 is executed and in 2nd case, it is getting enough time because of 1 extra statement in between.
But I would still love to get a clear explanation as to why it is behaving like this.
I’m not sure if this is same for all browsers, but I’ve tried it on Chrome and Safari on mac, and both of them gave same error.