JavaScript hard one! getting available time from array of available dates-time and array of booked dates-time

I am working in google app script
Please see the array of objects below, I’m trying to return the available array but with out the booked array timing in it

this is a sample of the Available array

[{"ID":362,"startDate":"2021-11-01T04:00:00.000Z","endDate":"2040-12-30T05:00:00.000Z","startTime":"1899-12-30T17:30:00.000Z","endTime":"1899-12-30T18:30:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"},
{"ID":434,"startDate":"2022-01-01T05:00:00.000Z","endDate":"2040-12-30T05:00:00.000Z","startTime":"1899-12-30T16:30:00.000Z","endTime":"1899-12-30T17:30:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"},
{"ID":614,"startDate":"2022-01-02T05:00:00.000Z","endDate":"2040-12-30T05:00:00.000Z","startTime":"1899-12-31T01:45:00.000Z","endTime":"1899-12-31T02:30:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"},
{"ID":732,"startDate":"2022-04-07T04:00:00.000Z","endDate":"2040-12-30T05:00:00.000Z","startTime":"1899-12-30T18:30:00.000Z","endTime":"1899-12-30T19:30:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"},
{"ID":758,"startDate":"2021-11-01T04:00:00.000Z","endDate":"2040-12-30T05:00:00.000Z","startTime":"1899-12-30T15:00:00.000Z","endTime":"1899-12-30T19:30:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"}]

and this is a sample of the Booked array (the ones that don’t have a end date are till the end of the world)

[{"ID":185,"startDate":"2022-01-01T05:00:00.000Z","endDate":"","startTime":"1899-12-30T16:30:00.000Z","endTime":"1899-12-30T17:30:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"},
{"ID":247,"startDate":"2022-01-02T05:00:00.000Z","endDate":"","startTime":"1899-12-31T01:45:00.000Z","endTime":"1899-12-31T02:30:00.000Z","daysOfWeek":"Sunday,Tuesday,Thursday"},
{"ID":624,"startDate":"2021-11-01T04:00:00.000Z","endDate":"","startTime":"1899-12-30T17:30:00.000Z","endTime":"1899-12-30T18:30:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"},
{"ID":901,"startDate":"2022-04-07T04:00:00.000Z","endDate":"2022-04-22T04:00:00.000Z","startTime":"1899-12-30T18:30:00.000Z","endTime":"1899-12-30T19:30:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"},
{"ID":1052,"startDate":"2022-04-12T04:00:00.000Z","endDate":"","startTime":"1899-12-30T15:15:00.000Z","endTime":"1899-12-30T16:15:00.000Z","daysOfWeek":"Sunday,Monday,Tuesday,Wednesday,Thursday"}]

I know this is a hard one but please help me out

Thank you so much for your time

JS open url in new tab on background is not working

I want script to open in new tab url without focusing on it. I
tried:

window.open("https://www.google.com/").blur();
window.focus();

But it opens a new tab and focuses on google.com not on site with script. What’s wrong?

edit:

This Open a new tab in the background? is not resolving my question. Answer is too old and doesn’t work anymore! Admins please read bold text: UPDATE: By version 41 of Google Chrome, initMouseEvent seemed to have a changed behavior, and so this answer no longer works.

JIMP Image being cut short

I am using Node.js, Express, NodeMailer, and JIMP to try to email an image after a POST. Sending an email with a completed image works when requests are spaced out but when I send multiple, sometimes old images are sent instead or partial images. I decided to cut out email for the moment and just do res.sendFile(myImage) to test that JIMP is finishing its work before the next line is called.
This results in partial images being displayed and I’m not sure why? The relevant code is below.

var Jimp = require('jimp');


app.post('/invite/:email/:name', async (req,res) => {
  try {
    var email = atob(req.params.email);
    var name = atob(req.params.name);
    var data = req.body;
    const inviteImage = await makeImg(name, data);
    res.type('png')
    res.sendFile(__dirname+`/${inviteImage}`);
  } catch (error) {
    return next(error);
  }
});


