Sharepoint 2013 add button to editform

I have a form in SP2013 I want to be able to export to pdf. For this I create an extra button in the ribbon. Now I get an error ‘unable to get property parentnode or undefined or null reference.


var linkButton = '<span class="ms-cui-ctl-largeIconContainer" unselectable="on"><span class=" ms-cui-img-32by32 ms-cui-img-cont-float ms-cui-imageDisabled" unselectable="on">'
+'<img class="" style="top: -102px;left: -408px;"unselectable="on" src="/_layouts/15/1033/images/formatmap32x32.png?rev=40"></span></span>'
+'<span class="ms-cui-ctl-largelabel" unselectable="on">Maak<br>PDF</span>';

    var editLink = document.getElementById("Ribbon.ListForm.Display.Manage.EditItem-Large");
    var node = document.createElement("A");
    node.text = "Print Item";
    node.className = "ms-cui-ctl-large";
    node.innerHTML = linkButton;
    node.onclick = function() {
        printTable(this);
        return false;
    };
    editLink.parentNode.appendChild(node);

});```
On another system my code worked.

Why canvas loses scaling while drawing images on it?

I set up a canvas and apply a setTransform to scale it smaller for specific devices. On one chromium 55 device this canvas first works correctly but after some drawings it suddenly first disappears from view and after returning it continues drawing without the scaling. What could be the reason?

While drawing I use drawImage. I was able to figure out that the problem that breaks is within the step that draws data from images to the canvas, but I don’t have any good ideas how to debug or overcome the issue.

So steps are

  1. Set up canvas, set scaling if needed (scaling is from 1080p to 720p)
  2. Draw images on canvas
  3. Clear canvas
  4. Draw new images on canvas
  5. Something changes, the image clears and when it redraws, the scaling is not applied anymore

I have set up different checks to handle the asynchronous processes and possible errors, but I don’t get any errors. I tried to figure out if it could be due to memory issues, but there seems to be no significant problems when I run it on dev. The error happens sooner if I draw more frequently, so I get to do less drawing if I do it faster before the bug. The amazing thing is that this problem had existed earlier and was thought to be corrected, but while refactoring it reappeared. Last time it just stopped occurring. I compared the changes and no significant logic is changed. In refactoring I had to change sizes, and divide code into different code blocks, but I retraced steps and the logic is the same.

Any ideas I could try?

Leaflet: Trying to change mapcenter when hover is true

Im trying to change the mapcenter when i hover. When the hoverResult is set, it contains and object with coordinates. I wanna change the map center to these coordinates whenever i hover something, but im struggelig. Im using react.
I have a fnction to get the coordinates i want, so its findMarkerCoordinates(hoveredResult)

return (
    <div>
        <MapContainer
            className="big-map w-75vw"
            center={mapCenter}
            zoom={zoom}
            minZoom={3}
            ref={mapRef}
        >

React Useeffect – Running continuously in browser

I am new to react. I have a GET api . First I will load in UseEffect.
whenever I am calling that my browser showing that api is running infinite time.
I did something in the useEffect dependency by providing wrong function . But I dont know how to stop that. Added screenshots belowthis is my usestate that holds the data

this is my function . in async I am sending that state

in this image the URL running infinite

How to solve this. Thanks by advance

react-leaflet-heatmap-layer-v3 src directory not found

Trying to use the npm library react-leaflet-heatmap-layer-v3 and after I install it successfully and then yarn start my react typescript app, I get the following warning messages:

WARNING in ./node_modules/react-leaflet-heatmap-layer-v3/lib/Heatmap.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/client/node_modules/react-leaflet-heatmap-layer-v3/src/Heatmap.ts' file: Error: ENOENT: no such file or directory, open '/client/node_modules/react-leaflet-heatmap-layer-v3/src/Heatmap.ts'

WARNING in ./node_modules/react-leaflet-heatmap-layer-v3/lib/HeatmapLayer.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/client/node_modules/react-leaflet-heatmap-layer-v3/src/HeatmapLayer.ts' file: Error: ENOENT: no such file or directory, open '/client/node_modules/react-leaflet-heatmap-layer-v3/src/HeatmapLayer.ts'

WARNING in ./node_modules/react-leaflet-heatmap-layer-v3/lib/index.js
Module Warning (from ./node_modules/source-map-loader/dist/cjs.js):
Failed to parse source map from '/client/node_modules/react-leaflet-heatmap-layer-v3/src/index.ts' file: Error: ENOENT: no such file or directory, open '/client/node_modules/react-leaflet-heatmap-layer-v3/src/index.ts'

When I go and check the node_modules for this library, there is no “src” directory but there is a “lib” directory that has all these files.

Am I missing something or doing something wrong as I need to use this library together with "react-leaflet": "^4.2.1" in my package.json

Do I need to use an earlier version of react-leaflet inorder for this to work?

React archive iframe onClick behaviour

I want to archive an onClick event on an iframe that I use to show different invoices pdf.

For that I use a filelist:

 const [filelist, setFilelist] = useState([])


  {filelist?.map((element, index) => (
                <div key={index} id={index + "_pdf"}
                    onMouseOver={(e) => handleOnMouseOver(e)}
                    onMouseOut={(e) => handleOnMouseOut(e)}
                >
                    {<iframe title="pdf_viewer" src={`${element.file_path_fe}`} width="100%" height="400em" />}
                </div>
            ))}

Now I’ve found this snippet:
https://codesandbox.io/p/sandbox/react-detect-mouse-click-over-iframe-708ys?file=%2Fsrc%2FApp.js%3A21%2C4
where clicks are detected via the blur effect.
Since I use functional components, I have rewritten it this way:

useEffect(() => {
        ...

        // iframe clickable:
        // Focus the page
        window.focus();
        // Add listener to check when page is not focussed
        // (i.e. iframe is clicked into)
        window.addEventListener("blur", onblur);

        return () => {
            // Anything in here is fired on component unmount.
            // so clean up the window eventlistener
            window.removeEventListener("blur", onblur);
        }

        // remove onblur missing dependency warning
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, []);

and the functions:

const onblur = (e) => {
        if (state) {
            //window.focus();
            console.log(e);
        }
    };

    const handleOnMouseOver = (e) => {
        console.log("mouse in");
        setState({ iframeMouseOver: true });
    };

    const handleOnMouseOut = (e) => {
        console.log("mouse out");
        window.focus(); // Make sure to set focus back to page
        setState({ iframeMouseOver: false });
    };

It works, but it’s not exactly how I want it to work.
So my questions would be:

  1. It detects the click correctly, but only one at a time. After that, clicks are ignored.
    I’ve tried to refocus the window in the hopes I can refire the blur eventListener on another click, but that doesn’t work.
    What can I do to archive and track multiple clicks?
  2. How can I detect the current Iframe if I click on it?
    e.target still detects the window it seems.
    Since I have multiple pdf’s, I would like to get the current pdf I’ve clicked on.
  3. Is it the correct approach to add the window.eventListener in the useEffect hook? Since there is the warning because of the onblur function.

Is there a way to refresh data in table i apps scrript with JS?

I want to refresh data in table every 5 second- table in Google Sheet is updated few times per hour- if it’s necesery- full div can be refreshed.

If there’s no way to do it- i tried yet refreshing full page with:

document.addEventListener('DOMContentLoaded', () => {
          setTimeout(function() {window.location.reload()}, 10000)
          google.script.run
            .withSuccessHandler(populateTable)
            .getNearlyTPT()
        });

But it returns me a a blank page.

Table looks like:

Data 1 Data 2 Data 3
Task 16:30 done

Code below:

Code in Code.gs:

function getNearlyTPT(){
  let ss = SpreadsheetApp.openByUrl('xxx');
  let ws = ss.getSheetByName("xxx");
  const today = new Date();
  let h = today.getHours();
  let m = today.getMinutes();
  let data = ws.getRange('H3:J').getValues().filter(r => r[0] && r[1] > h +":"+m);
  return data
}

Code in :

function makeRow(row) {
          let tr = document.createElement('tr');
          row.forEach(cell => {
            let td = document.createElement('td');
            td.textContent = cell;
            tr.appendChild(td)
          });
          return tr;
        }


        function populateTable(data) {
          let tasks = document.getElementById('tpt');
          data.forEach(row => {
            let tr = makeRow(row);
            tasks.appendChild(tr);
          });
        }

        document.addEventListener('DOMContentLoaded', () => {
          google.script.run
            .withSuccessHandler(populateTable)
            .getNearlyTPT()
        });

And div in html:

<div id = "tpt2Table">
      <table>
        <thead>
          <tr>
            <th>Data 1</th>
            <th>Data 2</th>
            <th>Data 3</th>
          </tr>
        </thead>
        <tbody id="tpt"></tbody>
      </table>
    </div>

Scroll position is not detect on React

I need to retrieve the scroll position to be able to remove the nav bar when the user scrolls down, currently the st variable

let st = window.pageYOffset || document.documentElement.scrollTop;

is always at 0 even when I scroll down.

Here the composant :


import "../App.css";
import { useEffect, useRef} from "react";

function NavBar({ sectionLists }){
    const Nav = useRef(null);
    const lastScrollTop = useRef(0);
    const HandleScrollInto = (name) => {
        sectionLists[name].current.scrollIntoView({ behavior: 'smooth' })
    }

    useEffect(() => {
        const onScroll = () => {
            let st = window.pageYOffset || document.documentElement.scrollTop;

            console.log(st)
            if (st > lastScrollTop.current) {
                console.log('Scrolling DOWN');
            } else if (st < lastScrollTop.current) {
                console.log('Scrolling UP');
            }
            lastScrollTop.current = st;
        };

        window.addEventListener('scroll', onScroll, true);

        return () => {
            window.removeEventListener('scroll', onScroll, true);
        };
    }, []);


    return(
        <>
            <div className={"main-container"} id={"navId"} ref={Nav}>
            <div className={"nav-container"}>
                <div className={"name"}>
                    <h1 className={"hb"}>HB</h1>
                    <h4 className={"web"}>Web developer<br/>Fullstack</h4>
                </div>

                <h2 className={"hamza"} onClick={() => HandleScrollInto('Bio')}>Hamza Benkejjane</h2>

                <div className={"ul-list"}>
                    <ul>
                        <li onClick={() => HandleScrollInto('Home')}>HOME</li>
                        <li onClick={() => HandleScrollInto('Project')} >PROJECT</li>
                        <li onClick={() => HandleScrollInto('Inspiration')} >INSPIRATIONS</li>
                        <li onClick={() => HandleScrollInto('Contact')}>CONTACT</li>
                    </ul>
                </div>
            </div>
            </div>
        </>
    )
}

export default NavBar;

the logic is when I call the onScroll function in an event to scroll on the page, the event works but it’s really the scroll position that stays at 0 all the time

Is it possible to roll-up rollupjs as a standalone module?

I’m trying to use Rollup to roll-up itself. The reason for this is that I need to integrate it into another app [a CLI built with vercel/pkg] as a standalone dependency.

In other words, I need to be able to use it in my source code as follows:

// From this: the usual way
import {rollup} from 'rollup';

const result = await rollup();
// To this: 
import defaultExport from './bundled-rollup.js';

const result = await defaultExport();

I have attempted to do this with the following source code:

// source.js

import { rollup } from 'rollup';

// define input options
const opts_input_obj = {
  context: 'globalThis',
  treeshake: true,
};

// define output options
const opts_output_obj = {
  format: 'es',
};

// create bundle
const bundle_obj = await rollup(opts_input_obj);

// generate outputs
const bundle_output_obj = await bundle_obj.generate(opts_output_obj);

console.log(bundle_output_obj);

with the following CLI command:

npx rollup  --input="./source.js" --config="./rollup.config.js" --file="./bundle.js"

When my config is this:

import { nodeResolve } from '@rollup/plugin-node-resolve';

export default {
  context: 'globalThis',
  treeshake: true,
  plugins: [
    nodeResolve({
      preferBuiltins: true,
    })
  ],
};

I get the following error:

[!] RollupError: ../../../../../../node_modules/rollup/dist/es/shared/parseAst.js (10:9): "parse" is not exported by "../../../../../../node_modules/rollup/dist/native.js", imported by "../../../../../../node_modules/rollup/dist/es/shared/parseAst.js".
https://rollupjs.org/troubleshooting/#error-name-is-not-exported-by-module
../../../../../../node_modules/rollup/dist/es/shared/parseAst.js (10:9)
 8:   Released under the MIT License.
 9: */
10: import { parse, parseAsync } from '../../native.js';
             ^
11: import { resolve, basename, extname, dirname } from 'node:path';
    at getRollupError (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/parseAst.js:282:41)
    at Object.error (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/parseAst.js:278:42)
    at Module.error (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:15122:28)
    at Module.traceVariable (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:15570:29)
    at ModuleScope.findVariable (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:13258:39)
    at ReturnValueScope.findVariable (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:7480:38)
    at FunctionBodyScope.findVariable (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:7480:38)
    at Identifier.bind (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:8752:40)
    at CallExpression.bind (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:6208:23)
    at CallExpression.bind (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:10416:15)

When I try this config:

import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

export default {
  context: 'globalThis',
  treeshake: true,
  plugins: [
    nodeResolve({
      preferBuiltins: true,
    }),
    commonjs()
  ],
};

I end up with the following:

[!] (plugin commonjs--resolver) RollupError: ../../../../../../node_modules/fsevents/fsevents.node (1:0): Unexpected character '�' (Note that you need plugins to import files that are not JavaScript)
../../../../../../node_modules/fsevents/fsevents.node (1:0)
1: ����@�
         @��...
   ^
2: 
3: 
   *
    h���/System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFound...
RollupError: Unexpected character '�'
    at Object.getRollupError (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/parseAst.js:282:41)
    at ParseError.initialise (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:12611:40)
    at convertNode (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:14356:10)
    at convertProgram (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:13673:12)
    at Module.setSource (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:15510:24)
    at ModuleLoader.addModuleSource (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:19805:13)
  [cause] RollupError: Unexpected character '�'
      at Object.getRollupError (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/parseAst.js:282:41)
      at ParseError.initialise (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:12611:40)
      at convertNode (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:14356:10)
      at convertProgram (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:13673:12)
      at Module.setSource (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:15510:24)
      at ModuleLoader.addModuleSource (/Users/obihill/My/Projects/Business/0_meta/1_monofab/3_dev/node_modules/rollup/dist/shared/rollup.js:19805:13)

Is it possible to use Rollup to roll-up itself as a standalone [ES] module?

User not found in AuthContext

import React, { useState, useContext, useEffect } from 'react';
import axios from 'axios';
import AuthContext from "../context/AuthContext";

const MessagingComponent = () => {
  const [messages, setMessages] = useState([]);
  const [isLoading, setIsLoading] = useState(true);
  const [newMessage, setNewMessage] = useState(''); // State to handle new message input
  const { user, isLoading: isUserLoading } = useContext(AuthContext);
  const [currentChatId, setCurrentChatId] = useState(null);

  const fetchMessages = async () => {
    try {
      if (!user) {
        console.error('User not found in AuthContext');
        setIsLoading(false); // Set isLoading to false to handle the case where user is not found
        return;
      }

      // Fetch messages associated with the user from MongoDB
      const response = await axios.get(`http://localhost:5000/api/messages/${user._id}`, {
        headers: {
          Authorization: `Bearer ${user.token}`, // Use token from AuthContext
        },
      });

      // Set messages state with fetched messages
      setMessages(response.data.messages);
      setIsLoading(false);
    } catch (error) {
      console.error('Error fetching messages:', error);
      setIsLoading(false); // Set isLoading to false in case of error
    }
  };

  useEffect(() => {
    if (!isUserLoading) {
      fetchMessages();
    }
  }, [user, fetchMessages, isUserLoading]); // Fetch messages whenever user changes or isUserLoading changes

  const sendMessage = async (event) => {
    event.preventDefault();
  
    try {
      if (!user) {
        console.error('User not found in AuthContext');
        return;
      }
  
      await axios.post(`http://localhost:5000/send-message`, {
        userId: user._id,
        content: newMessage,
        chatId: currentChatId, // Add the chatId to the message
      }, {
        headers: {
          Authorization: `Bearer ${user.token}`, // Use token from AuthContext
        },
      });
  
      setNewMessage(''); // Clear the input field
      fetchMessages(); // Fetch messages again to update the list
    } catch (error) {
      console.error('Error sending message:', error);
    }
  };
  

  return (
    <div>
      <h2>Previous Messages</h2>
      {isLoading ? (
        <p>Loading messages...</p>
      ) : messages.length === 0 ? (
        <p>No previous messages.</p>
      ) : (
        <ul>
          {messages.map((message, index) => (
            <li key={index}>
              <p>From: {message.sender}</p>
              <p>To: {message.recipient}</p>
              <p>Message: {message.content}</p>
            </li>
          ))}
        </ul>
      )}
      <form onSubmit={sendMessage}>
        <input
          type="text"
          value={newMessage}
          onChange={(e) => setNewMessage(e.target.value)}
          placeholder="Type your message here..."
        />
        <button type="submit">Send</button>
      </form>
    </div>
  );
};

