CSS transform-origin on SVG not working as expected

I’m trying to create a clickable map. The idea is that clicking on a region starts a zoom animation pointed to that specific area.
So far i managed to calcuate the center of each SVG rectangle that contain a region with getBBox(). This is visualized as a purple circle

Now I’m having trouble understanding how to scale on specific coordinates, which based on my idea are the same calculated in the previous step.
The code below basically updates the transform-origin style property of the<g id="italy" class="c"> group element every time a different <path> is clicked.

Question is how to scale an SVG and center on specific coordinates?
Or How to scale a SVG and center only a path with specific ID?

Code on Jsfiddle

Ninja Forms front-end.js long task in Chrome Performance impacting Core Web Vitals

In Core Web Vitals, we have high Total Blocking Time and it seems the main culprit is this script in Ninja Forms. If it is commented out, Ninja Forms does not load – obviously not a solution. But I would love to figure out a way to stop it from impacting the load performance.

This seems to be the specific code in front-end.js causing it:

//Simulate async callback;
    if (forceSync) {
        main(undef, deps, callback, relName);
    } else {
        //Using a non-zero value because of concern for what old browsers
        //do, and latest browsers "upgrade" to 4 if lower value is used:
        //http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#dom-windowtimers-settimeout:
        //If want a value immediately, use require('id') instead -- something
        //that works in almond on the global level, but not guaranteed and
        //unlikely to work in other AMD implementations.
        setTimeout(function () {
            main(undef, deps, callback, relName);
        }, 4);
    }

    return req;

Code
Performance

javascript: http-response into frontend

I have a programm in React that

does a http-request during componentWillMount and sets a variable
response on the response of the http-request

var response = "";
class App extends Component{
  componentWillMount(){
     var myRequest = new XMLHttpRequest(),
        method = 'GET',
        url = //url; 
      myRequest.open(method, url, true);
      myRequest.send();
      myRequest.onload = function() {
        response = myRequest.response;
    };

and that displays the response in the method render() by using the “response” variable.

However, this is not working -> the initial value “” is displayed. The HTTP-Request is working (tested), the HTTP-Response is recieved and correct(also tested), so perhaps the program is just not waiting untill the http request is done and instead takes the initial value for “response”.

How can i fix this, i.e. how can i enforce that response is set to the HTTP-response?

JS update the value of the filtered object using array.filter

So I need to perform two actions 1) filter my array and 2) update the unfiltered values.
currently, I am doing it this way and it works fine.

let installData = state.installData.filter((item) => {
        return item.sensor !== action.data.sensor;
      });

      installData = installData.map((item) => {
        return { ...item, asOfDate: false };
      });

however, I am doing operations here and was wondering if there is a more efficient way to update the value of my item directly inside the filtred method without having to use map

React-not displaying props

I am very new to react and am trying to use a geocoding API to display the city and latitude of a given location. For now, I’ve hard coded the location into the API call which I will change later, but when I call props.city and props.lat, nothing displays. Why is this? I can show the API more in detail if needed as well!

App.Js

import { render } from '@testing-library/react';
import React from 'react';
import './App.css';
import Weather from './components/Header';
import Location from './components/Location';


class App extends React.Component {
  constructor() {
    super();
    this.state = {
      city: undefined,
      lat: undefined
    };
  }

  getLocation = async() => {
    const api_call = await fetch(
      'http://api.openweathermap.org/geo/1.0/direct?q=London&limit=1&appid=a1ff59fe7bfbac4b4a1bbc981c33e490'
      );
    const response = await api_call.json();
    
    this.setState({
      city: response.name,
      lat: response.lat
    });

    console.log(response);
  };
  
  componentDidMount() {
    this.getLocation();
  }

  render(){
    return (
      <div className = "container">
        <div className = "Title">
          <Weather/>
        </div>
        <div className = "Input">
          <Location
            city = {this.state.city}
            lat = {this.state.lat}
          />
        </div>
      </div>
    );
  }
}
export default App;

Location.Js

import {useState} from "react"

const Location = props => {
    return (
        <div className = "container">
        <div>
            Address
            <input id = "address">
            </input>
        </div>
        <div>
            City
            <input id = "city">
            </input>
        </div>
        <div>
            Zip Code
            <input id = "zipcode">
            </input>
        </div>
        <div>
            <button id = "Submit"> 
            Submit
            </button>
        </div>
        <div>
            City and Lat: 
            {props.city}: {props.lat}
        </div>
    </div>
    );
};
export default Location;

Django forms integration with legacy UI component library

I’m working on a Django project and would like to incorporate a proprietary UI component library that my company created into my application. The library has CSS utility classes for positioning, font, margin, padding, etc. (similar to Tailwind or Bootstrap). These are simple enough to put into a Django template without overhead.

