Initializing QUILL via JQuery

Please consider this code:

var ec = $(`#${element.name}`);
ec.css({"height": "300px"});

if (typeof Quill === "undefined") {
  $.getScript("https://cdn.jsdelivr.net/npm/[email protected]/dist/quill.js", function() {
    // Add the CSS dynamically
    let link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = 'https://cdn.jsdelivr.net/npm/[email protected]/dist/quill.snow.css';
    document.head.appendChild(link);
    
    // Wait for the stylesheet to load
    link.onload = function() {
      // Initialize Quill editor
      var el = $(`#${element.name}`).get(0);
      if (!el) {
        console.error("Element not found:", `#${element.name}`);
        return;
    }

    // Ensure the element is contenteditable
    el.setAttribute('contenteditable', 'true');
    
      // Create the Quill editor instance with the toolbar
      let quill = new Quill(el, {
          theme: 'snow',
          modules: {
              toolbar: [
                  [{ 'header': '1' }, { 'header': '2' }, { 'font': [] }],
                  [{ 'list': 'ordered'}, { 'list': 'bullet' }],
                  ['bold', 'italic', 'underline', 'strike'],
                  ['link', 'image'],
                  [{ 'align': [] }],
                  ['blockquote', 'code-block'],
                  ['clean']  // This is the button to clear formatting
              ]
          }
      });
      quill.on('text-change', function() {
        console.log('Content changed');
      });
    };
  });
}

The result is that i can see the quill editor, and I can type in the Quill.
The buttons are visible.

The issue is – if I click on Bold or Italic button , there is no effect. That is, I select the text, and I click on “bold”. At this point, the line console.log('Content changed'); is active, and I can see the output on console. But the text does not change.

I was looking is SO, and found this one. It says i need to initialize Quill. So I kept looking, and found this one.

Note that I am supplying the DOM element as suggested. But still nothing happens.

Please help. Thank you.

Using Javascript/Typescript to monkey patch a function defined within a constructor?

I’m looking to monkey patch a class in a Javascript/Typescript library that essentially looks like this:

class Monkey extends SomeOtherClass {

   constructor(param = {}) {

     // this is my target
     function someFunctionDefinedInsideConstructor() {
        // does stuff
     }

     // calls said function, also inside constructor
     someFunctionDefinedInsideConstructor();
   }
}

From what I gather it seems constructor things are notoriously difficult to access using javascript reflection.

Is there a way to somehow ovveride function someFunctionDefinedInsideConstructor and have it do something else? Or is this beyond what can be done with JS/TS reflection?

Nested async-await with promise all loops behaviour not understandable

i have created 2-3 nested loops in js , if you try to run my code below , iam not sure why why my log “one record processed !!” prints all in the ends & another log say(this duty is allready considered in split logic) is not printing at all.

i want to process duty one by one even in async mode , why i kept function async because in my real code i wil have some db query in inside those function.

   var crews = [{
    crewname: "vikrant",
    type: "trip1",
    Duty: [{
            dutyid: 0,
            flag: "s",
        },
        {
            dutyid: 1,
            flag: "s",
        },
        {
            dutyid: 2,
            flag: "v",
        },
    ],
    task: [{
        taskId: "task1",
    }, ],
}, ];
async function dutyHrsCalculation(data) {
    return await Promise.all(
        data.map(async (crew, index) => {
            crew.dutyHRS = [];
            crew.mergedDUTYIDS = [];
            await Promise.all(
                crew.Duty.map(async (duty, dindex) => {
                    console.log("loop starting here on crew duty id-->", duty.dutyid);
                    if (crew.mergedDUTYIDS.includes(duty.dutyid) == false) {
                        await isLondonCCDPpayable(crew, dindex);
                        console.log("one record processed !!");
                    } else {
                        console.log(
                            "this duty is allready considered in split logic ",
                            duty
                        );
                    }
                    return duty;
                })
            );
            return crew;
        })
    );
}
async function isLondonCCDPpayable(crew, dindex) {
        return new Promise(async (resolve, reject) => {
            let firstDuty = crew.Duty[dindex];
            let secondDuty = crew.Duty[dindex + 1];
            console.log("Two duties------>", firstDuty, secondDuty);
            if (secondDuty != undefined) {
                console.log(
                    "next/secondary  duty is not undefined hence checking split logic function & secondary duty  is ----->",
                    secondDuty
                );
                if (await checkForSplit(firstDuty, secondDuty)) {
                    //collecting ids so that we will never process the considered record again
                    crew.mergedDUTYIDS.push(firstDuty.dutyid);
                    crew.mergedDUTYIDS.push(secondDuty.dutyid);
                    console.log("two duties collected", crew.mergedDUTYIDS);
                    let obj = {
                        name: crew.crewname,
                        dutyIndex: dindex,
                        ids: firstDuty.dutyid + "-" + secondDuty.dutyid,
                    };
                    crew.dutyHRS.push(obj);
                } else {
                    console.log("else part of  split ---->");
                    let obj = {
                        name: crew.crewname,
                        dutyIndex: dindex,
                        ids: firstDuty.dutyid,
                    };
                    crew.dutyHRS.push(obj);
                }
            } else {
                console.log("default part if we dont have next duty in the array ---->", firstDuty);
                let obj = {
                    name: crew.crewname,
                    dutyIndex: dindex,
                    ids: "",
                };
                crew.dutyHRS.push(obj);
            }
            resolve(crew);
        });
    }
    (async () => {
        let result = await dutyHrsCalculation(crews);
        result.map((element, index) => {
            console.log("final result --->", element.dutyHRS);
        });
    })();
async function checkForSplit(firstDuty, secondDuty) {
    return new Promise(async (resolve, reject) => {
        console.log("inside split function-------->");
        let result = false;
        if (firstDuty.flag == "s" && secondDuty.flag == "s") {
            result = true;
        } else {
            result = false;
        }
        console.log("returning from split result--------->", result);
        resolve(result);
    });
}

    

