How to sort and create a new object with own properties

Implement the function named sortProducts that takes one parameter (matrix), which is an array of arrays.

[
  [
    { product: "MacBook", price: 1019, category: 'tech'},
    { product: "Cheerios", price: 5, category: 'food'},
  ],

  [

    { product: "Snickers", price: 1.5 , category: 'food'},
    { product: "Air Pods", price: 129, category: 'tech'},
  ],

]
  • The function should loop over the (matrix) and create a new object
    containing the products sorted by their category.

  • The function should then return back this result object containing
    sorted products, stored in properties tech and food.

    result {
    tech: [ { tech product }, { tech product } ],
    food: [ { food product }, { food product } ],
    }

Why is my image not being displayed in React? [duplicate]

In my React app I’m trying to display an image in the project’s directory. In the browser that image is being displayed as the Google Chrome default image when a file cannot be found. Could someone tell me if I’m importing my image correctly?

Component trying to render the image:

import React from "react";
import "../css/navbar.css";

export default function Navbar() {
    return (
        <div className="navbar-container">
            <img src="../images/logo.png" className="logo" />
        </div>
    );
}

What I’m seeing:

enter image description here

How to declare prop default in Storybook without using defaultProps?

I am not using React’s .defaultProps system and instead relying on spreading my default props into my provided props:

type PropTypes = {
  /** My property desc */
  someProp?: boolean
}

const defaultProps = {
  someProp: true
}

const MyComponent = (incomingProps: PropTypes) => {
  const props = {
    ...defaultProps,
    ...incomingProps
  }

  return props.someProp ? <div /> : <span />
}

I am using storybook-addon-react-flow-docgen to look at my Flow code and extract the props and their types which then passes the data to react-docgen which renders most of it correctly:

enter image description here

However the default value is not extracted properly because the plugin has no clue about my default props.

How can I declare the default values for props?

I tried:

type PropTypes = {
  /**
   * Some description.
   * @default true
   */
  someProp?: boolean
}

I looked into how TypeScript does it and it also doesn’t seem to work. Every addon expects you to use .defaultProps.

Array of model in mongoose

I am using typescript and my code looks like:

const tournamentsYearWiseModel = new Schema<TournamentsYearWiseType>({
  year: { type: String, required: true },
  tournaments: {
    type: [Schema.Types.ObjectId],
    ref: "Tournament",
    required: true,
  },
});
const teamModel = new Schema<TeamType>({
  id: { type: String, required: true },
  name: { type: String, required: true },
  name_abbr: { type: String, required: true },
  country: { type: String, required: true },
  tournaments: { type: [tournamentsYearWiseModel] }, // This is what I want to achieve
});

So basically, I want an array of mongoose model. But my typescript throws me an error, I just want to know whether this is the right way.

The error typscript throws is:

Type '{ type: Schema<TournamentsYearWiseType, Model<TournamentsYearWiseType, any, any, any>, {}, {}>[]; }'
 is not assignable to type 'SchemaDefinitionProperty<TournamentsYearWiseType>'.

Unable to Retrieve the error message even if status is correct on ajax get request

I am not getting the error message intended after the ajax request call; status is retrieving correctly on the console. Getting a warning

perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
at PaperFormPage

import React, { useState, useEffect } from 'react';
import TextboxScannerElement from './TextboxScannerElement';

