Discord automated message from console

Can someone pls help me create some code to put in my console that will auto type “owo pray” into a discord text bar and send it once every 5 minutes? Note the span they use to contain the input only appears after it detect a key down and there’s no send button, u have to hit enter to send the message

Tried making innerTEXT = “owo pray” but when hit enter the text just dissapears, I think because the text isn’t in the right span

`get` syntax not working with class object destructuring [duplicate]

Suppose we have the following class:

class Car {
    private _id!: string;
    private _brand!: string;

    constructor(id: string, brand: string) {
        this.id = id;
        this.brand = brand;
    }

    get id() {
        console.log('getting id...');
        return this._id;
    }
    set id(value) {
        this._id = value;
    }

    get brand() {
        console.log('getting brand...');
        return this._brand;
    }
    set brand(value) {
        this._brand = value;
    }
}

And that we create the following class instance

let car1 = new Car('123', 'Ford');

When accessing the properties of car1 directly everything works perfectly (‘getting id…’ is printed, which means the get method is called as expected):

console.log(car1.id);
// getting id...
// 123

But when using object destructuring, this does not work:

const { id } = car1;
// in this case "getting id..." does NOT get printed,
// which means the get method is not being called :(
console.log(id);
// undefined

And when I print the object, the properties defined through get syntax also do not appear (and once again, the get method does not get called):

console.log(car1);
// { _id: '123', _brand: 'Ford' }
// note that nor "getting id..." nor "getting brand..." get printed :(
// so none of the get methods are being called

How can I make the get syntax work with object destructuring? (i.e., how can I use the get syntax (or a similar alternative) to store the properties in the instance itself and not in its prototype while mantaining the code clean?)

I have read about Object.defineProperty, but I find it very cumbersome to use it in every class I want to define. Are there any other alternatives or ways to achieve this? Thank you in advance!

NextJS 13 revalidatePath() working for created comments but not for created posts

I’m having trouble figuring out why revalidatePath() works in my CommentForm component but not in my PostForm component. I have made both components very similar in structure: createComment() will create a comment for a post or photo, while createPost() will create a post. Both functions activate when a form is submitted and both components are server components. I just do not understand why only one will use revalidatePath() correctly when they are practically the same.

CommentForm:

import { revalidatePath } from "next/cache";
import prisma from "../../../prisma/lib/prisma";

import { getServerSession } from "next-auth/next";
import { authOptions } from "../../api/auth/[...nextauth]/route";

// Components
import Button from '../Button';

interface CommentFormProps {
  type: string;
  id: number;
}

const CommentForm: React.FC<CommentFormProps> = async ({ type, id }) => {
  const session = await getServerSession(authOptions);

  const createComment = async (formData: FormData) => {
    "use server"

    const content = formData.get("content") as string;
    const username = session!.user.username!;
  
    switch(type) {
      case "Photo": {
        try {
          const foundPhoto = await prisma.photo.findFirst({
            where: {
              id: id
            },
            select: {
              id: true
            }
          });

          if(foundPhoto) {
            await prisma.comment.create({
              data: {
                content: content,
                authorUsername: username,
                photoId: foundPhoto.id
              }
            });
          } else {
            console.log('Photo not found');
          }
        } catch (e) {
          console.log('Failed to fetch photo: ', e);
        }
        break;
      }
      case "Post": {
        try {
          const foundPost = await prisma.post.findFirst({
            where: {
              id: id
            },
            select: {
              id: true
            }
          });

          if(foundPost) {
            await prisma.comment.create({
              data: {
                content: content,
                authorUsername: username,
                postId: foundPost.id
              }
            });
          } else {
            console.log('Post not found');
          }
        } catch (e) {
          console.log('Failed to fetch post: ', e);
        }
        break;
      }
    }
    revalidatePath('/');
  }

  return (
    <form action={createComment} className="flex flex-col text-center w-3/4 sm:w-1/2 m-auto mt-4">
      <label htmlFor="content" className="mb-3">
        New Comment<br />
        <textarea id="content" name="content" className="border border-gray-800 rounded-lg w-full text-black" rows={4} required />
      </label>
      <Button label="Add Comment" isDisabled={false} />
    </form>
  )
}