Scroll Animation Works with Mouse Wheel but Auto-Scrolls on Laptop Trackpad

I have implemented a scroll animation where images and text change as the user scrolls. The scrolling behavior works perfectly when using a mouse wheel, but when I try to scroll using a laptop’s trackpad (or touchpad), the sections auto-scroll too quickly or erratically, making the experience inconsistent.

here is the code :


<style> 
  .container {
    position: relative;
    display: flex;
    flex-direction: column;
    max-width: 100%; 
    margin: 0 auto;
    height: 100%;
    min-height: 100vh;
    max-height: calc(100vh * 9);
    align-items: center;
    overflow-y: scroll;
    scroll-snap-type: y mandatory;
    scroll-behavior: smooth;
    scrollbar-width: none;
    -ms-overflow-style: none;
    padding: 0;
    -webkit-overflow-scrolling: touch;
    overscroll-behavior: none;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  }

  .container::-webkit-scrollbar {
    display: none;
  }

  .image-section {
    height: 100vh;
    width: 100%;
    position: relative;
    overflow: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    scroll-snap-align: start;
    scroll-snap-stop: always;
    transition: all 1s cubic-bezier(0.4, 0, 0.2, 1);
  }

  .image-wrapper {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
  }

  .image-wrapper img {
    height: auto;
    width: 95%;
    object-fit: contain !important;
    max-width: none;
    max-height: 95vh;
    background-color: #fff;
  }

  .text-container {
    display: flex;
    position: fixed;
    top: 40%;
    width: 1280px;
    margin: 0 auto;
    z-index: 3;
    overflow: visible;
  }

  .content {
    position: absolute;
    width: 80%;
    display: flex;
    flex-direction: column;
    padding: 0 2%;
    opacity: 0;
    pointer-events: none;
    transition: opacity 0.4s ease;
  }

  .content.active {
    opacity: 1;
    pointer-events: auto;
  }

  .number {
    font-size: 150px;
    font-weight: bold;
    color: #f6f6f6;
  }

  .description {
    font-size: 42px;
    font-weight: 500;
    color: #000;
  }
</style>

<div class="container" style="--speed: 6">
  <div class="text-container">
    <div class="content" data-index="0">
      <div class="number">01</div>
      <div class="description">Lorem ipsum dolor sit amet</div>
    </div>
    <div class="content" data-index="1">
      <div class="number">02</div>
      <div class="description">Consectetur adipiscing elit</div>
    </div>
    <div class="content" data-index="2">
      <div class="number">03</div>
      <div class="description">Sed do eiusmod tempor incididunt</div>
    </div>
  </div>
  <div class="image-container">
    <section class="image-section">
      <div class="image-wrapper">
        <img src="/assets/dummy_1.gif" alt="" />
        <div class="description">Lorem ipsum dolor sit amet</div>
      </div>
    </section>
    <section class="image-section">
      <div class="image-wrapper">
        <img src="/assets/dummy_2.gif" alt="" />
        <div class="description">Consectetur adipiscing elit</div>
      </div>
    </section>
    <section class="image-section">
      <div class="image-wrapper">
        <img src="/assets/dummy_3.gif" alt="" />
        <div class="description">Sed do eiusmod tempor incididunt</div>
      </div>
    </section>
  </div>
</div>

<script>
  document.addEventListener("DOMContentLoaded", function () {
    const container = document.querySelector(".container");
    const sections = document.querySelectorAll(".image-section");
    let currentIndex = 0;
    let isScrolling = false;
    
    function scrollToSection(index) {
      if (index < 0 || index >= sections.length || isScrolling) return;
      isScrolling = true;
      sections[index].scrollIntoView({ behavior: "smooth" });
      setTimeout(() => {
        currentIndex = index;
        isScrolling = false;
      }, 700);
    }
    
    container.addEventListener("wheel", function (event) {
      if (event.deltaY > 0) {
        scrollToSection(currentIndex + 1);
      } else {
        scrollToSection(currentIndex - 1);
      }
    });
  });
</script>

Adjusting the setTimeout delay to debounce the event.
Adding event.preventDefault() inside the wheel event listener, but this disables smooth scrolling entirely.
Checking event.deltaY values for finer control, but trackpad scrolling seems continuous rather than discrete like a mouse wheel.

Pyvis Graphs Dropdown Selector

I have two graphs generated by using pyvis. I want to display each graph when their name is selected from a dropdown menu. Each graph will have own datasets in the source code, is there a way to refer the datasets of selected graph in one file rather than having two separate full html code?

Below python code generates two graphs and one with a dropdown menu:

from pyvis.network import Network
import os

def create_graph_1():
    net = Network(notebook=False)
    net.add_node(1, label="Node 1")
    net.add_node(2, label="Node 2")
    net.add_edge(1, 2)
    net.write_html("graph1.html")

def create_graph_2():
    net = Network(notebook=False)
    net.add_node(3, label="Node 3")
    net.add_node(4, label="Node 4")
    net.add_node(5, label="Node 5")
    net.add_edge(3, 4)
    net.add_edge(4, 5)
    net.write_html("graph2.html")

def generate_html():
    html_content = """
    <!DOCTYPE html>
    <html>
    <head>
        <title>PyVis Graph Selector</title>
        <script>
            function changeGraph() {
                var selectedGraph = document.getElementById("graph-selector").value;
                document.getElementById("graph-frame").src = selectedGraph;
            }
        </script>
    </head>
    <body>
        <label for='graph-selector'>Choose a graph:</label>
        <select id='graph-selector' onchange='changeGraph()'>
            <option value='graph1.html'>Graph 1</option>
            <option value='graph2.html'>Graph 2</option>
        </select>
        <iframe id='graph-frame' src='graph1.html' width='800' height='600'     style='border:none;'></iframe>
    </body>
    </html>
    """
    with open("index.html", "w") as f:
        f.write(html_content)

if __name__ == "__main__":
    create_graph_1()
    create_graph_2()
    generate_html()
    print("Generated index.html")

