How can I solve React Expo Webview Error?

I would like to create mobile app with react expo. I used webview at my app. I wanted to open ads link at webpage with onNavigationStateChange. But after opening ads link, at main app don’t be clickable. Is there anything I missed? Can you give me an idea please? Thank you in advance..

 let webRef:any = React.createRef();

 export default class App extends React.Component {
  
  constructor(props:any) {
    super(props);

    webRef = React.createRef();
    

    this.state = {
      canGoBack: false,
       url: '***'
    }
  }
 
  
  render() { 
      return (
        <View id='main'>
          <View>
          <WebView
              ref={(ref) => webRef.current = ref}
              style={{flex:1}}
              pullToRefreshEnabled={true}
              id='webmain'
              source={{ uri: '***' }}
              onMessage={(event) => {
                console.log('event: ', event)
              }}
            
              onNavigationStateChange={(event) => {
                  if (!event.url.includes('***') && event.canGoBack == true) {
                    console.log(event.canGoBack);
                      webRef?.current.stopLoading();
                      this.setState({
                        canGoBack: event.canGoBack
                      });
                      Linking.openURL(event.url);
                  }
              }}

              />
          </View>
        </View>
              
      );
  }
}

how to refersh OR render a dynamic page without reloading using Jquery Or AJAX

i am facing problem in ny web project my problem is when i submit a form so my page is full reloading this is my and my styling and scripting are reset like i am stand a starting point in web page

i am using a jquery but i am not understand the concept of jquery and how to use j query . i am also try to use AJAX for dynamic page refershing without full page reloading. but i don’t know how to use j query and AJAX for dynamic page refershing without full page reloading.

How to properly add a 2nd addEventListener properly?