export default MessagingComponent;
//authcontext.js
import { createContext, useContext, useEffect, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
// import { toast, ToastContainer } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import ToastContext from "./ToastContext";

const AuthContext = createContext();

export const AuthContextProvider = ({ children }) => {
  const { toast } = useContext(ToastContext);
  const navigate = useNavigate();
  const location = useLocation();

  const [user, setUser] = useState(null);
  // const [error, setError] = useState(null);



  // check if the user is logged in.
  // const checkUserLoggedIn = async () => {
  //   try {
  //     const res = await fetch(`http://localhost:8000/api/me`, {
  //       method: "GET",
  //       headers: {
  //         Authorization: `Bearer ${localStorage.getItem("token")}`,
  //       },
  //     });
  //     const result = await res.json();
  //     if (!result.error) {
  //       if (
  //         location.pathname === "/login" ||
  //         location.pathname === "/register"
  //       ) {
  //         setTimeout(() => {
  //           navigate("/", { replace: true });
  //         }, 500);
  //       } else {
  //         navigate(location.pathname ? location.pathname : "/");
  //       }
  //       setUser(result);
  //     } else {
  //       navigate("/login", { replace: true });
  //     }
  //   } catch (err) {
  //     console.log(err);
  //   }
  // };

  // useEffect(() => {
  //   checkUserLoggedIn();
  // }, [checkUserLoggedIn]);

  useEffect(() => {
    // check if the user is logged in.
    const checkUserLoggedIn = async () => {
      try {
        const res = await fetch(`http://localhost:8000/api/me`, {
          method: "GET",
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });
        const result = await res.json();
        if (!result.error) {
          if (
            location.pathname === "/login" ||
            location.pathname === "/register"
          ) {
            setTimeout(() => {
              navigate("/", { replace: true });
            }, 500);
          } else {
            navigate(location.pathname ? location.pathname : "/");
          }
          setUser(result);
        } else {
          navigate("/login", { replace: true });
        }
      } catch (err) {
        console.log(err);
      }
    };
  
    checkUserLoggedIn();
  
  }, [navigate, setUser, location.pathname]);
  


  // login request.
  const loginUser = async (userData) => {
    try {
      const res = await fetch(`http://localhost:8000/api/login`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ ...userData }),
      });
      const result = await res.json();
      if (!result.error) {
        localStorage.setItem("token", result.token);
        setUser(result.user);
        toast.success(`Logged in ${result.user.name}`);

        navigate("/", { replace: true });
      } else {
        toast.error(result.error);
      }
    } catch (err) {
      console.log(err);
    }
  };

  // register request.
  const registerUser = async (userData) => {
    try {
      const res = await fetch(`http://localhost:8000/api/register`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ ...userData }),
      });
      const result = await res.json();

      if (!result.error) {
        toast.success("user registered successfully! login into your account!");
        navigate("/login", { replace: true });
      } else {
        toast.error(result.error);
      }
    } catch (err) {
      console.log(err);
    }
  };

  return (
    <AuthContext.Provider value={{ loginUser, registerUser, user, setUser }}>
      {children}
    </AuthContext.Provider>
  );
};

