Can you use the activeElement property to see if an element with a specific class name has focus?

Im trying to get the Boolean true if elements with a certain class name are focused on. But it seems Document.activeElement only works with either ID or Tag name, which wont help since they’re elements of the same type. Heres the situation:



   var test2 = document.getElementsByClassName('test2')
   var test3 = document.getElementsByClassName('test3')

   test3[1].focus()

   isFocused2 = (document.activeElement === test2)
   isFocused3 = (document.activeElement === test3)

   document.getElementById('test').innerHTML = isFocused3

<!-- language: lang-html -->

       <input type="text" class="test2" >
       <input type="text" class="test3" >
       <input type="text" class="test2" >
       <input type="text" class="test3" >
       
        <div  id="test"></div>

<!-- end snippet -->

How to prevent from force restarting when saving file without modifications in VS Code?

I have index.js. I run it with Nodemon on WebStorm in Integrated terminal. When I press command + s shortcut if the file not modified, the Nodemon does not restart. If the file modified, it will restart. So, when I use VS Code and run index.js with nodemon, When I press command + s without file modifying, nodemon restarts. How can I prevent force saving if file not modified on Vscode.

I want WebStorm like feature for smart saving file.

Calculate difference between two times on Qualtrics

Respondents record a start time (time to bed) and and end time (time out of bed) in separate questions using flatpickr’s time picker. The responses are recorded in the format, for example, 11:00 PM and 8:00 AM, for start time and end time respectively.

I need to calculate time in bed = (time out of bed – time to bed) in minutes. I have attempted to do so with moment.js but have not been successful. Any help would be appreciated.

First, I am unsure if I have properly loaded the moment.js library. To do so, I included in the Look & Feel Header:

<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>

To calculate time in bed, I attempted the following:

    Qualtrics.SurveyEngine.addOnload(function() {

      // Function to calculate and store the time in bed
      function calculateTimeInBed() {
        var timeToBedStr = "${q://QID4/ChoiceTextEntryValue}";
        var timeOutOfBedStr = "${q://QID12/ChoiceTextEntryValue}";

        // Parse the time strings using Moment.js
        var timeToBed = moment(timeToBedStr, 'h:mm A');
        var timeOutOfBed = moment(timeOutOfBedStr, 'h:mm A');

        // Adjust timeOutOfBed if it is on the next day
        if (timeOutOfBed.isBefore(timeToBed)) {
          timeOutOfBed.add(1, 'day');
        }

        // Calculate duration using Moment.js
        var duration = moment.duration(timeOutOfBed.diff(timeToBed));
        var timeInBedMinutes = duration.asMinutes();

        // Store time in bed as an embedded data field
        Qualtrics.SurveyEngine.setEmbeddedData('timeInBed', timeInBedMinutes);
      }

      // Call the calculateTimeInBed function when the page unloads
      Qualtrics.SurveyEngine.addOnUnload(function() {
        calculateTimeInBed();
      });
    });

Error: Reading rich text fields is not supported pdf-lib

I am working on nextjs project where i have to write some text in fields in pdf placed on server. Whenever i try to right and save the document. it gives error

Uncaught (in promise) Error: Reading rich text fields is not supported: Attempted to read rich text field: Summary of care provided

I am using pdf-lib library to achieve this thing but facing this error.
See Error Here

The Code I am using to get this done

import { degrees, PDFDocument, rgb, StandardFonts } from "pdf-lib";
export default async function () {
  // Fetch an existing PDF document
  let response = await fetch(
    "https://url/application.pdf"
  );
  let bytes = await response.arrayBuffer();

  // Load a PDFDocument from the existing PDF bytes
  const pdfDoc = await PDFDocument.load(bytes);

  const form = pdfDoc.getForm();

  const textField = form.getTextField("City");

  textField.setText("One Punch Man");
  textField.enableReadOnly();
  // Serialize the PDFDocument to bytes (a Uint8Array)
  const pdfBytes = await pdfDoc.save();

  // Trigger the browser to download the PDF document
  const urlChan = window.URL.createObjectURL(
    new Blob([pdfBytes], { type: "application/pdf" })
  );
  window.open(urlChan);
}

Here we have this field in page no 8 of pdf

See here

I tried multiple methods given by pdf-lib but nothing worked.