async function makeImg(name, data) {
  try {
    let name2 = data["Name"];
    let style = data["Style"];
    let fanciness = data["Fanciness"];
    let dressMsg = dress(fanciness);
    let dateTime = data["Date"];
    let regex = /([0-9]+)-([0-9]+)-([0-9]+)T([0-9]+:[0-9]+)/;
    let match = dateTime.match(regex);
    let ordinal = getOrdinal(match[3][1]);
    let month = getMonth(match[2]);
    let date = `${match[3]}${ordinal} ${month} ${match[1]}`;
    let time = `Time: ${match[4]}`;
    
    let smallFontName;
    let largeFontName;
    let image;
    let filename = "";
    if(fanciness <= 3){
      image = await Jimp.read('./imgs/casualTemplate.png');
      filename = "Casual";
      smallFontName = Jimp.FONT_SANS_64_WHITE;
      largeFontName = Jimp.FONT_SANS_128_WHITE;
    }else if(fanciness > 3){
      image = await Jimp.read('./imgs/fancyTemplate.png');
      filename = "Fancy";
      smallFontName = Jimp.FONT_SANS_64_BLACK;
      largeFontName = Jimp.FONT_SANS_128_BLACK;
    }

    let width = image.bitmap.width;

    let [smallFont, largeFont] = await Promise.all([Jimp.loadFont(smallFontName), Jimp.loadFont(largeFontName)]);
    
    // Print Greeting
    await image.print(smallFont, (width-650)/2, 162, {
      text: `${name} invites ${name2} To:`,
      alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
      alignmentY: Jimp.VERTICAL_ALIGN_TOP
    }, 650, 162);

    // Print Date Activity
    await image.print(largeFont, (width-810)/2, 340, {
      text: `${style}`,
      alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
      alignmentY: Jimp.VERTICAL_ALIGN_CENTER
    }, 810, 505);
    
    // Print Dress fanciness
    await image.print(smallFont, (width-810)/2, 970, {
      text: dressMsg,
      alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
      alignmentY: Jimp.VERTICAL_ALIGN_TOP
    }, 810, 66);

    // Print date of the date
    await image.print(smallFont, (width-810)/2, 1080, {
      text: `${date}`,
      alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
      alignmentY: Jimp.VERTICAL_ALIGN_TOP
    }, 810, 66);

    // Print time of the date
    await image.print(smallFont, (width-810)/2, 1187, {
      text: `${time}`,
      alignmentX: Jimp.HORIZONTAL_ALIGN_CENTER,
      alignmentY: Jimp.VERTICAL_ALIGN_TOP
    }, 810, 66);

    await image.writeAsync(`./a${filename}Invite.png`);
    
    return `a${filename}Invite.png`;
  } catch(err) {
    console.log(err);
  }
}

Only the top of the image has rendered and saved, the grey shows how much more was left undone:enter image description here

Next.js client side API not rendering correct data?

I am attempting to learn Next.js by expanding upon Brad Traversy’s Next.js code. There is already one API route that returns a JSON object with all articles.

I am attempting to add “category” and “subcategory” attributes to the items in the data and create a series of routes that look like root.com/category/[category]/subcategory/[subcategory], but they all pull from the same dataset. To do this, I’ve tried to slugs that look like this under the API folder:

> category
>> index.js
>> [category].js

> subcategory
>> index.js
>> [subcategory].js

Each of the index.js files looks like this:

import { items } from '../../../data'

export default function handler({ query: { category } }, res) {
  const filtered = items.filter((item) => item.category === category)
  res.status(200).json(filtered[0])
}

The [slug].js files look like this:

import { items } from '../../../data'

export default function handler({ query: { category } }, res) {
  const filtered = items.filter((item) => item.category === category)
  res.status(200).json(filtered[0])
}

(so the same, I understand this might be redundant but I am throwing spaghetti at the wall). The intent of this is to only pull items where the category or subcategory matches the query.

In the pages, I have a structure like this (if this could be collapsed into one, that’d be great):

> category
>> [category]
>>> index.js

> subcategory
>> [subcategory]
>>> index.js

Where each of the index.js files looks like this:

const category = ({ items }) => {
  return (
    <>
      <Meta title={items.category} description={items.category} />
      <div>
        <ItemList items={items}/>
      </div>
      <Link href='/'>Go Back</Link>
    </>
  )
}

export const getStaticProps = async (context) => {
  const res = await fetch(`${server}/api/category/${context.params.category}`)
  const item = await res.json()

  return {
    props: {
      items,
    },
  }
}

export const getStaticPaths = async () => {
  const res = await fetch(`${server}/api/items`)
  const items = await res.json()

  const categories = items.map((item) => item.category)
  const paths = categories.map((category) => ({ params: { category: category.toString() } }))

  return {
    paths,
    fallback: false,
  }
}

export default category