export default AuthContext;
const express = require('express');
const bodyParser = require('body-parser');
const request = require('request');
const mongoose = require('mongoose');
const { isValidObjectId } = mongoose.Types.ObjectId;

require("dotenv").config();

const app = express();

// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.error('MongoDB connection error:', err));

// Load models
const Message = require('./models/messages');
const User = require('./models/user'); 
const Contact = require('./models/contact'); 

app.use(bodyParser.json());

// Route to handle fetching messages for a specific user
app.get('/api/messages/:chatId', async (req, res) => {
  try {
    const { chatId } = req.params;

    const messages = await Message.find({ chatId: chatId });
    return res.status(200).json({ messages });
  } catch (error) {
    console.error('Error fetching messages:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
});


// Route to handle sending messages and returning sent messages
app.post('/send-message', async (req, res) => {
  try {
    const { userId, message } = req.body;

    const user = await User.findById(userId);
    if (!user) {
      return res.status(404).json({ error: 'User not found' });
    }

    const contacts = await Contact.find({ postedBy: userId });
    if (!contacts.length) {
      return res.status(400).json({ error: 'No contacts found for the user' });
    }

    const sentMessages = await sendMessagesToContacts(user, contacts, message);

    await Message.insertMany(sentMessages);
    return res.status(200).json({ message: 'Messages sent successfully', sentMessages });
  } catch (error) {
    console.error('Error sending messages:', error);
    return res.status(500).json({ error: 'Internal server error' });
  }
});

async function sendMessagesToContacts(user, contacts, message) {
  const sentMessages = [];

  for (const contact of contacts) {
    const options = {
      method: 'POST',
      url: 'https://send.api.mailtrap.io/api/send',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
        'Api-Token': process.env.MAILTRAP_API_TOKEN
      },
      body: {
        to: [{ email: contact.email, name: contact.name }],
        from: { email: '[email protected]', name: 'Example Sales Team' },
        subject: 'New Message From Example',
        text: message,
        html: `<p>${message}</p>`
      },
      json: true
    };

    const response = await new Promise((resolve, reject) => {
      request(options, (error, response, body) => {
        if (error) reject(error);
        resolve(body);
      });
    });

    sentMessages.push({
      sender: user.name,
      recipient: contact.name,
      content: message,
      messageId: response.message_ids[0] // Assuming there's only one message ID
    });
  }

  return sentMessages;
}

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));
//app.js
require("dotenv").config({ path: "./config/config.env" });
const express = require("express");
const morgan = require("morgan");

