Angular 9 Video playing timeupdate event get 1 time?

I am newly Interactive video quiz developed, I am working Interactive quiz get Question show particular seconds. But I will face one issue, click on skipping question window not closed. The timeupdate event passes seconds multiple time how to get one time pass seconds. Please help me.

getVideoPlayingOnTime(event) {
    if (this.isVideoQuizFound) {
      var curTimeTrack = 0;

      const timeInMiliseconds = event.target.currentTime;

      const vidDuration = event.target.duration;

      var sec_num = parseInt(timeInMiliseconds, 10);
      var hours = Math.floor(sec_num / 3600);
      var minutes = Math.floor((sec_num - hours * 3600) / 60);
      var seconds = sec_num - hours * 3600 - minutes * 60;

      var x = hours < 10 ? "0" + hours : hours;
      var y = minutes < 10 ? "0" + minutes : minutes;
      var z = seconds < 10 ? "0" + seconds : seconds;

      var getHours = x + ":" + y + ":" + z;

      var a = getHours.split(":");

      var getSeconds = +a[0] * 60 * 60 + +a[1] * 60 + +a[2];

      var getAtSeconds = seconds * 60;

      const timeQuiz = this.interactiveVideoQuiz.map((el) => {
        return el;
      });

      const timeArray = this.interactiveVideoQuiz.map((e)=>{
        return e.quiz_time;
      })


      // if (timeArray.indexOf(getAtSeconds)!== -1) {
      //   console.log('yes the value exists!');
      // }else{
      //   console.log("No, the value is absent.");

      // }

      timeQuiz.some((x) => {
        if (parseInt(x.quiz_time) === getAtSeconds) {
          this.videoStream.nativeElement.pause();
          this.videoQuizId = x.quiz_id;
          this.getVideoQuizz = x.questions;
          this.pager.count = this.getVideoQuizz.length;
          this.activeQuiz = "block";
          this.videoQuizRequired = x.is_required;
        }
      });
    }
  }

Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (93)

Getting below error after installed latest node.js(v16.13.1)

Error: Node Sass does not yet support your current environment: Windows 64-bit with Unsupported runtime (93)
For more information on which environments are supported please see:
https://github.com/sass/node-sass/releases/tag/v4.14.1
I have created static pages for my application and use sass and gulp

I have a static pages and using Sass in the page and use gulp to run on the browser.(npm install). Below are the version whihc wokred my application:-
Node.js – 12.18.0
gulp – “4.0.2”
“gulp-sass”: “4.1.0”

Package.json file

“scripts”: {
“start”: “gulp watch”
},
“dependencies”: {
“@fortawesome/fontawesome-free”: “5.15.1”,
“@ttskch/select2-bootstrap4-theme”: “^1.5.2”,
“bootstrap”: “4.5.3”,
“bootstrap-datepicker”: “^1.9.0”,
“jquery”: “3.5.1”,
“jquery.easing”: “^1.4.1”,
“select2”: “^4.1.0-rc.0”,
“gulp”: “4.0.2”
},
“devDependencies”: {
“browser-sync”: “2.26.13”,
“del”: “6.0.0”,
“gulp”: “4.0.2”,
“gulp-autoprefixer”: “7.0.1”,
“gulp-clean-css”: “4.3.0”,
“gulp-header”: “2.0.9”,
“gulp-plumber”: “^1.2.1”,
“gulp-rename”: “2.0.0”,
“gulp-sass”: “4.1.0”,
“gulp-uglify”: “3.0.2”,
“merge-stream”: “2.0.0”
}

Even using this command npm rebuild node-sass is not changing anything.

Kindly help me to fix this issues.

Why can’t i map this array of objects within an object

Hi guy’s i’ve been working with next.js, redux and sanity.io. It’s been awful… Lol

Anyways here’s the code i’m stuck with

ServiceCards.js 

import React from 'react';
import { useSelector } from 'react-redux';
import { getNavItems } from '../redux/actions/navItems';

const ServicesCards = () => {
  const services = useSelector((state) => state.services.services);

console.log(services)

  return (
    <>
    {Object.keys(services).map((item) => {

   

return(
  <h2>{item}</h2>
)



     
  
    })}
   
    </>
  );
};
export default ServicesCards;


as you can see i am connecting to the redux store perfectly and the data is been retuned like:

