Accessing a data attribute on a script tag on a Node server

This question is designed as a bit of fun!

Let’s say I have these two files:

index.html

<!DOCTYPE html>
<html lang="en">
  <body>
    <script src="http://localhost:1234" data-foo="bar"></script>
  </body>
</html>

server.mjs

import http from "http"

const server = http.createServer((req, res) => {
  // can I access the data-foo="bar" attribute from the script tag here?
  req.setHeader("Content-Type", "application/javascript")
  req.end("") // empty JavaScript file
})

server.listen(1234, () => {
  console.log("Server running at http://localhost:1234/")
})

How can I access the data attribute on the script tag in server.mjs?

One answer (cheating!) would be to add it to the src instead. e.g.

<script src="http://localhost:1234?foo=bar"></script>

But maybe there’s a way of using data attributes?

TinyMCE: How can I convert an inserted image to Base64?

I must have looked at all the entries on the Internet, but nothing works. I am using TinyMCE 6 and I have the following code at the moment:

automatic_uploads: true,
paste_data_images: true,
plugins: 'table lists image code paste',
images_upload_handler: (blobInfo) => {
    const base64str = "data:" + blobInfo.blob().type + ";base64," + blobInfo.base64();
    return Promise.resolve(base64str);
}

The conversion works, and the “src” attribute of the tag is displayed as Base64. The tag also has a “data-mce-src” attribute, which contains the entire Base64 string. However, as soon as I click out of the text field, the “src” attribute becomes:

blob:http://localhost:8080/b2ee66ea-75f6-4ce8-9c9e-2e219582c987

How do I manage to save the base64 string in the “src” attribute without it always being reset to a reference to the server?

I have tried every other solution on stackoverflow. Unfortunately without success

How to create a photo gallery widget/database?

I am relatively new to IT and currently working on building a security system using a Raspberry Pi and Thingsboard. My Raspberry Pi 5 is connected to a camera and a PIR sensor and it shots a photo every time the PIR sensor detects a body, so I can see who was there.
I managed to build a widget in a Thingsboard dashboard that shows the latest photo shot. Basically, a Python code is run in my Raspberry, then it encode the photo from JPEG to base64 and sends the photo to Thingsboard in base64; after that, the widget receives the image and decode the photo in JPEG using Javascript.
Now, I need to find a way to see – let’s say – all the photos shot in the past 24 hours. Ideally, I would like to have a new widget on my dashboard where I can scroll through the photos captured over the specified timeframe (hours/days).
I tried to use a time-series table but the images aren’t displayed correctly (I only see the base64 encoded string and can’t decode it inside this widget). I’ve read the documentation and tried to understand how the rule engine works and it seems to me that it could be used for my goal but I’m completely lost.
Thanks in advance for your assistance.

Getting error in Urlfetchapp request from API

I have created this code and it used to work, but it has stopped working.

I checked the header requests using Requestly and I am getting the correct JSON response in the browser.

I am not sure why it is working in this case. I am getting the error message:Unauthorized. Response Code 401.

Can someone please investigate and let me know what has changed?

An example URL to try would be https://api.nhsd.healthdirect.org.au/v5/healthcareServices/_search?requestContext.serviceDeliveryMethod=PHYSICAL&filter.serviceType.codes=nhsd%3A%2Freference%2Ftaxonomies%2Fsnomed-servicetype%2F788007007&responseControl.offset=0&responseControl.limit=20&location.proximity.near_distance=1000000&location.proximity.near=-33.87341360149675%2C151.21006456818213

