My js is not work and I don’ know why is? [closed]

This is error:

This js is problem , because it isn’ realize skip new page, I don’t know why???

I want to get some data to verificate some formulation , data from this web:
http://www.nmc.cn/

So I write code to get data convience

but the js is seemly not work ,

my start page from http://www.nmc.cn/

, the new page is

http://www.nmc.cn/publish/forecast/AJS/nanjing.html

but it isn’t skip new page!!!!

Below is Part of my code

    search_content = driver.find_element(By.ID,'searchInput')
    search_content.clear()
    js = "(document.getElementById('searchInput').setAttribute('autocomplete','on'))"
    driver.execute_script(js)

How to make log with error for dear ImGui

I can’t make log info in dear ImGui

I try this

    "ImGui.Text(`Welcome to GRAPE CHEAT`);",
    "",
    "if (ImGui.Button("Enter Key"))",
    "{",
    "t if(buff == "DEBUG_FOREVER")",
    "{",
    "t alert("thx for buy cheat");",
    "} else {",
    "t alert("wrong key");",
    "t /* static */ let outputer = "Wrong Key";",
    "}",
    "}",
    "ImGui.Text(outputer);",
    "if (ImGui.Button("Get Key"))",
    "{",
    "t window.location.href = "http://google.com";",
    "}",
    "",
    "ImGui.InputText("key", (_ = buff) => buff = _, 256);",
    ""

this before click enter key
nothing changed after that

How to collect values of HTML input elements into a map-like object?

I have input elements like this:

<input name="fruit" id="fruit" value="Orange">
<input name="vegetable" id="vegetable" value="Spinach">
<input name="dairy" id="dairy" value="Eggs">
<input name="bread" id="bread" value="Bread">
<input name="soup" id="soup" value="Soup">

I need to get them all and create an object like this:

{
  fruit: "Orange", 
  vegetable: "Spinach", 
  dairy: "Eggs", 
  bread: "Bread", 
  soup: "Soup"
}

I created this method but perhaps there may be a better or more efficient and succinct way to achieve this result:

My code:

const inputs = document.getElementsByTagName('input');

function convertToObject(obj){
  let inputString = '';
  for(const input of inputs){
    inputString += `, "${input.id}": "${input.value}"`;
  }
  return JSON.parse(`{${inputString.substring(1).trim()}}`);
}

const objArray = convertToObject(inputs);
console.log(objArray);

What does “console.log.bind(1, 2)” do? [duplicate]

What does the following line of code do?

console.log.bind(1, 2)`Hello`;

Source URL:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#tagged_templates:~:text=console.log.bind(1%2C%202)%60Hello%60%3B%20//%202%20%5B%20%27Hello%27%20%5D

Thanks!


#What I have tried:

I have googled “console log bind”, and the only result I found was the following (which doesn’t directly answer my question):

What does this statement do? console.log.bind(console)


Define words in a text by hovering over them

I am trying to create a program for teaching English.
My aim is to take a text and have it so that students can read the text, and get the definition of individual words by hovering over any words that they don’t understand.

Ideally I want this to link to Dictionary.com or something similar so that I do not have to input the definition for every individual word.

Any help would be greatly appreciated.

I can use Javascript, CSS or HTML, but so far I haven’t found anything useful.

Are there any API’s that can get the average price for a product?

I’m trying to make a website that needs to frequently change the price of the product to the current market price so that I can order it and buy it for that price. Basically I’m just wondering if there’s any API out there that can take the average of different website’s prices for one product and give me an average so I can get the general price of that product.

Does google shopping have something like this? Any help would be appreciated, thanks!

how to import js file correctly in vue

