Express Cookie Sent With Header and Saved in Storage but After Reload they are gone

I’ve searched almost every topic about this issue but still could not fixed the problem. Set-Cookie is avaliable in response headers, see below, with a little warning. I am using http therefore i have to set secure to false. I even tried “SameSite=lax|strict” but still could not solve the problem. Also the cookies is presence in the application tab but when I change my url or refresh it the cookies are removed.

I start request with the function below and after this function I am sending the cookies with options configured. I’ve also shared cors options policy below.

http://localhost:3000/ this is my url, I am also aware an issue that it can also caused because a front-end and back-end domain are different. Im not acquinted with web so deeply I dont know how do I check domains are the same.

By the way I am using chrome version 127 and on macos.

enter image description here

const signInHandler = async function(e){
try {
    await axios({
        method: "POST",
        url: "http://127.0.0.1:3000/api/v1/users/login",
        data:{
            name: userName.value,
            password: password.value
        },
        withCredentials: true
    });
    
    
    // window.setTimeout(() => {
    //     location.assign("/");
    // },500);

} catch (error) {
    console.log(error);
    
}

}

const sendToken = function(user, res){
const token = createJWTToken(user);

const cookieOptions = {
    expires: new Date(Date.now() + process.env.JWT_COOKIE_EXPIRES_IN * 24 * 60 * 60 * 1000),
    httpOnly: true,
    secure: false,
    sameSite: "None"
}

res.cookie("jwt", token, cookieOptions);  

Below are my cors options.

const corsOptions = {
origin: true,
credentials: true
}

app.use(cors(corsOptions));

Is there a way to implement D3.js in Odoo?

I have managed to make some charts using d3.js but I wanted to put them into Odoo. I managed to get a dashboard run using Chart.js but d3.js is more complete for me. I loaded the d3.js but the charts aren’t showing.

This is the d3.js javascript’s I’m using. I resorted to pastebin because I don’t know what else could I add for this issue. Please bear with me. But I don’t really know why it is not showing…

Dynamically change padding in Vue js 3

Hello I want to change padding based on my selected locale, since div width is changing.

  <div
    class="input-group modal-check-show show-modal"
    :style="paddingLeft"
  >
  . . .
  </div>

const EnPaddingLeft = ref('padding-left: 27%;')
const DePaddingLeft = ref('padding-left: 28%;')
const SrPaddingLeft = ref('padding-right: 33% !important;')

const setPaddingLeft = computed(() => {
  let padding
  if (Tr.currentLocale === 'en') {
    padding = EnPaddingLeft
  } else if (Tr.currentLocale === 'de') {
    padding = DePaddingLeft
  } else if (Tr.currentLocale === 'sr') {
    padding = SrPaddingLeft
  } else {
    padding = EnPaddingLeft
  }
  return padding
})
const paddingLeft = setPaddingLeft

missing padding style

When I change computed to method it shows up at div tag, but it doesn’t change padding when I change locale.

My function that changes the elements background color isn’t working but works fine when changing the documents background color?

I’m using a switch statement to determine which button is being pressed, they both work with the same function when changing the documents background color, however, when I pass in the actual element and target it within the function and attempt to change it’s background color nothing is happening.

Changing the background color of the actual document works fine, but changing the background color of elements passed into the function is not working.

<div class="gender-toggle">
        <div class="toggle">
          <div id="male-toggle">
            <p>Male</p>
          </div>
          <div id="female-toggle">
            <p>Female</p>
          </div>
        </div>
</div>
const maleToggle = document.getElementById('male-toggle').addEventListener('click', changeGenderClick);
const femaleToggle = document.getElementById('female-toggle').addEventListener('click', changeGenderClick);

function changeGenderClick(event){
  const genderId = event.target.id;
  switch(genderId){
    case 'male-toggle':
      changeGender(femaleToggle);
      break;
    case 'female-toggle':
      changeGender(femaleToggle);
    break;
  }
}

function changeGender(currentGender){
  currentGender.style.backgroundColor = 'red';
};

how to get a line number in contenteditable div [closed]

I’m encountering an issue in my Vue 3 project where I need to determine the line number where the cursor is located in contenteditable div. This should work not only when typing but also when clicking anywhere within the text.

I’ve searched through many forums but only found solutions related to character offsets, not line numbers.

JavaScript Array of object get the data not present in other array

need an help I’ve two array which I needed to filte

const arr1 = [
    {
        "id": "processType",
        "name": "Conceptual Target State Process Model",
        "display_name": "Conceptual Target State Process Model",
        "checked": true
    },
    {
        "id": "processType",
        "name": "Current State Process Map",
        "display_name": "Current State Process Map",
        "checked": true
    },
    {
        "id": "processSubType",
        "name": "Current State Process Model",
        "display_name": "Current State Process Model",
        "checked": true
    },
    {
        "id": "processSubType",
        "name": "Current State Process Model (MCA)",
        "display_name": "Current State Process Model (MCA)",
        "checked": true
    }
]

const arr2 = [
    {
        "id": "processType",
        "name": "Current State Process Map",
        "display_name": "Current State Process Map",
        "checked": true
    }
]
 const filteredElements = arr1.filter(function(obj) {
        return !arr2.some(function(obj2) {
            return obj.name === obj2.name;
            //         ^             ^
        });
    });
console.log(filteredElements);

My expected output is

[
    { id: "processType",  name: "Current State Process Map", display_name: "Current State Process Map", checked: true
    },
    { id: "processSubType", name: "Current State Process Model", display_name: "Current State Process Model", checked: true
    },
    { id: "processSubType", name: "Current State Process Model (MCA)", display_name: "Current State Process Model (MCA)", checked: true
    }
]

Not sure what’s going wrong, I need to filter based on id & name
I’m filtering arr1 and using some checking for the name.

Socket.io not receiving data properly in React and Node JS

`I am trying to build a connection between a web application and a frontend using socket.io. I want it so that anytime I click on a button, I receive the JSON data that is being sent from the server side (web app) to the client (frontend). The server side is built with express/node and the client is built with react.

I click on the first button, and the JSON message “hello” appears. When I click “done with JSON”, I do not get another JSON message and instead get “Done with JSON” Anyone know how to solve this?

//////server side
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');



const app = express();
const server = app.listen(8080);
const io = require('socket.io')(server, {
    cors: {
      origin: '*',
    }
});
PORT = 8080;


app.get('/', (req, res) => {
    res.send('Socket.IO Server Running');
});

io.on('connection', (socket)=>{
    console.log("Connected");

      //this messsage is sent and received by the client
    const firstJson = {message:"hello"};
    socket.emit("receiveJson", firstJson);

    socket.on('jsonProcessed', () => {
        console.log('Client has processed the first JSON.');
        setTimeout(() => {
                  //this message is not received by the client
            const secondJson = { message: 'This is your second JSON!' };
            socket.emit('receiveJson', secondJson);
        }, 1000); // 1-second delay
    });
    
    socket.on('disconnect', ()=>{
        console.log('User disconnected');
    });
});



//Client side
`import React, {useRef, useState, useEffect} from 'react';
import { useNavigate } from 'react-router-dom';
import io from 'socket.io-client';
const Male = ({title})=>{
    const navigate = useNavigate();
    const socket = io('http://localhost:8080');

   
        const [jsonData, setJsonData] = useState(null);

        useEffect(()=>{
            socket.on('connect',()=>{
                console.log('Connection to server established');
            })
            socket.on('receiveJson',(data)=>{
                console.log('Received JSON from server: ', data);
                setJsonData(data);

            })
            return()=>{
                console.log("Disconnected from socket");
                socket.disconnect();
            }
        },[]);

        const handleJsonProcessing = () =>{
            console.log('Emitting jsonProcessed event');
            
            socket.emit('jsonProcessed');
            setJsonData(null);
        };
return(

</div>
                        {jsonData ? (
                <div>
                    <pre>{JSON.stringify(jsonData, null, 2)}</pre>
                    <button onClick={handleJsonProcessing}>Done with JSON</button>
                </div>
            ) : (
                <p>No JSON data received.!!</p>
            )}
);
};

It might also help if I show my console statements, which come up here:log statements

Vanilla JS in Vite can not detect web components

I’ve used npm create vite to create a vanilla JS project. I want to implement web components. This is my instruction as follow:

export class Header extends HTMLElement {
  constructor() {
    super();
  }

  connectedCallback() {
    const template = document.getElementById(
      "headerComponent"
    ) as HTMLTemplateElement;
    if (template) {
      const content = template.content.cloneNode(true);
      this?.appendChild(content);
    }
  }
}

customElements.define("my-header", Header);

I have imported this class in main.ts:

import { Header } from "./components/Header";

And this is index.html:

<template id="headerComponent">
  <h1>Header</h1>
  <p>Header is a component.</p>
</template>

<my-header></my-header>

But after opening the console, nothing is being shown in <my-header></my-header> tag.

What is the problem? What should I do?

Any help will be appreciated!

how to `getElementById` for an element inside a modal?

I have a webpage with a button. clicking the button opens a modal. inside this modal there’s a (Django) form. it has few inputs and some buttons (including a submit button).

  1. my form is: <form method="post" id="backupCreateForm" action="/backup/create/"> ...</form>
  2. its parent, the modal is : <div class="modal fade in" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" aria-hidden="true">

I can’t seem to select the submit button within the form element with document.getElementById, it returns undefined. how can I select it?

<div class="modal fade" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModalLabel" xit
    aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createModalLabel">Create Form</h5>
            </div>
            <div class="modal-body">
                <form method="post" id="backupCreateForm" action="{% url 'backup_create' %}">
                </form>
            </div>
        </div>
    </div>
</div>

backupCreateForm:

<form method="post">
    {% csrf_token %}
    {{ form.as_p }}
    <button type="submit" class="btn btn-success" id="submitButton">Create</button>
    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
</form>

my final goal is to add some extra functionality to the button (an api call) alongside actually submitting the form (I want to keep it in the template, and not in Django views/models)

P.S one idea is to programmatically submit the form with something like:

  document.addEventListener('DOMContentLoaded', function() {
    const form = document.getElementById('myform');
    form.addEventListener('submit', function(event) {
      event.preventDefault();
      submitForm();
    });
  });

  function submitForm() {
    const form = document.getElementById('myform');
    const formData = new FormData(form);

    fetch('{% url "form_submit" %}', {
      method: 'POST',
      body: formData,
      headers: {
        'X-CSRFToken': '{{ csrf_token }}'
      }
    })
    .then(response => response.json())
    .then(data => {
      // Handle the response from the server
      console.log(data);
      if (data.success) {
        // Call the API
        callAPI();
      } else {
        // Handle form errors
        console.error(data.errors);
      }
    })
    .catch(error => {
      // Handle any errors
      console.error(error);
    });
  }

  function callAPI() {
    fetch('/api/endpoint/', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    .then(response => response.json())
    .then(data => {
      // Handle the API response
      console.log(data);
    })
    .catch(error => {
      // Handle any errors
      console.error(error);
    });
  }

but how can I do the same thing without writing the form submission manually?

Extract dates in an text

I have a text with Shamsi date like this:

Pathology report on 01.09.1402 (22.11.2023): Baso-squamous carcinoma in right thigh skin.
Surgical pathology report on 30.03.1403, Multiple lymphoid tissue involved by metastatic epithelial tumor of right inguinal mass.

I want to extract all the dates in an array.

How would you do that?

So far we have this:

const text = `Pathology report on 01.09.1402: Baso-squamous carcinoma in right thigh skin. Surgical pathology report on 30.03.1403, Multiple lymphoid tissue involved by metastatic epithelial tumor of right inguinal mass.`

console.log(getDate(text));

function getDate(d) {
  var day, month, year;

  result = d.match("[0-9]{2}([-/ .])[0-9]{2}[-/ .][0-9]{4}");
  if (null != result) {
    dateSplitted = result[0].split(result[1]);
    day = dateSplitted[0];
    month = dateSplitted[1];
    year = dateSplitted[2];
  }
  result = d.match("[0-9]{4}([-/ .])[0-9]{2}[-/ .][0-9]{2}");
  if (null != result) {
    dateSplitted = result[0].split(result[1]);
    day = dateSplitted[2];
    month = dateSplitted[1];
    year = dateSplitted[0];
  }

  if (month > 12) {
    aux = day;
    day = month;
    month = aux;
  }

  return `${day}.${month}.${year}`;
  
  
}

React-router showing blank page

I’m new to React and currently working on a project in a tutorial. My app has been working fine with static routes, however, as soon as I introduce react router in my app, I get only blank page without any error. I have been searching for last two days, and tried all given solution such as:

  1. downgrade react router dom to v5.
  2. using exact keyword
  3. switched between component and element keyword
  4. Using Routes and without using Routes.

However, none of the solutions seem to work. I have a doubt that it is related to some other package dependency may be, but not sure which package to touch. Following is my package.json configuration:

  "name": "merstart",
  "version": "1.0.0",
  "description": "MERN practice",
  "main": "index.js",
  "scripts": {
    "start": "nodemon -w server server/server.js",
    "compile": "webpack",
    "watch": "webpack-dev-server --hot --no-client-overlay-runtime-errors",
    "test": "echo "Error: no test specified" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.2",
    "express": "^4.19.2",
    "mongodb": "^6.8.0"
  },
  "devDependencies": {
    "@babel/cli": "^7.0.0",
    "@babel/preset-env": "^7.0.0",
    "@babel/preset-react": "^7.0.0",
    "babel-loader": "^8.3.0",
    "babel-polyfill": "^6.26.0",
    "nodemon": "^3.1.4",
    "react": "^18.3.1",
    "react-dom": "^18.3.1",
    "react-router-dom": "^6.26.0",
    "webpack": "^5.93.0",
    "webpack-cli": "^5.1.4",
    "webpack-dev-middleware": "^7.3.0",
    "webpack-dev-server": "^5.0.4",
    "webpack-hot-middleware": "^2.26.1",
    "whatwg-fetch": "^3.6.20"
  }
}

My main app code is as following:

import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter as Router, Routes,Route} from 'react-router-dom';
import IssueEdit from './IssueEdit.jsx';