How can I make my dropdown disappear again using an if statement with css values as the condition?

The if statement isn’t working as it should. I have put a css value as the condition . However, there seems to be something wrong with the if statement’s condition as my clicking “document” is not having the desired effect of executing “dontGetIt” function and thus making the dropdown display as “none”.

HTML:

<div class="navs" id="menu">
            <p>MENU</p>
            <ul id="dropdown">
                <li><a href="index.html">HOME</a></li>
                <li><a href="blog.html">BLOG</a></li>
                <li><a href="books.html">BOOKS</a></li>
                <li><a href="about.html">ABOUT</a></li>
                <li><a href="contact.html">CONTACT</a></li>
            </ul>
        </div>

CSS:

.block {
    display: block !important;
}

#dropdown {
    display: none;
    border: 1px solid black;
    background: rgb(29, 18, 80);
    width: 6vw;
    list-style: none;
    text-align: left;
}

Javascript:

const menu = document.getElementById("menu");
const dropdown = document.getElementById("dropdown");

const getIt = () => {
    dropdown.classList.add("block");
}

const dontGetIt = () => {
    dropdown.classList.remove("block");
}

menu.onclick = getIt;

if (dropdown.style.display === "block") {
    alert("apple");
    dontGetIt;
}

else {
    alert("orange");
}

I want the dropdown to disappear again after I click the “document” (anywhere) once the dropdown appears after I click “menu”. However, even though clicking the menu turns the dropdown display to “block” in css, once I click the “document” again so the if statement can execute and the block display turns back to “none”, this doesn’t happen.

For some reason the if statement’s condtion in () is only detecting “dropdown.style.display” if I apply it in javascript, but not if I do it through CSS.

How to create a Splash screen without a package in android

I am facing problem while using the package of Splash Screen, Is there any other way I can set up a splash screen without the help of a package (in android)
reference: https://github.com/crazycodeboy/react-native-splash-screen

I tried all the possible methods listed in the repo, but still failed to do so either the package is too old now (version upgrade) or maybe some human error at my end.

Render and pass/specify dynamic field in JSX

I have a field object created at runtime (via API call) as below

field : {
    "firstNameField-0":  {id: 'firstNameField', mandatory: true, value: 'First Name 1'}
}

The index i.e. 0 above is dynamic, but at a time, only one value is possible for the index and I have this value in a state variable “index”…So, basically the field names are of the format “firstNameField-${index}”

I want to pass this field object/configuration to my JSX. So, looking at something like

{
field.firstNameField &&
    <MyField key={field.firstNameField.id} field={field.firstNameField} />
}

Is it possible to specify and render with this dynamic index in the JSX itself ?

I was trying something like below, but it is throwing syntax error;

<MyField key={field.[`firstNameField-${index}`].id} field={field.[`firstNameField-${index}`]}  />

Is there a way to make a drop down appear after clicking on a photo using javascript? [duplicate]

I am making a website where if someone clicks on my photo in a div, the photo travels to the top of the screen, and a new screen appears of full screen width, with all my information, and everything in the background blurs, and clicking again on the photo closes this taking the photo back to the way it was on the main page. All on the same page, no redirecting to another page.

In javascript, how to rename few properties of a huge object

I have an object with 120+ fields, and I am looking for a way to transform the object into a new object.

The new object is mostly identical to the original, except few fields are renamed and few fields are converted to Date object from milliseconds time.

Original Object:
type: Record<string, unknown>
Sample Value:

{
  "id":12,
  ...
  "created_at":1577999390226497 // Time in milliseconds
}

New Object
type: Custom Object

export class NewDto {
  client_id: number;
  ...
  client_created_at: Date;
  
}

I tried using slicing but it’s not working. Sample code:

  const newObject = {
    ...originalObject,
    id: client_id,
    created_at: convertToDate(created_at)
  } as NewDto;

How to create a sound fadeout effect with SpeechSynthesis API?

I’m trying to create a fadeout for the current SpeechSynthesis text being spoken(i.e. gradually decrement the volume until it is 0), and after that it should stop playing(once volume reaches 0) and start the next SpeechSynthesis text spoken that is in the queue. However, it seems as if the volume does indeed decrement while the text is being spoken(i tested it with the console log statements) but in reality the volume is the same(what I hear). Only for the next text is the volume 0(which I plan on changing back to 1 once I fixed this issue).

