How to style a child element when its parent element is hovered on (js stylesheet)

I have a js style file with a notification component that has its own class. It contains a viewDot div with its own separate class in the same file that is present when the notification hasn’t been clicked on yet. The viewDot div is inside of the div that has the notificationStyle class.

I want to make it so that if I hover over the notification with a cursor, the color of the viewDot also changes. As it is below, the color of the viewDot only changes if I hover directly on the viewDot. Any tips on accomplishing the described behavior are greatly appreciated

const styles = theme => ({
    viewDot: {
        backgroundColor: '#00B8C4',
        '&:hover': {
            backgroundColor: '#F9D967',
        }
    },
    notificationStyle: {
        backgroundColor: '#FFFFFF',
        '&:hover': {
            backgroundColor: '#52B5C2',
        },
        // want to do something like this, but this is not correct as is
        '&hover.viewDot': {
            backgroundColor: '#F9D967'
        }
    },
});

Fetch all images and keep in separate variable using jquery

I am working on web crawling (using axios, cheerio to get html from website)so as per requirement I have to fetch images from all section A,B but issue is due to this images are static.. sometimes section A contain 2 images and sometimes section B contain 3 images.. so requirement is keep section A images in different variable and section B images in different variable. I got stuck here how to do this… no idea how to distinguish this.

<div class="container headingWrapper">
   <h3 class="DetailSection_heading ">Section A:</h3>
</div>

<div class="DetailSection_content">
  <div class="container">
    <div class="css-0">
      <div class="row justify-content-center">
        <div class="col-lg-6">
          <img src="https://img_url_1" alt="" class="DetailSectionImage" data-index="0">
          <img src="https://img_url_2" alt="" class="DetailSectionImage" data-index="0">
        </div>
      </div>
    </div>
  </div>
</div>

<div class="container headingWrapper">
   <h3 class="DetailSection_heading ">Section B:</h3>
</div>

<div class="DetailSection_content">
  <div class="container">
    <div class="css-0">
      <div class="row justify-content-center">
        <div class="col-lg-6">
          <img src="https://img_url_3" alt="" class="DetailSectionImage" data-index="0">
            <img src="https://img_url_4" alt="" class="DetailSectionImage" data-index="0">
        </div>
      </div>
    </div>
  </div>
</div>

jquery Code:

const Fetched_imgs = $('div.DetailSection_content img').map(function() {
  return $(this).attr("src")
}).get();

How to start all print by a tab in Python

I have a script (in Python), that is called by another script (in JavaScript). And to have better readability of the log in my command line, I’d like that all the prints of the subscript (in Python) start with a tabulation. Is there a way to do that with one command, or should I put manually a t at the beginning of all my print?

I wanted to add the tab in the calling script, but when there are several prints in a row, only the first one gets the tab.

PS: if it can help, the calling of the Python script:

const spawn = require("child_process").spawn;
const pythonProcess = spawn('python3', ["../pythonscript.py"]);
pythonProcess.stdout.on('data', (data) => {          
  buff = Buffer.from(data.toString().trim(), "utf-8");

  console.log('Python answer = ' + buff.toString());
});

Parsing JSON values in React JS and mapping to component

I have been stuck for days trying to pull data into my components from a Fetch API JSON result. As a React beginner, this has been a challenge for me and any direction to help me learn and resolve the issue is appreciated. I have the following JSON response copied below followed by my component setup.

My thoughts are that I am not pulling in the correct JSON key values in order or something along those lines.

JSON:

{
  "data": [
    {
      "virusIndex": 2,
      "temperature": 26.5,
      "humidity": 58.6,
      "pm25": 3,
      "tvoc": 234,
      "co2": 435,
      "co": 0,
      "airPressure": 991,
      "ozone": 8.7,
      "no2": 19.4,
      "timestamp": 1646109873
    }
  ],
  "usersettings": {
    "temperature": "°C",
    "temp": "c",
    "humidity": "%",
    "pm25": "µg/m^3",
    "dust": "µg/m^3",
    "tvoc": "ppb",
    "voc": "ppb",
    "co2": "ppm",
    "co": "ppm",
    "airPressure": "mbar",
    "pressure": "mbar",
    "ozone": "ppb",
    "no2": "ppb",
    "pm1": "µg/m^3",
    "pm4": "µg/m^3",
    "pm10": "µg/m^3",
    "ch2o": "ppb",
    "light": "lux",
    "sound": "dBA"
  },
  "count": 104
}

App.js:

class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      airData: []
    }
   }

