(property) CommandInteractionOption.value?: string | number | boolean Discord.js Slash command options

I’m trying to make my first Discord Bot using typescript.
I made a simple dice roll command with a personal npm package, but there seems to be a problem with the Discord Slash command options.
I made a sum option that is NOT required, which sums any integer to the dice roll. But when I try to code that part, it returns these errors:
1-Argument of type 'string | number | boolean' is not assignable to parameter of type 'string'
2-Type 'number' is not assignable to type 'string'.ts(2345)

here is my code:

import { Command } from "../../structures/Command";
import { inlineCode } from "@discordjs/builders";
import aimless from "aimless";

export default new Command({
    name: "roll",
    description: "Rolls a dice.",
    options: [
        {
            name: "dice",
            description: "The dice you want to roll",
            type: "STRING",
            required: true
        },
        {
            name: "sum",
            description: "The sum you want to add to your roll(s)",
            type: "INTEGER",
            required: false
        }
    ],
    run: async({ interaction }) => {
        const dice = interaction.options.get("dice").value;
        const sum = interaction.options.get("sum");
        console.log(sum)
        let rolls;

        try {
            rolls = aimless.roll(dice);
        } catch (e) {
            return interaction.followUp(`**Invalid dice! n${inlineCode(e.toString().split(":")[2])}**`)
        }

        if (rolls.length == 1) {
            if (!sum) {
                return interaction.followUp(`**You rolled a ${inlineCode(rolls[0])}!**`);
            } else {
                return interaction.reply(`**You rolled a ${inlineCode(rolls[0])}!n ${inlineCode(rolls[0])} + ${inlineCode(sum.value)} = ${inlineCode(+rolls[0] + +sum.value)}.**`);
            }
        }
    }
});

The errors are in this line at sum.value and +rolls[0] + +sum.value:

` return interaction.reply(`**You rolled a ${inlineCode(rolls[0])}!n ${inlineCode(rolls[0])} + ${inlineCode(sum.value)} = ${inlineCode(+rolls[0] + +sum.value)}.**`);`

I tried the same exact command in JavaScript with the @discordjs/builder “SlashCommandBuilder()” and it worked fine.

Accessing CSS value out of parent’s div?

I don’t know if I asked it right…

<body> 
<div class="parent"> 
<div class="child"> </div>
</div>
</body>

If my child div has css value “left” it will be regarding to its parent, what I want is to access the value of “left” regarding to body. Is it possible?
Also to mention, I don’t want to change it, I just want to read it in javascript.

Variables in javascript + jinja2

I’m not good in javascript. I have google charts with data. And I need to add data via loop in javascript:

for (let i = 0; i < 3; i++) {
    data.addRow(
        ['{{list}}[i][0]',
        { v: {{list[i][1][0]}}, f: '{{list[i][1][1]}}' }]
        );
}

But it wrote me an error:

UndefinedError

jinja2.exceptions.UndefinedError: list object has no element Undefined

Can you advice me please, what I can do with it?

In my JavaScript server, why does my posted data have braces and quotes around it?

I have a simple JavaScript server to process a POST command. But my post data shows up surrounded with braces and quotes. I’m using curl to send this:

curl --data {title:'Odessey',author:'Homer'} localhost:4444/test/add

But my server gets the posted data like this:

{ "{title:'Odessey',author:'Homer'}": '' }

When I send it back to the client, it shows up with spaces removed and quotes converted:

{"{title:'Odessey',author:'Homer'}":""}

Curiously, if I put quotes around the string in curl, I get exactly the same thing:

curl --data "{title:'Odessey',author:'Homer'}" localhost:4444/test/add

I’m running this on Windows 10. I have no idea if the problem is with curl or my server. I’ve tried curl’s other options for sending data, like --data.ascii and --data.raw, but none of them help.

Here’s my server code:

const express = require('express');
const app = express();

app.use(
    express.urlencoded({ extended: true })
);

app.use(express.json());

app.post('/test/add', (req, res) => {
    console.log("req.body:", req.body)
    res.send(req.body);
})

var server = app.listen(4444, function() {
    var urlStr = "http://" + host + ':' + port;
    console.log ("Example app listeneing at", urlStr);
})

Bidirectional relationship mongoDB

I have been trying to follow the documentation to make a relationship between movies and categories (also among others that I will mention below, but starting with categories as an example).