//import IssueAdd from './IssueAdd.jsx';

const contentNode = document.getElementById('contents');

const noMatch = ()=> <p>Page not found.</p>

const RoutedApp = ()=> {
    console.log("Reached routed app");
    <Router>
    <Routes>
        <Route path="/" action={()=>{console.log("action")}} loader={()=>{console.log("Loader")}} element={<IssueList />} />
        <Route path="/issueEdit" element={<IssueEdit />} />
        <Route path="*" element={<noMatch />} />
    </Routes>
    </Router>
    console.log("Reached end of router");
};

ReactDOM.render(<RoutedApp />,contentNode);

if(module.hot){
    module.hot.accept();
}

Both the console logs for RoutedApp start and end are printed in console, but but console in action of first Route is not printed. Note that if I directly render my IssueList.jsx, it works fine, but when I try with react router it fails.

There are no errors to show. Can anyone guide please.

Impossible to reproduce the clickup carousel animation

its seems impossible to reproduce the carousel of clickup saas… Anyone can help me please ?

the carousel
https://clickup.com/

There is my actual code :

<!DOCTYPE html>
<html lang="fr">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Carousel</title>
      <style>
         body {
         font-family: Arial, sans-serif;
         background-color: #f0f0f5;
         display: flex;
         justify-content: center;
         align-items: center;
         height: 100vh;
         margin: 0;
         }
         .carousel-wrapper {
         position: relative;
         width: 70%;
         margin: 0 auto;
         display: flex;
         align-items: center;
         }
         .carousel-container {
         overflow: hidden;
         width: 100%;
         display: flex;
         justify-content: center;
         position: relative;
         padding-left: 100px;
         padding-right: 100px;
         }
         .carousel {
         display: flex;
         transition: transform 0.5s ease-in-out;
         position: relative;
         }
         .carousel-item {
         display: flex;
         flex-direction: column;
         align-items: center;
         justify-content: center;
         text-align: center;
         margin: 0 30px;
         padding: 20px;
         background-color: #fff;
         border-radius: 10px;
         box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
         opacity: 0.6;
         transition: opacity 0.3s ease, transform 0.3s ease-in-out;
         cursor: pointer;
         width: 150px;
         }
         .carousel-item:hover {
         transform: translateY(-5px);
         }
         .carousel-item.active {
         opacity: 1;
         transform: scale(1.1);
         box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
         }
         .fade-left, .fade-right {
         position: absolute;
         top: 0;
         bottom: 0;
         width: 100px;
         pointer-events: none;
         }
         .fade-left {
         left: 0;
         background: linear-gradient(to right, rgba(240, 240, 245, 1), rgba(240, 240, 245, 0));
         }
         .fade-right {
         right: 0;
         background: linear-gradient(to left, rgba(240, 240, 245, 1), rgba(240, 240, 245, 0));
         }
         .fa-duotone {
         font-size: 50px;
         color: #333;
         }
      </style>
   </head>
   <body>
      <div class="carousel-wrapper">
         <div class="fade-left"></div>
         <div class="carousel-container">
            <div class="carousel">
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-image"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-subtitles" style="--fa-primary-color: #000;"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-link"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-file-code"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-file-pen"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-wand-magic-sparkles"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-circle-question"></i></div>
               <!-- Dupliquer les éléments pour créer un effet continu -->
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-image"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-subtitles" style="--fa-primary-color: #000;"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-link"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-file-code"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-file-pen"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-wand-magic-sparkles"></i></div>
               <div class="carousel-item"><i class="fa-duotone fa-solid fa-circle-question"></i></div>
            </div>
         </div>
         <div class="fade-right"></div>
      </div>
      <script>
         const carousel = document.querySelector('.carousel');
         const items = document.querySelectorAll('.carousel-item');
         const visibleItems = 7; // Le nombre d'éléments visibles
         let currentIndex = Math.floor(items.length / 3); // Index de l'élément central initial
         
         function updateCarousel(newIndex) {
             const middleIndex = Math.floor(visibleItems / 2);
             const offset = newIndex - currentIndex;
         
             if (newIndex < 0 || newIndex >= items.length) return;
         
             const itemWidth = items[0].offsetWidth + 60;
         
             // Déplacer le carrousel pour centrer le nouvel élément cliqué
             carousel.style.transform = `translateX(${-(newIndex - middleIndex) * itemWidth}px)`;
         
             // Mettre à jour la classe active
             items[currentIndex].classList.remove('active');
             items[newIndex].classList.add('active');
         
             currentIndex = newIndex; // Mettre à jour l'index courant
         }
         
         // Ajouter l'événement de clic à chaque élément du carrousel
         items.forEach((item, index) => {
             item.addEventListener('click', () => {
                 updateCarousel(index);
             });
         });
         
         // Initialiser la position du carrousel
         items[currentIndex].classList.add('active');
         carousel.style.transform = `translateX(${-(currentIndex - Math.floor(visibleItems / 2))     * (items[0].offsetWidth + 60)}px)`;
      </script>
   </body>