I am using a document.addEventListener(“DOMContentLoaded”, function ()
to force the input pattern (first must be a letter, then prevent consecutive spaces, etc.)

Now I want to make a 2nd document.addEventListener(“DOMContentLoaded”, function () for an email.
(I want to prevent multiple .’s and prevent more than 1 @)

Here is my code for both of the above but it isn’t working, it only capitalizes the email (i kept that option on to see if that part works, which it does but nothing else does work.)

Here is the first part (I also tried something else, removing the first }); at the document.addEventListener(“DOMContentLoaded”, function () at the start of the 2nd as I heard that should work but that didn’t work either.

document.addEventListener("DOMContentLoaded", function() {
  // Function to handle all keypress events
  function handleKeyPress(event) {
    const input = event.target;
    const char = String.fromCharCode(event.which);

    // Prevent first character from being a space
    if (input.selectionStart === 0 && event.code === "Space") {
      event.preventDefault();
      return;
    }

    // Prevent first character from being a non-letter
    if (input.selectionStart === 0 && !/^[a-zA-Z]$/.test(char)) {
      event.preventDefault();
      return;
    }

    // Prevent consecutive spaces
    const lastChar = input.value.charAt(input.selectionStart - 1);
    if (char === " " && lastChar === " ") {
      event.preventDefault();
      return;
    }
  }

  // Attach event listeners to input fields
  const inputs = document.querySelectorAll("input[name='real_name'], input[name='display_name']");
  inputs.forEach(input => {
    input.addEventListener("keypress", handleKeyPress);

    // Set text-transform to capitalize to force capitalization of each word
    input.style.textTransform = "capitalize";
  });
});
document.addEventListener("DOMContentLoaded", function() {
  // Function to handle all keypress events
  function handleKeyPress2(event) {
    const input = event.target;
    const char = String.fromCharCode(event.which);

    // Prevent first character from being a space
    if (input.selectionStart === 0 && event.code === "Space") {
      event.preventDefault();
      return;
    }

    // Prevent consecutive spaces
    const lastChar = input.value.charAt(input.selectionStart - 1);
    if (char === "@" && lastChar === "@") {
      event.preventDefault();
      return;
    }

    var key = event.keyCode || event.charCode || event.which;
    if (key == 32) {
      return false;
    } else {
      return key;
    }
  }

  // Attach event listeners to input fields
  const inputs = document.querySelectorAll("input[name='email']");
  inputs.forEach(input => {
    input.addEventListener("keydown", handleKeyPress2);

    // Set text-transform to capitalize to force capitalization of each word
    input.style.textTransform = "capitalize";
  });
});

I have upgraded my version angular 17 to 18.I am trying to make the build or runing the angular app. getting maximum call stack error by collorette

  1. List item

I have upgraded my version angular 17 to 18.
I am trying to run ng serve or ng build . getting bellow error if any have faced this issue plz provide the solution

appnode_moduleslistr2node_modulescoloretteindex.cjs:54
head = string.substring(0, index) + replace,
^

RangeError: Maximum call stack size exceeded
at String.substring (<anonymous>)
at replaceClose (C:UsersE02973Desktopn6 – Copy (2)appnode_moduleslistr2node_modulescoloretteindex.cjs:54:17)
at replaceClose (C:UsersE02973Desktopn6 – Copy(2)appnode_moduleslistr2node_modulescoloretteindex.cjs:57:32)
at replaceClose (C:UsersE02973Desktopn6 – Copy (2)appnode_moduleslistr2node_modulescoloretteindex.cjs:57:32)
at replaceClose (C:UsersE02973Desktopn6 – Copy (2)appnode_moduleslistr2node_modulescoloretteindex.cjs:57:32)
at replaceClose (C:UsersE02973Desktopn6 – Copy (2)appnode_moduleslistr2node_modulescoloretteindex.cjs:57:32)

Node.js v20.17.0


When I am running the application collorete issue should not be come. If I use some old version but there some auto dependecies on new version I can not be modify them.

Scrolling animation works in VS Code but not on my Web Page [closed]

I have created a scrolling animation on Figma inspired by the Lusion website. I added an SVG from Figma to the HTML to follow the scrollbar movement added via javascript.

It works in VS Code, but on adding the code to my webpage it didn’t work as the animation appears as an image file instead of having the scrolling animation.

const svg = document.querySelector('svg.squiggle');
const path = svg.querySelector('path');

const scroll = () => {
  const distance = window.scrollY;
  const totalDistance = document.body.scrollHeight - window.innerHeight;
  const percentage = distance / totalDistance;
  const pathLength = path.getTotalLength();
  path.style.strokeDasharray = `${pathLength}`;
  path.style.strokeDashoffset = `${pathLength * (1 - percentage)}`;
};

scroll();
window.addEventListener('scroll', scroll);
.squiggle {
  postion: absolute;
  z-index: 1;
}
<svg class="squiggle" width="1526" height="1157" viewBox="0 0 1526 1157" fill="none" xmlns="http://www.w3.org/2000/svg">
  <path d="M0 15C93.3084 42.7373 271.962 89.4848 172.314 331.518C72.6661 573.552 723.459 610.432 779.712 434.249C807.428 347.442 757.345 204.851 536.619 261.148C315.893 317.444 374.557 592.112 434.828 722.409C524.165 915.543 830.072 1277.77 1511 1089.16" 
  stroke="#FF0000" 
  stroke-width="30" 
  stroke-linecap="round"/>
  </svg>

API Image doesn’t show after generate a release APK in react native

In my React Native project, I fetch data through an API and display it in the application. The data, including images, displays correctly in both the emulator and physical devices during development. However, when I generate a release APK and install it on devices, the images are not showing.

How can I resolve this issue and ensure that images fetched from the API display correctly in the release APK?

 {services.map((service, serviceId) => (
        <View key={serviceId}>
          {service.products.map((product, productId) => (
            <View key={productId} style={styles.FeatureCard}>
              <Image
                source={{uri: product.images.url}}
                style={styles.imageCard}
              />
              <View style={styles.textContainer}>
                <Text style={styles.titleCard}>{product.title}</Text>
                <View style={styles.priceContainer}>
                  <Text style={styles.price}>₹ {product.price}</Text>
                  <TouchableOpacity
                    style={[styles.customButton, getButtonColor(product)]}
                    onPress={() => handleAddToCart(product)}>
                    <Text style={styles.buttonText}>
                      {cartItems.some(item => item.id === product.id)
                        ? 'Remove'
                        : 'Add'}
                    </Text>
                  </TouchableOpacity>
                </View>
              </View>
            </View>
          ))}
        </View>
      ))}

Django Template: How to connect chat script passing in Django Tag with JavaScript?

I’m working on a Django project where I need to conditionally render and execute a chat script based on user cookie consent. Here’s what I’ve got so far:

In my Django template, I have the following snippet:

{% if page.page_type.chat_script %}
  {{ page.page_type.chat_script|safe }}
{% endif %}

This snippet is responsible for rendering a chat script (something like chat script code) which is set via the Django admin panel.

However, I only want this script to execute if the user has accepted all cookies. I already have a separate JavaScript file (cookies_configuration.js) that handles cookie consent and injects various scripts into the head or body once consent is given (it works pretty fine when I use it with normal different scripts placed in other files).

Here’s a simplified example of how that injection looks (a little snippet from my code):

'injections': [
    {
        'location': 'head',
        'code': 'initGoogleAnalytics()'
    },
]

Now, I want to do something similar for the chat script—essentially wrap the Django template snippet in a function like initChatScript() and then call this function only after cookie consent is granted.


However, I’m not sure how to dynamically include and execute this Django template code within the JavaScript function.

I’ve already tried to do something like this:

<script async type="text/javascript">
  function initChatScript() {
    {% if page.page_type.chat_script %}
      {{ page.page_type.chat_script|safe }}
    {% endif %}
  }
</script>

But obviously it didn’t work at all.

What would be the best approach to achieve this? **Is there a way to render the template code conditionally or inject it into the JavaScript function? **Or should I take a different approach altogether (maybe it will be necessary to change the business logic and replace django tags with normal code, probably pure scripts)?

Any help or guidance would be greatly appreciated!

Load .mat data in Python vs Javascript

I have a .mat file that comes out from a pre-designed processing softwarem in MATLAB. This file contains three different arrays (AutoPhased, Complex and Magnitude). For this problem, I only want to focus on the AutoPhased one. I want to now load this data into JavaScript, but I am having trouble doing so.

I have successfully loaded my data in Python using the following code:

data_path = 'path/CSIProcessedData.mat'


data = scipy.io.loadmat(data_path)
data = data['AutoPhased']

data = data[:, :, :, 0, 0, 0, 0] #The data has 4 elements on last dimension but I only want the first

data = np.transpose(data)

This way I obtain a (16,8,1024) array that matches the data I expect. However, I have tried the following in JS using the mat4js:


const buffer = await readFileAsArrayBuffer(file);
matFileData = mat4js.read(buffer);
matFileData = matFileData.data


let processedData = Array(16) // Creates an array with 16 elements
              .fill(null).map(() =>
                Array(8).fill(null).map(() =>
                    Array(1024).fill(null)
                  )
              );

for (let i = 0; i < 16; i++) {
     for (let j = 0; j < 8; j++) {
          for (let k = 0; k < 1024; k++) {
               processedData[i][j][k] = data[k][j][i][0][0][0][0].r;
              }
          }
      }

And although I get the (16,8,1024) array, the numbers do not match those on Python. I have observed that the first (0,0,:) to (0,8,:) are correct. However, the rest seem to be a copy of these first 8 arrays, but shifted 8 points. This means that (1,0,0) has the value of (0,0,8); (2,0,0) the value of (0,0,16). I have tried many different ways of parsing the data, but I think the problem is directly on how the mat data is loaded in JS vs in Python.

You can find an example of this data here: https://github.com/marinabatllo-vit/MRSI-data/tree/main

Can anyone help me with this?

Facing issue in setupProxy.js in react application

I’m facing an issue in my react application where I have created setupProxy.js file inside src folder. In that I have multiple proxy’s one should work for oidc login & another proxy will work as backend port (9098). Instead of passing this 9098 proxy in package.json file .Do to testing propose I have added inside setupProxy file.

  1. Package.json – > “proxy” : “http://localhost:9098”

Note: Below I have added setupProxy code/ proxy’s.

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function (app) {
  app.use(
    '/bizcomp/restservices/v1/auth',  // Match the API path you want to proxy
    createProxyMiddleware({
      target: 'https://bizcomp.dev.att.com',  // Target OIDC server
      changeOrigin: true,  // Modify the origin header to the target URL
      pathRewrite: {
        '^/bizcomp/restservices/v1/auth': '/bizcomp/restservices/v1/auth',  // Rewrite the URL path if necessary
      },
      onProxyReq: (proxyReq, req, res) => {
        // Optional: Add any custom headers to the proxy request
        proxyReq.setHeader('X-Special-Proxy-Header', 'foobar');
      },
      onProxyRes: (proxyRes, req, res) => {
        // Optional: Manipulate the proxy response before sending it back to the client
        proxyRes.headers['x-added'] = 'foobar';  // Example of adding a custom header to the response
      },
      logLevel: 'debug',  // Set to 'debug' to see detailed logs of the proxy activity
    })
  );
  app.use(
    '/bizcomp/restservices/v1/service',  // Match the exact path
    createProxyMiddleware({
      target: 'http://localhost:9098',  // Backend server URL
      changeOrigin: true,  // Modify the origin header to match the target
      logLevel: 'debug',  // Enable detailed logging for debugging
      pathRewrite: { '^/bizcomp/restservices/v1/service': '' },  // Remove the base path if needed
      followRedirects: true,  // Follow HTTP 3xx responses
    })
  );
};

http://localhost:3000/bizcomp/restservices/v1/service/systemtools/getActiveAnnouncements –> This is api which we are using in our application

This is error in network. Its getting 404 error (Not Found)

{
    "timestamp": "2024-09-02T18:56:18.883+00:00",
    "status": 404,
    "error": "Not Found",
    "path": "/systemtools/getActiveAnnouncements"
}

Mongoose Error: “The uri parameter to openUri() must be a string, got undefined” when running tests with Supertest and Node.js

I’m working on an Express application with a MongoDB database, using Mongoose for database interactions. I’ve set up my tests using Node.js’ built-in node:test module and Supertest for API testing. My beforeEach function connects to the database using connectDB(config.MONGODB_URI), but I keep getting the error:

Error connecting to Database MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined".

Here’s a version of my test code:

import test, { beforeEach } from "node:test";
import supertest from "supertest";
import mongoose from "mongoose";
import config from "../utils/config";
import app from "../app"; // If this line is placed before the config import, the error fades
import connectDB from "../db/connectDb";


const api = supertest(app);

beforeEach(async () => {
  await connectDB(config.MONGODB_URI);
});

// More test code follows...

Relevant Config File:

const PORT = process.env.PORT || 3001;
const MONGODB_URI =
  process.env.NODE_ENV === "test"
    ? process.env.TEST_MONGODB_URI
    : process.env.MONGODB_URI;

export default {
  PORT,
  MONGODB_URI,
};

I observed that:

  1. If I import app before config, the error does not occur.
  2. If I import config before app, I get the error: “uri parameter to openUri() must be a string, got undefined”.

My Questions:

  1. Why does the import order affect the MONGODB_URI value, causing it to be undefined in some cases?
  2. Are there known issues with environment variable loading or initialization timing that could be causing this behavior?

What I Tried:

I tried running my tests with different import orders of the app and config modules. Specifically:

I imported config before app, which resulted in the error: MongooseError: The uri parameter to openUri() must be a string, got “undefined”.
I then switched the order, importing app before config, and the error disappeared.

What I Expected:

I expected the import order not to affect the loading of environment variables or configuration values. I expected config.MONGODB_URI to always have the correct value from the environment.

What Actually Happened:

When config was imported before app, config.MONGODB_URI was undefined, leading to the database connection error. Changing the order of imports resolved the issue, but I don’t understand why.

Build discrepancies when installing npm module from source

I have a JS library that currently has the distribution folder on source control and I want to avoid using that solution. Some users of the library want to install using npm install <git-repo> without a tag, just the branch.

A solution I found was to use the prepare script to build the library on install, but I have some questions as I’m not well versed in js packaging:

Will this mean that on every install, even from the npm registry directly, it will build it on their machine?

Will this introduce build discrepancies based on the dev dependencies being updated when installing the library (they are not absolute versioned currently in package.json )

If so, what are some probable solutions to this issue? Keep the distribution folder on SC?

firebase/authentication error-Cross origin redirect sign-in on Google Chrome M115+ is no longer supported, and will stop working on June 24, 2024

i am building an webapp in react.js and using firebase for login by email/password method, but this error will not let me store the userid/password.mostly it is related to CORS issue.
this is my firebase configure code.

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getAuth } from "firebase/auth";

// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional, 

HIDED the PERSONAL ID AND DATA

const firebaseConfig = {
  apiKey: "AIzaSyDw6105zrb-IhlcZxDa****************",
  authDomain: "netlfix-gpt******.web.app",
  projectId: "netlfix-gpt******",
  storageBucket: "netlfix-gpt*******.appspot.com",
  messagingSenderId: "9065506*******",
  appId: "1:906550651177:web:***************",
  measurementId: "G-HQ********"
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);

export const auth= getAuth();

Firebase.json file code

{
  "hosting": {
    "public": "build",
    "ignore": [
      "firebase.json",
      "**/.*",
      "**/node_modules/**"
    ]
  }
}

Firebaserc file Code:

{
  "projects": {
    "default": "netlfix-gpt-*****"
  }
}

this is the firebase file codes.

i have tried other solution given on youtube,stackoverflow,but not so many answers,also readed firebase documentation,but not able to understand properly.

Here it is.DOCUMENTATION
https://firebase.google.com/docs/auth/web/redirect-best-practices?hl=en&authuser=0

const firebaseConfig = {
  apiKey: "<api-key>",
  authDomain: "<the-domain-that-serves-your-app>",
  databaseURL: "<database-url>",
  projectId: "<project-id>",
  appId: "<app-id>"
};

this is error thrown

Cross origin redirect sign-in on Google Chrome M115+ is no longer supported, and will stop working on June 24, 2024.
Migrate to an alternative solution before June 24, 2024
End-users can continue to sign in to your app until June 24, 2024
This is already required on Firefox 109+ and Safari 16.1+

kindly help,stuck from 2 weeks.

Table needs 1500ms between response Status is 200 and the expected result is shown

In my work-project I’ve got an issue with the search in a data record list.

When I enter the search word into the data record list search field and I wait for the successful response of the automatically generated POST call, there is lag of almost 1500ms between when the call gets the 200 OK response` and when the expected results are shown in the data record list.

The issue is that the table starts to load the results as soon as the success response is received but in this loading time the test moves forward to the next step already which is failing because the table content is not correct yet!

Is there a more pleasant way to skip those 1500ms than to use await page.waitForTimeout(1500)?

This is my current solution

await Promise.all([
  await this.searchField.fill(testNumber.toString()),
  await this.page.waitForResponse(resp => resp.url().includes('<PART OF THE URL>') && resp.status() === 200)
])

await this.page.waitForTimeout(1500)

Without the await page.waitForTimeout(1500) it doesn’t work.

Add newlines before selected hyphen symbols

I have such a pattern in my text:

PSA-image report on

-15.12.1402 (05.03.2024): 0.15 ng/ml

-19.04.1403 (09.07.2024): 0.36ng/ml.

And I have the above text as a one line string:

let string = `PSA-report on -15.12.1402 (05.03.2024): 0.15 ng/ml -19.04.1403 (09.07.2024): 0.36ng/ml.`

I want to convert the string from the one line format to the format you see in the pattern. I want to insert a newline before every hyphen which has a number directly after it.

I tried this code …

string = string.replaceAll('-', 'n-');

… but it adds a hyphen before every newline. How do I match just the ones which are directly followed by a number?

let string = `PSA-report on -15.12.1402 (05.03.2024): 0.15 ng/ml -19.04.1403 (09.07.2024): 0.36ng/ml.`
string = string.replaceAll('-', 'n-');
console.log(string);