const connectDB = require("./config/db");

const auth = require("./middlewares/auth");

const messages = require("./message")
const app = express();

// middlewares
app.use(express.json());
app.use(morgan("tiny"));
app.use(require("cors")());

// routes
app.use("/api", require("./routes/auth"));
app.use("/api", require("./routes/contact"));

// server configurations.
const PORT = process.env.PORT || 8000;
app.listen(PORT, () => {
  connectDB();
  console.log(`server listening on port: ${PORT}`);
});

I’ve been getting an error
SendMessages.js:15 User not found in AuthContext

[email protected]:

I tried adding isLoading state that is initially set to true. When the checkUserLoggedIn function is called, it sets isLoading to true before fetching the user data and sets it to false after the user data has been fetched. So, I can check the isLoading state in my components to determine whether the user data has been loaded.

Basic sorting number algorithm

const sortButton = document.getElementById("sort");

const sortInputArray = (event) => {
  event.preventDefault();

  const inputValues = [
    ...document.getElementsByClassName("values-dropdown")
  ].map((dropdown) => Number(dropdown.value));

  const sortedValues = selectionSort(inputValues);

  updateUI(sortedValues);
}

const updateUI = (array = []) => {
  array.forEach((num, i) => {
    const outputValueNode = document.getElementById(`output-value-${i}`);
    outputValueNode.innerText = num;
  })
}

