Array Of Objects with data of exams submitted, how can I get the average grade of each student in an array?

Let’s say I have an array of objects that contain information about all the exams submitted during a period of time. It’s structure’s like this:

[
    { name: 'Freddy', grade: 10, date: '20/07/2022' },
    { name: 'Jose', grade: 8, date:'20/07/2022' },
    { name: 'Freddy, grade: 8', date: '25/07/2022' },
    { name: 'Daniel', grade: 5, date: '21/07/2022' },
    { name: 'Jose', grade: 5 }, date: '22/07/22',
  ]

What I need is to ignore the date value and just calculate the average grade of each student and get a simple array like this:

[9, 6.5, 5]

Now let’s say I want the array to follow a specific order so how can I rearrange it following this order: Freddy -> Jose -> Daniel ?

It seems kind of weird but I kind of need the output to be like this in order to use it as a dataset for Chart.js later on.

How to match and extract string matching regular expression

This is main string:

MR HI Government He PIHe9 Hanumana Ji 3-� fafer/ DOB : 01/01/1959 989 / Male 2094 7051 9541 ������ - ��� ����� �� 3�1���

I want to match and extract 2094 7051 9541 using regular expression

and regex pattern to find is:

^[2-9]{1}[0-9]{-3}\s[0-9]{4}\s[0-9]{4}$

I want to use javascript to match and extract string. But not able to find right syntax to it.

Any help would be appreciated.

Thanks,
PD

Looping Over And Array of Objects and Updating Each One

I’m trying to update objects inside an array based on specific conditions that I check using two functions. I couldn’t achieve this with the match feature available in mongoose.

As you can see below, I’m trying to loop over the array of posts, send each post and check if it fulfills a condition, then update it using findOneAndUpdate. The functions isLessThanOne and isAchieved return the expected value.

(async () => {

  let posts = await Post.find()

  posts.map(async (post) => {
    if (isLessThanOneDay(post.deadline)) {
      console.log(post.id, post._id)
      await Post.findOneAndUpdate(post.id, { $set: { category: 'deadline' }})
    } else if (isAchieved(post.milestones)) {
      await Post.findOneAndUpdate(post.id, { $set: { category: 'achieved' }})
    } else {
      await Post.findOneAndUpdate(post.id, { $set: { category: 'newGoals' }})
    }
  })
  
})()

This is the schema

const { type } = require("express/lib/response")
const mongoose = require("mongoose")

const PostSchema = new mongoose.Schema({
    // we have to link or refer each post to a user
    user: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "user",
    },
    title: {
        type: String,
        required: true
    },
    desc: {
        type: String
    },
    milestones: [],
    likes: [
        {
            user: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "user"
            },
            fName: {
                type: String,
                required: true
            },
            date: {
                type: String,
                required: true
            }

        }
    ],
    comments: [
        {
            user: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "user"
            },
            text: {
                type: String,
                required: true
            },
            fName: {
                type: String,
            },
            date: {
                type: String,
            }
        }
    ],
    rewards: [
        {
            user: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "user"
            },
            fName: {
                type: String,
                required: true
            },
            date: {
                type: String,
                required: true
            },
            reward: {
                type: String,
                required: true
            },
            price: {
                type: Number,
                required: true
            }
        }
    ],
    date: {
        type: String,
        required: true
    },
    shares: [
        {
            user: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "user"
            },
            fName: {
                type: String,
                required: true
            },
            date: {
                type: String,
                required: true
            }

        }
    ],
    deadline: {
        type: String,
        required: true
    },
    category: {
        type: String,
    }


}) 

module.exports = Post = mongoose.model('post', PostSchema)

The problem is that I couldn’t update the posts and I’ve already tried using udpate, directly updating it with post.category then save. Any help would appreciated.

handing focus from input element to button