import React, { useEffect, useState } from "react";
import VoiceMessages from "./messages";
const VoiceAssistantProvider = ({ children }) => {
  // [public, private]
  const [isUsable, setIsUsable] = useState(false);
  // [public, private]
  const [isSpeaking, setIsSpeaking] = useState(false);
  // [public, public]
  const [isActive, setIsActive] = useState(false);
  // [private, private]
  const [voice, setVoice] = useState(null);
  // [public, private]
  const [voiceAssistant, setVoiceAssistant] = useState(null);

  // [private, private]
  const [fadeoutTime, setFadeoutTime] = useState(2000);
  // [private, private]
  const [startFadeout, setStartFadeout] = useState(false);

  // Handle voices once loaded
  const handleVoicesLoaded = () => {
    const voices = speechSynthesis.getVoices();
    setVoice(voices[2]);
  };

  // Once voice is set up and voiceAssistant is set up as well, set the voice
  useEffect(() => {
    if (voice && voiceAssistant) {
      voiceAssistant.voice = voice;
    }
  }, [voiceAssistant, voice]);

  // Run once to set up voiceAssistant
  useEffect(() => {
    if ("speechSynthesis" in window) {
      setIsUsable(true);
      setVoiceAssistant(new SpeechSynthesisUtterance());
      window.speechSynthesis.onvoiceschanged = handleVoicesLoaded;
    }
  }, []);

  // Start the fadeout
  useEffect(() => {
    if (startFadeout) {
      var volumeTimeout;
      const step = (voiceAssistant.volume * 100) / fadeoutTime;

      const fadeStep = () => {
        console.log(`Inside step`);
        voiceAssistant.volume -= step;
        console.log("Volume is: ", voiceAssistant.volume);
        if (voiceAssistant.volume > 0) {
          volumeTimeout = setTimeout(fadeStep, 100);
        } else {
          speechSynthesis.cancel();
          setIsSpeaking(false);
          setStartFadeout(false);
        }
      };
      fadeStep();
      return () => clearTimeout(volumeTimeout);
    }
  }, [startFadeout]);

  // Handle isActive change
  useEffect(() => {
    if (isSpeaking) {
      setStartFadeout(true);
    }
    if (isActive) {
      voiceAssistant.text = VoiceMessages.InitializeVoiceAssistant;
      speechSynthesis.speak(voiceAssistant);
      setIsSpeaking(true);
    } else if (!isActive && isUsable) {
      voiceAssistant.text = VoiceMessages.StopVoiceAssistant;
      speechSynthesis.speak(voiceAssistant);
      setIsSpeaking(true);
    }
  }, [isActive]);

  // Add event listener for voiceAssistant for the end of message.
  useEffect(() => {
    const handleEnd = () => {
      setIsSpeaking(false);
    };

    if (voiceAssistant) {
      voiceAssistant.addEventListener("end", handleEnd);
      return () => {
        voiceAssistant.removeEventListener("end", handleEnd);
      };
    }
  }, [voiceAssistant]);

  useEffect(() => {
    setVoiceAI({
      voiceAssistant,
      isUsable,
      isSpeaking,
      isActive,
      voice,
      setIsActive,
    });
  }, [voiceAssistant, isUsable, isSpeaking, isActive, voice]);

  const [voiceAI, setVoiceAI] = useState({
    voiceAssistant,
    isUsable,
    isSpeaking,
    isActive,
    voice,
    setIsActive,
  });

  const wrappedChildren = React.Children.map(children, (child) => {
    return React.cloneElement(child, { voiceAI });
  });

  return <>{wrappedChildren}</>;
};

export default VoiceAssistantProvider;

How can I dynamically add Events to this jQuery Timeline plug in”

I am trying to modify this jQuery plug in:

