Trouble accessing nested child element using querySelector in JavaScript

I’m encountering an issue with the querySelector method in JavaScript, specifically when attempting to access nested child elements. I have a selected element, and my goal is to retrieve the first child of the selected element and then obtain the first child of that inner element.

I’ve tried the following code:

let selected = document.querySelector(".main-box")
var desiredElement = selected.querySelector("div:nth-child(1) > div:nth-child(1)");

However, this seems to produce the same result as:

var desiredElement = selected.querySelector("div:nth-child(1)");

It appears that the second part of the selector (> div:nth-child(1)) is not behaving as expected.

My HTML structure is as follows:

<div class="main-box">
    <div>
        <div>Target Element</div>
        <div></div>
        <div></div>
    </div>
    <div>
        <div></div>
        <div></div>
        <div></div>
    </div>
    <div>
         <div></div>
         <div></div>
         <div></div>
    </div>
</div>

but it works fine when i use this code

var desiredElement = document.querySelector(".main-box > div:nth-child(1) > div:nth-child(1)")

then why this code is not working

let selected = document.querySelector(".main-box")
var desiredElement = selected.querySelector("div:nth-child(1) > div:nth-child(1)");

Align different images into a circle with fade in or slide in animation. Visual Explanation below

I am trying to make a circle with html css and javascript, where my main task is to combine multiple images just like pizza slices. Visual – Think of whole pizza cut into slices and all pulled out one by one but i want to do in reverse order. The final image should look like this–> Image

But the animation i want is like this–> animate image
In animation i need is a small delay in images to slide in. It would be great if anyone could help
Thank you in advance

I tried but the code is not working as i want it to work.

Why does using Date.now() in condition create an infinite loop?

I wanted to create a loop that could simulate a 5 second delay but ended up creating an infinite loop. I don’t get why that works this way.

let a = Date.now() + 5000;
while(Date.now() < a) {
    console.log(1);
}

What is wrong? a is a fixed value and isn’t Date.now() supposed to get changed after every iteration?

I’m also wondering why setTimeout still works when the loop is infnite? Isn’t it supposed to get executed only after the currently executing script is complete? Since this script is never complete why does setTimeout still get invoked?

setTimeout(() => {
    alert(2);
}, 2000);
let a = Date.now() + 5000;
while( Date.now() < a ) {
    console.log(1)
}

How to fix the wrong minification on constants declaration with Uglify v.^3.17.4?

The code I have:


export function SomeComponent({captions}: {captions?: string[]}) {
  const {firstConst, secondConst, thirdConst} = someVariable

  const text = captions && captions[firstConst]
  const max = secondConst - thirdConst
  const digits = Math.max(2, String(max + 1).length)
  //...more codes
}

However, when I try to minify, the code came out as:

function SomeComponent({
    captions: e
}) {
    var {
        index: r,
        total: o,
        visible: a
    } = t, e = e && e[r], o = o - a, a = Math.max(2, String(1 + o).length);
    // ...more code
}

As you can see, I’ll get error on e = e && e[r], o = o - a and a = Math.max(2, String(1 + o).length). The error message is:

Identifier 'e' has already been declared (14:48)

and so on…

The current uglify setting is just on default (with no custom settings)

UglifyJS.minify(code)

Superset: Not able to show more info in the chart

I’m using a superset and using the library deck.gl.scatterplot to represent the data but in the chart I want to show more info about the pointsMap

So I got to know about the javascript tooltip generator where I’m using this code

d => "<div>field: <strong> ${d.object.props.City}</strong></div>"

to represent the city but I’m not able to use the city name. I’ve also added extra data for JS which it ask for just before this but still

how do i fix this? also I’m trying to find some documentation on it which can help me understand this better

Bootstrap modal not working in Angular application

I am trying to use a Bootstrap modal in an Angular application using classes in HTML, but it not working.

