Passing data By Html & js

I writed html page,I want
display a web page from the GeoGebra website , So that he can the user to write an equation on my page then pass this equation to the GeoGebra web page to graph it

I just need to know how to pass equation between the two pages?!

I just need to know how to pass equation

interval not getting cleared in react

I have this problem where my intervals are not getting removed. When the intervalActive prop from its parent gets changed to false, it should run the function stopPagination, but instead it doesnt. The interval keeps going and it does not stop. Does anybody maybe know what is up with this?

   const startPagination = () => {
        if (!intervalId && intervalActive) {
            const id = setInterval(() => {
                paginate(1);
            }, interval[1] * 1000);
            setIntervalId(id);
        }
    };

    const stopPagination = () => {
        clearInterval(intervalId);
        setIntervalId(null);
    };

    useEffect(() => {
        console.log(intervalActive)
        if (intervalActive) {
            startPagination();
            return () => {
                clearInterval(intervalId);
                setIntervalId(null);
            };
        } else {
            stopPagination();
        }
    }, [intervalActive]);

I tried clearing all intervals, but that did not work and removing the clean up function inside the useEffect creates 2 intervals, one that can be removed and added and another one that I don’t know about.

Trying to find a simple way of getting the radio buttons input from this vanilla JS code

I am trying to create an option for the user to select their gender using these ionic radio buttons. However I’m not sure what the simplest solution would be.

HTML

 <ion-item>
                      <ion-radio-group id="genderradioGroup" value="male">
                          <ion-list-header>
                              What Is Your Gender?
                          </ion-list-header>
                      
                          <ion-radio value="male">Male</ion-radio><br />
                          <ion-radio value="female">Female</ion-radio><br />
                          <ion-radio value="pref-not-to-say">Prefer Not To Say</ion-radio><br />
                      </ion-radio-group>
                  </ion-item>

I tried asking ChatGPT in the hopes that would be to help me, but I can’t get any messages in the logs that indicated that the selection is working.

ChatGPT JS


    document.addEventListener('DOMContentLoaded', function() {
        const genderradioButtons = document.querySelectorAll('#genderradioGroup ion-radio');
      
        // Loop through each radio button and add event listener
        genderradioButtons.forEach(function(radioButton) {
            radioButton.addEventListener('click', function() {
                const genderselectedValue = radioButton.getAttribute('value');
                console.log("Gender:", genderselectedValue);
                // You can perform any action with the selected value here
            });
        });
    });

How to generate PDF’s that have expandable fields (on hover or click shows the extra text)

I use vue and jsPDF with domtoimage that makes my html page a jpeg and saves it to an adobe acrobat pdf

I need to generate PDF’s with dynamic data and sometimes the text in certain fields are quite long either cutting off or spreading line height so much that data is lost at the bottom of the page.
I setup my page using
display: grid;
grid-template-columns: fr
This sets the width of each column leaving the height to adjust for text
I currently set the lines per page for a report, however as i am working with dynamic data this often causes problems.

I need a better solution and if i could export a multilayer pdf that would essentially accordian/expand on hover or click where the text goes over that would be amazing.

I have very limited experience with creating pdfs dynamically and am open to any suggestions, i have tried counting the length of strings and adjusting the layout of the pdfs to accomidate the outlyers but this isnt exactly what i want.

‘Uncaught TypeError: Cannot read properties of undefined (reading ‘length’)’ in wasm-pack generated code

(For a better formatted message without a giant blob of code, I’d recommend seeing the GitHub issue.)

Error message

Uncaught TypeError: Cannot read properties of undefined (reading 'length') in https://cloverdev.serv00.net/pkg/rwst.js at 68:19. TypeError: Cannot read properties of undefined (reading 'length')

I used wasm-pack build --target web to generate everything in the pkg folder. I am currently unable to provide the full error message, but you can navigate to https://cloverdev.serv00.net/index.html (index.html must be specified) to see it yourself in the console. I have console-panic-error-hook, but this looks like an issue with wasm-pack. Here’s my code:

