How to re call a function so it can generate a new number

I have my getComputerCHoice function, it generates a number when the page load but not after that, i have tried to re call it inside my getHumanCHoice since i am re calling it over and over but it does not work and i am runing off ideas.
I will add the whole JavaScript code for contex

let humanScore = 0 ;
let  computerScore= 0 ;

            
            const humanSelection=getHumanChoice();
            const compSelection=getComputerChoice();
            let compChoice = compSelection;
            let humanChoice = humanSelection;
            
        function getComputerChoice(){
    
            let ramdom= Math.floor(Math.random()*3)+1; // mat floor round the number down, math random generates a number between 0 and 1, multiply by 3, max value now is 2, add one to bring up to 3.
            
            if (ramdom == 1){
               
               return "rock" ;
       
            }else if (ramdom == 2) {
               
               return "paper" ;
       
            } else {
               
               return "scissors" ;
            }
            
            
       }
 

            function getHumanChoice(){
            
                const btnPlayerChoice = document.querySelectorAll("button");
                let playerChoice= "";

                btnPlayerChoice.forEach((button) => {
                button.addEventListener("click", () => {
                    
                    
                    playerChoice=button.id;

                    playRound(playerChoice, compChoice);
                    
                    
            
                }) ;
            });
           
            return playerChoice;

            };
            
            
            

        function playRound(humanChoice,randomNumber){
    

            if (humanChoice === compChoice){

                
                return console.log (`${humanChoice} and ${compChoice} means a tie!`);
                
        
            } else if (humanChoice === "rock" && compChoice === "scissors") {
                
                console.log (`${humanChoice} win against ${compChoice} !`);
                return humanScore+=1;
        
            } else if (humanChoice === "paper" && compChoice === "rock"){
        
                console.log (`${humanChoice} win against ${compChoice} !`);
                return humanScore+=1;
        
            }else if (humanChoice === "scissors" && compChoice === "paper") {
        
                console.log (`${humanChoice} win against ${compChoice} !`);
                return humanScore+=1;
        
            } else {
                console.log (`${humanChoice} loses against ${compChoice} !`);
               return computerScore+=1;;
            }
        }
        

            if ( humanScore>computerScore) {

                alert(`Congratulations! PLayer wins with a score of ${humanScore}`);
                compChoice=0;

            } else if ( humanScore<computerScore){
                alert(`Sorry! the machine wins with a score of ${computerScore}`);
                compChoice=0;
            }

The last two if statements do nothing, they are there because i am re working this code. My focus is on the code bellow

Here is where i am struggling, i have tried the comments one after another, no everithing together

function getHumanChoice(){
            
                const btnPlayerChoice = document.querySelectorAll("button");
                let playerChoice= "";

                btnPlayerChoice.forEach((button) => {
                button.addEventListener("click", () => {
                    
                    
                    playerChoice=button.id;

                   // playRound(playerChoice, getComputerChoice());
                    playRound(playerChoice, compChoice);

                    // let newNumber= getComputerChoice();
                    //compChoice=0;
                    //compChoice = compSelection; 
                    // getComputerChoice();
                    
            
                }) ;
            });
           //getComputerChoice();
            return playerChoice;

            };

OpenLayers – remove vertex from geometry bud disable editing (adding or dragging vertex)

I need in OpenLayers to make the Modify tool work only for deleting geometry vertices. I only managed to get the vertex to delete after clicking on the snapped vertex, but unfortunately it is still possible to grab the vertex and change its coordinates by dragging.

My code:

this._removeVertex = new Modify({ source: source, insertVertexCondition: never, deleteCondition: singleClick });

The problem is that when I add a condition for the Modify tool (for example condition: click) deleteCondtion doesn’t work for some reason.

So I tried to work around it this way:

let allowDragging = true;

this._removeVertex.on('modifystart', () => {
    allowDragging = false;
});

this._removeVertex.on('modifyend', () => {
    allowDragging = true;
});

this._map.on('pointermove', (event) => {
    if (!allowDragging) {
        event.stopPropagation();
    }
});

however, this disables dragging vertex after some time, so it’s not a good solution.

Question is:

Is there a solution in OpenLayers where one can only delete vertices from the drawn geometry using singleClick but disable any other editing at the same time?

Thank you

Convert javascript code to bash script code

Below is the javascript code which produces output after it’s successful execution to something like this 542432b384789

Math.random().toString(16).substr(2, 32)

How can reproduce this operation in the linux bash script?

Tried below code

#!/bin/bash

