Variable and Parameter are declared but never read in jQuery AJAX Request Leaflet and JavaScript

I’m working through trying to plot, style and size cirlceMarker points in Leaflet/JS with a jQuery AJAX request and almost immediately am getting a variable moderateLayer and parameter feature that are declared but never read message. The points draw using the pointToLayer function without styling, but all the subsequent function don’t seem to work. No errors display in the console. Any idea what I’m missing here?

const commonStyles = {
    weight: 1,
    stroke: 1,
    fillOpacity: .8
}

// jQuery method using AJAX request for GeoJSON data
// add sviPoint data
$.getJSON("data/cdps_svis_whp_ctr.json", function (sviPoints) {
    var moderateLayer = L.geoJson(sviPoints, {
        pointToLayer: function (feature, latlng) {
            // Draw circle marker based on pointToLayer function
            return L.circleMarker(latlng, commonStyles);
        },
        // filter layer to display only class value of moderate
                    filter: function (feature) {
                        if (feature.properties.WHP_CLASS.Moderate) {
                            return feature;
                        }
                    },
                    // style stroke and fill
                    style: function (feature) {
                        return {
                            color: '#FF4000',
                            fillColor: '#FF4000',
                            // call function get radius from overall svi weighted mean
                            radius: getRadius(feature.properties.OVERALL_WM)
                        }
                    },
                    onEachFeature: function (feature, layer) {
                        // on mouseover change color to darker shade of orange
                        layer.on('mouseover', function () {
                            layer.setStyle({
                                fillColor: '#401000'
                            });
                        });
                        // return to original fill color when not hovering with mouse
                        layer.on('mouseout', function () {
                            layer.setStyle({
                                fillColor: '#FF4000'
                            });
                        });

                        var popup = `<h4>${feature.properties.CDP_STATE}</h4>
                        <p><b>Overall SVI:</b> ${feature.properties.OVERALL_WM}<br>
                        <p><b>Wildfire Hazard Potential:</b> ${feature.properties.WHP_CLASS}<br>`

                        // Loop through all fuel sources in plants that split atoms
                        // for (var fuelSource in feature.properties.fuel_source) {
                        //  // View the source
                        //  console.log(fuelSource)
                        //  //  Concat all fuel sources 
                        //  popup += `<br>${fuelSource}: ${feature.properties.fuel_source[fuelSource]} MW`
                        // }

                        layer.bindPopup(popup)
                    }
                }).addTo(map);

});```

Here, I am trying to login using firebase auth, but getting 400 error. I am giving exact email & password but it’s showing below error

FirebaseError: Firebase: Error (auth/invalid-email).
at createErrorInternal (assert.ts:122:1)
at _fail (assert.ts:65:1)
at _performFetchWithErrorHandling (index.ts:171:1)
at async _performSignInRequest (index.ts:189:1)
at async _signInWithCredential (credential.ts:37:1) 'n    at Login 

(http://localhost:3000/static/js/bundle.js:339:76)n at Routes
(http://localhost:3000/static/js/bundle.js:75188:5)n at divn at Appn at Router
(http://localhost:3000/static/js/bundle.js:75121:15)n at BrowserRouter
(http://localhost:3000/static/js/bundle.js:73930:5)’

Displaying data in table after fetch() in React Native

I have the following code:

import React, { useEffect, useCallback, useState } from "react";
import { View, TextInput, Pressable } from "react-native";
import { useForm } from "react-hook-form";

const HomeScreen = () => {
  const { register, handleSubmit, setValue } = useForm();
  const [data, setData] = useState([]);

  const onSubmit = useCallback((formData) => {
    fetch(
      "https://myendpoint.com/search?username=" + JSON.stringify(formData.username)
      .then((response) => {
        return response.json();
      })
      .then((data) => {
        setData(JSON.stringify(data));
      });
  }, []);

  const onChangeField = useCallback(
    (name) => (text) => {
      setValue(name, text);
    },
    []
  );

  useEffect(() => {
    register("username");
  }, [register]);

  return (
    <View>
      <TextInput
        style={styles.input}
        secureTextEntry={false}
        placeholder="Username"
        placeholderTextColor="#39364d"
        onChangeText={onChangeField("username")}
      />
      <Pressable style={styles.button} onPress={handleSubmit(onSubmit)}>
        <Text style={styles.buttonText}>Safey</Text>
      </Pressable>
    </View>
  );
};
export default HomeScreen;

What is the easiest way to get the data from the fetch() call and display it in a table? Here’s an example snippet of what the endpoint returns:

[{"username": "1234", "name": "GitHub", "url_main": "https://www.github.com/", "url_user": "https://www.github.com/1234", "exists": "Claimed", "http_status": "200", "response_time_s": "0.45885062500002505"}, {"username": "1234", "name": "GitLab", "url_main": "https://gitlab.com/", "url_user": "https://gitlab.com/1234", "exists": "Claimed", "http_status": "200", "response_time_s": "0.2107984429999874"}]

Ideally, I’d like for the form to disappear once the fetch() is complete and just show the results but not sure the best way to do this.

How does accessing by array index affect efficiency?

Lets say, in a for loop, i am accessing 2 indexes of an array say x and x+1, and comparing those two things to find out how often the numbers of the array increase or decrease.

Is it more/less/equally efficient to have a variable outside of the loop that i reassign each loop, or simply just access it by index inside the loop?

Such as

  let count = 0;

  
  let previousNum = data[0];

  for (let i = 1; i < data.length; i++) {
    const currentNum = data[i];


    if (currentNum > previousNum) {
      count++;
    }

    previousNum = currentNum;
  }

versus

  let count = 0;

  for (let i = 1; i < d.length; i++) {
    const firstNum = data[i - 1];
    const secondNum = data[i];

    if (secondNum > firstNum) {
      count++;
    }
  }

Like on a fundamental level, when it is accessing these indexes, is it iterating through the array to reach the value for these indexes or is it accessing them directly?
By accessing only one index inside the loop vs 2 am i increasing the efficiency of the code or is it no difference?

How to read an array and perform a task?

I have a sample input of array like this

Input data = ['100', 'Red', 'Green', '10', 'Yellow', '5', 'Yellow', '-5', 'Green', '0', '20', 'Red', 'Green', '-25'1]

We have 3 Commands :

“Red -> Stay at the same Location”;
“Yellow -> Go Backward”;
“Green -> Go Forward”

Using the Given Input above the pseudo code of the program is as follows

100 -> Start of the location
red -> 100 = 100 //remains same
green -> 100+10 = 110 //goes forward
yellow -> 110-5 = 105 //moves backward
yellow -> 105-(-5) = 110 //moves backward
green -> 110+0 = 110 //moves forward
green -> 110+20 = 130 //there are two consecutive numbers so it was considered to green
red -> 130
green -> 130+(-25) = 105

The output of the problem is 105.

My brother gave me this question which was asked for him in an interview. I’m a bit new to programming. Can someone please help me with this? I have been scraping web for two days, but can’t help my self. Please help me understand the program and an approach for the coding.

Thank you!

How to get average color from pixels within polygon?

I have object, and within it some data.

I also do have polygons defined as arrays of vertices, for example:

[ {x:50, y:50}, {x:50, y:150}, {x:200, y:100} ]

This is very simple polygon, some will be more complicated (currently the max is 10 points).

I’d like to either find a way to enumerate all pixels within the polygon, or just find average color of it.

Is there any library to do it? Or some clever algorithm?

How do I export mongodb html code to html file?

How do I display an html data piece from mongo db correctly?

Data: The html was encoded

What it shows: Not showing correctly

Code:

<script defer>
      function decodeHtml(html) {
    var txt = document.createElement("textarea");
    txt.innerHTML = html;
    return txt.value;
}
      
    const description = document.getElementById("descontainer")

    description.innerHTML += decodeHtml('<%= post.post.description %>')
 </script>

a const writing I have never seen. Want to know more [duplicate]

I am following an example of React/JavaScript.
In this example, the author wrote the codes about const with a usage I have never seen. I tried to search online but found nothing. I’d like to get an answer and learn more about the usage here. thanks. The codes are like this:

import React, { useEffect, useState } from "react";
function Login() {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const navigation = useUavigate();
  useEffect(()=> {
    if(loading){
       returen;
    }
    if (user) navigate("/dashborad");
  }, [user, loading]);
  return (
    <input
      type="text"
      value = {email}
      onChange = {(e)=> setEmail(e.target.value)}
    />
 // omit other input and button codes
}

export default Login;

I need help getting video ids from a playlist in youtube

I’m trying to fetch all the video ids from a playlist on YouTube. Currently, I have things almost working, except the ids that YouTube is returning a much longer than usual and don’t seem to work. Here’s part of my code:

const requestUrl = `https://www.googleapis.com/youtube/v3/playlistItems?key=${process.env.KEY}&playlistId=${id}&part=id&maxResults=40`

