How to order an array of object during a forEach()?

So, basically I have this array of objects and I need to order them dependently on the value caricoData, which is a date. Problem is, the value is a string and I can’t change that due to other interactions with the array that need it to be a string, so what I did is I made a forEach() method to turn each caricoData of each element into a date (DD/MM/YYY). But then I need it to put it back as a string due to it needing to be so.
So what I thought was “What if I make it so that before returning it into a string, I make it so the array sorts itself in the making?”
Problem is, I don’t know how to do it. I’ve tried with:

  filterDateCheck(array){
     array.sort((a,b) => (a.caricoData > b.caricoData) ? 1 : ((b.caricoData > a.caricoData) ? -1 : 0))
     return array
   }

But it doesn’t work, returning Invalid Date as a result. So, how can I do it?

TS:

check.forEach(e => {
  let formattedDate = Utilities.toDateTimeString(e.caricoData)
  let splitDate = formattedDate.split("/")
  let dateObject = new Date(+splitDate[2], +splitDate[1] - 1, +splitDate[0]); 
  // Method goes here? //
  e.caricoData = dateObject.toString();  
});

Array (check) structure:

 export class ResCheck{
  descrizioneIntervento: string;
  destinazioneDescrizione: string;
  fermoLocalita: string;
  caricoData: string;
  veicoloTarga: string; 
  destinazione: string;
}

chai-assertion to validate anyone is true should pass

I am trying to do assertion to validate any one statement is true, test should pass. Following is the code

expect(commuication.status).to.contain(
“PROCESSED”,
“NOT_PROCESSED”
);

where communication.status return different value out of “PROCESSED””NOT_PROCESSED” values. This assertion throwing me error->Unexpected Undefined. What am i doing wrong here? any help

TypeError: state.find is not a function

I try to use the find() method but I get cartItems.find is not a function,
what happens? and how to fix it?……………………………………………..

import React,{useState} from 'react'

function cart() {
  const [cartItems, setCartItems]  = useState([])
    
  const add = (pro) => {
      const exist = cartItems.find((item) => {
        return item.id === pro.id;
      });
      if (exist) {
        setCartItems(
          cartItems.find((item) => {
            return item.id === exist.id
              ? { ...exist, qnty: exist.qnty + 1 }
              : item;
          })
        );
      } else {
        setCartItems([...cartItems, { ...pro, qnty: 1 }]);
      }
    };
  return (
    <div>cart</div>
  )
}

export default cart

Using Link Tree Bio -> zapier webhook (make Java =Zapier child key )->HTTP address connect goal

My name is joe
My goal is
Using Link Tree Bio

https://kenclarkefitness.app/

This address connect

This my goal

First of all
Select from the Zapier webbook catch hook option
Paste the Zapier URL and
Test trigger successfully executed

  1. The problem is the setting of the child key
    Before that, I used Mailchimp api key
    Just because there’s a security vulnerability,
    I want to know how to make a child key
    Or I’m asking if you know the site that can be made

  2. https://kenclarkefitness.app/
    Which app should I use to connect this address?
    I send the coach and mail address of that address
    I’m trying to connect through Slack, is it okay?

Ps. I started playing Zapier last week.
I’m not familiar with the terms, and I’ve never done an automated system like this before, so I don’t know
I’m learning from the beginning
Especially, it’s not that I can’t zapier with my iPhone, but I can’t see a lot of the text in the setting option field and it’s hard to choose
If there’s anything I don’t know, I’ll ask
I look forward to your kind cooperation.

How to properly load JQuery Objects from Node Modules?

I am working on the simple NodeJs App. While working with Frontend, it correctly loads all NodeJS modules related to JQuery, but when I am going to make a simple JavaScript-based Implementation and trying to load all of those JQuery files from Node-Modules. I am unable to get anything out of them.

I am really new to NodeJS and JQuery, but I am passionate to develop a console-based Implementation for my testing.


