Sum of two random numbers with Javascript

I’m trying to create a program with Javascript that prints two random numbers and calculates their sum. It should be really easy, but for some reason I can’t get the program to work. I’ve got the program to print random numbers, but I can’t get it to add the numbers together. What am I doing wrong?


<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
</head>
    <body>

        <p id="myBtn"></p>
        <p id="number1"></p>
        <p id="number2"></p>

        <button id="myBtn" onclick="myFunction()">Get random number</button>


        <script>

            var allNumbers = 0;

            function myFunction() {
                num1 = document.getElementById("number1").innerHTML = Math.floor(Math.random() * (7 - 1) + 1);
                num2 = document.getElementById("number2").innerHTML = Math.floor(Math.random() * (7 - 1) + 1);
                var inTotal = num1 + num2;
                var allNumbers =+ inTotal;
            }

            document.write(allNumbers);

        </script>

    </body>
</html>

Send Invites to emails after creating google sheet using google sheet api from node.js

Hi I am creating a google sheet from Google Sheets API v4. I want to give access to my system users for that google sheet. is there any google sheet API for this? even for enterprise packages?

const service = google.sheets({ version: 'v4', auth: oauthClient });
const newSpreadSheet = await service.spreadsheets.create({
  requestBody: {
    properties: {
      title: 'Test Sheet 0001',
    },
  },
});

I have tried to add users to the protected range but still, those email didn’t get access to google sheet

await service.spreadsheets.batchUpdate({
  spreadsheetId: spredSheetId,
  requestBody: {
    requests: [
      {
        addProtectedRange: {
          protectedRange: {
            range: {
              sheetId: 0,
              startRowIndex: 0,
              endRowIndex: 10,
              startColumnIndex: 0,
              endColumnIndex: 5,
            },
            description: 'trying to give read or write access for emails',
            editors: {
              users: ['[email protected]'],
            },
          },
        },
      },
    ],
  },
});

can you please suggest or i have to create & move to shared drive folder?

How do I solve the Error with Await in JS


exports.helloWorld = (req, res) => {
  const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

const response = await openai.createCompletion({
  model: "text-davinci-003",
 temperature: 0,
  max_tokens: 100,
  top_p: 1,
  frequency_penalty: 0,
  presence_penalty: 0,
  stop: ["n"],
});


};

Deployment failure:
Build failed: /workspace/index.js:10
const response = await openai.createCompletion({
^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules
at Object.compileFunction (node:vm:360:18)
at wrapSafe (node:internal/modules/cjs/loader:1084:15)
at checkSyntax (node:internal/main/check_syntax:66:3); Error ID: d984e68f

How to test mouse clientY in React testing (JEST)

useEffect(() => {
    const maybeHandler = (event: MouseEvent) => {
      menuData.forEach((el) => {
        if (el.hasActiveDropdown && event.clientY > 50) {
          handleCloseDropDown();
          // handleDropDown('0');
        }
      });
    };
    document.addEventListener('mousedown', maybeHandler);
    return () => document.removeEventListener('mousedown', maybeHandler);
  }, [handleCloseDropDown, menuData]);

I am used this useEffect to handle mulltip dropdowns in navbar component,
navbar has fix height 50px so my logic is whenver use click outside the navbar the drop downs all are close.

I am unadble to test in JEST this clientY propery

Cannot POST / error using thunderclient to send request

I’m having trouble with my server routes. is there any problem with my routes? or a problem with the code?

I have checked all the possible question answers. 



I'm having trouble with my server routes.
used thunderclient to send request

when I route it shows this

enter image description here

I tried to set thunder client POST to GET but got the same error

Index.js

const connectToMongo = require('./db');
const express = require('express')

connectToMongo();
const app = express()
const port = 5000

//Available Routes
app.use('/api/auth', require('./routes/auth')) 
// app.use('./api/notes', require('./routes/notes'))


app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

my auth.js where login and register exist.

const express = require('express');
const User = require('../models/User');
const router = express.Router();
const { body, validationResult } = require('express-validator');


// Create a User using: POST "/api/auth/". Doesn't require auth
router.post('/',[
    body('name').isLength ({min: 3}),
    body('email').isEmail(),
    body('password').isLength ({min: 5})
], (req, res)=>{
    const errors = validationResult(req);
    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }
    res.send(req.body);
})

module.exports = router

my user.js which shows user data

const mongoose = require('mongoose');
const {Schema}= mongoose;

const UserSchema = new Schema({
    name:{
        type: String,
        required:  true
    },
    email: {
        type: String,
        required: true,
        unique: true
    },
    password:{
        type: String,
        required: true
    },
    date:{
        type: Date,
        default: Date.now
    },
    
  });

  module.exports = mongoose.model('user', UserSchema);

I tried to set thunder client POST to GET but got the same error

Is there any problem with my routes? or a problem with the code?

How can I programatically and conditionally skip/fail/select a single or group of Cypress (and Mocha) tests?

Programmatic Conditional Test Logic for Cypress and Mocha

I’ve both asked a few different flavors of the above question and come across many different answers to this topic on StackOverflow so I’ve decided to create a community wiki article with a few options to help tame this unruly beast.

Fair warning: the Cypress team hark on about conditional test execution being an anti-pattern. I think this is true in the vast majority of cases but there are still legitimate uses for conditional test execution (even if it’s just debugging) and quite frankly, I’m more concerned with saving us all some time rather than making assumptions about the validity of your use case. So here goes.

The Nature of the Beast

Grouping tests and running them based on specific tags is, in essence, just another way of phrasing the question “how can I $(someAction) a test based on $(someCondition)?”. If we zoom out a bit what all of these questions really boil down to is having a means to conditionally execute, skip, or select tests in the context of the Cypress or Mocha test frameworks.

The other common theme for many (but not all) of the posts on this topic is the desire to perform these checks at runtime, that is, the desire to programmatically choose what tests should be skipped/run/failed/etc.

This article is for people wanting to achieve their desired result programmatically, that is, by checking an expression that evaluates to a boolean value. For JavaScript that can mean a lot of things, read up on equality in JavaScript here.

Existing Plugins and Extensions

At the time of writing there are some pretty good Cypress plugins and npm packages that deal with this theme. If you’re looking for something a bit more robust and don’t mind adding some dependencies to your project for the sake of conditional test logic check these out:

  1. The skip-test npm package
  2. The cypress-tags npm package*
  3. The cypress-if plugin

The answers in the wiki are all DIY, for those wanting to know how to do this with just Cypress, Mocha, and (implied) Node.

Enable check box when PDF scroll to last page

I’m trying to open Term and Condition PDF with iframe. When user scroll to last page, i need to enable check box of Accept.

 <div>
    <iframe src="assets/terms.pdf" width="970px" height="370px"></iframe>
    <input type="checkbox" disabled> I Accept
    <input type="button" value="Submit"/>
  </div>

PHP : How to add active class in Category Tab after Category-> post URL open?

Good day!!!

I have recently created (cms) a PHP blog site and I’m stuck in Active Class, whenever I click on the menu(category) all links are actively working fine but whenever I click on a blog post the active class is removed…. so I want to set the blog post active with respective category (menu).

Active Class – http://example.com/category/

Active Class removed – http://example.com/category/title-of-the-article/

i wanted to Add active class in both url…. if i open the category page than category is activate or highligh and if i open any blog post than the respective category also active.

enter image description here

After I click on any blog post (Article) the active class is removed as you can see below the picture…

enter image description here

Here is my code [below]

<ul id="nav-main">        
  <li><a href="http://example.com/"> Home</a></li>
  <li><a href="/technology/"> Technology</li> 
  <li><a href="/business/"> Business</a></li>
  <li><a href="/entertainment/"> Entertainment </a></li>
</ul>


ul#nav-main li a.active {
       border-bottom: 4px solid #4db2ec;
       color: black;
       font-weight: bold;
     }

