PWA referral Codes – sharing data between initial browser and subsequent PWA installation

I’m looking to implement a referral code system for my PWA.
The goal is to allow existing users to share a ref-link with their friends who can then install the app and get some benefits or have their app pre-configured.

So user A shares his ref link app.foo.com/?refCode=123 with his friends.
They open it on their mobile browser and are prompted to install the PWA.

Once they open the installed PWA, they create their account and log in.

I’m looking for a way now to share the refCode from the original link that user B opens in his browser to the installed PWA context where he then creates his account (and can forward the refCode to our backend to track it).

From what I’ve read IndexedDB should have worked (since it’s same origin – both app.foo.com) but at least in iOS it doesn’t. It appears the PWA runs in a different context and does not share the same IndexedDB context (objectStore not found).

Also tried localstorage after coming across some rumours it’s supported now in iOS 17+, but doesn’t appear to be the case either.

I don’t want to introduce invasive fingerprinting and would prefer not to burden the UX flow with the users having to share or enter specific codes manually etc.

Is there a solution to share data between the initial browser context and the subsequent installed PWA context (for both iOS and Android)?

Angular API Insee Token Renewal Issue with CORS

I’ve been stuck for days without a solution. I tried to implement automatic token renewal for accessing the Insee API in my Angular project, but despite my configuration, I keep receiving the error:

“Access to XMLHttpRequest at ‘https://api.insee.fr/token’ from origin ‘http://localhost:XXXX’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.”

I even tried hardcoding the access token that I generated directly on the page, but nothing works. Could you please help me out?

Here is my code:

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, switchMap } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class InseeService {
  private apiUrlSiret = 'https://api.insee.fr/entreprises/sirene/V3.11/siret';
  private apiUrlSiren = 'https://api.insee.fr/entreprises/sirene/V3.11/siren';
  private tokenUrl = 'https://api.insee.fr/token';
  private consumerKey = 'XXXX';
  private consumerSecret = 'XXXX';

  constructor(private http: HttpClient) {}

  private getToken(): Observable<any> {
    const headers = new HttpHeaders({
      'Content-Type': 'application/x-www-form-urlencoded',
      'Authorization': 'Basic ' + btoa(`${this.consumerKey}:${this.consumerSecret}`)
    });

    const body = new URLSearchParams();
    body.set('grant_type', 'client_credentials');

    return this.http.post(this.tokenUrl, body.toString(), { headers });
  }

  getEnterpriseInfo(identifier: string): Observable<any> {
    return this.getToken().pipe(
      switchMap((tokenResponse: any) => {
        const token = tokenResponse.access_token;
        const headers = new HttpHeaders({
          'Authorization': `Bearer ${token}`
        });
        const apiUrl = identifier.length === 14 ? this.apiUrlSiret : this.apiUrlSiren;
        return this.http.get(`${apiUrl}/${identifier}`, { headers });
      })
    );
  }
}

I use react, and react hokes router, and router dont update page

my component

 

import React from "react";
//import HeadingRow from './HeadingRow';
import { useState, useEffect } from "react";
import Results from './Results';
 import {useRoutes,
  useParams, Outlet, useLocation, useNavigate } from "react-router-dom";
          
import Card from './Card';



class Services extends React.Component {
         

          constructor(props) {
            super(props);
            console.log(props);
            this. state = {
            cards: [],
            cardsError: "",
            id: props.id
          };
            
          }
        fetchServices = async (id) => {
            const res = await fetch(`http://localhost:5000/cards/${id}`);
            const data = await res.json();

            return data;
          };
        fetchgetServiceseses = async () => {
            const res = await fetch(`http://localhost:5000/cards`);
            const data = await res.json();
            console.log(data);
            return data;
          };
 