i import js-cloudimage-360-view(https://github.com/scaleflex/js-cloudimage-360-view) into index.html, but the code in vue template didn’t render successful and display nothing, chrome console didn’t report any error. And in my test, when the code paste in index.html it’s worked, but in myComponent.vue failed.
How to import js-cloudimage-360-view.min.js fully functional

import js in index.html

<div id="app"></div>
<!-- built files will be auto injected -->
<script src="https://scaleflex.cloudimg.io/v7/plugins/js-cloudimage-360-view/latest/js-cloudimage-360-view.min.js?func=proxy"></script>
</body>
</html>

failed in ***.vue file

<template>
    <div
        id="gurkha-suv"
        class="cloudimage-360"
        data-amount-x="73"
        data-filename-x="orange-{index}.jpg"
        data-folder="https://scaleflex.cloudimg.io/v7/demo/suv-orange-car-360/"
    ></div>
</template>

<script>
export default {
    name: "ShowComponent",
    mounted() {

    }
}
</script>

I’ve tryyed useing npm module, but the doc didn’t show the method how to import plugins correct in vue. (https://www.npmjs.com/package/js-cloudimage-360-view)
And i copy paste code directly in to index.html not vue (outside the #app div), and the code worked

<div id="app"></div>
<div
        id="gurkha-suv"
        class="cloudimage-360"
        data-amount-x="73"
        data-filename-x="orange-{index}.jpg"
        data-folder="https://scaleflex.cloudimg.io/v7/demo/suv-orange-car-360/"
></div>
<!-- built files will be auto injected -->
<script src="https://scaleflex.cloudimg.io/v7/plugins/js-cloudimage-360-view/latest/js-cloudimage-360-view.min.js?func=proxy"></script>

I’am expecting the code work functional inside vue, this js detect div with “cloudimage-360” class name and render correct.

why i am getting blocked by CORS policy error even though i use cors Origin statement with my frontend url

I have got ‘blocked by CORS policy’ error as mentioned below. I know this kind issue is reported in this portal many time. As suggested in one of the answers in this portal, I have used cors header ‘Origin’ with my frontend url. Please refer app.use statement in my server.js file. I am still getting same ‘blocked by CORS policy’ error. I am not facing this issue when is use postman. Can anyone please assist?

Note: In the frontend fetch statement, i used ‘mode:’no-cors’. It helps me to avoid the below error. But, my response from backend becomes opaque response. As mentioned in another post(Handle response – SyntaxError: Unexpected end of input when using mode: ‘no-cors’) in this portal, opaque response is probably because effect of setting no-cors mode is essentially to tell browsers, “Don’t let frontend JavaScript code access the response body or headers under any circumstances.”. So, i am not able to read the response(comes from backend) in my front end. I have tried with “mode:’cors'” as well as without mode statement also, no luck to fix this issue.

Error:

Access to fetch at ‘https://xxxxxx-xxxxxxx.el.r.appspot.com/signup/xxxxxxxxxxxxxx’ from origin ‘https://xxxxxxxxxxx-frontend.xxxx.r.xxxxxx.com’ 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. If an opaque response serves your needs, set the request’s mode to ‘no-cors’ to fetch the resource with CORS disabled.

My back-end(Node js): Server.js file

const bodyParser = require('body-parser');
const routesHandler = require('./routes/handler.js');

// Imports the Google Cloud client library for Bunyan.
const lb = require('@google-cloud/logging-bunyan');

// Import express module and create an http server.
const express = require('express');
const cors = require('cors');
app.use(cors({
    origin: 'https://xxxxxxsale-frontend.el.r.xxxxxxx.com'
}));

async function startServer() {
    const {logger, mw} = await lb.express.middleware({
      logName: 'samples_express',
    });
    const app = express();

    app.use(bodyParser.urlencoded({extended:false}));
    app.use(bodyParser.json());
    app.use('/', routesHandler);
  
    // Install the logging middleware. This ensures that a Bunyan-style `log`
    // function is available on the `request` object. This should be the very
    // first middleware you attach to your app.
    app.use(mw);
  
    // Setup an http route and a route handler.
    app.get('/', (req, res) => {
      req.log.info('this is an info log message');
      res.send('hello world 1');
    });
  
    const port = process.env.PORT || 8080;
  
    // `logger` can be used as a global logger, one not correlated to any specific
    // request.
    logger.info({port}, 'bonjour');
  
    // Start listening on the http server.
    const server = app.listen(port, () => {
      console.log(`http server listening on port ${port}`);
    });
  
    app.get('/shutdown', (req, res) => {
      res.sendStatus(200);
      server.close();
    });
  }
  
  startServer();

My back-end(node js): handler.js file

const app = express()
const router = express.Router();
const {getAuth} = require('firebase-admin/auth')
require("dotenv").config()

const bodyParser = require("body-parser")
const nodemailer = require("nodemailer");


app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())





router.get('/addtweets', (req, res) => {
    const str = [
        {
            "name": "Codr Kai",
            "msg": "This is my first tweet!",
            "username": "codrkai"
        },
        {
            "name": "Samantha Kai",
            "msg": "React JS is so simple!",
            "username": "Arun"
        },
        {
            "name": "John K",
            "msg": "Sweep the leg!",
            "username": "johnk"
        }
    ];
    res.end(JSON.stringify(str));
});
 

router.post('/signup/:emailId',function (req, res) {
    let useremailT = req.params.emailId;
    console.log(req.body);
    //const pass = req.body.password;
    let spc1=useremailT.indexOf(" ");
    let len1=useremailT.length;
     pass = useremailT.substr(0,spc1);
     useremailT = useremailT.substr(spc1+1,len1-spc1-1);
     let spc2=useremailT.indexOf(" ");
     len1=useremailT.length;
     let useremail = useremailT.substr(0,spc2);
     let username  = useremailT.substr(spc2+1,len1-spc2-1);
    
    
    var admin = require("firebase-admin");

var serviceAccount = require("../xxxxxxsales-19e4e-firebase-xxxxxx-xxxxx-xxxxxxxx-xxxxxx.json");

if (!admin.apps.length) {
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        origin:'*'
      });
}

getAuth()
  .getUserByEmail(useremail)
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    //console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
    if (userRecord.emailVerified) {
            //console.log('Res 1:' , res);
            res.send({"message":"Exist"});
        } else {
            //console.log('Res 2:' , res);
            res.send({"message":"Pending"});
        }
    
  })
  .catch((error) => {
 getAuth()
   .createUser({
    email: useremail,
    emailVerified: false,
    password: pass,
    disabled: false,
    displayName:username
  })
  .then((userRecord) => {
     username = userRecord.displayName;
     //console.log('in Error before generateEmailVerificationLink');
        getAuth()
        .generateEmailVerificationLink(userRecord.email)
        .then((link) => {
            // Construct email verification template, embed the link and send
            // using custom SMTP server.
            // return sendCustomVerificationEmail(useremail, displayName, link);
            //console.log(link);
            var email = userRecord.email;
            res.send({link}); 
        })
        .catch((error) => {
            // Some error occurred.
            console.log('error 1:' +error);
            //res.end('Error');
            res.send({"message":"Error"});
        });
  })
  .catch((error) => {
    console.log('error 2:' +error);
    //res.end('DBissue');
    res.end({"message":error});
    //res.send({"message":error});
  });
});  

});