export default function PaperFormPage(props) {
  const [pageUserInput, setPageUserInput] = useState([]);
  const [hasError, setHasError] = useState(false);
  const [errorMessage, setErrorMessage] = useState('');

  useEffect(() => {
    if (props.pageData !== undefined) {
      setPageUserInput([...props.pageData]);
    }
  }, [props.pageData]);

  // element = TextboxElement name
  function onUserInput(element, value) {
    setErrorMessage('');
    setHasError(false);

    if (typeof element === 'string') {
      let pageUserInputCopy = [...pageUserInput];
      let index = pageUserInputCopy.findIndex((obj) => obj.key === element);
      let itemCopy = { ...pageUserInputCopy[index] };

      itemCopy['userInput'] = value;
      pageUserInputCopy[index] = itemCopy;

      setPageUserInput(pageUserInputCopy);
    }
  }

  function isValid(userInput) {
    const vall=0;
    if (!/^[a-zA-Z0-9]+$/.test(userInput)) {
      setErrorMessage('Cannot contain non-alphanumeric characters.');
      setHasError(true);
      return false;
    }

    if (!/^.{10,}$/.test(userInput)) {
      setErrorMessage('Must be at least 10 characters in length.');
      setHasError(true);
      return false;
    }

    if (!userInput.startsWith('HBCD')) {
      setErrorMessage('Paper Form ID must begin with "HBCD".');
      setHasError(true);
      return false;
    }
    checkCodeExists(userInput)
  .then((result) => {
      console.log(result);
      if (result.status != 200) {

        setErrorMessage('Paper Form ID must begin with "HBCD".');
        setHasError(true);
        return false;
        return;
      }
    })

    return true;
  }

  function handleSubmit(e) {
    if (isValid(pageUserInput[0].userInput)) {
      props.updatePageData(pageUserInput);
      props.nextStep();
    }
  }

  function checkCodeExists(userInput)
  {
    let code=encodeURIComponent(userInput);
    return fetch(
      `/biosample/ajax/validateScannableCode.php?scannable_code=${code}`,
      {
        credentials: 'include',
        method: 'GET',
      }
    ).then((res) => {
      return res.json().then((json) => {
        return {
          status: res.status,
          json: json,
        };
      });
    });
  }

  const form =
    pageUserInput.length === 0 ? null : (
      <TextboxScannerElement
        keyStr={pageUserInput[0].key}
        label={pageUserInput[0].label}
        name={pageUserInput[0].key}
        onUserInput={onUserInput}
        value={pageUserInput[0].userInput}
        errorMessage={errorMessage}
      />
    );

  return (
    <>
      <div className="instructions">
        <strong>Instructions:</strong>
        <p>Scan the Paper Form found in the kit.</p>
      </div>
      <FormElement
        className="FormElement"
        name="form"
        fileUpload={false}
        onSubmit={handleSubmit}
        onUserInput={onUserInput}
      >
        {form}
        <ButtonElement label="Next" onUserInput={onUserInput} />
      </FormElement>
    </>
  );
}

Github Pages won’t load images I try to get using jquery after my website builds

first time posting to stack overflow so formatting might be wonky 🙂

Main problem: Github Pages won’t load images I try to get using jquery after my website builds

Details: I’m trying to build a portfolio website, the page loads and loads some textures and assets (mostly images) correctly. It even loads some of the images I try to get in my problem but only when I hard code it into my index.html. The problem comes after, currently, I have a carousel that I want to load images into dynamically (jquery script goes to the folder and grabs all the images in it and loads it onto the carousel). But this script keeps failing and I get a (example)”Failed to load resource: the server responded with a status of 404 ()
/assets/images/General/:1″ Error.

Note: everything is working correctly on VSCode local server.

Jquery Code (runs correctly locally):

let imgDir = "../assets/images/General/";
$(document).ready(function () {
  $.ajax({
    url: imgDir,
    success: function (data) {
      console.log(data);
      $(data)
        .find("a")
        .attr("href", function (i, val) {
          // Gets all image types
          if (val.match(/.(jpe?g|png|gif)$/)) {
            // Used to remove the file path to get image name
            let start, end;
            for (let i = val.length - 1; i >= 0; i--) {
              if (!end && val[i] == ".") {
                end = i;
              } else if (!start && val[i] == "/") {
                start = i + 1;
              } else if (start && end) {
                break;
              }
            }
            // Creates carousel elements to show images and names
            $(".names-track").append(
              '<li class="slide-name"><h3>' +
                val.slice(start, end).replace("%20", " ") +
                "</h3></li>"
            );
            $(".carousel-track").append(
              ' <li class="carousel-slide current-slide"><img class="carousel-image" src="' +
                val +
                '" alt=""/></li>'
            );
            $(".carousel-nav").append(
              '<button class="carousel-indicator"></button>'
            );
          }
        });
      // Builds the carousel with the data
refreshCarousel(document.querySelector(".projects-carousel"));
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      console.log("Status: " + textStatus);
      console.log("Error: " + errorThrown);
    },
  });
});

