why does the intellisense not work for mathjs?

I installed the mathjs module using the npm.

The instructions are here: https://www.npmjs.com/package/mathjs

I install globally (the -g flag) like this:

npm install -g mathjs

when i write my code in VScode like the below, the intellisense does not work for mathjs. So i cannot see the methods or attributes in the dropdown list when i press ..


/*
why does the intellisense not work for mathjs ?
*/

const mathjs = require('mathjs')  // intellisense does not work
const fs = require('fs')   // intellisense does work


let m = mathjs.mean([1,2,3,4,5])  // the actual module method works fine !
let n = Math.max(1,2,3,4,5)   // the intelisense works fine here too.


console.log(m)
console.log(n)

points to note:

  • the methods do work for mathjs, just not the intellisense.
  • the intellisense work for other imported modules (eg: require('fs')).
  • the intellisense in the Math module also work.

so, it seems to be specifically isolated to this one module.

So the question is: How can i get the intellisense working for mathjs ?

Lazy load always load largest images

I have implemented lazy load with this code:

<script>
(function(w, d) {
    var b = d.getElementsByTagName('body')[0];
    var s = d.createElement("script");
    var v = !("IntersectionObserver" in w) ? "8.17.0" : "10.20.1";
    s.async = true;
    s.src = "https://cdnjs.cloudflare.com/ajax/libs/vanilla-lazyload/" + v + "/lazyload.min.js";
    w.lazyLoadOptions = {
        elements_selector: '.lazy',
        threshold: 250
    };
    b.appendChild(s);
}(window, document));

Image:

<img class="mimg lazy" src="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEHAAEALAAAAAABAAEAAAICTAEAOw==" data-src="https://example.com/photos/galeries/11992/11992_3.jpg" data-srcset="https://example.com/photos/galeries/11992/11992_3.jpg 650w, https://example.com/photos/galeries/11992/11992_xxl_3.jpg 1600w" sizes="(max-width: 992px) 650px, (min-width: 993px) 1600px, 650px" width="650" height="433" alt="Alt text" />

The question is that it is always loading the largest image xxl.

I don’t know why it doesn’t load the little image for example in mobile devices.

Thank you

Foundation 6 Responsive Menu not functioning as expected. What do I need to change to make it work?

First, the source code:


<!DOCTYPE html>
<html class="no-js" lang="en-US">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <meta name='robots' content='max-image-preview:large' />
<link rel='stylesheet' id='foundation-css' href='https://cdn.jsdelivr.netnpm/[email protected]/dist/css/foundation.min.css' type='text/css' media='all' />
<script type="text/javascript" src="http://example.com/wp-includes/js/jquery/jquery.min.js?ver=3.7.1" id="jquery-core-js"></script>
<script type="text/javascript" src="http://example.com/wp-includes/js/jquery/jquery-migrate.min.js?ver=3.4.1" id="jquery-migrate-js"></script>
      
</head>
<body class="home blog">

    <ul class="vertical medium-horizontal menu" data-responsive-menu="drilldown medium-dropdown">
      <li>
        <a href="#">Item 1</a>
        <ul class="vertical menu">
          <li>
            <a href="#">Item 1A</a>
            <ul class="vertical menu">
              <li><a href="#">Item 1A</a></li>
              <li><a href="#">Item 1B</a></li>
              <li><a href="#">Item 1C</a></li>
              <li><a href="#">Item 1D</a></li>
              <li><a href="#">Item 1E</a></li>
            </ul>
          </li>
          <li><a href="#">Item 1B</a></li>
        </ul>
      </li>
      <li>
        <a href="#">Item 2</a>
        <ul class="vertical menu">
          <li><a href="#">Item 2A</a></li>
          <li><a href="#">Item 2B</a></li>
        </ul>
      </li>
      <li>
        <a href="#">Item 3</a>
        <ul class="vertical menu">
          <li><a href="#">Item 3A</a></li>
          <li><a href="#">Item 3B</a></li>
        </ul>
      </li>
    </ul>

        <script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/foundation.min.js?ver=6.7.4" id="theme-js"></script>
    <script>
        (function($){
            $(document).foundation();
        })(jQuery);
    </script>
</body>
</html>