Node-Modules:

Following are the node modules on which I am working right now.

  "dependencies": {
"crypto-js": "^3.1.9-1",
"jquery": "^3.6.0",
"jquery-json": "^2.6.0",
"verto": "0.0.2"
}

Working Example:

I have implemented the following files to work with these modules;

  • index.html
  • app.js

index.html


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Demo of Aswat Verto Integration</title>
    <link rel="stylesheet" href="app.css">
  </head>

  <body>
    <div class="config">
      <div class="config-row">
        <label for="hostname">Hostname</label>
        <input id="hostname" type="text">
      </div>
      <div class="config-row">
        <label for="socketURL">Socket URL</label>
        <input id="socketURL" type="text">
      </div>
      <div class="config-row">
        <label for="position">Position</label>
        <input id="position" type="text">
      </div>
      <div class="config-row">
        <label for="password">Password</label>
        <input id="password" type="text">
      </div>
      <div class="config-row">
        <button class="config-action" onclick="connectToFreeswitch()">Connect</button>
      </div>
    </div>

    <div class="dialler">
      <div class="dialler-status">
        Current status <br>
        <span id="positionStatus">Not Connected</span> <br> <span id="callStatus">Not in a Call</span>
      </div>
      <div class="dialler-content" id="dialler">
        <div class="dialler-row">
          <input type="text" class="dialler-input" id="diallerInput">
        </div>

        <div class="dialler-row">
          <span class="dialler-number" onclick="dial('1')">1</span>
          <span class="dialler-number" onclick="dial('2')">2</span>
          <span class="dialler-number" onclick="dial('3')">3</span>
        </div>

        <div class="dialler-row">
          <span class="dialler-number" onclick="dial('4')">4</span>
          <span class="dialler-number" onclick="dial('5')">5</span>
          <span class="dialler-number" onclick="dial('6')">6</span>
        </div>

        <div class="dialler-row">
          <span class="dialler-number" onclick="dial('7')">7</span>
          <span class="dialler-number" onclick="dial('8')">8</span>
          <span class="dialler-number" onclick="dial('9')">9</span>
        </div>

        <div class="dialler-row">
          <span class="dialler-number" onclick="dial('*')">*</span>
          <span class="dialler-number" onclick="dial('0')">0</span>
          <span class="dialler-number" onclick="dial('#')">#</span>
        </div>

        <div class="dialler-row">
          <button class="dialler-action" onclick="makeCall()">Call</button>
          <button class="dialler-action" onclick="hangupCall()">Hangup</button>
        </div>

        <div class="dialler-row">
          <button class="dialler-action" onclick="answerCall()">Answer</button>
          <button class="dialler-action" onclick="transfer()">Transfer</button>
        </div>

        <div class="dialler-row">
          <button class="dialler-action" onclick="mute()">Mute</button>
          <button class="dialler-action" onclick="unmute()">Unmute</button>
        </div>

        <div class="dialler-row">
          <button class="dialler-action" onclick="hold()">Hold</button>
          <button class="dialler-action" onclick="unhold()">Unhold</button>
        </div>
      </div>

      <video class="hide" id="positionDevice" autoplay="autoplay" style="width:100%; height:100%; object-fit:inherit;"></video>
    </div>

    <!-- Verto dependencies -->
    <script src="../node_modules/jquery/dist/jquery.min.js"></script>
    <script src="../node_modules/jquery-json/dist/jquery.json.min.js"></script>

    <!-- Verto library -->
    <script src="../node_modules/verto/src/jquery.verto.js"></script>
    <script src="../node_modules/verto/src/jquery.FSRTC.js"></script>
    <script src="../node_modules/verto/src/jquery.jsonrpcclient.js"></script>
    <script src="app.js"></script>
  </body>
</html>

app.js


let diallerInput = document.getElementById('diallerInput');
let currentCall = '';