function getDataFromAPI() {
  try {
    // Get URLs from the sheet named "URLs"
    var spreadsheetId = "1rg91FoGbBwmsSu3ZfP82dSBpmqe1xY3WObg1rfyQVck";
    var urlsSheetName = "URLs";
    var dataSheetName = "Data";

    var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
    var urlsSheet = spreadsheet.getSheetByName(urlsSheetName);
    var dataSheet = spreadsheet.getSheetByName(dataSheetName);

    if (!urlsSheet) {
      throw new Error("Sheet named 'URLs' not found in the specified spreadsheet.");
    }

    // Get URLs from column C starting from row 2
    var lastRow = urlsSheet.getLastRow();
    var urls = urlsSheet.getRange(2, 3, lastRow - 1, 1).getValues().flat();

    if (!urls || urls.length === 0) {
      throw new Error("No URLs found in the sheet 'URLs'.");
    }

    // Iterate through each URL
    urls.forEach(function(url) {
      var headers = {
        "Accept": "*/*",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36",
        "Accept-Language": "en-US,en;q=0.9",
        "Accept-Encoding": "gzip,deflate,br",
        "X-Api-Key": "XyS1Zywa5e9PcekAmgaid8MVnHrHbmdh7Hkzcv9a",
        "Connection": "keep-alive",
        "Referer": "https://widget.nhsd.healthdirect.org.au/"
      };

      var options = {
        "method": "GET",
        "contentType": "application/json",
        "headers": headers,
        "muteHttpExceptions": true
      };
      console.log(url);
      var response = UrlFetchApp.fetch(url, options);
      console.log(response);
      console.log(response.getContentText());
      var data = JSON.parse(response.getContentText());


      if (!data || !data._embedded || !data._embedded.healthcareServices) {
        throw new Error("Invalid or missing data from the API for URL: " + url);
      }

      // Extract data
      var extractedData = data._embedded.healthcareServices.map(function(service) {
        // Extracting serviceType.label from the array
        var serviceTypeLabel = service.serviceType && service.serviceType[0] ? service.serviceType[0].label : '';

        // Extracting addressLine2 from physicalLocation
        var addressLine2 = service.location && service.location.physicalLocation ? service.location.physicalLocation.addressLine2 : '';

        // Extracting additional location details
        var addressLine3 = service.location && service.location.physicalLocation ? service.location.physicalLocation.addressLine3 : '';
        var suburbLabel = service.location && service.location.physicalLocation && service.location.physicalLocation.suburb ? service.location.physicalLocation.suburb.label : '';
        var stateLabel = service.location && service.location.physicalLocation && service.location.physicalLocation.state ? service.location.physicalLocation.state.label : '';
        var postcode = service.location && service.location.physicalLocation ? service.location.physicalLocation.postcode : '';

        // Extracting contacts.value based on different contacts.valueType
        var websiteContacts = extractContactsByType(service.contacts, "Website");
        var phoneContacts = extractContactsByType(service.contacts, "Phone");
        var faxContacts = extractContactsByType(service.contacts, "Fax");
        var emailContacts = extractContactsByType(service.contacts, "Email");

        // Log the JSON response for one row of data
        Logger.log("JSON Response for One Row (URL: " + url + "): " + JSON.stringify(service));

        return [
          service.organisation.name,
          service._links.self.href,
          serviceTypeLabel,
          addressLine2,
          addressLine3,
          suburbLabel,
          stateLabel,
          postcode,
          websiteContacts.join(", "),
          phoneContacts.join(", "),
          faxContacts.join(", "),
          emailContacts.join(", ")
        ];
      });
      dataSheet.getRange("A2:L").clearContent();
      // Find the last row in the sheet and append data below it
      var lastDataSheetRow = dataSheet.getLastRow();
      var dataRange = dataSheet.getRange(lastDataSheetRow + 1, 1, extractedData.length, extractedData[0].length);
      dataRange.setValues(extractedData);

      Logger.log("Data appended to the sheet named 'Data' for URL: " + url);
    });

    Logger.log("All data appended to the sheet named 'Data' for all URLs.");
  } catch (error) {
    Logger.log("Error: " + error.message);
  }
}

// Helper function to extract contacts.value based on contacts.valueType
function extractContactsByType(contacts, valueType) {
  return contacts ?
    contacts
    .filter(function(contact) {
      return (
        contact.valueType &&
        contact.valueType.label &&
        contact.valueType.label.toLowerCase() === valueType.toLowerCase()
      );
    })
    .map(function(contact) {
      return contact.value;
    }) :
    [];
}

Find longest subsequnce- cant reset the array

I have a solution:

theres a task to find a longest common subsequence

function LCS(x, y) {
  let res = [];
  let temp = [];
  for (let i = 0; i < x.length; i++) {
    let val1 = x[i];
    console.log("val 1 is " + val1);
    for (let j = i; j < y.length; j++) {
      let val2 = y[j];
      console.log("val 2 is " + val2);
      if (val1 == val2) {
        console.log("they are the same");
        temp.push(val1);
        break;
      }
    }
    if (temp.length > res.length) {
      res = [...temp]; 
    }
  }
  return res.join("");
}

and for:

console.log(LCS("abxabc", "abyabc"))

the return value is:

ababc  instead of  `abc`

I think the logic is right, but i dont know why the ‘ab’ is not resseted. How to fix this? I think i only need this minor fix and the function will be completed. I want to undestand the task, not copy-paste the solution. I tried moving

temp = []

to outer loop but it didnt work.

Add framer motion effect for a flowbite-react modal

Im facing an issue regarding on adding the framer motion effect for the modal component

import {
  Modal as BaseModal,
  ModalProps as BaseModalProps,
  CustomFlowbiteTheme,
} from 'flowbite-react';
import React, { ReactNode } from 'react';
import { cn } from '@cafepos/shared/utils/cn';
import { motion } from 'framer-motion';