lib.rs

mod model;
use model::*;

use wasm_bindgen::prelude::*;
use web_sys::{window, Element};
use ewebsock::{Options, WsEvent, WsMessage::Text};
use serde_json;
use urlencoding::encode;

extern crate console_error_panic_hook;
use std::panic;
use web_sys_main_loop::FrameState;

#[wasm_bindgen]
pub fn main() {
    panic::set_hook(Box::new(console_error_panic_hook::hook));

    let window = window().expect("no global `window` exists");
    let document = window.document().expect("should have a document on window");
    let body = document.body().expect("document should have a body");

    let (mut sender, receiver) = ewebsock::connect("wss://cloverdev.serv00.net/ws", Options::default()).expect("");
    sender.send(ewebsock::WsMessage::Text(serde_json::to_string(&MessageSent { user: "test42".to_string(), msg: "hello".to_string(), time: None }).unwrap()));
    web_sys_main_loop::start(&window, move |_frame_state: FrameState|  {
        while let Some(WsEvent::Message(Text(event))) = receiver.try_recv() {
            match serde_json::from_str::<MessageTypes>(&event).unwrap() {
                MessageTypes::MessageSent(response) => {
                    /* MESSAGE TEMPLATE:

                        <div style='margin: 10px 0;'>
                            <div class="userDisplay">
                                ${jdenticon.toSvg(username[2], 26)}
                                <span>
                                    <a href='/profile/${encodeURIComponent(username)}'>
                                        username
                                    </a>
                                    <span class="msgTime">
                                        [at <time datetime="timeSent">
                                        timeSent
                                        </time>]
                                    </span>
                                </span>
                            </div>
                            <div id='message'>
                                <pre>
                                    message
                                </pre>
                            </div>
                        </div>

                    */
                    println!("Recieved event 'MessageSent' data (1/1) {:?}", response);
                    let _ = body.append_child(&create_message_element(response.clone()));
                },
                MessageTypes::RetrieveMessages(response) => {
                    let iterator = response.msgs.iter();
                    for (i, d) in iterator.clone().enumerate() {
                        println!("Recieved event 'RetrieveMessages' data ({}/{}) {:?}", i+1, iterator.len(), d);
                        let _ = body.append_child(&create_message_element(d.clone()));
                    }
                },
                MessageTypes::UserJoin(response) => {
                    println!("Recieved event 'UserJoin' data (1/1) {:?}", response);
                },
                MessageTypes::UserLeft(response) => {
                    println!("Recieved event 'UserLeft' data (1/1) {:?}", response);
                }
            } 
        }
    });
}

fn create_message_element(res: MessageSent) -> Element {
    // Get the document and create a new div element
    let document = window().unwrap().document().unwrap();
    let outer_div = document.create_element("div").unwrap();
    outer_div.set_attribute("style", "margin: 10px 0;").unwrap();

    // Create the inner div with the class "userDisplay"
    let user_display_div = document.create_element("div").unwrap();
    user_display_div.set_class_name("userDisplay");

    // Create and append the jdenticon element
    /*let jdenticon_svg = document.create_element("svg").unwrap();
    jdenticon_svg.set_inner_html(&format!("{}", jdenticon.to_svg(username[2], 26))); We'll wait for this...
    user_display_div.append_child(&jdenticon_svg).unwrap();*/

    // Create and append the anchor element
    let anchor = document.create_element("a").unwrap();
    anchor.set_attribute("href", &format!("/profile/{}", encode(&res.user))).unwrap();
    anchor.set_text_content(Some(&res.user));
    user_display_div.append_child(&anchor).unwrap();

    // Create and append the span element with class "msgTime"
    let time_span = document.create_element("span").unwrap();
    time_span.set_class_name("msgTime");
    time_span.set_inner_html(&format!(
        "[at <time datetime='{:?}'>{}</time>]",
        res.time, res.time.expect("no time when creating msg element").format("%x %r")
    ));
    user_display_div.append_child(&time_span).unwrap();

    outer_div.append_child(&user_display_div).unwrap();

    // Create the message div with id "message" and a pre element inside
    let message_div = document.create_element("div").unwrap();
    message_div.set_id("message");

    let pre_element = document.create_element("pre").unwrap();
    pre_element.set_text_content(Some(&res.msg));

    message_div.append_child(&pre_element).unwrap();

    outer_div.append_child(&message_div).unwrap();

    return outer_div;
}