export default CommentForm;

PostForm:

import { revalidatePath } from "next/cache";
import prisma from "../../../prisma/lib/prisma";

import { getServerSession } from "next-auth/next";
import { authOptions } from "../../api/auth/[...nextauth]/route";

// Components
import Button from '../Button';

const PostForm = async () => {
  const session = await getServerSession(authOptions);

  const createPost = async (formData: FormData) => {
    "use server"

    const content = formData.get("content") as string;

    try {
      await prisma.post.create({
        data: {
          content: content,
          author: {
            connect: {
              username: session?.user.username
            }
          }
        }
      });
      revalidatePath('/');
    } catch (e) {
      console.log('Failed to create post: ', e);
    }
  };

  return (
    <div className='flex flex-col items-center gap-4'>
      <form className="flex flex-col text-center w-3/4 sm:w-1/2 m-auto" action={createPost}>
        <label htmlFor="content" className="mb-3">
          New Post<br />
          <textarea 
            id="content" 
            name="content" 
            className="border border-gray-800 rounded-lg w-full text-black" 
            rows={4} 
            maxLength={750} 
            required 
          />
        </label>
        <Button label="Add Post" isDisabled={false} />
      </form>
    </div>
  )
}

export default PostForm;

how to have next/save button inside a tab to proceed with next tab

Im new/noob to coding, I would just like to ask how can you make a tab proceed on the next tab once the user click next/save? and would it be possible to change the color of the finished tab? for ex. all the finished tab will be green while the current/unfinished will be yellow and the unopened is gray. please help, i cant not get pass this task huhu thank you so much in advance

<script>
function openCity(evt, cityName) {
  var i, tabcontent, tablinks;
  tabcontent = document.getElementsByClassName("tabcontent");
  for (i = 0; i < tabcontent.length; i++) {
    tabcontent[i].style.display = "none";
  }
  tablinks = document.getElementsByClassName("tablinks");
  for (i = 0; i < tablinks.length; i++) {
    tablinks[i].className = tablinks[i].className.replace(" active", "");
  }
  document.getElementById(cityName).style.display = "block";
  evt.currentTarget.className += " active";
}

// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>

Security Implications of editable URLs on fetch requests

In my web app (js), I allow users to self host their own backend, and plug in their own api url to the client which will change subsequent network requests.

Ultimately wondering what the security implications are of allowing the user to override the url for all network request — are xss/csrf concerns valid?. I’m aware that a browser extension could replicate this pretty easily, so assume it’s safe.

Redirect Why doesn’t clicking on log in send me to the AdminView or the UserView?

Repositorio git: https://github.com/Mejia2002/Proyecto_Wed_Segundo_Corte
The login is in the screens folder, where could the problem be?

I want when I click on the log in button to be redirected to the AdminView or the UserView depending on the Role, I am using React + firebase, I have not been able to identify where the problem is, if it is in the navigation or in the authentication.

syncing new sheets and a hyperlink

I am trying to learn java script for google apps script to have a spreadsheet I can use for theater costume plots. Basically, I want the spreadsheet to generate sheets for different sorts, (by scene, by character, by actor, etc.) but then keep them updated with edits to the parent. I have an on Edit script to make a new sheet when an actor’s name is entered, but I can’t get it to include a hyperlink to the new sheet. It also does not sync with changes.

I have an onEdit script to generate a new sheet when an actor’s name is entered. It will highlight the name in blue, but does not make a hyperlink to the new sheet. Changes to the actor info does not change the sheet, but generates a new one. I need some code that will look for an existing sheet with that name perhaps?

Handling A constructor where one of it’s properties is gotten from an asynchronous function [duplicate]

So I made this js file and exported my Completion function so I can call this from any file I need it instead of re-coding everything.

import OpenAI from "openai";