So that I can dynamically add events to the timeline, using input fields.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>jQuery Timespace Plugin Examples</title>        
                
        <link href="css/jquery.timespace.dark.css" rel="stylesheet">
        
    <style>
        body {background:#262727;}
        a {color: #8baac0;}     
        </style>
</head>

<body text="white">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="jquery.timespace.js"></script>
 
 <br>
 
 <label for="Estart">Start Time</label>
  <input type="text" id="Estart" name="Estart" value="26">
  <br><br>
  
  <label for="Eend">End Time</label>
  <input type="text" id="Eend" name="Eend" value="30">
  <br><br>
  
  <label for="Etitle">Title</label>
  <input type="text" id="Etitle" name="Etitle" value="Event 4">
  <br><br>
  
  <label for="Edescription">Description</label>
  <input type="text" id="Edescription" name="Edescription" value="New Event number 4">
  <br><br>
  
  <button id = "addNew">Add New Event</button>    
  <br><br>
    
  <div id="timeline"> </div> 
    
<script>
    $(function () {
        
          $('#timeline').timespace({
          
            timeType: 'date',
            useTimeSuffix: false,           
            startTime: 0,
            endTime: 1900,
            markerIncrement: 1, // the amount of time between each marker
            selectedEvent: 0, // selected event 0 for first event, -1 to disable            
            markerAmount: 0, // the amount of time markers to use 0 to auto calculate            
            maxWidth: 1000, // max width in pixels
            maxHeight: 280, // max height in pixels            
            markerWidth: 72, // width of marker
            shiftOnEventSelect: true, // if the time table should shift when an event is selected            
            navigateAmount: 200, // the amount of pixels to move the Timespace     
            scrollToDisplayBox: true, // scroll to the event display box on event selection
            customEventDisplay: null, // jQuery object to use for the event display box
            
              controlText: {   
                               navLeft: 'Move Left',
                               navRight: 'Move Right',
                               drag: 'Drag',
                               eventLeft: 'Previous Event',
                               eventRight: 'Next Event',
                           },
                        
                        
        data: {
                      headings: [{start: 0, end: 1900, title: 'Event Time Line'},],
                      
            events: [                   
              {start: 4.3, end:20.5 , title: 'Event 1', description: 'Event number 1 text.'},
                          {start: 19, end: 25, title: 'Event 2', description: 'Event number 2 text.'},
                          {start: 21, end: 24, title: 'Event 3', description: 'Event number 3 text.'},
                                ],
          },                  
         },              
             
       function () {
                      // Set the navigation Seed
                      //this.navigateAmount = 100;
                   });                    
                   
    });
</script>

</body>
</html>

The only way I could get it to work was to add this the jQuery js script:

$("#addNew").on('click', () =>{

   let newItem = {
     start: $("#Estart").val(), end: $("#Eend").val(), title: ("#Etitle").val(),
      description: $("#Edescription").val()
       };
                    
       this.data.events.push(newItem);

         this.buildTimeEvents();
         this.buildTimeDisplay();
         this.updateStaticData();
         this.updateDynamicData();
         this.setDOMEvents();
                    
          alert("added");
    }),  

This adds the new event fine, but it also duplicates the events that are already there, so I end up with 2 of every event, except for the new event added.

I need a way to only add the new event, but I can’t figure it out.

I also want to be able to save the events array (ex: saved events list 1, saved events list 2, and so on), then be able to load any saved events from previously saved arrays.

Any help or suggestions would be greatly appreciated.

Thanks.

it is a write or wrong [closed]

long – standing issue in react ?

i’m stuck . i want to know what is long -standing issue ? is it similar to lazy loading . it is statement correct — We build large-scale apps using React. When building these apps, the major issue we face is app performance. When the app grows larger and larger, the performance might deteriorate. Particularly the initial loading time of the app will be affected more. Initial app loading needs to be fast without showing a blank screen for few seconds to the user. As taking more time to load will create a bad impression for the user.

How to fix ENOTFOUND error when running Mineflayer Minecraft bot in Python?

Minecraft bot mineflayer not working python

` from javascript import require, Once, once

mineflayer = require("mineflayer")

random_number = id([]) % 1000  
BOT_USERNAME = f'colab_{random_number}'

bot = mineflayer.createBot({
    'host': 'true host',  
    'port': "true port",  
    'username': 'ggBot',
    'hideErrors': False
})

# autorizstion
once(bot, 'login')
bot.chat('I spawned')`

but error:


Error: getaddrinfo ENOTFOUND timamozg.aternos.me:44286
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:107:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'tima.aternos.me:44286'
}

Process finished with exit code 0

port and host are correct

in general, this library was originally made for javascript, but it can also be used in python using javascript import