        async componentDidMount() {

            const {id} = this.state;
                
                if(id){

                    const data_card = await this.fetchServices(id);
                    const cards = [data_card] ;
                    this.setState({cards });
                    console.log(id);
                    console.log(cards);

                }else{

                        const cards = await this.fetchgetServiceseses();
                  this.setState({ cards });
                }

        }
        async componentDidUpdate() {

                const {id} = this.state;
                    
                    console.log(id);
                     
                    /*
                if(id){

                    const data_card = await this.fetchServices(id);
                    const cards = [data_card] ;
                    this.setState({cards });
                    console.log(id);
                    console.log(cards);

                }else{

                        const cards = await this.fetchgetServiceseses();
                  this.setState({ cards });
                }
                */
        }

        render() {  

             /*const forms_result =  this.setFormsResults();
              console.log(forms_result);*/
             const { cards } = this.state;
                console.log(cards);
                    console.log(cards.length);
            return (<div className="container px-4 px-lg-5 my-5">
                  
                 
             {cards.length > 0 ? (
                <div className="row gx-4 gx-lg-5   ">
                    {cards.map((card, key) => <Card name={card.name}  id={card.id} key1={key} key={key}  link={card.link} sort={card.sort} text={card.text} linkAlias={card.linkAlias} />)}
                </div>
              ) : (
                "Emry results"
              )}

              <Outlet />

            </div>);
             };

    };


export default Services;  
export const ServicesFunk = props => {
  const {id} = useParams();
  console.log(id);
const location = useLocation();
  const navigate = useNavigate();

  const [state] = useState(location.state || {});  

  useEffect(() => {
    navigate(".", { replace: true });  
  }, [navigate]);

  `return <Services id={id} navigate={navigate} {...props} />;`


}  

my app use route

const App = () => (
    
          <Routes>
            


               <Route
                path="/"
                exact 
                element={    <>
                     <TopMenuBlock />
                   <PageContent />
                   <Footer />
                    </>   }
              /> 
              <Route
              path="/form-result"
              exact
               element={    <>
                 <TopMenuBlock /> 
                 <FormResults />
                  <Footer />
                </>   }
            /> 
            <Route
              path="/about/"
              exact
               element={    <>
                 <TopMenuBlock /> 
                 <About />
                  <Footer />
                </>   }
            /> 
            
            <Route
              path="/contact/"
              exact
               element={    <>
                 <TopMenuBlock /> 
                 <Contact />
                  <Footer />
                </>   }
            /> 
            <Route
              path="/services/:id?"
              
               element={    <>
                  <TopMenuBlock /> 
                
                  <ServicesFunk />
                  <Footer />
                </>   }
            > 
           
          </Route>


      </Routes>
   
);

export default App;

when I go to pages

http://localhost:3000/services/1/ и http://localhost:3000/services/2/
the page remains the same, kod

return <Services id={id} navigate={navigate} {...props} />;
does not give a result and is not called. I get the answer here

const {id} = useParams(); console.log(id);

but not here
`async componentDidUpdate() {

            const {id} = this.state;
                
                console.log(id);`

id – undefined

I tried to find an answer on stackoverflow and other sites, no result

problem to position menu icon in the page mobile version

I want and I’m trying position the icon menu to her right edge to be equal to right edge of the image at the bottom. I don’t know why, but this icon won’t move :P. What’s wrong? How can I fix this? Here I am adding what does it look like:
enter image description here

I tried to add margin-left: auto on the icon-navigation class, display flex on a container. Then either flex grow on one child so it takes up as much space as possible. And I tried to add justify-content: space-between. But none of these ways doesn’t work. If it’s not working, there must be something wrong with the code structure (html or somewhere else a css property is overriding it), but I can’t find what is wrong.
This is my github: https://github.com/NatKacz99/news-homepage.
This is the live page: https://natkacz99.github.io/news-homepage/

How do I display a video element of a blob in React?

I’m making a video processing application where I upload a video, do some processing, and send a new video back. I’m having trouble displaying the new video in blob format on the frontend even though I was able to succesfully send it from the backend. How do I fix this?

My code for creating the blob and displaying it

.then((res) => {
        console.log(res);
        let matrixBlob = new Blob([res.data], { type: "video/avi" });
        const videoURL = URL.createObjectURL(matrixBlob);
        console.log(matrixBlob);
        console.log(videoURL);
        setVideoURL(videoURL);
      })

