When iterating through HTML elements, some elements are returning an empty image when using domtoimage.toPng()

I am trying to iterate through all the widgets (Charts/tables etc) that is currently being contained within a div to be generated as a png by utilizing domtoimage.toPng() however, it is only able to return me the PNG result of the first widget and not the following widgets. The following widgets will only display a empty png.

Image returned as follows
enter image description here
enter image description here

After some debugging,
I think domtoimage.toPng() is only able to return me the appropriate image of the HTML element when the HTML div element has the attributes of gs-x = 0 and gs-y = 0 which renders it as the first div in the div stack

Question
What is actually going on? Why cant all the widgets as represented by their divs that I am iterating through be converted into an actual png that I can use?

enter image description here

asp.net web application control client’s screen

We have this project requirement, An online exam where there are examinees and one examiner. Each examinee has own computer to where they will be answering the exam. However examinee has no control to move to next question only examiner has this control. Once the examiner move to next question all examinee’s screen will move to next question also. Is it possible in asp.net web application? Any idea please?

Convert UUID from type string to integer Javascript

So I am trying to pass a UUID to a function which then calls and endpoint of deleting a blog. I’m getting the id but it is in string format like “9ba354d1-2d4c-4265-aee1-54877f22312e” and i get an error of TypeError: Cannot create property 'message' on string '9ba354d1-2d4c-4265-aee1-54877f22312e'
I tried using the parseInt() but it’s not working in my case. Any solution ?

Why is Local Storage result undefined using ASP.Net core ViewComponent?

I’m using a Viewcomponent in asp.net core 6 in order to display database items in a dropwdownbox on the index page.

ViewComponent on Index Page:

@await Component.InvokeAsync(“DropDownList”)

The idea is to choose an item from this dropdownlist that’s in the index page and display the result on another page lets say in a input box. I tried using JavaScript’s Local Storage but then I get “undefined”.

Is this possible (to show the chosen item on another page using ViewComponent?) The code works using hard coded items in HTML. But I would like to display chosen items from db directly if possible. If there is a better logic please let me know. Thankyou.

Pulling a variable out of Promise when querying data from Firestore Firebase database – Javascript

let savedArrayUID = []; let savedArrayEmails = [];

function pullIt(emailSearch) {

    db.collection(collectionName).where('email', '==', emailSearch).get()
        .then((querySnapshot) => {
            querySnapshot.forEach((doc) => {
                savedArrayUID.push(doc.id);
                savedArrayEmails.push(doc.data());
                // doc.data() is never undefined for query doc snapshots

                console.log(doc.id, " => ", doc.data());
                // saved.   push(doc.id);
                return savedArrayUID; 
            })
        });
}

I can query the data from the database but cannot pull the variable out of the scope of the function.
I want to use this function to pass through emails to find info of their profile saved in my Database.

I really struggle to understand how Promiseses can help here. I have a feeling this is already solved, but I could not find an answer anywhere.

Mouse movement doesn’t appear to be updating fragment shader (three.js)

I’m trying to implement the Voronoi shader in the Book of Shaders in three.js and cannot seem to wrap my head around why the mouse position is not having any effect on my visible output. (This is for the initial demo where the mouse moves and the Voronoi updates)

I’m logging the mouse position, checking that the uniform value is updating, yet the shader doesn’t appear to be changing whatsoever on my end.

This is what I see (static image – no change at all) while animate is being called.

static voronoi

I’m seeing u_time update when I log it in animate so the callback is happening. The uniforms just don’t appear to be updated and I thought I was updating them correctly.

Note – I followed this SO post regarding tracking mouse position as a basis, though I tried both that mouse position and the tweaked mouse I have below (to map from [-1,1]).

Full code:

<!--
  * Based on Book of Shaders 12:
  https://thebookofshaders.com/12/
-->

<!DOCTYPE HTML>
<html>