Well, below I have the code of the parts of my code and the error response.

models/movie.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const {ObjectId} = mongoose.Schema; 

const movieSchema = new Schema(
  {
    title: {
      type: String,
      required: true,
    },
    year: {
      type: Number,
      required: true,
    },
    duration: {
      type: String,
      required: true,
    },
    rating: {
      type: String,
      required: true,
    },
    score: {
      type: String,
      required: true,
    },
    category: {
      type: ObjectId,
      ref: "Category"
    },
    description: {
      type: String,
      required: true,
    },
    director: [{
      type: ObjectId,
      ref: "Director"
    }],
    actor: [{
      type: ObjectId,
      ref: "Actor"
    }],
    studio: {
      type: ObjectId,
      ref: "Studio"
    },
    poster: {
      type: String,
      required: true,
    },
    trailer: {
      type: String,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model("Movie", movieSchema);

models/category.js

const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const {ObjectId} = Schema;
const categorySchema = new mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
    },
    movies: [
      {
        type: ObjectId,
        ref: "Movie",
      }
    ]
  },
  {
    timestamps: true,
  }
);

module.exports = mongoose.model("Category", categorySchema);

controllers/movie.js

const Movie = require('../models/movie');
const Category = require('../models/category');
const Actor = require('../models/actor');
const Director = require('../models/director');
const Studio = require('../models/studio');

const create = async (req, res) => {
    const content = req.body;

    const category = await Category.findById(content._id);
    const actor = await Actor.findById(content._id);
    const director = await Director.findById(content._id);
    const studio = await Studio.findById(content._id);
    
    const newMovie = new Movie({
        ...content,
        category,
        actor,
        director,
        studio
    });

    const savedMovie = await newMovie.save();

    category.movies = [...category.movies, savedMovie._id];
    await category.save();
    actor.movies = [...actor.movies, savedMovie._id];
    await actor.save();
    director.movies = [...director.movies, savedMovie._id];
    await director.save();
    studio.movies = [...studio.movies, savedMovie._id];
    await studio.save();

    res.status(201).json({
        message: 'Movie created successfully',
        movie: savedMovie
    });
};

Now my post request


POST http://localhost:3000/api/v1/movies HTTP/1.1
Content-Type: application/json

{
        "title": "The Matrixxx",
        "year": 1999,
        "duration": "136 min",
        "rating": "R",
        "score": "8.7",
        "category": "6265ba915a8064456ac6231b",
        "description": "A computer hacker learns from mysterious rebels about the true nature of his reality and his role in the war against its controllers.",
        "director": ["626502e956cd00fe36692bf9"],
        "actor": ["626501fc56cd00fe36692bf2"],
        "studio": "626502ac56cd00fe36692bf7",
        "poster": "https://images-na.ssl-images-amazon.com/images/M/MV5BNzQzOTk3OTAtNDQ0Zi00ZTVkLWI0MTEtMDllZjNkYzNjNTc4L2ltYWdlXkEyXkFqcGdeQXVyNjU0OTQ0OTY@._V1_SX300.jpg",
        "trailer": "https://www.youtube.com/embed/m8e-FF8MsqU"
}

Response

TypeError: Cannot read property ‘movies’ of null
at create (C:UsersdefaultDesktopstreaming-backendsrccontrollersmovie.js:26:36)
at processTicksAndRejections (internal/process/task_queues.js:95:5)

Thanks for the answers :3

How do I remove a random element from an array only ONCE? I keep getting more than 2 of each letter in my array [duplicate]

create a function to display a game board

function displayBoard(value)

create variables for the function to get the value for the number of cards, instantiate the array, and get the div element by id so I can insert my future div’s

var numOfCards = value * 2; //number of cards that we will have on the board by multiplying input value by 2
var letters2 = ["A", "B", "A", "B"]; // setting up an array of letters to use for the card faces
var gameDiv = document.getElementById("game"); //getting the game div element

create a for loop that goes through the number of cards, and creates a new div element and sets a unique id to that div, as well as pulling out a RANDOM letter from the array and storing in the inner html of a div element. I only need to pull the items out one time but it is not working. I tried to pop the element that I pull from the array but it seems to be by passing that method.

