how to make specific input readonly and take value (0.00) when a specific value exists in another input using JaQuery

$(document).on('change keyup', '.debtor , .creditor', function() {
  //get amt and qty value
  var debtor = $(this).closest('tr').find('.debtor').val();
  var creditor = $(this).closest('tr').find('.creditor').val();
  if (debtor > 0) {
    $(this).closest('tr').find('.creditor').val(0).css("pointer-events", "none", "cursor", "not-allowed");
  } else {}
  if (creditor > 0) {
    $(this).closest('tr').find('.debtor').val(0).css("pointer-events", "none", "cursor", "not-allowed");
  } else {}
});
<td class="td"><input type="number" class="form-control debtor"></td>
<td class="td"><input type="number" class="form-control creditor"></td>

<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.3/jquery.min.js"></script>

I am trying to make one of the two inputs take the read-only property automatically and take value (0.00) when the other input has any value entered, and when this value is deleted (i.e. when emptying the field that has a value) the two inputs take the normal position and are open to accepting values, so as soon as I write a value in any one of them it takes The other one is read-only mode and take value (0.00), and the (cursor”,”not-allowed) property is enabled automatically, and as soon as the value is deleted from the other input , the read-only mode is canceled and the (cursor”,”not-allowed) property is removed automatically.

JQuery ajax call connection refuse error : how to fix

I’m using jQuery ajax to pass same data to front end , but when I try to call a get method from my UI I’m getting this error. I had to hide few methods names due to security reasons. Any help would be really appreciated. Thanks

My code is:

I’m using jetty as my server.