<head>
  <title>WebGL Demo - Voronoi</title>
  <meta charset="utf-8">
  <style>
    body {
      margin: 0;
      padding: 0;
      overflow: hidden;
    }
  </style>

  <script src="./libraries/threejs/three.min.js"></script>

  <!-- shaders -->
  <script type="x-shader/x-vertex" id="vertexShader">
    void main() {
      vec4 modelViewPosition = modelViewMatrix * vec4(position, 1.0);
      gl_Position = projectionMatrix * modelViewPosition;
    }
  </script>
  <script type="x-shader/x-fragment" id="fragmentShader">
    uniform vec2 u_resolution;
    uniform vec2 u_mouse;
    uniform float u_time;

    void main() {
      vec2 st = gl_FragCoord.xy/u_resolution.xy;
      st.x *= u_resolution.x/u_resolution.y;

      vec3 color = vec3(.0);

      // Cell positions
      vec2 point[5];
      point[0] = vec2(0.83,0.75);
      point[1] = vec2(0.60,0.07);
      point[2] = vec2(0.28,0.64);
      point[3] = vec2(0.31,0.26);
      point[4] = u_mouse/u_resolution;

      float m_dist = 1.;  // minimum distance

      // Iterate through the points positions
      for (int i = 0; i < 5; i++) {
          float dist = distance(st, point[i]);

          // Keep the closer distance
          m_dist = min(m_dist, dist);
      }

      // Draw the min distance (distance field)
      color += m_dist;

      // Show isolines
      // color -= step(.7,abs(sin(50.0*m_dist)))*.3;

      gl_FragColor = vec4(color,1.0);
    }
  </script>
</head>

<body></body>

<script>
  let camera, scene, renderer;
  let uniforms, mesh;

  init();
  animate();

  function init() {
    scene = new THREE.Scene();
    camera = new THREE.Camera();
    camera.position.z = 1;

    renderer = new THREE.WebGLRenderer({ antialias: true });
    renderer.setClearColor(0x000000, 1);
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setPixelRatio(window.devicePixelRatio);
    document.body.appendChild(renderer.domElement);

    uniforms = {
      u_resolution: { type: 'vec2', value: new THREE.Vector2() },
      u_mouse: { type: 'vec2', value: new THREE.Vector2() },
      u_time: { type: 'float', value: 1.0 }
    };

    let vShader = document.getElementById("vertexShader").textContent;
    let fShader = document.getElementById("fragmentShader").textContent;

    let geometry = new THREE.PlaneGeometry(2, 2);

    // give it a material
    let material = new THREE.ShaderMaterial({
      uniforms: uniforms,
      fragmentShader: fShader,
      vertexShader: vShader,
    });

    // and now create the mesh (geom+mat)
    mesh = new THREE.Mesh(geometry, material);
    scene.add(mesh);

    onWindowResize();
    window.addEventListener('resize', onWindowResize, false);
  }

  function animate() {
    requestAnimationFrame(animate);
    render();
  }

  function render() {
    uniforms.u_time.value += 0.05;
    renderer.render(scene, camera);
  }

  function onWindowResize(e) {
    renderer.setSize(window.innerWidth, window.innerHeight);
    uniforms.u_resolution.value.x = renderer.domElement.width;
    uniforms.u_resolution.value.y = renderer.domElement.height;
  }

  document.onmousemove = function (e) {
    uniforms.u_mouse.value.x = (e.clientX / window.innerWidth) * 2 - 1;//e.pageX / window.innerWidth;
    uniforms.u_mouse.value.y = -(e.clientY / window.innerHeight) * 2 + 1;//e.pageY / window.innerHeight;
  }
</script>
</html>

Vite – esbuildx.x.x is not compate with vite

Issue

I created a React JS project using vite when starting the server today ran into this error after an update

X [ERROR] [plugin vite:dep-pre-bundle] Detected inconsistent metadata for the path "node_modules/react/index.js" when it was imported here:

I am using vite version 2.9.1

Details of the Issue


  vite v2.9.1 dev server running at:

  > Local: http://localhost:3000/
  > Network: use `--host` to expose

  ready in 234ms.

X [ERROR] [plugin vite:dep-pre-bundle] Detected inconsistent metadata for the path "node_modules/react/index.js" when it was imported here:

    node_modules/react/cjs/react-jsx-dev-runtime.development.js:16:20:
      16 │ var React = require('react');
         ╵                     ~~~~~~~

  The original metadata for that path comes from when it was imported here:

    dep:react:1:23:
      1 │ export default require("./node_modules/react/index.js");
        ╵                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

  The difference in metadata is displayed below:
  
   {
  -  "pluginName": null,
  +  "pluginName": "vite:dep-pre-bundle",
   }

System Info

System:
    OS: macOS 12.2.1
    CPU: (4) x64 Intel(R) Core(TM) i5-7600 CPU @ 3.50GHz
    Memory: 426.07 MB / 16.00 GB
    Shell: 5.8 - /bin/zsh
  Binaries:
    Node: 17.9.0 - /usr/local/bin/node
    Yarn: 1.22.17 - ~/.config/yarn/global/node_modules/.bin/yarn
    npm: 8.5.5 - /usr/local/bin/npm
  Browsers:
    Chrome: 100.0.4896.75
    Edge: 100.0.1185.39
    Safari: 15.3
  npmPackages:
    @vitejs/plugin-vue: ^2.3.0 => 2.3.1 
    vite: 2.9.1 => 2.9.1