for (var i = 0; i < numOfCards; i++) 
    {
        var cards = document.createElement("div"); //creating an div element that is set to variable cards
        cards.setAttribute("id", "card" + [i]); //setting each card with a unique ID
        gameDiv.appendChild(cards); //appending the div elements to the "game" div
        var currentCard = document.getElementById("card" + [i]);//creating a variable for the current card and getting the id to input text
        var randomItem = letters2[Math.floor(Math.random() * letters2.length)]; //create random item to store random array variable
        currentCard.innerHTML = randomItem; //setting the current cards html to the random array value
        letters2.pop(currentCard); //popping the array item so that it can not be used more than once

    }

thanks for all the help!

In this code when I select provinces it appears all cities in the province thats the problem how I fix this? using javascript only

html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Farhan</title>
</head>
<body>
<!--Create select with province list-->
<select id="province">
    <option value="">Select Province</option>
    <option value="Sindh">Sindh</option>
    <option value="Punjab">Punjab</option>
    <option value="Balochistan">Balochistan</option>
    <option value="Khyber Pakhtunkhwa">Khyber Pakhtunkhwa</option>
    <option value="Gilgit-Baltistan">Gilgit-Baltistan</option>
</select>
<!--Create select with city list-->
<select id="city">
    <option value="">Select City</option>
</select>
</body>

Javascript

As you can see when I select province it appears all the cities in an array means ,when I select Sindh then it select right cities but when I select Punjab it select cities of Punjab but cities of Karachi also visible they are not disappearing.

<script type="application/javascript">
    console.log("Hello World");
    //Create javascript object with pakistan provinces
    let pakistan = {
        "Sindh": [
            {"Karachi" : ["Korangi", "Kotli", "Shah Faisal"]},
            {"Hyderabad" : ["Korangi", "Kotli", "Shah Faisal"]},
        ],
        "Punjab": [
            {"Lahore" : ["Korangi", "Kotli", "Shah Faisal"]},
            {"Islamabad" : ["Korangi", "Kotli", "Shah Faisal"]},
            {"Faisalabad" : ["Korangi", "Kotli", "Shah Faisal"]}
        ],
        "Balochistan": [
            {"Quetta" : ["Korangi", "Kotli", "Shah Faisal"]},
            {"Sibi" : ["Korangi", "Kotli", "Shah Faisal"]},
            {"Karakoram" : ["Korangi", "Kotli", "Shah Faisal"]}
        ],
        "Khyber Pakhtunkhwa": [
            {"Peshawar" : ["Korangi", "Kotli", "Shah Faisal"]},
            {"Mardan" : ["Korangi", "Kotli", "Shah Faisal"]},
            {"Kohat" : ["Korangi", "Kotli", "Shah Faisal"]}
        ],
        "Gilgit-Baltistan": [
            {"Kundian" : ["Korangi", "Kotli", "Shah Faisal"]}
        ]
    };
    //On change of province display cities in console
     document.getElementById("province").onchange = function () {
            let cities = pakistan[this.value];
            console.log(cities);
            cities.forEach(function (city) {
            let currentCity = Object.keys(city)[0];
            //Create option element for cities and append to select element
            let option = document.createElement("option");
            option.value = currentCity;
            option.innerText = currentCity;
            
            document.getElementById("city").appendChild(option);
        });
    };
</script>

Angular find element attribute doesn’t work

I am following this simple article: Arrow Keys to Navigate. There is a problem with this line towards the bottom:

var nextInput = angular.element(angular.element.find('[arrow-keys-index="'+nextIndex+'"]'));

Basically, what it needs to do is find an element from my HTML where the attribute and value match the string so it can then call to focus that element. HTML example of what it needs to find would look like this:

<input type="text" arrow-keys-index="0:2" />

I am getting an error on that line:

TypeError: angular.element.find is not a function
at HTMLInputElement. (arrow-keys-index.js:47:65)
at defaultHandlerWrapper (angular.js:3795:11)
at HTMLInputElement.eventHandler (angular.js:3783:9)
at ZoneDelegate.invokeTask (zone-evergreen.js:406:1)
at Object.onInvokeTask (core.js:28564:1)
at ZoneDelegate.invokeTask (zone-evergreen.js:405:1)
at Zone.runTask (zone-evergreen.js:178:1)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:487:1)
at invokeTask (zone-evergreen.js:1600:1)
at HTMLInputElement.globalZoneAwareCallback (zone-evergreen.js:1626:1)

Any thoughts?

open file and download does not work in ubuntu