The solutions I have found are creating separate html files for each graph and the main html displays each graph in a frame. I need all html codes and datasets in a single html.

One example dataset is as below:

                  nodes = new vis.DataSet([{"color": "#97c2fc", "id": 1, "label": "Node 1", "shape": "dot"}, {"color": "#97c2fc", "id": 2, "label": "Node 2", "shape": "dot"}]);
                  edges = new vis.DataSet([{"from": 1, "to": 2}]);

multiple summernote style cusing the error of 403

problem :

hello, i am using the AdminLte3 dashboard to design and summernote editor for the first time . in my setting section i am using summernote editor for add updateappmsg, privacy policy, terms and conds. , about us . in this form i am trying to send my data through ajax .

when i try to submit the more then one summernote editor values (with style) together then it is casing me the error of 403 (forbidden). without style it is adding the value perfectly . but when i try to add the values(with style) for only single summernote then it’ working fine . but one summernote is saved after that it having the same error in other even tho i tried to only update one editor . can someone pls help me ?

HERE IS MY CODE :

INDEX.BLADE.PHP

@extends('layouts.app')

@section('content')

<form id="formAppSetting" action="{{ route('app-settings.update') }}" method="POST" enctype="multipart/form-data">
    @csrf

    <div class="p-2 pb-4 fixed-search-seaction">
        <div class="d-flex justify-content-end align-item-center pr-4">
            <button type="submit"  id="save-btn" onmousedown="toggleButtonClicked(this)" onclick="validateForm()">
                <i class="fas fa-save pr-1"></i> Save Changes
            </button>
        </div>
    </div>

//other fields

<div class="px-3 pb-2 m-3 d-lg-flex" style="gap:20px">
    
        {{-- summernote1 section --}}
        <div>
            <div data-toggle="collapse" data-target="#updateAppMessageSettings" aria-expanded="false" aria-controls="updateAppMessageSettings">
                <h5>Update App Message</h5>
            </div>
    
            <div class="collapse" id="updateAppMessageSettings">
                <div class="pt-4">
                    <div class="form-group">
                        <textarea class="summernote" name="updateAppMessage">{{ $data->updateAppMessage ?? '' }}</textarea>
                    </div>
                </div>
            </div>
        </div>
    
        {{-- summernote2 section --}}
        <div>
            <div data-toggle="collapse"  data-target="#aboutSettings" aria-expanded="false" aria-controls="aboutSettings">
                <h5>About Us</h5>
            </div>
    
            <div class="collapse" id="aboutSettings">
                <div class="pt-4">
                    <div class="form-group">
                        <textarea class="summernote" name="aboutUs">{{ $data->aboutUs ?? '' }}</textarea>
                    </div>
                </div>
            </div>
        </div>

    </div>

    <div>

        {{-- summernote3 --}}
        <div>
            <div data-toggle="collapse"
                data-target="#privacyPolicySettings" aria-expanded="false" aria-controls="privacyPolicySettings">
                <h5>Privacy Policy</h5>
            </div>
    
            <div class="collapse" id="privacyPolicySettings">
                <div class="pt-4">
                    <div class="form-group">
                        <textarea class="summernote" name="privacyPolicy">{{ $data->privacyPolicy ?? '' }}</textarea>
                    </div>
                </div>
            </div>
        </div>
    
        {{-- summnernote4 --}}
        <div>
    
            <div data-toggle="collapse"
                data-target="#termsCondSettings" aria-expanded="false" aria-controls="termsCondSettings">
                <h5>Terms And Conditions</h5>
            </div>
    
            <div class="collapse" id="termsCondSettings">
                <div class="pt-4">
                    <div class="form-group">
                        <textarea class="summernote" name="termsCond">{{ $data->termsCond ?? '' }}</textarea>
                    </div>
                </div>
            </div>
        </div>
    
    </div>

</form>

<script>

function summnernote() {
        $('.summernote').each(function() {
            $(this).summernote({
                placeholder: 'Add the text...',
                tabsize: 2,
                height: 200,
                dialogsInBody: true,
                dialogsFade: false,
                disableDragAndDrop: true,
                tooltip: false,
                toolbar: [
                    // Customize the toolbar by removing the 'color' option which includes highlight
                    ['style', ['style']],
                    ['fontsize', ['fontsize']],
                    // ['color', ['color']],
                    ['font', ['bold', 'italic', 'underline', 'clear']],
                    ['fontname', ['fontname']],
                    ['para', ['ul', 'ol', 'paragraph']],
                    ['table', ['table']],
                    ['insert', ['link']],
                    ['view', ['fullscreen','help']]
                ],
                fontSizes: [ '11', '13', '15', '17', '19', '21', '25', '30', '36'],
                callbacks: {
                    onPaste: function (e) {
                        var bufferText = ((e.originalEvent || e).clipboardData || window.clipboardData).getData('Text');
                        e.preventDefault();
                        document.execCommand('insertText', false, bufferText);
                    }
                }
            });
        }); 
    }

function validateForm() {
        let isValid = true;
        const requiredFields = $('input[required]');
        let firstInvalidField = null;

        requiredFields.each(function() {
            if (!$(this).val()) {
                isValid = false;
                if (!firstInvalidField) {
                    firstInvalidField = $(this); // Store the first invalid field
                }
            }
        });

        if (!isValid && firstInvalidField) {
            // Open the collapse div of the first invalid field
            firstInvalidField.closest('.collapse').collapse('show');
            // Scroll to the first invalid field for better UX
            $('html, body').animate({
                scrollTop: firstInvalidField.offset()
            }, 500);
        }

        return isValid;
    }

</script>


