Why the object is not iterable in angular? [duplicate]

I have an object this.billingInformationModel that has multiple values and keys. When console.log is done, the values and keys are clearly seen. However, when I try to access a value using a key, it shows undefined.

Below is the screenshot of console.log of the object.

enter image description here

And here it is that shows undefined when I try to access the country using this.billingInformationModel.country
enter image description here

Also, billingInformationModel is defined as: @Input() public billingInformationModel: any;

I also tried this.billingInformationModel[0].country but the error is still shown and country is not accessible.

Any help would be more than appreciable.

Having trouble with vue package image sources on production build

So I’ve made my first Vue package using Vite. The issue is that this component uses a set of flag images stored in public/country-flags folder and referenced in the component like this:

<img class="flag" :src="country-flags/${player.flag}" />

Everything works fine until I use the production build and import the component into another project, of course this path now doesn’t work.

What’s the proper way of handling this situation?

I’ve tried to find some Vite configuration with no luck.

Sorting table and displaying sorting symbols

I stumbled upon Nick Grealy’s answer to a question on here about sorting tables (https://stackoverflow.com/a/49041392), with jedwards fix for people having rows inside a tbody (https://stackoverflow.com/a/53880407). It was a nice piece of code, which worked perfectly for what I wanted it for.

I am just having a hard time implementing sorting symbols in the th headers of the table for when the table is sorted ascending or descending for a specific column. I came up with this which works somewhat okay:

const getCellValue = (tr, idx) => tr.children[idx].innerText || tr.children[idx].textContent;
const comparer = (idx, asc) => (a, b) => ((v1, v2) => 
    v1 !== '' && v2 !== '' && !isNaN(v1) && !isNaN(v2) ? v1 - v2 : v1.toString().localeCompare(v2)
    )(getCellValue(asc ? a : b, idx), getCellValue(asc ? b : a, idx));
document.querySelectorAll('th').forEach(th => th.addEventListener('click', ((e) => {
    const table = th.closest('table');
    const tbody = table.querySelector('tbody');
    let buttons = document.getElementsByTagName("button");
    const arrayButtons = ['0', '1', '2'];
    Array.from(tbody.querySelectorAll('tr'))
        .sort(comparer(Array.from(th.parentNode.children).indexOf(th), this.asc = !this.asc))
        .forEach(tr => tbody.appendChild(tr));
    arrayButtons.forEach(e => buttons[e].setAttribute("data-dir", ""));
    if (this.asc) {
        e.target.setAttribute("data-dir", "asc");
    } else {
        e.target.setAttribute("data-dir", "desc");
    }
})));
table, th, td {
  border: 1px solid black;
  border-collapse: collapse;
}
th button {
  background-color: transparent;
  border: none;
  cursor: pointer;
  font: inherit;
  color:inherit;
  width: 100%;
}
th button[data-dir="asc"]::after {
  content: " " url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13' xml:space='preserve' width='13' height='13' transform='scale(1 -1)'%3E%3Cpath d='M2.039 5.171c.114.114.25.172.406.172h8.107a.55.55 0 0 0 .406-.172c.114-.114.172-.25.172-.406s-.057-.292-.172-.406L6.906.302C6.792.187 6.658.13 6.5.13s-.292.057-.406.172L2.039 4.355a.557.557 0 0 0-.172.406.541.541 0 0 0 .172.408zM6.5 12.473a.163.163 0 0 1-.127-.055L2.319 8.364a.159.159 0 0 1-.055-.127c0-.042.01-.081.055-.127s.084-.055.127-.055h8.107c.042 0 .081.01.127.055s.055.084.055.127a.163.163 0 0 1-.055.127l-4.052 4.054c-.047.045-.084.055-.127.055m0 .396a.55.55 0 0 0 .406-.172l4.054-4.054a.557.557 0 0 0 .172-.406.549.549 0 0 0-.172-.406.557.557 0 0 0-.406-.172H2.447a.549.549 0 0 0-.406.172.557.557 0 0 0-.172.406.55.55 0 0 0 .172.406l4.054 4.053c.114.114.25.172.406.172z' fill='%23000'/%3E%3C/svg%3E");
}
th button[data-dir="desc"]::after {
  content: " " url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 13 13' xml:space='preserve' width='13' height='13'%3E%3Cpath d='M2.039 5.171c.114.114.25.172.406.172h8.107a.55.55 0 0 0 .406-.172c.114-.114.172-.25.172-.406s-.057-.292-.172-.406L6.906.302C6.792.187 6.658.13 6.5.13s-.292.057-.406.172L2.039 4.355a.557.557 0 0 0-.172.406.541.541 0 0 0 .172.408zM6.5 12.473a.163.163 0 0 1-.127-.055L2.319 8.364a.159.159 0 0 1-.055-.127c0-.042.01-.081.055-.127s.084-.055.127-.055h8.107c.042 0 .081.01.127.055s.055.084.055.127a.163.163 0 0 1-.055.127l-4.052 4.054c-.047.045-.084.055-.127.055m0 .396a.55.55 0 0 0 .406-.172l4.054-4.054a.557.557 0 0 0 .172-.406.549.549 0 0 0-.172-.406.557.557 0 0 0-.406-.172H2.447a.549.549 0 0 0-.406.172.557.557 0 0 0-.172.406.55.55 0 0 0 .172.406l4.054 4.053c.114.114.25.172.406.172z' fill='%23000'/%3E%3C/svg%3E");
}
<table width='100%'>
<thead>
<tr>
<th width='20%'>Image</th>
<th width='20%'><button data-dir=''>Number</button></th>
<th width='40%'><button data-dir=''>Name</button></th>
<th width='20%'><button data-dir=''>Postal code</button></th>
</tr>
</thead>
<tbody>
<tr>
<td>IMG1</td>
<td>xxx</td>
<td>John Johnson</td>
<td>56430</td>
</tr>
<tr>
<td>IMG2</td>
<td>yyy</td>
<td>Sally Johnson</td>
<td>56430</td>
</tr>
</tbody>
</table>

There are some problems with the code that I can’t seem to solve, and which I am asking for help to fix:

  1. When I click the th-header of the image-column, it sets the data-dir of the th and removes the data-dir from all the other columns. The image-column does not have a button and is not supposed to be able to trigger that function. Any way to fix this?
  2. When a table is already sorted ascending, for example the Name-column, when clicking the th-header for the name-column, it sorts it ascending first (even though it already is) and then on second-click descending, instead of descending right away. Any way to fix this?
  3. Is the code optimized as it is, especially the parts I have added with the let buttons, const arrayButtons and the if else for setAttribute of data-dir? Could it be more optimized?

I am trying to learn, so any feedback would be appreciated. 🙂

Thank you in advance!

‘Missing dependencies’ OWL Odoo15

I’m currently learning OWL and I want to do something like chat in the “Web Site” module (To display messages from the “Communication” module on the site).
I created a separate tab called “Chat” (I will output all messages from the “Communication” module there).
But here I encountered a problem, namely:
Missing dependencies

This is my code, it complains about this code, namely – can’t find the dependency of the ChatComposer variable (as I understand it)

/** @odoo-module **/

odoo.define('Portal_Chat', function (require) {
    'use strict';

    const session = require("web.session");
    const publicWidget = require('web.public.widget');

    const { ComponentWrapper } = require('web.OwlCompatibility');
    console.log("lalalalalal");
    
    const components = {
        ChatComposer: require('/portal_chat/static/src/components/chat_composer/chat_composer.js')
    };

    publicWidget.registry.PortalChatWidget = publicWidget.Widget.extend({
        selector: '.portal_chat',
        init: function(parent, options) {
            this.options = _.defaults(options || {}, {});
            this.component = false;

            return this._super.apply(this, arguments)
        },
        async start() {
            const partner_id = await this._rpc({ route: '/chat/get_partner_id' });
            const props = {
                partner_id: partner_id,
                do_warn: this.do_warn,
                onSeenChannel: (ev) => this.call('chat_service', 'checkUnreadMessages'),
            };

            this.component = new ComponentWrapper(this, components.ChatComposer, props);

            await session.load_qweb('portal_chat');
            await this.component.env.qweb.addTemplates(session.owlTemplates);

            this.call('chat_service', 'onOpenChannel', this, this._onOpenChannel);
            this.call('chat_service', 'onReceiveMessage', this, this._onReceiveMessage);

            return this.component.mount(this.el);
        },
        _onOpenChannel: function (data) {
            if(this.component) this.component.componentRef.comp.channels.comp.addChannel(data);
        },
        _onReceiveMessage: function (data) {
            if(this.component) this.component.componentRef.comp.channels.comp.receiveMessage(data);
            if(this.component) this.component.componentRef.comp.messages.comp.receiveMessage(data);
        },
    });

    return publicWidget.registry.PortalChatWidget;
});

This is my ChatComposer:

/** @odoo-module **/

import { Component } from owl;
import { useState, useRef } from owl.hooks
import { _ } from owl;

import { ChatChannels } from '@portal_chat/components/chat_channels/ChatChannels';
import { ChatMessagesHeader } from '@portal_chat/components/chat_messages_header/ChatMessagesHeader';
import { ChatMessages } from '@portal_chat/components/chat_messages/ChatMessages';
import { ChatInput } from '@portal_chat/components/chat_input/ChatInput';

export class ChatComposer extends Component {
    
    state = useState({
        current_channel: false
    });

    channels = useRef("channels");
    messages = useRef("messages");

    constructor(parent, props) {
        super(parent, props);
        this.state = useState(props);
    }

    setChannel(ev) {
        this.state.current_channel = ev.detail;
    }

    onSeenChannel(ev) {
        this.state.onSeenChannel(ev);
    }

    onScrollBottom(ev) {
        this.channels.comp.clearCurrentChannelCounter(ev);
    }
}
ChatComposer.components = { ChatChannels, ChatMessagesHeader, ChatMessages, ChatInput };
ChatComposer.template = "Portal_Chat";
return ChatComposer

Can we use multiple loader from different component within a component in react using react router dom?

Beginner in React

Want to load data from two different components within another component using loader in react router dom.

Data from different component loaded when routing for another component occur
Eg :Loader1 in Component1,Loader2 in Component2 and need both these in Component3

const router = createBrowserRouter([ 
{ path: "/", 
element: <Root />, 
errorElement: <ErrorPage />, },
{ path: "/signup", 
element: <SignUp />, 
loader: Loader,//Multiple Loaders Here like Loader1,Loader2,Is it Possible? action: signupAction }, 
]); 

Passport JS always directs me to the failure route and does not seem to use my local strategy

I have been trying to set up Passport JS on my Node server but I always seem to redirected to the failureRedirect endpoint.

I have added a console.log statement in LocalStrategy function however I never see this statement appear which suggests its not checking in the database for the user.

my app.js:

var express = require('express');
var path = require('path');
var createError = require('http-errors');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const session = require("express-session");
const passport = require("./middleware/passport");
//const LocalStrategy = require("passport-local").Strategy;
//const bcrypt = require("bcryptjs")
const mongoose = require("mongoose");
require('dotenv').config()

//routers
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var apiIndexRouter = require('./routes/api_index');
var requestsRouter = require('./routes/requests');

//models
const User = require("./models/user");

var app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

....

//user authentication
app.use(session({ secret: process.env.SECRET_KEY, resave: false, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());
app.use(express.urlencoded({ extended: false }));


middleware/passport.js:

const passport = require('passport')
const bcrypt = require('bcryptjs')
const LocalStrategy = require("passport-local").Strategy;
const User = require("../models/user");

passport.use(
    new LocalStrategy(async(username, password, done) => {
      try {
        console.log("hello")
        const user = await User.findOne({ email: username });
        if (!user) {
          return done(null, false, { message: "Incorrect username" });
        };
        bcrypt.compare(password, user.password, (err, res) => {
          if (res) {
            // passwords match! log user in
            return done(null, user)
          } else {
            // passwords do not match!
            return done(null, false, { message: "Incorrect password" })
          }
        })
      } catch(err) {
        return done(err);
      };
    })
  );

passport.serializeUser(function(user, done) {
    done(null, user.id);
  });
  
passport.deserializeUser(async function(id, done) {
    try {
      const user = await User.findById(id);
      done(null, user);
    } catch(err) {
      done(err);
    };
  });

module.exports = passport;

controllers/user_controller:

const User = require("../models/user");
const { body, validationResult } = require("express-validator");
const bcrypt = require("bcryptjs");
const passport = require("../middleware/passport");
//const app = require('../app.js')
//const LocalStrategy = require("passport-local").Strategy;
//require('../middleware/passport')

....

exports.user_login_get= async (req, res, next) => {
    res.render("users_login_form", {
        title: "Login"
    })
};

exports.user_login_post = passport.authenticate("local", {
    successRedirect: "/",
    failureRedirect: "/users/login"
    // failureFlash: true
  });

I currently have the passport functions in a middleware folder but I have tried adding these to the app.js and still no luck.

I have been following the Odin Project and have got my tester projects to work but am getting stuck here in my own project. Any help would be appreciated.

Unblock microphone when pressing listen and wait in Scratch

Currently I have the following code about speaking into the microphone and printing what I say into text to the Scratch screen:

class SpeechRecognitionApi {
     constructor() {
         console.log("audio recognition");
         const SpeechToText =
             window.speechRecognition || window.webkitSpeechRecognition;
         this.speechApi = new SpeechToText();
         this.speechApi.continuous = false;
         this.speechApi.lang = "en-VN";
         this.speechApi.interimResults = false;
         // this.output = options.output ? options.output : document.createElement('div');
         // console.log(this.output)
         this.speechApi.onresult = function (event) {
             console.log(event);
             var resultIndex = event.resultIndex;
             var transcript = event.results[resultIndex][0].transcript;

             console.log("transcript>>", transcript);
             // console.log(this.output)
             // this.output.textContent = transcript;
             sttEmitter.emit("stt", transcript);
         };
     }
     start0() {
         this.speechApi.start();
     }
}

     listenAndWait() {
         let speech = new SpeechRecognitionApi();
         speech.start0();
         return new Promise((resolve) => {
             sttEmitter.on("stt", resolve);
         });
     }

Listen and wait

But when I click listen and wait, my code is always blocked and can’t be removed in the browser

Block Microphone

Is there any way I can fix the code so that the browser doesn’t block the microphone?

I want when I click listen and wait, the browser won’t block the microphone and can print what I say to the screen

How to get the version number in a static file in electron?

I am trying to get the version of my electron app through electron.app.getVersion() in a static file.

I have tried using

document.getElementById("releasever").content = "Release:" + require('electron').app.getVersion();

to get the version number and set it as the content of a paragraph tag. But it errors out and says Uncaught TypeError: Cannot read properties of undefined (reading 'getVersion').

NodeIntegration and ContextIsolation is turned on for the window. If someone can explain to me why getVersion() isn’t working or has a better way of doing this, please tell me. Thank you so much!

Suspense fallback is not showing in NextJS 13

I am building an application to showcase the usage of the Suspense in Nextjs 13. But the Suspense fallback is not showing while loading.

Here is the page.js

import React, { Suspense } from "react";
import Loading from "./loading";
const Trending = React.lazy(() => import("./Trending"));

function Page() {
  return (
    <div>
      <Suspense fallback={<Loading />}>
        <Trending />
      </Suspense>
    </div>
  );
}

export default Page;

Here is the Trending

import axios from "axios";

export default async function Trending() {
  const res = await axios.get(
    `https://api.themoviedb.org/3/trending/movie/day?api_key=1428e09fe38be9df57355a8d6198d916`
  );

  const data = res.data;

  // Add a delay to ensure that the Suspense fallback is shown
  await new Promise((resolve) => setTimeout(resolve, 3000));

  return (
    <div>
      <li>{data.results[0].title}</li>
    </div>
  );
}

If you need anything else let me know.

I tried various method such as lazy loading, adding delay and all but still not working. I need to see the fallback component showing while loading the data.

Stripe.js and 3D SECURE modal design

I’m using Stripe.js to handle payment forms and additional authnetication steps (inclunding 3D Secure).

I’m using for that the function : stripe.confirmCardPayment(clientSecret,data?,options?)

I’m wondering if I can customize the dialog modal opened by Stripe to complete the 3DS flow (change colors, text etc.)

Thanks

ssh2: Module parse failed: Unexpected character ‘�’

ERROR in ./node_modules/cpu-features/build/Release/cpufeatures.node 1:2
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
 @ ./node_modules/cpu-features/lib/index.js 3:16-60
 @ ./node_modules/ssh2/lib/protocol/constants.js 7:12-35
 @ ./node_modules/ssh2/lib/server.js 26:4-38
 @ ./node_modules/ssh2/lib/index.js 33:10-32
 @ ./src/app.js 3:19-34

ERROR in ./node_modules/ssh2/lib/protocol/crypto/build/Release/sshcrypto.node 1:2
Module parse failed: Unexpected character '�' (1:2)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)
 @ ./node_modules/ssh2/lib/protocol/crypto.js 30:12-60
 @ ./node_modules/ssh2/lib/server.js 27:29-60
 @ ./node_modules/ssh2/lib/index.js 33:10-32
 @ ./src/app.js 3:19-34

How to resolve it? I couldn’t find the right loader in Webpack.org

webpack.config.js

const path = require("path");

module.exports = {
  resolve: {
    fallback: {
      fs: false,
      tls: false,
      net: false,
      path: false,
      zlib: false,
      http: false,
      https: false,
      stream: false,
      crypto: false,
      buffer: false,
      util: false,
      assert: false,
      dns: false,
      process: false,
      timers: false,
      url: false,
      child_process: false,
      string_decoder: false,
    },
  },
  entry: "./src/app.js",
  mode: "production",
  output: {
    filename: "app.js",
    path: path.resolve(__dirname, "dist"),
  },
};

app.js

const conf = require("./config.js");
const mysql = require("mysql2");
const { Client } = require("ssh2");

// create an instance of SSH Client
const sshClient = new Client();

const SSHConnection = new Promise((resolve, reject) => {
  sshClient
    .on("ready", () => {
      sshClient.forwardOut(
        conf.forwardConfig.srcHost,
        conf.forwardConfig.srcPort,
        conf.forwardConfig.dstHost,
        conf.forwardConfig.dstPort,
        (err, stream) => {
          if (err) reject(err);

          // create a new DB server object including stream
          const updatedDbServer = {
            ...dbServer,
            stream,
          };
          // connect to mysql
          const connection = mysql.createConnection(updatedDbServer);
          // check for successful connection
          //  resolve or reject the Promise accordingly
          connection.connect((error) => {
            if (error) {
              reject(error);
            }
            resolve(connection);
          });
        }
      );
    })
    .connect(conf.tunnelConfig);
});

SSHConnection.then(
  (resolve) => {
    console.log("ssh resolved");
  },
  (reject) => {
    console.log(`ssh reject: ${reject}`);
  }
);

Problem filtering array of date pairs where a null date is involved

I am having a problem getting the result I want from filtering an array of date pairs using Typescript where one of the existing entries is null.
The array is pairs of from and to dates where the to date may be null.

In this instance it has only one entry – From 01/04/2021 – To null – ie infinte duration
A new date is compared against this From 01/04/2023- To 30/04/2023

Because the from date already in currentDates ( 01/04/2021) is earlier than Candidate_Valid_From (01/04/2023) and the current to date is null, i would expect a result of length 1 from this code snippet:

    let fromCheck = currentDates.filter(x => x.p_Valid_From <= Candidate_Valid_From
                                                            && (x.p_Valid_To >= Candidate_Valid_From
                                                            || x.p_Valid_To == null));
    if (fromCheck.length > 0)
    {
          return DATEISSUEES.OVERLAPPED_FROM_DATE;;
    }

But it is returning 0.

This is the date pair defintion:

class DatePair {
    constructor(
        public p_Valid_From? : Date, 
        public p_Valid_To? : Date, 
    ) { }
}

currentDates is an array of DatePair

Sentry error caught TypeError: (0 , i.baggageHeaderToDynamicSamplingContext) is not a function

I have a website built using nextjs and attached Sentry on it. It works on localhost, dev, and staging environment.

But somehow, it doesnt work on my main prod server. It shows error like this:

caught TypeError: (0 , i.baggageHeaderToDynamicSamplingContext) is not a function
    at Oe (client.js:93:34)
    at Ne.setupOnce (browsertracing.js:99:5)
    at integration.js:64:19
    at Array.forEach (<anonymous>)
    at integration.js:60:16
    at ha.setupIntegrations (baseclient.js:217:28)
    at d.bindClient (hub.js:65:14)
    at sdk.js:32:7
    at re (sdk.js:110:3)
    at sdk.js:18:3
    at index.client.js:29:3
    at 37942 (sentry.client.config.js:12:1)
    at n (bootstrap:21:33)
    at e (_app-b4f4ecdac789e1ace475.js:74:2591185)
    at _app-b4f4ecdac789e1ace475.js:74:2591240
    at n.O (chunk loaded:25:12)
    at _app-b4f4ecdac789e1ace475.js:74:2591278
    at t (jsonp chunk loading:36:28)

I tried to remove node_modules and yarn install again, seems didnt work. Also I cannot replicate this on localhost/dev/stg.

For context, my app are using redirect. Example, my app is at https://myappexample.com/app , I redirect only the root url https://myappexample.com to another domain