router.post('/resendEmail', (req, res) => {
    const useremail = req.body.email;
    var username = ''
    var admin = require("firebase-admin");

var serviceAccount = require("../xxxxxxsales-19e4e-firebase-xxxxxx-xxxxx-xxxxxxxx-xxxxxx.json");

if (!admin.apps.length) {
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount)
      });
}

getAuth()
  .getUserByEmail(useremail)
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    //console.log(`Successfully fetched user data: ${userRecord.toJSON()}`);
    if (userRecord.emailVerified) {
        res.end(JSON.stringify('Exist'));
    } else {
        username = userRecord.displayName;
        getAuth()
        .generateEmailVerificationLink(userRecord.email)
        .then((link) => {
            var email = userRecord.email;
            res.send({"message":"Registered"});
            send_mail(link,userRecord.email,username);    

        })
        .catch((error) => {
            // Some error occurred.
            console.log('some error');
            res.end('Error');
        });
    }
    
  })
  .catch((error) => {
            res.end(JSON.stringify('UserNotFound'));    
  })
  
});  

router.post('/login', (req, res) => {
    const useremail = req.body.email;
    const pass = req.body.password;
    var username = ''
    var admin = require("firebase-admin");

var serviceAccount = require("../xxxxxxsales-19e4e-firebase-xxxxxx-xxxxx-xxxxxxxx-xxxxxx.json");

if (!admin.apps.length) {
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount)
      });
}