const openai = new OpenAI();

async function Completion(context, prompt) {
  const completion = await openai.chat.completions.create({
    messages: [
      { role: "system", content: context },
      { role: "user", content: prompt }
    ],
    model: "gpt-4-turbo-preview",
  });
  return completion.choices[0].message.content;
}

export default Completion;

So in a separate file, I made some class Car and tried to generate 3 fun facts about the car and the code works but it looks like every time I make an object it has to be in an async function.

import Completion from "./OpenAI.mjs";

class Car {
    constructor(name, year) {
        this.name = name;
        this.year = year;
        this.about = null;

        (this.initializeAbout = async () => this.about = await this.generateAbout(this.name, this.year))();
    }

    async generateAbout(name, year) {
        const context = "You are a car expert";
        const prompt = `In 3 lines give me 3 fun facts about the car ${name} ${year}`;
        return await Completion(context, prompt);
    }
}

async function main() {
    let merc = new Car("Mercedes GLE", 2022);

    // Wait for the about property to be set

    console.log(merc.name);

    await merc.initializeAbout();
    console.log(merc.about);
}

main();

Is there a better way of going about this? (I’m not experienced with JavaScript)
Thank you!

Error when adding images from a request input

I am trying to load images in ‘postValues’ for a request to the backend, I already tried adding images from insomnia and everything works fine, the configuration of the multer and routes, controllers and publication services are ok, the problem is when I try to send images in a forms From the frontend, I have the following code:

/* <----------------------- MODULOS --------------------------> */
import Creatable, { useCreatable } from 'react-select/creatable';

/* <----------------------- FUNCIONES --------------------------> */
import { useState, useEffect } from "react";

/* <---------------- COMPONENTES MATERIAL UI ------------------> */
import Avatar from '@mui/material/Avatar';

/* <----------------------- ICONOS --------------------------> */
import Button from '@mui/material/Button';
import SendIcon from '@mui/icons-material/Send';

/* <----------------------- SERVICIOS  -----------------------> */
import { getHashtags } from "@/services/hashtag.service";
import { createPost } from "@/services/post.service";

/* <----------------------- CONTEXTO  -----------------------> */
import { useAuth } from '@/context/AuthContext.jsx';

