How to calculate font size of input field in PDF in node js

I facing the issue while scaling the font size in pdf. I’m using pdf-lib package of node js. I’ve used font.widthOfTextAtSize() this method to get the width of the text and based on that I’m calculating maxWidth. In the last I’m calculating fontSize.
but it’s not an accurate match with the input box that I’m getting in pdf.

let fontSize = 12;
      let maxWidth =50;
      if (maxWidth) {
        let textWidth = font.widthOfTextAtSize(textData, fontSize);
        if(textWidth< 70) maxWidth = 50
        else if(textWidth< 100) maxWidth = 70
        else if(textWidth< 140) maxWidth = 100
        else if(textWidth< 160) maxWidth = 120
        else if(textWidth< 200) maxWidth = 130
        else if(textWidth > 200) maxWidth = 200
        
        while (textWidth > maxWidth && fontSize > 5) {
          fontSize -= 1;
          textWidth = font.widthOfTextAtSize(answer, fontSize);
        }
      }

I’ve tried Puppeteer and pdf-filler packages but have not gotten any proper solution.
Thanks in advance.

Angular 13 – Getting error “Cannot read properties of null (reading ‘getParsed’)”

working on an Angular 13 project and getting an exception:

TypeError: Cannot read properties of null (reading ‘getParsed’)
at …/main.2506c840be361c93.js:1:325924
at Array.filter ()
at nd._getActiveElements (…/main.2506c840be361c93.js:1:325808)
at nd.handleEvent (…/main.2506c840be361c93.js:1:325525)
at Object.afterEvent (…/main.2506c840be361c93.js:1:326752)
at Fe (…/main.2506c840be361c93.js:1:152333)
at Au._notify (…/main.2506c840be361c93.js:1:256447)
at Au.notify (…/main.2506c840be361c93.js:1:256268)
at ta.notifyPlugins (…/main.2506c840be361c93.js:1:275524)
at ta._eventHandler (…/main.2506c840be361c93.js:1:276188)

I searched for occurrences of “.getParsed” in the entire application but there are no results. Same with node_modules. Hopefully someone here as encountered this?

Thanks in advance 🙂

Stuck on making the final API GET fetch with pre-flight cors failure for LinkedIn API

I’ve been following the official docs at:
https://learn.microsoft.com/en-us/linkedin/shared/authentication/authorization-code-flow?context=linkedin%2Fcontext&tabs=HTTPS1

Here we’re instructed to:

  1. Request an authorisation code (through member sign-in)
  2. Swap this for an access token through a ‘POST’ request
  3. Finally call the API endpoint for data using a ‘GET’ request

Using vanilla javascript and fetch to do this..

I’m stuck on the last one with the browser stating ‘Access to fetch at ‘https://api.linkedin.com/v2/me’ from origin ‘http://127.0.0.1:5500’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.

My GET request:
enter image description here

As you can see I have added the ‘Authorisation’ header etc. but no success. What is the issue?

Thanks

Customer merging in netsuite via duplicate management tool gives error

The merge of the entity ‘xxx’ was blocked for the following reasons: The entities cannot be merged. Creation of the merged entity leads to following errors: You have modified the originating subrecord, and the clone can no longer be merged. To perform a merge, the clone’s originating subrecord must not change before the merge. You must create a new clone. You have modified the originating subrecord, and the clone can no longer be merged. To perform a merge, the clone’s originating subrecord must not change before the merge. You must create a new clone.

check subsidiary,currency,item price level etc

how, to achieve a filtered content from Django backend to my webpage

this is a web page, called description.html

 <button class="book-ticket" onclick="navigateToShowPage()" >Book Ticket</button>
        </div>
    </div>
    <script>
     function navigateToShowPage() {
    // Get movie name and city from the URL or any other source
    var movieName = '{{ movie.name }}'; // Get movie name from the backend
    var cityName = '{{ city }}'; // Get city name from the backend
    
    // Redirect to the shows page with query parameters
    window.location.href = `/shows/${movieName}/?city=${cityName}`;
     }
  
</script>

now what i want is that when user click on the button it, navigates to shows.html page


<h1>Screen</h1>
<div class="container">
    <div class="navbar">
        <div class="date-box">24</div>
        <div class="date-box">25</div>
        <div class="date-box">26</div>
        <div class="date-box">27</div>
        <div class="date-box">28</div>
    </div>

    <div>
        <h2>Theatre A</h2>
        <div class="show-container">
            <div class="show-box">Show 1: 10:00 AM</div>
            <div class="show-box">Show 2: 2:00 PM</div>
            <div class="show-box">Show 3: 6:00 PM</div>
        </div>
    </div>
    <div>
        <h2>Theatre B</h2>
        <div class="show-container">
            <div class="show-box">Show 1: 11:00 AM</div>
            <div class="show-box">Show 2: 3:00 PM</div>
            <div class="show-box">Show 3: 7:00 PM</div>
        </div>
    </div>