To get all the static hyperlinks from another view

Currently, I am able to get all the hyperlinks from the loaded page in the application. I have added the below code to the shared _Layout page in javascipt.
”’

    var links = document.getElementByTagName("a");
    var urls=[];
    for (var i = 0;i<links.length;i++)
    {
       var datalink = new Object();
       datalink.label=links[i].text;
       datalink.value=links[i].getAttribute("href");
       if (datalink.value.startswith("https://")) {
       urls.push(datalink);
       }
       }
       '''

What I want is that I should also be able to fetch the hyperlinks or the content from the other views (for example /Accounts/Index.cshtml) of the MVC application at the startup.
Any suggestions?

Django Javascript preselected value from database

I have a series of drop downs that are dependent upon the one above it. Starting with ‘state’ then pulls a list of all cities for that state and then all schools in that city.

I am trying to find a way that when a user wants to update this information that it will pull the current information from the database and then have that value preselected from the list. Currently it just shows the ‘Choose a state’ the whole time until selected. If the user is from Maine, I want that to be selected already.

Also, if possibly, how to make this an if statement. That if the user’s state is null, then ‘Choose state’ is displayed and if not null, display current state.

Thank you very much for the help!

views.py

def get_json_state_data(request):
    qs_val_unsorted = list(States.objects.values())
    qs_val = sorted(qs_val_unsorted, key=lambda d: d['name'])
    return JsonResponse({'data':qs_val})

display.html

<div class="ui fluid search selection dropdown" id='states_dropdown'>
  <input type="hidden" name="state">
  <i class="dropdown icon"></i>
  <div class="default text" id="state_text">Choose a state</div>
    <div class="menu" id='state_data_box'> </div>
  </div>

main.js

 $.ajax({
  type: 'GET',
  url: '/register/states-json/',
  success: function(response){
    const states_data = response.data
    states_data.map(item=>{
      const option = document.createElement('div')
      option.textContent = item.name
      option.setAttribute('class', 'item')
      option.setAttribute('data_value', item.name)
      statesDataBox.appendChild(option)
    })
  },
  error: function(error){
    console.log(error)
  }
})

Can I use a function js file and add it into react? Look at the files to understand a bit more on what I mean. Thanks in advance:)

So this is the javascript file loading a map. However in the react application google, map, infoWindow, ... all show up as undefined. Is there something I am doing wrong? Please let me know.

scripts.js. The point of this file is just showing a google map based on whether a search button is clicked. Otherwise, if a chat button is clicked, it shows a chat window.

    function initMap() {
      map = new google.maps.Map(document.getElementById("map"), {
        center: { lat: -34.397, lng: 150.644 },
        zoom: 15,
        mapId: 'myid'
      });
      infoWindow = new google.maps.InfoWindow();
      const geocoder = new google.maps.Geocoder();
      function fetchLocationName(lat, lng) {
          var latlng = new google.maps.LatLng(lat, lng);
          // This is making the Geocode request
          var geocoder = new google.maps.Geocoder();
          geocoder.geocode({ 'latLng': latlng }, function (results, status) {
              if (status !== google.maps.GeocoderStatus.OK) {
                  alert(status);
              }
              // This is checking to see if the Geoeode Status is OK before proceeding
              if (status == google.maps.GeocoderStatus.OK) {
                  //console.log(results[0].formatted_address);
                  var address = (results[0].formatted_address);
                  infoWindow.setContent(address);
                  return address
                  
              }
          });
      }
        
        const locationButton = document.createElement("button");

        
        locationButton.textContent = "Pan to Current Location";
        locationButton.classList.add("custom-map-control-button");
        map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton);
        locationButton.addEventListener("click", () => {
          // Try HTML5 geolocation.
          if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
              (position) => {
                const pos = {
                  lat: position.coords.latitude,
                  lng: position.coords.longitude,
                };

                
               fetchLocationName(pos.lat,pos.lng)
              
              const marker=new google.maps.Marker({
      
                  position: pos,
                  map,
                  title: "Location",
                });
                marker.addListener("click", () => {
                  infoWindow.open({
                    anchor: marker,
                    map,
                    shouldFocus: false,
                  });
                });
                infoWindow.open(map);
                map.setCenter(pos);
                
              },
              () => {
                handleLocationError(true, infoWindow, map.getCenter());
              }
            );
          } else {
            // Browser doesn't support Geolocation
            handleLocationError(false, infoWindow, map.getCenter());
          }
        });
      
        function handleLocationError(browserHasGeolocation, infoWindow, pos) {
          infoWindow.setPosition(pos);
          infoWindow.setContent(
            browserHasGeolocation
              ? "Error: The Geolocation service failed."
              : "Error: Your browser doesn't support geolocation."
          );
        }

          
        
       
       
     
        
      }
      
    
     
<!DOCTYPE html>
<!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]>      <html class="no-js"> <!--<![endif]-->
<html>
    <head>
        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Map for Mental Health Services</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="style.css">
    </head>
    <body>
        <h1> Map</h1>
        <div id="map"></div>
        <!--[if lt IE 7]>
            <p class="browsehappy">You are using an <strong>outdated</strong> browser. Please <a href="#">upgrade your browser</a> to improve your experience.</p>
        <![endif]-->
        
        <script src="scripts.js"></script>
        <script src="https://maps.googleapis.com/maps/api/js?key=key&map_ids=id&callback=initMap"></script>
        
    </body>
</html>
This is the main js file using the rfce template which React detects. I read somewhere Helmet allows you to add script files. Its not really working as google,initmap and so on are undefined. This is where the buttons are clicked to either show the google map or chat.

Res.js

import React from 'react'
import { useState } from "react";
import ReactDOM from "react-dom/client";
import {Routes, Route, useNavigate} from 'react-router-dom';
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';
import {Button} from '@material-ui/core'
import { auth } from '../firebase.js'
import Signin from './Signin';
import Signout from './Signout';
import {useAuthState} from 'react-firebase-hooks/auth'
import Chat from './Chat'
import App from '../App'
import Services from './Services.js';

import {Helmet} from "react-helmet";

function Res() {  
    
      
const [count, setRandomCount] = useState(false);
const [count2, setRandomCount2] = useState(false);
function clickHandler(e) {
  setRandomCount(true);

}
function clickHandler2(e) {
    setRandomCount2(true);
  
  }
 
  return (
    
    <div>
      
      {count? <h1>Start your chat below</h1>:<></>}
      {count || count2 ? <></>:<h1>Select an option</h1>}
      <p>
      {count ? <Chat/>:<h1></h1> }
      </p>
      <p>
      {count2 ? <Helmet>
    <script src="./scripts.js" type="text/javascript" />
</Helmet>:<h1></h1> }
      </p>
      <p>
    {count || count2? <h1></h1>:<button onClick={clickHandler}> Chat </button>}
    </p>
    <p>
    {count2 || count? <h1></h1>:<button onClick={clickHandler2}> Services nearby </button>}
      </p>
      
    </div>


  );

  
}


// const root = ReactDOM.createRoot(document.getElementById('root')); 

// root.render(<Res count={false} />);
// root.render(<Chat count={true} />);
export default Res

How can I use this separately functional js file (its own index.html and style.css files) and add it in this react application? I’m a newbie to React so anything would be really helpful!

I have been running into this error: Uncaught TypeError: Cannot read properties of undefined (reading ‘bind’)

//I am running into this issue after I used the v9 of firebase, the page will not render at all and I’ve been stuck on this for awhile and have tried 21 different imports I’ve found and none of them work. The code is show below along with the work arounds.

// import * as firebase from 'firebase'; //work around
// import firebase from 'firebase/compat/app'; //work around (works?)
// import 'firebase/compat/auth'; //work around 
// import 'firebase/firestore'; //work around 
// import 'firebase/firestore'; //work around
// import { initializeApp } from 'firebase/app'; //work around
// import { initializeApp } from 'firebase/app';
// import firebase from '@firebase/app'; //work around 
// require('firebase/auth'); //work around
// import firebase from 'firebase/app'; //work around
// import 'firebase/auth'; //work around 
// console.log(firebase.auth); //word around
// import firebase from 'firebase/app';
// import 'firebase/firestore'; //work around
// import 'firebase/auth';  //work around
// import {initializeApp} from 'firebase/app'; //work around 
// import {getFirestore, collection, getDocs} from 'firebase/firestore/lite'; //work around 
// import {getAuth} from 'firebase/auth'; //work around 
// import firebase from 'firebase/compat/app'; // work around 
// import 'firebase/compat/auth'; // work around 
// import 'firebase/compat/firestore'; // work around 
import firebase from 'firebase/compat/app';
import 'firebase/compat/auth';
import 'firebase/compat/firestore';


const firebaseConfig = {
    apiKey: "AIzaSyBYZCeQfHboP-zEDyNGyMODEfx33RiQmTg",
    authDomain: "graphqlmernstack.firebaseapp.com",
    projectId: "graphqlmernstack",
    storageBucket: "graphqlmernstack.appspot.com",
    // messagingSenderId: "165123567996",
    appId: "1:165123567996:web:6c808a04288956d188f4f9",
    measurementId: "G-6G4BVK9FQZ"
  };

  // Initialize Firebase
firebase.initializeApp(firebaseConfig); 
// const app = initializeApp(firebaseConfig); //work around
// const firebase = initializeApp(firebaseConfig); //work around 
// const db = getFirestore(firebase); //work around 
// const auth = getAuth(firebase); //work around

// const analytics = getAnalytics(app);


// console.log(auth);
export const auth = firebase.auth();
export const googleAuthProvider = new firebase.auth.GoogleAuthProvider();

//the last three imports are what I am currently using. Thank you for the help.

Can’t Pass HTML Markup Through AJAX to PHP

I have my html form sending data through AJAX to PHP. the form data contains a little HTML markup which I want to send to my PHP server.

My Form data is set up like so:

<form id="mail-formData">
    <input type="hidden" name="a" value="send-custom-mail">
    <input type="hidden" name="uid" id="cm-uid">
    <input type="text" class="form-control" id="cm-email2" name="to">
    <input type="text" class="form-control" name="message-subject" required>
    <textarea class="form-control" name="message-body" required</textarea>
    <button type="submit" class="btn btn-lg btn-primary sendMail">SEND MAIL</button>
</form>

NOTE: the content in my message-body contains markups like <b></b> and most especially <div style="">

My AJAX i well set up like so:

$.ajax({
    url: "send-mail.php",
    type: "POST",
    data: $("#mail-formData").serialize(),
    cache: false,
    success:function(response){
        console.log(response);
    }
});

and my send-mail.php is set up like so:

 if (isset($_POST['a'])&&$_POST['a']=='send-custom-mail') {
     die(var_dump($_POST));
 }

NOW,

  1. When I send this request without the html markups in it, it works flawlessly

  2. when I send with html markups like witouth the style=”” it works.

BUT

Once I introduce style=”color:red” it doesn’t work. the form submits quite fine but I’m guessing without the data in serialize();

how to fix Uncaught TypeError: Cannot read properties of null (reading ‘style) javascript [duplicate]

When I run this html (js) snippet:

<script>
const imgPosition = document.querySelectorAll(".aspect-ratio-169 img")
const imgContainer = document.querySelector('.aspect-ratio-ratio-169')
let imgNuber = imgPosition.length
let index = 0
// console.log(imgPosition)
imgPosition.forEach(function(image,index){
    image.style.left = index*100 + "%"
})
function imgSlide (){
    index++;
    console.log(index)
    if (index>=imgNuber) {index=0}
    imgContainer.style.left = index*100 + "%"
    //= "-" +index*100+ "%"

}

setInterval(imgSlide,5000)

</script>

Here is my section code:

<section id="Slide">
    <div class="aspect-ratio-169">
        <img src="slide 1.jpeg" alt="Hình ảnh 1">
        <img src="slide 1.jpeg" alt="Hình ảnh 2">
        <img src="slide 1.jpeg" alt="Hình ảnh 3">
        <img src="slide 1.jpeg" alt="Hình ảnh 4">
        <img src="slide 1.jpeg" alt="Hình ảnh 5">
    </div>
</section>

then I get the error: Uncaught TypeError: Cannot read properties of null (reading ‘style’)
at imgSlide ((index):84:18)
imgSlide @ (index):84
setInterval (async)
(anonymous) @ (index):89

Although I have read a few articles on google, I still can’t fix this code. Can someone help me?

Cannot read properties of undefined (reading ‘location’) while using the below JavaScript

I am getting error Cannot read properties of undefined (reading 'location')

<frame src='" & ServerURLBase & "/Ec/Priorities.asp?" & CleanQueryString(Request.ServerVariables( "QUERY_STRING" )) & "' name='SelectFrame' />" & vbcrlf _

ClientScript.RegisterStartupScript(GetType(), "Load", "<script type='text/javascript'>parent.SelectFrame.location.reload();</script>");