const customTheme: CustomFlowbiteTheme['modal'] = {
  content: {
    base: 'relative h-auto w-full p-4 ',
    inner: 'relative rounded-lg bg-white shadow flex flex-col max-h-[90dvh]',
  },
};

type ModalProps = {
  bodyClassName?: string;
  title: ReactNode;
  classNameHeader?: string;
} & Omit<BaseModalProps, 'title'>;

const Modal: React.FC<ModalProps> = ({
  className,
  bodyClassName,
  title,
  children,
  ...rest
}) => {
  return (
    <motion.div
      initial={{ y: '100%' }}
      animate={{ y: 0 }}
      transition={{ duration: 0.3, type: 'linear' }}
    >
      <BaseModal className={className} theme={customTheme} dismissible {...rest}>
        <BaseModal.Body
          className={cn('pt-0 md:px-[71px] md:pb-[65px]', bodyClassName)}
        >
          <div className="w-full text-center font-bold text-xl p-2">{title}</div>
          {children}
        </BaseModal.Body>
      </BaseModal>
    </motion.div>
  );
};

export default Modal; 

But the effect are not applied for the modal.
If I wrap it only for the body, the effect are only applied for the body but the background of the modal are not applied. How should I fix it?

And I have try create some const like:

const MotionComponent = motion(BaseModal )

But it throw error

How to calculate the page numbers to display in pagination?

I’m looking to create a function for pagination that determines which page numbers to display (1 | 2 | 3 | 4 …).

I follow these specifications:

  • The function, let’s call it calculatePages, should return an array of page numbers.
  • The inputs to the function are:
    • total: the total number of results.
    • perPage: the maximum number of items to display on each page.
    • page: the current page.
    • max: the maximum number of page numbers to display.
  • Here are the rules the function should follow:
    1. Always display the maximum number of items unless the total number of pages (totalPages) is less than max. In that case, display page numbers from page until totalPages.
    2. Start displaying from page until max items (if available). For example, if page=5, max=10, and totalPages=8, display 5,6,7,8. If the number of displayed pages is less than max, display pages from 1 until the required number is reached.
    3. If totalPages is more than max, start from page until the next max items, and if the number of displayed pages is less than max, go back to the beginning and add the difference to match max items.

Here’s what I did so far:

import { range } from 'lodash';

function calculatePages({ total, perPage, page, max }) {
  const pages = Math.ceil(total / perPage);
  const totalPages = [...Array(pages).keys()].map((i) => i + 1);

  let start = page - 1;
  const end = start + max > max ? start + (max - 1) : start + max;

  if (end - start < max) {
    start = start - (end - (end - start));
  }

  const results = totalPages.slice(start, end);
  return results;
}

const tests = [
  { in: { total: 1, perPage: 4, page: 1, max: 10 }, out: [1] },
  { in: { total: 4, perPage: 4, page: 1, max: 10 }, out: [1] },
  { in: { total: 8, perPage: 4, page: 1, max: 10 }, out: [1, 2] },
  { in: { total: 8, perPage: 4, page: 2, max: 10 }, out: [1, 2] },
  {
    in: { total: 38, perPage: 4, page: 2, max: 10 },
    out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  },
  {
    in: { total: 40, perPage: 4, page: 2, max: 10 },
    out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  },
  {
    in: { total: 40, perPage: 4, page: 1, max: 10 },
    out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  },
  {
    in: { total: 40, perPage: 4, page: 9, max: 10 },
    out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  },
  {
    in: { total: 40, perPage: 4, page: 10, max: 10 },
    out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  },
  {
    in: { total: 90, perPage: 4, page: 1, max: 10 },
    out: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  },
  { in: { total: 70, perPage: 4, page: 17, max: 10 }, out: range(9, 19) },
];

describe('calculatePages function', () => {
  tests.forEach((t, i) => {
    test(`#${i} ${JSON.stringify(t.in)}`, () => {
      const a = calculatePages(t.in);
      expect(t.out.length).toBeLessThanOrEqual(t.in.max);
      expect(a.join(',')).toBe(t.out.join(','));
    });
  });
});

I’m encountering an issue with the test case where total=70, perPage=4, page=17, and max=10. It’s expected to return [9, 10, ..., 17, 18], but it’s not passing.

Keyboard opens and then dissappear when clicking on input field on Android Devices

The keyboard is dissapearing automatically after 0.1 seconds when trying to enter card details/stripe payment details.
I have this problem on https://womanverse.ro/membership-checkout/?level=1. I was trying to reproduce the problem on Pixel 7 emulator device, but it is appearing only in live mode on Android Devices.

