Can not excess the value of a variable outside the class

i have this code where it will show the temperature of a place using Accuweather API. right now I have hardcoded newdelhi into it to find the weather condition of that place.but I want to know the weather by using the form. i am right know testing it with first name input form and trying to send that value in the location function. but I can’t use the input given by the user and use it outside the class. need help. i am new in react and appreciate if someone could help me with it. thank you

import React ,{useState,useEffect,state}from 'react';
import './App.css';
const apikey='zVp5GoY9fbwt8h4u5CvcWwneD1emnMMD';

const getcity = async(city) => {
    const base = 'http://dataservice.accuweather.com/locations/v1/cities/search';
    const query = `?apikey=${apikey}&q=${city}`;
  
    const response = await fetch(base + query);
    const data = await response.json();
  
    return data[0];
  }

  getcity('New Delhi')
  .then(data => {
    return getweather(data.Key);
  }).then(data =>{
    console.log(data);
  })
  .catch(err =>console.error(err));

  const getweather = async(id)=>{
  
    const base= 'http://dataservice.accuweather.com/currentconditions/v1/';
    const query =`${id}?apikey=${apikey}`;
  
    const response = await fetch(base + query)
    const data = await response.json();
  
    return data[0];
  }
  let newval = "initial value";
  console.log(newval)

export default class CustomerForm extends React.Component {

  
    
    
  constructor(props) {
    super(props);
    

    this.state = {
      customer: {
        firstName: props.firstName,
        lastName: props.lastName,
        status: props.status,
        
      }
    } 
  }

  handleFirstNameChanged(event) {
    var customer        = this.state.customer;
    customer.firstName  = event.target.value;

    this.setState({ customer: customer });
  }

  handleLastNameChanged(event) {
    var customer      = this.state.customer;
    customer.lastName = event.target.value;

    this.setState({ customer: customer });
  }

  handleStatusChanged(event) {
    var customer    = this.state.customer;
    customer.status = event.target.value;
    this.setState({ customer: customer });
  }
  
  
  handleButtonClicked() {
    console.log(this.state.customer);
    newval=this.state.customer.firstName;
    console.log(newval);
  }
  
  render() {
    return (
      <div>
        <label>
          First Name: 
        </label>
        <input type="text" value={this.state.customer.firstName} onChange={this.handleFirstNameChanged.bind(this)}/>
        <br/>
        <label>
          Last Name:
        </label>
        <input type="text" value={this.state.customer.lastName} onChange={this.handleLastNameChanged.bind(this)}/>
        <br/>
        <label>
          Status:
        </label>
        <select value={this.state.customer.status} onChange={this.handleStatusChanged.bind(this)}>
          <option value="PENDING">
            Pending
          </option>
          <option value="APPROVED">
            Approved
          </option>
        </select>
        <hr/>
        <button onClick={this.handleButtonClicked.bind(this)}>
          Save Record
        </button>
      </div>
    );
  }
}

Sending data from a Javascript program to a Python program and vice versa

I’m working on a project where data gathered from a Javascript program can be treated in a python program since many libraries in python are absent in Javascript. I’m currently trying to use Ajax to send the data between the .js file and the .py file

    $.ajax({
      type: "POST",
      url: "/Users/ryancheng/Desktop/coding/dashathon2021/dasha-app/webscrape.py",
      data: {param:restResult.data.features},
      success: function(response){
        output = response;
        alert(output);
      }
    }).done(function(data){
      console.log(data);
      alert(data);
    })

However I get the error ReferenceError: $ is not defined. Any help would be much appreciated. If there is any other method to send files back and forth that I am not aware of, please let me know.

how to insert array of data per column in MySQL?

I have arrays stacked in 1 array and I would like to insert each array per column in MySQL.
I have reached to insert all data in arrays to 1 column, but I want to insert an array per column.
Please see the screenshot and code below.

Image of array stack

con.connect(async(err)=>{
  const x = await getStock()
  if(err){
      console.log(err);
      return err;
  }else{
      console.log("DB ok");
  }
  console.log("connected");
  x.filter(item=>item===undefined?false:true).map(item=>item.forEach(item=>{
    const sql ="INSERT INTO test (testCol1) VALUES ?";
    const values=[
      [item]
    ];
    con.query(sql,[values],(err,result)=>{
      if(err)throw err;
      console.log("this have been recorded"+result);
    });
  }));
});