<div class="modal text-center" *ngIf="showmodal" tabindex="-1" id="withScrollExampleModal">
  <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title fw-normal">Basic dialogue title</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close">
          <i class="fa-light fa-circle-xmark"></i>
        </button>
      </div>
      <div class="modal-body f-14">
        <p>Lorem ipsum dolor sit amet consectetur. Enim libero commodo nibh vitae sed laoreet magna dui pharetra.
        </p>
      </div>
      <div class="modal-footer d-flex justify-content-center">
        <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">Action 1</button>
        <button type="button" class="btn btn-outline-primary rounded-pill">Action 2</button>
      </div>
    </div>
  </div>
</div>

Capturing a screenshot of a React ApexCharts component using use-screenshot-hook

I’m trying to capture a screenshot of a React ApexCharts component in my React application using the use-screenshot-hook library. Here’s the relevant code:

import React, { useState, useCallback } from 'react';
import Chart from 'react-apexcharts';
import { useScreenshot } from 'use-screenshot-hook';

const App = () => {
  const [chartData, setChartData] = useState({
    options: {
      chart: {
        id: 'apexchart-example'
      },
      xaxis: {
        categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999]
      }
    },
    series: [{
      name: 'series-1',
      data: [30, 40, 35, 50, 49, 60, 70, 91, 125]
    }]
  });

  const { takeScreenshot } = useScreenshot();

  const handleCaptureScreenshot = useCallback(async () => {
    const screenshot = await takeScreenshot();
    // Handle the screenshot, e.g., save it or display it
    console.log('Screenshot captured:', screenshot);
  }, [takeScreenshot]);

  return (
    <div>
      <Chart options={chartData.options} series={chartData.series} type="bar" width={500} height={320} />
      <button onClick={handleCaptureScreenshot}>Capture Screenshot</button>
    </div>
  );
};

export default App;

However, it seems that the screenshot is not being captured as expected. I’ve checked the documentation for use-screenshot-hook, but I might be missing something. Could someone please guide me on how to properly use use-screenshot-hook with React ApexCharts or suggest an alternative approach to capture screenshots of specific React components?

Javascript trying to replace all lines after a found string of text

Ive searched around and cannot find anything to help me, I was hoping for some help.

The javascript searches a body of text and finds a phrase then should grab all text after it finds it.