However, I’m struggling with using the library’s form/input components (which rely on JSON data as well as HTML).

        # html 
        <custom-select
            id="multiple-select-example"
            label="State"
            placeholder="Choose your state."
            multiple
        ></custom-select>

        # js 
        var multipleSelect = document.getElementById("multiple-select-example");

        multipleSelect.options = [{
            text: "Pennsylvania",
            value: "PA"
        }, {
            text: "California",
            value: "CA"
        }, {
            text: "Texas",
            value: "TX"
        }];

In a vacuum, it’s easy enough to use Django’s “json_script” tag to load JSON directly into the ‘.options’ and process the user’s data input in JS. But I feel like this misses out on some of the benefits of using Django’s built-in Forms (validation, serialization, etc.). How do I get the best of both worlds? Do I have to create custom form fields in Django? Or custom widgets with media assets? I don’t know what to do, everything I do is messy.

Please help.

Vue.js: How to retrieve css var under

I’m using chartJs to add a Doughnut chart on my app, but I need to setup it’s color under <script> and I’d like to get the color from theme/variables.css .

In the code below, I have a hardcoded backgroundColor, but I’d like to get it from --ion-color-secondary and --ion-color-secondary-contrast instead. How can I achieve that?

Here is the code:

<template>
  <Doughnut
    :chart-data="chartData"
    :chart-options="chartOptions"
  /> 
</template>

<script lang=ts>
import { defineComponent, PropType } from 'vue'

import { Doughnut } from 'vue-chartjs'
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  ArcElement,
  CategoryScale,
  Plugin
} from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, ArcElement, CategoryScale)

export default defineComponent<{fastdata: any}>({
  name: 'MrProgress',
  components: {
    Doughnut
  },
  inject: ["fastdata"],
  setup() {
    const chartOptions = {
      responsive: true,
      maintainAspectRatio: true,
      cutout: "90%",
      borderWidth: 0,
    }
    return {
        chartOptions,
    };
  },
  computed: {
    chartData() {
      const pts = this.fastdata.user.pts;
      const missing = this.fastdata.user.proximo_nivel - pts;
      return {
        datasets: [
          {
            backgroundColor: ['#41B883', '#e4e0d8'],
            data: [pts, missing]
          }
        ]
      }
    }
  }
})
</script>

Not able to understand how tag value is included from jsp page to js file

I am facing a problem where I have button in jsp page if i click it then it opens the dialogue and for the first time I am opening it , it shows the title of the dialogue box but from the second time onwards it doesnt show the title of dialogue.. I just started working on javascript and jsp , here I need a little help to understand where this value is coming from ,

**if($('#add-meeting-time').size() == 0)
                    $('body').append('<div id="add-meeting-time" />');**

How #add-meeting-time tag value is coming from jsp and why it is fetching the tag value add-meeting-time from jsp first time and not from the second time. I have added the code below.
please have a look and help
thanks in advance.

function addMeetingTime(caseId, passedds) {
    showOverlay();
    $.ajax({        
        url :   'case/RepairPro_addInputAgreeMeetingEvent?passedds='+passedds,
        type :  'get',
        data :  'cid=' + caseId + "&t=" + Math.random(),
        success :    function(data) {
            if($('#add-meeting-time').size() == 0)
                $('body').append('<div id="add-meeting-time" />');
            $('#add-meeting-time').html(data);
            
            $( "#add-meeting-time" ).dialog({
                autoOpen: false,
                modal: true,
                width:650,
                buttons: {
                    action: {
                        text: getText('save'),
                        click: function() {
                            disableDialogButton();
                            $('#add-meeting-time form').submit();
                        }
                    },
                    cancel: {
                        text: getText('cancel'),
                        click: function() {
                            $( this ).dialog( "close" );
                        }
                    }
                },
                create: function() {
                    var datepickerSettings = {minDate: 0};
                    if (getConfig('isDisplayTimezone')) {
                        datepickerSettings = {}
                    }

                    if(getConfig('isCalendarModularEnabled')) {
                        if(localMember.myrole > parseInt(getGlobal('AUTH2'))) {
                            $(this).parent().find('.ui-dialog-title').before($("<a href='javascript:void(0);' onclick='addMeetingTimeCalendar("" + passedds + "", " + caseId + ");' title="" + getText('calendar_view') + "" style='float:left; margin-right:1em;' class='ui-icon extra-dialog-button'></a>")
                            .button({icons:{primary: "ui-icon-calendar"},text: false}));
                        }
                        else {
                            $(this).parent().find('.ui-dialog-title').before($("<a href='javascript:void(0);' onclick='addPersonalMeetingTimeCalendar("" + passedds + "", " + caseId + ");' title="" + getText('calendar_view') + "" style='float:left; margin-right:1em;' class='ui-icon extra-dialog-button'></a>")
                            .button({icons:{primary: "ui-icon-calendar"},text: false}));
                        }
                    }

                    $(this).find('.datepicker').datetimepicker(datepickerSettings);
                    showTaskError(this, 'refreshCaseMessagesPage()');
                    
                    initTeamMemberSelect();         
                },
                open: function() {
                    $('select[id=add-meeting-member] option:eq(1)').attr('selected', 'selected');
                    $('select[id=add-meeting-member] option:eq(0)').attr('selected', 'selected');
                },
                close: function() {
                    $( this ).dialog( "destroy" ).remove();
                }
            });
            $( '#add-meeting-time' ).dialog( 'open' );
        }



    });
}