</div>

and now here i want website to show the dates in nav bar and cinema hall name in h2 and show timings, show-box , and want this all to take from backend django, models,

class Show(models.Model):
    movie = models.ForeignKey(Movie, on_delete=models.CASCADE)
    cinemahall = models.ForeignKey(CinemaHall, on_delete=models.CASCADE, null=True)
    city = models.ForeignKey(City, on_delete=models.CASCADE)
    timings = models.CharField(max_length=100)
    date = models.DateField(default=date.today)
    NumOfSeats = models.BigIntegerField(default=200)

    def __str__(self):
        return f"{self.movie.name} - {self.cinemahall.name} - {self.timings} - {self.date} - {self.NumOfSeats}"

now the function i want is that, take the movie name and city name form the description.html’s url , so in index.html there are cards of different movie when we click on them we navigates to description.html

function displayMovies(movies) {
    const movieList = document.getElementById('movieList');
    movieList.innerHTML = '';
    const selectedCity = document.getElementById('selectedCity').innerText; // Retrieve selected city
    movies.forEach(movie => {
        const card = document.createElement('div');
        card.classList.add('card');
        card.innerHTML = `
            <img src="${movie.image}" alt="${movie.image}">
            <div class="overlay">
                <p>Movie name: ${movie.name}</p>
            </div>
        `;
        // Add click event listener to each card
       card.addEventListener('click', function() {
    window.location.href = `/movie-details/${movie.name}/?city=${encodeURIComponent(selectedCity)}`;
});
        movieList.appendChild(card);
    });
}

so i want that only show dates of particular movie in particular city in the shows.html use filter and then i want is that like when user click on a particular date, then on that date , show only those shows that are running on that day of that movie in that city , so please help me how i achieve this how i do this , i tried different methods , but getting failed

Need HTML or Javascript Code To Stop iFrame Galleries Pulling Scroll Bar Further Down The Page When Loading or Refreshing a HTML Webpage

Inside our pair.com account control centre, we are currently using their basic html files for building and promoting a very basic, temporary webpage.

Is there a known html code or a javascript code available that stops Photobucket iframe auto slide show galleries pulling the scroll bar down and well away from the top of the page everytime we load or refresh?

This issue happens in Chrome, Opera, Firefox and a few other browsers on our Windows 10 computers, and this issue has been witnessed and reported by Pair.com and Photobucket customer support staff, amongst others out there on the net.

We are idiot friendly standard amateurs doing the best we can.

The website is loveforlife.com.au.

Thanks

Arthur & Fiona Cristian

So far, we have found a few basic html codes that don’t work.

Using files in Pyscript

I need to use some files in my Pyscript algorithm, and I know Pyscript can´t access local files because of a security issue. But my question is, can I somehow upload those files to a virtual file system, because otherwise I’m going to be unable to run my script. When using the open() function, I’m getting an error where the file isn’t found.

How to hide tooltip for selected Leaflet marker

I have multiple markers (vessels) on a Leaflet map. Each has popup content (marker title) and tooltip, which are the same (vessel name). The problem is when I click on a marker, it opens the popup showing the title. Then I hover the mouse on the marker, it shows the tooltip which is the same text as the title. This makes the UI become redundant.

enter image description here

Is there any way or option for the tooltip to make it hidden for the selected/focused marker? I used Leaflet interop with Blazor.

Cannot find the visuals section in the formatting tab when making Forge(aps) custom visual

the visual section inside the formatting tab does not appear next to the General section

I started the Javascript environment using the “npm start” command and activated the developer settings, then I chose in the visualisation section the developer visual but when selecting the white visual box in the report and looking at the formatting tab to insert what is need from access tokens and GUID and urn I don’t seem to find the visual section (only general);
What i see
errors i get

How to use mongodb in browser environment

I am doing a project where I am using mobilenet ML model.It is a kind of attendence system.But I am facing problems in some lines of code.Here is the specified code.

I want added that I have a little knowledge on mongodb but finishing the project is like compulsory for me. I am working on a browser environment.I am using mongodb atlas.

In the code below I am saving the input,output and examples numbers in the mongodb.This will work for the training data and these data will be saved.

const mongodbAtlasUrl = 'here is the url####';
const collectionName = 'trainingData';