const CreatePost = () => {

  const { user } = useAuth();

  const [postValues, setPostValues] = useState({
    author: user.id,
    title: "",
    description: "",
    images: [],
    hashtags: []
  });

  const [hashtagValues, setHashtagValues] = useState("");

  const getDataHashtags = async () =>{
    try {
      const response = await getHashtags();
      const optionsHashtags = response.data.data.data.map(hashtag => ({
        // No se utiliza el id, por como se programo en el backend -> value: hashtag._id,
        value: hashtag.nameHashtag,
        label: hashtag.nameHashtag
      }))
      setHashtagValues(optionsHashtags);
    } catch (error) {
      console.log(error);
    }
  }

  useEffect( () => {
    getDataHashtags();
  },[])

  // Manejo de campos simples
  const handleChange = (e) => {
    const { name, value } = e.target;
    setPostValues( (prevState) => ({
        ...prevState,
        [name]: value      
      })
    )
  }

  // Manejo de hashtags
  const handleHashtagChange  = (selectedOptions) => {
    const hashtags = selectedOptions ? selectedOptions.map(option => option.value) : [];
    setPostValues((prevState) => ({
      ...prevState,
      hashtags
    }));
  };

  const handleImageChange = (e) => {
    const files = Array.from(e.target.files);

    setPostValues((prevState) => (
      {...prevState, images: [...prevState.images, ...files]}
  ));
  }
  


  // Envio de postValues
  const onSubmit = async (e) => {
    e.preventDefault();
    try {
      await createPost(postValues);
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className='flex flex-row p-4 w-3/4 mx-auto space-x-2'>

      <div>
        <Avatar/>
      </div>
        
      <form className="flex flex-col w-full" encType="multipart/form-data">
        <input placeholder='Titulo' name="title" value={postValues.title} onChange={handleChange}
            className='bg-gray-100 p-2 mb-4 border-2 rounded-md leading-5 transition duration-150 ease-in-out sm:text-sm sm:leading-5 focus:outline-none focus:border-blue-500 flex w-full'>
        </input>

        <textarea id="postContent" rows="4" placeholder="Cuentanos más sobre lo que quieres publicar :-)" onChange={handleChange} name="description" value={postValues.description}
            className="bg-gray-100 p-2 mb-2  rounded-md px-4 py-2 leading-5 transition duration-150 ease-in-out sm:text-sm sm:leading-5 resize-none focus:outline-none focus:border-blue-500" >
        </textarea>



        <Creatable isMulti placeholder="Hashtags" onChange={handleHashtagChange}
          className="bg-gray-100 mb-2 rounded-md leading-5 transition duration-150 ease-in-out sm:text-sm sm:leading-5 focus:outline-none focus:border-blue-500"
          options= {hashtagValues}
          >
        </Creatable>

        <div className="mb-2">
          <div className="mb-2">
            <input type="file" multiple onChange={handleImageChange} />
          </div>
        </div>

        <div className="grid grid-cols-2 gap-2 mb-4">
          {postValues.images.map((image, index) => (
            <div key={index} className="relative">
              <img src={URL.createObjectURL(image)} alt={`upload-${index}`} className="w-full h-full object-cover rounded-md" />
            </div>
          ))}
        </div>

        <Button variant="contained" endIcon={<SendIcon />}
          className="rounded"
          onClick={onSubmit}
        >
          Publicar
        </Button>
      </form>
    </div>
  )
}

export default CreatePost

I use the route router.post("/createPost",[uploadImage.array('images')], postController.createPost); to send the request. And the multer is:

/* <---------------------- MODULES ---------------------- ----> */
const multer = require('multer');

// storage: Memory storage configuration
const storage = multer.memoryStorage();
// limits: File size limit (5MB)
const limits = { fileSize: 1024 * 1024 * 5 };

// filter: Filter function to allow only image files (PNG, JPEG, JPG)
const filter = (req, file, cb) => {
     if(file && (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg')){
         cb(null, true);
     }else{
         cb(null, false);
     }
}

// Multer configuration
const uploadImage = multer({
     storage: storage,
     fileFilter: filter,
     limits
});

module.exports = uploadImage;

I am getting the following error:

AxiosError {
  message: 'Request failed with status code 400',
  name: 'AxiosError',
  code: 'ERR_BAD_REQUEST',
  config: {...},
  request: XMLHttpRequest,
  response: {
    config: {...},
    data: {
      state: 'Error',
      message: '"images" is not allowed',
      details: {...}
    },
    headers: AxiosHeaders {
      content-length: '68',
      content-type: 'application/json; charset=utf-8'
    },
    request: XMLHttpRequest,
    status: 400,
    statusText: 'Bad Request',
    [[Prototype]]: Object
  },
  stack: 'AxiosError: Request failed with status code 400n    at settle (webpack-internal:///./node_modules/axios/lib/core/settle.js:24:12)n    at XMLHttpRequest.onloadend (webpack-internal:///./node_modules/axios/lib/adapters/xhr.js:125:66)n    at Axios.request (webpack-internal:///./node_modules/axios/lib/core/Axios.js:54:41)n    at async onSubmit (webpack-internal:///./src/components/CreatePost.jsx:80:13)',
  [[Prototype]]: Error
}

The problem seems to be in how I send the image data from the frontend to the backend, since it tells me that images is not of type string, when I print postValues I know that I send this:
enter image description here

Using the driver from insomnia works correctly
enter image description here

How do I prevent collision between bodies in a stack using MatterJS?

Using MatterJS I have a stack of circles and a floor rectangle:

var stack = Composites.stack(300, 0, 3, 3, 10, 10, function(x, y) {
    return Bodies.circle(x, y, Common.random(10, 20), {friction: 0, restitution: 0.2, density: 0.001 });
}); 

Composite.add(world, stack);

Composite.add(world, [
    Bodies.rectangle(300, 300, 600, 20, { isStatic: true, friction: 0, render: { fillStyle: '#060a19' } }),
]); 

How do I make those circles ignore each other and only collide with my floor rectangle?

How to pass golang gin sesssion to next.js

I am following gin-contrib cookie-based sessions documentation, to increment a session count

    // This is the backend golang code
    router.GET("incr", func(c *gin.Context) {
        session := sessions.Default(c)
        c.Header("Content-Type", "application/json")

        var count int
        v := session.Get("count")
        if v == nil {
            count = 0
        } else {
            count = v.(int)
            count++
        }
        session.Set("count", count)
        session.Save()
        c.JSON(200, gin.H{"count": count})
    })

This works using postman I can see the cookie session in the response and the counter increments with each request. However, when I try to send this request using fetch in next.js project.

        // this is the frontend next.js code
        const resp = await fetch(`${process.env.BACKEND}/incr`)
        const res = await Promise.all([resp.json()])
        console.log("this is the res ",res)

The output does not increment as expected,

this is the res  [ { count: 0 } ]
 POST /login 200 in 16ms
this is the res  [ { count: 0 } ]
 POST /login 200 in 17ms
this is the res  [ { count: 0 } ]
 POST /login 200 in 15ms
this is the res  [ { count: 0 } ]

and when I use the browser developer tools I can not see the cookie in the response.

How to create custom elements in HTML on demand?

I am curretly adding some customm elements for an inhouse framework , however I noticed that we are getting all the elements on an index file to use them inside the html.

Do you know a better way to do this ? like a lazy instantiation.

current code :

customElements.define('element-a', ElementA);
customElements.define('element-b', ElementB);
customElements.define('element-c', ElementC);
customElements.define('element-d', ElementD);
customElements.define('element-f', ElementF);
....

Failed to resolve module specifier “react-redux”

after I deploy a react project I keep getting this annoying error :

TypeError: Failed to resolve module specifier “react-redux”. Relative references must start with either “/”, “./”, or “../”

any solution

before that I get an error when deploying then I fix it and when the project get deployed I get that error

How to share types file between frontend and backend in nextjs?

As I am making a nextjs app I kept type related to frontend to close the frontend folders and for backend, I was putting them to close to the backend folders. Both backend and frontend are in the same project.

Such as at frontend I am putting type inside @/app/(code)/constants/ISnippet
and backend core>domain>entities>Snippet.ts

For this reason, there are duplicate of same type how to handle this properly?

Example

@/app/(code)/constants/ISnippet
export interface SnippetViews {
  count: number;
  snippetId: string;
}

export interface ISnippet {
  id: string;
  title: string;
  code: string;
  language: string;
  theme: string;
  fontFamily: string;
  fontSize: string;
  lineNumbers: boolean;
  padding: string;
  customColors: string[];
  colorMode: string;
  angle: number;
  grain: boolean;
  createdAt: Date;
  updatedAt: Date;
  userId: string;
  views: SnippetViews;
}



core>domain>entities>Snippet.ts

export interface Snippet {
  id: string;
  title?: string;
  code?: string;
  language: string;
  theme: string;
  fontFamily: string;
  fontSize: string;
  lineNumbers: boolean;
  padding: string;
  customColors?: object;
  colorMode: string;
  angle: number;
  grain: boolean;
  createdAt: Date;
  updatedAt: Date;
  userId: string;
}

how to make vscode extension that records voice

I would like to make an extension for VScode that would transcribe what user speaks into mic and add some functionality with VScode api depending on what the user says (for example “terminal” would open the terminal in VScode). I already have an API for transcription that accepts wav audio files. What i need now is to record audio from user’s mic (recording would start when the user executes the command in VScode). Is this possible to do within the typescript or javascript project for making VScode extensions?

I tried writing the recording with mic part with python and running it from extension.ts with python-shell module but it ends before recording audio.