How to combine radio inputs with values ​0,1,NA and conditionally

I want to find the sum of this radio input where the raidio input has values ​​0,1,NA. How can I calculate the NA value?
<input type="radio" name="D81" value="0" > <input type="radio" name="D81" value="1" > <input type="radio" name="D81" value="NA" >

<input type="radio" name="D82" value="0" > <input type="radio" name="D82" value="1" > <input type="radio" name="D82" value="NA" >

When the button is checked I need to sum it up.

total = D81+D82=….
result = ….if total >=1 ..result=1

such as

…D81 Checked 1 D82 Checked “NA” // total=1 and result=1

.or D81 Checked 0 D82 Checked “NA” // total=0 and result=0

or D81 Checked 1 D82 Checked 1 //total=2 and result=1

$('input[type="radio"]').click(function() {
var total8 = ($('input[name="D81"]:checked').val(); + $('input[name="D82"]:checked').val() * 1);
                console.log(t8);
                if (total8 >= 1) {
                    sum8 = 1;
                } else {
                    sum8 = 0;
                }
 $("[name=total]").val(total8.toFixed(0));
 $("[name=result]").val(sum8.toFixed(2));

When the button is checked I need to sum it up.

Format chart in Appscript

I have the following issue when I try to change the format of the vertical Axis of a chart by using the setOption instruction in an Appscript. The format does not change. I have tested other setOption like setOption(“vAxis”, {title: “Total”}) and that works.

The code used the following :

function doGet(e) {
  const { spreadsheetId, chartId } = e.parameter;
  const sheets = SpreadsheetApp.openById(spreadsheetId).getSheets();
  const res = sheets.some(sheet => {
    const chart = sheet.getCharts().find(c => c.getChartId() == chartId && c.modify().getChartType() == Charts.ChartType.COLUMN);
    if (chart) {
      sheet.updateChart(chart.modify().setOption("vAxis", {format: "currency"}).build());
      return true;
    }
    return false;
  });
  return ContentService.createTextOutput(res ? "Done." : `Chart with chart ID ${chartId} and COLUMN chart `was not found.`);
}

Why Is my program clicking on the body instead of the element chosen?

enter image description hereI’m quite new at this and It’s my first time and javascript. I wanted to do a bot that manage to make a reservation on a website. I use puppeteer. When I try a double click:

await page.click('#\31 9_0_6', { clickCount: 2 });

It does a double click on the body of the page.
I copied the selector from with the google tools so I think it’s the right one.
Does anyone here could help me?

enter image description here

I tried to use other elements instead of the selector (ID, class…) always the same thing.

I wrote a doscord.js-bot, but the bot can’t catch the members of the server

const { SlashCommandBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('pick')
    .setDescription('根據身分組抽選成員')
    .addStringOption(option =>
      option.setName('topic')
        .setDescription('主題')
        .setRequired(true))
    .addRoleOption(option =>
      option.setName('role')
        .setDescription('身分組')
        .setRequired(true))
    .addIntegerOption(option =>
      option.setName('num')
        .setDescription('人數')
        .setRequired(true)),

  async execute(interaction) {
    try {
      const topic = interaction.options.getString('topic');
      const selectedRole = interaction.options.getRole('role');
      const num = interaction.options.getInteger('num');
      
      console.log('Selected Role ID:', selectedRole.id);
      
      const membersWithRole = await getMembersByRole(interaction.guild, selectedRole);
      console.log('Members with Role:', membersWithRole.size);

      if (membersWithRole.size < num) {
        await interaction.reply('身分組成員數量不足,請重新設定人數。');
        return;
      }
      
      const membersArray = membersWithRole.array();

      const pickedMembers = getRandomMembers(membersArray, num);

      if (pickedMembers.length === 0) {
        await interaction.reply('未選中任何成員,請檢查身分組是否有成員。');
        return;
      }

      await interaction.reply(`主題: ${topic}。抽中:n${pickedMembers}`);

    } catch (error) {
      console.error(error);
      await interaction.reply('發生錯誤,請稍後再試!');
    }
  }
};

async function getMembersByRole(guild, role) {
  try {
    const members = await guild.members.fetch({ query: role.id });
    return members;
  } catch (error) {
    throw new Error('找不到身分組成員。');
  }
}

function getRandomMembers(members, num) {
  const pickedMembers = [];
  const shuffledMembers = members.sort(() => Math.random() - 0.5); 

  for (let i = 0; i < num && i < shuffledMembers.length; i++) {
    const member = shuffledMembers[i];
    pickedMembers.push(`<@${member.id}>`);
  }

  return pickedMembers.join('n');
}

這是我的程式碼
/pick +主題名稱 +身分組 +隨機抽2位

批如:今天吃飯誰去買 @同事群 2
回應: 今天吃飯誰去買 同事群 大a 小b

但我好像一直抓不到成員
Members with Role: 0
但我機器人權限好像都已經給了。

我不是太懂程式,就是拼拼湊湊看網路文章問gpt寫出來的
權限挪到最高 好像也沒辦法

This is my code
/pick +topic name +identity group +randomly draw 2 people

For example: Who will buy the food for dinner today @Colleagues Group 2
Response: Who will buy the food for dinner today? Group of colleagues: big a, small b

But I can’t seem to catch the members
Members with Role: 0
But it seems that my robot permissions have been given.

I don’t know much about programming, I just pieced it together and read online articles and asked gpt to write it.
There seems to be no way to move the permissions to the highest level.

Hello, How to group by on parent and group by child? [closed]

I Have data in array json like data that I show on
I have the following array: I want group by employeeId as parent array and Item group by itemId as child
`

   let arr = [
       {
         employeeId: 1,
         itemId: '001',
         qty: 10
       },
      {
        employeeId: 1,
        itemId: '001',
        qtyRingPull: 20
      },
      {
        employeeId: 1,
        itemId: '002',
        qty: 2000
      },
      {
        employeeId: 2,
        itemId: '002',
        qty: 100
      },
      {
        employeeId: 2,
        itemId: '002',
        qtyRingPull: 60
      }
      ]

And Then data I need like that and How to solve

  let arr = [
       {employeeId: 1},
       items[ {
           itemId: '001',
           qty: 10
           qtyRingPull: 20
       },{
           itemId: '002',
            qty: 10
         }
       ],
      {employeeId: 2},
       items[{
        itemId: '002',
        qty: 100,
        qtyRingPull: 60
      }],
   
      ]
   

React Form Validation Issue: Form State Not Reflecting Errors Set in Child Component within Parent Component

setting error at child Component Code Preview I’m currently facing an issue in a React project where I have a form implemented in a parent component and validation errors being handled in a child component. Despite setting errors in the child component, the form state in the parent component does not seem to reflect these errors, resulting in the form not being marked as invalid.

Here’s a brief overview of the setup:

The form is implemented in a parent component.
Validation errors are being handled and set in a child component.
Even though errors are present in the child component, the form state in the parent component does not show it as invalid.
I’ve double-checked the communication between the parent and child components, and it seems like the errors are being correctly passed from the child to the parent. However, the form state doesn’t seem to update accordingly.

I would appreciate any insights, suggestions, or examples of how to ensure that the form state in the parent component accurately reflects the validation errors set in the child component.

Thank you in advance for your help!

What I’ve Tried:

Verified that the errors are correctly set in the child component by console logging them.
Confirmed that the error values are being passed from the child to the parent component through props.
Checked that the parent component state is being updated with the correct error values.
Examined the form validation logic in the parent component to ensure it’s correctly utilizing the error values.
Expected Outcome:
I expected that when errors are present in the child component and passed to the parent component, the form state in the parent component should recognize these errors and mark the form as invalid. However, despite these efforts, the form state remains unaffected.

By providing this additional information, you give those helping you a clearer picture of your troubleshooting process and enable them to offer more targeted assistance.

How to send two variables in JavaScript

I’m trying to send data from google sheet using API

function sendDataToRoistatAPI() {
  var url = "https:/XXX";
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = spreadsheet.getSheetByName("Users"); 

  var data = sheet.getDataRange().getValues();

  for (var i = 1; i < data.length; i++) {
    var rowData = data[i];
    var payload = {
      manual_custom_metric_id: 2,
      source: rowData[1],
      value: rowData[2],
      period: JSON.parse(rowData[4]),
    };
    var payload1 = {
      manual_custom_metric_id: 3,
      source: rowData[1],
      value: rowData[3],
      period: JSON.parse(rowData[4]),
    };
    //Logger.log(payload);
    //Logger.log(payload1);
    var options = {
      method: "post",
      contentType: "application/json",
      payload: JSON.stringify(payload)
    };

    var response = UrlFetchApp.fetch(url, options);

    Logger.log(response.getContentText()); }

In payload and payload1 I write different kind of data, but cells B and D are the same

What I tried

payload: JSON.stringify([payload, payload1])

and also

var options1 = {
      method: "post",
      contentType: "application/json",
      payload: JSON.stringify(payload1)
    };

    var response1 = UrlFetchApp.fetch(url, options1);

    Logger.log(response1.getContentText());

but it didn’t help

Laravel Nova – JS quit working – TypeError: Cannot read properties of null (reading ‘nextSibling’)

I’m using Laravel Nova on a project and most JavaScript features have suddenly quit working.

When trying to search, I get the following errors:

TypeError: Cannot read properties of null (reading 'nextSibling')

TypeError: Cannot read properties of null (reading 'parentNode')

I am using:

  • Laravel version: 9.52.16
  • Laravel Mix version: 6.0.49
  • Nova version: 4.32.1
  • PHP version: 8.2.12
  • Node version: 18.0.0
  • NPM version: 8.6.0

This is compatible with Nova’s requirements:

  • Composer
  • Laravel Framework 8.x, 9.x, or 10.x
  • Laravel Mix 6
  • Node.js (Version 14.x+)
  • NPM
  • PHP 8

Any idea why this could be happening?

nextjs: my dynamic routes doesn’t work after i use rewrites

this is my project structure and it’s work before i add rewrites to my project

enter image description here

-dashboard
–admin
–page.tsx
—[adminId]
—page.tsx

–cars
–page.tsx
—[carId]
—page.tsx

-login
— page.tsx

i can access /dashboard/admin, /dashboard/admin/1, /dashboard/cars, /dashboard/cars/1, /login

but when i add

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    formats: ["image/webp"],
  },
/// ============== don't have this it can access dynamic but i want to use it
  async rewrites() {
    return [
      {
        source: "/:path*",
        destination: "/app/:path*",
      },
    ];
  },
/// =============== don't have this it can access dynamic but i want to use it

  assetPrefix: process.env.NODE_ENV === "production" ? "/app/" : "",
  publicRuntimeConfig: {
    basePath: process.env.NEXT_PUBLIC_BASEPATH,
  },
};

module.exports = nextConfig;

Now It’s can only access
/dashboard/admin, /dashboard/cars, /login

I can not access to /dashboard/admin/1, /dashboard/cars/1, any more

enter image description here

How can i fix this, Thanks

The behavior of promise.then() in node.js different from browser

let p1 = new Promise((resolve, reject) => resolve())
let p2 = p1.then((result) => {return 1})

console.dir(p1)
console.dir(p2)

According to what I learned,p2 would be a fulfilled promise with result=1.
I checked p2 in browser and it works well.
However, when I run the same code in node.js, p2 becomes a pending promise.
I’m new in javascript and node.js, so I want to learn the behavior of Promise correctly.

I have tried to search ‘node.js Promise.then()’ in Google but found nothing relative to my question.

How to solve problems with debuggin JS on Visual Studio 2022?

I have SPA project with ReactJS at the frontend and WebAPI at the backend.

In the past I put breakpoints and it did work correctly. I didn’t update my VS also I didn’t change my project from that time (maybe 5 month ago)

Now, I can’t put breakepoint whereever I want and if I put and catch breakpoint and then I press F11 or F10 then system goes to different places of code instead nextline.

Why it happen?
How to correct it?

Is there a way to fix the styling using javascript in html code

I am making a chatbot, but the function i am using to append messages is also responsible for displaying the bot icon and user icon. I want the bot icon to be justified to start (left side) and the user icon to be justified to end (right side) for my design. I’ve tried many ways to fix it. But there are two other functions that are creating a problem. first one is to display a welcome message and the other one is to ask a series of questions if a process is initiated. I cant seem to get past this problem.

        const userImgSrc = "https://i.ibb.co/d5b84Xw/Untitled-design.png";
        const botImgSrc = "https://i.ibb.co/fSNP7Rz/icons8-chatgpt-512.png";

        const userPosition = "justify-content-end";
        const botPosition = "justify-content-start";

        function appendMessage(content, isUser) {
            const date = new Date();
            const hour = date.getHours();
            const minute = date.getMinutes();
            str_time = hour + ":" + minute;

            const userImgSrc = "https://i.ibb.co/d5b84Xw/Untitled-design.png";
            const botImgSrc = "https://i.ibb.co/fSNP7Rz/icons8-chatgpt-512.png";

            const imgSrc = isUser ? userImgSrc : botImgSrc;
            const cssClass = isUser ? "msg_cotainer_send" : "msg_cotainer";
            const justifyClass = isUser ? "justify-content-end" : "justify-content-start";

            // Check if it's the initial bot message or sequential bot message
            const isInitialBotMessage = content.includes("Welcome to Headstart Admissions Co-Pilot!");

            const messageHtml = `
            <div class="d-flex ${justifyClass} mb-4">
                <div class="img_cont_msg">
                    <img src="${imgSrc}" class="rounded-circle user_img_msg">
                </div>
                <div class="${cssClass}">
                    ${content}
                    <span class="msg_time">${str_time}</span>
                </div>
            </div>`;

            $("#messageFormeight").append($.parseHTML(messageHtml));
        }

I was trying to fix this problem on my own but I wasn’t able to do so. The output i was getting will always have the icons on either right or left side of the page. I then used chatgpt and blackbox to fix the problem. But in that case the icon for bot message was on the right (justified to end) for welcome message and sequential messages, it fixed the normal question answering.

Cannot use import statement outside a module syntax error during unit testing using enzyme

/*` FAIL src/ApiComponent.test.js
● Test suite failed to run

Jest encountered an unexpected token

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

By default "node_modules" folder is ignored by transformers.

Here's what you can do:
 • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
 • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
 • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
 • If you need a custom transformation specify a "transform" option in your config.
 • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

You'll find more details and examples of these config options in the docs:
https://jestjs.io/docs/configuration
For information about custom transformations, see:
https://jestjs.io/docs/code-transformation

Details:

C:GenzeonEnzymemy-api-appnode_modulesaxiosindex.js:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import axios from './lib/axios.js';
                                                                                  ^^^^^^

SyntaxError: Cannot use import statement outside a module

  1 | // src/ApiComponent.js
  2 | import React, { useState, useEffect } from 'react';
> 3 | import axios from 'axios';
    | ^
  4 |
  5 | const ApiComponent = () => {
  6 |     const [data, setData] = useState(null);

  at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1728:14)
  at Object.<anonymous> (src/ApiComponent.js:3:1)
  at Object.<anonymous> (src/ApiComponent.test.js:5:1)
  at TestScheduler.scheduleTests (node_modules/@jest/core/build/TestScheduler.js:333:13)
  at runJest (node_modules/@jest/core/build/runJest.js:404:19)

Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 8.498 s`*/

import React, { useState, useEffect } from ‘react’;
import axios from ‘axios’;

const ApiComponent = () => {
const [data, setData] = useState(null);

useEffect(() => {
    const fetchData = async () => {
        try {
            const response = await axios.get('https://jsonplaceholder.typicode.com/posts/1');
            setData(response.data);
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    fetchData();
}, []);

return (
    <div>
        <h1>API Data</h1>
        {data ? (
            <div>
                <p>Title: {data.title}</p>
                <p>Body: {data.body}</p>
            </div>
        ) : (
            <p>Loading...</p>
        )}
    </div>
);

};

export default ApiComponent;

Creating a add to card block

Create a add to card block in website with function in js

I expecting a proper js card code and it should be working properly with UI . increase of number by clicking button . The data should be deleted when we click to cross button image should be hidden and show

Posting software update to embedded system from external website

I have an embedded program running on a Raspberry Pi Pico with a web interface via its USB port. I’d like to be able to send it a software update (a *.bin file) from a server on the web (let’s say www.parentcompany.com/software/newversion.bin)

I can select a local file from my computer and send it to the Pico using Javascript no problems using POST, but I’d like to be able to pull it from the location above and POST it to the Pico without the user having to download it to their local computer first.

The process would be: the user clicks on “Software Update”, some javascript code grabs the file from the URL and POSTs it to the Pico automatically.

Any thoughts on how/if this could be achieved? Note I can’t use PHP as the Pico doesn’t support it, but javascript has been working a treat thus far.

Cheers
Josh

So far all I’ve done to solve this element of the design is unsuccessfully searched the web and forums for other people having solved a similar problem already. The closest I’ve found is to have a hidden item on the webpage that is the file I want to download, so it’s in the cache ready to go, but I’ve not had enough experience in this aspect to apply the idea to my use case.