async function saveModel() {
  const trainingDataSave = {
    inputs: trainingDataInputs.map((tensor, index) => {
      if (!tensor) {
        console.error(`Null or undefined tensor found at index ${index}`);
        return null;
      }
      return Array.from(tensor.dataSync());
    }),
    outputs: trainingDataOutputs,
    examplesCount: examplesCount
  };

  try {
    const client = new MongoClient(mongodbAtlasUrl, { useNewUrlParser: true, useUnifiedTopology: true });
    await client.connect();
    const db = client.db();
    const collection = db.collection(collectionName);

    await collection.insertOne(trainingDataSave);
    await client.close();

    statusData.innerText = 'Training data saved to MongoDB.';
  } catch (error) {
    console.error('Error saving training data to MongoDB:', error.message);
    statusData.innerText = 'Error saving training data to MongoDB.';
  }
}

Here is the other function where I am loading data from the database and if there is no data I just simply assigning to [].

async function loadTrainingDataFromMongo() {
  try {
    const client = new MongoClient(mongodbAtlasUrl, { useNewUrlParser: true, useUnifiedTopology: true });
    await client.connect();
    const db = client.db();
    const collection = db.collection(collectionName);

    const response = await collection.findOne();

    await client.close();

    const { inputs, outputs, examplesCount } = response || { inputs: [], outputs: [], examplesCount: [] };

    // Clear existing training data
    trainingDataInputs.forEach(tensor => tensor.dispose());
    trainingDataInputs = [];
    trainingDataOutputs = [];
    examplesCount = [];

    // Convert loaded data back to tensors
    inputs.forEach(inputData => {
      trainingDataInputs.push(tf.tensor(inputData));
    });
    trainingDataOutputs = outputs;
    examplesCount = examplesCount;

    statusData.innerText = 'Training data loaded from MongoDB.';
    train();
  } catch (error) {
    console.error('Error loading training data from MongoDB:', error.message);
    statusData.innerText = 'Error loading training data from MongoDB.';
  }
}

window.addEventListener('load', loadTrainingDataFromMongo);

Is there any way to let the above code to work fine.

Can’t we submit each row using react-hook-form?

I’m creating a program to register my calendar.

After writing the table in one form, each row submit does not submit the corresponding row value, but the entire table submit.

The way I’ve tried it, every tr
When I try to create and send a form, there is an error that the form cannot be made in the table.

I’ve tried searching and getting help from different communities, but as a result, I’ve only heard the answer that everything goes over when I send the form.

No related content was found in the official document of the react-hook-form.

I’d like to try making a program that submit only each row value in the table using react-hook-form or get some help from anyone who has any ideas.

Mobile Touch X, Y coordinates not capturing with Android code

I am trying to capture X, Y coordinates for touch event but the output in the CSV is not capturing. I am running this in Android 11 version mobile, but this needs to work Android 9 and above all versions. Here is the code –

    package com.example.kb_keylog;