{0: {…}, 1: {…}, 2: {…}}
0:
body: (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
locations: [{…}]
mainImage: {_type: 'image', asset: {…}}
slug: {_type: 'slug', current: 'patios'}
title: "Patios"
_id: "70f4ad81-f8eb-414a-8e76-da8bf98cc4de"
[[Prototype]]: Object
1: {_id: 'cc9548aa-ccf5-4688-a6ac-3b1a41f9896d', body: Array(10), locations: Array(1), mainImage: {…}, slug: {…}, …}
2:
body: (12) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
locations: [{…}]
mainImage: {_type: 'image', asset: {…}}
slug:
current: "tree-removal"
_type: "slug"
[[Prototype]]: Object
title: "Tree Removal"
_id: "f63a0092-4b89-4ea9-9e49-f618d5f5f0b9"
[[Prototype]]: Object
[[Prototype]]: Object
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
__proto__: (...)
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

So the structure of the data i am getting back is

{
0:{...},
1: {...},
2:{...}

}

Usually i just use Object.keys to map objects and i have no issues using this, so why will it not work here?

Closer look at Object.keys

return (
    <>
      {Object.keys(services).map((item) => {
        return <h2>{item}</h2>;
      })}
    </>
  );

and this is what i get back from render

0
1
2

With no data at all.

store.js

import { createStore, applyMiddleware } from 'redux';
import rootReducer from './reducers';
import { composeWithDevTools } from 'redux-devtools-extension';
import thunkMiddleware from 'redux-thunk';
import { createWrapper } from 'next-redux-wrapper';
import reducer from './reducers/pages';

const middleware = [thunkMiddleware];

const initialState = {
  pages: {},
  navItems: {},
  services: []
};

const store = createStore(
  rootReducer,
  initialState,
  composeWithDevTools(applyMiddleware(...middleware))
);

const initStore = () => {
  return store;
};

const wrapper = createWrapper(initStore, { debug: true });

export default wrapper;


i Have had to set initialState in next-redux-wrapper to get it to work, don’t ask me why… I wish i would have stayed with Gatsby.js.

I really help someone can help with this as it’s driving me crazy, i bet it’s so simple!!

ChartJS (Radar) – Set base tick position for “0”

Using chart.js (v3.7.0)

Set up a Radar chart using multiple datasets that include 0 values (and needs to be kept as 0 for tooltip & data purposes).

Trying to find a way to set/include a drawn tick marker for 0 values on the chart.

beginAtZero option has no effect whatsoever on the initial tick display position.

Current Chart Display (image)Desired Chart Display (image)

Is this what’s supposed to happen with the beginAtZero option, and there’s been some sort of regression? If not, is this even possible with chart.js?

Options:

options = {
    scales: {
      r: {
        min: 0,
        max: 99,
        beginAtZero: true,
        angleLines: {
          display: false
        },
        ticks: {
          display: false,
          stepSize: 33.333
        }
      }
    }
  }

Sample Data:

data = {
    labels: ['Field 1','Field 2','Field 3','Field 4','Field 5','Field 6' ],
    datasets: [
      {
        label: 'Dataset 1',
        data: [ 10, 99, 0, 76, 0, 0 ]
      },
      {
        label: 'Dataset 2',
        data: [ 99, 35, 0, 0, 54, 0 ]
      }
    ],
  }

Thanks in advance!

D3.js–How to transition between multiple types of charts using buttons?

I am trying learn to transition between multiple charts using buttons. Here, i want to transition between bar and scatter chart (and may be add a line chart button as well). I have been able to show respective charts by the click of the button. But, i am not able to figure out how to exit one chart when the button for the other chart is clicked and vice-versa. Following is screenshot of the interactive figure that i have created. Here, we can see that both charts show together.

enter image description here

Following is the data (data.csv) i am using to create the interactive chart:

enter image description here

Below is the HTML code:

<!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">
    <title>Transition Scatter to Bar</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
    <div id="container" class="container">
        <h1>Transition from one chart to other</h1>
        <div id="main" role="main">
            <div class="btn-group" data-toggle="buttons-radio">
                <button type="button" id="bar" class="btn btn-default">Bar</button>
                <button type="button" id="scatter" class="btn btn-default">Scatter</button>
            </div>
            <div id="vis"></div>
        </div>
    </div>

    <script src="d3.v6.js"></script>
    <script src="transition.js"></script>
     
</body>
</html>

And the D3.js code:

//load data----


async function createApp(){
    const dataset= await d3.csv('data.csv')

    //create dimensions---
    let dimensions={
        width: 800,
        height:600,
        margins: {
            left: 50,
            right: 20,
            top:20,
            bottom: 50,
        },
    };

    //bound dimensions
    dimensions.boundedwidth=dimensions.width-
        dimensions.margins.left-
        dimensions.margins.right;
    dimensions.boundedheight=dimensions.height-
        dimensions.margins.top-
        dimensions.margins.bottom;


    //Draw canvas----
    wrapper=d3.select("#vis")
        .append("svg")
        .attr("width", dimensions.width)
        .attr("height", dimensions.height);

    bounds=wrapper.append("g")
        .style("transform", `translate(${
            dimensions.margins.left
        }px, ${
            dimensions.margins.top
        }px)`);
        
    //create scales------
    const xScatterscale= d3.scaleLinear()
        .range([0, dimensions.boundedwidth])
        .nice()        

    const yScatterscale= d3.scaleLinear()
        .range([dimensions.boundedheight, 0])
        .nice()     

    const xBarscale= d3.scaleBand()
        .range([0, dimensions.boundedwidth])
        .padding(0.2)
    
    const yBarscale=d3.scaleLinear()
        .range([dimensions.boundedheight, 0])
        .nice()

    //Draw perpherals--axes-------
    //create axis generators
    const xAxisgeneratorscatter= d3.axisBottom()
        .scale(xScatterscale)
        .ticks(8)      

    const yAxisgeneratorscatter= d3.axisLeft()
        .scale(yScatterscale)
        .ticks(9)
      
    const xAxisgeneratorbar=d3.axisBottom()
        .scale(xBarscale)

    const yAxisgeneratorbar=d3.axisLeft()
        .scale(yBarscale)

    const xAxis= bounds.append("g")
        .attr("class", "x-axis")
            .style("transform", `translateY(${
                dimensions.boundedheight
            }px)`)  
            
    const yAxis=bounds.append("g")
            .attr("class", "y-axis")

   //binding data to empty request----- 
    const requests= bounds.append("g")
            .attr("class", "request")

    const chartgroups= requests.selectAll(".request")
                .data(dataset)
                .enter().append("g")

    let duration = 750           

    const updateTransition = d3.transition().duration(duration) 
    
     scatterplot()
    
    //create functions to draw data scatter plot----
    function scatterplot(){

        const xAccessorscatter= d=> +d.risk
        const yAccessorscatter= d=> +d.return

        xScatterscale.domain([0, d3.max(dataset, xAccessorscatter)+0.05])
        yScatterscale.domain([0, d3.max(dataset, yAccessorscatter)+0.02])

        xAxis.call(xAxisgeneratorscatter)            

        yAxis.call(yAxisgeneratorscatter)
     
        const newscattergroup= chartgroups.append("circle")
            .attr("cx", d=>xScatterscale(xAccessorscatter(d)))
            .attr("cy", dimensions.boundedheight)
            .attr("r", 0)

        const scattergroups= newscattergroup.transition(updateTransition)
            
            scattergroups
                .attr("cx", d=>xScatterscale(xAccessorscatter(d)))
                .attr("cy", d=>yScatterscale(yAccessorscatter(d)))
                .attr("r", 5)
                .attr("fill", "cornflowerblue")               
                       
} 

    //create functions to draw data bar plot----
    function plotbar(){

        const xAccessorbar = d=> d.id
        const yAccessorbar = d=> +d.equity

        xBarscale
            .domain(dataset.map(xAccessorbar))
            
        yBarscale
            .domain([0, d3.max(dataset, yAccessorbar)+0.1])
      
        xAxis.call(xAxisgeneratorbar)

        yAxis.call(yAxisgeneratorbar)

        const newbarsgroups= chartgroups.append("rect")
            .attr("x", d=> xBarscale(d.id))
            .attr("height", 0)
            .attr("y", dimensions.boundedheight)
            .attr("width", xBarscale.bandwidth())

        const t= newbarsgroups
                .transition()
                .duration(duration)        
      
        t
            .attr("x", d=> xBarscale(d.id))
            .attr("y", d=> yBarscale(d.equity))
            .attr("width", xBarscale.bandwidth())
            .attr("height", d=>dimensions.boundedheight- yBarscale(yAccessorbar(d)))
            .attr("fill", "cornflowerblue")
                               
    }
 
        d3.select("#scatter").on("click", function () {
            scatterplot()
                      
          });
        
        d3.select("#bar").on("click", function () {
            plotbar()
          
          });

}

createApp()

I am new to d3.js and still trying to figure out the Enter, Update, Exit trinity. I have found some examples where button is has been used to transition/update bar charts with new data. However, i am struggling to figure out how to exit one chart when the other chart gets drawn and vice versa on the click of the button.

Any suggestions on how to accomplish this will be highly appreciated.

Thanks a lot!

Push to array not working inside If statement, but works one level higher in for loop. Google Script / JavaScript

I am trying to parse through a 2D array, remove empty cells, and then push it to a new 2D array. When I do the .push([]) step before the IF statement, everything works fine but unfortunately that pushes an empty array every iteration of the for loop. When I try to put that line within the If statement, I get the following error: TypeError: Cannot read property ‘push’ of undefined.

This doesn’t work:

  var i=0;
  var oA = [];

  for(i; i<bRows;i++)
  {  
  
    if(nbaValues[i][0]){
      oA.push([]);
      for(var j=0;j<bCol;j++){
          
        oA[i].push(nbaValues[i][j]);
        }
    }

  }
  Logger.log(oA);

While this works:

  var i=0;
  var oA = [];

  for(i; i<bRows;i++)
  {  
    oA.push([]);
    if(nbaValues[i][0]){
      
      for(var j=0;j<bCol;j++){
          
        oA[i].push(nbaValues[i][j]);
        }
    }

  }
  Logger.log(oA);

Thanks in advance!

Image recognition with Artificial Intelligence & Machine Learning

I want to know how to recognise images with pure JS and without any third-party APIs or libraries nor even AngularJS or ReactJS. Actually I wanted to implement it in the login system of my project. I had already implemented password authentication.

Is there any inbuilt API in JS to ask user to scan his finger with scanner for login.

And another thing that I wanted to know is how to create a payment application i.e Amazon pay. I just don’t know that how they work so accurately. At least I want to make a website to transfer amount from account to another account. I saw in an article that there is an inbuilt Payment web API which only works on Google Chrome. But I didn’t understood how can I archive that for at least Google Chrome.

get UTC Date without reference to local computer timezone in JS

When I get the datetime in JS, it always returns the date corresponding to my local computer.

Example:

// get the first day of 2022    
new Date(2022,0,1) // return 2021-12-31T16:00:00.000Z

Note that month part is zero indexed and my computer time zone is UTC +08:00.

I am happy with the datetime format. But I want my code to return the same result on any servers. Assume I always want it in UTC +00:00 and the expected result is 2022-01-01T00:00:00.000Z

How could we do it in simple JS?

Node import statement can’t recognize ../ prefix

I am trying to use the ES Module import with a path like ../module.js and it gives me this error:

node:internal/errors:464
    ErrorCaptureStackTrace(err);
    ^

Error [ERR_MODULE_NOT_FOUND]: Cannot find module 

Here is the structure of the folders:

.
├── module.js
├── index.js
├── folder
│   └── test.js

Also here is the import and export statements

//folder/test.js
import { test } from "../module"

//module.js
export async function test(data) {
    //Do Stuff then return data
}

Obviously, I have changed some file names and removed the function code. Please let me know if this is a problem.

Thank you!

How should I have API users send their keys?

I’m building an API in NodeJS and an SDK for people who want to use the API to make requests to it. When someone wants to make a request, they have to pass an API key to the method they’re using. For example, a request would look something like messages.send({body: "Hello"}, "key_randomKey");.

Is it safe to send keys in requests? In this scenario, the key would be passed as a request property, it would be accessed on the actual backend server for the API and then hashed there and compared to the one in the database (keys are also created on the backend server, not on the server making the request). Is this the wrong approach? I’m wondering how to do this securely.

Is there any ways to use react navigation props as a define object in reusable component?

I start using rn this week to make a medium scale app for some tutoring school. And found some problem with navigating with defined props.

As u will see i define the stack screen name with ‘test1’, ‘test2’ in root app.js same with address variable.

the problem is when i use ‘test1’ instead of {address} it is working fine, but when i use {address}, it’s yelling at me, even when i console it’s still ‘test1’.

Here’s my code :

....
....

    <Stack.Screen name="test1" component={GrLesson1} />
    <Stack.Screen name="test2" component={GrLesson2} />

    function GrHome({navigation}) {
        return (
    <View>
    
    <GrHomeProps title="test1" address="test1" navigation={navigation}/>
    <GrHomeProps title="test2" address="test2" navigation={navigation}/>
    
    </View>
        )
    }


function GrHomeProps({title,navigation,address}) {
    return (
<View>
<TouchableOpacity
onPress={()=>{
navigation.navigate({address})

}}
>

   <Text> {title} </Text>
</TouchableOpacity>
</View>
    )
}

Can somebody help me? find the mistake i made or teach me another way to do this with reusable component?

Electron .loadURL ERROR RR_FILE_NOT_FOUND (-6) Trying to open a local file or directory in new browserwindow

im triying to open a local file or directory in new electron window like the chrome does.
the new window open with nothing to show:

PDT Im using linux and vscode
new window open

and show this error:
error

the code from the script who launch the window:

    function shell(path){
    console.log(path);
    createWindow = () => {
        nombre=tittle(path);
       const fileWin = new remote.BrowserWindow({
            width: 800,
            height: 600,
            title: nombre,
            resizable: true,
            show: true,
            webPreferences: {
                plugins: true, 
                contextIsolation: false,
                nodeIntegration: true,
                enableRemoteModule: true,
                webSecurity: false 
            }
        });  
       
        remote.require("@electron/remote/main").enable(fileWin.webContents);
        fileWin.setMenu(null);
        fileWin.setIcon('src/assets/img/logo-FC.png');
        fileWin.loadURL('file://'+path); 
        fileWin.show(); 

    }
    
    createWindow();

  }

the variable path is for diferent locations of files or directorys the case of the error examples is:

/home/aromero/Documentos/3225 DOSSIER Julio/0. GENERAL/0.1 Calibración de equipos/HMV

if i put tha link with the ‘file://’ in front in the chrome browser, that display that i want.
chrome explorer

Sorting Dates in Node.js

I’m pretty new to javascript, and I’m working on a dashboard in which I want to display all of the dates since the first order was created. I have created the code that I need to add the dates for orders where the orders have not been created (with orders as 0), but now I’m having an issue where the dates that have orders created are listed in the beginning of the graph instead of in chronological order with the rest of the dates in the graph. I think this is a sorting issue, but I’m not sure, and my attempts to sort the date haven’t really made any changes to the graph. I would really appreciate any help or advice on how to fix this issue.

enter image description here

import express from 'express';
import expressAsyncHandler from 'express-async-handler';
import Order from '../models/orderModel.js';
import User from '../models/userModel.js';
import Product from '../models/productModel.js';
import {isAdmin, isAuth, isSellerOrAdmin, mailer, payOrderEmailTemplate} from '../utils.js';

const orderRouter = express.Router();
orderRouter.get(
  '/summary',
  isAuth,
  isAdmin,
  expressAsyncHandler(async (req, res) => {
function getDates(startDate, stopDate) {
  var dateArray = new Array();
  var currentDate = new Date(startDate);
  while (currentDate.getTime() <= new Date(stopDate).getTime()) {
      dateArray.push(getFormattedDate(currentDate));
      currentDate.setDate(currentDate.getDate() + 1)
      dateArray.sort((startDate, stopDate) => new Date(stopDate[0]).getTime() - new  Date(startDate[0]).getTime());
  }
  return dateArray;
}
  
    const dailySales = await Order.aggregate([
      {
        $group: {
          _id: { $dateToString: { format: '%m-%d-%Y', date: '$createdAt' } },
          orders: { $sum: 1 },
          sales: { $sum: '$totalPrice' },
          date: {$first: '$createdAt'}, 
        },
      },
      { $sort: { date: 1 } },
    ]);
  
  
    let today = new Date();

    let date=parseInt(today.getMonth()+1)+ "-"+ today.getDate()+"-"+today.getFullYear();
    
    
    const datesArray = getDates(dailySales[0]._id, date)
    
    
    for(let dateVal of datesArray){
      
     let isInArray = false;
     
     for(let dayVal of dailySales){
  
      
       if(dayVal._id === dateVal){
         isInArray = true;
       }
   
     }
       if(isInArray == false){
        dailySales.push({ "_id":dateVal, "orders":0, "sales":0}) 
      }
   }
res.send({dailySales});
  })
);