cdn.datatables.net connection refused, datatable won’t load

While navigating a page that include DataTable, I am getting the following errors on the browser’s console:

GET https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css
net::ERR_CONNECTION_REFUSED

GET https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js
net::ERR_CONNECTION_REFUSED

GET
https://cdn.datatables.net/fixedheader/3.1.7/js/dataTables.fixedHeader.min.js
net::ERR_CONNECTION_REFUSED

Consequently the DataTable is missing required resources

$(…).DataTable is not a function

What is the solution? Is there an alternative way to load the resources and make the datatable work?

I have a report in HTML and I need to highlight some data when the use inputs some text

<!DOCTYPE html>
<html>
<head>
  <title>Text Highlighter</title>
  <style>
    .highlight {
      background-color: yellow;
    }
  </style>
</head>
<body id="text">
  <input type="text" id="searchInput" placeholder="Enter text to highlight" oninput="highlightMatches()">
  <button onclick="highlightMatches()">Highlight</button>

  <div>
    <p>
      paragreaaf 1 sadasdas
    </p>
    <table>
  <caption>
    Front-end web developer course 2021
  </caption>
  <thead>
    <tr>
      <th scope="col">Person</th>
      <th scope="col">Most interest in</th>
      <th scope="col">Age</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th scope="row">Chris</th>
      <td>HTML tables</td>
      <td>22</td>
    </tr>
    <tr>
      <th scope="row">Dennis</th>
      <td>Web accessibility</td>
      <td>45</td>
    </tr>
    <tr>
      <th scope="row">Sarah</th>
      <td>JavaScript frameworks</td>
      <td>29</td>
    </tr>
    <tr>
      <th scope="row">Karen</th>
      <td>Web performance</td>
      <td>36</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <th scope="row" colspan="2">Average age</th>
      <td>33</td>
    </tr>
  </tfoot>
</table>
    This is an example paragraph. Feel free to search any text in this paragraph and it will be highlighted.
  </div>

  <script>
    function highlightMatches() {
      const searchTerm = document.getElementById('searchInput').value.trim();
      const body = document.body;

      removeHighlights(body);

      if (!searchTerm) return;

      const regex = new RegExp(searchTerm.replace(/[-/\^$*+?.()|[]{}]/g, '\$&'), 'gi');

      const walker = document.createTreeWalker(
        body,
        NodeFilter.SHOW_TEXT,
        {
          acceptNode: function (node) {
            if (
              node.parentNode &&
              ['SCRIPT', 'STYLE'].includes(node.parentNode.nodeName)
            ) return NodeFilter.FILTER_REJECT;
            return NodeFilter.FILTER_ACCEPT;
          }
        },
        false
      );

      const nodes = [];
      while (walker.nextNode()) {
        if (regex.test(walker.currentNode.nodeValue)) {
          nodes.push(walker.currentNode);
        }
      }

      nodes.forEach(node => {
        const frag = document.createDocumentFragment();
        const parts = node.nodeValue.split(regex);
        const matches = node.nodeValue.match(regex);

        parts.forEach((part, i) => {
          frag.appendChild(document.createTextNode(part));
          if (matches && i < matches.length) {
            const span = document.createElement('span');
            span.className = 'highlight';
            span.textContent = matches[i];
            frag.appendChild(span);
          }
        });

        node.parentNode.replaceChild(frag, node);
      });
    }

    function removeHighlights(root) {
      const spans = root.querySelectorAll('span.highlight');
      spans.forEach(span => {
        span.replaceWith(document.createTextNode(span.textContent));
      });
    }
  </script>
</body>
</html>

The first iteration was highlighting the letters from the tags which resulted in corrupting the HTML file. Because of this I need to parse the DOM. It only works when I use a single letter. If I add more, then it stops working. JavaScript is not my main language to use and I need a little help so I can resolve this. Thanks

How to track cursor position and get the current key in vanilla-jsoneditor

I am using json-editor-vue + [email protected] to implement a JSON editor. I want to add some additional functionality, for which I need to get information about which key’s value the user is currently editing.

For example:

{
  "k1": "v1",
  "k2": {
    "k3": "user's cursor is here"
  }
}

In this case, I should get the value k3. (I don’t need the full path, just the closest key.)

My requirements are:

  1. Regardless of whether the user has edited the content or not, as long as the cursor moves to a position, I want to be able to get the key corresponding to the value where the cursor is located (or return the key when the cursor is on the key itself)
  2. Receive a notification when the user moves the cursor (optional – if not possible, periodically checking the cursor position would be an acceptable alternative)