However, the list of items is always the same on the front end. Could someone please help me understand what is happening, or a better approach to nested routing in Next?

ESLint: how to sort import members with eslint-plugin-import?

I’m trying to add the sorting of import members such as this rule in sort-member.

However, since I’m already using eslint-plugin-import, there is a conflict because each of these rules is trying to sort imports based on different parameters:

  • sort-member sorts following the order ["none", "all", "multiple", "single"], depending on how many imports there is from one module
  • eslint-plugin-import sorts following the order ["builtin", "external", "parent", "sibling", "index"], depending on the type of import

Is there a way to only use the member sort of sort-member (== ignore the memberSyntaxSortOrder rule), or is there a feature similar to memberSort built in eslint-plugin-import?

All I’m trying to do is to have an error for:

import { b, a, c } from 'foo.js'

And have it automatically fixed to:

import { a, b, c } from 'foo.js'

How to access files from GitHub Action repo?

I have created a JavaScript automation and in that script I have created couple of YML files and I’m importing them using fs and js-yaml libraries. I have hosted this code in repo A.

I want to convert my repo A into an GitHub action. I have followed the documentation from GitHub to create JavaScript action. I have used the verbal/ncc to create one file with all my libraries as suggested by GitHub.

But when I use this action in repo B, I get an error saying the yml files are not available at the mentioned path.

Does GitHub workflow download the action’s repo during execution? if yes, how can I pass these iml files into the script?

If not, what are the options to pass these files into script?

Валидация имени и фамилии в input [closed]

Есть задание:
Поле “Имя Фамилия” может состоять только из 2-х слов (имя и фамилия). Min длина каждого слова 3 символа, max 30. Между словами только 1 пробел.

Код:

  const lengthValue = value.split(' ').length
  
  if (lengthValue !== 2) {
    return false
  } else {
      return value.split(' ').filter(el => el.length > 3 && el.length <= 30)
        ? value.search(/[A-Za-z]+(s+[A-Za-z]+)?/gi) !== -1
          ? true
          : false
        : ''
  }
} 

Проблема в том, что после первого слова, когда ставишь пробел, уже возвращает true. Почему? Как решить и проверить на пробелы? 

WYSIWYG: How to format the correct string? [duplicate]

I am trying to develop a simple WYSIWYG editor.

const SELECTED_TEXT = document.getSelection();

document.querySelector('button').addEventListener('click', () => {
  document.querySelector('p').innerHTML = document.querySelector('p').innerHTML.replace(SELECTED_TEXT, `<strong>${SELECTED_TEXT}</strong>`);
});
<button>B</button>
<p>Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum Lorem Ipsum</p>

The text contains the same words several times. So, if you select the last Lorem, the first one will be displayed in bold.

How can I format the correct word?

Primevue MultiSelect in DataTable not rendering correctly

I am using primevue and creating a datatable that has sort, search and the show/hide column functionality. The sort and search work some of the time and the show/hide does not work at all. The drop down that shows the columns to select to show/hide does not show. Below is a snippet of the code:

const searchResults = ref(mockDocumentData);

const filters1 = ref({ 'global': {value: null, matchMode: FilterMatchMode.CONTAINS}});

const columns = ref([
{ field: 'subject', header: 'TITLE' },
{ field: 'description', header: 'DESCRIPTION' },
{ field: 'dateOfclose', header: 'DATE OF Close' },
{ field: 'dateOfInterview', header: 'DATE OF INTERVIEW' },
{ field: 'Summary', header: 'SUMMARY' }
]);

const selectedColumns = ref(columns.value);

const onToggle = (val: string) => {
selectedColumns.value = columns.value.filter((col) => val.includes(col));
}     

</script> 

<template>
  <DataTable 
        :value="searchResults" 
        responsive-layout="scroll"
        v-model:filters="filters1"
        selectionMode="single"
        stateStorage="session"
        stateKey="dt-state-demo-session"
        dataKey="id"
        >
    <template #header>
      <div style="text-align: left">
        <MultiSelect
          :model-value="selectedColumns"
          :options="columns"
          option-label="header"
          placeholder="Select Columns"
          style="width: 20em"
          @update:model-value="onToggle" />
          <span>
            <i class="pi_pi-search" />
            <InputText v-model="filters1['global'].value" placeholder="Global Search" />
          </span>
      </div>
    </template>
    <Column 
    v-for="(col, index) of selectedColumns"
    :key="col.field + '_' + index" 
    :field="col.field" 
    :header="col.header" 
    :sortable="true"></Column>
  </DataTable>
 </template>