const bubbleSort = (array) => {
  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array.length - 1; j++) {
      if (array[j] > array[j + 1]) {
        const temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
      }
    }
  }

  return array;
}

const selectionSort = (array) => {
  for (let i = 0; i < array.length; i++) {
    let minIndex = i;

    for (let j = i + 1; j < array.length; j++) {
      console.log(array, array[j], array[minIndex]);
      if (array[j] < array[minIndex]) {
        minIndex = j;
      }
    }

    const temp = array[i];
    array[i] = array[minIndex];
    array[minIndex] = temp;
  }

  return array;
}

sortButton.addEventListener("click", sortInputArray);

I don’t understand. How is selectionSort algorithm working?. Can you give examples for inputs and outputs. Let me explain which part I didn’t understand.

[ 8, 2, 4, 1, 3 ] 2 8
[ 8, 2, 4, 1, 3 ] 4 2
[ 8, 2, 4, 1, 3 ] 1 2
[ 8, 2, 4, 1, 3 ] 3 1
[ 1, 2, 4, 8, 3 ] 4 2
[ 1, 2, 4, 8, 3 ] 8 2
[ 1, 2, 4, 8, 3 ] 3 2
[ 1, 2, 4, 8, 3 ] 8 4
[ 1, 2, 4, 8, 3 ] 3 4
[ 1, 2, 3, 8, 4 ] 4 8

