Inherit Permissions of a category when creating a channel in discord.js v14

I’m trying to create a channel that gives certain roles access and blocks out @everyone by default, but I also want it to work with categories, such as allowing other roles

let specificOverwrites = [
                ...members,
                {
                    id: creatorRoleId,
                    allow: [PermissionFlagsBits.ViewChannel]
                },
                {
                    id: interaction.guild.roles.everyone.id,
                    deny: [PermissionFlagsBits.ViewChannel]
                }
            ];

            // Use specificOverwrites during channel creation
            const channel = await interaction.guild.channels.create({
                name: allianceNameInput,
                type: ChannelType.GuildText,
                parent: alliancesCategory.id,
                permissionOverwrites: specificOverwrites
            });

The above is the code that I currently have which works, but it simply ignores category permissions. How can I make it work with category permissions?

We i cant copy? [closed]

I cant copy a code. Idk wahts the problem lmao. The problem is on the end but idk what.

I tried every end code didnt work.
I guess ye.

input.addEventListener("keyup", function() {
  h1.innerText = input.value.replace(/[a]/gi, "b");
var input = document.querySelector("input");
var h1 = document.querySelector("h1");

input.addEventListener("keyup", function() {
  h1.innerText = input.value.replace(/[a]/gi, "b");
});
<input type="text">
<h1></h1>

Implementing Error from Back End to Front End

I creating a MERN stack application, on the back end I have errorHandling, and create a backend code for register user. All goes well, however some Custom Error Handling dint display if I made some test. If user already existed in the database it display the Error: Request failed with status code 500 which it should be the throw new Error(‘User already exists’); from the back end error. Or any suggestion on this thank you so much

Below is the code for BACKEND

const registerUser = async (req, res, next) => {
  try {
    const { name, email, password } = req.body;

    // Check if user already exists or not
    let user = await User.findOne({ email });
    if (user) {
      throw new Error('User already exists');
    }
    // Creating a new user
    user = await User.create({ name, email, password });
    return res.status(201).json({
      _id: user._id,
      avatar: user.avatar,
      name: user.name,
      email: user.email,
      verified: user.verified,
      admin: user.admin,
      token: await user.getJWTToken(),
    });
  } catch (error) {
    next(error);
  }
};

And the FRONT END CODE

import axios from "axios";

export const signup = async ({ name, email, password }) => {
   try {
      const { data } = await axios.post("/api/users/register", {
         name,
         email,
         password,
      });
      return data;
   } catch (error) {
      if (error.response && error.response.data.message)
         throw new Error(error.response.data.message);
      throw new Error(error.message);
   }
};
import React from 'react';
import MainLayout from '../../components/MainLayout';
import { Link } from 'react-router-dom';
import { useForm } from 'react-hook-form';
import { useMutation } from '@tanstack/react-query';
import { signup } from '../../services/index/users';
import toast from 'react-hot-toast';
import './register.css';

const Register = () => {
  //creating a mutation for registering a users
  const { mutate, isLoading } = useMutation({
    mutationFn: ({ name, email, password }) => {
      return signup({ name, email, password });
    },

    //after getting the data from the mutation this function run
    onSuccess: (data) => {
      console.log(data);
    },
    onError: (error) => {
      toast.error(error.message);
      console.log(error);
    },
  });
  const {
    register,
    handleSubmit,
    formState: { errors, isValid },
    watch,
  } = useForm({
    defaultValues: {
      name: '',
      email: '',
      password: '',
      confirmPassword: '',
    },
    mode: 'onChange',
  });

  //getting the data from the form
  const submitHandler = (data) => {
    const { name, email, password } = data;
    mutate({
      name,
      email,
      password,
    });
  };

  //monitor the input from the password input
  const password = watch('password');

  return ( from here the code for the form );
};

export default Register;

How do I style exported and slotted parts in svelte?

Does Svelte slots function like vanilla-js/dom in any way (I can’t seem to get it to work).

In html/js I can do:

<style>
    body {color: red;}
    /* style exposed part from outside */
    my-element::part(header) {color: green;}
</style>

<h1>Hello World</h1>   

<my-element>
    <div slot="header"><strong>Header</strong></div>
    <div slot="body">Body</div>
</my-element>

<script>
    customElements.define('my-element', class extends HTMLElement {
        constructor() {
            super();
            const shadowRoot = this.attachShadow({mode: 'open'});
            shadowRoot.innerHTML = `
                <style>
                    .container { 
                        border: solid 1px blue;
                        padding: 5px;
                        position: relative;

                        &:after {
                            content: "my-element";
                            display: block;
                            position: absolute;
                            bottom: -.5em;
                            right: 5px;
                            border: inherit;
                            background-color: white;
                            padding: inherit;
                        }
                    }
                    /* style inserted/slotted part from inside */
                    [part="body"] ::slotted(div) { background-color: lightyellow; }
                </style>
                <div class="container">
                    <header part="header"><slot name="header"></slot></header>
                    <hr>
                    <div part="body"><slot name="body"></slot></div>
                </div>
            `;
        }
    });
</script>

Where the h1 will be red from the global style, the element marked with part="header" is styled from the outside to be green, and the content slotted into slot="body" is styled from the inside (of the shadow dom) to have a lightyellow background.

I can’t figure out how to do any of this (controlled) cross-boundary styling in svelte? (e.g. when using AppShell::part(content) I get an error:

[plugin:vite-plugin-svelte] C:/srv/svelte/yoda5/src/routes/+layout.svelte:23:18 Expected a valid CSS identifier

C:/srv/svelte/yoda5/src/routes/+layout.svelte:23:18

21 |  
22 |  <style>
23 |      AppShell::part(content) {
   |                    ^

I can’t seem to start a second animation after stopping the first one on javascript

Currently I’m trying to start a second animation after stopping the first one. The first animation did manage to stop but the second animation won’t manage to start. I don’t know what is going wrong with my codes and I don’t know how to test to see which part is going wrong.

function flyRocket() {
    let animatedElement = document.querySelector('.rocket');
    animatedElement.style.animation = 'none';
    moveRocket();
}

function moveRocket() {
    let movingElement = document.querySelector('.rocket');
    movingElement.classList.add('move-up-animation');
}
    
#Rocket {
  height: 100px;
  width: 50px;
}

.rocket {
  position: relative;
  animation: animate 0.5s ease infinite;
}

@keyframes animate {
  0%, 100% {
    transform: translateY(-4px);
  }
  50% {
    transform: translateY(4px);
  }
}

.rocket::before {
    content: '';
    position: absolute;
    bottom: -40px;
    left: 50%;
    transform: translateX(-50%);
    width: 10px;
    height: 50px;
    background: linear-gradient(#00d0ff, transparent);
}

.rocket::after {
    content: '';
    position: absolute;
    top: 5;
    left: 50%;
    transform: translateX(-50%);    
    width: 10px;
    height: 50px;
    background: linear-gradient(#00d0ff, transparent);
    filter: blur(20px);
}

.move-up-animation {
    animation: moveUpAnimation 2s ease forwards;
}

@keyframes moveUpAnimation {
  0% {
    transform: translateY(0);
  }
  100% {
    transform: translateY(-50px);
  }
}   
<div class='scene'>
    <div class='rocket'>
        <img id='Rocket' src='rocket.png'>
    </div>
</div>

Any help is appreciated.

Vuejs: Exclude last played sound from array of sounds

I’m trying to randomize the sounds that I play when clicking on a button, but I also wanted to skip the last played sound. For example, if Sfx4 will be played four times in a row it won’t sound natural. I want to always play a new sound (within these 5 sounds of course). What I’m doing wrong? Give me some ideas on how to implement it if possible.

<template>
    <button class="book__nav-btn" @click="playTurnSfx">
        <slot> </slot>
    </button>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import Sfx1 from '@/assets/sounds/page-turn-1.mp3?url';
import Sfx2 from '@/assets/sounds/page-turn-2.mp3?url';
import Sfx3 from '@/assets/sounds/page-turn-3.mp3?url';
import Sfx4 from '@/assets/sounds/page-turn-4.mp3?url';
import Sfx5 from '@/assets/sounds/page-turn-5.mp3?url';

const sounds = [Sfx1, Sfx2, Sfx3, Sfx4, Sfx5];
const lastPlayedIndex = ref(null);
let playableSounds = sounds.toSpliced(lastPlayedIndex.value, 1);
const randomIndex = computed(() => {
    return Math.floor(Math.random() * playableSounds.length);
});

const playTurnSfx = () => {
    const sound = new Audio(sounds[randomIndex.value]);
    sound.volume = 0.1;
    sound.play();
};
</script>

Create a bidding history component

I want to create a history component, which will be like this

There are two players in the game. If the player makes a bid, it will be added to the bids array.

  const bids = [
    { player: 1, bidType: 'level', level: '1', suit: 'NT' },
    { player: 0, bidType: 'level', level: '2', suit: 'NT' },
    { player: 1, bidType: 'level', level: '3', suit: 'S' },
    { player: 0, bidType: 'double' },
    { player: 1, bidType: 'pass' },
    { player: 0, bidType: 'pass' },
    { player: 1, bidType: 'double' },
    { player: 0, bidType: 'pass' },
    { player: 1, bidType: 'double' },
  ];

Based on this bids array I want to create a history component. The game can be played on browser –

The dealer is 0, so in Player 0’s screen – the bid History should be like this,

player0′ screen

in player1’s screen, the bid history should be like this,

Player1’s screen

How to implement this logic in svelte. I already made a component,
this is the link for that – you can run it and see the output.

https://codesandbox.io/p/sandbox/falling-glitter-t3yyy9?file=%2FButton.svelte%3A21%2C19

Reposition class element

I have an eye icon and when you click on it the icon changes and it repositions via js: left: 10%;.

However, if there is an element in the DOM with the ID login-section, it should be repositioned to left: 50%;.

I tried document.getElementsByClassName('fa-eye-slash').style.left = '50%'; but that doesn’t work.

let eye = document.querySelectorAll('.eye');
eye.forEach(function (v) {
    v.addEventListener('click', function () {
        this.classList.toggle('fa-eye-slash');
    

        if(document.getElementById('login-section')) {
            // Following line is not working:
            document.getElementsByClassName('fa-eye-slash').style.left = '50%';
        }
       

    })
});
.eye {
    position: absolute;
}
.fa-eye-slash {
    left: 10%;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css">

<div id='login-section'>
    <i class="fa-solid fa-eye eye"></i>
</div>

What is the best way to manage a number of state of child components in parent component?

I want to manage a number of child components in parent component.

However, when one of child component trigger onCheck event, all child components were re-rendered. (because handleToggleCheck function was changed.)

const Parent = (props) => {
    const {codes} = props // codes is list length 1000

    const [checkedCodes, setCheckedCodes] = useState<Set<string>>(new Set())

    const handleToggleCheck = (code) => {
        if (!checkedCodes.has(code)) checkedCodes.add(code)
        else checkedCodes.delete(code)

        setCheckedCodes(new Set(checkedCodes))
    }

    return (
        codes.map(code => (
            <Child key={code} checked={checkedCodes.has(code)} onCheck={handleToggleCheck} code={code} />
        ))
    }
}

const Child = (props) => {
    const {checked, code, onCheck} = props

    return (
        <input type=“checkbox” checked={checked} onChange={() => onCheck(code)} />
    )
}

I tried to wrap handleToggleCheck function using useCallback, but It doesn’t work because checkedCodes re-maked when called handleToggleCheck.

const handleToggleCheck = useCallback((code) => {
    //…
}, [checkedCodes])

And I tried also use useRef instead of useState, but it doesn’t re-render child component when checkedCodes changed.

//…
const checkedCodes = useRef(new Set())
//…

return (
    codes.map(code => (
        <Child … checked={checkedCodes.current.has(code)} … />
    ))
)

What is the best way?

Highcharts fix plotlines threshold show very near at bottom of the container

I’m using react with chart type is stockChart, 2 series line and area.
The threshold line (yellow line) show very near at bottom of the container.
How can I config in any case threshold line will not show very near at top and bottom of chart container ?

Tks for your help.
img

plotOptions: {
column: {
    maxPointWidth: 2
},
series: {
    fillOpacity: 0.1,
        marker: {
        enabled: false,
            states: {
            hover: {
                enabled: false
            }
        }
    },
    shadow: false,
        dataGrouping: {
        enabled: false
    },
    stacking: 'normal',
        negativeColor: '#ea3943',
            lineWidth: 1,
                states: {
        hover: {
            lineWidth: 1
        },
        inactive: {
            opacity: 1
        }
    },
    pointPadding: 0,
        groupPadding: 0.1
},
area: {
    fillOpacity: 0.6
}

}

Node.js : SyntaxError: Cannot use import statement outside a module [closed]

im trying to code a basic api with some functions but I ran into a problem when trying to import my controller function into my main app.js in node.js. Below are pictures of my project.
(https://i.stack.imgur.com/EPS7y.png)[main server.js file] (https://i.stack.imgur.com/BqEiU.png)[package.json file] (https://i.stack.imgur.com/q6AYl.png)[controller funcs] (https://i.stack.imgur.com/FBibq.png) [Error code]

Ive tried typing type: modules in my json file. Also converting my controller file in common js which then gace me a different error code that told me to not use the ‘require’ syntax but the import syntax which then brought me to the same error. Im trying to finish this project but can’t seem to continue with this error any help would be appreciated!

Chart.JS Bar Graph: How to keep bar appearance consistent with combination of hourly and daily points

I have a dataset that contains daily data points for the last year along with hourly data points for the last 24h. Without the hourly data points, the graph looks perfect but when adding the hourly points, the bars are too thin and far from each other due to the missing hourly data points for previous days. I believe Chart.js is keeping space in-between the daily points as it’s expecting hourly data points. I don’t have the data for the hourly points for the last year, and I also only need them for the last 24h anyways. I tried increasing the categoryPercentage, barPercentage, and barThickness but it still wasn’t as good as before adding the hourly points.

Here’s what it looks like without changing the mentioned variables: https://i.imgur.com/Zjwz7mi.png

Here’s the original graph without the hourly points: https://i.imgur.com/O1GmP5v.png

Do you have any suggestions? Thanks.

My dataset code:

{
        label: 'Vol',
        data: graphData['res'].map((it) => it.val),
        backgroundColor: 'orange',
        borderWidth: 1,
        yAxisID: 'volume',
        type: 'bar', 
        order: 2, 
      },

JavaScript click event not working on img when creating dynamically

I am trying to create a column dynamically in a table which I am able to do.
I have an click event on an img tag inside a td tag I am creating dynamically.

I have tried with addEventListenerand and .onclick.
I feel it could be because of the outerHTML I am using but not sure what else to use to solve this.

Below is the code:
https://jsfiddle.net/sev6wmkL/1/

I am trying to make the click event work and fire the “onMouseOver” method and print the log statement. i.e. below method:

function onMouseOver(e){
console.log('++++++++++');
} 

Error Loading Image: possibly due to crossOrigin = ‘anonymous’ set within html2canvas?

I’m using html2canvas to render HTML as an image.

I’m running into issues when the element I need to convert contains an img whose source is an external domain.

I think the issue could be that the library internally sets crossOrigin = 'anonymous' on cloned img elements.

Below is a summary of how I’ve managed to avoid CORS-related issues when rendering the img elements by converting them to base64 server-side, what I think could be the current roadblock, and questions regarding next steps.

This is part of a React/Next project.


Avoiding CORS issues by loading the images server-side:

To avoid CORS issues, I’m using a proxy server to handle fetching the image and converting it to a base64 value that can be used as the img source.

An example of this can be found in the associated library html2canvas-proxy-nodejs. The code for this library is fairly simple, and included below to give you an idea of what html2canvas expects the proxy to do:

const express = require('express');
const url = require('url');
const cors = require('cors');
const request = require('request');

function validUrl(req, res, next) {
    if (!req.query.url) {
        next(new Error('No url specified'));
    } else if (typeof req.query.url !== 'string' || url.parse(req.query.url).host === null) {
        next(new Error(`Invalid url specified: ${req.query.url}`));
    } else {
        next();
    }
}

module.exports = () => {
    const app = express.Router();
    app.get('/', cors(), validUrl, (req, res, next) => {
        switch (req.query.responseType) {
    case 'blob':
        req.pipe(request(req.query.url).on('error', next)).pipe(res);
        break;
    case 'text':
    default:
        request({url: req.query.url, encoding: 'binary'}, (error, response, body) => {
            if (error) {
                return next(error);
            }
            res.send(
            `data:${response.headers['content-type']};base64,${Buffer.from(
                body,
                'binary'
            ).toString('base64')}`
        );
    });
    }
});

    return app;
};

I originally tried using html2canvas-proxy-nodejs, but it constantly resulted in CORS issues even though it’s supposed to resolve them. Instead, I wrote my own server-side implementation that accepts a URL, converts it to a base64 string, and returns the value as follows:

res.status(200).json(`data:image/png;base64,${response}`)

I’ve tested my server-side proxy and confirmed that the response is able to be used in an img element without any issues:

const response = await fetch(proxyRoute)
const src = await response.json()
return <img src = {src} />

Using the server-side proxy with the library:

I can’t get the proxy to work correctly with html2canvas.

Below is an example of how I’m attempting to do this. The ref represents the element I’m attempting to convert to an image, and it contains at least one img element within it:

// Other options being set are width, height, and backgroundColor. Excluded here.
const options = { proxy: proxyRoute, ... }
const canvas = await html2canvas(ref?.current, options)
const src = canvas.toDataURL('image/png', 1.0)

When I attempt the above, the element is rendered without any issue except for the fact that space occupied by the img element within the overall element is left blank. The following error appears in the console:

550ms Error loading image https://link.toExternalDomain.jpeg

There’s no other information.

If I look in Chrome’s Network tab after attempting to render the HTML as an image, I can see various assets that html2canvas as the Initiator attempted to load. The content of the img element is there with a 200 status, and I can view the image in the Network Preview tab. Just to note, the Network tab lists the Type of that image as webp, but it doesn’t make a difference whether or not I change image/png above to image/webp.


crossOrigin = ‘anonymous’, the potential problem:

I looked through the library’s source code to try to find how and when it’s using the proxy, and found that it’s used here:

    private async loadImage(key: string) {

    const isSameOrigin = CacheStorage.isSameOrigin(key);
    const useCORS =
        !isInlineImage(key) && this._options.useCORS === true && FEATURES.SUPPORT_CORS_IMAGES && !isSameOrigin;
    const useProxy =
        !isInlineImage(key) &&
        !isSameOrigin &&
        !isBlobImage(key) &&
        typeof this._options.proxy === 'string' &&
        FEATURES.SUPPORT_CORS_XHR &&
        !useCORS;
    if (
        !isSameOrigin &&
        this._options.allowTaint === false &&
        !isInlineImage(key) &&
        !isBlobImage(key) &&
        !useProxy &&
        !useCORS
    ) {
        return;
    }

    // Here's where my proxy is being called. I'm not passing the useCORS prop.
    let src = key;
    if (useProxy) {
        src = await this.proxy(src);
    }

    this.context.logger.debug(`Added image ${key.substring(0, 256)}`);

    return await new Promise((resolve, reject) => {
        const img = new Image();
        img.onload = () => resolve(img);
        img.onerror = reject;
        //ios safari 10.3 taints canvas with data urls unless crossOrigin is set to anonymous
        if (isInlineBase64Image(src) || useCORS) {
            img.crossOrigin = 'anonymous';
        }
        img.src = src;
        if (img.complete === true) {
            // Inline XML images may fail to parse, throwing an Error later on
            setTimeout(() => resolve(img), 500);
        }
        if (this._options.imageTimeout > 0) {
            setTimeout(
                () => reject(`Timed out (${this._options.imageTimeout}ms) loading image`),
                this._options.imageTimeout
            );
        }
    });
}

The only thing I can imagine might be causing the issue is this portion:

//ios safari 10.3 taints canvas with data urls unless crossOrigin is set to anonymous
if (isInlineBase64Image(src) || useCORS) {
    img.crossOrigin = 'anonymous';
}

I’m not passing useCORS, but isInlineBase64Image(src) will be true:

const INLINE_BASE64 = /^data:image/.*;base64,/i;
const isInlineBase64Image = (src: string): boolean => INLINE_BASE64.test(src);

In an attempt to confirm this, I manually added crossOrigin = 'anonymous' to the img elements in my project, and they wouldn’t load correctly.

The error message in the console was the exact same error message I saw when passing the useCORS prop to html2canvas:

Access to fetch at ‘link.toExternalDomain.jpeg’ from origin ‘localhost:8080’
has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’
header is present on the requested resource. If an opaque response
serves your needs, set the request’s mode to ‘no-cors’ to fetch the
resource with CORS disabled.

The FetchEvent for “link.toExternalDomain.jpeg” resulted in a network error
response: the promise was rejected.

For reference, here’s the description of the useCORS prop:

useCORS: Whether to attempt to load images from a server using CORS


Conclusion:

Am I correct that the reason for the error message is that the library is setting crossOrigin = 'anonymous'?

Here’s the fairly unhelpful error message again, for reference:

550ms Error loading image https://link.toExternalDomain.jpeg

If I’m correct, how can I get around this? If that line really is the issue, one “solution” is to fork the library and comment that out, but assuming the author is correct that Safari taints the canvas otherwise, it seems like it would just create another issue further downstream.

If I’m not correct, what actually is the problem?

I attempted using other libraries such as html-to-image and modern-screenshot. Neither of these libraries worked as well as html2canvas in general. Most importantly, they both had similar CORS issues and provided no methods similar to the proxy prop of html2canvas to resolve the issues.