i complete my code on windows xampp to download text(or other file) file and its work good
but when i upload the code on ubuntu server its does not work
can you help me plz

$txt = fopen($file, "w") or die("Unable to open file!");
fwrite($txt,
"{
anything
}

");
fclose($txt);

header('Content-Description: File Transfer');
header('Content-Disposition: attachment; filename='.basename($file));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
ob_clean();
  flush();
header('Content-Length: ' . filesize($file));
header("Content-Type: text/plain");
readfile($file);

the response on ubuntu is Unable to open file!

REACT – Turn a selection from a dropdown to a tag label

Is there a way to turn a selection from a dropdown to a tag with the appropriate color (see the image).

export default function MenuItemDisplay() {
...
  const colourStyles = {
    singleValue: (provided, { data }) => ({
      ...provided,
      backgroundColor:
        data.value === "Good"
          ? "#36B37E"
          : data.value === "Medium"
          ? "#FF8B00"
          : data.value === "Bad"
          ? "#FF5630"
          : ""
    })
  };
...
  return (
      ...
          <CustomDropdown
            style={styles.select}
            options={TASTE}
            defaultValue={TASTE.find((t) => t.label === item.taste)}
            styleSelect={colourStyles}
          />
        </div> 
       ...      
  );
}

export default function CustomDropdown({ className, style, options, styleSelect, defaultValue, isMulti }) {
    return <div style={style}>
        <Select className={className} styles={styleSelect} options={options} defaultValue={defaultValue} isMulti={isMulti} />
    </div>
}

Here is the picture to get the idea:enter image description here

Here is the code

Images between slides aren’t smooth

I have sliders in my code and when I first click through the slides it isn’t smooth but after going through it once it becomes smooth. I do have several sliders and they all act the same. I can’t seem to find an answer. Can someone look at my code and see what I am doing wrong or what I may not be doing? Thanks for any and all help!

// -------------- Image Slider --------------

var slideIndex = [1, 1, 1, 1, 1, 1, 1];
var slideId = ["slide1", "slide2", "slide3", "slide4", "slide5", "slide6", "slide7"]
showImg(1, 0);
showImg(1, 1);
showImg(1, 2);
showImg(1, 3);
showImg(1, 4);
showImg(1, 5);
showImg(1, 6);

function side_slide(n, no) {
  showImg(slideIndex[no] += n, no);
}

function showImg(n, no) {
  var i;
  var x = document.getElementsByClassName(slideId[no]);
  if (n > x.length) {
    slideIndex[no] = 1;
  }
  if (n < 1) {
    slideIndex[no] = x.length
  }
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex[no] - 1].style.display = "block";
/* slider */

.portfolio__port-item .images {
  height: 100%;
  width: 100%;
}

.portfolio__port-item .images .sliderImg {
  height: 100%;
  width: 100%;
}

.sliders {
  position: absolute;
  top: 90%;
  transform: translateY(-50%);
  cursor: pointer;
  transition: all 2s, ease-in;
}

.left {
  margin-left: 10px;
}

.right {
  right: 0;
  margin-right: 10px;
}

.sliders span {
  line-height: 41px;
  font-size: 35px;
  color: white;
  transition: all 2s, ease-in;
}

.sliders span:hover {
  color: #84b4b1
}