@section('page-scripts')
<script>

    var data = @json($data);

    $(document).ready(function() {

        summnernote();

        if(!validateForm()){
        
            showAlert('error' , 'Please fill all the required field.');
            return false;
        
        } else {
            // Handle the confirmation button click
            $('#formAppSetting').on('submit', function(event) {
                event.preventDefault();


                let formData = new FormData(this);
                formData.append('_token', '{{ csrf_token() }}');

                for (var pair of formData.entries()) {
                    console.log(pair[0] + '========> ' + pair[1]);
                }

                $.ajax({
                    url: $(this).attr('action'),
                    type: 'POST', 
                    data: formData,
                    processData: false, 
                    contentType: false, 
                    success: function(response) {
                        showAlert('success', response.message);
                        $('#save-btn').prop('disabled', false);
                        $('#save-btn').text('Save Settings');

                        const appName = response.data.appName; // Assuming the response includes the updated app name
                        const placeholder = response.data.userPlaceholder;

                        if (appName) {
                            $('.app-name, .header-app-name').text(appName); // Adjust the selector to target your app name element
                            document.title = `${appName} Admin Panel`; // Update the page title if necessary
                        }

                        if (placeholder) {
                            $('link[rel="icon"]').attr('href', `{{ asset('storage') }}/${placeholder}`);
                        }

                    },
                    error: function(xhr) {
                        $('#save-btn').prop('disabled', false);
                        $('#save-btn').text('Save Settings');
                        var errorMessage = xhr.responseJSON?.message || 'An error occurred. Please try again.';
                        showAlert('error', errorMessage);

                        $('#formAppSetting')[0].reset();

                        $('.summernote').each(function() {
                            var textareaId = $(this).attr('name');
                            if (data[textareaId]) {
                                $(this).summernote('code', data[textareaId]); // Keep HTML content intact
                            }
                            
                        });

                        setInterval(function() {
                            // Reset checkbox values to default state
                            $('input[type="checkbox"]').each(function() {
                                $(this).prop('checked', $(this).prop('defaultChecked'));
                            });
                        }, 1300);
                    },
                });
            
            });

        }

    });
</script>
@endsection

@endsection

WEB.PHP

    Route::get('/app-settings', [AppSettingController::class, 'index'])->name('app-settings.index');
    Route::post('/app-settings-update', [AppSettingController::class, 'update'])->name('app-settings.update');

what i have tried

i tried everything i can console.log the from data also try adding the _token manually but nothing work but i couldn’t able to find what is the issue .

Javascript component not working when fired multiple times on one page

I am trying to turn javascript functionality into components. My code so far (reduced for clarity) is:

index.html

<div class="modal" data-component="cmpModal" id="addSetModal">Modal 1</div>
<div class="modal" data-component="cmpModal" id="workoutDateModal">Modal 2</div>

app.js

import cmpModal from "./components/cmp-modal";

export const componentScripts = {
    cmpModal: cmpModal,
}

document.addEventListener('DOMContentLoaded', () =>
{
    // find all elements with component attribute
    const componentElements = document.querySelectorAll('[data-component]');

    // iterate over all component elements
    for (const el of componentElements) {
        let componentName = el.getAttribute('data-component');

        // get the script that matches the component
        let componentScript = componentScripts[componentName];

        // if the script exists, fire the init
        if (typeof componentScript != 'undefined') {
            componentScript.init(el);
        }
    }
});

cmp-modal.js

const cmpModal = {
    component: null,

    /**
     * Initialise the component
     * @param element
     */
    init: function (element)
    {
        const _ = this;
        _.component = element;
        console.log(_);
    }
}

export default cmpModal;

The problem I am having is just with the cmp-modal.js file. As I have two modals on the page, I expect the console to log the component twice, one for each, but I expect the id in the log to be different. This appears to be the case

Closed console logs look correct

However, when I expand the logs, I see that both have taken on the ID of the last modal. the same goes with other properties. Both logs reflect the properties of the last modal.

Open console logs show the wrong ID

What am I doing wrong here? How can I keep each instance of the modal object isolated to just that one modal?

Why does it show me this error, do i need to install something?

const fs = require('fs');
const AdmZip = require('adm-zip');

//Path to the .bak file
const bakFilePath = 'C:UsersNiklaDocumentsAdventureWorksDW2022.bak';
//Path to the output .zip file
const zipFilePath = 'C:UsersNiklaDocumentszip';

//Read the .bak file
const bakBytes = fs.readFileSync(bakFilePath);

//Create a new zip archive
const zip = new AdmZip();
zip.addFile('file.bak', bakBytes);

//Write the zip file to disk
zip.writeZip(zipFilePath);

console.log(`Conversion complete: ${zipFilePath}`);

if i run this code i always get this error in te terminal
Error message in the image.

The result of the terminal

Node modules source files are not showing in browser source tab with vite config in react

I am working on migrating webpack to vite config in our react project.

But I am oberving a wierd issue, when I run the application locally on browser and tried to debug source files from node modules (from some other dependency package), I am not able to see the source code in that file but a plain html template like this:

<!DOCTYPE html>
<html lang="en">
<head>
<script type="module">
import RefreshRuntime from "/@react-refresh"
RefreshRuntime.injectIntoGlobalHook(window)
window.$RefreshReg$ = () => {}
window.$RefreshSig$ = () => (type) => type
window.__vite_plugin_react_preamble_installed__ = true
</script>
<script type="module" src="/@vite/client"></script>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Test</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/index.tsx"></script>
</body>
</html>

Does anyone aware of this? if so can you please provide a solution for it?

I want to see the source code of the typescript files which I was able to see with webpack previously.

How to always show content of HTML details tag?

The software I use to document my package produces a HTML structure similar to the one below:

<html>

<head>
  <script src="assets/custom.js" defer></script>
</head>

<body>
  <h1>My results</h1>
  <details>
    <summary>Show code</summary>

    <code class="language-julia">
a = [1,2,3]
a
</code>

    This is the code output, and should always remain visible

  </details>
  I am about something else...

</body>

</html>

How do I use JS in order to show everything inside details (independently of its open or closed nature) except code.language-julia that should remain with the normal select behaviour ?

SVG dimensions on window resize [D3.js]

I have started to create a heatmap chart with the help of D3.js.

So far everything works. My problem is that when the window is resized, my SVG element is no longer readable.