Console logging the blob and blobURL give me

Blob
   size: 1254491
   type: video/avi

blob:http://localhost:5173/9b71e82e-7d6f-406a-ae9b-fa500dd68398

Displaying the video

{/* Returned files */}
        <h3 className="title text-lg font-semibold text-neutral-600 mt-10 border-b pb-3">
          Returned Files
        </h3>
        {videoURL && (
          <video controls width={550}>
            <source src={videoURL} type="video/avi" />
          </video>
        )}

Video not being displayed correctly: problem

How can I add more than one plan tier with Stripe?

//api/stripe
import { auth, currentUser } from "@clerk/nextjs/server";
import { NextResponse } from "next/server";
import { prismadb } from "@/lib/prismadb";
import { stripe } from "@/lib/stripe";
import { absoluteUrl } from "@/lib/utils";


const billingUrl = absoluteUrl("/billing");

export async function GET() {
  try {
    const { userId } = auth();
    const user = await currentUser();

    if (!userId || !user) {
      return new NextResponse("Unauthorized", { status: 401 });
    }

    const userSubscription = await prismadb.userSubscription.findUnique({
      where: {
        userId,
      },
    });

    if (userSubscription && userSubscription.stripeCustomerId) {
      const stripeSession = await stripe.billingPortal.sessions.create({
        customer: userSubscription.stripeCustomerId,
        return_url: billingUrl,
      });

      return new NextResponse(JSON.stringify({ url: stripeSession.url }));
    }

    const stripeSession = await stripe.checkout.sessions.create({
      success_url: billingUrl,
      cancel_url: billingUrl,
      payment_method_types: ["card", "Paypal"],
      mode: "subscription",
      billing_address_collection: "auto",
      customer_email: user.emailAddresses[0].emailAddress,
      line_items: [
        {
          price_data: {
            currency: "USD",
            product_data: {
              name: "Plume Pro",
              description: "Gain Full Access",
            },
            unit_amount: 7999,
            recurring: {
              interval: "month",
            },
          },
          quantity: 1,
        },
        {
          price_data: {
            currency: "USD",
             product_data: {
              name: "Plume Plus",
              description: "Gain Full Access",
            },
            unit_amount: 3999,
            recurring: {
              interval: "month",
            },
          },
          quantity: 1,
        },
      ],
      metadata: {
        userId,
      },
    });

    return new NextResponse(JSON.stringify({ url: stripeSession.url }));
  } catch (error) {
    console.log("[STRIPE_GET]", error);
    return new NextResponse("Internal Error", { status: 500 });
  } 
}

"use client";

import { usePlanModal } from "@/hooks/use-plan-modal";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "../ui/dialog";
import { Separator } from "../ui/separator";
import { Button } from "../ui/button";
import { useToast } from "../ui/use-toast";
import axios from "axios";
import { useState } from "react";

export const PlanModal = () => {
  const planModal = usePlanModal();
  const { toast } = useToast();
  const [loading, setLoading] = useState(false);

  const onSubscribe = async () => {
    try {
      setLoading(true);
      const response = await axios.get("/api/stripe");

      window.location.href = response.data.url;
    } catch (error) {
      toast({
        variant: "destructive",
        description: "Oops! Something went wrong.",
      });
    } finally {
      setLoading(false);
    }
  };
  return (
    <Dialog open={planModal.isOpen} onOpenChange={planModal.onClose}>
      <DialogContent>
        <DialogHeader className="space-y-4">
          <DialogTitle className="text-center">Upgrade your Plan</DialogTitle>
          <DialogDescription className="text-center space-y-2">
            Choose a plan that meets your needs.
          </DialogDescription>
        </DialogHeader>
        <Separator />
        <div className="flex items-center justify-between">
          <p className="text-2xl font-plus font-medium">
            $39
            <span className="text-sm font-normal">.99</span>
          </p>
          <Button size="md" onClick={onSubscribe}>
            Subscribe
          </Button>
        </div>
      </DialogContent>
    </Dialog>
  );
};