getAuth()
  .getUserByEmail(useremail)
  .then((userRecord) => {
    // See the UserRecord reference doc for the contents of userRecord.
    //console.log(`Successfully fetched user data: ${JSON.stringify(userRecord)}`);
    if (userRecord.emailVerified) {
        res.end(JSON.stringify(userRecord.displayName));
    } else {
        res.end(JSON.stringify('Pending'));
    }
    
  })
  .catch((error) => {
            // Some error occurred.
           //console.log('some error');
            res.end('Error');
        });
  });

const send_mail=(link,email,username) =>{
let { text } = 'Welcome'
  const nodemailer = require('nodemailer');

let transport = nodemailer.createTransport({
  service: 'gmail',
  host: 'smtp.gmail.com',
    port: 2525,
    // secure: true,
    auth: {
        user: "xxxxxxxx.xx",
        pass: "xxxxxxxxxxxxxxx"
    },
    debug: true,
    logger: true
});

let mailTransporter = nodemailer.createTransport(transport);
 transport.sendMail({
  from: process.env.MAIL_FROM,
  to: email,
  subject: "Email verification",
  ContentType: "multipart/alternative",
ContentType: 'text/plain', charset:"UTF-8", format:'flowed', delsp:'yes',
ContentTransferEncoding: 'base64',
  html: `MY HTML CODE HERE `
});

}
router.get('/send_mail',cors(), (req, res) => {
    let { text } = 'Welcome'
    const transport = nodemailer.createTransport({
        host: process.env.MAIL_HOST,
        port: process.env.MAIL_PORT,
        auth: {
            user: process.env.MAIL_USER,
            pass: process.env.MAIL_PASS
        }
    })

     transport.sendMail({
        from: process.env.MAIL_FROM,
        to: "[email protected]",
        subject: "test email",
        html: `<div className="email" style="
        border: 1px solid black;
        padding: 20px;
        font-family: sans-serif;
        line-height: 2;
        font-size: 20px; 
        ">
        <h2>Here is your email!</h2>
        <p>${text}</p>
    
        <p>All the best, Darwin</p>
         </div>
    `
    })
})

module.exports = router;

My Front end(React):

if (form.email !== ''    && typeof(form.email)    !== undefined
       && form.password !== '' && typeof(form.password) !== undefined && errMessage === "") {
         //props.saveLogin(form);
         const databody =
               form.password+" "+form.email+" "+form.fname;

               // const data = await fetch('https://xxxxxxx-xxxxxx.el.r.xxxxxxx.com/signup/'+databody,
               // {
               //  method: "POST",
               //  mode:'no-cors',
               // headers:{headers}
               // }
               console.log('data Y1:'+ databody);
         const data = await fetch('https://xxxxxxxxx-xxxxxx.el.r.xxxxx.com/signup/'+databody,
                     {
                      method: "POST",
                      mode: 'cors',
                      headers: {

                      "Accept": "application/json",
                          "Content-Type": "application/json"
                        }
                     }
                     ).then((response) => {
                       console.log(response);
                       if (!response.status) {

                         //console.log("complete");
                         return response.json();
                       }
                       else {
                           throw new Error('Something went wrong');
                       }

                     })
                     .then((responseJson) => {
                       const items =  responseJson.message;
                       //console.log(items);
                       //console.log("error new");
                       if (items==='Pending') {
                         alert('Email id already exist. Kindly check your inbox and verify.');
                       }
                       else if (items==='Registered') {
                         //alert('Email id registered successfully. Kindly check your inbox and verify.');
                         //alertA.show('Email id registered successfully. Kindly check your inbox and verify.');
                         CreateUser();
                       }
                       else if (items==='DBissue') {
                         alert('Db issue. Please try after sometime.');
                       }
                       else if (items==='Error') {
                         alert('Error. Please try after sometime.');
                       } else if (items==='Exist')
                       {
                         //console.log(items);
                         alert('Email is already registered. You may proceed to Login.');
                       }
                       else
                       {
                         alert('Error occurred. Please after sometime.')
                       }

                     })
                     .catch((error) => {
                       alert(error);
                     });

      
     }
     else if(errMessage !== ""){
           console.log('in errMessage block');
           alert(errMessage);
     }

How can I deselect the toggle button after selecting it by clicking one more time on it?

enter image description here

The result of this code is the gif above, so I can select it, but to deselect it, I have to select another button!

Meaning, I don’t want the selected button to get deselected after selecting another button; the button should be deselected if I click on it one more time.