As an example, I render my chart with a large window, everything is great. enter image description here

When I reduce the size of my window, my chart is no longer readable. enter image description here

I guess my problem is that the size of the boxes etc, do not adjust dynamically. For this I probably have to use a resize function and not the viewBox attribute, right?

Therefor i found the following article, but I can’t manage to write a resize function for my case.

Can anyone help me with this?

King Regards

Jegor

                //Datasource
                const data1= [
                    {id: 1,group:"A",variable:"v1",value: 98},{id: 2,group:"A",variable:"v2",value:95},
                    {id: 3,group:"A",variable:"v3",value: 22},{id: 4,group:"A",variable:"v4",value:14},
                    {id: 5,group:"A",variable:"v5",value: 59},{id: 6,group:"A",variable:"v6",value:52},
                    {id: 7,group:"A",variable:"v7",value: 88},{id: 8,group:"A",variable:"v8",value:20},
                    {id: 9,group:"A",variable:"v9",value: 99},{id: 10,group:"A",variable:"v10",value:66},
                    {id: 11,group:"B",variable:"v1",value: 37},{id: 12,group:"B",variable:"v2",value:50},
                    {id: 13,group:"B",variable:"v3",value: 81},{id: 14,group:"B",variable:"v4",value:79},
                    {id: 15,group:"B",variable:"v5",value: 84},{id: 16,group:"B",variable:"v6",value:91},
                    {id: 17,group:"B",variable:"v7",value: 82},{id: 18,group:"B",variable:"v8",value:89},
                    {id: 19,group:"B",variable:"v9",value: 6},{id: 20,group:"B",variable:"v10",value:67},
                    {id: 21,group:"C",variable:"v1",value: 96},{id: 22,group:"C",variable:"v2",value:13},
                    {id: 23,group:"C",variable:"v3",value: 98},{id: 24,group:"C",variable:"v4",value:10},
                    {id: 25,group:"C",variable:"v5",value: 86},{id: 26,group:"C",variable:"v6",value:23},
                    {id: 27,group:"C",variable:"v7",value: 74},{id: 28,group:"C",variable:"v8",value:47},
                    {id: 29,group:"C",variable:"v9",value: 73},{id: 30,group:"C",variable:"v10",value:40},
                    {id: 31,group:"D",variable:"v1",value: 75},{id: 32,group:"D",variable:"v2",value:18},
                    {id: 33,group:"D",variable:"v3",value: 92},{id: 34,group:"D",variable:"v4",value:43},
                    {id: 35,group:"D",variable:"v5",value: 16},{id: 36,group:"D",variable:"v6",value:27},
                    {id: 37,group:"D",variable:"v7",value: 76},{id: 38,group:"D",variable:"v8",value:24},
                    {id: 39,group:"D",variable:"v9",value: 1},{id: 40,group:"D",variable:"v10",value:87},
                    {id: 41,group:"E",variable:"v1",value: 44},{id: 42,group:"E",variable:"v2",value:29},
                    {id: 43,group:"E",variable:"v3",value: 58},{id: 44,group:"E",variable:"v4",value:55},
                    {id: 45,group:"E",variable:"v5",value: 65},{id: 46,group:"E",variable:"v6",value:56},
                    {id: 47,group:"E",variable:"v7",value: 9},{id: 48,group:"E",variable:"v8",value:78},
                    {id: 49,group:"E",variable:"v9",value: 49},{id: 50,group:"E",variable:"v10",value:36},
                    {id: 51,group:"F",variable:"v1",value: 35},{id: 52,group:"F",variable:"v2",value:80},
                    {id: 53,group:"F",variable:"v3",value: 8},{id: 54,group:"F",variable:"v4",value:46},
                    {id: 55,group:"F",variable:"v5",value: 48},{id: 56,group:"F",variable:"v6",value:102}
                ];

            var selectedID = undefined;
            var selectedArray = []
            var i_region_static_id = "heatmap"
            var parentDiv = document.getElementById(i_region_static_id)
            var width_client = parentDiv.clientWidth;
            var i_height = 450;
            var selectedVar;
            var selectedGroup;
            var colorMidValue = 20;
            var showLegend = true;
            var margin
            if (showLegend){
                margin = {top: 0, right: 35, bottom: 25, left: 70};  
            }else{
                margin = {top: 0, right: 10, bottom: 25, left: 70};
            }
            const width = width_client - margin.left - margin.right;
            const height = i_height - margin.top - margin.bottom;  
            const labelGroup = "X-Label"
            const labelVars = "Y-Label"
            const color_start = "#f9f9f9"
            const colorEnd = "#6e69b3"
            const colorMid = "#bd326c"

            //Funktion zum Aufrunden der Y-Axis auf 5
            function updateColorAxis(a,b){
                if(b%5 !== 0){
                    b = b+(5-(b%5)); 
                }
                return [a,b];
            }
        
            //Funktion zum Berechnen der Anzahl der Ticks 
            function setColorAxisTicks(a,b){
                if(b%5 === 0){
                    return b/5;
                }
                return b/10;
            }

            //-----------------------------------------------------------------------------------
            // Anfügen von svg Elementen zu #heatmap
            const svg = d3.select('#' + i_region_static_id)
                            // Anfügen von svg an #heatmap
                            .append("svg")
                                .attr("id", "svg_" + i_region_static_id)
                                .attr("viewBox", `0 0 ${width_client + margin.right} ${parseInt(i_height) + margin.top + margin.bottom}`)
                        
            const g_area = d3.select("#svg_" + i_region_static_id)                           
                            // Anfügen einer Gruppe an das SVG Element
                            .append("g")
                                .attr("id", i_region_static_id + "_area")
                                .attr("transform", `translate(${margin.left},${margin.top})`);

            const g_nodes = g_area
                                    .append("g")
                                    .attr("id", i_region_static_id + "_nodes")
            //-----------------------------------------------------------------------------------
            // X-Skalierung
            const x_scale = d3.scaleBand()
                        .range([0, width])
                        .padding(0.01);

            // X-Achse erstellen
            const xAxis = g_area
                            .append("g")
                            .attr("id", i_region_static_id + "_x_axis")
            xAxis.append("g")
                .attr("id", i_region_static_id + "_x_axis_value")
                .attr("transform", `translate(0, ${height})`)
                .style("color", "rgba(0, 0, 0, 0.65)")
                .style("font-size", "16px")
                .style("font-family", "arial")

            // Einfügen xAxis Label
            xAxis.append("text")
                .attr("id", i_region_static_id + "_x_axis_label")
                .attr("x", width / 2)
                .attr("y", height + 50)
                .style("fill", "rgba(0, 0, 0, 0.65)")
                .style("font-size", "16px")
                .style("font-weight", "bold")
                .style("font-family", "sans-serif")
                .attr("text-anchor", "middle")
                .text(labelGroup);

            
            //-----------------------------------------------------------------------------------
            // Y-Skalierung
            const y_scale = d3.scaleBand()
                        .range([height, 0])
                        .padding(0.03);
                        
            // Y-Achse erstellen
            const yAxis = g_area
                            .append("g")
                            .attr("id", i_region_static_id + "_y_axis")
            yAxis.append("g")
                .attr("id", i_region_static_id + "_y_axis_value")
                .style("color", "rgba(0, 0, 0, 0.65)")
                .style("font-size", "16px")
                .style("font-family", "arial")

            // Einfügen yAxis Label
            yAxis.append("text")
                .attr("id", i_region_static_id + "_y_axis_label")
                .attr("y", - 45)         //Y ist hierbei die horizontale ausrichtung
                .attr("x", - height / 2) //X ist hierbei die vertikale ausrichtung
                .attr("transform", "rotate(-90)")
                .style("fill", "rgba(0, 0, 0, 0.65)")
                .style("font-size", "18px")
                .style("font-weight", "bold")
                .style("font-family", "sans-serif")
                .attr("text-anchor", "middle")
                .text(labelVars)

            //-----------------------------------------------------------------------------------     
            // ColorScale Legend
            const g_colorScale = g_area
                                    .append("g")
                                        .attr("id", i_region_static_id + "_colorLegend")

            // Erstelle yColorscale
            var yColorscale = d3.scaleLinear()
                            .range([height - 70, 0]);
            
            g_colorScale.append("g")
                        .attr("id" , i_region_static_id + "_colorscale_axis")
                        .attr("transform", `translate(${width + 30},${35})`)

            
            const g_def = g_colorScale.append("defs")
                        .append("linearGradient")
                            .attr("id", i_region_static_id + "_grad")
                            .attr("x1", "0%")
                            .attr("x2", "0%")
                            .attr("y1", "0%")
                            .attr("y2", "100%");

            g_colorScale.append("rect")
                        .attr("id", i_region_static_id + "_colorScale_legend")
                        .attr("x", width + 15)
                        .attr("y", 35)
                        .attr("rx", "4px")
                        .attr("width", 15)
                        .attr("height", height - 70)
                        .attr("stroke", "black")
                        .attr("stroke-width", "0.5px")
                        .attr("text-anchor", "middle")
                        .style("fill", "url(#"+ i_region_static_id + "_grad)");

            //-----------------------------------------------------------------------------------
            //Erstellen eines Tooltip
            const tooltip = d3.select("#" + i_region_static_id)
                .append("div")
                    .attr("id", i_region_static_id + "tooltip")
                    .style("position", "absolute")
                    .style("visibility", "hidden")
                    .style("background-color", "white")
                    .style("border", "solid")
                    .style("border-width", "2px")
                    .style("border-radius", "10px")
                    .style("padding", "5px");

            const dsad = d3.select("#" + i_region_static_id)
                .append("div")
                    .attr("id", i_region_static_id + "tooltip")
                    .style("position", "absolute")
                    .style("visibility", "hidden")
                    .style("background-color", "white")
                    .style("border", "solid")
                    .style("border-width", "2px")
                    .style("border-radius", "10px")
                    .style("padding", "5px");

            const mouseover = function(event,d) {
                tooltip
                    .style("visibility", "visible")
                d3.select(this).select("." + i_region_static_id + "_node")
                    .style("stroke", "black") 
                    .style("stroke-width", "2px") 
            };

            const mousemove = function(event,d) {
                tooltip
                    //.text("Wert: " + d.value)
                    .html("Wert: " + d.value + "<br>Group: " + d.group + "<br>Series: " + d.variable)
                    .style("left", (event.offsetX + 20) + "px")
                    .style("top", (event.offsetY + 95) + "px")
            };

            const mouseleave = function(d) {
                tooltip.style("visibility", "hidden")
                d3.select(this).select("." + i_region_static_id + "_node")  
                .style("stroke", "none")
            };

            const click = function(d, i) {
                var clickedID = i.id

                if (event.ctrlKey) {
                    if (!selectedArray.includes(clickedID)){
                        if (selectedArray.length === 0){
                            svg.selectAll("." + i_region_static_id + "_node_grp").style("opacity", 0.2)
                        }
                        selectedID = clickedID; //Single Click
                        selectedArray.push(clickedID);   // Multiple Click 
                        d3.select(this).style("opacity", 1)
                    }else{
                        svg.selectAll("." + i_region_static_id + "_node_grp").style("opacity", 1)
                        
                        selectedArray = [];
                    }
                }else{
                    selectedArray = [];
                    if (clickedID != selectedID){
                        selectedID = clickedID;
                        selectedArray.push(clickedID);

                        svg.selectAll("." + i_region_static_id + "_node_grp").style("opacity", 0.2)
                        d3.select(this).style("opacity", 1)
                    }else{
                        svg.selectAll("." + i_region_static_id + "_node_grp").style("opacity", 1) 
                        selectedID = undefined;
                    }
                };
            };
            
            //-----------------------------------------------------------------------------------               
            // Funktion für das Create, Update or Delete der D3 nodes
            function update_heatmap(data){
                const myId = data.map(function(d){return d.id})
                const myGroups = data.map(function(d){return d.group})
                const myVars = data.map(function(d){return d.variable})
                const value = data.map(function(d){return d.value})
                const extent = d3.extent(data, function(d){;return d.value}); 
                var colorArrayValue = updateColorAxis(extent[0], extent[1])
                colorArrayValue.push(colorMidValue)
                colorArrayValue.sort(function(a, b){return a - b});

                function longestStringReduce(arr) {
                    return arr.reduce((a, b) => a.length < b.length ? b : a, "");
                } 
                console.log(longestStringReduce(myGroups))

                //----------------------------------------------------------------------------------- 
                // Dynamisches Update der X-Achse
                const xAxisGroup = d3.select("#" + i_region_static_id + "_x_axis_value")
                x_scale.domain(myGroups)
                const xAxisCall = d3.axisBottom(x_scale)
                xAxisGroup.call(xAxisCall);

                //----------------------------------------------------------------------------------- 
                // Dynamisches Update der Y-Achse
                const yAxisGroup = d3.select("#" + i_region_static_id + "_y_axis_value")
                y_scale.domain(myVars)
                const yAxisCall = d3.axisLeft(y_scale)
                yAxisGroup.call(yAxisCall);

                const myColor = d3.scaleLinear()
                    .range([color_start, colorMid, colorEnd])
                    .domain(colorArrayValue)
                
                /*Returns Black/White depending on node color*/
                function calculateContrast(values){
                    var rgb = values.match(/d+/g);
                    // Wenn rgb leer, dann das erste sonst das zweite
                    const brightness = (rgb != undefined) ? Math.round(((parseInt(rgb[0]) * 299) + (parseInt(rgb[1]) * 587) + (parseInt(rgb[2]) * 114)) /1000) : 0;
                    return brightness < 150 ? 'white' : 'black'   
                }
                
                //-----------------------------------------------------------------------------------  
                // ColorScale Legend
                const GradColors = [myColor(updateColorAxis(extent[0], extent[1])[1]), myColor(colorMidValue), myColor(updateColorAxis(extent[0], extent[1])[0])];//NEU
    
                // Fügt scales zur Achse hinzu
                const yAxisColorGroup = d3.select("#" + i_region_static_id + "_colorscale_axis")
                
                yColorscale.domain(updateColorAxis(extent[0], extent[1]))

                const yAxisColorCall = d3.axisRight(yColorscale)
                                            .ticks(setColorAxisTicks(updateColorAxis(extent[0], extent[1])[0], updateColorAxis(extent[0], extent[1])[1]))
                yAxisColorGroup.call(yAxisColorCall);

                g_def.selectAll(i_region_static_id + "stop")
                    .data(GradColors)
                    .enter()
                    .append("stop")
                    .style("stop-color", function(d){return d;})
                    .attr("offset", function(d,i){
                        return 100 * (i / (GradColors.length - 1)) + "%";
                })

                //-----------------------------------------------------------------------------------  
                // Create, Delete and Update
                const rect_nodes = g_nodes.selectAll("." + i_region_static_id + "_node_grp")
                                        .data(data)

                const rect_node_grp = rect_nodes.enter()
                                                .append("g")
                                                /*each() für Create Sektion*/
                                                /*Mit der Each() wird alles in der gruppe geupdated*/
                                                .each(function(d, i) {
                                                //Append Elemente an g
                                                    d3.select(this).append('rect')   
                                                        .style("fill", function(d) {return myColor(d.value)}) 
                                                    d3.select(this).append('text')
                                                })
                                                .merge(rect_nodes)
                                                .attr("class", i_region_static_id + "_node_grp")
                                                //jedes Rect eine ID zu ordnen
                                                .attr("id", function (d){return i_region_static_id + "_node_grp_" + d.id})
                                                .attr("group", function(d) {return d.group})
                                                .attr("variable", function(d) {return d.variable})
                                                .attr("value", function(d) {return d.value})
                                                .on("mouseover", mouseover)
                                                .on("mousemove", mousemove)
                                                .on("mouseleave", mouseleave)
                                                .on("click", click)
                                                .style("cursor", "pointer")
                                                /*each() für Update Sektion*/
                                                .each(function(d, i) {
                                                    // Update meine Elemente in g tag
                                                    d3.select(this).select('rect')
                                                        .attr("class", i_region_static_id + "_node")
                                                        .transition()
                                                        .delay(50)
                                                        .attr("x", function(d) {return x_scale(d.group)})
                                                        .attr("y", function(d) {return y_scale(d.variable)})
                                                        .attr("width", x_scale.bandwidth())
                                                        .attr("height", y_scale.bandwidth())
                                                        .style("fill", function(d) {return myColor(d.value)})

                                                    d3.select(this).select('text').attr("class", i_region_static_id + "_label")
                                                        .transition()
                                                        .delay(50)
                                                        .attr("x", function(d) {return x_scale(d.group)})
                                                        .attr("y", function(d) { return y_scale(d.variable)})
                                                        .attr("dx", x_scale.bandwidth() / 2)
                                                        .attr("dy", y_scale.bandwidth() / 2)
                                                        .attr("text-anchor", "middle")
                                                        .attr("dominant-baseline", "central")
                                                        .attr("fill", function(d){return calculateContrast(myColor(d.value))})
                                                        .style("font-size", "14px")
                                                        .style("font-family", "sans-serif")
                                                        .text(function(d) {return (d.value)})
                                                    })

                rect_nodes.exit().remove()
            }
            
            //-----------------------------------------------------------------------------------               

            update_heatmap(data1)