these is appear when I clicked Sort button. So it has to be array, array[j], array[minIndex] right?
But why array[j], array[minIndex] increasing and decreasing 2 or 1? Aren’t they has to be change +1 because i++ and j++.

Why using helmet return 502?

Nginx configuration file inside /etc/nginx/sites-available/default

location /api {
    proxy_pass http://47.126.4.133:3000;
    proxy_http_version 1.1;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection 'upgrade';
    proxy_set_header Host $host;
}

Import

const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const { createServer } = require('https');
const { Server } = require('socket.io');

Express configuration

const app = express();
app.set('trust proxy', true);
app.use(helmet());
app.use(cors({
    origin: ['https://inswalst.com', 'https://www.inswalst.com'],
    credentials: true
}));
app.use(express.json());

Server configuration

const httpsServer = createServer(
    {
        key: readFileSync('/home/ubuntu/backend/privkey.pem'), 
        cert: readFileSync('/home/ubuntu/backend/fullchain.pem')
    }, 
    app
);

const io = new Server(httpsServer, {
    cors: {
        origin: ['https://inswalst.com', 'https://www.inswalst.com'], 
        credentials: true
    },
    transports: [ 'websocket' ]
});

httpsServer.listen(3001);

Why it return 502 Bad Gateway? How to solve it?