Javascrit .createTextNode output is giving errors

I created a website where it tells you your age. I use document.createTextNode to store the output but the output is not working properly. Here is the output code

var h1 = document.createElement("p");
h1.setAttribute("id", "mainText")
var mainText = document.createTextNode("You are ", ageYears, " years, ", ageMonths, " 
months and ", ageDays, " days old.");
h1.appendChild(mainText);
document.getElementById("new-age").appendChild(h1);

When I run my code, it only outputs the first part, “You are”. Is there any way to output the entire message.

when running npm run serve on lunix it’s not working

[email protected] serve
vue-cli-service serve

ERROR TypeError: Cannot read properties of undefined (reading ‘version’)
TypeError: Cannot read properties of undefined (reading ‘version’)
at module.exports (/home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-plugin-eslint/index.js:20:27)
at /home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-service/lib/Service.js:78:7
at Array.forEach ()
at Service.init (/home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-service/lib/Service.js:76:18)
at Service.run (/home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-service/lib/Service.js:215:10)
at Object. (/home/compumart/Public/Front-End/app-zero/node_modules/@vue/cli-service/bin/vue-cli-service.js:36:9)
at Module._compile (node:internal/modules/cjs/loader:1095:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1147:10)SEMBLY’ ‘-DV8_ALLOCATION_FOLDING’ ‘-DV8_ALLOCATION_SITE_TRACKING’ ‘-DV8_ADVANCED_BIGINT_ALGORITHMS’ ‘-DICU_UTIL_DATA_IMPL=ICU_UTIL_DATA_STATIC’ ‘-DUCONFIG_NO_SERVICE=1’ ‘-DU_ENABLE_DYLOAD=0’ ‘-DU_STATIC_IMPLEMENTATION=1’ ‘-DU_HAVE_STD_STRING=1’ ‘-DUCONFIG_NO_BREAK_ITERATION=0’ -I../deps/v8 -I.

Form POST request, not working. Undefined in Server (HTML,JS,EXPRESS,NODE,MONGODB)

Im working in an application with a front and a back end, my back end written in nodejs, using express, multer and mongoose, is working pretty fine when i send data through postman, but as soon as i try the same request in my client made with html,css and vanilla javascript, it doesnt work, it gives me the following error:

TypeError: Cannot read property ‘path’ of undefined (which is pointing towards my network file that manages connections for a specific entity).

Despite the error mentioned above, i’ve been trying to send a file and a string from the form in html to the network file in my node server, but i keep getting the same 2 or so errors in terminal.

Here is some code so you can understand better.

server.js (main entry point)

const express = require('express');
const app = express();
const server = require('http').Server(app);
const path = require('path');

const cors = require('cors');
const bodyParser = require('body-parser');
const db = require('./db');
const router = require('./network/routes');
const config = require('./config');

db(config.dbUrl);
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(`${config.publicRoute}`, express.static(path.join(__dirname, 'public')));
server.listen(config.port, function() {});
console.log(`Application listen on ${config.host}${config.port}`);
router(app);

network.js (file that manages connections for “banner” entity)

const express = require('express');
const multer = require('multer');
const router = express.Router();
const response = require('../../network/response');
const controller = require('./controller');
const path = require('path');
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, path.join(__dirname, '../../public/files'))
    },
    filename: function(req, file, cb) {
        cb(null, path.extname(file.originalname))
    }
})
const upload = multer({ storage: storage })

router.post('/', upload.single('file'), function(req, res) {

    console.log(req.body);
    controller.addBanner(req.body.name, req.file, req.file.path)
        .then((fullMessage) => {
            response.success(req, res, fullMessage, 201);
        })
        .catch(e => {
            response.error(req, res, 'Unexpected error', "Simulated Error", 400, e);
        });
});

router.get('/', function(req, res) {
    controller.getBanners()
        .then((banners) => {
            response.success(req, res, banners, 200);
        })
        .catch(e => {
            response.error(req, res, 'Internal Error', 500, e);
        })
});

router.delete('/:id', function(req, res) {
    controller.deleteBanner(req.params.id)
        .then(() => {
            response.success(req, res, `Imagen con id: ${req.params.id} ,eliminada`, 200);
        })
        .catch(e => {
            response.error(req, res, 'Internal Error', 500, e);
        })
});

module.exports = router;