<!DOCTYPE html>
<html>             
    <head>              

        <meta charset="utf-8" />   
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />    
        <title> 1.Grundgerüst </title>
    </head>
    <body>             
        <div id="heatmap"></div>
        <script src="https://d3js.org/d3.v7.js" charset="utf-8"></script>
    </body>
</html>

Unable to bundle @middy/core when bundling with esbuild for aws-lambda node js

I am trying to bundle a nodejs code for aws lambda using es build, i am using the following script to produce the bundle :-

 esbuild.build({
      entryPoints: [path.join(parentDirectory, dir, "index.ts")],
      outdir: path.join(__dirname, "build", dir),
      // minify: true,
      format: "cjs",
      target: "es2020",
      packages: "bundle",
      platform: "node",
    });

And the handler i am trying to bundle looks like this:-

  import middy from "@middy/core";
import jsonBodyParser from "@middy/http-json-body-parser";
import httpErrorHandler from "@middy/http-error-handler";
import validator from "@middy/validator";

const handler = async (event: any, context: any) => {
  console.log(event);

  return {
    statusCode: 200,
    body: JSON.stringify({ message: "handler" }),
  };
};

export const userHandler = middy()
  .use(jsonBodyParser())
  .use(httpErrorHandler())
  .handler(handler);

