Cookie returned in set-cookie header response disappears

I have an Angular site hosted on Firebase https://account.mydomain.com, and some Firebase/Google Cloud functions hosted at https://functions.mydomain.com.

I am trying to set up the scenario described in the articles at the end of this question.

In brief I,

  1. log in through Firebase auth on account.mydomain.com
  2. POST the idtoken obtained from a successful login to sessionLogin, a firebase function using onRequest which verifies the id token, and creates a session cookie, returning this in the response.
  3. make another seperate GET to the checkAuthStatus function endpoint to verify the cookie and get an access token which I use to authenticate on https://account.mydomain.com.

The whole aim of this is to use the session to authenicate against any subdomains of mydomain.com. However my issue is that the cookie is never set after step 2, despite being visible in the set-cookie header of the network response.

Set-Cookie:
__session=; Path=/; Domain=mydomain.co.uk; Expires=Mon, 09 Dec 2024 22:33:54 GMT; Max-Age=432000; HttpOnly; Secure; SameSite=None

This cookie doesn’t appear in the Chrome Devtools Application tab for account.mydomain.com. And it isn’t sent with my request in step three, even if I include ‘withCredentials: true’ on my GET request.

This is the body of the function I am posting to,

    res.setHeader('Access-Control-Allow-Credentials', 'true');
    res.setHeader('Access-Control-Allow-Origin', 'https://account.mydomain.com');

    if (req.method === 'OPTIONS') {
        // Send response to OPTIONS requests
        res.set('Access-Control-Allow-Methods', 'POST');
        res.set('Access-Control-Allow-Headers', ['Authorization', 'Content-Type']);
        res.set('Access-Control-Max-Age', '3600');
        res.status(204).send('');
        return;
    }
    else {

        // Get the ID token passed and the CSRF token.
        console.log(req.body.idToken);
        const idToken = req.body.idToken.toString();
        
        const auth = getAuth(app);

        auth.verifyIdToken(idToken).then((decodedToken) => {

            // Set session expiration to 5 days.
            const expiresIn = 60 * 60 * 24 * 5 * 1000;
            
            auth
                .createSessionCookie(idToken, { expiresIn })
                .then(
                    (sessionCookie) => {
                        // Set cookie policy for session cookie.
                        const options = { maxAge: expiresIn, httpOnly: true, secure: true, sameSite: 'none' as const, domain: 'mydomain.com' };
                        res.setHeader('Cache-Control', 'private');
                        
                        res.cookie('__session', sessionCookie, options);
                        res.send('Cookie set');
                        return;
                    },
                    (error) => {
                        res.status(401).send('UNAUTHORIZED REQUEST!');
                    }
                );

        }).catch((error) => {
            // Handle error
            console.error('Error creating sessionLogin:', error);
            res.status(401).send('UNAUTHORIZED REQUEST!');
        });
    }
});

And this is the code which is making the requests from my Angular site,

var responsePromise = new Promise<void>((resolve, reject) => {
  signInWithPopup(this.afAuth, provider)
    .then(async (result: UserCredential) => {

      return result.user.getIdToken().then(idToken => {

        var functionBaseUrl = 'https://account.mydomain.co.uk'; //Hosted

        var body = {
          idToken: idToken
        };

        axios.post(functionBaseUrl + '/sessionLogin', body).then(function (response) {
          console.log(response);

          axios.get(functionBaseUrl + '/checkAuthStatus', {
            withCredentials: true,
            headers: {
              'Content-Type': 'application/json'
            }
          })
            .then(function (response) {
              console.log(response);
            })
            .catch(function (error) {
              console.error(error);
            });
        })
          .catch(function (error) {
            console.error(error);
          });
      });
    })
    .catch((error) => {
      console.error(error);
    });
});

Can anyone spot why this isn’t being set, or provide any further information on now I could diagnose this issue? I don’t appear to have any cors problems, and I also belive I have set the cookie with the correct configuration for a cross site cookie. Can anyone spot, or explain what I might be missing?

The articles,

https://dev.to/johncarroll/how-to-share-firebase-authentication-across-subdomains-1ka8

https://dev.to/brianburton/cross-domain-firebase-authentication-a-simple-approach-337k

Count the number of emoji assigned by user using only 1 loop, charCodes for parsing and 1 result Object

I can use one loop only…
Only one object can be used to store results! not additional array or objects.

Use charCodeAt to find specific characters and fromCharCode for converting characters to lowercase.
No methods like map – that use cycle, and no methods – only char codes and math

An emoji is valid if it has the format :apple: (colon, lowercase or uppercase name, colon), with no spaces or other characters.