panel.html (where the form that supposedly sends the post request lies)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- <meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'"> -->
    <link rel="stylesheet" type="text/css" href="css/panel-style.css">
    <script defer src="panel-script.js"></script>
    <title>Panel de Control</title>
</head>

<body>
    <header>
        <img src="assets/mrvapeslogo.png" alt="mrvapes logo">
        <a href="index.html"></a>
    </header>
    <section>
        <form accept-charset="UTF-8" enctype="multipart/form-data" action="../components/banner/network.js" autocomplete="off" method="GET" target="_blank">
            <label for="user">Banners Activos</label><br/>
            <ul class="files-container">

            </ul>
        </form>
        <form accept-charset="UTF-8" enctype="multipart/form-data" action="http://localhost:3000/banner" autocomplete="off" method="POST" target="_blank">
            <div class="container">
                <div class="button-wrap">
                    <!-- <label class="button" for="upload">Subir</label> -->
                    <input type="text" id="name" placeholder="Nombre de Archivo" value="" name="name" required>
                    <input id="image" value="Subir" placeholder="Subir Archivo" type="file" required>
                    <button id="upload" name="send-post--request" value="post-request" type="submit">Enviar</button>
                    <!-- <input id="upload" type=" submit " value="Enviar " onclick="submit() "> -->
                </div>
            </div>
        </form>
    </section>
</body>

panel-script.js (client-side file that manages the logic for the http request)

const upload = document.getElementById("upload");
const image = document.getElementById("image");
const title = document.getElementById("name");

upload.addEventListener("click", (e) => {
    console.log('im in bro');
    e.preventDefault();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            alert(xhr.response);
        }
    }
    xhr.open("POST", 'http://localhost:3000/banner', true);
    //xhr.setRequestHeader("Accept", "multipart/form-data");
    //xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    var fileSent = {
        "name": title,
        "file": image
    };
    console.log(fileSent);
    xhr.send(fileSent);
    alert('Subida exitosa!');
})


function retrieve() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            alert(xhr.response);
        }
    }
    xhr.open('get', 'http://localhost:3000/banner', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send();
}

I’m all ears towards your suggestions, thanks in advance fellow developers.

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’) at (index):72

let searchBtn = document.querySelector ( '#Search-btn');

let searchBar = document.querySelector ( ‘.search-bar-container’);

searchBtn.addEventListener(‘click’, () =>{

searchBtn.classlist.toggle('fa-times');
searchBar.classList.toggle('active');

});

let searchBtn = document.querySelector ( '#Search-btn');
let searchBar = document.querySelector ( '.search-bar-container');

searchBtn.addEventListener('click', () =>{

    searchBtn.classlist.toggle('fa-times');
    searchBar.classList.toggle('active');
});
@import url('https://fonts.googleapis.com/css2?family=Nunito:wght@200;300;400;600;700&display=swap');

:root {
    --orange:#ffa500;
    
}

*{
    font-family: 'Nunito', sans-serif;
    margin: 0; padding: 0;
    box-sizing: border-box;
    text-transform: capitalize;
    outline: none; border: none;
    transition: all .2s linear;
    text-decoration: none;
    
}

*::selection{
    background: var(--orange);
    color: #fff;
}

html{
    font-size: 62.5%;
    overflow-x: hidden;
    scroll-padding-top: 6rem;
    scroll-behavior: smooth;
}

header{
    position: fixed;
    top: 0; left: 0; right: 0;
    background: #333;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 2rem 9%;
}

header .logo {
    font-size: 2rem;
    font-weight: bolder;
    color: #fff;
    text-transform: uppercase;
}

header .logo span {
    color: var(--orange);
}

header .navbar a{
    font-size: 2rem;
    color: #fff;
    margin:0 .8rem;
}

header .navbar a:hover{
    color: var(--orange);
}

header .icons i{
    font-size: 2.5rem;
    color:#fff;
    cursor: pointer;
    margin-right: 2rem;
}

header .icons i:hover{
    color: var(--orange);
}

header .search-bar-container{
    position: absolute;
    top: 100%; left: 0; right: 0;
    padding: 1.5rem 2rem;
    background: #333;
    border-top: .1rem solid rgba(225, 225, 225, .2);
    display: flex;
    align-items: center;
    z-index: 1001;
    clip-path: polygon(0 0, 100% 0, 0 0);
}

header .search-bar-container.active{
    clip-path: polygon(0 0, 100% 0, 0 0);
}