Texture mapping not working in Particle material in three.js

I am trying to create a space warp particle effect with three js but ran on a problem. The particle created is cubical, but I want it to be spherical. I loaded a circle png and mapped it to the particle material but it doesn’t work.

function init() {

  const renderer = new THREE.WebGLRenderer({
    antialias: true,
  });
  renderer.setSize(innerWidth, innerHeight);
  const app = document.getElementById("app");
  app.appendChild(renderer.domElement);

  // setup camera
  const camera = new THREE.PerspectiveCamera(
    60,
    innerWidth / innerHeight,
    1,
    1000
  );
  camera.position.set(0, 0, 1);
  camera.rotation.x = Math.PI / 2;

  const scene = new THREE.Scene();

  const starGeo = new THREE.BufferGeometry();
  const starCount = 6000;
  const vertices = new window.Float32Array(starCount * 3);
  starGeo.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
  const starsArr = [];

  for (let i = 0; i < starCount * 3; i += 3) {
    vertices[i] = Math.random() * 600 - 300;
    vertices[i + 1] = Math.random() * 600 - 300;
    vertices[i + 2] = Math.random() * 600 - 300;
    if (i % 3 === 0) {
      starsArr.push({
        velocity: 0,
        acceleration: 0.02,
      });
    }
  }

  starGeo.attributes.position.stars = starsArr;
 


// link to yellow circle 
 const starTexture = new THREE.TextureLoader().load("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRHU59FFoWzbzpl_37EPznha05psUWXZJqeXDK_57OXhRCuB6IYMamNujWbewVL4CAYuMM&usqp=CAU"); 
  
  // using white circle does nothing, gives blank screen, even while using local image
 /*  const starTexture = new THREE.TextureLoader().load("https://toppng.com/uploads/preview/white-circle-png-new-moon-phase-drawi-11563654400bdrw3yigxk.png");*/
  
  
  const material = new THREE.PointsMaterial({
   // size: 0.7,
     size: 5,
    map: starTexture,
     transparent: true,
  });

  const stars = new THREE.Points(starGeo, material);

  scene.add(stars);

  window.addEventListener("resize", () => {
    renderer.setSize(innerWidth, innerHeight);
    camera.aspect = innerWidth / innerHeight;
     camera.updateProjectionMatrix()
  });

  
  
  animate();

  function update() {
    const position = starGeo.getAttribute("position");
    const { array } = position;

    for (let i = 1; i < array.length; i += 3) {
      const _i = parseInt(i);
      const j = Math.floor((_i - 1) / 3);

      position.stars[j].velocity += position.stars[j].acceleration;
      array[i] -= position.stars[j].velocity;
      if (array[i] < -200) {
        array[i] = 200;
        position.stars[j].velocity = 0;
      }
    }

    stars.rotation.y += 0.01;
  }

  function animate() {
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
   // update();

    starGeo.getAttribute("position").needsUpdate = true;
  }
}

init();
*{
  box-sizing: border-box;
}

