How to do selections on an image on mobile?

I’m trying to make a website of mine responsive. It uses JavaScript to let you select parts of an image on PC but it doesn’t work on mobile. That’s because of the events used – mouseup, mousedown, mousemove. How can I refactor my code so that it works on mobile? All I need to know is the coordinates of the selection.

Sort array by number from other array

I have two arrays and I want to sort first one based on some values from another array:

const items = [
 ['music', ['arr']],
 ['movies', ['arr']],
 ['quizes', ['arr']],
 ['series', ['arr']]
];

const categories = [
 { name: "music", priority: 3},
 { name: "movies", priority: 2},
 { name: "quizes", priority: 5},
 { name: "series", priority: 1},
 { name: "sports", priority: 4},
];

I want to sort my first array, by property ‘priority‘ from my second array -> from the biggest one.

Like this:

const expectedResult = [
 ['quizes', ['arr']],
 ['music', ['arr']]
 ['movies', ['arr']],
 ['series', ['arr']],
];

This is what I tried but without success.

const sorted = items.sort((a,b) => {
  const [aKey, aVal] = a;
  const [bKey, bVal] = b;
 
  const prio = categories.filter(c => c.name === aKey)[0];
  // not sure how to use this prio
  return aKey.priority - bKey.priority;
})

Postman Returning 404 for post route

I am new to postman and am trying to do some test uploads to cloudinary. However when i try do some test uploads i am getting status 404 not found in my localhost:5000/api and localhost:5000/api/upload.

Here is my upload.js where i am using router.post:

const router = require("express").Router();
const cloudinary = require("cloudinary");
const fs = require("fs");

//UPLOAD TO CLODUINARY
cloudinary.config({
  cloud_name: process.env.CLOUD_NAME,
  api_key: process.env.CLOUD_API_KEY,
  api_secret: process.env.CLOUD_API_SECRET,
});

//upload image
router.post("./upload", (req, res) => {
  try {
    console.log(req.files);
    res.json("test upload");
  } catch (error) {
    res.status(500).json({ msg: error.message });
  }
});

module.exports = router;

used in server.js:

const productRoutes = require("./routes/productRoutes");
const uploadRoutes = require("./routes/upload");