Javascript append url date

I’m trying append “from=2024-04-21&to=2024-02-03” this to URL but I’m getting this

&date=%3Ffrom%3D2024-04-01%26to%3D2024-04-30%26


const fromDateFormatted = format(new Date(time.from), 'yyyy-MM-dd');
const toDateFormatted = format(new Date(time.to), 'yyyy-MM-dd');
const dateRange = `?from=${fromDateFormatted}&to=${toDateFormatted}`;
router.push....

Laravel Route missing required parameter

i have this modal to edit data by populating the modal with data retrieved using ajax. but i faced problems with the url in ajax and the laravel route with this error Missing required parameter for [Route: get-project-data] [URI: get-project-data/{projectId}] [Missing parameter: projectId].

html

<button type="button" class="item edit-button"
                                                            data-toggle="modal" data-id="{{ $item->id }}" data-url="{{ route('get-project-data', ['projectId' => '']) }}"
                                                            data-target="#editModal" data-placement="top"
                                                            title="Edit">
                                                            <i class="zmdi zmdi-edit"></i>
                                                        </button>

web.php

    Route::get('/get-project-data/{projectId}', [HomeController::class, 'getProjectData'])->name('get-project-data');

js

$(document).on('click', '.edit-button', function() {
  var projectId = $(this).data('id');
  console.log("Selected Project ID: " + projectId);
  
  // Store projectId in edit modal's data attribute
  $('#editModal').data('projectId', projectId);
  
  // Retrieve the base URL for the AJAX request from the data-url attribute
  var baseUrl = $(this).data('url');
  
  // Construct the complete URL for the AJAX request
  var url = baseUrl + projectId;

  // Fetch existing data of the selected project
  $.ajax({
      url: url,
      method: 'GET',

How to make quantity increase / decrease with minimal_quantity in Prestashop shopping cart

i would use for all Products the {$product.minimal_quantity} query to increase / decrease the amount of products in the Prestashop Cart.

I use this function already in the Product Details Site with

data-step="{$product.minimal_quantity}"

and

value="{if in_array( $product->id, array(xxx,xxx,xxx)) }
{$product.minimal_quantity}{else}{$product.quantity_wanted}{/if}"

That works fine. For example, if the minimal quantity 10, then gives me 10,20,30…steps.

I try the same function in the cart site. There visually give me the same function if i add
data-step=”{$product.minimal_quantity}”

but increase the product value just with 1 not with 10.

How can i modify the cart section to add the Function to increase the quantity of product = minimal_quantity? Version is 1.8

Thanks for any help