As you can see, Foundation 6.8.1 and jQuery 3.7.1 have been added. I’ve initialised Foundation and I know it’s working as the responsive menu is gaining a data-mutate attribute.

<ul class="vertical medium-horizontal menu" data-responsive-menu="drilldown medium-dropdown" data-mutate="4vsm9h-responsive-menu">
      <li>
        <a href="#">Item 1</a>
        <ul class="vertical menu">
          <li>
            <a href="#">Item 1A</a>
            <ul class="vertical menu">
              <li><a href="#">Item 1A</a></li>
              <li><a href="#">Item 1B</a></li>
              <li><a href="#">Item 1C</a></li>
              <li><a href="#">Item 1D</a></li>
              <li><a href="#">Item 1E</a></li>
            </ul>
          </li>
          <li><a href="#">Item 1B</a></li>
        </ul>
      </li>
      <li>
        <a href="#">Item 2</a>
        <ul class="vertical menu">
          <li><a href="#">Item 2A</a></li>
          <li><a href="#">Item 2B</a></li>
        </ul>
      </li>
      <li>
        <a href="#">Item 3</a>
        <ul class="vertical menu">
          <li><a href="#">Item 3A</a></li>
          <li><a href="#">Item 3B</a></li>
        </ul>
      </li>
    </ul>

However, it’s not adding the dropdown classes or the data-dropdown-menu attribute.

I’ve tried using different versions of Foundation that I’ve used in past projects where the responsive menu worked as expected. I’ve also tried initialising a straight dropdown menu, i.e. data-dropdown-menu, and that also mutates without adding any of the classes to the elements. I’m sure I must be missing something obvious, but I’m just not seeing what could be wrong with it.

How to install casperjs on yarn

I’ve been creating web scraping slack bot.

When I installed casperjs on yarn, then I ran the program below, I got the error below, that can’t find package “casperjs” imported from calculate.js. How can I fix it?

Error [ERR_MODULE_NOT_FOUND]: Cannot find package '/bot-study/node_modules/casperjs/' imported from /bot-study/calculate.js
    at new NodeError (node:internal/errors:399:5)
    at legacyMainResolve (node:internal/modules/esm/resolve:235:9)
    at packageResolve (node:internal/modules/esm/resolve:876:14)
    at moduleResolve (node:internal/modules/esm/resolve:938:20)
    at defaultResolve (node:internal/modules/esm/resolve:1153:11)
    at nextResolve (node:internal/modules/esm/loader:163:28)
    at ESMLoader.resolve (node:internal/modules/esm/loader:838:30)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:424:18)
    at ModuleWrap.<anonymous> (node:internal/modules/esm/module_job:77:40)
    at link (node:internal/modules/esm/module_job:76:36) {
  code: 'ERR_MODULE_NOT_FOUND'
}

calculate.js:

"use strict";
import bolt from "@slack/bolt";
import dotenv from "dotenv";
import chalk from "chalk";
import casperjs from "casperjs";
const casper = casperjs.create();
dotenv.config();
console.log(`SLACK_APP_TOKEN: ${process.env.SLACK_APP_TOKEN}`);
console.log(`SLACK_BOT_TOKEN: ${process.env.SLACK_BOT_TOKEN}`);
const app = new bolt.App({
    token: process.env.SLACK_BOT_TOKEN,
    appToken: process.env.SLACK_APP_TOKEN,
    socketMode: true,
    logLevel: "debug"
});

casper.start();