Here’s the code.

Can detect when a browser extension has access to document cookies in the browser?

I’m playing around with a browser extension for a website I’m helping out with, and I’m asking for the ‘cookies’ permission in the manifest.json file.

I’m wondering if on the website side of things, there is a way to block that permission to cookies access or more specifically to listen to when it has been granted and display something to the user?

Unfortunately, googling ‘detect cookies permissions from a browser extension’ just brings up thousands of articles about how to turn of the cookie popups on websites in the EU.

How do I use Javascript to return the text of the paragraph clicked as a usable variable?

I’m new to Javascript and self taught, my english is a little rough too, please bare with me. I’ve searched all over and tried everything I can.

I’m trying to make a table of content where clicking it brings up a form modal.. I want that when the form opens the innerHTML of the button clicked becomes a variable on it’s own. It will be submitted alongside other form inputs..
I just want to extract the paragraph text and use it as a variable that can be recall or something like that.
I can’t seem to get the topicHeading variable out of the for loop, I get undefined.

var topicHeading;
var topicButtons = document.querySelectorAll('p[class^=topicName]');

for (var i = 0; i < topicButtons.length; i++) {
  topicButtons[i].addEventListener('click', function() {
    var topicHeading = this.innerHTML;
    return topicHeading;
  });
};

console.log(topicHeading);
<div class="wallet-buttons" id="walletsList">

  <div id="Topic1" class="button-section" onclick="opendetails()">
    <i class="active-icon"></i>
    <div class="btn-name">
      <p class="topicName">Topic 1</p>
    </div>
    <div class="btn-img">
      <img src="img/topicimg.svg" alt="Topic Image">
    </div>
  </div>

  <div id="Topic2" class="button-section" onclick="opendetails()">
    <i class="active-icon"></i>
    <div class="btn-name">
      <p class="topicName">Topic 2</p>
    </div>
    <div class="btn-img">
      <img src="img/topicimg.svg" alt="Topic Image">
    </div>
  </div>

  <div id="Topic3" class="button-section" onclick="opendetails()">
    <i class="active-icon"></i>
    <div class="btn-name">
      <p class="topicName">Topic 3</p>
    </div>
    <div class="btn-img">
      <img src="img/topicimg.svg" alt="Topic Image">
    </div>
  </div>

  <div id="Topic4" class="button-section" onclick="opendetails()">
    <i class="active-icon"></i>
    <div class="btn-name">
      <p class="topicName">Topic 4</p>
    </div>
    <div class="btn-img">
      <img src="img/topicimg.svg" alt="Topic Image">
    </div>
  </div>

</div>

react formik Error: invalid hook call. Hooks can only be called inside of a functional component. This could happen for one of the following reasons

I’m a beginner who just started with react formik and i get error message on the console each time i try to make use of formik

Warning: Invalid hook call. Hooks can only be called inside of a functional component. This could happen for one of the following reasons.

  1. You might have mismatching versions of React and the renderer (such as React DOM).
  2. You might be breaking the rules of hooks.
  3. You might have more than one copy of React on the same app.

I’ve checked my version of react and it’s up to date, Here’s my package-lock.json.

 "name": "formik-demo",
 "version": "0.1.0",
 "private": true,
 "dependencies": {
   "@testing-library/jest-dom": "^5.16.4",
   "@testing-library/react": "^13.3.0",
   "@testing-library/user-event": "^13.5.0",
   "react": "^18.2.0",
   "react-dom": "^18.2.0",
   "react-scripts": "5.0.1",
   "web-vitals": "^2.1.4"
 },
 "scripts": {
   "start": "react-scripts start",
   "build": "react-scripts build",
   "test": "react-scripts test",
   "eject": "react-scripts eject"
 },
 "eslintConfig": {
   "extends": [
     "react-app",
     "react-app/jest"
   ]
 },
 "browserslist": {
   "production": [
     ">0.2%",
     "not dead",
     "not op_mini all"
   ],
   "development": [
     "last 1 chrome version",
     "last 1 firefox version",
     "last 1 safari version"
   ]
 }
}

Here’s my code…

import React from "react";
import { useFormik } from "formik";