I am building my app using Nextjs and Stripe, which have multiple plans for users to subscribe to. This is the first app I have built with various tiers and I am failing to find a way to make it work. So, the help I am seeking is to know if there is a way I can make my plans in a single API folder(if so, how), or if I will have to create different API files for each tier. The way I did it above just adds up the two tiers and the checkout is $119.98.

Unable to calculate number of bnb in metamask wallet

I am trying to add an option to my webapp where user can add number of coins they want to buy using their bnb.
It connects with metamask and execute the order.
Problem is- value of my 1 coin is 0.0001 BNB, when I select 1 coin it should ideally execute order for 0.0001 BNB but it executes order for 0.07205759 BNB.

Below is the js-

    <script type="text/javascript">
    let web3;
    let userAddress = null;

    // Initialize Web3
    if (typeof window.ethereum !== 'undefined') {
        web3 = new Web3(window.ethereum);  // Initialize Web3 with MetaMask
    } else {
        alert('MetaMask or another compatible wallet is not installed. Please install it and try again.');
    }

    // Connect Wallet Logic
    document.getElementById('connect').addEventListener('click', async () => {
        if (web3) {
            try {
                const accounts = await window.ethereum.request({ method: 'eth_requestAccounts' });
                userAddress = accounts[0];
                document.getElementById('bnb_address').value = userAddress;
                alert("Wallet connected: " + userAddress);
            } catch (error) {
                console.error("User denied account access or connection failed:", error);
                alert("Failed to connect wallet. Please try again.");
            }
        }
    });

    document.getElementById('buyButton').addEventListener('click', async () => {
        try {
            if (!userAddress) {
                alert('Please connect your wallet first.');
                return;
            }

            // Ensure the user is connected to Binance Smart Chain
            const chainId = await window.ethereum.request({ method: 'eth_chainId' });
            const bscChainId = '0x38'; // 56 in hexadecimal, the chain ID for BSC mainnet

            if (chainId !== bscChainId) {
                alert('Please switch your network to Binance Smart Chain.');
                return;
            }

            const tokenAmount = parseFloat(document.getElementById('token_amount').value);
            if (isNaN(tokenAmount) || tokenAmount <= 0) {
                alert('Please enter a valid number of tokens.');
                return;
            }

            // Correct BNB amount calculation
            const tokenPriceInBNB = 0.0001; // 1 token = 0.0001 BNB
            const bnbAmount = tokenPriceInBNB * tokenAmount; // Calculate the correct BNB amount

            // Convert BNB to Wei
            const bnbAmountInWei = web3.utils.toWei(bnbAmount.toFixed(18), 'ether');

            console.log(`Token Amount: ${tokenAmount}`);
            console.log(`BNB Amount (before conversion to Wei): ${bnbAmount}`);
            console.log(`BNB Amount in Wei (to be sent): ${bnbAmountInWei}`);

            const transactionParameters = {
                to: '{{ receiving_address }}', // The address to send to
                from: userAddress, // The user's active address
                value: bnbAmountInWei, // Pass the correct value in Wei
                gas: '210000', // Temporarily increased gas limit for testing
            };

            try {
                const txHash = await window.ethereum.request({
                    method: 'eth_sendTransaction',
                    params: [transactionParameters],
                });
                alert("Transaction sent! Hash: " + txHash);
            } catch (error) {
                console.error("Transaction failed during send:", error);
                alert("Transaction failed during send: " + error.message);
            }
        } catch (error) {
            console.error("Transaction preparation failed:", error);
            alert("Transaction preparation failed: " + error.message);
        }
    });
</script>

JavaScript Integration Issue with Food Menu Pricing App

I’m trying to create a mobile app for my website that displays food menu prices, but I’m facing issues integrating JavaScript with my website’s data. How can I resolve this JavaScript integration issue to display my website’s data in my mobile app?

I tried to integrate JavaScript code into my mobile app to fetch food menu pricing data from my website’s API. I expected the data to be displayed in the app, allowing users to view and compare prices. However, instead of the data being displayed, I’m getting a JavaScript error saying ‘Failed to load resource’ and the app is not rendering the data as expected. I’ve checked the API endpoint and it’s returning the data correctly, but somehow the JavaScript integration is not working as intended.