/**
  This function will execute the _bootstrap function to connect to the Verto server
  and log in with specified credentials and configurations.
  To see the full documentation, go to: http://evoluxbr.github.io/verto-docs/tut/initializing-verto.html
**/
function connectToFreeswitch() {
  hostname  = document.getElementById('hostname').value;
  socketURL = document.getElementById('socketURL').value;
  position  = document.getElementById('position').value;
  password  = document.getElementById('password').value;

  function _bootstrap(status) {
    vertoHandle = new jQuery.verto({
      login: position + '@' + hostname,
      passwd: password,
      socketUrl: socketURL,
      ringFile: 'ringtone.mp3',
      tag: 'positionDevice',
      deviceParams: {
        useMic: true,
        useSpeak: true
      },
      iceServers: true
    },
    /**
      Almost everything that happens in Verto fires an event.
      onWSLogin will be fired on login
      onWSClose will be fired when closing the socket
      onDialogState is used to handle incoming and outgoind calls
    **/
    {
      onWSLogin: onWSLogin,
      onWSClose: onWSClose,
      onDialogState: onDialogState
    });
  }

  if (hostname && socketURL && position && password) $.verto.init({}, _bootstrap);
  else alert('You need to provide the full configuration settings.');
}


Using the above files, NodeJs Modules related to these JQuery Files are properly loading into Dom Object;

    <!-- Verto dependencies -->
    <script src="../node_modules/jquery/dist/jquery.min.js"></script>
    <script src="../node_modules/jquery-json/dist/jquery.json.min.js"></script>

    <!-- Verto library -->
    <script src="../node_modules/verto/src/jquery.verto.js"></script>
    <script src="../node_modules/verto/src/jquery.FSRTC.js"></script>
    <script src="../node_modules/verto/src/jquery.jsonrpcclient.js"></script>

I have tested it with the front-end, and everything is going really great; But What I need is to load the above given node modules, directly into JS.


Not Working Example:

Here I have implemented this technique to load JQuery Objects;

verto.html

<!doctype html>
<html>
  <head>
    <meta charset="UTF-8">
    <title></title>
  </head>
  <body>
    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
    <script src="./node_modules/jquery-json/dist/jquery.json.min.js"></script>

    <script src="./node_modules/verto/src/jquery.verto.js"></script>
    <script src="./node_modules/verto/src/jquery.FSRTC.js"></script>  </body>
</html>

app.js


'use strict';

const { JSDOM } = require('jsdom');

const options = {
  resources: 'usable',
  runScripts: 'dangerously',
};

JSDOM.fromFile('verto.html', options).then((dom) => {
  console.log(dom.window.document.body.textContent.trim());
  
  // Importing the jquery and providing it
  // with the window
  const jquery = require("jquery")(dom.window);
  console.log(jquery);
  console.log(jquery.verto);


  setTimeout(() => {
    console.log(dom.window.document.body.textContent.trim());
  }, 5000);
});

When I run this simple app, it’s not loading simple JQuery at all. I need assistance regarding the above problem; I have visited these articles but I am not sure where I am doing wrong;

Your little assistance might save my whole day; Thanks in Advance

Vue test can’t find store in child components

I have a parent component and there are several child components. Some children use Vuex store. When I try to mount parent component like below in Vue test, I’m getting an error “Cannot read state of undefined” in child components.

const store = new Vuex.Store({
    modules: {
      local: localStore
    },
  });

wrapper = mount(ParentComponent, {
      localVue,
      i18n,
      propsData,
      store,
      attachTo: document.body,
    });

I am sending a mock store in the mount. But it seems child component will not have access to it. How to mount a parent component with a child component that uses store?

javascript setTimeout()

I have below javascript function.

function checkEven(number){
  return(nu % 2 == 1 ? true : false)

  setTimeout(checkEven(number), 2000)
}

I want to call checkEven function within every 2 seconds. but it is not working.