model.rs

use serde::{Deserialize, Serialize};
use chrono::{DateTime, Utc};

#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(untagged)]
pub enum MessageTypes {
  MessageSent(MessageSent),
  RetrieveMessages(RetrieveMessages),
  UserJoin(UserJoin),
  UserLeft(UserLeft)
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct MessageSent {
    pub msg: String,
    pub user: String,
    #[serde(skip_serializing)]
    pub time: Option<DateTime<Utc>>
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct RetrieveMessages {
    pub msgs: Vec<MessageSent>
}

// User related messages
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserJoin {
    pub userjoin: String
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct UserLeft {
    pub userleft: String
}

Cargo.toml

[package]
name = "rwst"
version = "0.1.0"
edition = "2021"

[package.metadata.wasm-pack.profile.release]
wasm-opt = false

[lib]
crate-type = ["cdylib"]

[dependencies]
wasm-bindgen = "0.2.92"
ewebsock = "0.5.0"
chrono = { version = "0.4.37", features = ["serde", "wasmbind"] }
serde = { version = "1.0.197", features = ["derive"] }
serde_json = "1.0.115"
urlencoding = "2.1.3"
web-sys-main-loop = "0.1.8"
console_error_panic_hook = "0.1.7"

[dependencies.web-sys]
version = "0.3.4"
features = [
  'Document',
  'Element',
  'HtmlElement',
  'Node',
  'Window',
  'BinaryType',
  'Blob',
  'ErrorEvent',
  'FileReader',
  'MessageEvent',
  'ProgressEvent',
  'WebSocket',
]

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>My Rust + Webpack project!</title>
  </head>
  <body>
    <script type="module">
      import init, { main } from "./pkg/rwst.js";
      window.onerror = (a,b,c,d,e) => { window.alert(`${a} in ${b} at ${c}:${d}. ${e}`) }
      init().then(() => {
        main();
      });
    </script>
  </body>
</html>

wasm-pack doesn’t appear to generate any errors, so I don’t know what could be going wrong. Any help would be nice, thank you all!

How can I increase the gap between the values of the x axis in a line chart and also change its width and height?

I just started using charts js in react and I wanted to know that can I increase the gap between the values of the x axis in a line chart and also in need to change the width and height of the chart.

import React from 'react';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  PointElement,
  LineElement,
  Title,
  Tooltip,
} from 'chart.js';
import { Line } from 'react-chartjs-2';
import Linechartstyle from './Linechart.module.css';

ChartJS.register(
    CategoryScale,
    LinearScale,
    PointElement,
    LineElement,
    Title,
    Tooltip,
  );

  export const options = {
    responsive: true,
    plugins: {
      legend: {
        display: false,
      },
    },
    maintainAspectRatio: false,
  };
  
const labels = ['January', 'February', 'March', 'April', 'May'];
  
export const data = {
    labels,
    datasets: [
      {
        label: 'Coins',
        data: [105, 59, 80, 18, 190],
        borderColor: '#34b2fe',
        backgroundColor: '#34b2fe',
      },
    ],
};

function Linechart() {
  return (
    <>
      <div>
        <Line options={options} data={data} />
      </div>
    </>
  )
}

export default Linechart

I need to increase this gap and change the width and height

To increase the width and height I added the height and width css property to the <Line /> block but It didn’t work.

How to track cumulative data upload of total data to be uploaded in axios

let uploadedFiles = 0;
let fileProgress = {};
let currentSize = 0;
let fileTracker = {};
let totalFileSize = 0;
const config = {
  onUploadProgress: function (progressEvent) {
fileProgress[fileTracker.name] =
  (progressEvent.loaded * 100) / progressEvent.total;

  currentSize = progressEvent.loaded;

 const totalSize = sizeConverter(totalFileSize);
 // sum up all file progress percentages to calculate the overall progress
 let totalPercent = fileProgress
  ? Object.values(fileProgress).reduce((sum, num) => sum + num, 0)
  : 0;
// divide the total percentage by the number of files
let percentCompleted = parseInt(
  Math.round(totalPercent / selectedFiles.length)
);
progressBar.setAttribute("value", percentCompleted);
percentDetails.firstChild.textContent = `${Math.round(
  percentCompleted
)}% uploaded`;

uploadedFilesDetails.firstChild.textContent = `${uploadedFiles} of ${selectedFiles.length} files uploaded`;
uploadedFilesDetails.lastChild.textContent = `${sizeConverter(currentSize)} of ${totalSize}     Uploaded`;} };
//generic submsion function
const submitFile = async (url, dept, files) => {
uploadedFiles = 0;
fileProgress = {};
currentSize = 0;
loadingOverlay.style.display = "flex";
const formData = new FormData();
totalFileSize = files.reduce((total, file) => total + file.size, 0);

for (let file of files) {
formData.append(`file`, file);
fileTracker = file;
try {
  const response = await axios.post(url + `${dept}`, formData, config);
  if (response.data.message == "upload successful") {
    uploadedFiles++;
    uploadedFileSize = file.size;
  }
} catch (error) {
  failDisplay();
}
}
if (uploadedFiles == files.length) {
successDisplay();
}
}; 

i am trying to display the cumulative data that has been uploaded over the total size of files to be uploaded here
uploadedFilesDetails.lastChild.textContent = ${sizeConverter(currentSize)} of ${totalSize} Uploaded;

`my issue is when a particular file as been uplaoded the ui resartes from 0mb, since i am uploading the files one at a time, how can i prevent this from happening, doing this currentSize+=progerssEvent.loaded, only results in an ambigous value
any help would be appreciated

i got half of what i expected, but the when a file has been uploaded, the the current size starts from 0 again`

Frontend Advice: Integrating 3D Beveling in Pie Chart NEXT.js project

So I’m currently working on a project where I need to create pie charts that dynamically takes data from a JSON array. I’ve found several React modules for this functionality, so that part seems easy right, but my manager has a specific requirement that I cant seem to get right. He wants the pie chart to have a 3D beveling effect, similar to what you might see in PowerPoint presentations. [see image link as an example] Making this 3D beveling is driving me nuts cause I just can’t get it the way he wants it.

I was wondering if anyone here has experience or insights into how I could implement such a feature? Are there any libraries or techniques specifically tailored for this, like beveling, to charts created in React?

Any advice, guidance, or even alternative approaches would be greatly appreciated. Thank you in advance for your help!

Example pie chart

I have looked into three.js no luck with a solution & I have tried

ResponsivePie from from “@nivo/pie” but can’t get the pie chart to look exactly the same as the angle isn’t precise enough also tried

react-chartjs-2 which doesn’t really have 3D effects for the pie charts

Lastly I also tried three.js with slight luck just can’t really wrap my head around it.

CSS Text styling bugging on WebKit

I’ve got this page, that has a JavaScript script that changes the text of an H1 and a p.

const slide_data = {
  1: {
    text: "Example",
    sub: "This is an example text.",
    time: 10
  },
  2: {
    text: "Title for the Looooooooooong Example Section",
    sub: "This is an example text for this section to show my issue to StackOverflow.",
    time: 10
  }
  3: {
    text: "4",
    time: 10
  }
}

var slide_change = 1;
let currentSleep;
async function slides() {
  var header = document.querySelector('#header');
  var sub = document.querySelector('#subtitle');

  for (i = 1; i <= Object.keys(slide_data).length; i = i + slide_change) {
    var slide = slide_data[i]
    slide_change = 1
    main.style.fontSize = "4rem";
    main.style.color = "white";
    header.innerHTML = slide.text;

    if (slide.sub != null) {
      sub.innerHTML = slide.sub;
    } else {
      sub.innerHTML = ""
    }

    bar = document.querySelector(`#bar_${i}`);

    currentSleep = new Sleep();
    await currentSleep.start(slide.time * 1000, bar, bar.maxWidth)
  }
}

It works as a mock of the Spotify Wrapped. When the time is over or if you tap on the side of the screen, the text changes to match the next section of the Wrapped. It looks good in desktop Google Chrome (even with a vertical aspect ratio), but testing on my iOS phone, where all browsers use Apple’s WebKit, the text appears uncentered, and sometimes part of it outside of the screen when is changed; as if the text’s justification wasn’t updated propertly.

It seems that rotating the screen of my phone to horizontal and then turning it again as it was fixes the issue, but that is not the expected behaviour.
I’ve also tried this on macOS’s Safari, that also uses the same technology. The seen behaviour is the same as on my phone. If I resize the window it automatically fixes (until the next section, that bugs out again).

Based on this, I’ll guess that this is an issue related with WebKit, as trying this on desktop Google Chrome behaves as expected.

To show the issue, I’ve made two sections: one with a short title and text, and a long one.
The first section is shown normally, but when we move on to the second one we can see that it’s a little bit off to the right side and margins are ignored

Short example text, works as expected Long example text, bugged Screen record

when the callback function of the timeout function is executed?

setTimeout(() => {console.log("test1")},2)
let i = 0;
while(i < 5000){
    i++
    console.log('t')
}
console.log("test2")
console.log("test3")
console.log("test4")

The while loop takes more than 2ms. So, when the while loop has finished, the setTimeout has also finished its 2ms of waiting. Therefore, normally, my output would be:

test1
test2
test3
test4

However, I get:

test2
test3
test4
test1

Can someone explain to me why?

CSS @media print move element to the last page

On a website I have an img-carousel and carousel-indicators which are basically img-thumbnails. I want to create a print-version where the structure is

  1. div.one (carousel) – only the currently active image should be printed
  2. div.three
  3. div.four
  4. div.one (carousel-indicators) – now here i want all other thumbnails to be printed

Is there any way to say like “print an element at a different position on the printed version”? It seems like :last_page selector doesn’t work anymore.

example code:

<div class="one">
    <div class="carousel">
    </div>
    <div class="carousel-indicators">
    </div>
</div>
<div class="two">
...two...
</div>
<div class="three">
...three...
</div>
<div class="four">
...four...
</div>


@media print {
    @page {
      margin: 1rem !important;
    }
    .two {
      display: none;
    }
  }

I tried using jsPDF and html2pdf so I could move the items using javascript. But I couldn’t get those libs really working and i feel like the amount of time I need would exceed everyting.

Odoo 16 – ValueError: External ID not found in the system: web.assets_backend

I have Odoo 16 up with docker-compose and I´m trying to create some charts with Highchart but I keep getting “ValueError: External ID not found in the system: web.assets_backend” when importing the assets. Does anyone know what´s wrong?

This are the assets in my views.xml

<template id="assets_account_dashboard" name="Account Dashboard" inherit_id="web.assets_backend">
     <xpath expr="." position="inside">
         <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet"/>
         <script type="text/javascript" src="/digital_twin/static/src/js/dashboard.js"/>
         <script type="text/javascript" src="digital_twin/static/lib/Highchart/code/highcharts.js"/>
         <link rel="stylesheet" type="text/scss" href="/digital_twin/static/src/css/style.scss"/>
     </xpath>
</template>

And this is my manifest

{
    'name': "digital_twin",

    'summary': """
        Short (1 phrase/line) summary of the module's purpose, used as
        subtitle on modules listing or apps.openerp.com""",

    'description': """
        Long description of module's purpose
    """,

    'author': "My Company",
    'website': "https://www.yourcompany.com",

    'category': 'Uncategorized',
    'version': '0.1',

    'assets': {
        'web.assets_backend': [
            'digital_twin/static/src/js/dashboard.js',
        ],
    },

    'depends': ['base'],

    'data': [
        'security/ir.model.access.csv',
        'views/views.xml',
        'views/predictive_analisis_views.xml',
        'views/templates.xml',
    ],

    'demo': [
        'demo/demo.xml',
    ],
}

I have tried changing the inherit_id to ‘website.assets_backend’, ‘web.assets_frontend’, ‘website.assets_frontend’, but I keep getting the same error even though its referenced in the manifest. I also have the developer mode (with assets) active in Odoo.

Map alternative for rendering faster in JavaScript

There is a list of data coming in from an API, which I am displaying with the help of Map() in my React Application. But the problem here is that the data consists of more than 200 records and all of them are loading one by one. Hence making the load time very high which is not suitable for any website. Please provide any alternative to load the data immediately when the page is opened or maybe a better alternative.
Let me post a sample of my code for better understanding of my problem.

function getEventDetails(){
    const formattedDay = day.format("DD-MM-YYYY");
    const eventsOnDay = eventsCountandDate.find(evt => evt.date === formattedDay);
    
    return eventsOnDay && eventsOnDay.courseCount > 0 ? (
      <div className="eventDetailsBox">
        {eventsOnDay.courses.map((course) => {
          return (
            <div className="force-overflow">
              {course.registrationLink ? ( 
                <p className="eventsDetailsOnBox_text isClickableEvent" onClick={() => RedirectToPage(course.registrationLink)}>{course.courseName}</p>
              ):(
                <p className="eventsDetailsOnBox_text" onClick={() => RedirectToPage(course.registrationLink)}>{course.courseName}</p>
              )}
            </div>
          )
        })}
    </div>
) : null;

javascript – heap out of memory

i have api in nodejs for read data from mysql database and write it into csv file and download file after complete write in csv file. when i have 1.7 million records in database it is working but now i have 5 million record it is give me error

javascript – heap out of memory

my api code:

exports.exportdatatocsv = async (req, res) => {
    con.query(
        "SELECT sender_name, table_name FROM sender_tbl where sender_name ",
        function (error, data) {
            if (error) {
                console.error(error);
                res.status(500).send("Internal Server Error");
                return;
            }

            var mysqlData = JSON.parse(JSON.stringify(data));
            var workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ stream: res });

            mysqlData.forEach((sender, index) => {
                var worksheet = workbook.addWorksheet(
                    sender.sender_name.substring(0, 31)
                );

                con.query(
                    `SELECT * FROM ${sender.table_name} ORDER BY id DESC`,
                    function (error, tableData) {
                        if (error) {
                            console.error(error);
                            res.status(500).send("Internal Server Error");
                            return;
                        }

                        var fileHeader = [
                            "message",
                            "info",
                            "credit/debit",
                            "amount",
                            "netbal",
                        ];
                        worksheet.addRow(fileHeader);

                        tableData.forEach((row) => {
                            worksheet.addRow([
                                row.message,
                                row.info,
                                row.isdebit ? "debit" : "credit",
                                row.amount,
                                row.netbal,
                            ]);
                        });

                        if (index === mysqlData.length - 1) {
                            workbook
                                .commit()
                                .then(function () {
                                    res.status(200).end();
                                })
                                .catch(function (err) {
                                    console.error(err);
                                    res
                                        .status(500)
                                        .send("Error occurred while generating Excel file");
                                });
                        }
                    }
                );
            });
        }
    );
};

i have implement stream but still not working and i do not have to much idea regarding stream