componentDidMount(){
var myHeaders = new Headers();
      myHeaders.append("Authorization", "Bearer xxxxxxxxx");

      var urlencoded = new URLSearchParams();
      urlencoded.append("macAddress", "xxxxxxxx");
      urlencoded.append("mode", "minute");

      var requestOptions = {
      method: 'POST',
      headers: myHeaders,
      body: urlencoded,
      redirect: 'follow'
      };

  fetch("MY_API_URL", requestOptions)
   .then(response => response.json())
   .then(res => {
     console.log(res)
     this.setState({
       airData: res.data
     })
   });
  }


  
  render () {
        return (
          <div className="app">
            <Header />
            <div className="spacer"></div>
            <OverallStatus />
            {this.state.airData.map(res => {
                  <div>
                    <div className='qualityFactor'>
                      <h1><img src={iconHumidity} alt="Logo" className="iconSmall" />Humidity {res.humidity}%</h1>
                      <ProgressBar completed={res.humidity}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconAirPressure} alt="Logo" className="iconSmall" />Air Pressure {e.AirPressure} hPa</h1>
                      <ProgressBar completed={e.AirPressure}
                      maxCompleted={1030} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonDioxide} alt="Logo" className="iconSmall" />Carbon Dioxide {e.CO2} ppm</h1>
                      <ProgressBar completed={e.CO2}
                      maxCompleted={2000} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconVOCs} alt="Logo" className="iconSmall" />Chemicals {e.TVOC} ppb</h1>
                      <ProgressBar completed={e.TVOC}
                      maxCompleted={1000} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconParticulateMatter} alt="Logo" className="iconSmall" />Particles {e.PM25} ug/m3</h1>
                      <ProgressBar completed={e.PM25}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconCarbonMonoxide} alt="Logo" className="iconSmall" />Carbon Monoxide {e.CO} ppm</h1>
                      <ProgressBar completed={e.CO}
                      maxCompleted={100} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconNitrogenDioxide} alt="Logo" className="iconSmall" />Nitrogen Dioxide {e.NO2} ppb</h1>
                      <ProgressBar completed={e.NO2}
                      maxCompleted={200} className="statusBar" />
                    </div>
                    <div className='qualityFactor'>
                      <h1><img src={iconOzone} alt="Logo" className="iconSmall" />Ozone {e.Ozone} ppb</h1>
                      <ProgressBar completed={e.Ozone}
                      maxCompleted={100} className="statusBar" />
                    </div>
                  </div>
              })}
          </div>
        )
    }
  }
  
  

export default App;

Can we make timer in alert using javascript?

i want to make an alert that have timer in it,
the alert will show this message:

Please wait to process data 3 second..

Please wait to process data 2 second..

Please wait to process data 1 second..

and if the timer is done, the text will change to
Succesfully process data..

I tried this one

    function countdown() {
    var seconds = 3;
    function tick() {
        var counter = document.getElementById("counter");
        seconds--;
        counter.innerHTML = "Please wait to process data " + String(seconds)+ " Second";
        if( seconds > 0 ) {
            setTimeout(tick, 1000);
        } else {
            alert("Succesfully process data");
        }
    }
    tick();
}

countdown();

<div id="results"></div>
<button id="stop">Stop</button>

but this code will show the timer in div not in alert, i tried to edit to make it show in alert but still can not figure it out, can you guys help me?
i really need your help thankyou

Pizza order – extra cheese

I’m having problems understanding JavaScript. I have the following assignment. I’m trying to add to the final cost. the Extra Cheese.

var extraCheeseUpcharge = 1.5
var extraCheese = confirm("Would you like extra cheese?")

if (extraCheese == true) {
  pizza.extraCheese =  true;
  extraCheese = extraCheeseUpcharge + pizza.cost;
} else {
   pizza.extraCheese =  false;
  extraCheese = extraCheeseUpcharge - pizza.cost;
  
}

React component not updating when redux state changes

I have a React component that maps state to props to get data via redux. Everything works fine with the action and the value being updated properly in the reducer. My only problem is that when the state value changes, I want my component to re render so that it is always displaying the most up to date value in the reducer. As of right now I have to call a separate function that refreshes the component, but I’d rather have it automatically re render every time that value changes in the reducer.

Action:

export const createPickup = (selected, pickups) => dispatch => {
  let icon;
  icon = check(selected);
  pickups.icon = icon;
  return API('/createPickUp/', {
    ...pickups,
  })
    .then(res => {
      dispatch({type: types.CREATE_PICKUP, res});
    })
    .catch(err => console.log(err));
};

Reducer:

const initialState = {
  pick: [],
};
export default function pickup(state = initialState, action) {
  switch (action.type) {
    case types.GET_PICK:
      return {
        pick: action.pickup,
      };
    case types.CREATE_PICKUP:
      return {
        pick: [action.res, ...state.pick],
      };
    case types.DEL_GAME:
      return {
        pick: state.pick.filter(p => p._id !== action.id),
      };
    case types.START_GAME:
      return {
        pick: state.pick.map(p =>
          p._id === action.id ? {...p, start: true} : p,
        ),
      };
    case types.STOP_GAME:
      return {
        pick: state.pick.map(p =>
          p._id === action.id ? {...p, stop: true} : p,
        ),
      };
    default:
      return state;
  }
}

how to get the value from html slider in js

I’m coding an event function for my slider. I wanna get the value from the slider. However, it doesn’t work. And I found that the update function is never called, and _value is never updated.
Here is my HTML code

<input type="range" id="slider" min="20" max="200" value="20" step = "1">

