How to find Unix timestamp of a given calendar date and time in a specific time zone in Javascript?

With APIs like Intl, I can obtain the date and time of any Unix timestamp in any time zone. How can I do the reverse?

I’d like to be able to convert any particular triplet of <calendar-date> (YYYY-MM-DD), <local-time> (HH:MM:SS), and <time-zone> (IANA timezone) (which do not necessarily correspond with fixed timezone offsets) to a Unix timestamp. I am not looking to just convert the current timestamp (which is trivial) or looking for solutions that presuppose I have a Javascript Date object; what we have is only the calendar date, local time, and time zone.

Solutions such as adding time zone offsets do not work reliably (eg in cases of DST). I had hoped Intl allowed for easy calculation of this problem.

Google Appscript append data from Queryimport to FK the Col C needs to be checked and appended in Col D no duplication


This is my function details any help would be appreciated

    **function calling**
    function appendDataIfNotExists() {
     var ss = SpreadsheetApp.getActiveSpreadsheet();
     var sheet1 = ss.getSheetByName("QueryImport");
     var sheet2 = ss.getSheetByName("FK");
     
     var data1 = sheet1.getRange("C6:C").getValues();
     var data2 = sheet2.getRange("D6:D").getValues();
     
     var newData = [];
     **Traversing**
     for (var i = 0; i < data1.length; i++) {
       var valueToAppend = data1[i][0];
       **appending**
       // Skip empty or null values
       if (valueToAppend !== null && valueToAppend !== "" && valueToAppend !== "Ppppppppp") {
         if (!data2.some(function(row) { return row[0] === valueToAppend })) {
           newData.push([valueToAppend]);
         }
       }
     }
     
     if (newData.length > 0) {
       sheet2.getRange(sheet2.getLastRow() + 1, 4, newData.length, 1).setValues(newData);
     }

“/////////////////////////////////////////////////////////////////////////////////////

Highlighting Elements Within Shadow DOMs – How to Achieve This Without Event Listeners?

I am working on a project where I need to highlight elements within both regular DOM and shadow DOM. Currently, I have a function that binds event listeners to elements within shadow DOMs, but I want to modify it to add a class that highlights the elements instead of attaching event listeners.

Here is the function I have for attaching event listeners to shadow DOMs:

function injectToShadowDoms(doc, eventName, listener, capture) {
  var allElements = doc.all;
  for (var i = 0; i < allElements.length; i++) {
    var element = allElements[i];

    if (element.shadowRoot) {
      element.shadowRoot.addEventListener(eventName, listener, capture);
    }
  }
}

Now, I want to enhance this function to add a class that highlights elements within shadow DOMs. Additionally, I have a separate function (highlightElementsInShadow) for highlighting elements within a shadow DOM using a class.

Here is the modified code for adding a class instead of attaching event listeners:

function injectToShadowDoms(doc, highlightClass) {
  var allElements = doc.all;
  for (var i = 0; i < allElements.length; i++) {
    var element = allElements[i];

    if (element.shadowRoot) {
      highlightElementsInShadow(element.shadowRoot, highlightClass);
    }
  }
}

function highlightElementsInShadow(shadowRoot, highlightClass) {
  var allShadowElements = shadowRoot.querySelectorAll('*');
  allShadowElements.forEach(function (shadowElement) {
    shadowElement.classList.add(highlightClass);
  });
}

I would appreciate any guidance on how to properly modify the injectToShadowDoms function to achieve the desired highlighting effect without using event listeners.

Javascript form validation help… My output will not show

Here is my code: https://github.com/Mac2G/JavascriptForm/blob/main/TestingGround

I am trying to take the input submitted into these text boxes and simply output them, after some validation, into the text box below the submit button. I’ve tried rearranging the code in multiple ways but for the life of me I cannot figure it out.

Whenever I click the submit button, the page just reloads and the inputs clear… The validation works but the output into the text box doesn’t… What am I doing wrong?

<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<script>
// Function to validate the case number input
function validateCaseNumber() {
  var casenumber = document.getElementById("casenumber").value;
  var regex = /^d{2}-d{4}$/;
  if (!regex.test(casenumber)) {
    alert("Invalid case number format. Please enter a case number in the format 00-0000.");
    return false;
  }
  return true;
}

// Function to validate the date input
function validateCaseDate() {
  var casedate = document.getElementById("casedate").value;
  var regex = /^d{2}/d{2}/d{4}$/;
  if (!regex.test(casedate)) {
    alert("Invalid date format. Please enter a date in the format 00/00/0000.");
    return false;
  }
  return true;
}

// Function to validate the first name input
function
 
validateFirstName() {
  var firstname = document.getElementById("firstname").value;
  var regex = /^[a-zA-Z]+$/;
  if (!regex.test(firstname)) {
    alert("Invalid first name. Please enter a first name that contains only letters.");
    return
 
false;
  }
  return
 
true;
}

// Function to validate the last name input

function
 
validateLastName() {
  var lastname = document.getElementById("lastname").value;
  var regex = /^[a-zA-Z]+$/;
  if (!regex.test(lastname)) {
    alert("Invalid last name. Please enter a last name that contains only letters.");
    return
 
false;
  }
  return
 
true;
}

// Function to validate the price input

function
 
validatePrice() {
  var pricevalue = document.getElementById("pricevalue").value;
  var regex = /^[0-9]+$/;
  if (!regex.test(pricevalue)) {
    alert("Invalid price value. Please enter a price that contains only numbers.");
    return
 
false;
  }
  return
 
true;
}

// Function to submit the form

function
 
submitForm() {
  // Validate the form inputs

  
if (!validateCaseNumber() || !validateCaseDate() || !validateFirstName() || !validateLastName() || !validatePrice()) {
    return
 
false;
  }

  // Get the form input values

  
var casenumber = document.getElementById("casenumber").value;
  var casedate = document.getElementById("casedate").value;
  var firstname = document.getElementById("firstname").value;
  var lastname = document.getElementById("lastname").value;
  var pricevalue = document.getElementById("pricevalue").value;

  // Output the form input values to the endresult paragraph

  
const someID = document.getElementById("someID");
  someID.innerHTML = "Case number: " + casenumber + "<br>Case date: " + casedate + "<br>First name: " + firstname + "<br>Last name: " + lastname + "<br>Price: $" + pricevalue;

  return
 
true;
}


</script>

</head>

<body>

<form id="formSubmission">

<table>

  
<tr>
    
<td>Case number:</td>
    
<td><input type="text" id="casenumber" required></td>
    
<td>Date:</td>
  
<td><input type="text" id="casedate" required></td>
 
<td>First name:</td>
    
<td><input type="text" id="firstname" required></td>

<td>Last name:</td>

    
<td><input type="text" id="lastname" required></td>

    
<td>Price:</td>
    
<td><input type="text" id="pricevalue" required></td>

</tr>

</table>

<br>

<textarea id="theend" cols="50" rows="6"></textarea>

<br>

<p id="someID"> </p>
<input type="submit" id="someID()" value="Submit">

</form>

</body>

</html>

Scraping Google Maps

when i search on google maps i get results which is in a single div, if i want to get more information, i have to chick on that particular result and then only i can access the location and other stuff, can i do something so that i can access those information directly from search

context : i am building a web scraper for scraping google maps using selenium python and i don’t want to click on every result to get the other info like contact and location, i want these info to show up directly from search

i tried to extract these info by clicking on every particular result but the process is very slow because i want to get around 15000 results

ReactJS Update State Values [duplicate]

I have the following useState declared to hold the state data for my registration form. In there I have state variables for form fields and corresponding error messages for those form fields.

const [registerForm, setRegisterForm] = useState({
        email: '',
        emailError: '',
        fullName: '',
        fullNameError: '',
        password: '',
        passwordError: '',
        confirmPassword: '',
        confirmPasswordError: '',
        country: '',
        countryError: '',
        state: '',
        stateError: '',
        suburb: '',
        suburbError: ''
    });

Below piece of code check for the validation issues in my register form (at the moment it has only email, full name & password validation). If there is a validation message, it will set the relevant state value.

// validate form inputs
    const formInputValidation = () => {
        
        let result      = true;

        // clear validation errors before setting any new validation messages
        clearValidationMessages();

        let emailResult     = Validation.validateEmailInput(registerForm.email);
        setValidationMessages('emailError', emailResult.message);
        result              = result && emailResult.isSuccess;

        let fullNameResult      = Validation.validateTextInput(Constants.AUTHENTICATION_FORMS.registerForm.fullName, registerForm.fullName);
        setValidationMessages('fullNameError', fullNameResult.message);
        result              = result && fullNameResult.isSuccess;

        let passwordResult      = Validation.validateTextInput("password", registerForm.password);
        setValidationMessages('passwordError', passwordResult.message);
        result              = result && passwordResult.isSuccess;

        return result;
    }

The following piece of code set the relevant error state variable based on the validation message (value) it received. As an example if the email is empty, it will set the validation message for emailError in the registerForm state.

    // set validation messages
    const setValidationMessages = (name, value) => {

        switch (name) {
            case 'emailError':
                setRegisterForm({ ...registerForm, emailError: value });
                break;
            case 'fullNameError':
                setRegisterForm({ ...registerForm, fullNameError: value });
                break;
            case 'passwordError':
                setRegisterForm({ ...registerForm, passwordError: value });
                break;
            case 'confirmPasswordError':
                setRegisterForm({ ...registerForm, confirmPasswordError: value });
                break;
            case 'countryError':
                setRegisterForm({ ...registerForm, countryError: value });
                break;
            case 'stateError':
                setRegisterForm({ ...registerForm, stateError: value });
                break;
            case 'suburbError':
                setRegisterForm({ ...registerForm, suburbError: value });
                break;
            default:
                break;
        }
    }

However when I click the register button without filling any of the fields, the error message is shown for the confirm password only. The email validation and full name validation is not shown.

What I expected was to see all the validation messages(email, full name & password).

My thinking is that, at the time of setting the validation message for password, the …registerForm is completely empty, in the sense the other validation messages (email & full name) are not set yet. Hence seeing only the password validation message.

I can declare each state variable for each form field and relevant error message and resolved this issue. But would like to know if it possible to achieve the same with my above implementation.

enter image description here

How do I save a string to a .md file in javascript

I have a website that is meant to be fillable and sent to a .md file, which I am having trouble doing at the moment.

I have a html as follows;

<div class="content" id="content">
            <form class="title" id="title">
                <textarea class="heading" placeholder="Heading" id="heading"></textarea>
                <textarea class="body" placeholder="Body" id="body"></textarea>
                <img src="../images/submit.png" class="buttons" onclick="save()">
            </form>
            <form class="table" id="table">
                <textarea class="tableTitle" placeholder="Title"></textarea>
                <textarea class="tableBody" placeholder="Content"></textarea>
            </form>
        </div>
        <div class="console">
            <p id="message"></p>
        </div>

the content of the two forms is grabbed by the following function which turns the content of the two forms into a string that I then can pass into a .md file. I am attempting to use the code in the solution for this article , however am unable to make it work.

function save(){
    // get elements from title
    var heading = document.getElementById("heading").value;
    var body = document.getElementById("body").value;
    // format title elements
    var message = "# " + heading + "n" + body + "nn"; 
    var tableID = document.getElementsByClassName("table");
    for(var i = 0; i < tableID.length; i++){
        // get elements from table
        var title = tableID[i].getElementsByClassName("tableTitle")[0].value;
        var tableBody = tableID[i].getElementsByClassName("tableBody")[0].value;
        // format table elements
        tableContents = "## " + title + "n-" + tableBody + "nn" ;
        // set new message value
        message = message + tableContents;
    }
    // create markdown file
    localStorage.setItem("weekly", message);
    document.getElementById("message").innerText = message;
    // save markdown file
    var blob = new Blob([message], {type: "text/plain;charset=utf-8"});
    var link = window.URL.createObjectURL(blob);
    window.location = link;
}

please note that the for loop is there as a different function creates duplicates of that form in the html.

How can I handle these user sessions of the Logout button in Next.js to render it inside the Navbar components correctly?

I have these AuthButton done in server and client-side:

Client

'use client';

import { Session, createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import Link from 'next/link';
import { useRouter } from 'next/navigation';

export default function AuthButtonClient({ session } : {session: Session | null}) {
  const supabase = createClientComponentClient();
  const router = useRouter();

  const handleSignOut = async () => {
    const { error } = await supabase.auth.signOut();
    router.refresh();

    if (error) {
      // eslint-disable-next-line no-console
      console.error('ERROR:', error);
    }
  }


  return session ? ( 
    <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full" type="button" onClick={handleSignOut} >
      Sign Out
    </button>
  ) : (
    <Link href="/login">
      
      <button className="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-full" type="button" onClick={handleSignOut} >
        Login
    </button>
    
    </Link>
  )
  
}

Server

import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import { cookies } from "next/headers";
import AuthButtonClient from "./AuthButtonClient";

//for server component
export default async function AuthButtonServer(){
    const supabase = createServerComponentClient({cookies});

    const {data: {session}} = await supabase.auth.getSession();

    return <AuthButtonClient session={session}/>
}

And this is the navbar that I have done:

import AuthButtonServer from "@/app/auth/AuthButton/AuthButtonServer";
import Link from "next/link";
import NavbarComponent from "./NavBarComponent";

const NavBar = async ({ session} : {session: any}) => {  
    return ( 
        <div>
            {/* Links here */}

            {session ? <> 
            <NavbarComponent/>
            </>: <>You must login first</>}
            {/* Button for Login and Logout */}
            <AuthButtonServer/> 

        </div>
     );
}
 
export default NavBar;

And the NavBarComponent that I would like to put the Logout button at the right side of the navbar:

export default function NavbarComponent() {
    const pathname = usePathname()
  return (
    <Disclosure as="nav" className="bg-gray-800">
      {({ open }) => (
        <>
          <div className="mx-auto max-w-7xl px-2 sm:px-6 lg:px-8">
            <div className="relative flex h-16 items-center justify-between">
              <div className="absolute inset-y-0 left-0 flex items-center sm:hidden">
                {/* Mobile menu button*/}
                <Disclosure.Button className="relative inline-flex items-center justify-center rounded-md p-2 text-gray-400 hover:bg-gray-700 hover:text-white focus:outline-none focus:ring-2 focus:ring-inset focus:ring-white">
                  <span className="absolute -inset-0.5" />
                  <span className="sr-only">Open main menu</span>
                  {open ? (
                    <XMarkIcon className="block h-6 w-6" aria-hidden="true" />
                  ) : (
                    <Bars3Icon className="block h-6 w-6" aria-hidden="true" />
                  )}
                </Disclosure.Button>
              </div>
              <div className="flex flex-1 items-center justify-center sm:items-stretch sm:justify-start">
                <div className="flex flex-shrink-0 items-center">
                  <img
                    className="h-8 w-auto"
                    src="https://tailwindui.com/img/logos/mark.svg?color=indigo&shade=500"
                    alt="Your Company"
                  />
                </div>
                   <div className="hidden sm:ml-6 sm:block">
                   <div className="flex space-x-4">
                     {navigation.map((item) => (
                       <Link
                         key={item.name}
                         href={item.href}
                         className={
                            item.href === pathname
                              ? 'bg-gray-900 text-white rounded-md px-3 py-2 text-sm font-medium'
                              : 'text-gray-300 hover:bg-gray-700 hover:text-white rounded-md px-3 py-2 text-sm font-medium'
                          }
                          aria-current={item.href === pathname ? 'page' : undefined}
                       >
                         {item.name}
                       </Link>
                     ))}
                   </div>
                 </div>
              </div>
              <div className="absolute inset-y-0 right-0 flex items-center pr-2 sm:static sm:inset-auto sm:ml-6 sm:pr-0">
                 <button
                  type="button"
                  className="relative rounded-full bg-gray-800 p-1 text-gray-400 hover:text-white focus:outline-none focus:ring-2 focus:ring-white focus:ring-offset-2 focus:ring-offset-gray-800"
                >
                  Logout
                </button>
                 </div>
            </div>
          </div>
          

          <Disclosure.Panel className="sm:hidden">
            <div className="space-y-1 px-2 pb-3 pt-2">
              {navigation.map((item) => (
                <Disclosure.Button
                  key={item.name}
                  as="a"
                  href={item.href}
                    className={classNames(
                    item.href === pathname ? 'bg-gray-900 text-white' : 'text-gray-300 hover:bg-gray-700 hover:text-white',
                    'block rounded-md px-3 py-2 text-base font-medium'
                  )}
                  aria-current={item.href === pathname ? 'page' : undefined}
                >
                  {item.name}
                </Disclosure.Button>
              ))}
            </div>
          </Disclosure.Panel>
        </>
      )}
    </Disclosure>
  )
}

Now, I am quite lost on how I can approach this. I cannot use the AuthButtonServer inside the NavBarComponent because this is a client component. Any suggestions would be greatly appreciated!

Implementation of a navigation menu on a website. What script is it implemented on?

I found a good example of a vertical menu on the website https://zooatlanta.org/. But I can’t find the script for this menu. Does anyone know what script this is implemented in, or are there similar examples of scripts for implementing such a vertical menu? thanks in advance

links to the resource of this script, or example scripts for similar examples of a vertical menu

Appsheet calculated expired date spesifiec 2

I have an Appsheet who consist of two columns, let’s both named is Production Date and Expired Date. If column Production Date has 35 months of Expired Date, then how the formula in appsheet to calculated it? Let say the example, Production Date is 01/10/2023, therefore Expired Date is 01/09/2026. I want the formula to consider leap years.

Before that, i have created a formula but it is not worked. There was note “DATE function is used incorrectly.”

enter image description here

Does anyone know the formula to solve this problem? Please let me know

hierarchical traverse a target object and replace a source obj into it by using its key

I want to merge two objects:

Target object:

"ac0ca677-edb6-4187-85f3-c8b02e874315": {
                "groups": {
                    "30f8168b-0e98-4d1d-b7d9-e652651ad240": {
                        "groups": {
                            "4cab91b5-1732-40c3-81a7-6471da687061": {
                                "name": "Transformer 1.2.3",
                            },
                            "e4e4c636-9216-4787-86b5-cabc058bdb9b": {
                                "name": "Transformer 1.2.1",
                            },
                            "1e42137b-4ad0-4969-8d83-b27a16ccb5ff": {
                                "name": "Transformer 1.2.2",
                            }
                        },
}

Source object:

"4cab91b5-1732-40c3-81a7-6471da687061": {
                                "name": "Transformer 3.3.3",
                                
                            },
}

As you can notice the two keys are the same, I need to find the source’s key into target and replace the data.

I tried various solutions about merging, cloning, etc. but none of them worked.

Displaying mixed results in JS

I am getting started with JS so I have been doing some assignments. Currently working on an exercise to calculate average grades and display the output. The code I have has a bug I am unable to locate or identify since it’s giving me mixed results.

const marks = [50, 59, 90];
var average;

console.log(calculateGrade(marks))
function calculateGrade(marks ) {

var sum = 0;

for(i = 0 ; i < marks.length ; i++) {        
    sum += marks[i]  ;                  
}
var average  = sum / marks.length;
console.log ('Average marks : ' + Math.floor(average));


if (average < 59){
console.log(' Grade : F');
}
if(average >= 60 && average<= 69){
console.log('Grade : D');
}
if(average >= 70 && average <=79) {
console.log('Grade : C');
}
if(average => 80 && average <= 90){
console.log('Garde : B');
}
else
console.log ('Grade : A')

}

What I am getting is :

Average marks : 66
Grade : D
Garde : B
undefined

How do I keep load module dynamically but without constant memory usage increase?

There is a need to load and serialize esm module dynamically on deno. As of I know, since there is no way to clear cache on await import(), I tried importing inside WebWorker, then kill it after it’s done.

Profiler tells me that all of the imported source code is piled up inside the worker, but after killing the worker I don’t see process’ memory usage decline. (checked using docker status)

Below is simplified example code.

// worker.ts
self.onmessage = async (evt: MessageEvent) => {
  const mod = await import(evt.data);
  self.postMessage(JSON.stringify(mod));
}
// manager.ts
let worker = new Worker("./worker.ts");

// trying to clear source code piled up
setInterval(() => {
  worker.terimnate();
  worker = new Worker("./worker.ts")
}, 10_000);

worker.onmessage = (evt: MessageEvent) => console.log(e.data);

worker.postMessage('https://deno.land/x/[email protected]/index.ts')

Cannot require/import while creating yeoman generator

I’m trying to create yeoman generator but I’m unable to get started. I’m following this video on the subject and I can’t even get my code to run.

here’s my package.json file:

{
  "name": "generator-test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "yeoman-generator": "^7.1.0"
  }
}

and my index.js file:

const Generator = require("yeoman-generator");

module.exports = class extends Generator {
  initializing() {
    this.log("working!");
  }
};

I can run npm link no issues, and when I try to run it I can see it’s been hit, but then I get this error:

require() of ES Module …generator-testnode_modulesyeoman-generatordistindex.js from …generator-testgeneratorsappindex.js not supported.

Instead change the require of …generator-testnode_modulesyeoman-generatordistindex.js in …generator-testgeneratorsappindex.js to a dynamic import() which is available in all CommonJS modules.

so I tried that, and ended up with this index.js:

import Generator from "yeoman-generator";

module.exports = class extends Generator {
  initializing() {
    this.log("working!");
  }
};

and this error:

Cannot use import statement outside a module

I’m sure I’m doing something wrong I just don’t what it is.
Can some one point me in the right direction?

Why is a void type constructor param not optional, but the same is optional as a function/method params?

Typescript playground link:

class A<T> {
    data: T;
    constructor(data : T){
        this.data = data;
    }

    setData(newData: T) {
        this.data = newData;
    }
}

const instance = new A<void>();
//                           ^ Error: Expected 1 arguments, but got 0.
instance.setData();
//               ^ no error

Here, the type parameter is set to void for the instance of class A. This sets both the constructor’s data parameter and setData‘s newData parameter to type void.

The constructor throws an error that data param is not optional, but setData works fine if you don’t pass any value as an argument. Even though the type of the param is same, the behaviour seems to be different.

Why is this the case? How can I make constructor’s param optional too, but only for void cases?