Is there a way to implement this? I’ve looked through the vanilla-jsoneditor readme, but it doesn’t seem to cover this functionality.

Changing the default Print Option for Margin in Chrome

Is there any way to change the “Margins” to None in Print Option ( CTRL + p )? using css or javascript.

I have tried @page { margin:0; } but it does not work. Also referred to multiple solutions on stackoverflow but noting seems to work. Basically I want the Print Screen option for Margins to default to “None” instead of “Default.

enter image description here

I tried change chrome print preview default options but did not help.

CSS selector computed aria name

Is it possible to select via a CSS selector (or xpath) an element based on its computed aria name (=accessible name)? For instance for buttons it is computed like

The button has an accessible label. By default, the accessible name is computed from any text content inside the button element. However, it can also be provided with aria-labelledby or aria-label.

I tried to use [aria-label=Foo] that is supposed to be global (edit: hence automatically defined for button based on their content), but it fails…

Motivation: robotframework-browser only allows text, css or xpath selectors in locators (and get by role is quite impractical to use as it involves an extra variable), and chrome recorder extension gives me aria-based selectors.

MWE: you can run it in here:

<script>
    let clickme = () => {
        console.log('foo', document.querySelectorAll('[aria-label=Hello]').length)
    };
</script>

<div class="preference">
  <label for="cheese">Do you like cheese?</label>
  <input name="cheese" id="cheese" />
</div>

<button>Hello</button>

<button onclick={clickme}>Click</button>

In a diagram, relations are always deleted from last to first instead of selected

I have a basic diagram in D3JS, containing objects and relations between objects initialized in these arrays :

      let objectsData = [
        { id: 1, x: 150, y: 150, type: "circle", color: "#ff6b6b" },
        { id: 2, x: 300, y: 200, type: "rect", color: "#4ecdc4" },
        { id: 3, x: 500, y: 150, type: "circle", color: "#45b7d1" },
        { id: 4, x: 400, y: 350, type: "rect", color: "#96ceb4" },
        { id: 5, x: 200, y: 400, type: "circle", color: "#feca57" },
      ];

      let relationsData = [
        { source: 1, target: 2 },
        { source: 2, target: 3 },
        { source: 3, target: 4 },
        { source: 4, target: 5 },
      ];

When my updateRelations() method is first called, everything is displayed correctly, but as I click relations to remove them, they are always removed from last to first in the relationsData table, it’s never the one that’s been clicked that is removed :

const relations = svg.append("g").attr("class", "relations");

  function updateRelations() {

    const relationGroups = relations.selectAll(".relation-group").data(relationsData);

    const enterGroups = relationGroups
    .enter()
    .append("g")
    .attr("class", "relation-group")
    .style("cursor", "pointer")
    .on("click", function (event, d) {
      event.stopPropagation();
      const index = relationsData.indexOf(d);
      if (index > -1) {
        relationsData.splice(index, 1);
        updateRelations();
      }
    });

    // Add visible line
    enterGroups
      .append("line")
      .attr("class", "relation");

    const allGroups = enterGroups.merge(relationGroups);

    allGroups.selectAll(".relation")
    .attr("x1", (d) => getObjectById(d.source).x)
    .attr("y1", (d) => getObjectById(d.source).y)
    .attr("x2", (d) => getObjectById(d.target).x)
    .attr("y2", (d) => getObjectById(d.target).y);

    relationGroups.exit().remove();
  }

  function getObjectById(id) {
    return objectsData.find((obj) => obj.id === id);
  }

At first I thought it was my index variable that was miscalculated (like : it would always be -1), but its value seems correct.

Postman Exchange Data Between Platform (Bitrix-Jotform)

I want to transfer my list of data from Bitrix to Jotform. I already made this flow in Postman, it show no error and seems fine, but it still not posted to my Jotform. Can someone tell me where did I go wrong?

enter image description here

My question:

  1. Is it possible to connect GET Request Bitrix output directly to POST Request Jotform without ‘storing’ it?

  2. Jotfrom input need to be new line for each data, I tried to parse my JSON post response using this code, but as for the input of the POST Request were empty. As shown.

function formatJsonNewLinesCompact(jsonResponse) {
    try {
        const jsonData = typeof jsonResponse === 'string' 
            ? JSON.parse(jsonResponse) 
            : jsonResponse;
            
        return Object.entries(jsonData)
            .map(([key, value]) => `${key}: ${JSON.stringify(value)}`)
            .join('n');
    } catch (error) {
        console.error('Error formatting JSON:', error);
        return jsonResponse;
    }
}

