send email with attachments from google sheets

I am new to codes. I created this code to send an email with attachments but it’s not working.

We get the URL through “var ppt” that is from a google sheets cell and I tried to transform in a URL inside javascript in the “var file” and send via “attachments: [file]” in the “MailApp.sendEmail”.

Thanksss.

function kickoff1() {
  
//Declarando as variáveis
  var planilha = SpreadsheetApp.getActiveSpreadsheet();
  var aba_sanidade = planilha.getSheetByName("Envios");
  var ppt = aba_sanidade.getRange("F4").getValues();
  var file = DriveApp.getFilesByType(ppt);

  //Iniciando e-mail
  var assunto = 'Kickoff - Parte 1'
  var corpo = "Oi, pessoal! :)" 
  var emails = "email"
  
MailApp.sendEmail({
    to: emails,
    subject: assunto,
    htmlBody: corpo,
    attachments: [file]});   

Not receiving current state within setInterval

Im trying to get the current state within the setInterval function, which isn’t working. I’m only getting the default value. I think it has to do something with the useEffect that only loads on mount.

const [liveMouse, setLiveMouse] = useState({
        currentX: 0,
        currentY: 0,
        lastX: 0,
        lastY: 0
});


useEffect(() => {

        let mounted = true;

        if (mounted) {

        document.addEventListener("mousemove", (event) => {

                setLiveMouse(previousMouse => ({...previousMouse, currentX: event.clientX, currentY: event.clientY }));

         })

  
       const mouseCheckInterval = setInterval(() => {

         // Not getting the current state, only the default value
         if (liveMouse.currentX !== liveMouse.lastX || liveMouse.currentY !== liveMouse.lastY) {

              setLiveMouse(previousMouse => ({...previousMouse, lastX: liveMouse.currentX, lastY: liveMouse.currentY }))

         }

       }
       return (() => {

         mounted = false;

         clearInterval(mouseCheckInterval)

       }

}, [])

How can I fix this problem?

get a list of specific values sorted by the sum of specific field that related to the sesific values

i have this schema

const callData = new callDataSchema({
    to        : String,
    userId    : String,
    date      : String,
    direction : String, // if inbound or outband
    duration  : Number,
    from      : String,
});

wich i am using to save a call obj.

as you can see each call obj have a userId field (this field let us know wich user made that call)
and every new call will create a new call obj.

i made a func that returns me some call statistics by user id,

example output :

    {
        "totalDouration": 208,
        "answeredAvg": 12.235294117647058,
        "totalAvg": 3.9245283018867925,
        "allCalls": 53,
        "outbound": 53,
        "inbound": 0,
        "answered": 17,
        "userId": "622dfba7cd94e60667444aad",
    },

the problem is, if i want to use pagination i cant sort the results (because i am using aggrate to get most of the statistics).

i was wonder if there is a way to implement this algoritem with mongodb:

(a) get all unique userIds with distinct

(b) sort userIds by the sum of all of the call duration that belongs to the call objects that contains the same userId

(c) paginate the result (with skip)

example of wanted results:

// for this collection
[
    {
        "to": "a",
        "userId": "1",
        "date": "1647247551021",
        "direction": "outbound",
        "duration": 13,
        "from": "380893202409",
    },
    {
        "to": "b",
        "userId": "1",
        "date": "1647247551021",
        "direction": "outbound",
        "duration": 11,
        "from": "380893202409",
    },
    {
        "to": "c",
        "userId": "2",
        "date": "1647247551021",
        "direction": "outbound",
        "duration": 2,
        "from": "380893202409",
    },
    {
        "to": "d",
        "userId": "2",
        "date": "1647247551021",
        "direction": "outbound",
        "duration": 24,
        "from": "380893202409",
    },
]
// i'll get this list

[
    {
        "userId": "2",
        "total": 26
    },
    {
        "userId": "1",
        "total": 24
    },

thanks.

I want to fetch an ID from json file and substitute it in a javascript function . I’m quite stuck. how do I proceed?

// demo.json

{
“id”:”35179″,
“key”:”17676″,
“fields”:{
“description”:”A small, distinct piece of work.”,
“name”:”Task”,
“hierarchyLevel”:0
},

//I need to fetch the id field and replace it in “mainID” in the below function

(function() {

var mainID
    atlToken = getAtlToken();
function createTask(tasks, step) {
    step = step || 0;
    console.log(tasks, tasks[0]);
    triggerCreateTask(tasks[step++], () => {
        step < tasks.length && createTask(tasks, step);
    });
}

How to display data from clicked container to other con

I am trying to list data on the left in Your Playlist container When I click on one of the music it should show it in Your Playlist container. It has to save it to browser history as well and it has to remove it from Search because it is already gonna be in Your Playlist container. I will deploy it later to Firebase but now I need help.
It should be added to the left while clicking on one of the listed songs after a search.
Please support me on that.

enter image description here

I am adding my codes here as well for my project:

I have App.js

import "./App.css";
  
import MySongs from "./MySongs.js";
import Search from "./Search.jsx";
function App() {
  return (
    <div className="App">
     
      <div className="body">
        <MySongs />
        <Search />
      </div>
    </div>
  );
}

export default App;
.App {
  background-color: #303030;
  width: 100%;
  height: 100vh;
}
.body {
  display: flex;
}

I have Search.jsx

import React, { useState, useEffect, useRef } from "react";
import "./Search.css";
import styled from 'styled-components';
import { IoSearch,IoClose } from "react-icons/io5";
import {motion, AnimatePresence} from "framer-motion";
import {useClickOutside} from "react-click-outside-hook";
import MoonLoader from 'react-spinners/MoonLoader';
import { useDebounce } from "./hooks/debounceHook";
import axios from "axios";
import { TvShow } from "./tvShow";

const SearchBarContainer = styled(motion.div)`
  margin-left: 10px;
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  width: 96%;
  height: 2.5em;
  background-color: #424242;
  border-radius: 3px;
  
`;

const SearchInputContainer = styled.div`
  width: 98%;
  min-height: 2.5em;
  display: flex;
  align-items: center;
  position: relative;
  padding: 2px 15px;
`;

const SearchInput = styled.input`
  width: 100%;
  height: 100%;
  outline: none;
  border: none;
  font-size: 15px;
  color: white;
  font-weight: 300;
  border-radius: 6px;
  background-color: transparent;
  &:focus {
    outline: none;
    &::placeholder {
      opacity: 0;
    }
  }
  &::placeholder {
    color: #white;
    transition: all 250ms ease-in-out;
  }
`;

const SearchIcon = styled.span`
  color: #bebebe;
  font-size: 14px;
  margin-right: 10px;
  margin-top: 6px;
  vertical-align: middle;
`;

const CloseIcon = styled(motion.span)`
  color: #bebebe;
  font-size: 15px;
  vertical-align: middle;
  transition: all 200ms ease-in-out;
  cursor: pointer;
  &:hover {
    color: #dfdfdf;
  }
`;

const LineSeperator = styled.span`
  display: flex;
  min-width: 100%;
  min-height: 2px;
  background-color: #d8d8d878;
`;

const SearchContent = styled.div`
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 1em;
  overflow-y: auto;
`;

const LoadingWrapper = styled.div`
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
`;

const WarningMessage = styled.span`
  color: #a1a1a1;
  font-size: 14px;
  display: flex;
  align-self: center;
  justify-self: center;
`;

const containerVariants = {
  expanded: {
    height: "26em",
  },
  collapsed: {
    height: "2.5em",
  },
};

const containerTransition = { type: "spring", damping: 22, stiffness: 150 };

export function SearchBar(props) {
  const [isExpanded, setExpanded] = useState(false);
  const [parentRef, isClickedOutside] = useClickOutside();
  const inputRef = useRef();
  const [searchQuery, setSearchQuery] = useState("");
  const [isLoading, setLoading] = useState(false);
  const [tvShows, setTvShows] = useState([]);
  const [noTvShows, setNoTvShows] = useState(false);
  
  
  const isEmpty = !tvShows || tvShows.length === 0;

  const changeHandler = (e) => {
    e.preventDefault();
    if (e.target.value.trim() === "") setNoTvShows(false);

    setSearchQuery(e.target.value);
  };
  

  const expandContainer = () => {
    setExpanded(true);
  };

  const collapseContainer = () => {
    setExpanded(false);
    setSearchQuery("");
    setLoading(false);
    setNoTvShows(false);
    setTvShows([]);
    if (inputRef.current) inputRef.current.value = "";
  };

  useEffect(() => {
    if (isClickedOutside) collapseContainer();
  }, [isClickedOutside]);

  

  const searchTvShow = async () => {
    if (!searchQuery || searchQuery.trim() === "") return;

    setLoading(true);
    setNoTvShows(false);

    const options = {
      method: 'GET',
      url: 'https://deezerdevs-deezer.p.rapidapi.com/search',
      params: {q: searchQuery},
      headers: {
        'x-rapidapi-host': 'deezerdevs-deezer.p.rapidapi.com',
        'x-rapidapi-key': '6a99d5e101msh1e9f2b2f948746fp1ae1f3jsn6b458fe8b4e4'
      }
    };
    
    axios.request(options).then(function (response) {
      
      if (response) {
        
        if (response.data && response.data.length === 0) setNoTvShows(true);
        
        setTvShows(response.data.data);
      }
    }).catch(function (error) {
      console.error(error);
    });

    

    setLoading(false);
  };

  useDebounce(searchQuery, 500, searchTvShow);
//  console.log(tvShows);
  return (
    
    <div className="my__search">
    <SearchBarContainer
      animate={isExpanded ? "expanded" : "collapsed"}
      variants={containerVariants}
      transition={containerTransition}
      ref={parentRef}
    >
      <SearchInputContainer>
        <SearchIcon>
          <IoSearch />
        </SearchIcon>
        <SearchInput
          placeholder="Search for Series/Shows"
          onFocus={expandContainer}
          ref={inputRef}
          value={searchQuery}
          onChange={changeHandler}
        />
        <AnimatePresence>
          {isExpanded && (
            <CloseIcon
              key="close-icon"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={collapseContainer}
              transition={{ duration: 0.2 }}
            >
              <IoClose />
            </CloseIcon>
          )}
        </AnimatePresence>
      </SearchInputContainer>
      {isExpanded && <LineSeperator />}
      {isExpanded && (
        <SearchContent>
          {isLoading && (
            <LoadingWrapper>
              <MoonLoader loading color="#000" size={20} />
            </LoadingWrapper>
          )}
          {!isLoading && isEmpty && !noTvShows && (
            <LoadingWrapper>
              <WarningMessage>Start typing to Search</WarningMessage>
            </LoadingWrapper>
          )}
          {!isLoading && noTvShows && (
            <LoadingWrapper>
              <WarningMessage>No Tv Shows or Series found!</WarningMessage>
            </LoadingWrapper>
          )}
          {!isLoading && !isEmpty && (
            <>
              {tvShows.map((show) => (
                <TvShow
                  key={show.id}
                  thumbnailSrc={show.album.cover_medium}
                  name={show.title_short}
                  artist={show.artist.name}
                  
                />
              ))}
            </>
          )}
        </SearchContent>
      )}
    </SearchBarContainer>
    </div>
  );
}

export default SearchBar;
.my__search {
  margin-top: 20px;
  flex: 0.6;
  height: 450px;
  border-radius: 5px;
  border: 1px solid black;
  margin-left: 80px;
  background-color: #424242;
}

I have tvShow.jsx

import React, { useState } from "react";
import styled from "styled-components";
import {ImDownload} from "react-icons/im";

const TvShowContainer = styled.div`
  width: 96%%;
  min-height: 3em;
  display: flex;
  border-bottom: 2px solid #555555;
    align-items: center;
`;

const Thumbnail = styled.div`
  width: auto;
  height: 80%;
  display: flex;
  flex: 0.4;
  img {
    border-radius: 20px;
    width: auto;
    height: 100%;
  }
`;

const Name = styled.h3`
  font-size: 12px;
  color: white;
  flex: 2;
  display: flex;
  flex-direction: column;
`;

const Artist = styled.span`
  margin-top: 10px;
  font-size: 8px;
  color: white;
  
  display: flex;
  align-items: center;
`;

const Rating = styled.span`
  color: #a1a1a1;
  font-size: 16px;
  display: flex;
  flex: 0.2;
`;

export function TvShow(props) {
  const { thumbnailSrc, name, artist,clickedMusic } = props;
  
  const [wantedMusic, setWantedMusic] = useState("");


  // const [clickedShow, setClickedShow] = useState("");

  // function clickedContainer(e){
  //   const element = e.currentTarget();
  //   setClickedShow(element);
  //   console.log("I am clickedShow " +clickedShow);
  // }

  return (
    
    <TvShowContainer onclick="location.href='#';" >
      <Thumbnail>
        <img src={thumbnailSrc} />
      </Thumbnail>
      <Name>{name}
      <Artist>
        {artist}
      </Artist> 
      </Name>
    </TvShowContainer>
  );
}

I have mySongs.js

import React from "react";
import "./MySongs.css";

function MySongs() {
  return (
    <div className="my__songs">
      <p>Your Playlist</p>
    </div>
  );
}

export default MySongs;
.my__songs {
  margin-left: 10px;
  margin-top: 20px;
  flex: 0.3;
  height: 300px;
  height: 450px;
  border: 1px solid black;
  border-radius: 5px;
  background-color: #424242;
}
.my__songs > p {
  color: white;
  opacity: 90%;
  margin-left: 10px;
  font-size: 13px;
}

How do I logout my Discordbot in JS savely with a command

I built a basic Discord bot which I want to go offline when I type the corresponding command on the Discord server “!logout”. I searched for answers, but those who used discord.js weren’t responsed…

If I use client.logout() it throws an error and crashs with

TypeError: client.logout is not a function

and it won’t even call my error function.
Maybe the answer is simple but I can’t find it anywhere.

Here’s my basic code:

require('dotenv').config()

const Discord = require('discord.js')
const client = new Discord.Client({ 
  intents: ["GUILDS", "GUILD_MESSAGES"],
})

client.on('ready', () => {
    console.log('Bot is ready');
});

client.on("messageCreate", msg => {
  if (msg.content === '!logout'){
    
      client.logout(() => {
        msg.reply('couldn^t go offline')
      })
    }
  
  
})

client.login(process.env.BOT_TOKEN)

Thank you! 🙂

Detect when someone use an emoji in discord.js

I made a function in a discord bot that will delete user message, when its lenght is past 100 characters, animated/custom/unicode emojis however bypasses this 100 characters limit (theoretically, 1 emoji is not equal to 1 character, idk how it works) but my bot crash after to many of them. I want to make a function, that will detect these emojis, and if it finds one, just delete this person comment. I was working on something like that.

client.on('messageCreate', message =>{ 
  if(message.content.startsWith(":") && message.content.endsWith(":") || message.content.startsWith("<:") && message.content.endsWith(":>") {
    return;
  }
  else {
  if(!message.content.startsWith(prefix) || message.author.bot || message.member.roles.cache.has('828277437242146816')) return;

If you have any other solution, you can share it in a comment.

One button for many forms

<div align="center">
<form method="get" name="formSubmit">
<input type="checkbox" name="formWheelchair" value="1" />
<input type="submit" name="formSubmit" value="Submit" />
</form>

This works only if submit button is in form.How connect to others forms

<td align="center">
<form method="get" name="formSubmit">
Do you need wheelchair access?
<input type="checkbox" name="formWheelchair" value="1" />
</form>     
</td>
<td align="center">
<form method="post" name="formSubmit">
<input type="checkbox" name="formWheelchair" value="2" />
</form>         
</td>

CoCart – Where Can I find or make a new Cart Key?

I am trying to make an app using Woocommerce and CoCart. CoCart is used for the cart items. It works fine when I am trying to add update and delete with JWT. But what to do with guest users?

So I read that you can use a cart_key in the params. However, do I need to make my own cart_key like: ‘12345’ or even better use a random character and number generator?

Or does CoCart gives you a cart_key when you put in a first item in the card and you call the endpoint without a JWT? (I tried this but if I do not put a cart_key without JWT I get an error message.

Do you have any experience?
Thanks!

Message origin must match parent origin! error JavaScript

I am getting an error when loading JavaScript file to Webview.

[chromium] [INFO:CONSOLE(7)] "Message origin must match parent origin!", source: https://service.force.com/embeddedservice/5.0/eswFrame.min.js (7)

This is my JS file

<html>
<body>

    <button onclick="Chat1()">Submit</button>
    <script type='text/javascript' src='https://service.force.com/embeddedservice/5.0/esw.min.js'></script>

    <script type='text/javascript'>
        function Chat1() {
            try {
                var initESW = function (gslbBaseURL) {
                    embedded_svc.settings.displayHelpButton = true; //Or false
                    embedded_svc.settings.language = ''; //For example, enter 'en' or 'en-US'
                    embedded_svc.settings.enabledFeatures = ['LiveAgent'];
                    embedded_svc.settings.entryFeature = 'LiveAgent';
                    console.log("inside initESW- ", gslbBaseURL);
                    embedded_svc.init(
                        'https://ulr.my.salesforce.com',
                        'https:/ulr.force.com/visualforce',
                        gslbBaseURL,
                        '00D00055uj',
                        'US_Universities',
                        {
                            'baseLiveAgentContentURL': 'https://c.la3-c1cs-cdg.salesforceliveagent.com/content',
                            'deploymentId': '5720Q008Oqg',
                            'buttonId': '5730Q000PID',
                            'baseLiveAgentURL': 'https://d.la3-c1cs-cdg.salesforceliveagent.com/chat',
                            'eswLiveAgentDevName': 'EmbeddedServiceLiveAgent_Q00000000jLUAQ_17d9a605e8e',
                            'isOfflineSupportEnabled': false
                        }
                    );
                };

                if (!window.embedded_svc) {

                    var s = document.createElement('script');
                    console.log("Control here1", s);
                    var MinFile = 'https://ulr.my.salesforce.com/embeddedservice/5.0/esw.min.js/'
                    console.log("Control here2")
                    s.src = MinFile;
                    s.crossOrigin = 'anonymous';                   
                    s.onload = function () {
                        initESW(null);
                    }
                    document.body.appendChild(s);
                }
                else {
                    initESW('https://service.force.com');
                }
            }
        }
    </script>
</body>
</html>

How can I fix this issue ?

How to get inline svg from an external svg file with D3 v6?

I’ve just lost my whole morning to what should have been a very basic and straightforward task. Sorry if the solution to this problem is obvious to you, I’m beginning on D3.js and Javascript.

I’m looking to load, in D3, an external svg file, and have it as an inline svg to do further operations, not as a static image, and working on local files. I don’t understand how there couldn’t be a way to do such a simple and basic thing. I’ve tried anything I could:

<!DOCTYPE html>
<html>
<head>
<script src="https://d3js.org/d3.v6.min.js"></script>
</head>
<body>
<script>
d3.xml('nameOfMysvgFile.svg')
    .then(data => {
        document.body.append(data.documentElement)
    })
</script>
</body>
</html>

So far the best I achieved was to load my svg as an object (as done here: http://dahlström.net/svg/html/get-embedded-svg-document-script.html), and then I’m stuck, as I can’t do any operation in Javascript on that object. How to transfer the contents of the object to inline svg? Or how to take out that #document “wrapping” that prevents from doing anything on the svg? Or even better, add the contents to an existing svg container (mySvgContainer.append("g").[magic command to add the contents of external svg file])?

How can we have a conditional deconstruction declaration in NodeJS

In my NodeJS project, I have a line like this:

const { fieldA, fieldB, fieldC, fieldD, fieldE, fieldF, ...rest } = originalObject;

fieldB, fieldC, fieldD, fieldE & fieldF are never used again in code, but as we know, the way the ES-6 deconstruction works, the rest object will be a new object without fields A-F. Therefore, later somewhere there is a dB operation, in a way so that fields A-F aren’t upserted.

const updatedItem = await model.findOneAndUpdate({ fieldA }, rest, { upsert: true });

However, I want to conditionally include/ exclude fieldF in rest. I know it can be done on the reading side, but how do it in the assignment side?