I thought this could be due to cross origin issue and add the following code , but it solve the issue.
@Bean
public WebMvcConfigurer corsConfigurer(){
return new WebMvcConfigurer() {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping(“/**”).allowedOrigins(“http://localhost:8080”);
}
};
}

MSAL Error: You may need an appropriate loader to handle this file type

I am trying to configure Azure MSAL from scratch. This is new React app with v16.
But i am getting error. I have tried to download the Azure MSAL React example project it is working on React v18.

Getting error in file: “./node_modules/@azure/msal-react/dist/msal-react.esm.js”

Error:

    Module parse failed: Unexpected token (135:13)
You may need an appropriate loader to handle this file type.
|   if (newInProgress !== previousState.inProgress && !accountArraysAreEqual(currentAccounts, previousState.accounts)) {
|     // Both inProgress and accounts changed
|     return { ...previousState,
|       inProgress: newInProgress,
|       accounts: currentAccounts

Working with:

Package.json:

{
  "name": "msal-test",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@azure/msal-browser": "^2.34.0",
    "@azure/msal-react": "^1.5.4",
    "react": "^16.12.0",
    "react-dom": "16.12",
    "react-scripts": "^1.1.5",
    "web-vitals": "^3.3.0"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/core": "^7.21.3",
    "@babel/plugin-proposal-class-properties": "^7.18.6",
    "@babel/plugin-proposal-object-rest-spread": "^7.20.7",
    "@babel/preset-env": "^7.20.2",
    "@babel/preset-react": "^7.18.6",
    "babel-loader": "^9.1.2",
    "babel-plugin-transform-class-properties": "^6.24.1",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "file-loader": "^6.2.0",
    "url-loader": "^4.1.1",
    "webpack": "^5.76.2",
    "webpack-cli": "^5.0.1",
    "webpack-dev-server": "^4.12.0"
  }
}

.babelrc

{
    "presets": [
        "@babel/preset-typescript",
        [
            "@babel/preset-env",
            {
                "modules": "commonjs"
            }
        ]
    ],
    "plugins": [
        "@babel/proposal-class-properties",
        "@babel/proposal-object-rest-spread"
    ]
}

I am not able to understand loader is required in dependency or can i configure any thing to solve this.

Note: Working in React 18 and giving this error in react 16

a lot of typeorm queries in succession failing basically of 2 categories, updating the user table and creating transactions but

async subscribeUserToPlan(planId: string, userId: string) {
    const plan = await this.planService.findOne(planId);
    const user = await this.findOne(userId);

    await this.userRepository
      .createQueryBuilder('user')
      .update(User)
      .set({
        plan: plan,
        isHibaActive: true,
        balance: () => `balance + ${plan.bv}`,
        shopping_wallet: () => `shopping_wallet + ${plan.coupon}`,
      })
      .where('id = :id', { id: userId })
      .execute();

    await this.mlmService.bonus(userId);
    await this.mlmService.binaryBonus(user.sponsor.id, user.position);
    await this.mlmService.matchingBonus(user.referrer.id);
    await this.mlmService.groupSalesBonus(user);
}

the following are the referenced methods: bonus binaryBonus matchingBonus groupSalesBonus

async bonus(id: string) {
    const user = await this.findOne(id);
    if (user.referrer) {
      const referral_comission = this.getComission(
        user.plan.bv,
        user.referrer.plan.referralBonus,
      );

      if (user.referrer.plan.price < user.plan.price) {
        const higher_ref_comission = this.getComission(
          referral_comission,
          user.referrer.plan.higherReferralBonus,
        );
        await this.referralBonus(
          id,
          user,
          higher_ref_comission,
          'higher_ref_bonus',
        );

        const upgrade_comission = this.getComission(
          referral_comission,
          100 - user.referrer.plan.higherReferralBonus,
        );
        await this.upgradeWalletBonus(id, user, upgrade_comission);
        // console.log('namee', referral_comission, upgrade_comission);
      } else {
        await this.referralBonus(
          id,
          user,
          referral_comission,
          'referral_bonus',
        );
      }
    }
  }
async binaryBonus(id: string, position: string) {
    const user = await this.findOne(id);
    const userTree = await this.getUserTree(id);
    console.log('innnn..');
    if (userTree[1] && userTree[2] && userTree[0].binary_bonus == 0) {
      console.log('2innnn..');
      const amount = 4;
      // pre-transaction
      const pre_transaction = await this.transactionService.create({
        user: user,
        preBalance: user.balance,
      });
      // award bonus
      this.usersRepository
        .createQueryBuilder('user')
        .update(User)
        .set({
          balance: () => `balance + ${amount}`,
          total_bonus: () => `total_bonus + ${amount}`,
          binary_bonus: () => `binary_bonus + ${amount}`,
        })
        .where('id = :id', { id: user.id })
        .execute();
      // post-transaction
      await this.transactionService.update(pre_transaction.id, {
        charge: 0,
        postBalance: Number((await this.findOne(user.id)).balance) + amount,
        amount,
        trx: generateTrx(),
        trxType: '+',
        details: 'binary_bonus',
      });
      // add bv log
      await this.bvLogService.create({
        user,
        amount,
        position,
        details: 'binary_bonus',
      });
    }
    return;
  }
async matchingBonus(id: string) {
    const user = await this.findOne(id);
    const userTree = await this.getUserTree(id);
    if (
      userTree[1] &&
      userTree[2] &&
      userTree[3] &&
      userTree[4] &&
      userTree[5] &&
      userTree[6] &&
      user.matching_bonus == 0
    ) {
      let amount: number, position: string;
      if (userTree[2].total_bonus > userTree[1]?.total_bonus) {
        amount = userTree[1]?.total_bonus * 0.15;
        position = userTree[1]?.position;
      } else {
        amount = userTree[2]?.total_bonus * 0.15;
        position = userTree[2]?.position;
      }
    
      // pre-transaction
      const pre_transaction = await this.transactionService.create({
        user: user,
        preBalance: user.balance,
      });
      // award bonus
      this.usersRepository
        .createQueryBuilder('user')
        .update(User)
        .set({
          // total_referral_bonus: 9,
          balance: () => `balance + ${amount}`,
          total_bonus: () => `total_bonus + ${amount}`,
          matching_bonus: () => `matching_bonus + ${amount}`,
        })
        .where('id = :id', { id: user.id })
        .execute();
    
      // post-transaction
      await this.transactionService.update(pre_transaction.id, {
        charge: 0,
        postBalance: Number((await this.findOne(user.id)).balance) + amount,
        amount,
        trx: generateTrx(),
        trxType: '+',
        details: 'matching_bonus',
      });
      // add bv log
      await this.bvLogService.create({
        user,
        amount,
        position,
        details: 'matching_bonus',
      });
    }
    return;
  }
async groupSalesBonus(user: User) {
    if (user.referrer) {
      // check new user's position on referrer's tree to determine reward
      const referrerTree = await this.getUserTree(user.referrer.id);
      const treeIds = [];
      for (const u of referrerTree) {
        treeIds.push(u?.id);
      }
      const userPositionOnReferrerTree = treeIds.indexOf(user.id);
      let value: number, reward: number;

      if (user.referrer.total_bv_left > user.referrer.total_bv_right) {
        value = user.referrer.total_bv_right;
      } else {
        value = user.referrer.total_bv_left;
      }

      function between(x: number, min: number, max: number) {
        return x >= min && x <= max;
      }
      // 6th - 8th
      if (between(userPositionOnReferrerTree, 63, 510)) {
        reward = this.getComission(value, 5);
      }
      console.log('final', reward);

      // 9th - 12th
      if (between(userPositionOnReferrerTree, 63, 510)) {
        reward = this.getComission(value, 3);
      }
      // 13th - 16th
      if (between(userPositionOnReferrerTree, 63, 510)) {
        reward = this.getComission(value, 2);
      }
      // 17th - 20th
      if (between(userPositionOnReferrerTree, 63, 510)) {
        reward = this.getComission(value, 1);
      }
      // 21th - 25th
      if (between(userPositionOnReferrerTree, 63, 510)) {
        reward = this.getComission(value, 0.5);
      }

      reward = 6
      if (reward) {
        // pre-transaction
        const pre_transaction = await this.transactionService.create({
          user: user.referrer,
          preBalance: user.referrer.balance,
        });

        this.usersRepository
          .createQueryBuilder()
          .update(User)
          .set({
            balance: () => `balance + ${reward}`,
            total_bonus: () => `total_bonus + ${reward}`,
          })
          .where('id = :id', { id: user.referrer.id })
          .execute();

        // post-transaction
        await this.transactionService.update(pre_transaction.id, {
          charge: 0,
          postBalance: Number((await this.findOne(user.referrer.id)).balance) + reward,
          amount: reward,
          trx: generateTrx(),
          trxType: '+',
          details: 'group_sales_bonus',
        });
        // add bv log
        await this.bvLogService.create({
          user: user.referrer,
          amount: reward,
          position: user.position,
          details: 'group_sales_bonus',
        });
      }
    }
  }

when the subscribUserToPlan method runs, the query builder operation in it works fine but other querybuilder operations in bonus binaryBonus matchingBonus groupSalesBonus methods don’t work but the create and update transaction operations in all of them succeed.

HTML canvas setTranslate does not work with onClick

I have an HTML canvas with some content. This content needs to be draw translated to the canvas. That is working. But now I need to detect which object is clicked, so I need to search in the coordinates of the objects to find an matching one. But since the objects are drawn at a different x, y position then known I don’t know how to match them.

I have created this fiddle with the situation. I want to highlight the correct object when clicked. One thing to keep in mind is that this canvas is used in an environment (HMI screen connected with PLC) where I don’t have the full functions which are normally available in a browser. That means also that I only get an x and y coordinate on the ‘onClick’ function.

https://jsfiddle.net/gkho89wd/

This code is not the cleanest but I use this to try some things.
Quick explanation of this code:

I have an array with some objects (boxes)

const rawPositions = [];

every position has some properties including x and y, width and length. Those are used to draw some rects on the canvas. I also calculate an ‘ratioX’ and ‘ratioY’ to scale everything. Those x and y are used to actually draw.

Before I draw the rects, I’m doing an ‘setTransform’ to horizontally flip the canvas:

ctx.setTransform(1, 0, 0, 1, 0, ctx.height);

How can I translate the coordinates from the click event to the ‘original’ ones?

Pass a javascript variable to README.md/ markdown

I want to use something of this sort in my readme –

wherein the assetsBaseUrl is resolved by a javascript function called getAssetsBaseUrl. How can I pass the value of assetsBaseUrl to my README.md?

I am able to embed javascript in markdown as shown below

  import getAssetsBaseUrl from './utils';
  private assetsBaseUrl = getAssetsBaseUrl('');

But not able to access such variables

How we get the device type (phone, tab, desktop) of the react-native app without using package?

I want to get the device type(phone, tablet or desktop) in a react-native app but without using any package

Right now I’m using “Platform” from react-native and getting this output:

{
  "Model": "abc",
  "reactNativeVersion": {
    "minor": 71,
    "prerelease": null,
    "major": 0,
    "patch": 4
  },
  "Version": 31,
  "uiMode": "normal",
  "Release": "12",
  "Fingerprint": ".....",
  "Serial": "unknown",
  "isTesting": false,
  "ServerHost": "localhost:8081",
  "Manufacturer": "...",
  "Brand": "..."
}

but there is no field which gives me information about the device type: means “mobile”, “tab”, “desktop” etc…

So, if there is no direct solution for this in react-native please suggest to me how can I get this value either by native solution means in android or iOS.
Here I just want a custom solution instead of packages.

Overhead of any react hook

Context: We have a theme context provider which passes down a theme to all our children. The theme is calculated basis the device’s dimensions. We can easily extract the values out of this theme using useTheme hook at any component.

Also, we have a constants file where we generate our theme and export the above values.

So in our React codebase we have to two ways to get theme properties. Either using the useTheme hook or importing the constants from the constants file.

I am assuming that using the constant will be computationally efficient because react hooks are special functions (with their special rules) and there must be some overhead to them. Can anyone clarify which is the better approach and overall what overhead do react hooks add?

function of javascript always run without involk [duplicate]

here HTML

    <form action="" method="get">
                <input type="text" placeholder="Họ" id="inputHo"><br>
                <span id="annouceHo"></span><br>
                <input type="submit" id="btnSubmit">
    </form>

here JAVASCRIPT

    var annouceHo= document.getElementById("annouceHo");
    var  btnSubmit= document.getElementById("btnSubmit");
    btnSubmit.onclick=checkValuation();
    function checkValuation(){
    inputHo= document.getElementById("inputHo").value;
    if (inputHo==""){
        // alert("check");
        annouceHo.innerHTML="first name cant empty";
      } 
    }

**the function checkValuation alway run althought i didnt call it by click button. **

How can I find number of days excluding saturdays and sundays using Datepicker?

I found a code for finding days excluding weekends between two date without using datapicker but I need to show calendar(visually).I wrote code for showing calendar with datapicker but I could not be successful to update the code to write the code the way to cover the weekend.I need this calendar for an ASP.NET Core MVC project.

I will write both:

<script>
    $(function () {
        $("#date1").datepicker();
        var date1 = $("#date1")
    });
    $(function () {
        $("#date2").datepicker();
        var date2 = $("#date2")
    });
    count = 0;
    
    function Diffr() {
        date1 = new Date(date1.value);
        date2 = new Date(date2.value);
        if (date1 < date2)
        {
            var milli_seconds = date1.getTime() - date2.getTime();
        }
        else
            var milli_seconds = date2.getTime() - date1.getTime();
      
        var days = milli_seconds / (1000 * 3600 * 24);
        document.getElementById("idd").innerHTML = Math.round(Math.abs(days));
    }
</script>

<p>
    Date1 :
    <input type="text" id="date1">
</p>

<p>
    Date2 :
    <input type="text" id="date2">
</p>
<button id="sub" class="btn btn-success" onclick="Diffr()">Submit</button>
<h3 id="idd">Difference</h3>

The other one is:

<script>
    function CalculateDiffr() {
        var date = document.getElementById('txt_Start').value;
        var date1 = date.split('.')[1] + "/" + date.split('.')[0] + "/" + date.split('.')[2];

        date = document.getElementById('txt_Last').value;
        var date2 = date.split('.')[1] + "/" + date.split('.')[0] + "/" + date.split('.')[2];

        var days = ['N', 'Y', 'Y', 'Y', 'Y', 'Y', 'N'];

        var d1 = new Date(date1);
        var d2 = new Date(date2);

        var busssinessday= 0;

        while (true) {

            if (d1 > d2) {
                break;
            }

            var dayName = days[d1.getDay()];

            if (dayName != "N") {
                businessday++;
            }

            d1.setDate(d1.getDate() + 1);
        }

        document.getElementById('Days').value = businessday.toString();
    }
</script>

@Html.TextBox("txt_Start", "", new { @class = "form-control" })
@Html.TextBox("txt_Last", "", new { @class = "form-control" })
@Html.TextBox("Days", "", new { @class = "form-control" })

<button onclick="CalculateDiffr()">OK</button>

Code inside .then after SendGrid request runs on localhost but not on Vercel

I’ve spent over an hour on this and still can’t figure why this console.log won’t work on Vercel production. It works fine on localhost but not on Vercel.

async function sendGridMail(email: string, unsubscribeLink: string, msg: string) {
  sgMail.setApiKey(process.env.SENDGRID_API_KEY_TEST!)

  return sgMail.send(msg).then(() => {
    console.log('email sent')
  }).catch((error) => {
    console.log(error.message)
  })
}

The email is sent just fine, but the console.log simply won’t work, no matter what I do.

I’ve tried including a return before the console.log. I’ve tried removing the return from before sgMail.send, I’ve tried including an await before sgMail.send, but none of this seems to work.
All the above solutions work fine on localhost, though.
This console.log is not important for the function but I would like to understand why it doesn’t run on Vercel.

I am having trouble with declaration files in TypeScript

I’m trying to use the trace function in my TypeScript code, which has been declared in a .d.ts file as follows:

declare function trace(arg: string | number | boolean);
declare function trace(arg: { id: number; name: string });

However, when I try to use the trace function in my code in the file index.ts as follows:

trace("trace with string"); // calls the trace function with a string argument
trace(true); // calls the trace function with a boolean argument
trace(1); // calls the trace function with a number argument
trace({ id: 1, name: "test" }); // calls the trace function with an object argument

I get the following error:

ReferenceError: trace is not defined

Can anyone help and tell me what I am doing wrong? The declaration option is enabled in tsconfig.json too.

Thank you in advance.

Uncaught TypeError: Cannot read properties of undefined (reading ‘capture’)

I am getting the above error when trying to use tabCapture API in the content-script.js

I used the required permissions in manifest.json file, the tabCapture API is working in the popup.js file, but I want to use it after the button click inside the content-script.js

content.js
    var recordButton = document.createElement("button");
    recordButton.innerHTML = "Record";
    
    recordButton.addEventListener("click", function() {
      // Use the chrome.tabCapture API to capture the current tab and record the screen
       chrome.tabCapture.capture({ video: true, audio: true }, function(stream) {
      
           const video = document.createElement("video");
           video.srcObject = stream;
           video.style.position = "fixed";
           video.style.bottom = "0";
           video.style.right = "0";
           video.style.zIndex = "9999";
           document.body.appendChild(video);
         
       });
      
    });
    
    // Inject the record button into the page
    document.body.appendChild(recordButton);
manifest.json
{
    "manifest_version": 3,
    "name": "Once More",
    "version": "1.0",
    "description": "Description of my extension",
    "permissions": ["scripting", "activeTab", "tabs", "tabCapture"],
    "action": {
      "default_popup": "popup.html",
      "default_title": "Click Me"
       
    },
    
      "background": {
        "service_worker": "background.js"
      },
      "host_permissions": ["<all_urls>"]
    
  }

The error looks like this :- Uncaught TypeError: Cannot read properties of undefined (reading 'capture')

How to perform search in nested object hierarchy to build list ReactJS?

I want to build a search function which can result in returning the search response in deeply nested hierarchy.

Type of data I am having::

[
  {
    label: "Navigation",
    accordion: true,
    key: "navigation",
    actions: [
      {
        action: "navigateTo",
        label: "Navigate To"
      },
      {
        action: "Back",
        label: "Back"
      },
      {
        action: "closeDialog",
        label: "Close Dialog"
      },
      {
        action: "delay",
        label: "Delay"
      }
    ]
  }]

and I am searching “Delay” it will returns the following result.

[
  {
    label: "Navigation",
    accordion: true,
    key: "navigation",
    actions: [
      {
        action: "delay",
        label: "Delay"
      }
    ]
  }]

If I am searching “navigation” this is expected to return the complete object with a “navigation” label.

[
  {
    label: "Navigation",
    accordion: true,
    key: "navigation",
    actions: [
      {
        action: "navigateTo",
        label: "Navigate To"
      },
      {
        action: "Back",
        label: "Back"
      },
      {
        action: "closeDialog",
        label: "Close Dialog"
      },
      {
        action: "delay",
        label: "Delay"
      }
    ]
  }]

I need help building a search function which can be able to search the results on the basis of labels in the nested deep hierarchy. Here I want to perform a search on the basis of the “label” field. And will always return the result with its parent-wrapped object.
Here you can check the sample I have created:: https://codesandbox.io/s/focused-kapitsa-ctl8ud?file=/src/App.js