<script type="text/javascript">

jQuery(document).ready(function($){
        var path = window.location.href;
        $('#nav-main li a').each(function() {
            if (this.href === path) {
                $(this).addClass('active'); 
            }
        });
    });

</script>

I have an array of objects and I want to know how to get a property from an object in the array and use it in a function?

I have an array of stocks and I want to know how to get price from the array find out the highest/lowest price and return the object with highest/price.
`

'use strict';

const stocks = [
    { company: 'Splunk', symbol: 'SPLK', price: 137.55 },
    { company: 'Microsoft', symbol: 'MSFT', price: 232.04 },
    { company: 'Oracle', symbol: 'ORCL', price: 67.08 },
    { company: 'Snowflake', symbol: 'SNOW', price: 235.8 },
    { company: 'Teradata', symbol: 'TDC', price: 44.98 }
];

I want to get price for each object in stocks and return the object with the highest price as max and return the object with lowest price as min.

// Function for highest/lowest price
function findStockByPrice(stocks) {
    max = Math.max.apply(null, stocks.price);
    min = Math.min.apply(null, stocks.price);
    if (max === true) {
        return stocks
    } else if (min === true) {
        return stocks
    }
}

I am trying to use Math.max() but I am getting ReferenceError: max is not defined.

What is the difference between `jest` and `jasmine`?

I’m investigating different testing frameworks for my SPAs (some of them are built with Angular and some with React). Both jasmine and jest have very similar API and end purpose (they are both suitable for unit and integration testing). I’m trying to understand, how are they different, what does one have that another doesn’t. Any features, APIs, performance differences? Or is it just a matter of preference to pick one?

Researched a bunch of articles but didn’t see any clear tables comparing features, APIs, performance differences.

How can I fix a cursor position inside of a particular div?

I am developing a simple 2d game where a user have to point a gun at different objects and shoot them. When a user moves his mouse, the crosshair’s position always stays the same, but the environment (all other objects) move, creating an effect of a crosshair moving. The problem is, when a cursor leaves the div (where all of the above happens), everything stops moving.

So, the question is: how can I make the cursor never leave the div (with a game) unless the game is paused?

Example of what I expect: link. In this game, when a user’s playing, their cursor is always inside a game screen, but when he’s in the menu or the game is paused, their cursor can leave a game screen.

How to add multiple Leaflet map on the same page?

I want to add multiple Leaflet map with different content on the same page but it gives me the error:

Map container is already initialized.

I’m initializing the map in a useEffect:

  useEffect(() => {
    if (!map) {
      const newMap = L.map("map", {
        zoomControl: true,
        minZoom: minZoom,
        maxZoom: maxZoom,
        maxBounds: latLngBounds,
        attributionControl: false,
      }).setView(latLngCenter, defaultZoom)

      L.tileLayer("https://{s}.basemaps.cartocdn.com/dark_nolabels/{z}/{x}/{y}{r}.png").addTo(
        newMap
      )
      setMap(newMap)
    }
  }, [map])

Then I’m returning a div with id=map.

I’m getting the error on line const newMap. I think we can’t have 2 maps on the same page with different contents?