Trying to use apps scripts to transpose event data to get one day per row in google sheets (events are between 0.5 and 30 days)

I have imported a series of events from google calendar. Each event has a title, start_date, end_date, id, etc.

function getEvents(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("SHEET_NAME");
  let MONTHS_IN_ADVANCE = 12;

let minDate = new Date(44927);
  let maxDate = new Date();
  maxDate.setMonth(maxDate.getMonth() + MONTHS_IN_ADVANCE)

  var cal = CalendarApp.getCalendarById("CALENDAR_ID");
  var events = cal.getEvents(minDate,maxDate);

  for(var i = 0;i<events.length;i++){
    var title = events[i].getTitle();
    var start_time = events[i].getStartTime();
    var end_time = events[i].getEndTime();
    var id = events[i].getId();

For the sake of creating an example, let’s say that events = [[a,b,c,d,e,f,g]]

If I send this to google sheets, I can get a table that looks like this:

email title start_time end_time id etc…
Cell 1 a start_time end_time id etc…
Cell 2 b start_time end_time id etc…
Cell 3 c start_time end_time id etc…
Cell 4 d start_time end_time id etc…
Cell 5 e start_time end_time id etc…
Cell 6 f start_time end_time id etc…
Cell 7 g start_time end_time id etc…
sheet.getRange(i+2,1).setValue(title);
sheet.getRange(i+2,3).setValue(start_time);
sheet.getRange(i+2,4).setValue(end_time);
sheet.getRange(i+2,5).setValue(id);

Here’s the actual question…

The thing is, I know that event ‘b’ is 6 days long, event ‘f’ is 2 days long, ‘g’ is 30 days long, and the others are 1 day long or less.

What I actually want, is a table that looks like this:

email title day start_time end_time id etc…
Cell 1 a 1 start_time end_time id etc…
Cell 2 b 1 start_time end_time id etc…
Cell 3 b 2 start_time end_time id etc…
Cell 4 b 3 start_time end_time id etc…
Cell 5 b 4 start_time end_time id etc…
Cell 6 b 5 start_time end_time id etc…
Cell 7 b 6 start_time end_time id etc…
Cell 8 c 1 start_time end_time id etc…
Cell 9 d 1 start_time end_time id etc…
Cell 11 e 1 start_time end_time id etc…
Cell 12 f 1 start_time end_time id etc…
Cell 13 f 2 start_time end_time id etc…
Cell 14 g 1 start_time end_time id etc…
Cell 15 g 2 start_time end_time id etc…
Cell … …30 start_time end_time id etc…

(note: the column “day” isn’t necessary, just here to try to make my request clearer.)

To get the array of dates between start and finish for ‘b’, ‘f’, and ‘g’, I use getDatesBetween:

var betweenDateArray = getDatesBetween(start_time,end_time);
function getDatesBetween(startT, endT) {
    var dateArray = new Array();
    var midDate = startT;
       while (startT <= endT) {
        dateArray.push(new Date (midDate));
        midDate.setDate(midDate.getDate() + 1);
    }
    return dateArray;
  }

…which returns an object with the correct dates, but I don’t know how to transpose this data into additional rows with the correct (original [i]) email/title/id labels.

Currently betweenDateArray sits within the for loop, my thinking being that I need to run another loop for each iteration of [i] – but as a Javascript newbie I’m unsure.

As the output is going to be in sheets anyway, I’d be equally happy solving this with a formula as with the script, but I’m stuck on both. In sheets I’ve tried TRANSPOSE and FLATTEN after applying SEQUENCE to find the dates between start_date and end_date, but the additional rows created by doing so try (and fail) to overwrite the rows that follow. The incoming data from the calendar updates regularly, so I can’t say that event ‘b’ will always be in row 2, because another event may be added or ‘a’ might get deleted – therefore I suspect any formula in sheets would have to be an arrayformula, hence the attempt to use a script instead…help please!

Calling a method on interval [duplicate]

I want to call the method of an object every second. My code throws the error

this.methodA is not a function

Why is this happening? this.methodA is clearly a function.

I noticed that when I replace obj.methodB with () => obj.methodB() it works. Why?

class Class {
  methodA() {
    console.log('A was called.');
  }
  methodB() {
    console.log('B was called.');
    this.methodA();
  }
}

var obj = new Class();
setInterval(obj.methodB, 1000);

v1 function for uuid not working for react native expo?

I have the following code:

const handlefb = async () => {
    const fb = sRef(storage, `paramKey/${feedback + v1()}`);
    uploadString(fb, todoDatafb).then((snapshot) => {
      console.log('Uploaded new feedback')
    })

According to https://www.npmjs.com/package/uuid, v1 is for Create a version 1 (timestamp) UUID. But it does not generate a timestamp for me.

Refer to screenshot of the file:

enter image description here

How come? Am I using the function wrongly?

Get ID of an ARUCO marker in Open CV JS

I am new to JAVA Script and I am learning Open CV JS. I want to print the ID of the ARUCO Marker in the console but I am having a hard time figuring out how.

According to this tutorial,
https://docs.opencv.org/4.x/d5/dae/tutorial_aruco_detection.html

cv.detectMarkers() will return markerCorners as well as markerIds.

However, when I print markerIds I am getting this and I can’t find where the IDs are. Could anyone please help me 🙂

enter image description here

The onChange proparty reset the textfield every time when i type un textfield

I’m trying to create a SignUp authentication page with firebase, So when I’m try to type anything in the textfield every time the text field got reset, I cant able to find the problem. But the main problem I found that with the “onChange” property. Please fix the issue why the textfield state change every time.
The SignUp page code:

import React,{useState,useContext} from 'react';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import Link from '@mui/material/Link';
import Grid from '@mui/material/Grid';
import Box from '@mui/material/Box';
import Typography from '@mui/material/Typography';
import Container from '@mui/material/Container';
import { styled } from '@mui/material';
import Logo from '../assets/QpiVolta-Logo.png'
import { useTheme,IconButton } from '@mui/material';
import { tokens } from '../theme';
import {Person,Lock, Mail, Visibility, VisibilityOff} from '@mui/icons-material';
import { useNavigate } from 'react-router-dom';
import { UserAuth } from '../context/AuthContext';

const SignUp = () => {
  const theme = useTheme();
  const colors = tokens(theme.palette.mode);
  
  const [showPassword, setShowPassword] = useState(false);
  const handleClickShowPassword = () => setShowPassword((show) => !show);

  const handleMouseDownPassword = (event) => {
    event.preventDefault();
  };

  const [email, setEmail] = useState("")
  const [password, setPassword] = useState("")
  const [name,setName] = useState("")
  const [error, setError] = useState("")
  const {signUp} = UserAuth()
  const navigate = useNavigate()
  const handleSubmit= async(e) => {
    e.preventDefault()
    try {
      await signUp(email,password)
      setError('')
      navigate('/') 
    }
    catch (error) {
      console.log(error)
      setError(error.message)
    }
  }
    const RootStyle = styled("div")({
        backgroundColor:"#d4cbf6",
        background:`${colors.primary[400]} !important`,
        height: "100vh",
        display: "flex",
        placeItems: "center",
    });
    const logoStyle = {
      height: '80px',
      
    };

    const CssTextField = styled(TextField)({
      '& label.Mui-focused': {
        color: `${colors.pinkAccent[500]}`,
      },
      '& .MuiInput-underline:after': {
        borderBottomColor:  `${colors.pinkAccent[500]}`,
      },
      '& .MuiOutlinedInput-root': {
        '& fieldset': {
          borderColor: 'grey',
        },
        '&:hover fieldset': {
          borderColor: `${colors.pinkAccent[500]}`,
        },
        '&.Mui-focused fieldset': {
          borderColor: `${colors.pinkAccent[500]}`,
        },
      },
    });
    return (
      <RootStyle>
        <Container  maxWidth="sm" >
        <Box
          sx={{
            marginTop: 8,
            display: 'flex',
            flexDirection: 'column',
            alignItems: 'center',            
          }}
        >
          
          <img component="img" src={Logo} style={logoStyle}  />
          <Typography component="h1" variant="h2" color={colors.grey[100]} >
            Create an account<span style={{ color:`${colors.pinkAccent[500]}`}}>.</span>
          </Typography>
          <Box component="form"  onSubmit={handleSubmit} sx={{ mt: 2 , mb:2}}>
            <Grid container spacing={3} >
              <Grid item xs={12} sm={6} >
              <Box sx={{ display: 'flex', alignItems: 'flex-end' }}>
              <Person sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
              <CssTextField  
                  fullWidth
                  label="First Name" 
                  id="FirstName"
                  name="FirstName"
                  autoComplete="family-name"
                  variant='standard' 
                  onChange={(e)=> setName(e.target.value)}
              />
                  </Box>
              </Grid>
              <Grid item xs={12} sm={6}>
              <Box sx={{ display: 'flex', alignItems: 'flex-end' }}>
              <Person sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
                <CssTextField
                  fullWidth
                  id="lastName"
                  label="Last Name"
                  name="lastName"
                  autoComplete="family-name"
                  variant='standard' 
                />
                </Box>
              </Grid>
              <Grid item xs={12}>
              <Box sx={{ display: 'flex', alignItems: 'flex-end' }}>
              <Mail sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
                <CssTextField
                  required
                  fullWidth
                  id="email"
                  label="Email Address"
                  name="email"
                  autoComplete="email"
                  variant='standard' 
                  onChange={(e) => {
                    console.log(e.target.value); // add this line
                    setEmail(e.target.value);
                  }}
                />
                </Box>
              </Grid>
              <Grid item xs={12}>
              <Box sx={{ display: 'flex', alignItems: 'flex-end' }}>
              <Lock sx={{ color: 'action.active', mr: 1, my: 0.5 }} />
                <CssTextField
                   required
                   fullWidth
                   name="password"
                   label="Password"
                   id="password"
                   autoComplete="new-password"
                   type={showPassword ? 'text' : 'password'}
                   variant='standard'
                   onChange={(e) => setPassword(e.target.value)}
                   InputProps={{
                     endAdornment: (
                      <IconButton
                        aria-label="toggle password visibility"
                        onClick={handleClickShowPassword}
                        onMouseDown={handleMouseDownPassword}
                      >
                        {showPassword ? <Visibility /> : <VisibilityOff />}
                      </IconButton>
                     ),
                   }}
                />
                </Box>
              </Grid>
            </Grid>
            <Button
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 3, mb: 2 }}
            >
              Sign Up
            </Button>
            <Grid container justifyContent="flex-end">
              <Grid item>
                <Link href="/Login" variant="body2" sx={{color:"grey"}}>
                  Already have an account? Sign in
                </Link>
              </Grid>
            </Grid>
          </Box>
        </Box>
      </Container>
      </RootStyle>    
  )
  }
  
  export default SignUp

throw new MongooseError(‘Query.prototype.exec() no longer accepts a callback’); req.login

app.post("/login" ,function(req,res){

  const user = new User({
username:req.body.username,
password:req.body.password
})

req.login(user, function(err){
    if(err){
      console.log(err);
    }else{
      passport.authenticate("local")(req,res,function(){
        res.redirect("/secrets");
      })
    }
  })

please give me a solution , can any one solve it with “then” and “catch” method

What is the use of NextJS API feature

I have seen Next JS API feature, it provides you the API folder where you can create API for frontend. But I am still confuse about few things.

  1. Does it replace the need of backend e.g database and file handling etc
  2. Is this for just sending you the response in JSON e.g mock service.

I am unable to understand the actual use case of this. I want to create full stack website. Frontend, backend, database, etc. Would this be possible with just Next JS?

Thank you.

I have tried some examples for returning the JSON

CytoscapeJS edges

im trying to get the edges of an node with the incomers() function and based on a condition it shouldtn close the node. (when more than one edge is connected to it) but my problem is, that the edges always is connected to the node either the edge isnt displayed

heres what I tryed:

removeNodes(target) {
        const targetData = target.data();
        if (targetData?.children?.length) {
          targetData?.children.forEach(child => {
            if (!child.opened && !this.rootData.includes(child.id)) { // Überprüfen, ob Knotenpunkt ist offen und ein root Knoten
              const childNode = this.cy.getElementById(child.id);

              const edges = childNode.incomers();

              // Überprüfen, ob Knotenpunkt mehr als eine Kante hat
              if (edges.length > 1) {
                console.log("more than one edge connected!: " + edges.length + " " +  child.label)
              } else {
                console.log(edges.length)
                childNode.remove();
              }

              if (child.children.length) {
                this.removeNodes(childNode)
              }

            }
          })
          this.cy.getElementById(targetData?.id).style({
            width: '250px',
            height: '250px',
            'font-weight': 'normal',
            'text-wrap': 'ellipsis'
          })
          target.removeData('opened')
        } else {
          target.remove();
        }

Deploy next js app to aws ec2 through codedeploy

I created a new NextJS app, no changes just the basic boilerplate files, code, and folders. and pushed it to a CodeCommit repo. Already had a working CodePipeline and just swapped Source stages. Deployments are failing on Step 3, where a replacement instance is created, and Target Group shows the original instance is healthy but new instances are given a 403 error code.

For the appspec.yml file, I’ve set the source to / b/c that’s what the Next JS docs said. I also tried setting it to pages/_app.js and /app.js b/c that’s what Fireship mentioned as the entry. None have worked and codedeploy keeps failing. I talked to AWS Support and we narrowed it to Next JS causing the issue.

If you’re also running a NextJS app and deploying it to EC2 through CodeDeploy and CodePipeline, what did you set the source path to? For both the appspec and Target Group health check. Do I need to use Docker and Kubernetes like this SO Thread? Or are the failures caused by something else I should check?

I’m learning HTML/CSS/JS and am following a tutorial. When I have entered the code EXACTLY the page doesn’t display like in the tutorial

As the title says I am learning HTML/CSS/JS and have entered the code exactly from the tutorial and when I try to display the page locally it simply doesn’t display.

I can’t work out why.

The page is a barebones HTML page, that is supposed to scale an image linked from the CSS in from 0 to 100%. As part of it, it overlays the count from 1 – 100% because it’s a tutorial.

I’ve console.logged the bits of the JS (ie the scale from 1 – 100) that should work, work.

I’ve made sure that JavaScript is turned on in the Browsers (and I have tried more than one.)

I’ve even just simply moved the link to the image as a background to the HTML file and when I do that it displays no problems – remove it again and it just goes back to the 0% thing.

For some reason, having the page set up as a typical HTML/CSS/JS structure exactly like the tutorial and yet when he executes it in the tutorial it works. When I try to open the page from the index.html page – all it does is display the 0% (which is exactly how it should start) and then does nothing. It is supposed to gradually scale from nothing to the full image and nothing happens – it just sits there at 0% on a blank page.

It’s fairly straightforward – a blank HTML page that the image just scales.

I’ve even downloaded Blowfish to execute it from within and it opens the code, however, I get exactly the same result when trying to display the page – it sits there at 0% on a white page again.

I can’t work out why – it just seems like the HTML CSS and JS aren’t talking to each other.

I found something online about changing my DNS Servers, so I tried that – same result it just displays the white page with 0% displayed.

I’m programming on a Mac in VSCode2 – not that, that really matters, it should be simply a case of editing the code and then trying to open the index.html file from Finder.

Any ideas as to what I might be missing? Especially since as I said – I have checked and rechecked the code – character by character just in case and it is exactly the same – it just won’t perform what it is supposed to.

Thanks if anyone can point me in the right direction to get it right.

Oh, and by the way, I am a University qualified programmer – I mainly worked with WPF using MVVVM, so I’m no dolt and learning the code side has been simple. However, just getting a single relatively simple web page just wont work.

Thanks if anyone can offer advice, because I should be able to advance relatively quickly if I could just work out this bazaar issue.

puppeteer timeout issue on waitForSelector


const puppeteer = require("puppeteer");
require("dotenv").config();

const WIDTH = 1080;
const HEIGHT = 1024;
async function logInToSSDC() {
  const browser = await puppeteer.launch({ headless: false });
  const page = await browser.newPage();
  await page.goto("https://www.ssdcl.com.sg/User/Login", {
    timeout: 60000,
    waitUntil: "domcontentloaded",
  });
  //set screen size
  await page.setViewport({ width: WIDTH, height: HEIGHT });
  const userName = process.env.user;
  const password = process.env.pass;

  await page.waitForSelector("#userName", { visible: true });
  await page.type("#userName", userName, { delay: 100 });
  //   await browser.close();
}

logInToSSDC();

I am using puppeteer to try to log in to a webpage but I am getting a timeOut issue on waitForSelector. I tried several methods including adding condition visible: true and even { timeout : xxx ms } but its still throwing the error.

Appreciate any ideas on this. Thanks.

Get WordPress page title and pass through to iframe as URL parameter

We’re using Pardot forms embedded on some pages on a WordPress site through a WP page template, and I have some URL parameters that are being passed from the main window into the iframe, so they can be captured in Pardot, which is working.

However I also need to get the WordPress page title (not the full meta title tag) and pass that to the iframe as well. I was thinking to append it to the end of the URL as a parameter like the others, but I’m not sure how best to do that.

This is the code that is currently in the WP page template:

    <script type="text/javascript">
        var form = 'https://go.sample.com/XXX/YYY/';
        var params = window.location.search;
        var thisScript = document.scripts[document.scripts.length - 1];
        var iframe = document.createElement('iframe');

        iframe.setAttribute('src', form + params);
        iframe.setAttribute('width', '100%');
        iframe.setAttribute('height', 700);
        iframe.setAttribute('type', 'text/html');
        iframe.setAttribute('frameborder', 0);
        iframe.setAttribute('allowTransparency', 'true');
        iframe.setAttribute('id', 'formiFrame');
        iframe.style.border = '0';

        thisScript.parentElement.replaceChild(iframe, thisScript);
    </script>

How could I modify the above code to get that result?

This is where I got the code that is working for the existing URL parameters: https://help.salesforce.com/s/articleView?id=000383147&type=1