const urls = {
  "MathA": [
    "https://www.nnn.ed.nico/courses/1919/chapters/26869",
    "https://www.nnn.ed.nico/courses/1919/chapters/26870",
    "https://www.nnn.ed.nico/courses/1919/chapters/26871",
    "https://www.nnn.ed.nico/courses/1919/chapters/26872",
    "https://www.nnn.ed.nico/courses/1919/chapters/26873",
    "https://www.nnn.ed.nico/courses/1919/chapters/26874",
    "https://www.nnn.ed.nico/courses/1919/chapters/26875",
    "https://www.nnn.ed.nico/courses/1919/chapters/26876"
  ],
  "History": [
    "https://www.nnn.ed.nico/courses/1859/chapters/24327",
    "https://www.nnn.ed.nico/courses/1859/chapters/24328",
    "https://www.nnn.ed.nico/courses/1859/chapters/24329",
    "https://www.nnn.ed.nico/courses/1859/chapters/24330",
    "https://www.nnn.ed.nico/courses/1859/chapters/24331",
    "https://www.nnn.ed.nico/courses/1859/chapters/24332",
    "https://www.nnn.ed.nico/courses/1859/chapters/24333",
    "https://www.nnn.ed.nico/courses/1859/chapters/24334",
    "https://www.nnn.ed.nico/courses/1859/chapters/24335"
   ],
  "Home Economics": [
    "https://www.nnn.ed.nico/courses/1919/chapters/26869",
    "https://www.nnn.ed.nico/courses/1919/chapters/26870",
    "https://www.nnn.ed.nico/courses/1919/chapters/26871",
    "https://www.nnn.ed.nico/courses/1919/chapters/26872",
    "https://www.nnn.ed.nico/courses/1919/chapters/26873",
    "https://www.nnn.ed.nico/courses/1919/chapters/26874",
    "https://www.nnn.ed.nico/courses/1919/chapters/26875",
    "https://www.nnn.ed.nico/courses/1919/chapters/26876",
  ],
  "Japanese": [
    "https://www.nnn.ed.nico/courses/1847/chapters/24267",
    "https://www.nnn.ed.nico/courses/1847/chapters/24268",
    "https://www.nnn.ed.nico/courses/1847/chapters/24269",
    "https://www.nnn.ed.nico/courses/1847/chapters/24270",
    "https://www.nnn.ed.nico/courses/1847/chapters/24271",
    "https://www.nnn.ed.nico/courses/1847/chapters/24272",
    "https://www.nnn.ed.nico/courses/1847/chapters/24273",
    "https://www.nnn.ed.nico/courses/1847/chapters/24274",
    "https://www.nnn.ed.nico/courses/1847/chapters/24275",
    "https://www.nnn.ed.nico/courses/1847/chapters/24276",
    "https://www.nnn.ed.nico/courses/1847/chapters/24277",
    "https://www.nnn.ed.nico/courses/1847/chapters/24278"
  ],
  "art": [
    "https://www.nnn.ed.nico/courses/1903/chapters/24092",
    "https://www.nnn.ed.nico/courses/1903/chapters/24093",
    "https://www.nnn.ed.nico/courses/1903/chapters/24094",
    "https://www.nnn.ed.nico/courses/1903/chapters/24095",
    "https://www.nnn.ed.nico/courses/1903/chapters/24096",
    "https://www.nnn.ed.nico/courses/1903/chapters/24097",
  ],
  "health": [
    "https://www.nnn.ed.nico/courses/1901/chapters/24080",
    "https://www.nnn.ed.nico/courses/1901/chapters/24081",
    "https://www.nnn.ed.nico/courses/1901/chapters/24082",
    "https://www.nnn.ed.nico/courses/1901/chapters/24083",
    "https://www.nnn.ed.nico/courses/1901/chapters/24084",
    "https://www.nnn.ed.nico/courses/1901/chapters/24085",
  ],
  "biology": [
    "https://www.nnn.ed.nico/courses/1889/chapters/24357",
    "https://www.nnn.ed.nico/courses/1889/chapters/24358",
    "https://www.nnn.ed.nico/courses/1889/chapters/24359",
    "https://www.nnn.ed.nico/courses/1889/chapters/24360",
    "https://www.nnn.ed.nico/courses/1889/chapters/24361",
    "https://www.nnn.ed.nico/courses/1889/chapters/24362",
  ],
  "English": [
    "https://www.nnn.ed.nico/courses/1911/chapters/24146",
    "https://www.nnn.ed.nico/courses/1911/chapters/24147",
    "https://www.nnn.ed.nico/courses/1911/chapters/24148",
    "https://www.nnn.ed.nico/courses/1911/chapters/24149",
    "https://www.nnn.ed.nico/courses/1911/chapters/24150",
    "https://www.nnn.ed.nico/courses/1911/chapters/24151",
  ],
  "Physical Education": [
    "https://www.nnn.ed.nico/courses/1897/chapters/24170",
    "https://www.nnn.ed.nico/courses/1897/chapters/24171",
    "https://www.nnn.ed.nico/courses/1897/chapters/24172",
  ],
  "Spacial Activity": [
    "https://www.nnn.ed.nico/courses/2025/chapters/25318",
    "https://www.nnn.ed.nico/courses/2024/chapters/25317"
  ]
}
const percentages = [];