The result under data.items looks like this:

[
  {
    kind: 'youtube#playlistItem',
    etag: 'DxS1pY8G6dwZwfAUJeE8naJEvXM',
    id: 'T0xBSzV1eV9uUHdpaDVQbWY3aEJWQ1Q2LU14bVFOTGFBSVAwellYVGsuRUVCNzhFRENBQzBENDM4MA'
  },
  {
    kind: 'youtube#playlistItem',
    etag: 'hi9WR5RovxYzHpBXddP__e5nFSA',
    id: 'T0xBSzV1eV9uUHdpaDVQbWY3aEJWQ1Q2LU14bVFOTGFBSVAwellYVGsuQzVBOTAwNjQ1OTJFMTVBRg'
  }
etc...

However those ids are much longer than normal and when I go to for example

youtube.com/watch?v=T0xBSzV1eV9uUHdpaDVQbWY3aEJWQ1Q2LU14bVFOTGFBSVAwellYVGsuRUVCNzhFRENBQzBENDM4MA
the url automatically gets shortened to https://www.youtube.com/watch?v=T0xBSzV1eV9 and I get a video unavailable screen. When I changed &part=id to &part=snippet, the same thing happened, I just got more video info.

Thanks in advance!

How can i sort and group data by month in react

Below i have my data from the backend. i want to sort and group this data into months. So i can show this data into charts by month. i am building an admin panel in reactjs and for Chart i am using recharts library. And i want to show the user activity on charts by month.

here is my data.

const data = [
  {
    name: "GameFinished",
    time: 1642599221000,
    properties: {
      gameName: "Game One",
      tenantName: "Player One",
    },
  },
  {
    name: "GameStart",
    time: 1642598611000,
    properties: {
      gameName: "Game One",
      tenantName: "Player One",
    },
  },
  {
    name: "GameStart",
    time: 1642651399000,
    properties: {
      gameName: "Game One",
      tenantName: "Player One",
    },
  },
  {
    name: "GameFinished",
    time: 1643347660000,
    properties: {
      gameName: "Game One",
      goldScore: 300,
      metersRun: 774,
      score: 404,
      tenantName: "Player One",
    },
  },
  {
    name: "GameStart",
    time: 1643347049000,
    properties: {
      gameName: "Game One",
      tenantName: "Player Two",
    },
  },
  {
    name: "GameStart",
    time: 1646468683000,
    properties: {
      gameName: "Game One",
      tenantName: "Player One",
    },
  },
  {
    name: "GameFinished",
    time: 1644560827000,
    properties: {
      gameName: "Game Two",
      goldScore: 0,
      metersRun: 274,
      score: 0,
      tenantName: "Player Two",
    },
  },
  {
    name: "GameStart",
    time: 1644559994000,
    properties: {
      gameName: "Game One",
      tenantName: "Player One",
    },
  },
  {
    name: "GameStart",
    time: 1650508188000,
    properties: {
      gameName: "Game Two",
      tenantName: "Player Two",
    },
  },
  {
    name: "GameStart",
    time: 1650508398000,
    properties: {
      gameName: "Game One",
      tenantName: "Player Two",
    },
  },
  {
    name: "GameFinished",
    time: 1649726319000,
    properties: {
      gameName: "Game Two",
      metersRun: 272,
      score: 0,
      tenantName: "Player One",
    },
  },
];

desired output from this data should look like this


const readyData = [
  {
    month: "Jan",
    gameStart: "7",
    gameFinished: "5",
  },
  {
    month: "Feb",
    gameStart: "5",
    gameFinished: "2",
  },
  {
    month: "Mar",
    gameStart: "0",
    gameFinished: "0",
  },
  {
    month: "Apr",
    gameStart: "1",
    gameFinished: "0",
  },
  {
    month: "May",
    gameStart: "10",
    gameFinished: "10",
  },
  {
    month: "Jun",
    gameStart: "1",
    gameFinished: "8",
  },
  {
    month: "Jul",
    gameStart: "0",
    gameFinished: "0",
  },
  {
    month: "Aug",
    gameStart: "365",
    gameFinished: "230",
  },
  {
    month: "Sep",
    gameStart: "521",
    gameFinished: "230",
  },
  {
    month: "Oct",
    gameStart: "440",
    gameFinished: "120",
  },
  {
    month: "Nov",
    gameStart: "122",
    gameFinished: "70",
  },
  {
    month: "Dec",
    gameStart: "333",
    gameFinished: "330",
  },
];

how to youtube api function run on button click and values are print in toolset metabox

i create a metabox with ‘import’ button in post.php. Also, ready for youtube api data code. but i need, “when i click ‘import’ button to run youtube api data function and the values are print in toolset custom fields metabox” before i publish or draft the post. after, i check the data is correct then will publish the post in wordpress php.

function add_your_meta_box()
    {
    
    add_meta_box('import-data', 'YT Import', 'function_of_metabox', 'movie', 'side', 'high');
    }
    
    add_action('add_meta_boxes', 'add_your_meta_box'); 
    
    function function_of_metabox()
    {?>
        <input type="submit" class="button button-primary button-large" value="Import" id="Import"/>
    <?php }

button meta box

    function my_add_custom_fields1(){
$post_id = get_the_ID();   
$meta2 = get_post_status($post_id);
$meta3 =   get_post_type( $post_id );
$meta1 = get_post_meta(get_the_ID(), 'wpcf-song-duration', true);  
$ytURL = get_post_meta(get_the_ID(), 'wpcf-song-av', true);
// video id from url
$YouTubeCheck = preg_match('%(?:youtube(?:-nocookie)?.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu.be/)([^"&?/ ]{11})%i', $ytURL, $Data);
    If($YouTubeCheck){
        $youtube_id1 = $Data[1];
    }
    // video json data
$dur1 = file_get_contents("https://www.googleapis.com/youtube/v3/videos?part=contentDetails&id=$youtube_id1&key=AIzaSyAbFclaJBklZ53t_UD-Xz85FbWsfD37sX0");
$duration_key1 = json_decode($dur1, true);
$duration1 = $duration_key1['items'][0]['contentDetails']['duration'];
$start = new DateTime('@0');
$start->add(new DateInterval($duration1));
$h11 = $start->format('H:i:s');
// print the value toolset meta box using print_r $h11;
}

print value toolset custom field meta box
toolset custom field meta box

Is there a method in React + PeerJS to end a call without reloading the page?

The original code reloaded the whole page when the call was ended. It’s like after a socket connection the other Peer needs to be destroyed. However, I’m wondering for graphical purposes if there’s a method where you don’t have necessarily to do so.

Here’s actual source code:

SocketContext.jsx

import React, { createContext, useState, useRef, useEffect } from 'react';
import { io } from 'socket.io-client';
import Peer from 'simple-peer';
import * as Constants from '../Constants';
import axios from 'axios';

const SocketContext = createContext();

var socket = io(Constants.BACKEND_URL,{ autoConnect: false });
console.log(socket)

const ContextProvider = ({ children }) => {
  const [callAccepted, setCallAccepted] = useState(false);
  const [callEnded, setCallEnded] = useState(false);
  const [stream, setStream] = useState();
  const [name, setName] = useState('');
  const [call, setCall] = useState({});
  const [me, setMe] = useState('');
  const myVideo = useRef();
  const userVideo = useRef();
  const connectionRef = useRef();
  const [selectedUser, setSelectedUser] = useState('');

  useEffect(() => {
    socket.on('me', (id) => setMe(id));

    socket.on('callUser', ({ from, name: callerName, signal }) => {
      setCall({ isReceivingCall: true, from, name: callerName, signal });
    });
  }, []);

  const connect = () => {
    socket.connect();
  };

  const selectReceiver = (receiver) => {
    axios.get(Constants.SET_SOCK_USER, { params: { username: receiver} }).then(response => {
        setSelectedUser(response.data);
    }).catch(err => {
        setSelectedUser('offline');
    });
  };

  const disconnect = () => {
    socket.disconnect();
  };

  const answerCall = () => {
    setCallAccepted(true);

    const peer = new Peer({ initiator: false, trickle: false, stream });

    peer.on('signal', (data) => {
      socket.emit('answerCall', { signal: data, to: call.from });
    });

    peer.on('stream', (currentStream) => {
        console.log("Call accepted:" + callAccepted)
      userVideo.current.srcObject = currentStream;
    });

    peer.signal(call.signal);
    connectionRef.current = peer;
  };

  const callUser = (id) => {
    const peer = new Peer({ initiator: true, trickle: false, stream });

    peer.on('signal', (data) => {
      socket.emit('callUser', { userToCall: id, signalData: data, from: me, name });
    });

    peer.on('stream', (currentStream) => {
      userVideo.current.srcObject = currentStream;
    });

    socket.on('callAccepted', (signal) => {
      setCallAccepted(true);
      peer.signal(signal);
    });
    console.log(connectionRef.current);
    connectionRef.current = peer;
    console.log(connectionRef.current);
  };

  const leaveCall = () => {
    if (!callEnded) {
      call.isReceivingCall = false;
      console.log('denied');
    }
    else {
      setCallEnded(true);
      disconnect();
      userVideo.current.srcObject = null;
      console.log(connectionRef.current);

      socket = io(Constants.BACKEND_URL,{ autoConnect: false });
      connect();
      socket.on('me', (id) => setMe(id));
      socket.on('callUser', ({ from, name: callerName, signal }) => {
        setCall({ isReceivingCall: true, from, name: callerName, signal });
      });
    }
  };

  return (
    <SocketContext.Provider value={{
      call,
      callAccepted,
      myVideo,
      userVideo,
      stream,
      name,
      setName,
      callEnded,
      me,
      callUser,
      leaveCall,
      answerCall,
      setStream,
      connect,
      selectedUser,
      selectReceiver,
      connectionRef,
      disconnect
    }}
    >
      {children}
    </SocketContext.Provider>
  );
};

export { ContextProvider, SocketContext };

Notifications.jsx

import { Button } from '@material-ui/core';
import { SocketContext } from '../Contexts/SocketContext';
import Slide from '@mui/material/Slide';
import Stack from '@mui/material/Stack';
import Divider from '@mui/material/Divider';
import { Phone, PhoneDisabled } from '@material-ui/icons';
import ReactAudioPlayer from 'react-audio-player';
import ringtone from '../audio/ringtone.mp3';
import {Typography, Box } from '@material-ui/core';

export default function Notifications() {
  const { answerCall, call, callAccepted, leaveCall } = useContext(SocketContext);

  return (
    <>
    {call.isReceivingCall && !callAccepted && (
        <ReactAudioPlayer
         src= { ringtone }
         autoPlay
         loop
       />
    )}
    <Slide style={{
        backgroundColor: '#5865f2',
        position: 'absolute',
        bottom: '10px',
        right: '10px',
        zIndex: 1,
        padding: '20px',
        border: '1px solid white',
        color: 'white',
        height: "25%",
    }}
     direction="left" in = {call.isReceivingCall && !callAccepted} mountOnEnter unmountOnExit>
     <Stack direction="column"
         divider={<Divider sx={{ bgcolor: "#999a9d" }} orientation="vertical" flexItem />}
         spacing={2}
         justifyContent="center"
         >
            <Typography component="div">
                <Box sx={{ fontSize: 25, m: 1 }}>Incoming call from:</Box>
                <Box sx={{ fontSize: 25, m: 1, fontStyle: 'oblique' }}>{call.name}</Box>
            </Typography>
            <Stack direction="row" justifyContent="center" spacing={2}>
                <Button variant="contained" style={{ backgroundColor: '#98ff30', color: 'black'}} startIcon={<Phone fontSize="large" />} onClick={answerCall}>
                  Answer
                </Button>
                <Button variant="contained" style={{ backgroundColor: '#ff3419', color: 'black'}} startIcon={<PhoneDisabled fontSize="large" />} onClick={leaveCall}>
                  Decline
                </Button>
            </Stack>
        </Stack>
    </Slide>
    </>
  );
}

VideoPlayer.jsx

import React, { useContext } from 'react';
import {Typography, Box, makeStyles } from '@material-ui/core';
import { SocketContext } from '../Contexts/SocketContext';
import Stack from '@mui/material/Stack';
import Divider from '@mui/material/Divider';

const useStyles = makeStyles((theme) => ({
    video: {
      width: '100%',
      height: window.innerHeight * 0.80,
    },container: {
        backgroundColor: '#393b41',
    }
}));

const VideoPlayer = () => {
  const { callAccepted, myVideo, userVideo, callEnded, stream, name, call } = useContext(SocketContext);
  const classes = useStyles();

  return (
    <Stack direction="row"
        divider={<Divider sx={{ bgcolor: "#999a9d" }} orientation="vertical" flexItem />}
        spacing={2}
        justifyContent="center"
        >
      {stream && (
        <Box className={classes.container}>
            <video playsInline muted ref={myVideo} autoPlay className={classes.video} />
            <Typography variant="h6" style = {{color: "white"}} gutterBottom component="div">{name}</Typography>
        </Box>
      )}
      {callAccepted && !callEnded &&(
        <Box className={classes.container}>
            <video playsInline ref={userVideo} autoPlay className={classes.video} />
            <Typography variant="h6"  style = {{color: "white"}} gutterBottom component="div">{call.name}</Typography>
        </Box>
      )}
    </Stack>
  );
};

export default VideoPlayer;

Any suggestion is appreciated!
Thanks in advance!