Usernames are extracted from the format <@username /> and are no case-insensitive (converted to lowercase to push).

MAIN PROBLEM:
If one user is immediately followed by another user, they form a group, and any subsequent emojis are shared among all users in that group. This means:

If a user (e.g., Max) does not have any valid emojis and is followed by another user (Kate) who does, then Max should inherit the emoji count from Kate.
This can form a chain of users without emojis, and all their counts must be updated when a valid emoji is found for any subsequent user in the group.
Constraints:
No additional loops or cycles (e.g., no for, while, etc.).
No extra arrays or objects can be used to manage grouping.

function countEmoji(message, emoji) {
  const ASCII = {
    numFirstCharCode: 48,
    numLastCharCode: 57,
    openBracket: 60,
    closeBracket: 62,
    atSign: 64,
    slash: 47,
    toLowerOffest: 32,
    upperCaseStart: 65,
    upperCaseEnd: 90,
    lowerCaseStart: 97,
    lowerCaseEnd: 122,
    space: 32,
    colon: 58,
  };

  let result = {};

  let name = "";
  let isNameCreated = false;
  let nameCreationStage = 0;

  let emojiFounded = 0;
  let emojiStage = -1;

  function toLowerCase(char) {
    const isInUpperCase =
      ASCII.upperCaseStart <= char && char <= ASCII.upperCaseEnd;
    if (isInUpperCase) {
      return String.fromCharCode(char + ASCII.toLowerOffest);
    }
    return char;
  }

  for (let i = 0; i < message.length; i++) {
    const charCode = message.charAt(i).charCodeAt();
    const isInLowerCase =
      ASCII.lowerCaseStart <= charCode && charCode <= ASCII.lowerCaseEnd;
    const isInUpperCase =
      ASCII.upperCaseStart <= charCode && charCode <= ASCII.upperCaseEnd;

    if (!isNameCreated) {
      if (charCode === ASCII.openBracket && nameCreationStage === 0) {
        nameCreationStage++;
      } else if (charCode === ASCII.atSign && nameCreationStage === 1) {
        nameCreationStage++;
      } else if ((isInUpperCase || isInLowerCase) && nameCreationStage === 2) {
        if (isInLowerCase) {
          name += String.fromCharCode(charCode);
        } else if (isInUpperCase) {
          name += String.fromCharCode(charCode + ASCII.toLowerOffest);
        }
      } else if (name) {
        if (charCode === ASCII.space) {
          continue;
        } else if (charCode === ASCII.slash) {
          nameCreationStage++;
        } else if (charCode === ASCII.closeBracket && nameCreationStage === 3) {
          nameCreationStage = 0;
          isNameCreated = true;
        }
      }
      continue;
    }

    if (isNameCreated) {
      //search for pattern start - :
      if (charCode === ASCII.colon && emojiStage === -1) {
        emojiStage++;
        continue;
      }
      if (emojiStage - (emoji.length - 1) === 1) {
        if (charCode === ASCII.colon) {
          emojiFounded++;
          emojiStage = -1;
          continue;
        }
      }
      //start compering symbols
      if (charCode === toLowerCase(emoji.charAt(emojiStage).charCodeAt())) {
        emojiStage++;
        continue;
      } else {
        if (charCode === ASCII.openBracket && nameCreationStage === 0) {
          nameCreationStage++;
          isNameCreated = false;
          result = { ...result,
            [name]: emojiFounded
          };
          name = "";
          emojiFounded = 0;
        }
        emojiStage = -1;
      }
    }
  }
  result = { ...result,
    [name]: emojiFounded
  };
  return result;
}

const text = '<@Kate />:apple: <@Max/>:like:<@alisa /> :like: received:apple::apple:';
const emoji = "apple";

console.log(countEmoji(text, emoji));
//my results: {kate: 1, max: 0; alisa: 2}

// expected result
// {
// kate: 1,
// max: 2,
// alisa: 2
// }

//For test:

//const text = "<@Kate />:apple: <@Max/>:apple: :APPLE: :AppLe:<@alisa /> :like: //received:apple::apple:";

//{ kate: 1, max: 3, alisa: 2 } // no case-insensitive for emoji

//const text = "<@Kate />:apple: <@Max/><@olia/><@misha/><@dasha/><@alisa /> :like: //received:apple::apple: <@dima/><@vasia/><@gena/><@ihor/><@tolik />";
//{ kate: 1, max: 2, olia: 2, misha: 2, dasha: 2, alisa: 2 }

Javascript formula to math.js formula format