How to obtain the handle of the input box in Electron

When we use a barcode scanner or type things in manually, if the input method is set to Simplified Chinese, a Chinese suggestion box pops up. The first time you hit Enter, it actually selects a word from the suggestion box instead of submitting your input, which is really inconvenient for quick scanning. What I’m doing now is using im-select to switch the input method, but my product manager told me not to change the user’s own input method settings. He wants me to keep the user’s input method as it is, but still let the input box accept English directly, without showing the Chinese suggestion box. Later, I showed him a small program written in C, and he said that would work and users wouldn’t have to change anything. So now I’m learning C++ and planning to package this approach into an exe file, so it’s easy for my Electron app to call.

Why does Wikipedia claim UTF-16 is obsolete when Javascript uses it?

The Wikipedia page for UTF-16 claims that it is obsolete, saying:

UTF-16 is the only encoding (still) allowed on the web that is incompatible with 8-bit ASCII. However it has never gained popularity on the web, where it is declared by under 0.004% of public web pages (and even then, the web pages are most likely also using UTF-8). UTF-8, by comparison, gained dominance years ago and accounted for 99% of all web pages by 2025. The Web Hypertext Application Technology Working Group (WHATWG) considers UTF-8 “the mandatory encoding for all [text]” and that for security reasons browser applications should not use UTF-16.

But browsers support Javascript natively, nearly every interactive webpage uses it, and Javascript strings are UTF-16. What’s going on here?

JavaScript Django default scaling using extends index

I’m using Django’s template inheritance (extends) in every page of the app. The current design looks too zoomed out, and I want to adjust the default scaling through my index.html, but it didn’t work. I also tried using custom CSS, but it still doesn’t fix the issue. Does anyone have an idea how I can adjust the default scaling properly?

I have this in my index.html

<meta name="viewport" content="width=450, initial-scale=0.6, user-scalable=yes, minimum-scale=0.6, maximum-scale=0.6" />

How to choose the correct Firebase JS SDK version for firebase-messaging-sw.js in a Flutter Web app?

I have a Flutter/Firebase web app where I am trying to add firebase cloud messaging (notifications).

Part of this setup is to create a service worker file “firebase-messaging-sw.js”, with example contents:

importScripts('https://www.gstatic.com/firebasejs/10.3.0/firebase-app-compat.js');
importScripts('https://www.gstatic.com/firebasejs/10.3.0/firebase-messaging-compat.js');

firebase.initializeApp({
  apiKey: "YOUR_API_KEY",
  authDomain: "your-app.firebaseapp.com",
  projectId: "your-app",
  storageBucket: "your-app.appspot.com",
  messagingSenderId: "YOUR_SENDER_ID",
  appId: "YOUR_APP_ID"
});

const messaging = firebase.messaging(); 

But how am I supposed to know what exact version (other than 10.3.0) that I should be using?

I assume it relates to the version of firebase messaging in my pubspec.yaml… and that there is a some matrix somewhere online but I cant find it. I keep going in circles through docs, youtube videos, and chat gpt.

There is this doc with a note:

// Please see this file for the latest firebase-js-sdk version: //
https://github.com/firebase/flutterfire/blob/main/packages/firebase_core/firebase_core_web/lib/src/firebase_sdk_version.dart

… but that just tells you the latest version, not the version that matches your project… so I’m nervous to use it… or is it always backward compatible?

Finding the first timestamp where sum of ceiling functions exceeds a threshold

Context:

I’m modeling repeated button presses for an incremental game. There will be buttons in-game set to press repeatedly. These buttons have:

  • variable presses/sec speeds, or rates.
  • variable “speed limits” (max presses/sec allowed).
  • variable cooldown timers when the speed limits are exceeded.
  • variable presses/press multipliers that amplify each press (not the same as multiplying the presses/sec value directly)

In practice, the game calculates in discrete time chunks (ticking). I need to determine exactly when during a tick the speed limit is first broken, so I can apply cooldowns precisely. (speed limit broken -> overheat and reset tally -> cooldown, rinse and repeat).

Some impl details:

To keep presses independent from the size of the tick calculation window, Presses are “aligned” to the next timestamp divisible by (1000/pressesPerSec), i.e. milliseconds per press.
For example, 4 presses/sec would align presses to timestamps % 250 = 0, e.g. … 9750, 10000, 10250, 10500, …