On clicking a button, I want an input element to get focus. When the input element looses focus, I want the button to receive focus. Here is a simple example.

   <body>
    <button id="b1"
            onclick="document.getElementById('i1').focus();">1</button>
    <input id="i1" type="text"
           onblur="document.getElementById('b1').focus();"/>
    <button id="b2"
            onclick="document.getElementById('i2').focus();">2</button>
    <input id="i2" type="text"
           onblur="document.getElementById('b2').focus();"/>
  </body>

When I click any of the buttons, the input element gets focus. This works as desired. When I leave any of the two inputs by clicking on the canvas, the focus does not go to the button. This is my main issue.

When I leave the first input with tab, all browsers pass the focus to the first button. But when I leave the second button with tab, only firefox passes the focus to the second button. Chrome and opera don’t show a focus. I am puzzled as to why the second button is treated differently.

Redux – Can’t Update Product Quantity that is already in the Cart but instead it Creates the Object again

When I add the product to the cart and then I add another one, then if I try to add the first one again it doesn’t increase only the quantity but it creates a new object for this product; how can I fix it

 switch (action.type) {
    case actionTypes.ADD_TO_CART:
      const product = state.products.find((p) => p.id === action.payload.id);
      const inCart = state.cart.find((item) =>
        item?.product.id === action.payload.id ? true : false
      );

      if (inCart) {
        let check = false;
        state.cart.map((item, key) => {
          if (
            item.product.id === action.payload.id &&
            item.setVar === action.payload.setVar
          ) {
            state.cart[key].quantity++;
            check = true;
          }
        });
        if (!check) {
          const newItem = {
            product: product,
            setVar: action.payload.setVar,
            quantity: 1,
          };
          state.cart.push(newItem);
        }
      } else {
        const newItem = {
          product: product,
          setVar: action.payload.setVar,
          quantity: 1,
        };
        state.cart.push(newItem);
      }
      return {
        ...state,
      };

  }

Rollupjs not including function in bottom line export command of index.js

I’m using rollupjs and my function “clone” is appearing in the outputted index.js but not in the bottom line export. This means that clients can’t get to it.

dist/esm/index.js
enter image description here

I’ve noticed tsc is working though beceause its included in the typescript declaration file

dist/index.d.ts
index.d.ts

my rollup config file

const packageJson = require("./package.json");

const EXTERNAL = Object.keys(packageJson.devDependencies);

let includePathOptions = {
    include: {},
    paths: ['src/components', 'src/utils'],
    external: EXTERNAL,
    extensions: ['.ts', '.tsx', '.html']
};

export default [
  {
    input: "index.ts",
    output: [
      {
        file: packageJson.module,
        format: "esm",
        sourcemap: true,
      },
    ],
    plugins: [
      includePaths(includePathOptions),
      peerDepsExternal(),
      resolve(),
      commonjs(),
      typescript({ tsconfig: "./tsconfig.json" }),
    ],
    external: EXTERNAL
  },
  {
    input: "dist/esm/types/index.d.ts",
    output: [{ file: "dist/index.d.ts", format: "esm" }],
    external: EXTERNAL,
    plugins: [dts()],
  },
];

my clone function is like so:

import { CloneMode } from "./enums";

const clone  = <T>(obj: T, mode?: CloneMode) : T => {
    // if it's deep we'll write it out as a sting then rencode it
    if (mode == CloneMode.Deep) {
        return JSON.parse(JSON.stringify(obj));
    } else {
        if (obj instanceof Array) {
            if (mode == CloneMode.Iterate) {
                let tmp: any[] = []
                obj.forEach((elem) => tmp.push(elem))
                //@ts-ignore : This will work
                return tmp;
            } else {
                return JSON.parse(JSON.stringify(obj));
            }
        } else {
            return { ...obj };
        }
    }    
}

export { clone }

how does the bottom line export get generated? and how can i make the index.js be the same as the index.d.ts

chrome.storage.local.set() is not working properly

I’m having a difficult time dealing with chrome storage. I’ve looked at the latest documentation for chrome storage and have the following code (this is a code snippet inside an ajax call success function, info.userName is a value returned by my backend program):