</html>

But i have already try many things.

So, to recap, I’m trying to create a carousel where 7 elements are visible at the same time, with the 4th element always centered. When a user clicks on an element to the right or left of the center, that element should move to take the central position. For example, if I click on an element that’s to the right of the center, that element should move to the center. The same behavior should occur if an element to the left of the center is clicked. The movement should be smooth and maintain the order of the elements, without scrolling through the entire carousel. Basically, just like ClickUp.

Thanks for any help !


Try & test

Moving Based on Initial and Target Index
Problem: Movement was fixed in increments of 7 items, causing inconsistent shifts and incorrect centering of items.

Absolute Pixel Calculation for Movement
Problem: Used fixed pixel values for movement, resulting in incorrect display and misalignment of centered items.

Using currentOffset for Position Calculation
Problem: Incorrect initial positioning led to misalignment and improper centering of items.

CSS Animation for Pixel Movement
Problem: CSS animations were out of sync with JavaScript calculations, causing display issues.

Recalculation Based on Clicks
Problem: Miscalculated the pixel movement needed, leading to improper centering and alignment.

Initial Centering with Movement Calculation
Problem: Incorrect initial centering resulted in the wrong element being centered and displayed.

Direct translateX Manipulation
Problem: Directly manipulating translateX with incorrect values led to inconsistent movement and centering.