I used Maple 2024 to find some big expressions which I want to use in Javascript for further calculations. In total there are 20 big expressions which I have in the format of Latex and Maple. The input parameters are all real positive values (1 can be 0, which is ok). But for some specific combinations of parameters, some values inside roots go below 0. I saw that the package “math.js” accepts complex values and can also calculate with them.

Unfortunately I have te rewrite my equations in a completely different format. Is there a tool or method to easily do this?

The smallest expression I have:

function expression(beddingsconstante, Phiy, L, EIyy) {
  var bc = beddingsconstante;
      
  var a_p = math.sqrt(math.add(Phiy * L ** 2 * math.sqrt(bc), math.sqrt(bc * Phiy ** 2 * L ** 4 - 576 * EIyy)));
  var a_m = math.sqrt(math.subtract(Phiy * L ** 2 * math.sqrt(bc), math.sqrt(bc * Phiy ** 2 * L ** 4 - 576 * EIyy)));
  var b_p = math.multiply(a_p, L * math.sqrt((6 * math.sqrt(bc)) / (144 * EIyy)));
  var b_m = math.multiply(a_m, L * math.sqrt((6 * math.sqrt(bc)) / (144 * EIyy)));
      
  var sh_b_p = math.sinh(b_p);
  var ch_b_p = math.cosh(b_p);
  var sh_b_m = math.sinh(b_m);
  var ch_b_m = math.cosh(b_m);
      
  return math.sqrt(6) * math.sqrt(EIyy) * bc ** (5 / 4) * ((Phiy ** 3 * a_m * sh_b_m * L ** 6 * (-1 * ch_b_p ** 2 + (ch_b_m + sh_b_p) * ch_b_p + ch_b_m * sh_b_p) * a_p * bc ** (3 / 2) - 432 * (Phiy * a_m * sh_b_m * L ** 2 * (-1 * ch_b_p ** 2 + (ch_b_m + sh_b_p) * ch_b_p + ch_b_m * sh_b_p) * a_p * math.sqrt(bc) + 192 * EIyy * (sh_b_m ** 2 * ch_b_p + ch_b_m * sh_b_p * (-1 * ch_b_p + ch_b_m + sh_b_p))) * EIyy) * math.sqrt(L ** 4 * Phiy ** 2 * bc - 576 * EIyy) + a_p * sh_b_m * a_m * (L ** 4 * Phiy ** 2 * bc - 576 * EIyy) * (L ** 4 * Phiy ** 2 * bc - 144 * EIyy) * (ch_b_p - sh_b_p) * (ch_b_m - ch_b_p)) / ((L ** 2 * sh_b_p * bc * Phiy * (L ** 4 * Phiy ** 2 * bc - 432 * EIyy) * sh_b_m - 144 * EIyy * math.sqrt(bc) * a_m * a_p * (ch_b_m * ch_b_p - 1)) * (Phiy * (a_p * sh_b_m + (-1 * ch_b_p + ch_b_m + sh_b_p) * a_m) * math.sqrt(bc) * L ** 2 * math.sqrt(L ** 4 * Phiy ** 2 * bc - 576 * EIyy) + (-a_p * sh_b_m + (-1 * ch_b_p + ch_b_m + sh_b_p) * a_m) * (L ** 4 * Phiy ** 2 * bc - 288 * EIyy)))
}

console.log(expression(100, 0.712, 1000, 62500000000000));

// If the formula is copied correctly into the function, this should be the solution:
// 439586.9657 + 0.0002542252659*I
<script src="https://cdnjs.cloudflare.com/ajax/libs/mathjs/12.4.0/math.js"></script>

As you may see, all the variables are already in the good format. But I was not so happy to do that for 20 huge expressions… Any idea how I could do this easily?

React-Native Expo project loads the same module twice, once as ts, once as js