# Generate a random number between 0 and 1
RANDOM_NUMBER=$(Math.random())

# Convert the random number to a hexadecimal string
HEX_STRING=$(RANDOM_NUMBER.toString(16))

# Remove the first two characters of the hexadecimal string
RANDOM_STRING=$(HEX_STRING.substr(2, 32))

# Print the random string
echo $RANDOM_STRING

But it’s throwing below error messages.

test-string.sh: command substitution: line 5: syntax error near unexpected token `)'
test-string.sh: command substitution: line 5: `Math.random())'
test-string.sh: command substitution: line 8: syntax error near unexpected token `16'
test-string.sh: command substitution: line 8: `RANDOM_NUMBER.toString(16))'
test-string.sh: command substitution: line 11: syntax error near unexpected token `2,'
test-string.sh: command substitution: line 11: `HEX_STRING.substr(2, 32))'

How can we reproduce this javascript operation in the Linux bash script?

Problem when sending data with to c# controller with ajax, javascript

I am trying to send my session storage from the view to a controller.
Here is my code:

`$(document).ready(function () {

document.querySelector('.k-spreadsheet-sheets-bar-add').style.display = 'none';

const urlParams = new URLSearchParams(window.location.search);
const id = urlParams.get('analysisId');
var sessionPassword = sessionStorage.getItem('analysisPassword').toString();



$.ajax({
    url: "@Url.Action("Create", "Create")",
    data: { id: id, sessionPassword: sessionPassword },
    contentType: "application/json",
    type: "GET",
    success: function (response) {
        if (response.success) {
            alert("Daten wurden erfolgreich geladen!");
        }
        else if (response.passwordIncorrect) {
            alert("Kein gültiges Passwort!");
            window.location.href = 'http://localhost:55844/Index/Index'
        }
    },
    error: function () {
        alert("Error loading data.");
    }
});

})`

I want to sen the “sessionPassword” to my Controller:

public ActionResult Create(int analysisId, string password)

This is how i want to recive it. The analysisId is sent correct, but the password not…

I did the “.toString” on the sessionPassword, i thought this was the problem, but it did not solve.

Warning when using moment-with-locales

../../../../node_modules/moment/min/moment-with-locales.min.js
Module not found: Can't resolve './locale' in 'C:Usersarnavnode_modulesmomentmin'

Import trace for requested module:
../../../../node_modules/moment/min/moment-with-locales.min.js
./node_modules/moment-with-locales-es6/index.js
./src/components/events/EventDetails.jsx
./src/components/events/EventGridLayout.jsx
./src/components/events/SingleEventCard.jsx
./src/components/events/MainPageEeventList.jsx
./src/app/page.js

get this waring when i change moment package to moment-with-locales-es6 package to change the language of months in my website . What does this mean

i want to save data in the local storage

i am creating a file where there is a form.. when a user enters his info in the form and click to submit the data should be display in the user list in the form of cards… im using post method to send the data… but my data is not displaying in the user list…. neither the previous cards in the user list are editing and deleting… i have used post, get, put and delete methods for these functionalities… but these are not working…. there is not any error in the file but functions are not performing that way i want…

i tried many times to save the users in the user list’s local storage and edit and delete the user cards.. but i am unable to do so…

Not able to get a function to work on page load but it work on click. How can I get it to work on both?

I am trying to call a the subSection function both on onLoad and on click. But for some reason my code work only on On onClick but not on OnLoad and I am not sure why.

Here is my code:

fileOne.js

$(function () {
    if ($('.MainSection .folderTab').length) {
 
        subSection($('a.tab.present'));
 
        // calling subSection() on Click.
        $('.MainSection .folderTab a.tab').click(function() {
            subSection($(this));
        });
 
        // calling subSection() on page load.
        $('.MainSection .folderTab a.tab').on( "load", function() {
            subSection($(this));
        });
    }
});

fileTwo.js

function subSection(element) {
    // some code...
}

Currently on Click, the subSection function get trigged properly and it works. But I also want to call the subSection function on page load, and for some reason it not working. Am I not calling the function on page load correctly?

I have tried using the .on( "load", function() or just calling the function directly like this: subSection($(this));. But none of these approaches are triggering the function on page load.

Regular expression for finding a function call

I’m trying to find all calls to a function $t
I tried this expression
/$t([^)]+)/g
but this does not work if I have a ) in the string like so

$t('Name (optional)')

other possible complex values can be

$t('hello' + x)
$t("hello"  + x)
$t(`hello ${x}`)
$t(x)

