How to dynamically retrieve the content text of a HTML tag and its child tags?

I would like to know how to dynamically retrieve the content text of a HTML tag and its child tags?

Here is my HTML code, for example:

<p><code>C:<select>
        <option value="test1">test1</option>
        <option value="test2">test2</option>
    </select>test3<select>
        <option value="test4">test4</option>
        <option value="test5">test5</option>
    </select>test6<select>
        <option value="test7">test7</option>
        <option value="test8">test8</option>
        <option value="test9">test9</option>
    </select>test10.txt</code></p>

I would like to create a button after this code, and when it is clicked, I would like to write the content directly within the console.

For example:

C:test2test3test4test6test8test10.txt

or

C:test1test3test5test6test9test10.txt

It might be possible that another paragraph of code only contains 1 or 2 <select> tags. So, I don’t want a code that only works for 3 <select> tags, like in the previous example.

Thank you very much in advance

Discord.js fs.writeFile not updating the correct json

I am using discord.js to write a bot. I am using a json called data in order to hold information that can be changed via slash commands. However, using fs.writeFile doesn’t modify the targeted json.

My file structure is

node_modules
src
 - index.js
 - data.json
.env
package.lock
package.json

This is what data.json looks like when the project is started

{
    "something": "fdafda"
}

This is what index.js looks like:

require('dotenv').config();
const { Client, IntentsBitField } = require('discord.js');

const fs = require('fs');
const dataFileName = './data.json';
const data = require(dataFileName);


const client = new Client({
  intents: [
    IntentsBitField.Flags.Guilds,
    IntentsBitField.Flags.GuildMembers,
    IntentsBitField.Flags.GuildMessages,
    IntentsBitField.Flags.MessageContent,
  ],
});

client.on('ready', (c) => {
  console.log(`✅ ${c.user.tag} is online.`);

  console.log(data);
  data.modCreationId = "new value";

  fs.writeFile(dataFileName, JSON.stringify(data, null, 2), (err) => {
    if (err) return console.log(err);
    console.log(JSON.stringify(data, null, 2));
  });


});

client.login(process.env.DISCORD_TOKEN);

This what’s logged in the terminal when the bot is initialized:

KTANE FAQ#1840 is online.
{ something: 'fdafda' }
{
  "something": "fdafda",
  "modCreationId": "new value"
}

The file is being read correctly as something is populated in the data variable, and the JSON.stringify console.log shows what I want data.json to have, but the file still only shows

{
    "something": "fdafda"
}

When I looked back at my file structure, I realized that a new data.json file was created outside of the src folder. With the correct information.

node_modules
src
 - index.js
 - data.json
 
data.json
.env
package.lock
package.json

I thought getting rid of the json inside the src folder would fix the problem, but a MODULE_NOT_FOUND error appears if I do so. What do I have to do in order to target the json inside the src folder, and not create any new files?

how can i get all of sabre hotel images, not all area returning images only logo