But I tried below code. It working fine and print method call in every 2 seconds.

function print(){
  console.log(new Date());
  setTimeout(print, 2000)
}

why first code is not working. Can someone help me for this.

React-Hook-Form – defaultValues not updated are not registered

I have a form who get updated directly when an user change an input.
For that, I use the onBlur method.

When I change an input from the defaultValue, it save it in the DB, but it doesn’t take the whole form data with it.
Some fields are ‘registered’ (like the field Titre) and are updated but not all of them.

I would like that every input register in the form and not only the one I changed.
I need that because I use reset() in onSubmit() and it makes some field become empty.

What I’m a missing here?

const {
    control,
    register,
    handleSubmit,
    reset,
    formState: { isDirty, errors },
} = useForm({
    mode: "all",
});

Function to submit the form

const onSubmit = (data: any) => {
    console.log(data);
    for (const key in data) {
        if (data[key] === undefined) data[key] = "";
    }

    if (!isDirty) return false;
    agent.Spectacle.updateSpectacle(data)
        .then(() => dispatch(updateSpectacle(id)))
        .catch((error) => console.log(error))
        .finally(() => reset(data));
};

This input is automatically registered:

<input
   type="text"
   className="form-control"
   {...register("titre", { required: true, minLength: 3, disabled: isNotEditable })}
   defaultValue={spectacle?.titre}
   onBlur={handleSubmit(onSubmit)}
/>

This input is not automatically registered so if I update the title, ‘data’ will not contain any value when the function onSubmit in trigerred :

<input
   type="date"
   disabled={isNotEditable}
   className="form-control"
   defaultValue={spectacle?.date_Spectacle}
   {...register("date_Spectacle")}
   onBlur={handleSubmit(onSubmit)}
/>

This input works too :

                                    <Controller
                                        name="id_Usr"
                                        control={control}
                                        render={({ field: { onChange, value, onBlur } }) => (
                                            <Select
                                                isDisabled={isNotEditable}
                                                isClearable={true}
                                                isSearchable={true}
                                                options={optionsUsers}
                                                value={optionsUsers.find((c) => c.value === value)}
                                                onChange={(val) => onChange(val?.value === undefined ? "" : val?.value)}
                                                onBlur={handleSubmit(onSubmit)}
                                                noOptionsMessage={() => "Aucun élément trouvé"}
                                            />
                                        )}
                                        rules={{ required: true }}
                                        defaultValue={
                                            spectacle?.id_Usr?.toString() === undefined ? "" : spectacle?.id_Usr?.toString()
                                        }
                                    />

window.open() concats current url

If i use the function