Here is my js code

let slider = document.getElementById("slider");
let _value=20;
slider.addEventListener('oninput',update);
function update(event){
    console.log("hi");
    _value=slider.value;
}

Deployed app on Heroku, but can’t access mongoDB from it

I deployed my first MERN stack app on Heroku, it is basically a liquor inventory manager : https://stockify-inventory-manager.herokuapp.com/

However it is unable to access database. Whenever I make an Axios call, my requests get rejected. I’ve wasted 7 hours trying to fix it today but to no avail. Any help is appreciated.

Here is my server.js

const express = require('express')
const dotenv = require('dotenv').config()
const connectDB = require('./config/db')
const {errorHandler} = require('./middleware/errorMiddleware')
const port = process.env.PORT || 5000
const app = express()
const path = require('path')
const cors = require('cors')
const mongoose = require('mongoose')

connectDB()

app.use(express.json());
app.use(cors());

app.use('/api/users', require('./routes/userRoutes'))
app.use('/api/inventory', require('./routes/inventoryRoutes'))
app.use('/api/weekly', require('./routes/weeklyRoutes'))

mongoose.connect( process.env.MONGODB_URI, { useNewUrlParser: true })

// Serve frontend
if (process.env.NODE_ENV === 'production') {
    app.use(express.static(path.join(__dirname, '../frontend/build')))
  
    app.get('*', (req, res) =>
      res.sendFile(
        path.resolve(__dirname, '../', 'frontend', 'build', 'index.html')
      )
    )
  } else {
    app.get('/', (req, res) => res.send('Please set to production'))
  }
app.use(errorHandler)

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

This is my package.json

{
  "name": "stockify-inventory-manager",
  "version": "1.0.0",
  "description": "Manage your Alcohol Inventory easily",
  "main": "server.js",
  "scripts": {
    "start": "node backend/server.js",
    "server": "nodemon backend/server.js",
    "client": "npm start --prefix frontend",
    "dev": "concurrently "npm run server" "npm run client"",
    "heroku-postbuild": "NPM_CONFIG_PRODUCTION=false npm install --prefix frontend && npm run build --prefix frontend"
  },
  "author": "Steve Yoo",
  "license": "MIT",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "bootstrap": "^5.1.3",
    "colors": "^1.4.0",
    "cors": "^2.8.5",
    "dotenv": "^16.0.0",
    "express": "^4.17.3",
    "express-async-handler": "^1.2.0",
    "font-awesome": "^4.7.0",
    "jsonwebtoken": "^8.5.1",
    "mongoose": "^6.2.3",
    "react-router-dom": "^6.2.1"
  }
}

Here are checklists of what I tried:

  1. Whitelist IP on mongoDB with 0.0.0.0/0
  2. Double check connection string from mongoDB and way it is set up in .env
  3. Check if any item is stuck in devdependencies instead of dependencies
  4. Double check my Heroku config variables and ensure they match .env
  5. Update nodejs to latest

If you need more clues source code is in my GitHub: https://github.com/dun1007/Stockify-Inventory-Manager

How to display the average calculation in the screen using react

I have filtered out procedures that I am interested on, and now want to display their average patient_cost. I have the calculation working, but am unsure how to display it in the screen for users to see it. This is what I have:

import React, { useState, useEffect, useMemo } from "react";

function Average ({posts, setUser, user}){
  
  const [procedures, setProcedures] = useState ([])
  const [filteredProcedure, setFilteredProcedure] = useState ("")
  const [averageCost, setAverageCost] = useState (0)
  const uniques = procedures.map(procedure => procedure.procedure)
  .filter((value, index, self) => self.indexOf(value) === index )

  useEffect(() => {
    fetch(`/posts/${procedures}`)
      .then((r) => r.json())
      .then(setProcedures);
  }, [posts]);

    function handleProcedureChange(procedure) {
      setFilteredProcedure(procedure);
      let filteredObject = procedures.filter (p=> p.procedure === procedure)
      console.log("lenght of filtered procedure:", filteredObject)
      
      let total = 0;
      for (let ii = 0; ii < filteredObject.length; ii++) {
        total = total + filteredObject[ii].patient_cost
      }
      console.log("total:", total)
      let avg = total / filteredObject.length
      console.log("average:", avg)
     }
    function handleChange(e) {
      handleProcedureChange(e.target.value);
      console.log(e.target.value)
    }
    return (

    <div >
      <div >
      <label htmlFor="procedure">Procedure:</label>
      <select
        id="procedure"
        name="procedure"
        value={filteredProcedure}
        onChange={handleChange}      >
        <option>Select Procedure</option>
        {uniques.map((procedure) => (
          <option key={procedure} value={procedure}>
            {procedure} 

          </option>
        ))}
      </select>
          </div>
        
          average: {averageCost}
    </div>
  )
}

export default Average;

How can I tie the “let avg = total / filteredObject.length” to the state “average: {averageCost}” at the end? I’m new at this and do not know if there is a better way to write this code.
Appreciate the help here.