You can check it here https://streamable.com/xj49em.

Aalexusmai laravel-file-manager how store events in database

I have used alexusmai/laravel-file-manager for my File Manager system. I need help how I can store various events e.g. upload, delete , copy , paste etc. in my database table?

I have configured filemanager on my local system and test create , delete files now I am trying to store these events in database which user add , delete or upload files.

Resetting NetSuite Sandbox to Default Without Production Data

I’m seeking advice on resetting a NetSuite sandbox to its original, default state (no data, default settings) after it’s been refreshed from the production account. The aim is to use the sandbox for testing without production data interference.

Challenges:
Existing methods mainly suggest refreshing from production, which is not suitable for our needs.
Manual data cleanup is overly time-consuming and may miss hidden configurations.

Questions:
Is a full reset to a “newly provisioned” state possible for a NetSuite sandbox?
Are there recommended practices or tools for thoroughly cleaning the sandbox environment?

Any guidance or insights on achieving a clean slate for development and testing in a NetSuite sandbox would be greatly appreciated.

Resetting NetSuite Sandbox to Default Without Production Data

I’m seeking advice on resetting a NetSuite sandbox to its original, default state (no data, default settings) after it’s been refreshed from the production account. The aim is to use the sandbox for testing without production data interference.

Challenges:
Existing methods mainly suggest refreshing from production, which is not suitable for our needs.
Manual data cleanup is overly time-consuming and may miss hidden configurations.

Questions:
Is a full reset to a “newly provisioned” state possible for a NetSuite sandbox?
Are there recommended practices or tools for thoroughly cleaning the sandbox environment?

Any guidance or insights on achieving a clean slate for development and testing in a NetSuite sandbox would be greatly appreciated.

Ghost line when adding box-shadow to a div with background-image and circular shape

I want to insert an image with a box-shadow that “opens” when you hover over with the mouse. The problem is that a ghost border is appearing and I am not sure how I can deal with it.

I tried setting a border with black color, also to set the background-color of the div containing the image to black, but it’s not helping.
Is there another approach I could take here?

body {
    background-color: black;
}

#imageShadow {
    height: 400px;
    width: 400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    border-radius: 50%;
    box-shadow: 0px 0px 40px 140px rgb(0, 0, 0) inset;
    transition: box-shadow 1s;
    background-image: url('https://images.freeimages.com/images/large-previews/866/butterfly-1-1535829.jpg');
}


#imageShadow:hover {
    box-shadow: 0 0 20px 20px rgb(0, 0, 0) inset;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">  
</head>

<body>
<div id='imageShadow'></div>
</body>

</html>

Ghost line when adding box-shadow to a div with background-image and circular shape

I want to insert an image with a box-shadow that “opens” when you hover over with the mouse. The problem is that a ghost border is appearing and I am not sure how I can deal with it.

I tried setting a border with black color, also to set the background-color of the div containing the image to black, but it’s not helping.
Is there another approach I could take here?

body {
    background-color: black;
}

#imageShadow {
    height: 400px;
    width: 400px;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    margin: auto;
    border-radius: 50%;
    box-shadow: 0px 0px 40px 140px rgb(0, 0, 0) inset;
    transition: box-shadow 1s;
    background-image: url('https://images.freeimages.com/images/large-previews/866/butterfly-1-1535829.jpg');
}


#imageShadow:hover {
    box-shadow: 0 0 20px 20px rgb(0, 0, 0) inset;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">  
</head>

<body>
<div id='imageShadow'></div>
</body>

</html>

how to get my javascript output in json format

success: true
datatype: "string"
timestamp: 09140820
registerId:123"
**value: "{"Relay Abc":"Off","Relay Bedf":"On","MP  R31":0,"NM  R2":-1,"SP  R3":-1,"Current":0,"Voltage":0,"Voltage2":51}"**
deviceID: "5A6B3038-8FA0-43F8-A54B-BCE52902337C"
tagName: "k_Test_02"
deviceName: "abc_SERVER"
   

imagege is the code of the function node

I want same output as shown just value data should come one after another

how to get my javascript output in json format

success: true
datatype: "string"
timestamp: 09140820
registerId:123"
**value: "{"Relay Abc":"Off","Relay Bedf":"On","MP  R31":0,"NM  R2":-1,"SP  R3":-1,"Current":0,"Voltage":0,"Voltage2":51}"**
deviceID: "5A6B3038-8FA0-43F8-A54B-BCE52902337C"
tagName: "k_Test_02"
deviceName: "abc_SERVER"
   

imagege is the code of the function node

I want same output as shown just value data should come one after another