I am storing the repeating presses as press objects (pressObjs), containing the timestamp pressing starts, the timestamp pressing stops, and the presses/sec rate.

I intend for the presses/sec, cooldown timer, etc. to be taken to the extremes; think 10^1000 and 10^-1000. (Thanks break_infinity.js)

The problem:

I’ve reduced this to: Find the smallest timestamp x where f(x) = sum of ceiling functions > threshold

Each group of presses, defined by a pressObj, is effectively a piecewise function with ceiling operations. When multiple press objects overlap, I need to find when their sum first exceeds the speed limit.

Example:

A button is upgraded from 10 presses/sec to 14 presses/sec. The button has a presses/press multiplier = 2 and a speed limit = 25 presses/sec.

Press objects (pressObjs) are created every 210 ms starting at the timestamp 2500. There are a total of 12 press objects; The first six perform 10 presses/sec, and the second six perform 14 presses/sec.

There will be some “uneven behavior” to the running presses/sec tally as it transitions. It will cross the 25 presses/sec speed limit multiple times.

This Desmos visualization shows the limit is first broken around the timestamp 4285.71429. Likely approximating ≈ 30,000 / 7.

Desmos graph of example showing the cumulative sums of piecewise functions as stacked colors, highlighting the eyeballed approximate timestamp at which the cumulative sum (running presses per second tally) first goes over 25.

(In this example, because we see the limit is broken on the ninth press object, the last three press objects would not be created during the run of the program, unless cooldown time was tiny.)

My thought process:

Each press object effectively creates a piecewise function based on four breakpoints where its effect on the running presses/sec tally changes:

  1. repeated pressing starts — incrementing the running tally,
  2. repeated presses stop, or expire (happen over a second ago) at the same rate they are performed — plateauing the running tally,
  3. presses have stopped and the last presses begin expiring — decrementing the running tally,
  4. the last press has expired — tally is back to 0.

The pseudocode for constructing the piecewise function from a repeated press object:

tsStartPressing = pressObj.startPressingTimestamp
tsStopPressing = pressObj.stopPressingTimestamp
ppMs = pressObj.pressesPerSecond / 1000
mspp = 1 / ppMs
pressMul = pressObj.pressMul

// The four breakpoints
tsStart
tsPlateau = min( tsStop, tsStart + 1000 )
tsStartDecrease = max( tsStop, tsStart + 1000 )
tsEnd = tsStop + 1000

// The first performed press is aligned to the next timestamp divisible by milliseconds/press
tsAlignedFirstPress = ceil(tsStartPressing / mspp) * mspp

plateauTally = ceil((tsPlateau - tsAlignedFirstPress) * ppMs) * pressMul

// Breakpoints 1-2: Increment -- presses 'ramp up'
F_inc(t) = ceil((t - tsAlignedFirstPress) * ppMs) * pressMul

// Breakpoints 2-3: Plateau -- presses stop, or expire at the same rate they are pressed
F_plateau(t) = plateauTally

// Breakpoints 3-4: Decrement -- presses 'ramp down' as no more occur and they expire
F_dec(t) = plateauTally - ceil((t - (tsStartDecrease - tsStartPressing) - tsAlignedFirstPress) * ppMs) * pressMul

// Piecewise:
F(t) = {
    F_inc(t)      |  tsStart <= t < tsPlateau
    F_plateau(t)  |  tsPlateau <= t < tsStartDecrease
    F_dec(t)      |  tsStartDecrease <= t < tsEnd
    0             |  else
}

My current approach:

After processing overlapping piecewise functions’ segments — summing plateau segments as constants, and cancelling out increment and decrement ceiling functions with equal presses/sec — I am left with ceiling functions with unequal presses/sec.

My current algorithm splits every ceiling function into many flat segments, which creates insanely many breakpoints when presses/sec values are large (e.g., 10^10 presses/sec). This becomes computationally expensive.

As a sanity check I put the above 10 p/s -> 14 p/s example into Mathematica to use its fancy Minimize, NMinimize, and ArgMin functions. (I can post the full Mathematica code if desired.) The results it produced were rather inconsistent. The best was 4293, not even close to 30,000 / 7 ≈ 4285.71429.

I know optimizing nonlinear or non-convex problems is very hard analytically. There are several posts on math.stackexchange.com regarding sums with floor()s and ceil()s, but none regarding the specific case of finding the smallest x that causes f(x) > threshold.

Question:

How can I efficiently find the first timestamp where the sum of the ceiling functions exceeds a threshold?

Alternatively, is there a better approach for modeling this game mechanic that avoids the ceiling function complexity entirely?