const login_id = process.env.LOGIN_ID;
const password = process.env.PASSWORD;

app.message(/pro-rate (.+)/i, async({message, say}) => {
  const argument = message.text.match(/pro-rate (.+)/i)[0];
  console.log(chalk.green(argument));
  console.log(chalk.blue("First value of the retrieved category:", urls.argument[argument][0]));
  casper.start("https://www.nnn.ed.nico/oauth_login?next_url=https://www.nnn.ed.nico/home&target_type=n_high_school_mypage", function(){
    this.fillSelectors("form#oauth_identifier", { 
      'input[name="loginId"]': login_id,
      'input[name="password"]': password
    }, true);
  });
  casper.waitForUrl("https://www.nnn.ed.nico/home", function(){
    for(let i = 0; i <= urls[argument].length; i++){
      this.thenOpen(urls[argument][i], function() {
         const progressRate = document.querySelector("li.sc-1yme7mc-3.eZrrkf").slice(3, 6).value;
         console.log(chalk.blue("Progress Rate:", progressRate));
         if(progressRate === "100") {
          percentages.push(Number(progressRate));
         }
         percentages.push(Number(progressRate.slice(2, 3)));
      });
    }
  });
  
  casper.run();

  let sum = 0;

   percentages.forEach((value) => { sum += value });
   say(`Current progress rate: ${sum / urls[argument].length}%`);
});

app.start();

“dependencies” part in package.json:

  "dependencies": {
    "@slack/bolt": "^3.17.1",
    "@types/phantomjs": "^1.9.35",
    "casperjs": "^1.1.4",
    "chalk": "^5.3.0",
    "dotenv": "^16.4.5"
  },

I already tried:

  • Install casperjs with Typescript type difinition like “@types/casperjs”
  • import the casperjs with the code “import casperjs from “@types/casperjs”;”

Svelte list crossfade randomly misplaces elements

I have a list which I want to animate so that when an item is selected, it floats to top and the rest fly out. On reselecting the element it floats back to its place and others fly back in.

Using this crossfade demo I was able to produce a pretty solid version:

REPL

However, I noticed that the elements sometimes aren’t returned to their original position and only a subsequent re-animating might fix it. I am pretty sure this is because my crossfade function needs more sophisticated handling (or that I should use just regular transition instead?) but I am unsure how exactly.

<script>
  import { flip } from 'svelte/animate'
  import { writable } from 'svelte/store'
  import { crossfade, fly } from 'svelte/transition'

  const ACTIONS = [
    { key: 'blue' },
    { key: 'green' },
    { key: 'yellow' },
    { key: 'purple' },
    { key: 'orange' },
    { key: 'red' },
  ]
  const selectedAction = writable(null)
  let shownActions = ACTIONS.map(a => a)

  const [send, receive] = crossfade({
    fallback(node, _params) {
      return fly(node, { x: -800, duration: 600 })
    }
  })

  function selectAction(action) {
    if ($selectedAction === action) {
      shownActions = ACTIONS.map(a => a)
      selectedAction.update(v => {
        if (v === action || action === undefined) {
          return null
        } else {
          return action
        }
      })
    } else {
      shownActions = ACTIONS.filter(a => a.key === action)
      selectedAction.update(v => {
        if (v === action || action === undefined) {
          return null
        } else {
          return action
        }
      })
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      })
    }
  }
</script>