Node JS and Firebase Firestore add/update operations on array of references

I’m new to firestore and I have users collection and addresses collection, and user have array of references of address. But not able to add, update array of reference.

   const userRef = getFirestore()
        .collection(FirebaseCollections.USERS)
        .doc(userId);

const result = await getFirestore()
    .collection(FirebaseCollections.ADDRESSES)
    .add(address);
    
     const userAddressRef = userRef.collection(FirebaseCollections.ADDRESSES);
      const refPath = `${FirebaseCollections.ADDRESSES}/${result.id}`;
      const refId = userAddressRef.doc(refPath); << CREATING REF
      await userAddressRef.add(refId); << ADDING IT TO ARRAY OF ADDRESS

it gives error

"Value for argument "documentPath" must point to a document, but was "addresses/LWELWL3goUA5ba8QjHSj". Your path does not contain an even number of components.",

enter image description here

What’s the correct way to do that?

How to reveal Minesweeper tiles with no mines recursively?

I’m trying to make Minesweeper using JavaScript and I wanted to make a bit of code so that when you reveal a tile with no adjacent mines it reveals the tiles next to it. If any of those tiles also have no adjacent mines, they reveal their neighbouring tiles too. This should continue until you have revealed a field of tiles without adjacent mines and all of the tiles next to them.