Works great on single line strings but not on multiple lines 🙁

 // Check if the array item contains the Components affected.
        if (text[i].includes('Components affected')) {
            // If it does, store the Components affected by removing the label.
            var requestorName = text[i].replace('Components affected', '')

            // Put the Components affected into the correct field and remove and whitespace.
            document.getElementById('requestorname').value = requestorName.trim()

Body of text :

Ideally the search would stop when an empty line was found

paragraph of text here….

**> Components affected

red
blue
black
purple
green

more text here……………**

Whoop API Error when trying to login with passport and OAuth 2.0

Hi I’m trying to make a log in using whoop api, currently they use passport and OAuth2.0, but it seems that it gaves me an error when i do the passport.authenticate in the callback endpoint.
This is my User.js routes

const express = require('express')
const app = express()
const passport = require('passport')
const OAuth2Strategy = require('passport-oauth2')
const User = require('../Models/User')
require('dotenv').config()

const whoopOAuthConfig = {
    authorizationURL: `${process.env.WHOOP_API_HOSTNAME}/oauth/oauth2/auth`,
    tokenURL: `${process.env.WHOOP_API_HOSTNAME}/oauth/oauth2/token`,
    clientID: process.env.CLIENT_ID,
    clientSecret: process.env.CLIENT_SECRET,
    callbackURL: process.env.CALLBACK_URL,
    state: true,
    scope: [
        'offline',
        'read:profile',
        'read:recovery',
        'read:cycles',
        'read:sleep',
        'read:workout',
        'read:body_measurement'
    ],
}

async function  getUser(
    accessToken,
    refreshToken,
    {expires_in},
    profile,
    done,
){
    console.log(profile)
    const {first_name, last_name, user_id} = profile

    const user = await User.findOne({userId: user_id})

    if (user) {
        user.acessToken = accessToken
        user.refreshToken = refreshToken
        user.expiresIn = Date.now() + expires_in * 1000
        user.firstName = first_name
        user.lastName = last_name
        user.userId = user_id

        await user.save()

        done(err, user)
    } else{
        const newUser = new User({
            acessToken: accessToken,
            refreshToken: refreshToken,
            expiresIn: Date.now() + expires_in * 1000,
            firstName: first_name,
            lastName: last_name,
            userId: user_id,
        })

        done(err, newUser)
    }
}

async function fetchProfile(
    accessToken,
    done,
){
    console.log(accessToken)
    const profileResponse = await fetch(
        `${process.env.WHOOP_API_HOSTNAME}/developer/v1/user/profile/basic`,
        {
            headers: {
                Authorization: `Bearer ${accessToken}`,
            },
        },
    )

    const profile = await profileResponse.json()

    done(err, profile)
}

const whoopAuthorizationStrategy = new OAuth2Strategy(whoopOAuthConfig, getUser)
whoopAuthorizationStrategy.userProfile = fetchProfile

passport.use('oauth2', whoopAuthorizationStrategy)

var printSometing = function(req, res, next) {
    console.log("I'm still here");
    return next();
}

app.get('/auth/performance',
    passport.authenticate('oauth2'));



app.get('/auth/performance/callback',
    passport.authenticate('oauth2', {failureRedirect: '/', failureMessage: true }),
printSometing, function (req, res) {
    res.redirect('http://localhost:3000/');
});



module.exports = app;

And this is my index.js

const express = require('express')
const app = express()
const port = 8081
const cors = require('cors')
const session = require('express-session')
const mongoose = require('mongoose')
require('dotenv').config()
var bodyParser = require( 'body-parser' );
const passport = require('passport')


mongoose.connect(process.env.MONGO_URI)
const database = mongoose.connection;

database.on('error', console.error.bind(console, 'connection error:'));

database.once('connected', function() {
  console.log("Connected to MongoDB")
});


app.get('/', (req, res) => {
  res.send({msg: 'Hello World!'})
})

app.use(session({secret: process.env.CLIENT_SECRET, resave: true, saveUninitialized: true}))
app.use(express.urlencoded({ extended: false }));
app.use(bodyParser.json({ limit: '10mb' }));
app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
app.use(passport.initialize());
app.use(passport.session());
app.use(cors());

app.use('/api', require('./routes/user.js'));

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

I’ve followed the Whoop’s API documentation and it didn’t work, tried to change the secret and api keys and online reasearch.

Pointermove event not returning element index on touch

I’m trying to let users change some dot colours on a d3.js SVG chart.

It seems current element index is not being updated continuously in the pointermove event function on touch while for example cursor coordinates are.

I’ve used touch-action on the chart as advised elsewhere. I’ve tried many different options but none seem to work and I’ve run out of ideas.

The only thing I’m uncertain of is how I’m updating the function — maybe there’s some proper way to do it?

I’m testing on iOS Safari.

let col = "#000000";

const num = 60;

let LEDs = Array(num).fill(col);

const index = d3.local();

const width = 600;
const height = 600;
const r = Math.min(width, height) / 2.5;
const cr = (r * Math.PI) / num - 4;

const pie = d3.pie().value(1);
const arc = d3.arc()
  .innerRadius(0)
  .outerRadius(r * 2);

const svg = d3.create("svg")
  .attr("width", "100%")
  .attr("height", "100%")
  .attr("viewBox", [0, 0, width, height])
  .attr('preserveAspectRatio', 'xMidYMid meet');

const touchGroup = svg.append("g")
  .attr("transform", `translate(${width / 2}, ${height / 2})`)
  .attr("id", "touch-group");
const circleGroup = svg.append("g")
  .attr("transform", `translate(${width / 2}, ${height / 2})`)
  .attr("id", "circle-group");

// LEDs
function updateLEDs() {
  touchGroup.selectAll("path")
    .data(pie(LEDs))
    .enter()
    .append("path")
    .attr("d", arc)
    .each(function(d, i) {
      index.set(this, i);
    })
    .on("touchstart", function(event) {
      event.preventDefault();
    })
    .on("pointermove", touched);

  const circleNodes = circleGroup
    .selectAll("circle")
    .data(LEDs)
    .join("circle")
    .attr("fill", d => d)
    .attr("cx", (d, i) => r * Math.cos((2 * Math.PI * i) / num - Math.PI / 2))
    .attr("cy", (d, i) => r * Math.sin((2 * Math.PI * i) / num - Math.PI / 2))
    .attr("r", cr);

  function touched(event, d) {
    const i = d3.select(this).datum().index;
    let j = index.get(this);
    const a = [event.clientX, event.clientY];
    const p = event.pointerType;
    if (event.buttons === 1) {
      d3.select("#info").text("LED " + i + "/" + j + ", " + p + " @" + a);
      LEDs[index.get(this)] = `#${Math.floor(Math.random()*16777215).toString(16)}`;
      circleNodes.data(LEDs);
      updateLEDs();
    }
  }
}

// Init
clock.append(svg.node());
updateLEDs();
body {
  background-color: #ccc;
}

#info {
  background: #222;
  color: #bbb;
  font-size: 0.6em;
  padding: 0.4em;
}