<ul>
{#each shownActions as action (action)}
  <li
    class={`${$$props.class || ''}`}
    animate:flip={{ duration: 600 }}
    in:receive={{ key: action.key }}
    out:send={{ key: action.key }}
  >
    <button on:click={e => selectAction(action.key)}>{action.key}</button>
  </li>
{/each}
</ul>

<style lang="scss">
    ul {
        list-style: none;
    }
    li {
        display: flex;
        margin-bottom: 1rem;
    }
    button {
        margin-right: 1rem;
        padding: 0.5rem 1rem;
    }
</style>

Not able to stop a long running task using promise.race and settimeout [duplicate]

in this code block my requirement is to execute a functionality such that the function test() should stop executing ( it was going through an infinite loop and crashing the page) if it takes more than than 1 min.

I used promise and timeout to solve this issue but here the problem i am facing is timeout function is being called even before executeWithRace was executed and it is not working as expected, How to refactor this code?

async function executeWithRace() {
    const response = await Promise.race([timeoutPromise, testPromise]);
    console.log(response)
}


    const timeoutPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve('Timed Out');
        }, 60000); // 1 minute timeout
    });
 



  
    const testPromise = new Promise((resolve, reject) => {
        
            test(); // Execute the original test function
            resolve("testSuccessfull"); // Resolve if test function completes without error
      
    });

Thanks

I also tried to create functions for both of the promises and passed those functions to promise.race() but here I have faced this situation : only the first mentioned function in promise.race() was being executed and both the functions weren’t being executed simultaneously.

—I wanted to know why this issue “only the first mentioned function in promise.race() was being executed and both the functions weren’t being executed simultaneously” when functions are passed to promise.race instead of promise objects, I noticed this by adding some debugging console logs.

Click comment button on Reddit

I want to add a comment to a Reddit post.

Without using Praw.

I have to click on “Add comment”, type text and press “Comment” button.

I am in the first step of “Add comment”.

Link: https://www.reddit.com/r/startups/comments/15er6kw/how_do_you_actually_come_up_with_realistic/

I’m testing it with the Chrome console in javascript. But once it works I will move it to python.

I have tried this code but without success.

console.log(document.querySelector('faceplate-tracker[noun="add_comment_placeholder"] button[data-testid="trigger-button"]'));
document.querySelector('faceplate-tracker[noun="add_comment_placeholder"] button[data-testid="trigger-button"]').click();
console.log(document.querySelector('faceplate-tracker[noun="add_comment_button"] button[data-testid="trigger-button"]'));
document.querySelector('faceplate-tracker[noun="add_comment_button"] button[data-testid="trigger-button"]').click();

What am I doing wrong?

I need to click on the button “Add comment” to be able to write text.

POST https://api.openai.com/v1/chat/completions 404 (Not Found)

I am trying to use open ai api for chatGPT integration website project
but i got those errors:

1-POST https://api.openai.com/v1/chat/completions 404 (Not Found)