app.use("/api", uploadRoutes);
app.use("/api/products", productRoutes);

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server running on port ${PORT}`));

I dont end up seeing my “test upload message” and postman doesnt seem to be able to connect to it.:

Postman

Any help would be much appreciated

How to prevent bypass with markdown (Word blacklist system)

I’ve created a word-blacklist system that works decently, I remove all spaces from the message content, then use regex to match for blacklisted words, and if there’s a match, delete the message.

const msgContent = message.content.replace(/s/g, '');

let foundBlacklist = false;

for (const word of data.Words) {
   const regex = new RegExp(`${word}`, 'gi');
   if (regex.test(msgContent)) {
     foundBlacklist = true;
   }
}

if(foundBlacklist) message.delete().catch(err => console.log(`There was an error trying to delete that message: ${err}`))

The problem is that it’s very easy to use markdown to bypass this, if bad is a blacklisted word, simply doing b*a*dto to make it italic, would make the message content b*a*d, and the regex won’t match. This of course applies to underline, strikethrough … etc, where b__ad__ or **b**ad etc won’t match either.

How could this be prevented?

Dynamic text fields does not allow different values of it. How can I fix this?

You can add more text fields of size, color, and stocks. If I’ll add more sizes, the values for the color and stocks will duplicate from what was first entered. But there’s no duplicate forExample:

Expected output:

1st Size : small

color: red, stocks: 10

color: green, stocks: 3

2nd Size: medium

color: white, stocks: 3

color: red, stocks: 6 the sizes field.

What it currently does is in the 2nd size, it will just duplicate whatever value was entered from the first size. How can I fix this? Thank you.

Link: https://codesandbox.io/s/form-2-add-more-size-ddqqo?file=/demo.js

import React, { useState, useEffect } from "react";
import Box from "@mui/material/Box";

import { TextField, Button } from "@mui/material";

export default function BasicSelect() {
  const [productName, setProductName] = useState();
  const [sizeList, setSizeList] = useState([{ size: "" }]);
  const [colorList, setColorList] = useState([{ color: "", colorStocks: "" }]);

  //sizes
  const handleServiceChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...sizeList];
    list[index][name] = value;
    setSizeList(list);
  };

  const handleServiceRemove = (index) => {
    const list = [...sizeList];
    list.splice(index, 1);
    setSizeList(list);
  };

  const handleServiceAdd = () => {
    setSizeList([...sizeList, { service: "" }]);
  };

  // color
  const handleColorChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index][name] = value;
    setColorList(list);
    // console.log(colorList);
  };

  const handleColorStocksChange = (e, index) => {
    const { name, value } = e.target;
    const list = [...colorList];
    list[index][name] = value;
    setColorList(list);
    // console.log(colorList);
  };

  // const handleColorChange = (e, index) => {
  //   const { value } = e.target;

  //   const arr = [...colorList]; //Shallow copy the existing state
  //   arr[index].color = value; //Update the size to the selected size
  //   console.log(arr[index].value);
  //   setColorList([...arr]); //Set the updated array to be the new state
  // };

  // const handleColorStocksChange = (e, index) => {
  //   const { value } = e.target;
  //   console.log(value);
  //   const arr = [...colorList];
  //   arr[index].colorStocks = value;
  //   // console.log(arr)
  //   setColorList([...arr]);
  // };

  const handleColorRemove = (index) => {
    const list = [...colorList];
    list.splice(index, 1);
    setColorList(list);
  };

  const handleColorAdd = () => {
    setColorList([...colorList, { color: "", colorStocks: "" }]);
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log("Product: ", productName, "size: ", sizeList, colorList);
  };

  return (
    <Box sx={{ minWidth: 120 }}>
      <form onSubmit={handleSubmit}>
        <TextField
          label="Product Name"
          name="name"
          type="text"
          id="productName"
          value={productName}
          onChange={(e) => setProductName(e.target.value)}
          required
        />

        {sizeList.map((singleSize, index) => (
          <div key={index}>
            <TextField
              label="Size"
              name="size"
              type="text"
              id="size"
              required
              value={singleSize.size}
              onChange={(e) => handleServiceChange(e, index)}
            />
            {colorList.map((singleColor, index) => (
              <div key={index}>
                <TextField
                  label="color"
                  name="color"
                  type="text"
                  id="color"
                  required
                  value={singleColor.color}
                  onChange={(e) => handleColorStocksChange(e, index)}
                />
                <TextField
                  label="Stocks"
                  name="colorStocks"
                  type="text"
                  id="colorStocks"
                  required
                  value={singleColor.colorStocks}
                  onChange={(e) => handleColorChange(e, index)}
                />
                {colorList.length !== 1 && (
                  <Button onClick={() => handleColorRemove(index)}>
                    Remove
                  </Button>
                )}
                <br />
                {colorList.length - 1 === index && (
                  <Button onClick={handleColorAdd}>Add Color</Button>
                )}
                <br /> <br />
                {/* add or remove sizes */}
              </div>
            ))}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={handleServiceAdd}>
                Add size
              </Button>
            )}
            {sizeList.length - 1 === index && (
              <Button type="button" onClick={() => handleServiceRemove(index)}>
                Remove Size
              </Button>
            )}
          </div>
        ))}

        <br />
        <Button type="submit">Submit </Button>
      </form>

      <div className="output">
        <h2>Output</h2>
        <h3>Sizes:</h3>
        {sizeList &&
          sizeList.map((singleSize, index) => (
            <ul key={index}>{singleSize.size && <li>{singleSize.size}</li>}</ul>
          ))}

        <br />
        <h3>Color:</h3>
        {colorList &&
          colorList.map((singleSize, index) => (
            <ul key={index}>
              {singleSize.color && (
                <li>{singleSize.color + " - " + singleSize.colorStocks}</li>
              )}
            </ul>
          ))}
      </div>
    </Box>
  );
}

Adding Attributes to HTML elements via Jquery

I am using wordpress and there is no way to add custom attribute to HTML element via theme. I found that it can be done via Jquery, but it doesn’t help me.

Attributes that I want to add to HTML element on load (No need to click anything specific):

data-tf-popup="Vxs1VOeK" 
data-tf-hide-headers="" 
data-tf-transitive-search-params="utm_source, utm_medium,utm_campaign,utm_term,utm_content" 
data-tf-iframe-props="title=Dermatologo konsultacija internetu - iDerma" 
data-tf-medium="snippet" 
data-tf-hidden="utm_source=xxxxx,utm_medium=xxxxx,utm_campaign=xxxxx,utm_term=xxxxx,utm_content=xxxxx" 

Specific button/item to which I want to add it. Currently it has Ahref, but I will remove the ahref, to keep it empty.

<li id="menu-item-37" class="menu-singup menu-item menu-item-type-custom menu-item-object-custom menu-item-37" data-tf-popup="Vxs1VOeK"><a href="https://form.typeform.com/to/Vxs1VOeK">Pradėti konsultaciją</a></li>

Any help will be appreciated!

ReferenceError: interaction is not defined

I need help defining ‘interaction’ I do not know how to fix this but here is my code. I’m trying to get the slash command’s author to get their user tag and avatar and put it in the author of the embed. Could anyone help me out?

The problem I am facing is with the .setAuthor field in which 'interaction' is undefined.

Here is the .setAuthor code:

.setAuthor({ name: interaction.user.tag, url: interaction.user.displayAvatarURL(), iconURL: interaction.user.displayAvatarURL() })

Here is my full code:

const Discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
const { MessageEmbed } = require('discord.js')

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

const embed = new Discord.MessageEmbed()
    .setColor('#0099ff')
    .setTitle('Hello!')
    .setURL('https://discord.js.org/')
    .setAuthor({ name: interaction.user.tag, url: interaction.user.displayAvatarURL(), iconURL: interaction.user.displayAvatarURL() })
    .setDescription('Hello! This is a test embed')
    .setThumbnail('https://i.imgur.com/AfFp7pu.png')
    .setTimestamp()
    .setFooter({ text: 'Some footer text here', iconURL: 'https://i.imgur.com/AfFp7pu.png' });


client.on('interactionCreate', async interaction => {
    if (!interaction.isCommand()) return;

    const { commandName } = interaction;

    if (commandName === 'ping') {
        await interaction.reply(`Pong! My current response time is: **`${client.ws.ping}`** ms`);
    } else if (commandName === 'server') {
        await interaction.reply(`Server name: ${interaction.guild.name}nTotal members: ${interaction.guild.memberCount}nServer Creation Date: ${interaction.guild.createdAt}nServer Verification Level: ${interaction.guild.verificationLevel}`);
    } else if (commandName === 'user') {
        await interaction.reply(`**User info for ${interaction.user.username}**nUser Tag: ${interaction.user.tag}nUser ID: ${interaction.user.id}`);
    } else if (commandName === 'embed') {
    await interaction.reply({ embeds:  });
  }
});

client.login(token);

If anyone knows how to fix this please let me know. Thanks!

How to set orientation to landscape in flutter web?

I want my flutter web app to run in landscape mode.

Till now I have tried to add the following line in my main.dart

WidgetsFlutterBinding.ensureInitialized();
  SystemChrome.setPreferredOrientations([
    DeviceOrientation.landscapeLeft,
    DeviceOrientation.landscapeRight,
  ]);

But I think the above code works for only the android or ios apps.

I have also set the orientation to landscape in my manifest.json file:-

"orientation": "landscape",

If anyone can tell me any way to do this in flutter or even by using JavaScript then also it will work.

Break for loop inside promise Then in Cypress Typescript

How to Break ‘for’ loop inside promise ‘Then’ in Cypress Typescript as in below code:

for (let i = 2; i <= iterationspage; i++) {
    cy.wait(5000)
    cy.get(".page").contains(i).click()
    cy.log("clicked on page"+i)
    // let FlagFound='False'
    homePage.getProductNamesSearchResults().each(($el, index, $list)=> {
        const expProductName=$el.text()
        if(expProductName.includes(this.addtocart.ProductToBuy)){
            homePage.getAddToCartButton().eq(index).click()
            
            homePage.getPriceTagForSearchedProducts().eq(index).then(function(productPrice){
                cy.log(productPrice.text())
                cy.log(expProductName)
                
            }) 
        
            //break
        }
    })
}

Selector not finding my element in DOM tree

I’m following a tutorial and am having trouble accessing an element on a website using testcafe. The person in the tutorial does not have this problem and there are no comments on the tutorial regarding.
I have a constructor with a selector that is trying to access a button on a page and then called from another script. Here is selector code piece

    this.continueBtn = Selector("input.button-1.new-address-next-step-button")

The element I am trying to reach on the website

<button type="button" name="save" class="button-1 new-address-next-step-button"
onclick="Billing.save()" data-hammerhead-focused="true">Continue</button>

I am getting an error that says:

The specified selector does not match any element in the DOM tree.
 > | Selector('input.button-1.new-address-next-step-button')

I have tried to reach it using [name=’save’], instead of input I used button but then they said the element is hidden. Tried .withText(“Continue”). and some other similar things but nothing seems to be working.

Note: the “Input.classname” works on most other selectors.

Can anyone help me out, or explain why this is happening?

SseEmitter request is pending forever

My frontend is Vue.js.
The following js code is put in the setup. (My question has nothing to do with Vue.js, you can think of setup as a place where the js code runs)

    let eventSource = new EventSource(
        "http://127.0.0.1:8080/sse/connect");

My backend code (SpringBoot application running on localhost:8080)
This is the controller.

@Controller
@RequestMapping("/sse")
public class SseEmitterController {
    SseEmitterServer sseEmitterServer;

    @Autowired
    public void setSseEmitterServer(SseEmitterServer sseEmitterServer) {
        this.sseEmitterServer = sseEmitterServer;
    }

    @GetMapping("/connect")
    public SseEmitter connect() {
        return sseEmitterServer.connect(1L);//1L is userId, for testing, I set it to 1L
    }
}

SseEmitterServer:

@Service
public class SseEmitterServer {

    private   Map<Long, SseEmitter> sseEmitterMap = new ConcurrentHashMap<>();

    public   SseEmitter connect(Long userId) {
        SseEmitter sseEmitter = new SseEmitter(0L);
        sseEmitter.onCompletion(completionCallBack(userId));
        sseEmitter.onError(errorCallBack(userId));
        sseEmitter.onTimeout(timeoutCallBack(userId));
        sseEmitterMap.put(userId, sseEmitter);
        return sseEmitter;
    }
}

However, the request to get a SseEmitter is forever pending.

I wonder what is wrong with my code. I am using Chrome with SSE support.
enter image description here

request detail, it has no response:

enter image description here

TypeError: string.charCodeAt is not a function. How to encode object in node.js using express (restful api)

I use restful API with express & node.js and want to encode data to utf-8.

  1. I install utf8 with npm install utf8

  2. I set const utf8 = require('utf8');

  3. I use utf8.encode(string) to object like that:

     pool.query(`CALL Get_Discharge_Station('${dateNow}', ${daysBefore}, ${stNumber})`, function (error, result, fields) {
       if (error)
         return res.status(500).json({ error: "Грешна заявка. Опитай отново !" })
       HQdataAHS = utf8.encode(result);
       res.json({ HQdataAHS })
     });
    

    });

I receive error like that:

How to encode object in node.js using express (restful api)

How to properly bundle the React 17 library with new JSX transform as ES Module?

I am building a simple library of React components and need to publish as ES Module only package to NPM. Since I am using React 17, I have used new JSX transform. I use rollup and typescript to generate ES package. The generated JS file looks like this:

// ./dist/index.js
import { jsx, jsxs } from 'react/jsx-runtime';
import { forwardRef } from 'react';
import { SVGIcon } from './SVGIcon.js';

const Add = forwardRef(function Add(props, ref) {
  return (jsx( /*  */));
});

const Bell = forwardRef(function Add(props, ref) {
  return (jsx( /*  */));
});

This looks fine. The TypeScript compiler is adding the jsx-runtime to the generated code:

import { jsx, jsxs } from 'react/jsx-runtime';

However, the problem happens when I try to use this library in another application. Webpack complains that it cannot find 'react/jsx-runtime'. The precise error is this:

error - Error [ERR_MODULE_NOT_FOUND]: Cannot find module '/home/hp/test/node_modules/react/jsx-runtime'
imported from /home/hp/test/node_modules/@hrp/icons/dist/index.js
Did you mean to import react/jsx-runtime.js?

It doesn’t complain about react. When I change extension of the imported module manually (adding .js extension) to 'react/jsx-runtime.js' then it works.

So, how to configure rollup or any other module bundler to add appropriate filename extension for subpath imports from third-party modules?