#clock {
  position: relative;
  width: 100%;
  max-width: 480px;
  margin: 0 auto;
  overflow: hidden;
  background-color: #aaa;
  cursor: pointer;
  touch-action: none;
  #touch-group {
    fill: none;
    pointer-events: all;
  }
  #circle-group {
    pointer-events: none;
  }
}
<script src="https://cdn.jsdelivr.net/npm/d3@7"></script>
<div id="info">LED</div>
<div id="clock"></div>

How do I get value of MUI Autocomplete componet using FormData

I am trying to submit values in React JS application using FormData but, I have an issue with Autocomplete component.

This component has value “4” for “US Dollars” option, but FormData gives me selected text instead of selected value.

const fd = new FormData(document.getElementById('frmMain'));
    var formDataObject = Object.fromEntries(fd.entries());
    console.log(fd);

enter image description here
I tried all the methods for FormData but there is nothing to get value of selected Item or such

dir-compare throws empty error inside VSCode extension

When running the dir-compare package compare() method inside a VSCode Extension it is not succeeding, while it does from a regular node script.

It doesn’t seem to output any error. What is happening here? Is there a way to find the underlying error? Is this even possible? How do I proceed?

The code below results in outputting err {}.

const path1 = 'C:/a';
const path2 = 'C:/b';

try
{
    dircompare.compare(path1, path2)
        .then(res => terminal.sendText( 'echo "res ' + JSON.stringify( res ) + '"' ))
        .catch(error => terminal.sendText( 'echo "E2 ' + JSON.stringify( error ) + '"' ));
}
catch(e)
{
    terminal.sendText( 'echo "err ' + JSON.stringify( e ) + '"' );
}

D365 Navigate away from record without showing unsaved changes dialog

We are implementing a custom duplicate detection handler off the save of a new contact record in D365.
It is being done via Javascript.
In the JS OnSave method, we stop the default save action and do some checks via WebAPI to determine whether this may be a duplicate or not.
If no potential duplicates are detected, we manually call the save again in JS.
If some potential duplicates are detected, we display a HTML web resource listing the possible duplicates.

What we are trying to achieve is that the user can double-click on one of the potential duplicates and we will navigate them directly to that other contact record without saving the record that the user was keying in originally.
We are using the Xrm.Navigation.openForm command to achieve this.

The problem is that by default this displays a popup to the user asking them if they wish to save their changes first before leaving the page.
Once they have interacted with this dialog -> it does navigate them to the other record but clearly this is a non-runner in terms of useability (and they can still choose to save the record first anyway).
Is there any way for me to achieve the programmatic navigation to another CRM contact record whilst already being in a CRM contact form in creation mode?
I can’t seem to find anyway to hide that default dialog.

Unable to display image in React Native using Image component

I’m facing an issue with displaying images in my React Native app using the Image component. I have the following code:

import React from 'react';
import { View, Image } from 'react-native';

const App = () => {
  return (
    <View>
      <Image
        source={{ uri: 'https://example.com/image.jpg' }}
        style={{ width: 200, height: 200 }}
      />
    </View>
  );
};

export default App;

However, the image is not showing up on the screen. I have verified that the image URL is correct. Am I missing something in my code, or is there a common mistake that could be causing this issue? Any help would be greatly appreciated!

Feel free to customize it based on your specific situation or add more details if needed.

Key assigning for re-rendering list

(Not any commercial thing, I use the brands as an example)