And many other things…

How can I get the decibel (dB) level from sound URI in react native?

const stopRecording = async (coordinate: { latitude: number; longitude: number }) => {
    try {
      if (record) {
        await record.stopAndUnloadAsync();
        const uri = record.getURI();
        const dB = //dB level here
        if (uri) {
          setMarkers((prevMarkers) => [
            ...prevMarkers,
            { coordinate, audioUri: uri },
          ]);
        }
      }
    } catch (err) {
      console.error('Failed to stop recording', err);
    }
  };

Me and my group have been making a noise pollution map. This map allows users to record audio in their cities, which then the location and loudness of the recording will be entered into our database, allowing other users to see the noise pollution in that location. We are able to get the user’s location, but we are having trouble getting the loudness, in dB, of the recording. Nothing has worked so far. How can we do it?

Question about synchronous ajax call in JS

With below code, what I was expecting is “diameter-selected” class to be added to the button and then to run the synchronous ajax calls. But, it seems that ajax calls run before the “.addClass” command and since it is waiting the promise I guess, I see the button effect after ajax request is completed. When I added setTimeout to the ajax calls for 1 nano second, I see the button effect before ajax calls are completed. So, I solved my issue in a weird way but I want to learn if there is a more professional way to achieve this.

    $(document).on("click", ".btn-diameter", function(){

       $(this).addClass("diameter-selected");

       $.ajax({
         method: "POST",
         async: false,
         url: "/page1.asp"
       });

       $.ajax({
         method: "POST",
         async: false,
         url: "/page2.asp"
       });

    });