2-Uncaught (in promise) D {message: ‘Request failed with status code 404’, name: ‘AxiosError’, code: ‘ERR_BAD_REQUEST’, config: {…}, request: XMLHttpRequest, …}code: “ERR_BAD_REQUEST”config: {transitional: {…}, adapter: Array(2), transformRequest: Array(1), transformResponse: Array(1), timeout: 0, …}message: “Request failed with status code 404″name: “AxiosError”request: XMLHttpRequest {onreadystatechange: null, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …}response: {data: {…}, status: 404, statusText: ”, headers: i, config: {…}, …}stack: “AxiosError: Request failed with status code 404n at https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js:1:21076n at XMLHttpRequest.d (https://cdnjs.cloudflare.com/ajax/libs/axios/1.2.3/axios.min.js:1:21221)”[[Prototype]]: Error
(anonymous) @ script.js:35

here is my post request

const response = await axios.post('https://api.openai.com/v1/chat/completions',{
        model: "text-davinci-003",
        messages: [
            {
                role: "user",
                content: message
            }
        ]
    },
    {
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer ${apiKey}`,
        },
      }

How to reuse layout.component.ts with routing in Angular?

my goal is to reuse accounts.layout.ts for 2 paths /v3/signin/identifier and /v3/signin/challenge/pwd.

The problem is <ng-content select="[right-content-action]" /> do not work well with <router-outlet/>

What I’ve tried:

  1. create a accounts.layout.ts

It works well if I use it in sign-in-identifier.page.html.

accounts.layout.ts 

<div class="overlay" [class.overlay-show]="showOverlay"></div>

<div class="main">
  <img class="logo" src="/assets/google-logo.svg" alt="google logo" />
  <div class="section">
    <div class="left-content">
      <span class="com-headline-5">{{ title }}</span>
      <span class="com-headline-6">{{ description }}</span>
    </div>
    <div class="right-content">
      <ng-content select="[right-content-input]" />

      <div class="actions">
        <ng-content select="[right-content-action]" />
      </div>
    </div>
  </div>
</div>

sign-in-identifier.page.html

<acc-accounts
  title="Sign In"
  description="Use your Google Account"
  [showOverlay]="isLoading"
>
  <com-input-text
    #inputEmail
    placeholder="Email"
    [(value)]="email"
    [errorMessage]="errorMessage"
    right-content-input
  />

  @if (isCreateAccountEnabled) {
    <com-button-basic (buttonClick)="onCreateAccount()" right-content-action
      >Create account</com-button-basic
    >
  }

  <com-button-flat
    (buttonClick)="onNext()"
    [disabled]="isLoading"
    right-content-action
    >Next</com-button-flat
  >
</acc-accounts>
  1. try to use it with <router-outlet /> in app.component.html

app.component.html

<acc-accounts>
  <router-outlet />
</acc-accounts>

Expected result:

enter image description here

Actual result:

enter image description here

Need help replicating image hover effect from xfiner.com/contact-us [closed]

https://www.xfiner.com/contact-us
This is a website, on its page ie contact page there is an image hover effect, I want to apply this effect in my project, but it is not working, I have given html and css code, only javascript code Writing can you help me to create this project in this image hover effect clip-path animation is var transform this is the website link.
https://www.xfiner.com/contact-us

<style>
      * {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
      }

      body {
        margin: 0;
        padding: 0;
        min-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
        font-family: "Inter", sans-serif;
        background-color: #0f0d11;
      }

      .image-container {
        max-width: 46%;
        aspect-ratio: 4 / 2.5;
        width: 100%;
        display: grid;
        grid-auto-columns: 1fr;
        min-height: 580px;
        position: relative;
        width: 60%;
        border-radius: 10px;
        min-height: 400px;
        overflow: hidden;
      }

      .double-image {
        grid-area: 1 / 1 / -1 / -1;
        background: url(1.jpg) no-repeat 50% 50%;
        background-size: cover;
        width: 100%;
        height: 100%;
        position: relative;
        transition: clip-path 0.5s ease-in-out;
      }

      .double-image:nth-child(1) {
        background-image: url(https://images.unsplash.com/photo-1438761681033-6461ffad8d80?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D);
        transform: translate(1%, -1%) scale(0.94, 0.94);
      }

      .double-image:nth-child(2) {
        background-image: url(https://images.unsplash.com/photo-1438761681033-6461ffad8d80?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D);
        transform: translate(-0.0191%, 0%) scale(0.97, 0.97);
        filter: saturate(400%) blur(5px);
        clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
      }

      .double-image:nth-child(3) {
        background-image: url(https://images.unsplash.com/photo-1438761681033-6461ffad8d80?q=80&w=2070&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D);
        clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
        transition-delay: 0.2s; /* Add a delay for the third image */
      }
    </style>
<div class="image-container">
      <div class="double-image"></div>
      <div class="double-image"></div>
      <div class="double-image"></div>
    </div>

I tried by myself, one is the clip-path effect is not working and the other is the shake effect.

And I want it to be the same effect that is on this website with javascript

This `dispatch()` is completely ignored. Why?

I created a reproduction for an issue with Svelte dispatch not being called:

Steps to reproduce

  1. Open the reproduction

  2. Open the browser console

  3. Go on the “About” page using the link

  4. No message in console. I sould see the message: “handleInput”

Relevant code

<script>
    import Select from 'svelte-select';
    import { createEventDispatcher } from 'svelte';

    export let value = undefined;
    export let id = undefined;
    
    const dispatch = createEventDispatcher();
    
    let result;

    let items = [
        { value: 'one', label: 'One' },
        { value: 'two', label: 'Two' },
        { value: 'three', label: 'Three' },
    ];

    $: if (id !== undefined) {
        result = id;
    }

    $: if (result != undefined) {
        value = { value: 'custom', label: 'Custom' };
        console.log("this should dispatch!")
        dispatch('input', value);
        console.log("is it dispatched?")
    }
</script>

<Select {value} {items} on:change on:input />

The dispatch('input', value) is completely ignored.

Why?

How to get someone’s Computer Username in JavaScript. Like the “whoami” Command in CMD

I’m trying to make a meta game and for one of the planned scenes I want the player’s name inside a book. The thing is… I’m using PenguinMod, a block programming language that has almost nothing to do with JavaScript. Except for an Extension that you can install with blocks that run diffrent JavaScript commands depending on what you put in them. Example Image.The Javascript Blocks in Question

So I tried looking up tutorials and found nothing. I even tried looking on here [Stack Overflow] and found nothing. I was expecting to find a command you could input that’ll grab the Name you use on your computer but it just doesn’t seem like that exists. The only thing I could get from what I lookuped was how to get a Users IP Adress. So now my only hope is that you can help out in some way. Thank you.

I need a JavaScript regular expression that matches a domain which contains 2 or more characters

I need a simple JavaScript regular expression to match URLs in a string. This is what I have at the moment:

/(https?://)?[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9].[^s]{2,}/gi

This works 99% of the time for any URL that contains 3 or more characters, for example all of these work:

  • abc.com

  • abcd.com

but I can’t get it to work for a URL with 2 characters:

  • ab.com

  • ow.ly

I’m using the match method like this:

let regex = /(https?://)?[a-zA-Z0-9][a-zA-Z0-9-]+[a-zA-Z0-9].[^s]{2,}/gi

let matches = "http://ab.com".match(regex)

disabled leave types of a newly permanent

What way or method can be used to disable the leave type in the options?
Because in the console, it says that the leave type is already disabled, but it’s still visible in the options and can be clicked or selected. How can this be blocked?

here is the screenshot of the console saying it is disabling the leave type

enter image description here

this is the screenshot of the option but it still visible to pick enter image description here

this is the code i tried using to disable the leave type option

if (employeeInfo.permanent_status == 1 && today >  allowedLeaveStartDate) {
                    var disabledValues = ['1', '5']; // Values to be disabled

                    console.log('Disabling leave types:', disabledValues);
                    $("#leaveTypeDropdown option").filter(function() {
                        return disabledValues.includes($(this).val());
                    }).prop('disabled', true);
                }

i expect it will be blocked or disable the leave type, i don’t know what is wrong, please help.

this is the whole code i’m using, the permanent status 0 is for new employee and the permanent status 1 is for regular employee

 <script>

$(document).ready(function () {
var originalLeaveTypes = {!! json_encode($leaveTypeList) !!};

function updateLeaveTypes(selectedEmployeeId) {
    $('#leaveTypeDropdown').empty();

    // Add a placeholder option
    $('#leaveTypeDropdown').append('<option value="">----Please select----</option>');

    if (!selectedEmployeeId) {
        $.each(originalLeaveTypes, function (index, leaveType) {
            $('#leaveTypeDropdown').append('<option value="' + index + '">' + leaveType + '</option>');
        });
        return;
    }

    // Continue with the existing logic for updating leave types
    $.ajax({
        url: '/getEmployeeInfo/' + selectedEmployeeId ,
        type: 'GET',
        success: function (employeeInfo) {
            var excludedLeaveTypeIds = [];
            var allowedLeaveStartDate = '{{ $allowedLeaveStartDate }}';
            var today = '{{ CarbonCarbon::now() ->toDateString() }}';

    console.log('Allowed Leave Start Date:', allowedLeaveStartDate);
    console.log('Today:', today);


            // Additional condition for excluding leave types based on nationality, department ID, and permanent_status
             if (employeeInfo.permanent_status == 0 ) {
                excludedLeaveTypeIds = [1, 2, 3, 4, 5, 6, 7, 9, 10, 11, 12, 13]; // Hide all leave types except 8

            } else if (
                employeeInfo.nationality == 1 &&
                (employeeInfo.department_id == 29 || employeeInfo.department_id == 32 || employeeInfo.department_id == 33 || employeeInfo.department_id == 34 || employeeInfo.department_id == 36 || employeeInfo.department_id == 37 || employeeInfo.department_id == 38 || employeeInfo.department_id == 39 || employeeInfo.department_id == 62 || employeeInfo.department_id == 63 || employeeInfo.department_id == 64 || employeeInfo.department_id == 68 || employeeInfo.department_id == 69 || employeeInfo.department_id == 71 || employeeInfo.department_id == 72)
            ) {
                excludedLeaveTypeIds = [6, 4, 2, 12, 13];
            } else if (
                employeeInfo.nationality == 1 &&
                !(employeeInfo.department_id == 29 || employeeInfo.department_id == 32 || employeeInfo.department_id == 33 || employeeInfo.department_id == 34 || employeeInfo.department_id == 36 || employeeInfo.department_id == 37 || employeeInfo.department_id == 38 || employeeInfo.department_id == 39 || employeeInfo.department_id == 62 || employeeInfo.department_id == 63 || employeeInfo.department_id == 64 || employeeInfo.department_id == 68 || employeeInfo.department_id == 69 || employeeInfo.department_id == 71 || employeeInfo.department_id == 72)
            ) {
                excludedLeaveTypeIds = [6, 4, 2, 12, 13];
            } else if (employeeInfo.nationality >= 2 && employeeInfo.nationality <= 5) {
                excludedLeaveTypeIds = [3, 1, 5, 12, 13];
            } else if (employeeInfo.nationality >= 6 && employeeInfo.nationality <= 10) {
                excludedLeaveTypeIds = [3, 1, 5, 6, 2];
            }
            
            if (employeeInfo.permanent_status == 1 && today >  allowedLeaveStartDate) {
                var disabledValues = ['1', '5']; // Values to be disabled

                console.log('Disabling leave types:', disabledValues);
                $("#leaveTypeDropdown option").filter(function() {
                    return disabledValues.includes($(this).val());
                }).prop('disabled', true);
            }

            // Filter and append leave types based on the exclusion list
            $.each(originalLeaveTypes, function (index, leaveType) {
                var leaveTypeId = parseInt(index);
                if (excludedLeaveTypeIds.indexOf(leaveTypeId) === -1 ) {
                    $('#leaveTypeDropdown').append('<option value="' + leaveTypeId + '">' + leaveType + '</option>');
                }
            }); 
        },
        error: function () {
            console.log('Error fetching employee information.');
        }
    });
}

$('#employeeDropdown').change(function () {
    updateLeaveTypes($(this).val());
});

// Trigger the change event initially to set the initial leave type options
$('#employeeDropdown').trigger('change');

});

</script>

what is the better approach here for scaling sse with nodejs using redis pub/sub?

I’m using server sent events to send real time updates to clients. I’ve thought about 2 ways on how I can implement this

  1. subscribe to a redis channel and use nodejs event emitter. Whenever there is a new message received from channel, use event emitter listener to write message to response stream. The problem I have with this is that the event emitter is synchronous and will block the event loop if there are a larger number of connections.

  2. whenever a new request is made to subscribe to events, I create a new redis client and subscribe the client to channel. So this approach leads to N number of redisClients where N = number of users connected to server. Now, I’m aware I’m limited by the max limit of connections on redis server. Not a great way but if this is the way to go, I’ll use redis clusters.

Which approach would be better here when scaling the app?

I’ve added some code I wrote for both the approaches

  1. using event emitter
const emitter = new EventEmitter();

redisClient.subscribe(CHANNEL_NAME, (msg, channel) => {
  emitter.emit("event",msg);
});


function subscribe(req: Request, res: Response) {
    const handleEvent = (msg: string) => {
      res.write(formatSseData("message", msg));
    };

    emitter.addListener("event", handleEvent);

    req.on("close", () => {
      emitter.removeListener("event", handleEvent);
    });
  }
  1. Setting up new redis client for every new user connected
async function subscribe(req: Request, res: Response) {
    try {
      const redisClient = createClient({ url: "redis://localhost:6379" });

      await redisClient.connect();

      redisClient.subscribe(CHANNEL_NAME, (msg, channel) => {
        res.write(formatSseData("message", msg));
      });

      req.on("close", () => {
        redisClient
          .unsubscribe(CHANNEL_NAME)
          .catch(err => {
            console.log("error while unsubscribing", err);
          });
      });
    } catch (error) {
      console.error("Failed to connect: %s", (error as Error).message);
    }
  }