#search-bar {

    width: 100%;
    padding: 1rem;
    text-transform: none;
    color: #333;
    font-size: 1.7rem;
    border-radius: 100rem;
}

header .search-bar-container label{
    color: #fff;
    cursor: pointer;
    font-size: 3rem;
    margin-left: 1.5rem;
}

header .search-bar-container label:hover {
    color: var(--orange);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Travel Agency</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    
<header>
    <a href="#" class="logo"> <span>T</span>ravel</a>

    <nav class="navbar">
        <a href="#home">home</a>
        <a href="#book">book</a>
        <a href="#package">package</a>
        <a href="#services">services</a>
        <a href="#review">review</a>
        <a href="#contact">contact</a>
    </nav>

    <div class="icons">
        <i class="fa fa-search" id="search-btn"></i>
        <i class="fa fa-user" id="login-btn"></i>
    </div>

    <form action="" class="search-bar-container">
        <input type="search" id="search-bar" placeholder="search here...">
        <label for="search-bar" class="fa fa-search" ></label>
    </form>

</header>

When I try to run my javascript code its give me an error. I do check my code and syntax twice i could not find the error please help me with that.

Using XPath to get an elmement in SVG

I am trying to get an element in an SVG file using XPath. I have tried the following code, but singleNodeValue is null. The doc seems to be correct, so I guess either evaluate() arguments or the XPath is wrong, but I cannot find anything wrong. Why doesn’t it work?

JavaScript

fetch('test.svg')
.then(response => response.text())
.then(data=>{
    const parser = new DOMParser();
    const doc = parser.parseFromString(data, "text/xml");
    console.log(doc);
    const res = doc.evaluate("//symbol[@label='square']", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    console.log(res.singleNodeValue);
})

SVG

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">

    <symbol label ="square">
        <rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
    </symbol>

</svg>

How do i trigger a link with no id via console

I am simply trying to trigger a link with no id via console. I have tried multiple scenarios and none seem to work. It is a link with lots of classes and no id.

$('.videoHolder').find('a.icon-play').trigger('click');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="videoHolder hover">
  <div class="videoDisplay">

    <video class="persistentNativePlayer nativeEmbedPlayerPid" poster="data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%01%00%00%00%01%08%02%00%00%00%90wS%DE%00%00%00%01sRGB%00%AE%CE%1C%E9%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%07tIME%07%DB%0B%0A%17%041%80%9B%E7%F2%00%00%00%19tEXtComment%00Created%20with%20GIMPW%81%0E%17%00%00%00%0CIDAT%08%D7c%60%60%60%00%00%00%04%00%01'4'%0A%00%00%00%00IEND%AEB%60%82"
      id="pid_kaltura_player" kentryid="1_4u0ocu4u" kuiconfid="" kwidgetid="" kpartnerid="" preload="none" width="560" height="395" src="" style="position: absolute; left: 0px; top: 0px;"></video>
    <div class="videoShadow"></div>
    <div class="mwEmbedPlayer" id="kaltura_player" style=""></div>
  </div><a tabindex="-1" href="#" role="button" class="comp largePlayBtn  largePlayBtnBorder icon-play" aria-label="Play clip" data-order="1" data-plugin-name="largePlayBtn" style="display: flex; opacity: 1;">Mylink</a></div>

while clicking local push notification how to navigate and reload a page in flutter

Hi iam new user in flutter app. I need while clicking the notification navigate and reload the page. can you please suggest how to navigate and reload the page while clicking the notification. i have used flutter local push notification as the following example link(https://blog.logrocket.com/implementing-local-notifications-in-flutter/) working fine but while clicking the notication the page does’t navigate and reload.

I have also created secondscreen(this is navigate page) but in this code selectNotification functionality not working. please check below code and give me a solution.

//notification_service.dart
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'secondscreen.dart';

import 'main.dart';

class NotificationService {
  //NotificationService a singleton object
  static final NotificationService _notificationService =
      NotificationService._internal();

  factory NotificationService() {
    return _notificationService;
  }

  NotificationService._internal();

  static const channelId = '123';

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  Future<void> init() async {
    final AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    final IOSInitializationSettings initializationSettingsIOS =
        IOSInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
    );

    final InitializationSettings initializationSettings =
        InitializationSettings(
            android: initializationSettingsAndroid,
            iOS: initializationSettingsIOS,
            macOS: null);

    tz.initializeTimeZones();

    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: selectNotification);
  }

  AndroidNotificationDetails _androidNotificationDetails =
      AndroidNotificationDetails(
    'channel ID',
    'channel name',
    'channel description',
    playSound: true,
    priority: Priority.high,
    importance: Importance.high,
  );

  Future<void> showNotifications() async {
    await flutterLocalNotificationsPlugin.show(
      0,
      "Notification sundar",
      "This is the Notification Body!",
      NotificationDetails(android: _androidNotificationDetails),
    );
  }

  Future<void> scheduleNotifications() async {
    await flutterLocalNotificationsPlugin.zonedSchedule(
        0,
        "Notification Title",
        "This is the Notification Body!",
        tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
        NotificationDetails(android: _androidNotificationDetails),
        androidAllowWhileIdle: true,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime);
  }

  Future<void> cancelNotifications(int id) async {
    await flutterLocalNotificationsPlugin.cancel(id);
  }

  Future<void> cancelAllNotifications() async {
    await flutterLocalNotificationsPlugin.cancelAll();
  }
}

Future selectNotification(String payload) async {
  //handle your logic here
  print('String');
  if (payload != null) {
    print('sundar');
    BuildContext context;
    Navigator.push(
      context,
      MaterialPageRoute<void>(builder: (context) => SecondScreen()),
    );
  }
}

what is callback function?

  1. could you please explain code (fastseries,cb)
  2. how to use fastseries
  3. I dont understatnd cb ,
    what is promisify

const { readFile } = require('fs')
const series = require('fastseries')()
const files = Array.from(Array(3)).fill(__filename)

const print = (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(Buffer.concat(data).toString())
}

 const readers = files.map((file) => {
  return (_, cb) => {
    readFile(file, (err, contents) => {
      if (err) cb(err)
      else cb(null, contents)
    })
  }
})

series(null, readers, null, print)

Prepending text to list items without class or id tags

I’m working with the Docsify.js markdown parser framework and it automatically creates a sidebar from the headings in a document (unless you manually create a sidebar).

I have some CSS that numbers list elements, but want to convert it to JS as there are rendering issues when classes are added as the page scrolls (ie. adding .active).

Originally I was trialling using this snippet but it doesn’t output it as an auto incrementing hierarchical number system:

var li = document.getElementsByTagName( 'li' );
for( var i = 0; i < li.length; i++ ) {
  var prefix = '1.';
  li[i].innerHTML = prefix + ' Title ' + i;
  prefix++;
}

The sidebar that is generated is in the following format:

<aside class="sidebar">
  <div class="sidebar-nav">
    <ul>
      <li>Title 1</li>
      <ul>
        <li>Title 2</li>
        <ul>
          <li>Title 3</li>
          <ul>
            <li>Title 4</li>
            <ul>
              <li>Title 5</li>
              <ul>
                <li>Title 6</li>
              </ul>
            </ul>
          </ul>
        </ul>
      </ul>
      <li>Title 1</li>
      <ul>
        <li>Title 2</li>
        <ul>
          <li>Title 3</li>
          <ul>
            <li>Title 4</li>
            <ul>
              <li>Title 5</li>
              <ul>
                <li>Title 6</li>
              </ul>
            </ul>
          </ul>
        </ul>
      </ul>
    </ul>
  </div>
</aside>

I understand the HTML structure isn’t valid with <ul> being a descendant of an <ul> but this is the code that is outputted and I have no control over it.

However, I want to be able to number the headings with sections and sub-sections:

1. Title 1
 1.1. Title 2
  1.1.1. Title 3
   1.1.1.1. Title 4
    1.1.1.1.1. Title 5
     1.1.1.1.1.1. Title 6
2. Title 7
 2.1. Title 8
  2.1.1. Title 9
   2.1.1.1. Title 0
    2.1.1.1.1. Title 1
     2.1.1.1.1.1. Title 2

I’m struggling to find a way to be able to target the first <li> (or the H1), and then being able to access the next <ul> via .nextElementSibling to continue the loop and prepend the numbering.

As far as I have gotten to at the moment is: document.querySelectorAll( 'div.sidebar-nav > ul' ) and its not much to go on!

I think I’m really out of my depth for javascript here, and was hoping that I’d be able to get some help on being able to loop through the <li> and ` elements to prepend the numbers.