chrome.storage.local.set({ "userName": info.userName }, () => {
    chrome.storage.local.get("userName", function(data) {
        console.log(data.userName)
    });
});

but the console.log() always returns undefined, while I’m pretty sure that info.userName has a value. I’ve also tried this which is not working as well:

chrome.storage.local.set({ "userName": info.userName });
chrome.storage.local.get("userName", function(data) {
    console.log(data.userName)
});

It seems that the set function doesn’t save anything locally, does anyone has any thought about this?

why isnt this code working? i just learned how to use js with html and css so im confused

heres the link to the website if you wanna see how it works https://mini-2.kodewithklossy.repl.co/
its supposed to show the original facts then use the button to switch between both fact pages

var par1 = $('.p1');
var par2 = $('.p2');
var par3 = $('.p3');
var button = $('button');
var picture = $('img')
var body = $('body')

button.on('click', showFacts);
button.on('click', hideFacts);

function showFacts () {
  Header.text('Tree Facts');
  par1.text('Trees can help to reduce stress');
  par2.text("Trees are the longest living organisms on Earth, and never die of old age.");
  par3.text('Planting trees can help reduce your energy costs.');
  picture.attr('src', 'https://cdn.shopify.com/s/files/1/0212/1030/0480/products/91cnlaObmbL._SL1500.jpg?v=1627168523');
  button.text('hide the secrets!');
  Header.css('color', 'darkolivegreen');
  button.css('background-color', 'darkolivegreen');
  body.css('background-color', 'lightsalmon');
  button.css('border', '2px', 'solid', 'black');
  
};