I assume I need a lookbehind?
Thank you

Unchecked Input for Loop Condition CheckMarx for simple code

I created some little app that get args and use them to create report file.
but i got medium checkmarx.
this is my code (after i tried to fix the checkmarx with Math.min):

import reporter from 'cucumber-html-reporter';

/*******************************************************
 * Only for local run, this comes from the base docker
 */

const options = {
    theme: 'bootstrap',
    jsonFile: 'report/reportData.json',
    output: 'report/report.html',
    reportSuiteAsScenarios: true,
    scenarioTimestamp: false,
    launchReport: false,
    brandTitle: 'Puppeteer Tests Report',
    columnLayout: 1,
    metadata: {
        Name: 'Puppeteer Tests'
    }
};

const total = Math.min(parseInt(process.argv.length), 1000);
if(total < 0) {
    throw new Error('Invalid userInput');
}

// getting the IP
for (let i = 0; i < total; i++) {
    const arg = process.argv[i];

    if (arg.includes('--ip')) {
        options.metadata.IP = process.argv[i + 1];
    }
}

reporter.generate(options);

and this is the checkmarx:

The application goes into a loop with total at base_ond_puppeteer_jsreporter.js in line 27. However, to determine the amount of iterations that this loop performs, the application relies on the user input argv at base_ond_puppeteer_jsreporter.js in line 21. Similarity ID: 954597347

and one more checkmarx for same line:

Method Math.min at line 21 of base_ond_puppeteer_jsreporter.js gets user input from element argv . This element’s value flows through the code without being validated, and is eventually used in a loop condition in for at line 27 of base_ond_puppeteer_jsreporter.js. This constitutes an Unchecked Input for Loop Condition. Similarity ID: 954683830

i tried a lot of things to validate the argv but nothing worked.
TNX a lot 🙂

I’m using NEXTUI Modal. When I click on Its calling all Modals

Blog has max-w and overflow so it can’t show full text. I used NextUI’s Modal so I can see the full post.

const TaskM = () => {

const { myapp, handleRemoveTodo, desc, handleAddTodo, blog,tyPe,task } = useContext(Context);
const { isOpen, onOpen, onOpenChange } = useDisclosure();
const [scrollBehavior, setScrollBehavior] = React.useState("inside");
const [modalPlacement, setModalPlacement] = React.useState("center");
const modal =(_index: any)=>{
    document.getElementById("hello")
}

return (

    <div className='flex flex-col justify-center w-full items-start '>
        <ul className="todo-list items-center flex flex-col gap-5 w-full h-auto justify-center ">
            {(myapp || [])?.map((blog: any, index: number) => {
                if (blog.type === "Backlog") {
                    return <>
                        <Button onPress={onOpen}
                            key={index} className='bg-white min-h-[100px] h-auto rounded-2xl flex shadow-lg shadow-gray-300 md:break-words flex-col w-[90%] justify-start gap-4 items-center'>
                            <div className='flex flex-row mt-2 justify-between w-[90%] '>
                                <h1 className='text-black w-[90%] '>
                                    <li className={`block text-gray-700 md:break-words w-[90%] mb-3  flex-row text-xs justify-between items-center rounded-lg  `} id={blog.title} key={index}>
                                        {blog.title}
                                        {/* {JSON.stringify(_cards)} */}
                                    </li>
                                </h1>
                                <button className="  text-gray-300  items-center flex justify-center   w-[10%] h-[20px] " onClick={() => handleRemoveTodo(index)}>
                                    <BsThreeDots />
                                </button>
                            </div>
                            <div className='w-full h-auto flex flex-col justify-start items-center rounded-none'>
                                <li className=' text-gray-700 h-auto max-h-[160px] max-w-[90%] text-wrap capitalize  overflow-ellipsis overflow-hidden break-all w-[90%] mb-3 flex flex-row text-xs justify-start items-start rounded-lg' id={blog.desc} key={index}>
                                    {blog.desc}
                                </li>
                            </div>


                        </Button>

                        <Modal
                            isOpen={isOpen}
                            onOpenChange={onOpenChange}
                            scrollBehavior={scrollBehavior}
                            placplacement={modalPlacement}
                            key={index}
                            id ='hello'
                        >
                            <ModalContent 


                            >
                                {(onClose) => (
                                    <>

                                        <div className='bg-white min-h-[100px] h-auto rounded-2xl text-black flex shadow-lg shadow-gray-300 md:break-words flex-col w-full justify-start gap-4 items-center'>
                                            <ModalHeader className="flex flex-col gap-1 ">
                                                {blog.type}
                                            </ModalHeader>
                                            <h1 className='text-black w-[90%] '>
                                                <li className={`block text-gray-700 md:break-words w-[90%] mb-3  flex-row text-xs justify-between items-center rounded-lg  `} id={blog.title} key={index}>
                                                    {blog.title}
                                                    {/* {JSON.stringify(_cards)} */}
                                                </li>
                                            </h1>
                                            <ModalBody className='flex justify-start items-start w-full'>


                                                
                                                <div className='w-full h-auto flex flex-col justify-start items-start rounded-none'>
                                                    <li className=' text-gray-700 h-auto max-h-[210px] max-w-[90%] text-wrap capitalize break-all w-[90%] mb-3 flex flex-row text-xs justify-start items-start rounded-lg' id={blog.desc} key={index}>
                                                        {blog.desc}
                                                    </li>
                                                </div>

                                            </ModalBody>
                                            <ModalFooter>
                                                <Button
                                                    color="danger"
                                                    variant="light"
                                                    onPress={onClose}
                                                    className="p-2  rounded-2xl w-auto bg-blue-500 text-white border-0 outline-none hover:bg-blue-400 "
                                                >
                                                    Close
                                                </Button>

                                            </ModalFooter>
                                        </div>

                                    </>
                                )}
                            </ModalContent>
                        </Modal>
                    </>;
                }
            }
            )}

        </ul>
    </div>
)


}