I have an npm module called Body. (https://github.com/ouroboroscoding/body-js) It exports a single instance of an object.

const body = new Body();
export default body;

I have a second npm module, called Brain. (https://github.com/ouroboroscoding/brain-js) Brain requires the use of body, the instance, not the class, so it imports it like so.

import body from '@ouroboros/body';

and exports itself

const brain = new Brain();
export default brain;

Both packages contain .ts, .d.ts, and .js files for all modules.

Before anything can be used from body, it needs to be passed a specific string. This is done in the top level project using these packages.

import body from '@ouroboros/body';
body.domain('somedomain.com');

In projects where I use JavaScript exclusively, I have never run into an issue, however recently I started a React Native project using Expo, which is using tsx files for components, and any time brain tried to use body, it would throw errors that it was missing the domain, despite it absolutely being set.

At this point I added a unique constructor to body just to add a console.log line, and this is what came out.

typescript constructor                index.ts:111
javascript constructor                index.js:54

Everything about how TypeScript / JavaScript works says it’s impossible for a module to be evaluated twice, so by definition it’s impossible for the Contructor to be called twice unless both the ts and js files are being loaded as different imports.

Why would the same call of import body from '@ouroboros/body'; in two different files end up loading different versions of the file? What makes one choose ts over js and vice versa?

Also, thanks to StackOverflow suggestions, I came across the “preferTsExts” option, added it as true to tsconfig.json, but nothing changed, still 2 instances.

Reproducible steps:

$: npx create-expo-app@latest ExpoTest
$: cd ExpoTest
$: npm install @ouroboros/body @ouroboros/brain

then in ExpoTest/app/_layout.tsx add

import body from '@ouroboros/body';
import brain from '@ouroboros/brain';
body.domain('somedomain.com');

And the body instance is created twice, once from ts, once from js.

If you absolutely must see the output to believe it, add the following to @ouroboros/body/src/index.ts

constructor() {
   console.log('typescript constructor');
}

and add the following to @ouroboros/body/src/index.js

constructor() {
   console.log('javascript constructor');
}

First time you run the app, no reload, no hot refresh, first time, you will see

typescript constructor
javascript constructor

vuejs add a modul to js file that is not needed

I am trying to migrate one of my projects form ASP.NET MVC to VueJS (latest). On one of my pages in ASP.NET MVC I have win wheel (this). When I try to add it to the vue page I am getting the following error in colnsole:

ActivateChoice.vue:55 SyntaxError: The requested module ‘/node_modules/.vite/deps/primevue_image.js?v=07215650’ does not provide an export named ‘Image’ (at wheel.js:2:1)
Uncaught (in promise) SyntaxError: The requested module ‘/node_modules/.vite/deps/primevue_image.js?v=07215650’ does not provide an export named ‘Image’ (at wheel.js:2:1)

In the Sources in the browser I can see, that somehow this line got added:
import {Image, image} from “/node_modules/.vite/deps/primevue_image.js?v=07215650”;
and I do not know why.

I imported the winwheel.js file like this:

import * as Winwheel from ‘./../../infrastructure/wheel.js’;

I also found that someone had already made a wrapper around vuejs (here). I copied the ES6 formated winwheel.js file to my solution, but still the same.

I am usging primevue, and I have configured AutoImport for the primevue;

thnx

Issue with Slider Centering on Mobile: Elements Shift, Duplicate, and Lose Alignment Over Time

I’m facing an issue with the slider on the mobile version of my site, and I can’t figure out what exactly is wrong. On the mobile version, the slides are not centering as they should. As a result, elements sometimes move to the side, and sometimes the slides are duplicated. Over time, the centering of the slides completely breaks, and they start behaving inconsistently. On the desktop version, this is not as noticeable since the container takes up the full width of the screen, but on mobile, I just need the slide to be exactly in the center during both manual and auto scrolling. I just started learning JS, so I can’t figure it out. I’ve already spent two days on it and would appreciate your help!

document.addEventListener("DOMContentLoaded", function() {
  const wrapper = document.querySelector(".wrapper");
  const slides = Array.from(wrapper.children);
  const leftButton = document.querySelector(".scroll-button.left");
  const rightButton = document.querySelector(".scroll-button.right");

  function getSlideWidth() {
    const slide = slides[0]; // Первый слайд
    const style = window.getComputedStyle(slide);
    const marginRight = parseInt(style.marginRight, 10) || 0; // Учитываем отступ между слайдами
    return slide.getBoundingClientRect().width + marginRight;
  }

  const slideWidth = getSlideWidth();

  // Дублируем слайды для бесконечного скролла
  slides.forEach(slide => {
    const cloneStart = slide.cloneNode(true);
    const cloneEnd = slide.cloneNode(true);
    wrapper.appendChild(cloneEnd); // Дублируем в конец
    wrapper.insertBefore(cloneStart, wrapper.firstChild); // Дублируем в начало
  });

  const originalSlidesCount = slides.length;

  wrapper.scrollLeft = originalSlidesCount * slideWidth;



  // Корректировка положения
  function correctScrollPosition() {
    const maxScrollLeft = (originalSlidesCount * 2 - 1) * slideWidth;

    if (wrapper.scrollLeft < originalSlidesCount * slideWidth - slideWidth / 2) {
      wrapper.scrollLeft += originalSlidesCount * slideWidth;
    } else if (wrapper.scrollLeft > maxScrollLeft + slideWidth / 2) {
      wrapper.scrollLeft -= originalSlidesCount * slideWidth;
    }
  }

  // Прокрутка влево
  leftButton.addEventListener("click", function() {
    const targetScrollLeft = wrapper.scrollLeft - slideWidth;
    wrapper.scrollTo({
      left: targetScrollLeft,
      behavior: "smooth",
    });

    setTimeout(correctScrollPosition, 300); // Исправляем после анимации
  });

  // Прокрутка вправо
  rightButton.addEventListener("click", function() {
    const targetScrollLeft = wrapper.scrollLeft + slideWidth;
    wrapper.scrollTo({
      left: targetScrollLeft,
      behavior: "smooth",
    });

    setTimeout(correctScrollPosition, 300); // Исправляем после анимации
  });

  // Корректируем позицию при ручной прокрутке
  wrapper.addEventListener("scroll", () => {
    clearTimeout(wrapper.isScrolling);
    wrapper.isScrolling = setTimeout(correctScrollPosition, 100);
  });

  // Автоскролл
  const intervalTime = 5000; // Интервал в миллисекундах
  let autoScroll = setInterval(() => {
    const targetScrollLeft = wrapper.scrollLeft + slideWidth;
    wrapper.scrollTo({
      left: targetScrollLeft,
      behavior: "smooth",
    });

    setTimeout(correctScrollPosition, 300); // Исправляем после анимации
  }, intervalTime);

  // Остановка автоскролла при наведении мыши
  wrapper.addEventListener("mouseenter", () => clearInterval(autoScroll));

  // Возобновление автоскролла при убирании мыши
  wrapper.addEventListener("mouseleave", () => {
    autoScroll = setInterval(() => {
      const targetScrollLeft = wrapper.scrollLeft + slideWidth;
      wrapper.scrollTo({
        left: targetScrollLeft,
        behavior: "smooth",
      });

      setTimeout(correctScrollPosition, 300);
    }, intervalTime);
  });
});
.scroll-container {
  display: flex;
  margin-bottom: 15px;
  align-items: center;
  gap: 10px;
  width: 100%;
  position: relative;
}

.wrapper {
  display: flex;
  overflow-x: scroll;
  gap: 10px;
  padding: 10px;
  border-radius: 10px;
  width: 100%;
  overflow-y: hidden;
  /* Скрываем полосу прокрутки */
  -ms-overflow-style: none;
  scrollbar-width: none;
}

.wrapper::-webkit-scrollbar {
  display: none;
  /* Chrome, Safari и Opera */
}

.content-item {
  flex: 0 0 608px;
  /* Фиксированная ширина слайда */
  height: 200px;
  /* Высота слайда */
  background-color: #f0f0f0;
  position: relative;
  /* Для позиционирования заголовка */
  color: #fff;
  text-align: left;
  padding: 20px;
  display: flex;
  box-sizing: border-box;
  flex-direction: column;
  justify-content: flex-end;
  background-size: cover;
  /* Адаптация фонового изображения */
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 10px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  /* Лёгкая тень */
}

.content-text {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  position: relative;
  z-index: 1;
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: normal;
  max-width: 80%;
}

.content-text h2 {
  margin: 0 0 10px 0;
  font-size: 18px;
  font-weight: bold;
  color: #333333;
}

.content-text p {
  margin: 0;
  font-size: 14px;
  color: #666666;
  line-height: 1.4;
}

.scroll-button {
  background-color: transparent;
  width: 40px;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  cursor: pointer;
  position: absolute;
  z-index: 10;
  border: none
}

.scroll-button.left {
  left: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.scroll-button.right {
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
}

.scroll-button span {
  font-size: 18px;
  font-weight: bold;
  color: #333;
}

.scroll-button:hover {
  background-color: #f8f9fa;
}

.scroll-button:active {
  background-color: #e2e6ea;
}

.scroll-button::after {
  content: '';
  position: absolute;
  inset: 0;
  border-radius: 0;
  box-shadow: none;
}

.icon-container {
  position: absolute;
  /* Абсолютное позиционирование */
  top: 50%;
  /* Центрируем по вертикали */
  right: 20px;
  /* Отступ от правого края */
  transform: translateY(-50%);
  /* Корректируем вертикальное центрирование */
}

.icon-container img {
  width: 160px;
  /* Размер иконки */
  height: 160px;
  object-fit: contain;
  /* Сохраняем пропорции */
}


}
@media (max-width: 768px) {
  .wrapper {
    overflow-x: scroll;
    /* Отключаем горизонтальную прокрутку */
  }
  
  .content-item {
    flex: 0 0 100%;
    /* Слайд занимает 100% ширины экрана */
    height: 200px;
    /* Задайте нужную высоту */
    margin-right: 0;
    /* Убираем отступы между слайдами */
  }
}
@media (max-width: 500px) {
  .category-item img {
    scale: 1.5
  }
}
@media (max-width: 768px) {
  .scroll-container {
    overflow: hidden;
    position: relative
  }
  
  .content-item {
    flex: 0 0 90%;
    /* Слайды занимают 90% ширины экрана */
    height: 150px;
    /* Уменьшаем высоту для мобильных */
  }
  
  .wrapper {
    gap: 5px;
    /* Уменьшаем отступы между слайдами */
    padding: 5px;
    /* Сужаем внутренние отступы */
  }
}
@media (max-width: 480px) {
  .content-item {
    flex: 0 0 95%;
    /* Слайды занимают почти всю ширину экрана */
    height: 120px;
    /* Ещё меньше высота для маленьких экранов */
  }
  
  .icon-container img {
    width: 100px;
    height: 100px;
    object-fit: contain;
  }
}
@media (max-width: 768px) {
  .wrapper {
    display: flex;
    justify-content: start;
    align-items: center;
    overflow-x: auto;
    scroll-behavior: smooth;
  }
  
  .wrapper::-webkit-scrollbar {
    display: none;
  }
  
  .scroll-button {
    display: none;
  }
}
<div class="scroll-container">
  <button class="scroll-button left"><span> &lt;</span></button>
  <div class="wrapper">
    <div class="content-item" style="background-color:#EBD8F4">
      <div class="content-text">
        <h2>Osalege konkursil</h2>
        <p>Saage võitjaks ja võitke väärtuslikke auhindu!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/cup.png" alt="Icon">
      </div>
    </div>
    <div class="content-item" style="background-color:#ADD2FF">
      <div class="content-text">
        <h2>Postitage kuulutusi</h2>
        <p>Rääkige maailmale oma toodetest ja teenustest!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/pen.png" alt="Icon">
      </div>
    </div>
    <div class="content-item" style="background-color:#FEEE99">
      <div class="content-text">
        <h2>Turvalisuse juhend</h2>
        <p>Kuidas vältida petuskeeme?</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/security.png" alt="Icon">
      </div>
    </div>
    <div class="content-item" style="background-color:#F3E1D7">
      <div class="content-text">
        <h2>Vaheta oma kaup</h2>
        <p>Vaheta vana uue vastu — lihtsalt ja mugavalt!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/exchange.png" alt="Icon">
      </div>

    </div>
    <div class="content-item" style="background-color:#F3E1D7">
      <div class="content-text">
        <h2>Vaheta oma kaup</h2>
        <p>Vaheta vana uue vastu — lihtsalt ja mugavalt!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/exchange.png" alt="Icon">
      </div>

    </div>
    <div class="content-item" style="background-color:#FEEE99">
      <div class="content-text">
        <h2>Turvalisuse juhend</h2>
        <p>Kuidas vältida petuskeeme?</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/security.png" alt="Icon">
      </div>
    </div>
    <div class="content-item" style="background-color:#ADD2FF">
      <div class="content-text">
        <h2>Postitage kuulutusi</h2>
        <p>Rääkige maailmale oma toodetest ja teenustest!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/pen.png" alt="Icon">
      </div>
    </div>
    <div class="content-item" style="background-color:#EBD8F4">
      <div class="content-text">
        <h2>Osalege konkursil</h2>
        <p>Saage võitjaks ja võitke väärtuslikke auhindu!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/cup.png" alt="Icon">
      </div>
    </div>
    <div class="content-item" style="background-color:#F3E1D7">
      <div class="content-text">
        <h2>Vaheta oma kaup</h2>
        <p>Vaheta vana uue vastu — lihtsalt ja mugavalt!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/exchange.png" alt="Icon">
      </div>

    </div>
    <div class="content-item" style="background-color:#FEEE99">
      <div class="content-text">
        <h2>Turvalisuse juhend</h2>
        <p>Kuidas vältida petuskeeme?</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/security.png" alt="Icon">
      </div>
    </div>
    <div class="content-item" style="background-color:#ADD2FF">
      <div class="content-text">
        <h2>Postitage kuulutusi</h2>
        <p>Rääkige maailmale oma toodetest ja teenustest!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/pen.png" alt="Icon">
      </div>
    </div>
    <div class="content-item" style="background-color:#EBD8F4">
      <div class="content-text">
        <h2>Osalege konkursil</h2>
        <p>Saage võitjaks ja võitke väärtuslikke auhindu!</p>
      </div>
      <div class="icon-container">
        <img src="https://h2h.ee/assets/img/icons_slider/cup.png" alt="Icon">
      </div>
    </div>
  </div>
  <button class="scroll-button right"><span> &gt;</span></button>
</div>

How do I make my javascript know the index number of the post i want to delete?

This is the second question I’m asking about this capstone project! I feel bad about that, but I’m sure I’m not the only one…
For the project, I need to make it possible to delete and edit posts. I’m focusing on the delete part now, but I don’t know where to start. I want to make it so I click the button on the post and it deletes the correct post based on the index number, but I don’t know how to send the index of the post selected to the javascript? here’s some of the code:

<% if ((locals.ptit)) {%>
    <% for (let index = 1 ; index < ptit.length; index++) { %>
        
    
    <div class="post">
        <h1><%= ptit[index] %></h1>
        <p><%= stuff[index] %></p>
    <form action="/delete" method="DELETE">
        <input type="submit" value="POST IS DONE" class="donebtn" name=index/>

    </form></div>
    <% } %>
    <% } %>

^ that is the EJS and v is the JS

app.delete("/delete" (req, res) => {
titles.push(req.body["puttit"]);
posts.push(req.body["posty"]);
res.render("blog.ejs", {
ptit: titles,
stuff: posts,
});
})

Please help me, I’ve tried to search this to the best of my ability but I feel like I’m missing too much…

How to pass a variable like an ID to a URL in Playwright?

I’m creating a new user on a test in Playwright and at next point, I will need to take the id of this new user to to be deleted.
At the end of the code, I’m creating a variable with the id of this user, like this:

const loginResponseJson = await response.json();
const id = loginResponseJson.id;
console.log(id);
console.log("New Created User is: " + id);

And then my question is:
How to pass a variable like an ID to a URL in Playwright?
To delete, I should do like this:

test('Should be able to delete a new created user', async ({ request }) => {
const response = await request.delete(`/public/v2/users/`, {
});

The ID should enter after the URL in request, but I don’t get to put this properly. How I pass this in Playwright?

Content Security policy Error in vercel deployment

I have the following error when I deploy the server to vercel.

Refused to load the script ‘https://vercel.live/_next-live/feedback/feedback.js’ because it violates the following Content Security Policy directive: “default-src ‘none'”. Note that ‘script-src-elem’ was not explicitly set, so ‘default-src’ is used as a fallback

I tried the following in index.js to solve but it does not make any effect…Any one kindly tell the solution.

app.use((req, res, next) => {
   res.setHeader(
     'Content-Security-Policy', "default-src 'self'; script-src 'self' cdn.example.com https://vercel.live; img-src 'self' img.example.com; style-src 'self';"
   );
   next();
});"

Please solve this code, as it throws up many errors؟ [closed]

const baseUrl = “https://api.football-data.org/v4/competitions/2014”
const token = “07245a5da7754673b21dcc575d373dc4”

function gatStandings(){
const url = ${baseUrl}/standings
axios.get(url, {
headers: {
“X-Auth-Token”: token
}
})
.then((response) => {
console.log(response.data.standings);
})
}

gatStandings()

I couldn’t find a solution

How do I dynamically alter the speed of a GraphicObject in Incisor?

I am attempting to dynamically alter the speed of a GraphicObject in motion in Incisor. I have a speed property initialized to zero. I add motion, using the speed property as my motion speed. Then, I swoop value on the speed property.

Here’s a simple example of what I’m doing.

class ProjectMain {


    init() {
     

        let myGraphicObject = new GraphicObject( nc.graphicAssets.whiteBox, nc.mainScene, "Box" );

        this.speed = 0;

        myGraphicObject.position.addMotion.each( [-300,-100,0], [300,100,10], this.speed, nc.motionTypes.MoveInCircle );

    // swoop the speed property to alter the motion
        nc.swoopValue( this, "speed", 10, 10 );
        
    }
}

I expect to see the box increase speed as it spins but it is actually not moving at all. I am obviously doing something wrong here. My assumption is that the speed is initialized to zero, and swooping it is having no effect on the motion. So, the motion is zero. No movement.

How can I accomplish what I am trying to do?

I am a girl, and I don’t know which path to take, and I also don’t know how to write code [closed]

The main problem is that I am a girl with a diploma in Computer Science, and I only learned the basics. I don’t know which path to take, and I also don’t know how to write code. Should I memorize it or what? I hope someone can guide me, as I am confused about which path to follow

I have tried watching YouTube and tutorial videos, and I was practicing and applying writing codes. But when I try to create a code, I don’t know how to write it. I feel like this field is not for me.

Inputs are not being registered in JavaScript

If I invoke greeting() on page load then I receive nothing in the browser (I am looking to amend h1 accordingly). I have tried console.log on various points and my conclusion is that since I am invoking greeting() upon page load, the userInput() is still an empty string when inputValidator() needs it. I don’t want an event listener such as okBtn.addEventListener("click", () => {*some code here*} in the main code body because when I am doing so, the {*some code here*} runs every time I click on okBtn , and I have some other functionalities as well which I would like to associate with this button’s click. Also I would like all my messages to appear in the same h1 and I would prefer not to include additional elements for the above. Thanks

[A little side note, upon reloading the page, I get the input (cached data) from before refreshing the page appearing in the browser console when I use console log. Just for my knowledge, is there a way to clear the browser cache upon page reload? I tried window.location.reload(); but —(1)- This doesn’t seem to work in Google Chrome and works only in Fire Fox —(2)- I am using VS Code Live Server and using this command keeps refreshing my page as it is probably meant to do.]

HTML

<h1 id="name-move"></h1>
<form action ='#'>
  <input type="text" placeholder="Type here..." id="input" required>
  <button id="ok-btn">OK</button>
</form>

JavaScript

var nameInput = document.getElementById("input");
var questions = document.getElementById("name-move");
var okBtn = document.getElementById("ok-btn");

window.onload = function () {
  document.querySelector("form").reset();
  questions.innerHTML = `Please enter your first name!`;
};

let userInput = () => {
  return nameInput.value;
};

let inputValidator = (val) => {
  okBtn.addEventListener("click", () => {
    if (val.length > 15 || /[0-9.*+?><,#^=!:${}()|[]/\]+/g.test(val)) {
      questions.innerHTML = `No numbers or special characters and no more than 15 characters allowed`;
    } else { 
       return val;
    }
  });
};

function greeting() {
  let us = inputValidator(userInput());
  questions.innerHTML = `Welcome ${us}! Let's play Rock Paper and Scissors!`;  
}

Optimization of render for a draggable component in React.js

I am working on creating a draggable component that should support gestures (dragging). I’ve encountered a performance optimization issue: the animation does not look smooth despite various attempts to improve performance. I notice that while dragging, the component stutters and doesn’t respond as smoothly as I would like.

I have already tried different optimization methods, including using requestAnimationFrame(), but it still did not help to achieve the desired smoothness.

For comparison, I noticed that the framer-motion library provides much smoother movement without such lag. I’m curious how they managed to achieve that level of smoothness. I suspect the issue may be related to improper render implementation, but I haven’t been able to find an optimal solution.

I am attaching resources for better understanding of the problem:

It’s worth noting that the component has been greatly simplified, and all unnecessary parts have been removed, leaving only the problematic section. Therefore, please ignore the code’s cleanliness.

  1. Link to the sandbox with the test: https://codesandbox.io/p/sandbox/24rmvm

  2. Video showing the behavior without framer-motion: https://drive.google.com/file/d/1ZUcLiyQywpL6oHUMP-5KwM6gQAei0xpk/view?usp=sharing

  3. Video showing the behavior with framer-motion: https://drive.google.com/file/d/10aERUyDrba4AFp5qEqZhlMTd45D5Z_Js/view?usp=sharing

I would appreciate any advice or hints on how to optimize the rendering of draggable components!

I have already tried different optimization methods, including using requestAnimationFrame(), but it still did not help to achieve the desired smoothness.

How do I iterate within columnDefs in DataTables

I’m building a DataTable with SearchPanes, trying to construct custom options, more or less following this documentation: https://datatables.net/extensions/searchpanes/examples/customFiltering/customOptionConditions.html

Now, the options are in fact within a separate array, like this e.g.:

cities = ['London','Edinburgh'];

So, instead of having fixed options like this:

options: [
    {
        label: 'London',
        value: function (rowData, rowIdx) {
            return rowData[3] == 'London';
        }
    },
    {
        label: 'Edinburgh',
        value: function (rowData, rowIdx) {
            return rowData[3] == 'Edinburgh';
        }
    },
]

.. I want to construct them dynamically, iterating over the array, like this:

options: [
    cities.forEach((element) =>
    {
        label = element,
        value = function (rowData, rowIdx) {
            return rowData[3] == element;
        }
    },
]

But this doesn’t really work, and I cannot figure out where I’m doing wrong, mainly due to my lack of javascript knowledge. I’m probably not constructing the object in the right way. I’ve tried various things, but to no avail, usually getting back an “Unexpected token” error.

So, please enlighten me =)