After deploying the code via CDK , when i try to execute the lambda, it fails with following error:-

2025-02-14T10:37:02.529Z    undefined   ERROR   Uncaught Exception  
{
    "errorType": "Runtime.ImportModuleError",
    "errorMessage": "Error: Cannot find module '@middy/core'nRequire stack:n- /var/task/index.jsn- /var/runtime/index.mjs",
    "stack": [
        "Runtime.ImportModuleError: Error: Cannot find module '@middy/core'",
        "Require stack:",
        "- /var/task/index.js",
        "- /var/runtime/index.mjs",
        "    at _loadUserApp (file:///var/runtime/index.mjs:1087:17)",
        "    at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1119:21)",
        "    at async start (file:///var/runtime/index.mjs:1282:23)",
        "    at async file:///var/runtime/index.mjs:1288:1"
    ]
}

It is as if it did not inline the middy package into the outfile, which i hoped the packages: "bundle" would do…
Am i doing something wrong ?

How to get HTML from PartialViewResult?

I’m trying to get html from PartialViewResult which is in class, but when I get the result in post I get a regular object. If I return PartialViewResult without class then everything works and I get html code. I will present part of the code where this problem occurs. Why does it happen that PartialViewResult returns a different result???

A class in which I have multiple PartialViewResult

public class MultiPartialViewResult
{
    public PartialViewResult? Options { get; set; }
    public PartialViewResult? Products { get; set; }
}