/* end of slider */
<!---------- College Admissiosn HQ Website Content ---------->
<div id="CollegeAdmissionsHQWebsite" class="portfolio__port">
  <div class="row">
    <div class="portfolio__port-container">
      <div class="portfolio__port-description">
        <h2>College Admissions HQ</h2>

        <p>Role: Web Designer | Created: 2014-2018</p>
        <p>Programs Used: <span class="vsc">VSC</span> <span class="ps">Ps</span> <span class="wp">WP</span></p>
        <p>URL: <a href="https://www.collegeadmissionshq.org" target="_blank">collegeadmissionshq.org</a></p>

        <p> Since being hired by the online company, College Admissions HQ, LLC, to design their website, the trajectory of the company changed several times, and each time I redesigned the website to fit the new company goals. </p>
        <p>The current version of the website was built using a WordPress theme with the addition of custom HTML and CSS to create exact design elements to the client's specifications. The custom code was created using SCSS and HTML and then added into WordPress.
          The website includes a blog page and a resources page, both of which I set up for AdSense to run ads on. </p>

      </div>
      <!-- / .portfolio__port-description -->
      <div class="portfolio__port-item">
        <img src="../image/bifold-menu-inside.jpg" alt="">
      </div>
      <div class="portfolio__port-item">
        <div class="images">
          <img class="slide1" src="../img/bg1.jpeg">
          <img class="slide1" src="../img/bg2.jpg">
          <img class="slide1" src="../img/bg3.jpeg">
          <img class="slide1" src="../img/bg4.jpeg">
          <img class="slide1" src="../img/bg5.jpg">
        </div>
        <!-- / .images -->
        <div class="sliders left" onclick="side_slide(-1, 0)">
          <span class="fa fa-angle-left"></span>
        </div>
        <!-- / .sliders .left -->
        <div class="sliders right" onclick="side_slide(1, 0)">
          <span class="fa fa-angle-right"></span>
        </div>
        <!-- / .sliders .right -->
      </div>
      <div class="portfolio__port-item">
        <div class="images">
          <img class="slide2" src="../img/bg6.jpeg">
          <img class="slide2" src="../img/bg7.jpg">
          <img class="slide2" src="../img/bg8.jpeg">
          <img class="slide2" src="../img/bg9.jpeg">
          <img class="slide2" src="../img/bg10.jpg">
        </div>
        <!-- / .images -->
        <div class="sliders left" onclick="side_slide(-1, 1)">
          <span class="fa fa-angle-left"></span>
        </div>
        <!-- / .sliders .left -->
        <div class="sliders right" onclick="side_slide(1, 1)">
          <span class="fa fa-angle-right"></span>
        </div>
        <!-- / .sliders .right -->
      </div>
      <div class="portfolio__port-item">
        <div class="images">
          <img class="slide3" src="https://cdn.dribbble.com/users/545884/screenshots/2883479/cover.jpg">
          <img class="slide3" src="https://cdn.dribbble.com/users/545884/screenshots/4360101/liberosis_--_12.png">
          <img class="slide3" src="https://cdn.dribbble.com/users/545884/screenshots/3981307/lorena2.png">
          <img class="slide3" src="https://cdn.dribbble.com/users/545884/screenshots/2883479/cover.jpg">
          <img class="slide3" src="https://cdn.dribbble.com/users/545884/screenshots/4154721/dive--001.png">
        </div>
        <!-- / .images -->
        <div class="sliders left" onclick="side_slide(-1, 2)">
          <span class="fa fa-angle-left"></span>
        </div>
        <!-- / .sliders .left -->
        <div class="sliders right" onclick="side_slide(1, 2)">
          <span class="fa fa-angle-right"></span>
        </div>
        <!-- / .sliders .right -->
      </div>
      <div class="portfolio__port-item">
        <img src="../image/TAFE/Postcards/GLY-Postcard.jpg" alt="">
      </div>
      <div class="portfolio__port-item">
        <img src="../image/TAFE/Postcards/Thank-You-1.jpg" alt="">
      </div>
      <div class="portfolio__port-item">
        <img src="../image/TAFE/Posters/Women-&-One-Acts-Poster.jpg" alt="">
      </div>
      <div class="portfolio__port-item">
        <img src="../image/TAFE/Posters/Mystery-At-Senior-Manor.jpg" alt="">
      </div>
      <div class="portfolio__port-item">
        <img src="../image/TAFE/Posters/An-Enchanted-Bookshop-Christmas-Poster.jpg" alt="">
      </div>
      <div class="portfolio__port-item">
        <img src="../image/TAFE/Posters/Talent-In-the-Time-Of-Covid-Poster.jpg" alt="">
      </div>
      <div class="portfolio__port-item">
        <img src="../image/TAFE/Posters/Talent-In-the-Time-Of-Covid-Poster.jpg" alt="">
      </div>
      <div class="portfolio__port-item">
        <div class="images slider-7">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Cover.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread1.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread2.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread3.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread4.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread5.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread6.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread7.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread8.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Spread9.jpg">
          <img class="slide7" src="../image/TAFE/Brochures-Programs-Handouts/Woman-And-One-Acts/Woman-and-One-Acts-Back.jpg">
        </div>
        <!-- / .images -->
        <div class="sliders left" onclick="side_slide(-1, 6)">
          <span class="fa fa-angle-left"></span>
        </div>
        <!-- / .sliders .left -->
        <div class="sliders right" onclick="side_slide(1, 6)">
          <span class="fa fa-angle-right"></span>
        </div>
        <!-- / .sliders .right -->
      </div>
    </div>
    <!-- / .portfolio__port-container -->
  </div>
  <!-- / .row -->