Below is the function that runs when you click a tile.
mines is a 2D array. If the value is 1 there is a mine.
minesNearby is a 2D array where each value is the number of mines next to the tile at that position.
checkedTiles is a 2D array. If the value is 1 the tile has been clicked.
findNeighbours returns an array of all the positions of the tiles around a given tile. (e.g. [[19,5],[19,4],[19,3],[18,3]…)
updateTile updates the tile div in the HTML.

function openTile(y,x) {  

    console.log(`opening tile y ${y} and x ${x}`)  
    checkedTiles[y][x] = 1;  
    updateTile(y,x);  
    if (mines[y][x] == 1) {  
        // death  
    } else if (minesNearby[y][x] == 0) {  
        findNeighbours(y,x).forEach((tile,index) => {  
            console.log(`${tile[0]}+${tile[1]}`)  
            if (checkedTiles[tile[0]][tile[1]] == 0) {  
                openTile(tile[0],tile[1])  
            };  
        });  
    }  
}

This looks fine to me, but I’m sure there’s something I’m missing.
When you click a tile with no adjacent mines, it sometimes will reveal the tile to the top-left and sometimes will not reveal anything. (The top-left tile isn’t even the first in the indNeighbours array).
If there are more tiles with no adjacent mines to the top left, a diagonal line of revealed tiles may occur.
How do I make this work properly?

Is there any solution to the error: Cannot use import statement outside a module in JavaScript? [duplicate]

I’ve been creating an exam organizer these days and I needed an examiners list on the other file, I created an object and listed all my examiners. However, while importing theese examiners’ object to main logic file, I am getting an error which says that I can not use import statement outside a module. Here is piece of my code,

import { examiners } from 'database.js';
 # other things from html...
 submitBtn.onclick = () => { let examinerLocal = localStorage.setItem('exorg-examiner', examiners[0]); }

database.js file

let examiners = [
    {
      name: "Smn",
      surname: "Smb",
      age: 94
    }
]

It might seem as unfinished but I couldn’t use anything else with this list as I couldn’t import that. And because of this, other logic also stopped functioning.

So I’ve tried to do it by moving it into onclick function but the error I got was the same. I did that because I do not know what the module is here. Moreover, I’ve tried this article and changed the database.js file to this:

export default class examiners {   
    constructor() {     
        let examiners = [
           {
            name: "smn",
            age: 20       
           }
         ]
       }
 }

But then I got another error: GET http://127.0.0.1:5500/database net::ERR_ABORTED 404 (Not Found)

Project Euler 101

Here is my solution to the Project Euler 101 problem (https://projecteuler.net/problem=101)… I know I don’t actually have to implement a full matrix solver but I did it whatsoever, but now my answer is a bit off, can anyone please tell me where I got it wrong?

I created a function to solve the equations. For example, it returns [6, -11, 6] for 6a^2 -11b + c for the (3, n) for n^3. Somehow the final answer is slightly off

// OP's functions
let equationsResult = [];
let equations = [];
let numbersFound = [];
let sumOfNumbers = 0;
let result = 0;
let equationsLength = 0;
let finalResult = 0;

const generateEquations = (seq, length, numOfEquations) => {
  equations = [];
  for (let a = 1; a < numOfEquations + 1; a++) {
    for (let b = length - 1; b >= 0; b--) {
      equations.push(a ** b);
    };
    equations.push(a ** seq);
  }
};

const createEquations = (seq, length) => {
  generateEquations(seq, length, length);
  toSimplifyEquations(length, length);
  numbersFound = [];
  numbersFound.push(equations[equations.length - 1] / equations[0]);
  findNextNumber(seq, length);
};

const simplifyEquations = (arr, cLength, dLength, length) => {
  for (let c = 0; c < cLength - 1; c++) {
    for (let d = 0; d < dLength + 1; d++) {
      equationsResult.push(arr[(c * (dLength + 1)) + d + length + 1] - arr[(c * (dLength + 1)) + d]);
    };
  };
};

const toSimplifyEquations = (length, eLength) => {
  for (let e = 0; e < eLength - 1; e++) {
    simplifyEquations(equations, length - e, length, length);
    equations = equationsResult;
    equationsResult = [];
  };
};

const findNextNumber = (seq, length) => {
  if (numbersFound.length === length - 1) {
    sumOfNumbers = 0;
    numbersFound.forEach((num) => sumOfNumbers += num);
    numbersFound.push(1 - sumOfNumbers);
  } else {
    equations = [];
    generateEquations(seq, length, length - numbersFound.length);
    for (let g = 0; g < equations.length; g++) {
      if ((g + 1) % (length + 1) === 0) {
        for (let j = 0; j < numbersFound.length; j++) {
          equations[g] -= numbersFound[j] * equations[g - length + j];
        };
      };
    };
    equationsLength = equations.length / (length + 1);
    for (let h = 0; h < equationsLength; h++) {
      equations.splice(h * (length + 1 - (length - equationsLength)), length - equationsLength);
    };
    toSimplifyEquations(length - numbersFound.length, length - numbersFound.length);
    numbersFound.push(equations[equations.length - 1] / equations[0]);
    findNextNumber(seq, length);
  };
};

const optimumPolynomialOfN = (n) => {
  result = 1;
  for (let i = 2; i < n + 1; i++) {
    createEquations(n, i);
    for (let j = 0; j < numbersFound.length; j++) {
      result += ((i + 1) ** (numbersFound.length - j - 1)) * numbersFound[j];
    };
  };
  return result;
};

const optimumPolynomial = () => {
  finalResult = 1;
  for (let k = 0; k < 10; k += 2) {
    finalResult += optimumPolynomialOfN(k + 2) - optimumPolynomialOfN(k + 1);
  };
  return finalResult;
};
<!-- Include Mocha CSS for test results styling -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/mocha/10.2.0/mocha.min.css">

<!-- Div where Mocha will render the test results -->
<div id="mocha"></div>

<!-- Include Mocha JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/mocha/10.2.0/mocha.min.js"></script>

<!-- Include Chai JS for assertions -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/chai/4.3.7/chai.min.js"></script>

<script>
  // Initialize Mocha
  mocha.setup('bdd');
  const expect = chai.expect;



  // Test suite
  describe('Polynomial Calculation Tests', function() {

    beforeEach(function() {
      // Reset variables before each test
      equationsResult = [];
      equations = [];
      numbersFound = [];
      sumOfNumbers = 0;
      result = 0;
      equationsLength = 0;
      finalResult = 0;
    });

    it('should generate correct equation sequences', function() {
      generateEquations(2, 3, 3);
      expect(equations).to.eql([1, 1, 1, 1, 1, 2, 4, 8, 1, 3, 9, 27, 8]);
    });

    it('should calculate the correct numbersFound sequence', function() {
      createEquations(2, 3);
      expect(numbersFound).to.eql([8, 7, -14]);
    });

    it('should simplify the equations correctly', function() {
      generateEquations(2, 3, 3);
      simplifyEquations(equations, 3, 3, 3);
      expect(equationsResult).to.eql([1, 0, 1, 3, 8, 1, 4, 9, 0, 0, 1]);
    });

    it('should simplify the full equation set correctly', function() {
      generateEquations(2, 3, 3);
      toSimplifyEquations(3, 3);
      expect(equations).to.eql([1, 3, 8, 1, 4, 9, 0, 0, 1]);
    });

    it('should calculate the next number in sequence correctly', function() {
      createEquations(2, 3);
      findNextNumber(2, 3);
      expect(numbersFound).to.eql([8, 7, -14, 0]);
    });

    it('should calculate the correct polynomial result for n = 2', function() {
      const result = optimumPolynomialOfN(2);
      expect(result).to.equal(15);
    });

    it('should calculate the correct polynomial result for n = 3', function() {
      const result = optimumPolynomialOfN(3);
      expect(result).to.equal(25);
    });

    it('should return the correct final result', function() {
      const result = optimumPolynomial();
      expect(result).to.equal(1025);
    });
  });

  // Run the tests
  mocha.run();
</script>

ui-select Dropdown Search Not Working properly

I’m working on an AngularJS project where I’ve upgraded from ui-select2 to ui-select due to security concerns. However, I’ve run into a couple of issues with the ui-select dropdown:

Search Issue: The search functionality in the dropdown does not seem to work as expected. When I search for an item, the results are not displayed correctly, and the “No matches found” message is not showing as it should.

Here’s the relevant code:

Html :

 <div class="col-sm-3">
  <!--<select name="procurementMode" ui-select2="dropDown" ng-model="templateId" data-placeholder="Select Email Template" class="col-sm-10">
    <option></option>
    <option ng-repeat="t in etemplates" value="{{t.Id}}">{{t.Name}}</option>
  </select>-->
  <ui-select ng-model="templateId.Id" theme="select2" class="col-sm-10" style="width: 100% !important;" convert-to-string stringify-value="true">
    <ui-select-match allow-clear="true" placeholder="Select Email Template">{{$select.selected.Name}}</ui-select-match>
      <ui-select-choices refresh-delay="500" repeat="t.Id | valueToString as t in etemplates | filter:$select.search">
        {{t.Name}}
      </ui-select-choices>
      <div ui-select-no-choice class="no-match-message">No matches found</div>
    </ui-select>
 </div>

JS :

(function (window, angular, undefined) {
    'use strict';
    angular.module('angularModule.controllers').controller('searchempManagerCtrl', ['$scope', '$compile', '$window', 'ajaxCall', '$controller', 'checkPermissions', '$rootScope', 'permissionCheckService', 'emailManagerColumns', '$timeout', function ($scope, $compile, $window, ajaxCall, $controller, checkPermissions, $rootScope, permissionCheckService, emailManagerColumns, $timeout) {
        permissionCheckService.check('Email_Manager_View');
        //Injecting common useful values to the scope
        $controller('commonCtrl', { $scope: $scope });
       $scope.templateId = {Id:null};
       
      $scope.getEmailTemplates = function () {
            ajaxCall.get('/ManageData/EmailTemplates/GetEttEmailTemplates').then(function (data) {
                if (!isValidObject(data)) {
                    return;
                } else {
                    if (data.IsError) {
                        alertify.error(data.Message);
                    } else {
                        $scope.etemplates = data.templates;
                    }
                }
            });
        }

        $scope.init = function () {
            $scope.getEmailTemplates();
        }
        $scope.init();
 //Send Email
        $scope.sendEmail = function () {
            $rootScope.viewLoading = true;
            if (!isValidObject($scope.templateId.Id )) {
                alertify.error("Please Select Email Template");
                $rootScope.viewLoading = false;
                return;
            }
            var selectedRows = getSelectedIdsFromList($scope.gridConfig.getSelectedItems());
            var ids = "";
            if (!$scope.isSelectAll) {
                if (!isValidObject(selectedRows)) {
                    alertify.error("Please select a record to send an email.");
                    $rootScope.viewLoading = false;
                    return;
                }
                if (selectedRows.length == 0) {
                    alertify.error("Please select a record to send an email.");
                    $rootScope.viewLoading = false;
                    return;
                } else {
                    if (selectedRows.length > 0) {
                        // for (var i = 0; i < selectedRows.length; ++i) {
                        ids = selectedRows.join();
                        // }
                    }
                }
            }
            $scope.sendEmailData = JSON.stringify({
                templateId: $scope.templateId.Id,
                employeids: ids,
                isSelectAll: $scope.isSelectAll,
                emailManager: $scope.search
            });

            ajaxCall.post('/ETT/EmailManager/SendEmail', $scope.sendEmailData)
                .then(function (data) {
             if (isValidObject(data)) {
              if (!data.isError) {
                  $rootScope.viewLoading = false;
                  if (data.Message != "")
                      log(data.Message);
                  if (data.InvalidEmailMessage != "")
                      alertify.error(data.InvalidEmailMessage);
                  if (data.EmailNotFoundMessage != "")
                      alertify.error(data.EmailNotFoundMessage);
                  if (data.ToEmailNotFound != "")
                      alertify.error(data.ToEmailNotFound);
                  if (data.DateOfJoining != "")
                      alertify.error(data.DateOfJoining);
                  if (data.EmpClassNotFound != "")
                      log(data.EmpClassNotFound);

              } else {
                  $rootScope.viewLoading = false;
                  alert(data.Message);
              }
          }
      }, function (data) {
          consoleLog("Error: " + data.statusText);
          $rootScope.viewLoading = false;
      });
        }

    }]);
})(window, window.angular);

What I Have Tried:

  • Checked the ui-select documentation to ensure proper configuration.
  • Verified that etemplates contains the expected data.
  • Confirmed that templateId.Id is correctly bound to the ng-model.

Observed that during search, the dropdown displays incorrect data and the “No matches found” message does not appear as expected.

Expected Behavior:

  • The search input should correctly filter and display matching results in the dropdown.
  • The “No matches found” message should be displayed when no results match the search query.

When using TypeScript with “type” : “module” getting TypeError: Unknown file extension “.ts”

I am currently trying to be familiarize with TypeScript and i was creating a Node JS project from scratch and i have a question that why i am getting error while adding "type":"module" to package.json.

Error : 
TypeError: Unknown file extension ".ts" for F:node_pracindex.ts
[1]     at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:160:9)
[1]     at defaultGetFormat (node:internal/modules/esm/get_format:203:36)
[1]     at defaultLoad (node:internal/modules/esm/load:143:22)
[1]     at async ModuleLoader.load (node:internal/modules/esm/loader:409:7)
[1]     at async ModuleLoader.moduleProvider (node:internal/modules/esm/loader:291:45)
[1]     at async link (node:internal/modules/esm/module_job:76:21) {
[1]   code: 'ERR_UNKNOWN_FILE_EXTENSION'
[1] }
[1] [nodemon] app crashed - waiting for file changes before starting...

Why i am unable to use ECMAScript module with TypeScript here and What changes are required to make it working and why?

Note : It is working good if i am not adding “type”:”module” in package.json.

Currently i only have a base folder structure which involves following files:

Project/
  |
  |- node_modules/
  |- index.ts
  |- package-lock.json
  |- package.json

**package.json **

{
  "name": "node_prac",
  "version": "1.0.0",
  "description": "Practice project",
  "main": "index.ts",
  "scripts": {
    "start": "concurrently "ts-node" "nodemon index.ts"",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@types/node": "^22.4.0"
  },
  "dependencies": {
    "concurrently": "^8.2.2"
  }
}

I am writing this to understand what is actually the issue is and why it is? as well as to know what is the best possible way to solve it.

I had tried removing "type" : "module" in package.json and it was working but i want to use ECMAScript module in my project.