Things I’ve tried:

Make sure the case in my path is correct (should be since I can already load some of the same images by hand).

Tried adding a .nojekyll file [now removed] (heard that can be used to bypass jekyll build which would mess up loading of some assets and folders).

Tried changing path and folder structure.

Current folder structure:

  • Main Folder
    • assets
      • css
      • images
        • General
          • images.png here
        • Highlighted Projects
          • images.png here
        • Projects
          • images.png here
        • textures
          • images.png (loads before the page is displayed)
      • js
    • HTML
      • index.html
    • index.html (dummy file that calls the index.html in HTML folder) [is loading correctly]

It probably has something to do with how I’m using jquery or the fact that I’m trying to load the images after my main page is built and displayed but I want to be able to load these images into the carousel dynamically since I can just add an image in the folder in the future and it would load.
Again I can already load some of the images by hand so the paths have to be correct. I just can’t load them after the window loads.

Tried to google for hours but haven’t found a question similar to mine. So I had to post.

Thanks For Reading!

Edit: Forgot to add in the post but the success function in the jquery function never gets called (checked through some testing).
Also I’m very new to jquery (currently on my list to learn) and got that code from another stackoverflow question so I don’t fully understand the language.

Integrating URL.createObjectURL in to VBA?

Attempting a ‘POST’ XMLHTTP request to action based on a blob URL created by an interactive userform on a webpage (that specifically generates a URL based on a selected item from a filename). Realize that string is created from the browser session/interaction, but is there an easier way to do this?

Ultimately, trying to take a static filepath/filename and create a URL from that, which is applicable for a ‘POST’ that takes action based on the URL.

Appreciate any help, in advance.

How can I read a local file with a fixed path in Javascript? I only have the location of the file as a string. NO HTML forms allowed

I am creating a web app where I already know the location of a file that needs to be uploaded. Note that all I have is the path (example: Users/username/Downloads or Users/username/Documents) or something like that. How can I get Javascript to read that file as a File object or as a binary string so that I can POST it to a server.

Additionally, this file is not a simple file like a JSON or a txt file. This file would usually be a Microsoft Word file.

Why SVG is not rendered in NEXTJS project after deploying on vercel

I had created a showcase single page nextJS application styled with Tailwind CSS. I am adding the background of a component SectionWrapper as an svg file.

I had created a custom class in global.css using @layer utility like this

@layer components {
  .banner {
    @apply bg-[url('../assets/banner.svg')] bg-no-repeat w-full bg-cover bg-center h-full;
  }

  .banner02 {
    @apply bg-[url('../assets/banner02.svg')] bg-no-repeat w-full bg-cover bg-center h-full;
  }
  .
  .
}

And using them in my index.js like this where I’m passing banner as props.

.
.
.
<Sectionwrapper
        title="Creative way to showcase the store"
        description="The app contains two screens. The first screen list all NFTs while the second shows the details of a specific NFT."
        mockupImg={assets.mockup.src}
        banner="banner02"
      />
.
.
.

And in sectionWrapper component, it is used as ${banner} in the first div.

import React from "react";
import assets from "../assets";
import Button from "./Button";