function hideFacts() {
  Header.text('Puppy Facts');
  par1.text('They spend 15–20 hours a day sleeping.');
  par2.text('Puppies can be twins!');
  par.text('Puppies become adults when they turn one.');
  picture.attr('src', 'https://www.cbc.ca/kidscbc2/content/the_feed/fact-2-puppies-sleep-compressor.jpg');
  button.text('show me the secrets!');
  Header.css('color', 'mediumblue');
  button.css('background-color', 'cornflowerblue');
  body.css('background-color', 'white');
  button.css('border', '2px', 'solid', 'mediumblue' );
}; ```

NextJS – React google maps api – infinite loop

trying to figure out why my react function component map is infinite looping and continuously rerendering the map. i’ve stared at this for a while and am thinking it has to do with the useEffects but I can’t seem to fix it.. attached is screenshot of error and the map component code. let me know if you need to see other code

screenshot of error

  useJsApiLoader,
  GoogleMap,
  DirectionsRenderer,
} from "@react-google-maps/api";
import { useEffect, useState } from "react";
import { useRouter } from "next/router";
import { Box } from "@chakra-ui/react";
import { useDebouncedCallback } from "../../hooks/useDebouncedCallback";

export default function Map(props) {
  const router = useRouter();
  const { isLoaded } = useJsApiLoader({
    googleMapsApiKey: process.env.NEXT_PUBLIC_GOOGLE_MAPS_API_KEY,
    id: "google-map-script",
  });

  const [map, setMap] = useState(/** @type google.maps.Map */ (null));
  const [directionsResponse, setDirectionsResponse] = useState(null);

  async function calculateRoute() {
    /* eslint-disable */
    const directionsService = new google.maps.DirectionsService();
    /* eslint-disable */
    const results = await directionsService.route({
      origin: props.from,
      destination: props.to,
      /* eslint-disable */
      travelMode: google.maps.TravelMode.DRIVING,
    });

    console.log(results);
    setDirectionsResponse(results);
  }

  useEffect(() => {
    console.log("useEffect fired!", { asPath: router.asPath });
    calculateRoute();
  }, [router.asPath]);

  useEffect(() => {
    calculateRoute();
  });

  if (!isLoaded) {
    return <div>ligma</div>;
  }
  return (
    <GoogleMap
      center={directionsResponse}
      zoom={15}
      mapContainerStyle={{
        width: props.width,
        height: props.height,
        borderRadius: "20px",
      }}
      options={{
        zoomControl: false,
        streetViewControl: false,
        mapTypeControl: false,
        fullscreenControl: false,
      }}
      onLoad={(map) => setMap(map)}
    >
      <DirectionsRenderer directions={directionsResponse} />
    </GoogleMap>
  );
}

how to run $.ajax on node.js

How to use $.ajax() on node.js

 function check_js(a, b) {
    const access_key = a;
    const accnum = b;
    if (access_key.length != 32) {
        system_message_alert('', "show error msg");
        return false;
    }


    $.ajax()
}

This is python execjs code :

import execjs

#json_data = {"act":"Display/initial/Display/initial/abe2d445e9a8d18e7c684cb3e7e8d5d7/226672"}

with open('test.js',encoding='utf-8') as f:
    js_code = f.read()
#print(js_code)
ctx = execjs.compile(js_code)
encode_data = ctx.call('check_js','abe2d445e9a8d18e7c684cb3e7e8d5d7','226672')
print(encode_data)

when i run the python3 code ,the console will show this error:

execjs._exceptions.ProgramError: ReferenceError: $ is not defined

Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse () at onFileUploadSuccess at xhr.onreadystatechange

I’m trying to make an online file-sharing system, I’m taking help from these two youtube videos while doing so: https://youtu.be/CwnViYV4gM0 and https://youtu.be/_xKCi5OI_Mg

I’m doing things exactly the same, with a few modifications to my need, but as I’ve come to the end of the project I’m facing an error that I cannot understand fully and debug. the error says Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse

The error is coming from the index.js file of the frontend system, as shown in the google chrome inspector tab:

Screenshot of the problem

The entire code to my index.js is this:

const dropZone = document.querySelector(".drop-zone");
const fileInput = document.querySelector("#fileInput");
const browseBtn = document.querySelector("#browseBtn");

const bgProgress = document.querySelector(".bg-progress");
const progressPercent = document.querySelector("#progressPercent");
const progressContainer = document.querySelector(".progress-container");
const progressBar = document.querySelector(".progress-bar");
const status = document.querySelector(".status");

const sharingContainer = document.querySelector(".sharing-container");
const copyURLBtn = document.querySelector("#copyURLBtn");
const fileURL = document.querySelector("#fileURL");
const emailForm = document.querySelector("#emailForm");


const toast = document.querySelector(".toast");

const baseURL = "https://share-app-proj.herokuapp.com";
const uploadURL = `${baseURL}/api/files`;
const emailURL = `${baseURL}/api/files/send`;

const maxAllowedSize = 100 * 1024 * 1024; //100mb


browseBtn.addEventListener("click", () => {
  fileInput.click();
});

dropZone.addEventListener("drop", (e) => {
  e.preventDefault();
  //   console.log("dropped", e.dataTransfer.files[0].name);
  const files = e.dataTransfer.files;
  if (files.length === 1) {
    if (files[0].size < maxAllowedSize) {
      fileInput.files = files;
      uploadFile();
    } else {
      showToast("Max file size is 100MB");
    }
  } else if (files.length > 1) {
    showToast("You can't upload multiple files");
  }
  dropZone.classList.remove("dragged");
});

dropZone.addEventListener("dragover", (e) => {
  e.preventDefault();
  dropZone.classList.add("dragged");

  // console.log("dropping file");
});

dropZone.addEventListener("dragleave", (e) => {
  dropZone.classList.remove("dragged");

  console.log("drag ended");
});

// file input change and uploader
fileInput.addEventListener("change", () => {
  if (fileInput.files[0].size > maxAllowedSize) {
    showToast("Max file size is 100MB");
    fileInput.value = ""; // reset the input
    return;
  }
  uploadFile();
});

// sharing container listenrs
copyURLBtn.addEventListener("click", () => {
  fileURL.select();
  document.execCommand("copy");
  showToast("Copied to clipboard");
});

fileURL.addEventListener("click", () => {
  fileURL.select();
});

const uploadFile = () => {
  console.log("file added uploading");

  const files = fileInput.files[0];
  const formData = new FormData();
  formData.append("myfile", files);

  //show the uploader
  progressContainer.style.display = "block";

  // upload file
  const xhr = new XMLHttpRequest();

  // listen for upload progress
  xhr.upload.onprogress = function (event) {
    // find the percentage of uploaded
    let percent = Math.round((100 * event.loaded) / event.total);
    progressPercent.innerText = percent;
    const scaleX = `scaleX(${percent / 100})`;
    bgProgress.style.transform = scaleX;
    progressBar.style.transform = scaleX;
  };

  // handle error
  xhr.upload.onerror = function () {
    showToast(`Error in upload: ${xhr.status}.`);
    fileInput.value = ""; // reset the input
  };

  // listen for response which will give the link
  xhr.onreadystatechange = function () {
    if (xhr.readyState == XMLHttpRequest.DONE) {
      onFileUploadSuccess(xhr.responseText);
    }
  };

  xhr.open("POST", uploadURL);
  xhr.send(formData);
};

const onFileUploadSuccess = (res) => {
  fileInput.value = ""; // reset the input
  status.innerText = "Uploaded";

  // remove the disabled attribute from form btn & make text send
  emailForm[2].removeAttribute("disabled");
  emailForm[2].innerText = "Send";
  progressContainer.style.display = "none"; // hide the box

  const { file: url } = JSON.parse(res);
  console.log(url);
  sharingContainer.style.display = "block";
  fileURL.value = url;
};

emailForm.addEventListener("submit", (e) => {
  e.preventDefault(); // stop submission

  // disable the button
  emailForm[2].setAttribute("disabled", "true");
  emailForm[2].innerText = "Sending";

  const url = fileURL.value;

  const formData = {
    uuid: url.split("/").splice(-1, 1)[0],
    emailTo: emailForm.elements["to-email"].value,
    emailFrom: emailForm.elements["from-email"].value,
  };
  console.log(formData);
  fetch(emailURL, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(formData),
  })
    .then((res) => res.json())
    .then((data) => {
      if (data.success) {
        showToast("Email Sent");
        sharingContainer.style.display = "none"; // hide the box
      }
    });
});

let toastTimer;
// the toast function
const showToast = (msg) => {
  clearTimeout(toastTimer);
  toast.innerText = msg;
  toast.classList.add("show");
  toastTimer = setTimeout(() => {
    toast.classList.remove("show");
  }, 2000);
};

Can someone please help me out with this? I’m making this as a university project to showcase in an exhibition, I need this to work. Thank you 🙂

vue-autosuggest output object-object on twice click

by the way this question very similar on Vue algolia autosuggest on select showing [Object object]

but i still did not solve here is my debug or code

<b-form-group
                label="Name Agen"
                label-for="vi-agen-name"
              >
                <span v-text="form.agen.name_agen" />
                <vue-autosuggest
                  id="vi-agen-name"
                  v-model="form.agen.name_agen"
                  :suggestions="[{ data: form.agen.agens }]"
                  :limit="7"
                  :input-props="{
                    id: 'autosuggest__input',
                    class: 'form-control',
                    placeholder: 'Name Agen',
                  }"
                  @selected="onSelectedFrom"
                  @input="searchForm($event, 'agen/', 'agen', 'name_agen')"
                >
                  <template slot-scope="{suggestion}">
                    <span class="my-suggestion-item">{{ suggestion.item.name_agen }}</span>
                  </template>
                </vue-autosuggest>
              </b-form-group>

my problem:

  1. i have on typing yogi on form input

  2. select item that show on suggesstion : [ { data : [ { name_agen : 'Yogi' .....

<span v-text="form.agen.name_agen" /> // output : Yogi

form input // output : yogi

but when i tried to type again on form input yogiabc
thats not show any suggestion so i remove by backspace so the input now is yogi

then i tried select again

the unexpected on twice select :

<span v-text="form.agen.name_agen" /> // output : Yogi // why this result is string

form input // output : object-object // but on form input is an object-object ?

function code:

async onSelectedFrom(option) {
      const model = this.form.currentModel
      const fieldSuggest = this.form.currentFieldSuggest
      const currentLoadData = this.form[`${model}`][`${model}s`]

      const currentField = this.form[`${model}`][`${fieldSuggest}`]
      this.form[`${model}`] = {
        isNew: false,
        [`${model}s`]: currentLoadData,
        ...option.item,
      }
      console.log('selected', this.form[`${model}`], 'Name Agen:', currentField)
    },
    searchForm(keyword, uri, model, currentSuggest) {
      this.form.currentModel = model
      this.form.currentFieldSuggest = currentSuggest
      if (keyword) {
        clearTimeout(this.timeoutDebounce)
        this.timeoutDebounce = setTimeout(() => {
          useJwt.http.get(`${uri}`, { params: { keyword, single_search: true } })
            .then(response => {
// test debug
              if (response.data.total_items === 0) {
                // no data
                this.form[`${model}`].isNew = true
                this.form[`${model}`].user.full_name = null
                this.form.isAgenAndTrans = false
                this.form[`${model}`][`${model}s`] = []
                console.log('no data show', this.form[`${model}`])
              } else {
                // this.form[`${model}`].isNew = false
                this.form.isAgenAndTrans = false
                this.form[`${model}`][`${model}s`] = response.data[`${model}s`]
              }
            }).catch(e => {
              this.form[`${model}`].isNew = true
              this.form[`${model}`].user.full_name = null
              this.form.isAgenAndTrans = false
              this.form[`${model}`][`${model}s`] = []
            })
        }, 300)
      }
    },

Could not establish connection error when sending message from content script to background script in google chrome extension

When I send a message from content to background, I am getting this error in the content script log (chrome console log):

Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.

In the service worker log, nothing is being logged when I send message fronm content. Below are my backgroundScript, contentScript, and my manifest.json. I am using manifest v3.

backgroundScript.js

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
      console.log('request: ', request);
});

contentScript.js

chrome.runtime.sendMessage({ greeting: 'hello' });

manifest.json

{
  "manifest_version": 3,
  "name": "Chrome Extension with React & Webpack",
  "description": "A chrome extension boilerplate built with React 17, Webpack 5, and Webpack Dev Server 4",
  "options_page": "options.html",
  "background": { "service_worker": "background.bundle.js" },
  "action": {
    "default_popup": "popup.html",
    "default_icon": "icon-34.png"
  },
  "chrome_url_overrides": {
    "newtab": "newtab.html"
  },
  "icons": {
    "128": "icon-128.png"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*", "<all_urls>"],
      "js": ["contentScript.bundle.js"],
      "css": ["content.styles.css"]
    }
  ],
  "host_permissions": ["http://*/"],
  "devtools_page": "devtools.html",
  "web_accessible_resources": [
    {
      "resources": ["content.styles.css", "icon-128.png", "icon-34.png"],
      "matches": []
    }
  ]
}

Problemas ao rodar o “`npm start“` em um projeto React.js

Estou tendo o seguinte erro ao executar um projeto em react pela primeira vez:

Failed to compile.

Invalid configuration object. Webpack has been initialized using a configuration object that does not match the API schema.
 - configuration.cache.cacheDirectory: The provided value "C:\Users\isaac\Documents\!REACT\1_INTRO\hello-world\node_modules\.cache" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
   -> Base directory for the cache (defaults to node_modules/.cache/webpack).
 - configuration.module.rules[1].oneOf[3].include: The provided value "C:\Users\isaac\Documents\!REACT\1_INTRO\hello-world\src" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
 - configuration.output.path: The provided value "C:\Users\isaac\Documents\!REACT\1_INTRO\hello-world\build" contains exclamation mark (!) which is not allowed because it's reserved for loader syntax.
   -> The output directory as **absolute path** (required).