export default TaskM

THIS component is for post my blog. When I click on the posted blog , onpress={onOpen} calling every modals of every blog at the same time. I copied this modal code from NextUI Modal. So I don’t know what to do and how to fix it. I think I should give id on every blogs but I don’t know how to do it. Because every blogs are posted from 1 component.

why values are removed from object after button click?

I am using below package for my demo application.
https://www.npmjs.com/package/mui-react-hook-form-plus

Above package have dependency of react-hook-form

Object key are removed after button click don’t know why ?

I am setting the value like this on button click.

const update = () => {
    const data = {
      person: { firstName: "", lastName: "", sex: "Male" },
    };

    setValues(data);
  };

here is my component

export default function App() {
  const defaultValues = {
    person: { firstName: "", lastName: "", sex: "" },
  };

  const methods = useHookForm<any>({
    defaultValues,
  });

  const { registerState, handleSubmit, getValues, setValues } = methods;
  console.log(getValues());
  const onSubmit = (data: any) => {
    console.log(JSON.stringify(getValues(), null, 2));
  };
  const update = () => {
    const data = {
      person: { firstName: "", lastName: "", sex: "Male" },
    };

    setValues(data);
  };
  return (
    <div className="App">
      <HookFormProvider {...methods}>
        <form onSubmit={handleSubmit(onSubmit)}>
          <Stack direction="row" spacing={2}>
            <HookTextField
              {...registerState("person.firstName")}
              textFieldProps={{ label: "First Name" }}
            />
            <HookTextField
              {...registerState("person.lastName")}
              textFieldProps={{ label: "Last Name" }}
            />
          </Stack>
          <button onClick={update}>set value</button>
          <br />
          {JSON.stringify(getValues("person"), null, 2)}
          <br />
        </form>
      </HookFormProvider>
    </div>
  );
}

code
https://stackblitz.com/edit/vitejs-vite-61ya5m?file=src%2Findex.css,src%2FApp.css&terminal=dev

steps to repr

  1. Run application .. see OBJECT Value { “firstName”: “”, “lastName”: “”, “sex”: “” }
  2. Click Button see Object { “sex”: “Male” }
  3. firstName. and lastName key removed from object why ?

enter image description here

i say internally removing field why
https://github.com/adiathasan/mui-react-hook-form-plus/blob/master/src/utils/form-utils.ts

How to download a pdf with specific file name from a blob url


const b64toBlob = (b64Data, extension) => {

  const byteCharacters = atob(b64Data);

  const len = byteCharacters.length;

  const buffer = new Uint8Array(len);

  for (let i = 0; i < len; i += 1) {

    buffer[i] = byteCharacters.charCodeAt(i);

  }

  return new Blob([buffer], { type: `application/${extension}` });

};

 const blob = b64toBlob(base64Content, extension);

const url = URL.createObjectURL(blob);
window.open(url, '_blank');

This is how I open the pdf in a new window, and when I try to save this pdf it’s showing a random filename, I need to save it with a specific filename.

Is there any way to download the pdf with the actual filename.