import android.content.ContentValues;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private Button startButton, stopButton, submitButton;
    private EditText sentenceEditText;
    private boolean logging = false;
    private int seconds = 0;
    private Handler handler = new Handler();
    private List<String> coordinatesList = new ArrayList<>();
    private StringBuilder typedCharacters = new StringBuilder();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        startButton = findViewById(R.id.startButton);
        stopButton = findViewById(R.id.stopButton);
        submitButton = findViewById(R.id.submitButton);
        sentenceEditText = findViewById(R.id.sentenceEditText);

        startButton.setOnClickListener(v -> startLogging());
        stopButton.setOnClickListener(v -> stopLogging());
        submitButton.setOnClickListener(v -> exportToCSV());

        // Add touch listener to capture touch events
        sentenceEditText.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                // Touch down event
                String touchCoordinates = event.getX() + "," + event.getY();
                String timestamp = String.valueOf(System.currentTimeMillis());
                coordinatesList.add(timestamp + "," + touchCoordinates + ",TAP");
            }
            return false;
        });

        // Add text change listener to capture typed characters
        sentenceEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {}

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // Add typed character information
                String timestamp = String.valueOf(System.currentTimeMillis());
                int endIndex = start + count; // Calculate the end index
                if (count > 0) {
                    // Append typed characters
                    typedCharacters.append(s.subSequence(start, endIndex));
                    coordinatesList.add(timestamp + ",-,-," + s.charAt(endIndex - 1) + "," + typedCharacters.toString() + ",TAP");
                } else {
                    // Backspace/delete key pressed
                    if (start > 0 && typedCharacters.length() > 0) {
                        // Remove the last character from typedCharacters
                        typedCharacters.deleteCharAt(typedCharacters.length() - 1);
                    }
                    coordinatesList.add(timestamp + ",-,-,Backspace," + typedCharacters.toString() + ",Backspace");
                }
            }





            @Override
            public void afterTextChanged(Editable s) {}
        });
    }

    private void startLogging() {
        logging = true;
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                seconds++;
                startButton.setText("Start (" + seconds + "s)");
                if (logging) {
                    handler.postDelayed(this, 1000);
                }
            }
        }, 1000);
    }

    private void stopLogging() {
        logging = false;
        seconds = 0;
        startButton.setText("Start");
    }

    private void exportToCSV() {
        // Define the content values for the new media file
        ContentValues values = new ContentValues();
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, "captured_data.csv");
        values.put(MediaStore.MediaColumns.MIME_TYPE, "text/csv");

        // Prepare the CSV file content
        StringBuilder csvContent = new StringBuilder();
        csvContent.append("id,xCoordinate,yCoordinate,timestamp,character,charSq,typen"); // CSV header
        int id = 1;
        for (String entry : coordinatesList) {
            String[] parts = entry.split(",");
            if (parts.length >= 6) { // Ensure array has at least 6 elements
                String timestamp = parts[0];
                String coordinates = parts[1] + "," + parts[2]; // Combine x and y coordinates
                String character = parts[3];
                String charSq = parts[4];
                String type = parts[5];
                csvContent.append(id++).append(",").append(coordinates).append(",").append(timestamp)
                        .append(",").append(character).append(",").append(charSq).append(",").append(type).append("n");
            } else {
                // Handle invalid entry (missing data)
                // Log a warning or skip this entry
                // You can also consider adding error handling based on your app's requirements
            }
        }

        // Insert the content values into the MediaStore
        Uri uri = getContentResolver().insert(MediaStore.Files.getContentUri("external"), values);

        try {
            // Open an OutputStream to the MediaStore URI
            OutputStream outputStream = getContentResolver().openOutputStream(uri);
            if (outputStream != null) {
                // Write data to the OutputStream
                outputStream.write(csvContent.toString().getBytes());
                outputStream.close();

                // Show a success message to the user
                Toast.makeText(this, "Data exported to CSV: " + uri.toString(), Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            // Handle any errors that occur during file operations
            e.printStackTrace();
            Toast.makeText(this, "Error exporting data to CSV", Toast.LENGTH_SHORT).show();
        }
    }
}

I believe on text change or somewhere it is missing to capture the coordinates.

how to make setTimeOut to run the counter animation more faster?

I have this piece of code for a counter. I want to run it very fast like the speed of light because the numbers are in thousands and right now the animation looks very silly and so slow, please any idea? or maybe a better approach?

const stat = document.querySelectorAll(".stats span");

export const startCounter = () => {
    stat.forEach(stat => {
        console.log("fore");
        
        let counter = 0;

        function updateCount() {            
            const traget = parseInt(stat.dataset.count);

            if(counter < traget) {
                console.log("target >");
                
                counter++;
                stat.innerText = counter;
                setTimeout(updateCount, 1);
            }
            
        else {
            console.log("> targ");
            
            stat.innerText = counter.toLocaleString();
        }
        }

        updateCount();

    });
}


startCounter();

Datatables pagination links not styled with bootstrap5 in a Laravel application not working after running npm run build

I’m building with datatables.js, vite as the bundler, Laravel and vanilla JavaScript. Been working in development with npm run dev and everything was fine so I didn’t notice earlier. Now after running npm run build, my datatable previous and next links have lost their style. When I run npm run dev it works fine but when I build with npm run build, the styles are lost again.
enter image description here
I have the useBootstrapFive function in the boot method of the AppServiceProvider.

public function boot(): void
    {
        JsonResource::withoutWrapping();
        Paginator::useBootstrapFive();
    }

I have deleted node modules and reinstalled npm packages afresh.

this is how I am loading my scss bootstrap files in my app.scss file

@import "./variables.scss";
@import "../../node_modules/bootstrap/scss/bootstrap.scss";
@import "../../node_modules/bootstrap-icons/font/bootstrap-icons.css";
@import "../../node_modules/datatables.net-bs5/css/dataTables.bootstrap5.css";

these are the imports into my app.js file

import "../css/app.scss";
import "bootstrap";
import "./bootstrap";
import "../../node_modules/jquery/dist/jquery.min.js";
import "../../node_modules/datatables.net/js/jquery.dataTables.min.mjs";
import "../../node_modules/datatables.net-bs5/js/dataTables.bootstrap5.min.mjs";
import 'datatables.net-plugins/api/sum().mjs';
import 'datatables.net-fixedheader-bs5';
import 'datatables.net-buttons-bs5';
import 'datatables.net-buttons/js/buttons.colVis.mjs';
import 'datatables.net-buttons/js/buttons.html5.mjs';
import 'datatables.net-buttons/js/buttons.print.mjs';
import 'datatables.net-fixedcolumns-bs5';
import 'datatables.net-select-bs5';
import 'datatables.net-staterestore-bs5';