The core issue is that ceiling functions create discontinuous jumps, and their sum can exceed the threshold at any of these discontinuity points. I need an efficient way to check these critical points without evaluating every possible breakpoint.

Angular NBG Modal appears at the bottom of the screen

I have an Angular app using NgbModal from ng-bootstrap, but the modal appears incorrectly: instead of centering and overlapping the parent, it renders at the bottom of the screen underneath the parent component.

Inspecting the modal’s computed styles in devtools shows it’s missing expected positioning CSS like position: fixed|absolute, top, left, and transform: translate(-50%, -50%), which ng-bootstrap normally applies to center modals.

When inspecting the modal element in the browser devtools, I see that the computed styles do not include any position: fixed|absolute, top, left, or transform: translate(-50%, -50%) rules that it would normally have. The only CSS rules I can find on the modal or its parents are font and margin/padding styles — nothing about positioning.

I suspect that either the modal CSS from ng-bootstrap is missing, not loaded properly,
or some other CSS is overriding or removing the positioning styles.

This is the parent:

 <button class="add-user-btn" (click)="openNewUserModal(null)">Add User</button>

...

import {NgbModal} from "@ng-bootstrap/ng-bootstrap";
export class UsersComponent implements OnInit {

  constructor(
    private modalService: NgbModal
  ) { }

  openNewUserModal(user: User | null = null) {
    const modalRef = this.modalService.open(UserModalComponent);
  }

Child:

<div class="modal-header">
  <h4 class="modal-title">User Modal</h4>
  <button type="button" class="btn-close" aria-label="Close" (click)="activeModal.dismiss()"></button>
</div>
<div class="modal-body">
  Hello, minimal modal!
</div>
<div class="modal-footer">
  <button type="button" class="btn btn-primary" (click)="activeModal.close('Save click')">Save</button>
</div>


...

import {NgbActiveModal} from "@ng-bootstrap/ng-bootstrap";

@Component({
  selector: 'app-user-modal',
  templateUrl: './user-modal.component.html',
  styleUrls: ['./user-modal.component.scss']
})
export class UserModalComponent implements OnInit {

  constructor(public activeModal: NgbActiveModal) { }

}

There is no custom CSS for the modal right now.

I have confirmed a few things that I have seen suggested elsewhere:

1.) I imported the Angular Material prebuilt theme globally at the top of styles.scss:

@import "~@angular/material/prebuilt-themes/indigo-pink.css";

2.) In my angular.json file my build configuration includes both Angular Material’s and Bootstrap’s CSS files globally:

"styles": [
              "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css",
              "./node_modules/bootstrap/dist/css/bootstrap.min.css",
              "src/styles.scss"
                        ],

This is currently my index.html. I do not believe that I need to do anything here but I have read some answers suggesting trying some things here and I’ve tried it all only to have other styles messed up so I have not really touched it. I am open to suggestions.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>TIMS</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="favicon.ico">
  <link rel="preconnect" href="https://fonts.gstatic.com">
  <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
  <app-root></app-root>
</body>
</html>

Venmo PayPal Smart Button shows inconsistent loader after clicking “Pay” in popup

I’m integrating Venmo via PayPal Smart Buttons (JavaScript SDK).

When a user clicks the Venmo button, a popup appears where they log in and click “Pay”. After this:

The popup closes

The onApprove function runs

I make an API call to my backend to capture the payment via /paypal/capture-order

I set a loader flag (screenLoading = true) to show the UI is processing

❗The Problem:
Sometimes the loader shows for 2–3 seconds and disappears, even though the backend is still processing

Sometimes the loader doesn’t show at all

This creates confusion for the user, who might think the payment failed or nothing is happening.

questions about callback function in javascript

So I was learning Javascript and came across callback function, from what I understand, callback function is a way of making sure that some dependent code runs after the code that it was dependent on is finished.

And so I have this code here:

//A function that takes an argument, which is another function, that will be run after everything else above is done

function requestFunc(callBackFunc){
    const request = new XMLHttpRequest();          
    request.open("GET", "https://somewebsite.com");
    request.send();

    callBackFunc(request.response);
}

//A function that logs the argument

function printFunc(response){
    console.log(response);
}

//Calling requestFunc() and passing printFunc() as the argument

requestFunc(response => {
    printFunc(response);
});

So I tested this, and the output was blank, nothing was displayed because apparently printFunc() was called before the response finished loading, but isn’t Javascript supposed to wait and run printFunc() after everything else was done?