a method that receives a request and returns the result

[HttpPost]
public object TestPage(string date)
{
    MultiPartialViewResult multiPartial = new MultiPartialViewResult();

    var model = products.Where(x => x.ProducingCountry == "PL").ToList();
    var partial = PartialView("_ViewTestPage", model);

    multiPartial.Products = partial;

    return multiPartial;
}

javascript ajax, in $(‘#testPage’).html(result.Products); I have to insert the result as html code, but I get an objectenter image description here

$.ajax({
        method: 'post',
        url: location.pathname,
        data: "data",
        success: function (result) {
            $('#testPage').empty();
            console.log(result);
            console.log(result.products);
            $('#testPage').html(result.products);
        }
    })

and when I return the PartialViewResult itself directly, I get the html I need

[HttpPost]
public IActionResult TestPage(string date)
{
    var model = products.Where(x => x.ProducingCountry == "PL").ToList();
    return PartialView("_ViewTestPage", model);
}

javascript

$.ajax({
        method: 'post',
        url: location.pathname,
        data: "data",
        success: function (result) {
            $('#testPage').empty();
            console.log(result);
            $('#testPage').html(result);
        }
    })

resultenter image description here

Callback which will be called when DOM element been MOUNTED to document with pure JavaScript

parent.appendChild(child) does not mean that child has been mounted to the document because the parent could be not mounted:

const parent = document.createElement("div"); // Created but not mounted
const child = document.createElement("span") // Created but not mounted
parent.appendChild(child); // Child has been appended to parent but both of them not mounted

I need to know when the child has been mounted by the callback.

document.querySelector("body").appendChild(parent);
// Well, it has been mounted now, but in my case I don't know when exactly is will be monted

As far as I has analyzed the topics Detect when Element attached to DOM in javascript it does not cover the actual mounting to the document. The MutationObserver has been recommended but no code samples which I could check does it satisfies to my case.

Use Case: Text Area Auto Resizing

The following text area resizing solution (source) will not work if the textarea is not mounted yet because in this case the scrollHeight will be 0:

document.querySelectorAll("textarea").forEach(function(textarea) {
  textarea.style.height = textarea.scrollHeight + "px";
  textarea.style.overflowY = "hidden";

  textarea.addEventListener("input", function() {
    this.style.height = "auto";
    this.style.height = this.scrollHeight + "px";
  });
});

To make it work, the the anonymous function inside forEach must be called when the text area actually has been mounted to the document.

Cannot read properties of undefined (reading ‘validate’) [closed]

I am getting testcases failur after upgrading from angular 10 to 11

    TypeError: Cannot read properties of undefined (reading 'validate')
        at isValidatorFn (http://localhost:9876/_karma_webpack_/vendor.js:184440:21)
        at http://localhost:9876/_karma_webpack_/vendor.js:184452:12
        at Array.map (<anonymous>)
        at normalizeValidators (http://localhost:9876/_karma_webpack_/vendor.js:184451:21)
        at composeValidators (http://localhost:9876/_karma_webpack_/vendor.js:184475:40)
        at coerceToValidator (http://localhost:9876/_karma_webpack_/vendor.js:185477:37)
        at FormControl.setValidators (http://localhost:9876/_karma_webpack_/vendor.js:185695:35)
        at setUpValidators (http://localhost:9876/_karma_webpack_/vendor.js:185204:13)
        at setUpControl (http://localhost:9876/_karma_webpack_/vendor.js:185127:3)
        at FormGroupDirective.addControl (http://localhost:9876/_karma_webpack_/vendor.js:189401:7)
    Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'validate')

any solutions for this?