am trying to fetch sabre hotel images with the get availablle hotel api(https://api.cert.platform.sabre.com/v5/get/hotelavail)… but only few of the results contains the hotelRefInfo

only few of the results contains the HotelRefInfo;
it tried using the get hotel images to see if i can add the images by making two API calls but same result….

i have tried to change the categories but still

PHP code issue causing grid container and bootstrap 5 cards (grid-items) not to render on web-page loading?

I am trying to create a grid container that will dynamically display bootstrap cards of treeseed items that I added to MySQL database.The items should be displayed on the shop portion of a webpage I am making for arboretum I can make a connection to the database and get data back but from the moment I included DOMDocument elements within the code I have not got the expected output.

//shopconnect.php

$domDoc = new DOMDocument();
function generateTreeCard(){
  // global $domDoc;
  $topicDiv = $GLOBALS['domDoc']->createElement('div'); 
  $topicDiv->setAttribute('class','tree-card'); //tree-card div is to be appended to the container mt-3
  return $topicDiv; //DONE ALREADY AT END OF THE LOOP BELOW
}

function generateCardBody(){
  $cardBody = $GLOBALS['domDoc']->createElement('div');
  $cardBody->setAttribute('class','card-body');
  return $cardBody;  //DONE ALREADY APPENDED TO TREECARD BELOW IN THE LOOP
}


function addheaderH4Text($value){
  $cardTitle = $GLOBALS['domDoc']->createElement('h4',$value);//needs to be appended on to card body
  $cardTitle->setAttribute('class','card-title');//needs to be appended on to card body
  return $cardTitle; //ALREADY DONE IN THE LOOP BELOW
}

function generateInfoText(){
  $information = $GLOBALS['domDoc']->createElement('p','Information:');
  $information->setAttribute('class','info-text:');
  return $information; //DONE ALREADY IN LOOP BELOW VIA INFO PARAGRAPH VARIABLE
}

function generateListElements($key,$value){
  $resultItem = "";
  switch($key){
    case "commonName":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "speciesName":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "family":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "seedcostInclVAT":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "quantityInStock":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "seedNumberPerPack":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "colour":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "hardiness":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "soilType":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "soilAcidity":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
      break;
    case "description":
      $resultItem = $GLOBALS['domDoc']->createElement('li',"$key : $value"); 
    break;
  }
  return $resultItem; //needs to be appended to the productInfoList variable <ul>
}

$outerContainer = $domDoc->createElement('div');
$outerContainer->setAttribute('class','items-wrapper');

$productInfoList = $domDoc->createElement('ul');
$listElementResult = "";

$imgCollectorArr = [];
$h4Text = "";
$cardBody = "";
$treeCard = "";
$treeImage1 = "";
$infoParagraph = "";
$cardContainer = "";

portion of code causing issues (shown below) is the nested foreach loop. I am using the functions above to create the DOM elements necessary to build the bootstrap cards (items) dynamically. 

foreach($treeSeedArr as $key => $value){
   $infoParagraph = generateInfoText(); //Just to display "Information:"
  foreach($value as $key1 => $value1){
     echo $key1 . " has a value of " . $value1 . "<br/>";
     if($key1 === 'commonName'){
      $h4Text = addheaderH4Text($value1); //GENERATE h4 text line'
      $cardBody = generateCardBody()->appendChild($h4Text)->appendChild($infoParagraph);
     }
     if($key1 !== 'id' && $key1 !== 'treeImage1' && $key1 !== 'treeImage2' && $key1 !== 'treeImage3'){
       $listElementResult = generateListElements($key1,$value1); // the bullet pointed list of properties
       $productInfoList->appendChild($listElementResult);//this is the <ul> tag
     }
     if($key1 === 'treeImage1' && !(is_null($value["treeImage1"]))){

        if(array_key_exists("treeImage2",$value) && !(is_null($value["treeImage2"]))){
          $imgCollectorArr["treeImage1"] = $value[$key1];
          continue; //if a treeseed has more at least 2 images 
        }
        $treeImage1 = generatetreeImage1($value1); //this is if a treeseed only has one image
        $treeCard = generateTreeCard()->appendChild($treeImage1)->appendChild($cardBody);
     }

     if($key1 === 'treeImage2' && !(is_null($value["treeImage2"]))){
        if(array_key_exists("treeImage3",$value) && !(is_null($value["treeImage3"]))){
          $imgCollectorArr["treeImage2"] = $value[$key1];
          continue; //if a treeseed has 3 images instead of 2
        }
         //design what happens when there are 2 images
         $slideBox1 = $domDoc->createElement('div');
         $slideBox1->setAttribute('class','mySlides fade');
         $countText1 = $domDoc->createElement('div','1 / 2');
         $countText1->setAttribute('class','numbertext');
         $slideBox1->appendChild($countText1);
         $firstImg = $domDoc->createElement('img');
         $firstImg->setAttribute('style','width:100%');
         $firstImg->setAttribute('src',$imgCollectorArr["treeImage1"]);
         $slideBox1->appendChild($firstImg);

         $slideBox2 = $domDoc->createElement('div');
         $slideBox2->setAttribute('class','mySlides fade');
         $countText2 = $domDoc->createElement('div','2 / 2');
         $countText2->setAttribute('class','numbertext');
         $slideBox2->appendChild($countText2);
         $secondImg = $domDoc->createElement('img');
         $secondImg->setAttribute('style','width:100%');
         $secondImg->setAttribute('src',"$value1");
         $slideBox2->appendChild($secondImg);
        
          $treeCard->appendChild($slideBox1);
          $treeCard->appendChild($slideBox2);

        //attach on to treecard
        $previousLink = $domDoc->createElement('a','&#10094;');
        $previousLink->setAttribute('class','prev');
        $previousLInk->setAttribute('onclick','plusSlides(-1)');

        $forwardLink = $domDoc->createElement('a','&#10095;');
        $forwardLink->setAttribute('class','next');
        $forwardLInk->setAttribute('onclick','plusSlides(1)');
        $treeCard->appendChild($previousLink);
        $treeCard->appendChild($forwardLink);


          //dots/circles
      $dotCircleBox1 = $domDoc->createElement('div');
      $dotCircleBox1->setAttribute('style','text-align:center');
      $dotSpanA = $domDoc->createElement('span');
      $dotSpanA->setAttribute('class','dot');
      $dotSpanA->setAttribute('onclick','currentSlide(1)');


      $dotSpanB = $domDoc->createElement('span');
      $dotSpanB->setAttribute('class','dot');
      $dotSpanB->setAttribute('onclick','currentSlide(2)');

      $dotCircleBox1->appendChild($dotSpanA);
      $dotCircleBox1->appendChild($dotSpanB);
      $treeCard->appendChild($dotCircleBox1);
     }

     if($key1 === 'treeImage3' && !(is_null($value[$key1]))){
      $slideBoxA = $domDoc->createElement('div');
      $slideBoxA->setAttribute('class','mySlides fade');
      $countTextA = $domDoc->createElement('div','1 / 3');
      $countTextA->setAttribute('class','numbertext');
      $slideBox1->appendChild($countTextA);
      $firstImg = $domDoc->createElement('img');
      $firstImg->setAttribute('style','width:100%');
      $firstImg->setAttribute('src',$imgCollectorArr["treeImage1"]);
      $slideBoxA->appendChild($firstImg);

      $slideBoxB = $domDoc->createElement('div');
      $slideBoxB->setAttribute('class','mySlides fade');
      $countTextB = $domDoc->createElement('div','2 / 3');
      $countTextB->setAttribute('class','numbertext');
      $slideBoxB->appendChild($countTextB);
      $secondImg = $domDoc->createElement('img');
      $secondImg->setAttribute('style','width:100%');
      $secondImg->setAttribute('src',$imgCollectorArr["treeImage2"]);
      $slideBoxB->appendChild($secondImg);

      $slideBoxC = $domDoc->createElement('div');
      $slideBoxC->setAttribute('class','mySlides fade');
      $countTextC = $domDoc->createElement('div','3 / 3');
      $countTextC->setAttribute('class','numbertext');
      $slideBoxC->appendChild($countTextB);
      $thirdImg = $domDoc->createElement('img');
      $thirdImg->setAttribute('style','width:100%');
      $thirdImg->setAttribute('src',$value1);
      $slideBoxC->appendChild($thirdImg);

      $treeCard->appendChild($slideBoxA);
      $treeCard->appendChild($slideBoxB);
      $treeCard->appendChild($slideBoxC);


      $previousLink = $domDoc->createElement('a','&#10094;');
      $previousLink->setAttribute('class','prev');
      $previousLInk->setAttribute('onclick','plusSlides(-1)');

      $forwardLink = $domDoc->createElement('a','&#10095;');
      $forwardLink->setAttribute('class','next');
      $forwardLInk->setAttribute('onclick','plusSlides(1)');

      $treeCard->appendChild($previousLink);
      $treeCard->appendChild($forwardLink);

      //dots/circles
      $dotCircleBox2 = $domDoc->createElement('div');
      $dotCircleBox2->setAttribute('style','text-align:center');
      $dotSpan1 = $domDoc->createElement('span');
      $dotSpan1->setAttribute('class','dot');
      $dotSpan1->setAttribute('onclick','currentSlide(1)');


      $dotSpan2 = $domDoc->createElement('span');
      $dotSpan2->setAttribute('class','dot');
      $dotSpan2->setAttribute('onclick','currentSlide(2)');


      $dotSpan3 = $domDoc->createElement('span');
      $dotSpan3->setAttribute('class','dot');
      $dotSpan3->setAttribute('onclick','currentSlide(3)');

      $dotCircleBox2->appendChild($dotSpan1);
      $dotCircleBox2->appendChild($dotSpan2);
      $dotCircleBox2->appendChild($dotSpan3); 
      $treeCard->appendChild($dotCircleBox2);

      
     }
  }
    $cardBody->appendChild($productInfoList);
    $treeCard->appendChild($cardBody);
  //for the forward and backwards arrow heads
    $cardContainer = $domDoc->createElement('div');//needs to be appended to items-wrapper
    if(!(is_null($value["treeImage2"])) || !(is_null($value["treeImage3"]))){
      $cardContainer->setAttribute('class','container mt-3 slides-container'); 
    }else{
      $cardContainer->setAttribute('class','container mt-3'); 
    }
    
    $cardContainer->appendChild($treeCard);
  
  $outerContainer->appendChild($cardContainer);
}
$domDoc->appendChild($outerContainer);
$htmlString = $domDoc->saveHTML();
echo $htmlString;

//gardenshop.php (I require once shopconnect.php)

<!DOCTYPE html>
<html lang="en">
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta name="author" content="Jacob">
      <link rel="stylesheet" href="./gardenshop.css">
      <link rel="icon" href="../tree_icon.png">
      <script src="../node_modules/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
      <!-- <script src="./slidelogic.js"></script> -->
      <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" 
      integrity="sha512-SnH5WK+bZxgPHs44uWIX+LLJAJ9/2PkPKZ5QiAj6Ta86w+fsb2TkcmfRyVX3pBnMFcV7oQPJkl9QevSCWr3W6A==" 
      crossorigin="anonymous" referrerpolicy="no-referrer" />
    </head>
    <body>
       <header>
         <div class="img-container"></div>
         <section class="shop-header"><h1>SPROUTY'S GARDENING SHOP</h1></section>
         <ul class="header-grp">
           <li class="header-item"><a id="back-link" href="./homepage.html"><i id="header-arrow" class="fa-solid fa-arrow-left-long"></i>Back To Homepage</a></li>
           <li class="header-item"><i class="fa-solid fa-cart-shopping"></i></li>
         </ul>
       </header>
       <main>
          <div class="f-container">
            <div class="box-1">
              <dl>
                <dt class="inline-dt">Contains Stainless Steel</dt>:&nbsp<input type="checkbox" class="filter-checkbox" id="tool_stainlessstl" name="tool_stainlessstl"/>
                <dt class="inline-dt">FSC &#40;Forest Stewardship Council&#41; certified</dt>:&nbsp<input type="checkbox" class="filter-checkbox" id="tool_fsc_cert" name="tool_fsc_cert"/>
                <dt class="inline-dt">In Stock</dt>:&nbsp<input type="checkbox" class="filter-checkbox" id="tool_stock" name="tool_stock"/>
              </dl>
             </div>
             <div class="box-2">
               <dl>
                <dt class="inline-dt">In Stock</dt>:&nbsp<input type="checkbox" class="filter-checkbox" id="giftcard_stock" name="giftcard_stock"/>
                <dt class="inline-dt">Weight &#40;grams&#41;</dt>:&nbsp<input type="range" min="0" max="50" id="giftcard_weight" name="giftcard_weight"/>
                <dt class="inline-dt">Price</dt>:&nbsp<input type="range" min="0" max="30" step="0.01" id="giftcard_price" name="giftcard_price"/>  
                <dt class="inline-dt">FSC &#40;Forest Stewardship Council&#41; certified</dt>:&nbsp<input type="checkbox" class="filter-checkbox" id="giftcard_fsc_cert" name="giftcard_fsc_cert"/>
               </dl>
             </div>
             <div class="box-3">
              <dl>
                <dt class="inline-dt">In Stock</dt>:&nbsp<input type="checkbox" class="filter-checkbox" id="fertiliser_stock" name="fertiliser_stock"/>
                <dt class="inline-dt">Litres &#40;Capacity&#41;</dt>:&nbsp<input type="range" min="10" max="60" id="fertiliser_capacity" name="fertiliser_capacity"/>
                <dt class="inline-dt">Price</dt>:&nbsp<input type="range" min="0" max="20" step="0.01" id="fertiliser_price" name="fertiliser_price"/>
              </dl>
             </div>
             <div class="box-4">
              <dl>
                <dt class="inline-dt">In Stock</dt>:&nbsp<input type="checkbox" id="treeseed_stock" name="treeseed_stock"/>
                <dt class="inline-dt">Soil Type</dt>:&nbsp<select name="soiltypes" id="soiltypes">
                  <option value="chalk">chalk</option>
                  <option value="sand">sand</option>
                  <option value="loam">loam</option>
                  <option value="clay">clay</option>
                </select>
                <dt class="inline-dt">Soil Acidity</dt>:&nbsp<select name="soilacidity" id="soilacidity">
                  <option value="acid">acid</option>
                  <option value="alkaline">alkaline</option>
                  <option value="neutral">neutral</option>
                </select>
                <dt class="inline-dt">Hardiness</dt>:&nbsp<select name="hardiness" id="hardiness">
                  <option value="hardy">hardy</option>
                  <option value="tender">tender</option>
                  <option value="hardy/half-hardy">hardy/half-hardy</option>
                </select>
                <dt class="inline-dt">Price</dt>:&nbsp<input type="range" min="0" max="4" step="0.01" id="treeseed_price" name="treeseed_price"/>

              </dl>
             </div>
             <div class="box-5">
              <dl>
                 <dt class="inline-dt">In Stock</dt>:&nbsp<input type="checkbox" id="compost_stock" name="compost_stock"/>
                 <dt class="inline-dt">Is Biodegradable</dt>:&nbsp<input type="checkbox" class="filter-checkbox" id="compost_degradable" name="compost_degradable"/>
                 <dt class="inline-dt">Litres &#40;Capacity&#41;</dt>:&nbsp<span><input type="range" min="0" max="280" id="compost_capacity" name="compost_capacity"/>
                 <dt class="inline-dt">Price</dt>:&nbsp<input type="range" min="0" max="20" step="0.01" id="compost_price" name="compost_price"/>
              </dl>
            </div>
          </div>
            <?php require_once './shopconnect.php'; ?>
            <script type="text/javascript" src="./slidelogic.js"></script>

       </main>

    </body>
</html>

I added conditional if statements inside the nested foreach loops to create bootstrap cards that could hold a standalone treeimage or more than one treeimage in which case each card would have a slideshow.

Unfortunately the output is the following and the console in my Chrome browser shows no errors:

No grid rendered on webpage loading

How to update map coordinates after zooming in Leaflet?

I am new to working with maps. I have currently implemented a feature that allows users to draw an area on the map, which gets marked. What I need is for, when the user zooms in on the map while drawing, the geographic coordinates to be updated to reflect the new visible area on the map.

Currently, when the user zooms in while drawing, the final mark refers to the initial coordinates before the zoom, resulting in a marked area that is different from what the drawing currently shows.

I am working with Leaflet and Leaflet.draw.

My intention was to capture the pixel points of the drawing before the zoom and then convert them back to geographic coordinates after the zoom. However, it seems that this is not working, as the coordinates remain the same. Below is a part of the code where the coordinates are captured before creating the marker.

Basically, I need latlngs to contain the updated coordinates after the zoom, so I can pass them as parameters to create the marker.

        let isZoomed = false;

        map.on("zoomend", () => {
          isZoomed = true;
        });


        freeDraw.on('markers', (event: any) => {
          if (event.eventType == 'create' && event.target.map.drawLatLngs) {
            var latlngs = event.target.map.drawLatLngs;
            handleNewPolyline(latlngs);
          }

          if (event.eventType == 'create' && event.latLngs && event.latLngs.length > 0) {
            let latlngs: any = event.latLngs;
            let newPoints:any = [];

            let initialPoints = latlngs
            .flatMap((polygon: any) =>
              polygon.map((coord: any)=> map.latLngToLayerPoint(coord))
            );

            if (isZoomed) {
              newPoints = initialPoints.map((point: any) => map.layerPointToLatLng(point));
              latlngs = newPoints;             
              isZoomed = false;
              newPoints = [];
            } else {
              latlngs = event.latLngs;
            }

npm install is giving error – npm error ERESOLVE unable to resolve dependency tree

In my React Native with TypeScript project, I wanted to install dependencies.

To install Testing Libraries I’ve used this command:
npm install @testing-library/react-native @testing-library/jest-native –save-dev

**But it's giving me this error:**

npm error code ERESOLVE
npm error ERESOLVE unable to resolve dependency tree
npm error
npm error While resolving: [email protected]
npm error Found: [email protected]
npm error node_modules/react
npm error   react@"18.2.0" from the root project
npm error   peer react@">=16.8.0" from @testing-library/[email protected]
npm error   node_modules/@testing-library/react-native
npm error     dev @testing-library/react-native@"*" from the root project
npm error   1 more (react-native)
npm error
npm error Could not resolve dependency:
npm error peer react@"^18.3.1" from [email protected]
npm error node_modules/react-test-renderer
npm error   peer react-test-renderer@">=16.8.0" from @testing-library/[email protected]
npm error   node_modules/@testing-library/react-native
npm error     dev @testing-library/react-native@"*" from the root project
npm error
npm error Fix the upstream dependency conflict, or retry
npm error this command with --force or --legacy-peer-deps

— I’ve also tried –legacy-peer-deps but, then npm install is not working and I’m not sure what’s wrong.

===> Output of npm ls react-dom:

[email protected] /Users/App
└── (empty)

===> Output of npm ls react:

[email protected] /Users/****/App
├─┬ @testing-library/[email protected]
│ └── [email protected] deduped
├─┬ @testing-library/[email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ └── [email protected] deduped
├─┬ [email protected]
│ ├─┬ @react-native/[email protected]
│ │ └── [email protected] deduped
│ ├─┬ [email protected]
│ │ └── [email protected] deduped
│ └── [email protected] deduped
└── [email protected]

I’ve tried –legacy-peer-deps, it’s working temporary but when I try to add ESLint, it’s again giving me error.

npm error code ERESOLVE
npm error ERESOLVE could not resolve
npm error
npm error While resolving: @testing-library/[email protected]
npm error Found: [email protected]

What is different in my Ajax vs XMLHttpRequest Call that lets my Server understand Ajax but not XMLHttpRequest?

I have a very simple server call like this:

[HttpPost]
[AllowAnonymous]
public JsonResult Test(TestRequestModel requestModel)
{
    //do stuff
    return Json(new { result.Success });
}

My TestRequestModel looks like this:

public class TestRequestModel
{
    public string Email { get; set; } = string.Empty;
}

I am trying to do a POST request to the server. But for a complex list of reasons I need to be using XMLHttpRequest instead of $.ajax. To do this I am going to show you how I did it in ajax and then how I did it with XMLHttpRequest.

First here is how I call my server:

function MyTestFunction() {
   let parameters = {
       Email: "[email protected]"
   }

    CallServer(function () {
        //Do stuff
    }, function () {
        //Do other stuff
    }, "/Home/Test", parameters)
}

Ajax:

function CallServer(resolve, reject, path, parameters) {
    $.ajax({
        type: "POST",
        url: path,
        data: AddAntiForgeryToken(parameters),
        success: function (response) {
            //do stuff
        },
        error: function (xhr) {
            //do stuff
        },
        complete: function () {
            //do more stuff
        }
    });
}

XMLHttpRequest Way:

function CallServer(resolve, reject, path, parameters) {
    let xhr = new XMLHttpRequest();

    xhr.open("POST", path, true);
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    xhr.setRequestHeader('RequestVerificationToken', GetMyToken());
    xhr.onreadystatechange = function (e) {
        if (xhr.readyState === XMLHttpRequest.DONE) {
            if (xhr.status === 200 || xhr.status === 201) {
                //do stuff
            }
            else {
                //do other stuff
            }
        }
    };
    
    xhr.send(JSON.stringify(parameters));
}

If I run the above code the ajax way, then it works without issues. If I try to do it the XMLHttpRequest way then my request model gets created but the Email field is not populated. Now I found that I can solve this by adding [FromBody] on the request model and it does work, I tested it and no problems.

Also, as I read online and hopefully understood correctly, but ajax uses XMLHttpRequest behind the hood right?

So why do I have to add [FromBody] on my controller for this to work? Is there a way I can modify my XMLHttpRequest so that it is not needed? The solution I am looking for how to not have to specify [FromBody] on a json post request to .net core server.

Highchart vertical and horizontal scrollbar

I have dependency information that I would like to show on a web page using Highcharts. I chose Treegraph chart as I think it’s more suitable for what I need it for. This is the link to a demo https://www.highcharts.com/demo/highcharts/treegraph-chart.

The issue I have and I couldn’t overcome on my own is that when there are lots of branches and Leaves then the whole graph will get squeezed to show everything in one view. jsfiddle for code below is available in the link above.

Highcharts.chart('container', {
    chart: {
        spacingBottom: 30,
        marginRight: 120,
        height: 1200,
        scrollablePlotArea: {
            minWidth: 1500, // Set minimum width for horizontal scrolling
            minHeight: 1200 // Set minimum height for vertical scrolling
        }
    },
    title: {
        text: 'Phylogenetic language tree'
    },
    series: [
        {
            type: 'treegraph',
            keys: ['parent', 'id', 'level', 'color'], // Add color to keys
            clip: false,
            data: [
                [undefined, 'Proto Indo-European'],
                ['Proto Indo-European', 'Balto-Slavic'],
                ['Proto Indo-European', 'Germanic'],
                ['Proto Indo-European', 'Celtic'],
                ['Proto Indo-European', 'Italic'],
                ['Proto Indo-European', 'Hellenic'],
                ['Proto Indo-European', 'Anatolian'],
                ['Proto Indo-European', 'Indo-Iranian'],
                ['Proto Indo-European', 'Tocharian'],
                ['Indo-Iranian', 'Dardic'],
                ['Indo-Iranian', 'Indic'],
                ['Indo-Iranian', 'Iranian'],
                ['Iranian', 'Old Persian'],
                ['Old Persian', 'Middle Persian'],
                ['Indic', 'Sanskrit'],
                ['Italic', 'Osco-Umbrian'],
                ['Italic', 'Latino-Faliscan'],
                ['Latino-Faliscan', 'Latin'],
                ['Celtic', 'Brythonic'],
                ['Celtic', 'Goidelic'],
                ['Germanic', 'North Germanic'],
                ['Germanic', 'West Germanic'],
                ['Germanic', 'East Germanic'],
                ['North Germanic', 'Old Norse'],
                ['North Germanic', 'Old Swedish'],
                ['North Germanic', 'Old Danish'],
                ['West Germanic', 'Old English'],
                ['West Germanic', 'Old Frisian'],
                ['West Germanic', 'Old Dutch'],
                ['West Germanic', 'Old Low German'],
                ['West Germanic', 'Old High German'],
                ['Old Norse', 'Old Icelandic'],
                ['Old Norse', 'Old Norwegian'],
                ['Old Swedish', 'Middle Swedish'],
                ['Old Danish', 'Middle Danish'],
                ['Old English', 'Middle English'],
                ['Old Dutch', 'Middle Dutch'],
                ['Old Low German', 'Middle Low German'],
                ['Old High German', 'Middle High German'],
                ['Balto-Slavic', 'Baltic'],
                ['Balto-Slavic', 'Slavic'],
                ['Slavic', 'East Slavic'],
                ['Slavic', 'West Slavic'],
                ['Slavic', 'South Slavic'],
                ['Polish', 'POLISH2'],
                ['PPPPPPPPP1', 'QQQQQQQQQ'],
                // Leaves:
                ['Proto Indo-European', 'Phrygian', 6],
                ['Proto Indo-European', 'Armenian', 6],
                ['Proto Indo-European', 'Albanian', 6],
                ['Proto Indo-European', 'Thracian', 6],
                ['Tocharian', 'Tocharian A', 6],
                ['Tocharian', 'Tocharian B', 6],
                ['Anatolian', 'Hittite', 6],
                ['Anatolian', 'Palaic', 6],
                ['Anatolian', 'Luwic', 6],
                ['Anatolian', 'Lydian', 6],
                ['Iranian', 'Balochi', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Kurdish', 6],
                ['Iranian', 'Pashto', 6],
                ['Iranian', 'Sogdian', 6],
                ['Old Persian', 'Pahlavi', 6],
                ['Middle Persian', 'Persian', 6],
                ['Hellenic', 'Greek', 6],
                ['Dardic', 'Dard', 6],
                ['Sanskrit', 'Sindhi', 6],
                ['Sanskrit', 'Romani', 6],
                ['Sanskrit', 'Urdu', 6],
                ['Sanskrit', 'Hindi', 6],
                ['Sanskrit', 'Bihari', 6],
                ['Sanskrit', 'Assamese', 6],
                ['Sanskrit', 'Bengali', 6],
                ['Sanskrit', 'Marathi', 6],
                ['Sanskrit', 'Gujarati', 6],
                ['Sanskrit', 'Punjabi', 6],
                ['Sanskrit', 'Sinhalese', 6],
                ['Osco-Umbrian', 'Umbrian', 6],
                ['Osco-Umbrian', 'Oscan', 6],
                ['Latino-Faliscan', 'Faliscan', 6],
                ['Latin', 'Portugese', 6],
                ['Latin', 'Spanish', 6],
                ['Latin', 'French', 6],
                ['Latin', 'Romanian', 6],
                ['Latin', 'Italian', 6],
                ['Latin', 'Catalan', 6],
                ['Latin', 'Franco-Provençal', 6],
                ['Latin', 'Rhaeto-Romance', 6],
                ['Brythonic', 'Welsh', 6],
                ['Brythonic', 'Breton', 6],
                ['Brythonic', 'Cornish', 6],
                ['Brythonic', 'Cuymbric', 6],
                ['Goidelic', 'Modern Irish', 6],
                ['Goidelic', 'Scottish Gaelic', 6],
                ['Goidelic', 'Manx', 6],
                ['East Germanic', 'Gothic', 6],
                ['Middle Low German', 'Low German', 6],
                ['Middle High German', '(High) German', 6],
                ['Middle High German', 'Yiddish', 6],
                ['Middle English', 'English', 6],
                ['Middle Dutch', 'Hollandic', 6],
                ['Middle Dutch', 'Flemish', 6],
                ['Middle Dutch', 'Dutch', 6],
                ['Middle Dutch', 'Limburgish', 6],
                ['Middle Dutch', 'Brabantian', 6],
                ['Middle Dutch', 'Rhinelandic', 6],
                ['Old Frisian', 'Frisian', 6],
                ['Middle Danish', 'Danish', 6],
                ['Middle Swedish', 'Swedish', 6],
                ['Old Norwegian', 'Norwegian', 6],
                ['Old Norse', 'Faroese', 6],
                ['Old Icelandic', 'Icelandic', 6],
                ['Baltic', 'Old Prussian', 6],
                ['Baltic', 'Lithuanian', 6],
                ['Baltic', 'Latvian', 6],
                ['West Slavic', 'Polish', 6],
                ['POLISH2', 'PPPPPPPPP', 6],
                ['POLISH2', 'PPPPPPPPP', 6],
                ['POLISH2', 'PPPPPPPPP', 6],
                ['POLISH2', 'PPPPPPPPP1', 6],
                ['POLISH2', 'PPPPPPPPP', 6],
                ['POLISH2', 'PPPPPPPPP', 6],
                ['POLISH2', 'PPPPPPPPP', 6],
                ['POLISH2', 'PPPPPPPPP', 6],
                ['QQQQQQQQQ', '_=========_', 6],
                
                ['West Slavic', 'Slovak', 6],
                ['West Slavic', 'Czech', 6],
                ['West Slavic', 'Wendish', 6],
                ['East Slavic', 'Bulgarian', 6],
                ['East Slavic', 'Old Church Slavonic', 6],
                ['East Slavic', 'Macedonian', 6],
                ['East Slavic', 'Serbo-Croatian', 6],
                ['East Slavic', 'Slovene', 6],
                ['South Slavic', 'Russian', 6],
                ['South Slavic', 'Ukrainian', 6],
                ['South Slavic', 'Belarusian', 6],
                ['South Slavic', 'Rusyn', 6]
            ],
            marker: {
                symbol: 'circle',
                radius: 6,
                fillColor: '#ffffff',
                lineWidth: 3
            },
            dataLabels: {
                align: 'left',
                pointFormat: '{point.id}',
                style: {
                    color: '#000000',
                    textOutline: '3px #ffffff',
                    whiteSpace: 'nowrap'
                },
                x: 24,
                crop: false,
                overflow: 'none'
            },
            levels: [
                {
                    level: 1,
                    levelIsConstant: false,
                    colorByPoint: true
                },
                {
                    level: 2,
                    colorVariation: {
                        key: 'brightness',
                        to: -0.5
                    }
                },
                {
                    level: 3,
                    colorVariation: {
                        key: 'brightness',
                        to: 0.5
                    }
                },
                {
                    level: 6,
                    dataLabels: {
                        x: 10
                    },
                    marker: {
                        radius: 4
                    }
                }
            ]
        }
    ]
});


document.getElementById('container').style.overflow = 'auto';
document.getElementById('container').style.width = '100%';
document.getElementById('container').style.height = '800px';

How can I avoid the squeezing and add like a vertical and horizontal scrollbar? and as the graph grow vertically or horizontally instead of putting stuff on one another, grow the graph and add scrollbars(or maybe the ability to move the graph by dragging the graph).

I have been stuck on this for two days and it seems that I cannot figure it out on my own. I would appreciate any help. I’m not a web developer or a UI designer so please forgive any obvious thing that I might have missed.

Thanks

Chart JS Curved Labels in Polar Area

I am working on a web project using Chart.js to create a PolarArea chart that dynamically updates based on the selected class from a dropdown menu. I have encountered an issue where the labels are dynamic, but I need it to be static

  const subjects = {
5: ["Укр. мова", "Укр. літ.", "Заруб. літ.", "Англ. мова", "Історія", "Математика", "Природа", "ІТ", "Фізкультура", "Мистецтво"],
6: ["Укр. мова", "Укр. літ.", "Заруб. літ.", "Англ. мова", "Історія", "Математика", "Природа", "ІТ", "Географія", "Фізкультура", "Мистецтво"],
7: ["Укр. мова", "Укр. літ.", "Заруб. літ.", "Англ. мова", "Всесвіт. історія", "Історія Укр.", "Алгебра", "Геометрія", "ІТ", "Біологія", "Географія", "Фізика", "Хімія", "Здоров'я", "Мистецтво", "Фізкультура"],
8: ["Укр. мова", "Укр. літ.", "Заруб. літ.", "Англ. мова", "Всесвіт. історія", "Історія Укр.", "Алгебра", "Геометрія", "ІТ", "Біологія", "Географія", "Фізика", "Хімія", "Здоров'я", "Мистецтво", "Фізкультура"],
9: ["Укр. мова", "Укр. літ.", "Заруб. літ.", "Англ. мова", "Всесвіт. історія", "Історія Укр.", "Алгебра", "Геометрія", "ІТ", "Біологія", "Географія", "Фізика", "Хімія", "Здоров'я", "Мистецтво", "Фізкультура"],
10: ["Укр. мова", "Укр. літ.", "Заруб. літ.", "Англ. мова", "Всесвіт. історія", "Історія Укр.", "Алгебра", "Геометрія", "ІТ", "Біологія", "Географія", "Фізика", "Хімія", "Здоров'я", "Мистецтво", "Фізкультура"],
11: ["Укр. мова", "Укр. літ.", "Заруб. літ.", "Англ. мова", "Всесвіт. історія", "Історія Укр.", "Алгебра", "Геометрія", "ІТ", "Біологія", "Географія", "Фізика", "Хімія", "Здоров'я", "Мистецтво", "Фізкультура"]

};

    const data = {
        labels: [],
        datasets: [{
            data: [],
            backgroundColor: [],
            borderColor: 'rgba(54, 162, 235, 0.7)',
            borderWidth: 1
        }]
    };

    const ctx = document.getElementById('myChart').getContext('2d');
    const myChart = new Chart(ctx, {
type: 'polarArea',
data: data,
options: {
    responsive: true,
    maintainAspectRatio: false,
    
    layout: {
        padding: {
            top: 30,
            bottom: 30,
            left: 30,
            right: 30
        }
    },
    scales: {
        r: {
            min: 1, // мінімальне значення
            max: 12,
            ticks: {
                stepSize: 1, 
                color: '#000', // колір поділок
                backdropColor: 'rgba(255,255,255,0.8)', // фон під поділками
                font: {
                    size: 14 // розмір шрифту для поділок
                }
            },
            grid: {
                color: '#888', // колір сітки
                circular: true
            },
        }
    },
    plugins: {
        legend: {
            display: false
        },
        labels: {
            size: 1,
            render: 'label',
            arc: true,
            fontColor: '#000',
            position: 'outside'
        }
    }
}

});
I’ve tied everything, but nothing works

Dynamic audio rendering with tone.js

Sorry for the trivial question, but I’m struggling in finding the correct/best method that I should use to achieve this simple task using Tone.js (and/or a clear example):

  • I would like to create a “stereo audio stream” (don’t know what’s the correct name in Tone.js, AudioWorklet??) and connect it to the default output

  • set a callback function that is called whenever the “audio stream” needs more audio data, and I can fill two float buffers (left and right) with my own data (a buffer should be an array of 2048 floats)

I also would like to be able to connect it to a chain of effects (reverb and/or delay) implemented in Tone.js.

I found something with “createScriptProcessor” but it seems deprecated and not in the Tone.js framework.

Thank you in advance.

How to know what graph are you referring with multiple eCharts graphs in one page with `renderItem` callback

If there are more then one charts in a single page and you got some functions like this to change the graph type

function setGraph_chartName1_to_customType(e){ //there are multiple functions like this
    chartName1.setOption({
        series: [{
            customtypename: 'customType',
            renderItem: renderItemCallback,
        }]
    });
       // ... somethings
}

and then in renderItemCallback() you have to identify the chart needed because the function renderItemCallback() it’s used for more then one chart (eg. chartName1, chartName2, chartName3)

function renderItemCallback(params, api) {
    var points_array = chartName1.getOption().dataset[0].source; //HERE IS NEEDED THE CHART OBJECT
    if (points_array.length) {
             // ... somethings
    }
}

Now, after the code, see the question(s):

How to get chartName1 as referer graph inside renderItemCallback function?

Is there a way to send other parameters to the callback function in addition to params, api (to identify the graph you are working on)?

Prop is usable in template but not in script

I’m a little confused as I’ve got a prop called filterData with an array being sent from the parent app to a child app, and it both shows in the Vue inspector with the populated array:

Vue prop data

and it also works fine populating the page with products when I run it as a v-for loop in the child component:

<div v-for="(product, index) in filterData" :key="index">

However I can’t access it in the childs <script> area to create a new function from the data. Even just trying to console.log(filterData) gives error 'filterData' is not defined.

Here’s how I’ve got it setup:

PARENT

import productData from './assets/products.json'

export default {
  name: 'App',
  data(){
    return{
      productData: productData
    }
  },
}

<template>
  <ChildComponent 
      :productsData="productData" 
      :filterData="productData.products"
    />
</template>

CHILD COMPONENT

<template>
  <div v-for="(product, index) in filterData" :key="index"> // loops fine
    <div class='productName'>{{product.title}}</div>                    
  </div>
</template>

<script>
  console.log(filterData) // throws error

  export default {
    name: 'ChildComponent',
    props: {
        productsData: {
            type: Array,
            required: true
        },
        filterData: {
            type: Array,
            required: true
        }
    }
};
</script>

I’ve tried looking through other questions like this one but they usually discuss what I’ve already got working, any help on how I get this working?

How to arrange data structure for querying in firebase for this explained query not to give any error?

I have a database existing of user docs. Sample user object is as follows:

user {
 id: string,
 name: string,
 town: string,
 city: string,
 country: string,
 filter: ["town", "city"] // array of strings
}

I want to get users where their id’s don’t include spesific ids (which is a must), also some other query parameters. I have a filter field which is an array (its structure can be changed for doing the purpose of the query), consisting of items ["town", "city", "country"]. Its alternative values are ["town"], ["town","city"], ["town","city","country"] and ["noone"]. There is a contains order for filtering: country > city > town. I mean parent is country, its children are cities, its children are towns. I firstly tried with setting the filter field as string, but I got error from firebase telling OR cannot be used with NOT-IN. Then I transformed the filter field to an array. But again due to limitations of firebase, I cannot obtain what I try to. Maybe my issue is about not creating the right skeleton data structure about filter field.

What I need to do is exactly querying these: if I want to query where filter is “town”, it should bring all users with same “town” names whose filter value is not [“noone”], but can have values of [“town”], [“town”, “city”] or [“town”,”city”,”country”].

If my filter is “city”, it should bring all users with same “city” named users whose filter value is not ["noone"] or ["town"], but if queried user’s filter value is [“town”] and having same town with the querying user, than it should be included this in results.

If my filter is “country” it should bring all users with same “country” name, also including users having the same city names and having same town names whose filter value is not set to [“noone”]. But this result should bring users whose filter values are “town” who are in the same town with querying user, also whose filter values are “city” who are in the same city with querying user.

I hope I could explain what I try to achieve, briefly querying users by applying mutual filter values. What I tried is:

let locFilter, filterVal
      if (user.filter.includes("country")) { 
        locFilter = or(where("country", "==", user.country), where("city", "==", user.city), where("town", "==", user.town))
        filterVal = ["town", "city", "country"] } // this logic is faulty when querying user's town or city is same as queried user's town or city while his filterVal is whether ["town"] or ["town", "city"]. But I couldn't find a better way
      else if (user.filter.includes("city")) { 
        locFilter = or(where("city", "==", user.city), where("town", "==", user.town))
        filterVal = ["town", "city"] } // this logic is faulty when querying user's city is same as queried user's city while his filterVal is whether ["town"] or ["town", "city", "country"]. But I couldn't find a better way
      else if (user.filter.includes("town")) { 
        locFilter = where("town", "==", user.town)
        filterVal = ["town"] }  // this logic is faulty when querying user's town is same as queried user's town while his filterVal is whether ["town", "city"] or ["town", "city", "country"]. But I couldn't find a better way

await getDocs(query(collection(db, "users"), 
  and(
   where("id","not-in", [...blockedIds, ...deletedIds]),
   where("filter", "array-contains-any", filterVal),
   locFilter
  )))

but this gives error, because of firebase limitations (NOT-IN cannot be used with 'IN', 'ARRAY_CONTAINS' or 'OR'). Should I change my data structure for firebase to query without errors? If so, how? Data structure of filter field should be rearranged other than array for this aim? Can someone help?

d3js pie chart with specific less traditional different patterns for the segments with slightly rounded corners

I am experimenting with different styles for charts – and I am wondering how to create these exact kind of pattern textures charts for the different segments.

enter image description here

How do you start creating some of these specific patterns if its something less traditional like a big/small dot tessellation.

enter image description here

Or if there is a gradient instead of a pattern

enter image description here

and in this case there appears to be a slight rounding at the edges of the pie as if it were stacked on top of each other and overlayed more.
d3js pie chart with different patterns for the segments

enter image description here

demo reference with a legend on the left – and pie/half pie on the right

enter image description here

https://codesandbox.io/p/sandbox/magical-wiles-forked-fvj79p

my current build — regular pie

import React from 'react';
import * as d3 from 'd3';
import './PieChart1.scss';

class PieChart extends React.Component {
    constructor(props) {
        super(props);
        this.myRef = React.createRef();
        this.state = {
            data: [],
            theme: this.props.theme ? this.props.theme : ['#bde0fe', '#2698f9', '#71bcfd', '#f1f8fe']
        };
    }

    componentDidMount() {
        var $this = this.myRef.current;

        d3.select($this)
            .selectAll('svg')
            .remove();

        const data = this.props.data;

        const width = parseInt(this.props.width, 10),
            height = parseInt(this.props.height, 10),
            radius = parseInt(this.props.r, 10),
            innerradius = parseInt(this.props.ir, 10);

        var color = d3.scaleOrdinal().range(this.state.theme);

        var arc = d3
            .arc()
            .outerRadius(radius)
            .innerRadius(innerradius);

        data.forEach(function(d) {
            d.total = +d.value;
        });

        var pie = d3
            .pie()
            .sort(null)
            .value(function(d) {
                return d.total;
            });

        var svg = d3
            .select($this)
            .append('svg')
            .attr('width', width)
            .attr('height', height)
            .append('g')
            .attr('class', 'piechart')
            .attr('transform', 'translate(' + width / 2 + ',' + height / 2 + ')');

        var segments = svg.append('g').attr('class', 'segments');

        var slices = segments
            .selectAll('.arc')
            .data(pie(data))
            .enter()
            .append('g')
            .attr('class', 'arc');

        slices
            .append('path')
            .attr('d', arc)
            .attr('fill', function(d, i) {
                return color(i);
            })
            .transition()
            .attrTween('d', function(d) {
                var i = d3.interpolate(d.startAngle+0.1, d.endAngle);
                return function(t) {
                    d.endAngle = i(t);
                    return arc(d);
                }
            });

    }

    render() {
        return <div ref={this.myRef} className="PieChart" />;
    }
}
export default PieChart;

I’ve seen this example in making a pattern – how would you make these 4 pattern types — one appears to be just a gradient

<!DOCTYPE html>
<html>
<head>
    <style>
        
    </style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="hook"></div>
<script type="text/javascript">
        // SVG injection:
var svg = d3.select("#hook").append("svg").attr("id", "d3svg")
    .attr("width", 120)
    .attr("height", 120);
//Pattern injection
var defs = svg.append("defs")
var pattern = defs.append("pattern")
        .attr({ id:"hash4_4", width:"8", height:"8", patternUnits:"userSpaceOnUse", patternTransform:"rotate(-45)"})
    .append("rect")
        .attr({ width:"4", height:"8", transform:"translate(0,0)", fill:"#88AAEE" });

//Shape design
svg.append("g").attr("id","shape")
    .append("circle")
.attr({cx:"60",cy:"60",r:"50", fill:"url(#hash4_4)" })
    </script>
</body>
</html>

Found this as a reference — but not sure how to make those exact patterns in the demo

How to make the patterns of a pie chart parallel to the center line of sectors in d3.js?

<script src="https://unpkg.com/[email protected]/dist/d3.min.js"></script>
<script src="https://d3js.org/d3.v4.js"></script>
<svg id="pie" width="300" height="200"> </svg>
<svg id="legend">
    
        <rect x="0" y="0" width="100" height="100"
        style="stroke: #000000; fill: url(#pattern0);" />   
    <rect x="100" y="0" width="100" height="100"
        style="stroke: #000000; fill: url(#pattern1);" />   
        <rect x="200" y="0" width="100" height="100"
        style="stroke: #000000; fill: url(#pattern2);" />   
</svg>

<script>
    var data = [{ year: '2001', value:10 },
            { year: '2002', value:30 },
            { year: '2003', value:60 },
           ]

    var svg = d3.select("svg#pie"),
        width = svg.attr("width"),
        height = svg.attr("height"),
        radius = Math.min(width, height) / 2,
        g = svg.append("g").attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    var color = d3.scaleOrdinal(['#4daf4a','#377eb8','#ff7f00','#984ea3','#e41a1c']);

    // Generate the pie
    var pie = d3.pie().value(function(d) { 
    return d.value;})(data);

    // Generate the patterns
    var legend = d3.select("svg#legend"),
        defs = legend.append("defs");
    defs.selectAll("pattern")
        .data(pie)
        .enter()
        .append("pattern")
        .attr("id", (d, i) => "pattern" + i)
        .attr("patternUnits", "userSpaceOnUse")
        .attr("width", 20)
        .attr("height", 20)
        .attr("patternTransform", (d) => `rotate(${(d.startAngle + d.endAngle) * 90 / Math.PI})`)
        .style("fill", (d, i) => color(i))
             .append("rect")
             .attr("x", 5)
             .attr("y", 5)
             .attr("width", 10)
             .attr("height", 10)

    // Generate the arcs
    var arc = d3.arc()
                .innerRadius(0)
                .outerRadius(radius);

    //Generate groups
    var arcs = g.selectAll("arc")
                .data(pie)
                .enter()
                .append("g")
                .attr("class", "arc")

    //Draw arc paths
    arcs.append("path")
        .attr("d", arc)
  .attr('stroke', "black")
            .attr('stroke-width', '1')
            .attr("fill", function(d,i) { return  "url(#pattern" + i +")"});
</script>
</script>

19th Sep – latest version – with general patterns – but not the ones we need or legend in the right place.

enter image description here

https://codesandbox.io/p/sandbox/magical-wiles-forked-pmdgrs

import React from "react";
import * as d3 from "d3";
import "./PieChart1.scss";

class PieChart extends React.Component {
  constructor(props) {
    super(props);
    this.myRef = React.createRef();
    this.state = {
      data: [],
      theme: this.props.theme
        ? this.props.theme
        : ["#bde0fe", "#2698f9", "#71bcfd", "#f1f8fe"],
    };
  }

  componentDidMount() {
    var $this = this.myRef.current;

    d3.select($this).selectAll("svg").remove();

    const data = this.props.data;

    const width = parseInt(this.props.width, 10),
      height = parseInt(this.props.height, 10),
      radius = parseInt(this.props.r, 10),
      innerradius = parseInt(this.props.ir, 10);

    var color = d3.scaleOrdinal().range(this.state.theme);

    var arc = d3.arc().outerRadius(radius).innerRadius(innerradius);

    data.forEach(function (d) {
      d.total = +d.value;
    });

    var pie = d3
      .pie()
      .sort(null)
      .value(function (d) {
        return d.total;
      });

    var svg = d3
      .select($this)
      .append("svg")
      .attr("width", width)
      .attr("height", height)
      .append("g")
      .attr("class", "piechart")
      .attr("transform", "translate(" + width / 2 + "," + height / 2 + ")");

    // Generate the patterns
    var legend = d3.select("svg#legend"),
      defs = legend.append("defs");
    defs
      .selectAll("pattern")
      .data(pie(data))
      .enter()
      .append("pattern")
      .attr("id", (d, i) => "pattern" + i)
      .attr("patternUnits", "userSpaceOnUse")
      .attr("width", 20)
      .attr("height", 20)
      .attr(
        "patternTransform",
        (d) => `rotate(${((d.startAngle + d.endAngle) * 90) / Math.PI})`
      )
      .style("fill", (d, i) => color(i))
      .append("rect")
      .attr("x", 5)
      .attr("y", 5)
      .attr("width", 10)
      .attr("height", 10);

    var segments = svg.append("g").attr("class", "segments");

    var slices = segments
      .selectAll(".arc")
      .data(pie(data))
      .enter()
      .append("g")
      .attr("class", "arc");

    slices
      .append("path")
      .attr("d", arc)
      //.attr("fill", function (d, i) {
      //  return color(i);
      //})
      .attr("stroke", "black")
      .attr("stroke-width", "1")
      .attr("fill", function (d, i) {
        return "url(#pattern" + i + ")";
      })
      .transition()
      .attrTween("d", function (d) {
        var i = d3.interpolate(d.startAngle + 0.1, d.endAngle);
        return function (t) {
          d.endAngle = i(t);
          return arc(d);
        };
      });
  }

  render() {
    return (
      <>
        <svg id="legend">
          <rect
            x="0"
            y="0"
            width="100"
            height="100"
            style={{ stroke: "#000000", fill: "url(#pattern0)" }}
          />
          <rect
            x="100"
            y="0"
            width="100"
            height="100"
            style={{ stroke: "#000000", fill: "url(#pattern1)" }}
          />
          <rect
            x="200"
            y="0"
            width="100"
            height="100"
            style={{ stroke: "#000000", fill: "url(#pattern2)" }}
          />
        </svg>

        <div ref={this.myRef} className="PieChart" />
      </>
    );
  }
}
export default PieChart;

How can I detect whether authorization is complete?

Basic question

Is there a way for a browser to detect whether a user has been authenticated via SAML on a different site?

Background

My organization has a custom application that is a portal that uses an iframe to serve up reports stored on two different servers, Tableau and PowerBI. The Tableau and PowerBI servers use SAML authentication and require MFA. When the portal opens, it’s supposed to open a Tableau report on the home page. In the past, the Tableau authentication could take place in the iframe, but Microsoft no longer allows that, so the iframe shows a broken page. I’m tasked with finding a workaround.

My Idea

My idea is to make the portal open popup windows for Tableau and PowerBI authentication. After authentication has taken place, display the report in the iframe. But I don’t know how to detect whether authentication has taken place. Can anyone help me?