Like this:

enter image description here

Code:


const [selected, setSelected] = useState(Array(arrayOfItems.length).fill(false)); 
 
return arrayOfItems.map((item, index) => ( 
  <Card key={item.id}> 
    <CardContent> 
      <Typography>{item.name}</Typography> 
      <Button 
        variant="contained" 
        color={selected[index] ? "primary" : "secondary"} 
        onClick={() => { 
          const newSelected = [...selected]; 
          newSelected[index] = !newSelected[index]; 
          setSelected(newSelected); 
        }} 
      > 
        Toggle 
      </Button> 
    </CardContent> 
  </Card> 
)); 

I’m not using MUI’s toggle button because I couldn’t figure out how to return, say, hundreds of toggle buttons by iterating over an array with the map function, and clicking on one toggle button would not select the others, so I’m using a button instead. 

How to optimize the conditional statement

I need help in optimizing this code. How can we have the common if else condition for the number defined and undefined condition

Below is the code snippet.

if(number === undefined) { Const a = true; if(a=== true) { Do something; else { Do something; } } else if (number === defined) { Const a = false; if(a=== true) { Do something; else { Do something; } }

Can we have some flags here. Pls suggest

I receive information from an api with axios and the result is a mixture of string and json objects, how can I read this?

The json examples is: {"code": 200, "message": "", "response": {"bvcc": [Object], "financiero": [Object], "ibc": [Object], "industrial": [Object]}, "success": true} how i read with javascript, i try with this code but show me an error the first time (Error: “Cannot read property ‘bvcc’ of undefined”)

My code in React Native:

    useEffect(() => {
      const config = {
      headers: {
        'Content-Type': 'application/json',
        Authorization: token
      }
    };

    setModalVisible(true);
    const indexQuery = async () => {
      const urlIndices = baseUrl + "/mercado/indices";
      await axios.get(urlIndices, config)
      .then((res1) => {
        setBvcMonto(res1.data.response.bvcc.PRECIO_ULT);
        setBvcUltVarRel(res1.data.response.bvcc.ULT_VAR_REL);
        setBvcVolumen(res1.data.response.bvcc.VOLUMEN);
      })      
      .catch((error) => {
        console.log("Error:"+error);
      });
    };
    indexQuery();
  }, [token]);



When i try JSON.stringify(res1) show me the error.    Thanks in advance

one click two checkbox are checked

i have multiple checkbox dynamicly.if i check one checkbox or select any its should be check another checkbox is checked

<div class="ic_schedule mb_20"
    <div class="form-check sc_click">
        <input class="form-check-input" type="checkbox" name="date[]" value="2023-03-02">
        <input class="form-check-input" type="checkbox" name="timeslot[]" value="18" id="18">
        <label class="form-check-label d-flex justify-content-between align-items-center" for="18">
            <span> 11:00 AM - 01:00 PM (2 Hour)</span>
            <span class="ic_date_time">02, Thu</span>
        </label>
    </div>
<div class="form-check sc_click">
        <input class="form-check-input" type="checkbox" name="date[]" value="2023-03-02">
        <input class="form-check-input" type="checkbox" name="timeslot[]" value="18" id="18">
        <label class="form-check-label d-flex justify-content-between align-items-center" for="18">
            <span> 11:00 AM - 01:00 PM (2 Hour)</span>
            <span class="ic_date_time">02, Thu</span>
        </label>
    </div>
<div class="form-check sc_click">
        <input class="form-check-input" type="checkbox" name="date[]" value="2023-03-02">
        <input class="form-check-input" type="checkbox" name="timeslot[]" value="18" id="18">
        <label class="form-check-label d-flex justify-content-between align-items-center" for="18">
            <span> 11:00 AM - 01:00 PM (2 Hour)</span>
            <span class="ic_date_time">02, Thu</span>
        </label>
    </div>
</div>

if i check one checkbox its check top date[] array checkbox is checked

Auto play audio/video in chrome browser

Is there a method to determine whether the user has interacted with the DOM in the Chrome browser, as auto-play is not permitted unless there has been interaction, and I wish to avoid auto-playing if there has been no interaction?

One solution is to add an onClick event on the body and if that event triggers, it means that the user has interacted. Is there any better approach?

enter image description here