window.open(“http://localhost:9525/some-link”)

with on a node.js environment on the site “http://localhost:9525/, for example, it opens the new tab with the following url:

http://localhost:9525/://localhost:9525/some-link

This doesn’t works. I would like to open the new tab with only the url i set as a parameter without the concatenation from the origin url. I tried to use the same function with the google chrome debug console and the result is the same.

I think this used to work, i don’t know if I’m wrong but, might this be a change since the 101 chromes update?

react-native-webview href html tag not wrapping and going off screen

The long href url content inside my WebView does not go to the line and makes the view scrollable horizontally when it should break the text and make it go to the line even if it is one big chunk of text.

I was unable to find a way to fix this in the docs, see attached photo.

function fomatHTML(html: string) {
        const metaViewport = '<meta name="viewport" content="width=device-width, initial-scale=1">';
        const formatedHTML = `<html><head>${metaViewport}</head><body>${html}</body></html>`
        return formatedHTML;
    }

<WebView
    source={{html: fomatHTML(text)}}
    originWhitelist={['*']}
    />

the part causing the issue

<a href="..." target="_blank"><span style="color: blue;">...</span></a>

enter image description here

for salt and hashing passwords i used Bcrypt method but its showing , error = new Error(‘data and salt arguments required’);

for salt and hashing passwords i used Bcrypt method but its showing ,
error = new Error(‘data and salt arguments required’);
i think my code have the problem please i need help please;
eCommerce website is my project so ,i created signup form in user panel

*user.js

const userHelpers=require('../helpers/user-helpers')
 
router.get('/signup',(req,res)=>{
   res.render('user/signup')
})

router.post('/signup',(req,res)=>{
  userHelpers.doSignup(req.body).then((response)=>{
     console.log(response);
  })

user-helpers.js

var db=require('../config/connection')
 var collection=require('../config/collections')
 const bcrypt=require('bcrypt')

module.exports={
    doSignup:(userData)=>{
        return new Promise(async(resolve,reject)=>{
            // var salt =  await bcrypt.genSalt(10);
            userData.Password= await bcrypt.hash(userData.Password ,10)
                db.get().collection(collection.USER_COLLECTION).insertOne(userData).then((data)=>{

                    resolve(data) 
                });
                     
            });
          
    }

collection.js

module.exports={
    PRODUCT_COLLECTION:'product',
    USER_COLLECTION:'user'
}  

this is my code but the error shoing

error = new Error('data and salt arguments required');
                ^

Error: data and salt arguments required

how to fix the problem ..

stripe payment not receving in firebase

It is showing no error but it is not reaching Firebase.

console.log(success: order ${session.id} had been added to db); this line never comes in the console.
the terminal shows everything created but it does not reach Firebase database I am thinking there is an error in the code.
The stripe dashboard also says connected.
I am using the forward to localhost line in git terminal.
if someone knows please post the code as I am thinking there is a problem in firebase connecting

webhook code

import { buffer } from "micro";
import * as admin from 'firebase-admin'

//secure a connection to Firebase from backend
const serviceAccount = require('../../../permissions.json');
const app = !admin.apps.length ? admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
}) 
  : admin.app();

// establish connection to stripe
const stripe = require('stripe')(process.env.STRIPE_SECRET_KEY);

const endpointSecret = process.env.STRIPE_SIGNING_SECRET;
if (typeof endpointSecret !== "string") {
    console.error("Unexpected value for STRIPE_SIGNING_SECRET");
    // potentially throw an error here
  }

const fulfillOrder = async (session) => {
    //console.log('Fulfilling order', session)

    return app
    .firestore()
    .collection("user")
    .doc(session.metadata.email)
    .collection("orders")
    .doc(session.id)
    .set({
        amount: session.amount_total / 100,
        amount_shipping: session.amount_total_details.amount_shipping / 100,
        images: JSON.parse(session.metadata.images),
        timestamp: admin.firestore.FieldValue.serverTimestamp(),
    })
    .then(() => {
        console.log(`success: order ${session.id} had been added to db`);
    });
};

export default async (req, res) =>{
    if(req.method === 'post'){
        const requestBuffer = await buffer(req);
        const payload = requestBuffer.toString();
        const sig = req.headers["stripe-signature"];

        let event;

        // verify that the event posted came from stripe 
        try{
            event = stripe.webhooks.constructEvent(
                 payload,
                 sig,
                 endpointSecret);
        } catch (err) {
            console.log('ERROR', err.message)
            return res.status(400).send(`Webhook error: ${err.message}`)
        }

        //handle the checkout event 
        if (event.type === 'checkout.session.completed') {
            const session = event .data.object;

            //fulfill the order...
            return fulfillOrder(session)
            .then(() => res.status(200))
            .catch((err) => res.status(400).send(`Webhook error: ${err.message}`));
        }
    }
};

export const config = {
    api: {
        bodyParser: false,
        externalResolver: true,
    },
};

firebase rules

rules_version = '2';
service cloud.firestore {
  match /databases/{database}/documents {
    match /{document=**} {
      allow write: if false;
      allow read: if true;
    }
  }
}

file folder

console

[![also tried][3]][3]

tried
[3]: https://i.stack.imgur.com/2Lt3A.jpg

Jest test case for React hook component

When I write a react hook component which import ‘*.png’ resource like this:

import React, { useState, useEffect } from 'react';
import './topMenu.less';
import intl from 'react-intl-universal';
import { Breadcrumb } from 'antd';
import home from '@/image/project/home.png';

const TopMenu: React.FC<{}> = () => {
  const [page, setPage] = useState<string>('overview');
  const [projectName, setProjectName] = useState<string>('');

  useEffect(() => {
    let hashUrl = window.location.hash;
    let tempPage = hashUrl.split('/')[3];
    let projectNameStr = sessionStorage.getItem('projectName');
    setPage(tempPage);
    setProjectName(projectNameStr ? projectNameStr : '');
  }, []);

  /**
   * 功能描述 依据页面路由渲染面包屑组件的尾部文字
   * 
   * @return {string} 面包屑的末级页面名称
   */
  function getPageName(): string {
    switch(page) {
      case 'overview':
        return intl.get('PROJECT_OVERVIEW');
      case 'inference':
        return intl.get('ROOT_CAUSE_INFERENCE');
      case 'bigModel':
        return intl.get('BIG_MODEL_DIAGNOSTICS');
      default:
        return intl.get('PROJECT_OVERVIEW');
    }
  }

  return (<div className="slider-menu">
    <Breadcrumb>
      <Breadcrumb.Item href="#/kgom/packageList">
        <img src={home} />
        <span>{intl.get('PROJECT_LIST')}</span>
      </Breadcrumb.Item>
      <Breadcrumb.Item >
        <span>{projectName}</span>
      </Breadcrumb.Item>
      <Breadcrumb.Item>
        <span>{getPageName()}</span>
      </Breadcrumb.Item>
    </Breadcrumb>
  </div>);
};

export default TopMenu;

then i write a easy test code like this:

import TopMenu from './topMenu';
import React from 'react';
import renderer from 'react-test-renderer';

jest.mock('@/image/project/home.png', () => '../image/project/home.png');

describe('TopMenu Test', () => {
  it('render TopMenu', () => {
    const component = renderer.create(<TopMenu />);
    expect(component.toJSON()).toMatchSnapshot();
  });
});

when i run npm test, it calls this error:
enter image description here

espicially this line: jest.mock(‘@/image/project/home.png’, () => ‘../image/project/home.png’);
I try many ways to rewrite this line, but it always error, when i not write this line, it calls that error:
enter image description here

how do i write this hook component jest render test???

Why I got empty object on Angular route?

Why I got empty object from ActivatedRoute params and how to fix that?

  routeId$ = this.route.params.pipe(
    tap((params) => console.log(params)), // <--- {}
    pluck('id')
  );

I defined the :id in the route of the children:

    RouterModule.forChild([
      {
        path: '',
        component: OrdersComponent,
        children: [{ path: ':id', component: OrderComponent }], <-- here.
      },
    ]),

Because I want to use facade, I declared it in the providers to have facade instance for the component:

...
providers: [FooFacade],
})
export class OrderComponent {
  constructor(private facade: FooFacade) {}
  doWork() {
    console.log('doWork');
    this.facade.doWork();
  }

FooFacade is using the service.

I try to find why I got an empty object and not the id so I found out that works:

 routeIdWorks$ = this.route.firstChild.firstChild.firstChild.params.pipe(
    tap((params) => console.log(params)),
    pluck('id')
  );

But it’s not the ideal solution because I have to specify alot of firstChild. also a function that aggrigate firstChild feel worng.

So there is a way to make this to work?

  routeId$ = this.route.params.pipe(
    tap((params) => console.log(params)),
    pluck('id')
  );

I also defined those options in the router root:

  {
        paramsInheritanceStrategy: 'always', <---??
        initialNavigation: 'enabledBlocking',
        enableTracing: false,
      }

stackblitz