const Sectionwrapper = ({
  title,
  description,
  showBtn,
  banner,
  mockupImg,
  reverse,
}) => {
  return (
    <div
      className={`min-h-screen flex justify-center items-center p-16 sm:p-8 ${banner} ${
        reverse ? "bg-white" : "bg-primary"
      }`}
    >
      <div
        className={`flex items-center w-11/12 sm:w-full minmd:w-3/4 ${
          reverse
            ? "flex-row-reverse md:flex-col-reverse fadeRightMini"
            : "flex-row md:flex-col fadeLeftMini"
        } `}
      >
        .
        .
        .
        </div>
      </div>
    </div>
  );
};

export default Sectionwrapper;

ISsue

The SVGs are working fine in the local environment. But on the deployed environment of Vercel and Netlify , the SVG is not rendering. It is working fine in localhost but not in production.

in local env

local

on vercel/netlify

vercel

More resources

Github link here

Vercel link/Live Demo here

Cancel button for pop up message before delete not functioning

I’ve facing problem where, when the confirmation message appear, I click the cancel button, the data will be also deleted. Can someone suggest where need to be fix? Below is the code.

echo “<a onClick=’myFunction()’ href=’./delete.php?userID=”.$row[‘userID’] .”‘>Delete”;

    <script> 
        function myFunction() {
            $r = confirm("OK to delete?");
            if ($r == false) {
                return false;
                } 
        }
    </script>

How to detect if a child have a specific className in React js

I’m trying to add a className to the ul element if contains a child with an specific className. Using only css it’s not possible (it’s :has but only in css 4). I’m trying to made this with react but I can’t figure it out.

const MenuLink = () => (
<ul className="parent">
    <li>
        <NavLink activeClassName="is-active" className="link">
            link 3
        </NavLink>
    </li>
    <li>
        <NavLink activeClassName="is-active" className="link">
            link 3
        </NavLink>
    </li>
    <li>
        <NavLink activeClassName="is-active" className="link">
            link 3
        </NavLink>
    </li>
</ul>

);

I want to add a class to the ul if .is-active is present in a children.

How can I efficiently parse this large text file of Q&A?

I have a large text file in the following format with about 300 entries. Each Entry starts with “QUESTION #” text followed by the actual question, then the choices and an optional explanation.

QUESTION 1
What color is the Sky?

A. Blue
B. Red
C. Yellow 
D. Green 
E. Orange

Answer: A   

The sky is blue due to a phenomenon called Raleigh scattering. This scattering refers to the scattering of electromagnetic radiation (of which light is a form) by particles of a much smaller wavelength.
        

QUESTION 2
What's the name of our galaxy?

A. M&Ms
B. Chocolate Bear
C. Milky Way
D. Caramel Cluster
   
Answer: C

Since prehistoric times, human beings have looked up at at the night sky and pondered the mystery of the band of light that stretches across the heavens. And while theories have been advanced since the days of Ancient Greece as to what it could be, it was only with the birth of modern astronomy that scholars have come come to know precisely what it is – i.e. countless stars at considerable distances from Earth.

The term “Milky Way”, a term which emerged in Classical Antiquity to describe the band of light in the night sky, has since gone on to become the name for our galaxy. Like many others in the known Universe, the Milky Way is a barred, spiral galaxy that is part of the Local Group – a collection of 54 galaxies. Measuring 100,000 – 180,000 light-years in diameter, the Milky Way consists of between 100 and 400 billion stars.

QUESTION 3
What's the best dessert?

A. Appie Pie
B. Chocolate Cake
C. Rice Pudding
D. Blueberry Muffin
   
Answer: D

What’s the most efficient way to parse the above in Java, Kotlin (or in any other language) and then convert them into a list of Questions i.e List<Question

data class Question(
val id:Float, 
val question: String, 
val choices: List<Choice>,
val explanation: String?
)

data class Choice(
val choice:String,
val isCorrect: Boolean
)

Simon Game Challenge not Functional Written Code for Mobile and Tablet View

I just want to ask for help for the Simon Game Challenge Activity. The code works well in a Desktop View, but in Mobile and Tablet View it is not functional since there no “Press Key to Start” unlike in Desktop, we have a external keyboard to press a key. Hoping for the help! Thank you. Here is the written code:

HTML

 <body>
  <section>

  <div class="backgroundContainer1">
    <div class="pressKeyPadding">
      <h1 id="level-title">Press Key <br> to Start</h1>
    </div>

    <div class="buttonPadding">
      <div class="grid-container1">
        <div type="button" id="red" class="btn red"></div>
        <div type="button" id="yellow" class="btn yellow"></div>
        <div type="button" id="green" class="btn green"></div>
        <div type="button" id="blue" class="btn blue"><div>
      </div>
    </div>

    <div class="flex-container1">
      <a class="myButton" href="index.html">HOME  </a>
    </div>
  </div>

JS

    var buttonColours = ["red", "blue", "green", "yellow"];
    var gamePattern = [];
    var userClickedPattern = [];
    var started = false;
    var level = 0;
    
    $(document).keypress(function () {
      if (!started) {
        $("#level-title").text("Level " + level);
        nextSequence();
        started = true;
      } else {
        startOver();
      }
    });

$(".btn").click(function () {
  var userChosenColour = $(this).attr("id");
  userClickedPattern.push(userChosenColour);
  playSound(userChosenColour);
  animatePress(userChosenColour);
  checkAnswer(userClickedPattern.length - 1);
});
function checkAnswer(currentLevel) {
  if (gamePattern[currentLevel] === userClickedPattern[currentLevel]) {
    console.log("Correct");
    if (userClickedPattern.length === gamePattern.length) {
      setTimeout(function () {
        nextSequence();
      }, 1000);
    }
  } else {
    playSound("wrong");
    playSound("wrong");
    $("body").addClass("game-over");
    setTimeout(function () {
      $("body").removeClass("game-over");
    }, 200);
    $("#level-title").text("Game Over, Press Any Key to Restart");
  }
}

function nextSequence() {
  userClickedPattern = [];
  level++;
  $("#level-title").text("Level " + level);
  var randomNumber = Math.floor(Math.random() * 4);
  var randomChosenColour = buttonColours[randomNumber];
  gamePattern.push(randomChosenColour);

  $("#" + randomChosenColour)
    .fadeIn(100)
    .fadeOut(100)
    .fadeIn(100);
  playSound(randomChosenColour);
}

function animatePress(currentColor) {
  $("#" + currentColor).addClass("pressed");
  setTimeout(function () {
    $("#" + currentColor).removeClass("pressed");
  }, 100);
}

function playSound(name) {
  var audio = new Audio("sounds/" + name + ".mp3");
  audio.play();
}

function startOver() {
  console.log("starting Over");
  level = 0;
  gamePattern = [];
  started = false;
  $("#level-title").text("Level 0");
  nextSequence();
}

CS

 /* Colors */
    .game-over {
      background-color: red;
      opacity: 0.8;
    }
    .red {
      background-color: #ff595d;
    }
    .green {
      background-color: #8bc926;
    }
    .blue {
      background-color: #1982c4;
    }
    .yellow {
      background-color: #ffc939;
    }
    .pressed {
      box-shadow: 0 0 20px white;
      background-color: grey;
    }

Is it safe to use eval for a client-side JavaScript calculator

I was making a calculator which is served as a static html page to the user’s browser. The page is not designed to submit any information back to the server. Nothing else will be present on the web page except for this calculator.

Is it safe to use “eval” in this scenario? Or put another way, does the use of eval in this case cause additional security risk?

To me, it doesn’t seem like the user can do anything nefarious with this page they can’t do by simply opening the browsers development tools. I have always read “never” use eval, but in this case, it seems like it makes good sense.

Here is an example calculator:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Calculator</title>
</head>

<body>
    <input id="input" type="text">
    <button onclick="{
        let result= '';
        try {
            result = eval(document.getElementById('input').value);
        } catch (error) {
            result = error;
        }
        console.log(result);
        document.getElementById('result').innerHTML=result;
        }">calculate</button>
    <div id="result">result here</div>
</body>

</html>