function YoutubeForm() {
  const formik = useFormik({
    initialValues: {
      name: "",
      email: "",
      channel: "",
    },
  });

  return (
    <div>
      <form>
        <label htmlFor="name">Name</label>
        <input
          type={"text"}
          id="name"
          name="name "
          onChange={formik.handleChange}
          value={formik.values.name}
        />

        <label htmlFor="email">E-mail</label>
        <input
          type={"email"}
          id="email"
          name="email"
          onChange={formik.handleChange}
          value={formik.values.email}
        />

        <label htmlFor="channel">Channel</label>
        <input
          type={"text"}
          id="channel"
          name="channel"
          onChange={formik.handleChange}
          value={formik.values.channel}
        />

        <button>Send</button>
      </form>
    </div>
  );
}

export default YoutubeForm;

How to use Amazon product image as html img src url

I want to use this amazon product link for img src in the html below

'<a href="https://www.amazon.com/Wilson-NFL-MVP-Football-Official/dp/B000FADVPQ?_encoding=UTF8&pd_rd_w=efnXC&content-id=amzn1.sym.bbb6bbd8-d236-47cb-b42f-734cb0cacc1f&pf_rd_p=bbb6bbd8-d236-47cb-b42f-734cb0cacc1f&pf_rd_r=C23VXKNWY7RX5ZWH1VPE&pd_rd_wg=fjE8e&pd_rd_r=9fda94df-c269-40e1-a9b5-e9e295b7c222&linkCode=li1&tag=gyfbox09-20&linkId=efed33779a363bc0982cf193922ff8d8&language=en_US&ref_=as_li_ss_il" target="_blank"><img border="0" src="//ws-na.amazon-adsystem.com/widgets/q?_encoding=UTF8&ASIN=B000FADVPQ&Format=_SL110_&ID=AsinImage&MarketPlace=US&ServiceVersion=20070822&WS=1&tag=gyfbox09-20&language=en_US" ></a><img src="https://ir-na.amazon-adsystem.com/e/ir?t=gyfbox09-20&language=en_US&l=li1&o=1&a=B000FADVPQ" width="1" height="1" border="0" alt="" style="border:none !important; margin:0px !important;" />'

here is the html tag

.items {
  display: grid;
  grid-template-rows: 150px 150px;
  grid-auto-flow: column;
  gap: 10px;
  row-gap: 10px;
}


#grid {
  display: grid;
  width: 100%;
  grid-template-columns: 300px 2fr;  
}



#areaB { 
  display: grid;
  width: 100%;
  grid-template-columns:1fr 50px;
 
}
<div class="">

 <div id="areaB">

      <div class="items">
         
        <div class="product">

              <img src="https://placeimg.com/640/480/arch" alt="Placeholder Image" class="img-fluid">
              <div class="mask flex-center">
                <p class="white-text">Gallery Item</p>
              </div>

         </div>
           
        <div class="product">

              <img src="https://placeimg.com/640/480/arch" alt="Placeholder Image" class="img-fluid">
              <div class="mask flex-center">
                <p class="white-text">Gallery Item</p>
              </div>

         </div>
           
        <div class="product">

              <img src="https://placeimg.com/640/480/arch" alt="Placeholder Image" class="img-fluid">
              <div class="mask flex-center">
                <p class="white-text">Gallery Item</p>
              </div>

         </div>
      </div>
        
   </div>
   

How can i use the Amazon product image link as img src ?

How can I send a self-signed certificate through axios in the browser?

I am working on a create-react-app that queries an API that requires a self-signed certificate to validate the request. I am grabbing the certificate through a GET request and using a helper to create a new Agent. My initial solution was to assign the httpsAgent in axios.interceptor to attach the certificate to every axios call.

But from what I understand the httpsAgent object is not being passed correctly to index.js because index.js runs in the browser and https is a core node module.

Is there a browser equivalent to https or an alternative method to sending the certificate to the back end? I saw a suggestion to proxy API requests and add the certificate that way, but I am unsure if that’s the way to proceed.

Thanks so much!!

httpsAgent.js

const https = require('https');

const createAgent = (data) => {
  const httpsAgent = new https.Agent({
    ca: data,
    rejectUnauthorized: true,
    checkServerIdentity() {
      return undefined;
    },
  });
  return httpsAgent;
};

index.js

axios
  .get('/certificate.pem')
  .then(({ data }) => {
    httpsAgent = createAgent(data);
  })
  .catch((err) => {
    console.log(err);
  })
  .finally(() => {
    axios.interceptors.request.use((config) => {
      const newConfig = {
        ...config,
        httpsAgent,
      };
      return newConfig;
    });
  });