I am trying to implement a simple watchlist application. For that, I implement a search input area with a result box just below the input(to search stocks). And when I type some stock, for example “apple”, I can see the results clearly.

enter image description here

So after the add “apple” to the watchlist by checking the checkmark, it is added to the watchlist successfully.

enter image description here

When I search for another stock, for example “nvidia”, results are shown successfully, but there is a problem with the checkboxes. It comes with the marked checkbox although it is not in the watchlist as you see.

enter image description here

SearchResultBox.tsx:

import { APISearchResult } from "../../types/ApiSearchResult";
import SearchResultBoxItem from "../search-result-box-item";
import styles from "./styles.module.scss";

type SearchResultBoxProps = {
  apiSearchResults: APISearchResult | null;
  searchInputRef: React.RefObject<HTMLInputElement>;
  searchText: string;
  searchResultBoxRef: React.RefObject<HTMLDivElement>;
  error: Error | null;
};

const SearchResultBox: React.FC<SearchResultBoxProps> = ({
  apiSearchResults,
  searchInputRef,
  searchText,
  searchResultBoxRef,
  error,
}) => {
  return (
    <div className={styles["search-bar"]}>
      <input
        type="text"
        placeholder="Search..."
        defaultValue={searchText}
        ref={searchInputRef}
      />
      <div className={styles["search-result-box"]} ref={searchResultBoxRef}>
        {error ? (
          <h1>{error.message}</h1>
        ) : (
          apiSearchResults?.ResultSet?.Result.map((result, index) => (
            <SearchResultBoxItem key={index} stock={result} />
          ))
        )}
      </div>
    </div>
  );
};

export default SearchResultBox;

SearchResultBoxItem.tsx:

import { useContext, useEffect, useRef } from "react";
import styles from "./styles.module.scss";
import { WatchlistContext } from "../../contexts/watchlistContext";
import { StockSearchResult } from "../../types/ApiSearchResult";
import { fromEvent } from "rxjs";

type SearchResultBoxItemProps = {
  stock: StockSearchResult;
};

const SearchResultBoxItem: React.FC<SearchResultBoxItemProps> = ({ stock }) => {
  const checkboxRef = useRef<HTMLInputElement | null>(null);
  const context = useContext(WatchlistContext);

  if (!context) {
    return (
      <p>We are having a problem with the watchlist. Please try again later.</p>
    );
  }

  const { addToWatchlist, removeFromWatchlist, watchlist } = context;

  const isChecked = (stock: StockSearchResult) => {
    return watchlist.some((s) => s.symbol === stock.symbol);
  };

  useEffect(() => {
    if (checkboxRef.current) {
      const checkboxObservable$ = fromEvent(checkboxRef.current, "change");
      const checkboxObserver = {
        next: (e: Event) => {
          const target = e.target as HTMLInputElement;
          if (target.checked) {
            addToWatchlist(stock);
          } else {
            removeFromWatchlist(stock);
          }
        },
        error: (err: Error) => console.log(err),
        complete: () => console.log("complete"),
      };

      const checkboxSubscription =
        checkboxObservable$.subscribe(checkboxObserver);

      //clean up when unmount
      return () => checkboxSubscription.unsubscribe();
    }
  }, []);

  return (
    <div className={styles["info-box-item"]}>
      <div className={styles.left}>
        <h4>{stock.name}</h4>
        <p className={styles.silent}>{stock.symbol}</p>
      </div>
      <div className={styles.right}>
        <div className={styles.info}>
          <h4>{stock.exch}</h4>
          <p className={styles.silent}>{stock.type}</p>
        </div>
        <div>
          <input
            type="checkbox"
            id={stock.symbol}
            className={styles.toggle}
            defaultChecked={isChecked(stock)}
            ref={checkboxRef}
          />
        </div>
      </div>
    </div>
  );
};

export default SearchResultBoxItem;

I am clearly aware the reason why this is happening: I am assigning keys to indexes and when indexes are equal, React cannot understand the difference between the components.

When I assign stock.stmbol to the key problem is solved. But I am also know that, assigning key to some string value is also not great. So, is there another way, assigning
keys differently, without breaking this code?