</div>
<!-- / #CollegeAdmissionsHQWebsite -->

Sending a profile picture from react frontend to flask-restful backend and storing

I want to store profile pictures on the file system (images/{username}_pfp.{extension} and store its location in the database as a string.
My frontend react code is

const Signup = () => {
    const [state, setState] = useState({
        email: "",
        password: "",
        confirmPassword: "",
        username: "",
        profile_picture: "",
    });

    const navigate = useNavigate();

    const onSubmit = (e) => {
        e.preventDefault();
        console.log(state.email, state.password, state.confirmPassword, state.username);

        if (state.password === state.confirmPassword) {

            getData('http://localhost:5000/users')
            .then(data => {
                console.log(data);
                let userExists = false;
                for (let i = 0; i < data.length; i++) {
                    if (data[i].email === state.email) {
                        userExists = true;
                    }
                    if (data[i].username === state.username) {
                        userExists = true;
                    }
                }
                if (userExists) {
                    alert("Email or Username already exists");
                } else {
                    const data = new FormData();
                    for(var x = 0; x<state.profile_picture.length; x++) {
                        data.append('file', state.profile_picture[x])
                    }
                    postData('http://localhost:5000/users', {
                        email: state.email,
                        password: state.password,
                        name: state.username,
                        profile_picture: data
                    })
                    .then(data => {
                        console.log(data);
                        alert("User created successfully");
                        navigate('/');
                    })
                    .catch(err => {
                        console.log(err);
                        alert("Error creating user");
                    });
                }
            })
            .catch(err => {
                console.log(err);
                alert("Error creating user");
            });

        };
    };
    return (
        <>
        <Header />
    <div className="container">
    <Form>
    //creating other values
    <Form.Group className="mb-3" controlId="formFile">
        <Form.Label>Upload Profile Picture (image format must be png, jpg, or jpeg).</Form.Label>
        <Form.Control type="file" onChange={e => setState(prevState => { return {...prevState, profile_picture: e.target.value}})}/>
    </Form.Group>

    <Button variant="primary" type="submit" onClick={onSubmit}>
        Submit
    </Button>
    </Form>
</div>
</>
    );
};

and my flask backend code is

class UserListResource(Resource):
    def get(self):
        users = User.query.all()
        return users_schema.dump(users)

    def post(self):
        received_file = request.json['profile_picture']
        filename = request.json['name'] + '_pfp' + received_file.filename.split('.')[1]
        filename = secure_filename(filename)
        filename = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        received_file.save(filename)
        new_user = User(
            email=request.json['email'],
            password=request.json['password'],
            name=request.json['name'],
            profile_picture=filename
        )
        db.session.add(new_user)
        db.session.commit()
        return user_schema.dump(new_user)


api.add_resource(UserListResource, '/users')

I have gotten the bits of code relevant to this from multiple sources (Flask – Get the name of an uploaded file minus the file extension, https://flask.palletsprojects.com/en/2.1.x/patterns/fileuploads/). When the image is sent to the backend, it gives an AttributeError: dict object has no attribute filename in the backedn terminal. How can I get this to work? Have I missed something?

Adding a class to a div when the div is on scrolled into the screen

So I am trying to add the fadeInTop class to the div with the class animation. I think the Javascript is not working correctly… Is the Js supposed to go into the application.js or into a different file?

This is in the application.js file:

import Rails from "@rails/ujs"
import Turbolinks from "turbolinks"
import * as ActiveStorage from "@rails/activestorage"
import "channels"


const observer = new IntersectionObserver(entries => {
  entries.forEach(entry => {
    if(entry.isIntersecting){
      document.querySelectorAll(".animated".classList.add(fadeInTop))
    }
  })
})

observer.observe(document.querySelector(".containerFadeIn"))

This is from the home.html.erb view:

<main class="home-main">
<%# fist box %>

  <div class="home-text-1 containerFadeIn">
    <div class="row containerFadeIn">
      <div class="col-md-9 d-flex animated">
        <div class="vendo-logo-home">
          <%= image_tag "vendo-logo.png"%>
        </div>
        <div>
          <h1>The Future begins</h1>
          <h1 > with <span class="light-blue"><strong>VENDO</strong></span></h1>
        </div>
      </div>
    </div>
  </div>
</main>

my main goal is to make the text fade into the screen when the text is scrolled into the screen (if i add the fadeInTop class to the the fade in animation works)

How can I make these dynamic form fields have unique values?

This code has been taken from a larger project, so don’t mind that it doesn’t seem like it’s doing anything special. Essentially, I want to create a dynamic form that, as it’s being filled out, populates information for the Property Interface in the PropertyStructs Array.

To do this, I’m mapping over the PropertyStructs array to display the fields I would like, in this case the field ‘project’, over and over. But each time it’s displayed, it alters the property at the given index.

I’m facing two problems:

The first problem I’m facing is that when you run this code, and you click on the add property button, it creates a new field which has the same input as the first field. If I then write into any of the two fields, it changes the property information for all of them in the same time.

The second problem is that I want to be able to remove the property at the given index and not just the last property when someone clicks the remove button. This seems to work for all properties but the first one and I’m not sure why.

Can anyone help with this issue?

import React, {useRef, useState} from "react"


const ONE: number = 1
const ZERO: number = 0
const NEGATIVE_ONE: number = -1
const BLANK = ""

interface Property {
  project: string
}

export const defaultResidential: Property = {
  project: BLANK,
}

interface PropertyStruct {
  property: Property
  pos: number
}

const initializePropertyStructArray = (): PropertyStruct[] => {
  return [{
    property: defaultResidential,
    pos: ZERO
  }]
}

const App = () => {

  const form: any = useRef()

  const [propertyStructs, setPropertyStructs] = useState<PropertyStruct[]>([])

  const handleResidentialPropertyAdd = (index: number) => {
    const newProperty: PropertyStruct = {
      property: defaultResidential,
      pos: index + ONE
    }

    setPropertyStructs([...propertyStructs, newProperty])
  }

  const handleRemove = (index: number, array: any[], setter: React.Dispatch<React.SetStateAction<any>>) => {
    const list = [...array]

    const newList = list.filter(entry => entry.pos !== index)
    newList.forEach(entry => entry.pos > index ? entry.pos-- : entry.pos)

    setter(newList)
  }

  const handlePropertyProjectChange = (changeEvent: React.ChangeEvent<HTMLInputElement>, index: number) => {
    const list = [...propertyStructs]

    list[index].property.project = changeEvent.target.value
    setPropertyStructs(list)
  }

  console.log(propertyStructs)

  return (
      <>
        <div className="client-form__page p-4">
          <form ref={form}>
            <div>
              {/*Property Form*/}
              <div className="">
                <div className="client-form__background">
                  <div className="client-form__header">Property Details</div>

                  {
                    propertyStructs.length === ZERO ?
                        <button
                            type="button"
                            onClick={() => handleResidentialPropertyAdd(NEGATIVE_ONE)}>
                          Add Residential Property
                        </button> :
                        <></>
                  }
                  {
                    propertyStructs.map((element: PropertyStruct, index: number) => (
                        <div key={index}>
                          <div>Property {index + ONE}</div>
                          <div>
                            <div>
                              <div>
                                <label htmlFor="project">
                                  Project*
                                  <input
                                      type="text"
                                      name="project"
                                      placeholder="eg. Address Hotel"
                                      onChange={e => handlePropertyProjectChange(e, index)}
                                      required
                                  />
                                </label>
                              </div>

                            </div>
                            {
                              propertyStructs.length > ZERO ?
                                  <button
                                      type="button"
                                      onClick={() => handleRemove(index, propertyStructs, setPropertyStructs)}>
                                    Remove Property
                                  </button> :
                                  <></>
                            }
                          </div>
                          <div>
                            {
                              propertyStructs.length - ONE === index ?
                                  <button
                                      type="button"
                                      onClick={() => handleResidentialPropertyAdd(index)}>
                                    Add Residential Property
                                  </button> :
                                  <></>
                            }
                          </div>
                        </div>
                    ))
                  }
                </div>
              </div>

            </div>
            <div className="d-flex flex-column align-items-center">
              <div className="row">
                <button type="submit" className="client-form__submit-btn mx-4">Submit Form</button>
              </div>
            </div>
          </form>
        </div>
      </>
  )
}

export default App