body{
  margin: 0;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="icon" type="image/svg+xml" href="favicon.svg" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Vite App</title>
  </head>
  <body>
    <div id="app"></div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
  </body>
</html>

I also have made codepen for this here > https://codepen.io/exxnnonymous/pen/rNJyYwx

Why web app is freezing forever when it uses 100% CPU for a long time [closed]

I’m interesting why web app is freezing forever when it uses 100% CPU for a long time but when performance monitoring shows that CPU is low app is still freeze. For example canvas that render 1000 rows uses 100% and I have a little freezes but if I will render 4000 rows my app freezes forever even when I see that CPU is 13% for example. CPU started to skip operations and browser waits respond from CPU ?

I cant put echartinstance into data In vue 3

I am using Vue 3 and Echart. The function was that when options were detected to be changed, the chart will update accordingly.

<template>
  <div ref="theChart" :style="{ height: '400px' }"></div>
</template>

<script lang="ts">
import { defineComponent, inject } from "vue";
import echarts from "echarts";
import * as _ from "lodash";

type EChartsOption = echarts.EChartsOption;

export default defineComponent({
  name: "LineChart",
  components: {},
  setup() {
    const echartsModule = inject<typeof echarts>("echarts");
    return {
      echartsModule,
    };
  },
  props: {
    options: {
      type: Object,
      required: true,
    },
  },
  mounted() {
    this.drawChart(this.options);
  },
  watch: {
    options: {
      handler(newOptions, oldOptions) {
        if (!_.isEqual(oldOptions, newOptions)) {
          console.info('hello')
          this.drawChart(newOptions);
        }
      },
      deep: true,
    },
  },
  methods: {
    drawChart(options: EChartsOption) {
      if (this.echartsModule) {
        const chartElement = this.$refs.theChart as HTMLElement;
        const chart = this.echartsModule.init(chartElement, undefined, {
          renderer: "svg",
        });
        chart.setOption(options, true);
      }
    },
  },
});
</script>

But I got the following “warning” but it works fine, I don’t understand the meaning of itWarning

Of course, I tried to put this.echartsModule.init(XXXX) into a component data. But I got the following error when I clicked on the legend of the chart https://github.com/apache/echarts/issues/14198 That is why I used to put this.echartsModule.init(XXXX) into const as zhenghaiyang said.
Do you have a better solution for me? Thanks in advance!

Implementing an auto-grader for user’s submission of React applications

I am currently trying to work on an app that tests user’s submission of react applications after providing a certain set of rules of how the app should function/ look like, but I am stuck on understanding how i can implement a function to where when student’s ‘submit’ their application on my website, how i can have like an auto-grader grade their submission right away when they hit submit and the user can see their score right away and try for a resubmission if they are not pleased with their score.

Would cypress be a good option for this or is something else that is already well-developed for auto-grading student’s applications/ code?

What I have found:

-codePost – An application used by universities to auto-grade student’s code that they submit

-cypress – Tests Frontend functionality of an application but i do not want to recreate the wheel if another application covers frontend application testing w/o coding but simple drag and drop features maybe?

Vue JS how to create array of strings from FormulateInput

I’m using below FormulateForm to have input field with the submit button:

<div class="col-12 col-md-3">
  <FormulateInput
  name="product_codes"
  label="Style number"
  placeholder="Style number"
  />
</div>

<div class="col-12 col-md-3">
  <button
    type="button"
    class="btn btn-primary"
    @click="syncProducts"
  >
    Sync
  </button>
</div>

I want to sent this input data to BE as an array:

<script>

export default {
  name: 'SyncProducts',
  data() {
    return {
      styleCodes: [],
    }
  },
}
</script>

But with this code, instead of Array of String, it sends it as a String.

Is there any way to let website thumbnail changes automatically and randomly every second from a facebook comment to an other?

I need important! somehow to let my website thumbnail changes in everytime typing the URL in a comment on facebook, and must chnage automatically and randomly every second from a thumbnail to another (I’ve about 30 image to use for switching…)

any JavaScript or pure PHP script using Facebook devs?
any helpful article or tutorial?

Many thanks <3

ArcGIS JS and Google Charts JS not working together

So I recently encountered a problem where I load both ArcGIS scripts and Google Charts scripts. I’m building out a website where I need both to work on the same page. However, I haven’t been able to come up with a solution.

My code is simple and as follows:

<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<script src="https://js.arcgis.com/4.23/" defer></script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>

<div id="sankey_basic" style="width: 900px; height: 300px;"></div>

<script>
$(document).ready(function(){

  google.charts.load('current', {'packages':['sankey']});
  google.charts.setOnLoadCallback(drawChart);

  function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'From');
    data.addColumn('string', 'To');
    data.addColumn('number', 'Weight');
    data.addRows([
      [ 'A', 'X', 5 ],
      [ 'A', 'Y', 7 ],
      [ 'A', 'Z', 6 ],
      [ 'B', 'X', 2 ],
      [ 'B', 'Y', 9 ],
      [ 'B', 'Z', 4 ]
    ]);

    // Sets chart options.
    var options = {
      width: 600,
    };

    // Instantiates and draws our chart, passing in some options.
    var chart = new google.visualization.Sankey(document.getElementById('sankey_basic'));
    chart.draw(data, options);
  }
});
</script>

I set up a CodePen at https://codepen.io/bryant-essense/pen/YzeZrOp, https://codepen.io/bryant-essense/pen/YzeZrOp to replicate the problem.

Notice the “d3.sankey is not a function” message however when you remove or uncomment the ArcGIS script file, Google Charts work correctly, is there a workaround for this?