Requesting user information from api with axios in react

so I’m doing this assignment and can’t seem to understand how to make the request that I’m being asked to do, the information given is the following (going to be editing the names):

api url: https://this.api.com/entity

api apikey: somePa$$word

and 2 endpoints to get information based on an user info:

/category/userID=11111111

/category/userPassport=20111111113

An example of usage was given: screenshot of example

I’m not really clear on how to write this and so far every post I found doesn’t work.

What I have so far:

const [apiData, setApiData] = useState(null);
  useEffect(() => {
    axios
      .get(
         //testing attaching the endpoint as the example shows?
        'https://this.api.com/entity/category/userID=11111111', 
        {
          headers: {
            Authorization: `Apikey somePa$$word`,
          },
        }
      )
      .then((res) => {
        setApiData(res.data);
        console.log('axios: ' + res.data);
      });
      .catch((error) => {
        console.log('axios: ' + error);
      });
  }, []);

I get these errors in the console: console errors

First time I ask a question here and I hope the info I provided is enough, if anything else is needed pls let me know.

Thanks you

Dynamically calculating total for each column based on selected rows for HTML table using Javascript

html table

From the picture, I am trying to calculate the total of each column for the selected rows a and c. The code works if I unwrap it from the function calculateCols. Is it possible to make it work in the wrapped function. I want to be able to choose a variation of rows to sum for each column without copy and pasting the code and editing it multiple times for each one.

<!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>Document</title>
</head>
<body>
  <table>
    <tbody>
    <tr>
      <td></td>
      <th scope="col">2013</th>
      <th scope="col">2014</th>
      <th scope="col">2015</th>
      <th scope="col">2016</th>
    </tr>
      <tr id="a">
        <th scope="row">a</th>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>4</td>
      </tr>
      <tr id="b">
        <th scope="row">b</th>
        <td>5</td>
        <td>6</td>
        <td>4</td>
        <td>5</td>
      </tr>
      <tr id="c">
        <th scope="row">c</th>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>7</td>
      </tr>
      <tr id="d">
        <th scope="row">d</th>
        <td>5</td>
        <td>6</td>
        <td>8</td>
        <td>5</td>
      </tr>
  
      <tr id="total">
        <th scope="row" id="Total">Total a + c</th>
        
      </tr>
    </tbody>
  </table>
      <script src="checkit.js"></script>
    
</body>
</html>
function calculateCols(ID, calculate) {
  var final = 0
  var tbody = document.querySelector('tbody');
  var howManyCols = tbody.rows[0].cells.length;
  var totalRow = document.getElementById(ID);

  for (var j = 1; j < howManyCols; j++) {
    final = calculate;
    const check = document.createElement('td');
    check.innerText = final;
    totalRow.appendChild(check);
  }
  
    function getRow(rowID) {

      var result = 0;
        
      try {
          var check = document.getElementById(rowID)                
          var thisNumber = parseInt(check.cells[j].childNodes.item(0).data);
             
          if (!isNaN(thisNumber))
              result += thisNumber;
            
      } finally {
      return result;
      }
    }
     
}

calculateCols('total', getRow('a') + getRow('c'));

Importing a js file into a php file and accessing the specified value

I want to import my “createToken.js” file into the “test.php” file and I want to get the Token value in my “createToken.js” file using jquery but i couldn’t do it. I hope you understand what I mean from the code examples below.

createToken.js

const Testing = {

Token: null,
CreateToken: function(){
    return this.Token = "01"; // for test.
},
Init: function(){
    if( this.Token == null ){
        this.CreateToken();
    }
}}

test.php

<script src="assets/js/createToken.js"></script>
<script>
    $(document).ready(() => {
    Testing.Init();
    console.log(Token); // 01
    });
</script>

OnKeyDown event triggers onClick event on another button

I am implementing the list with items and details page(opened on item click)

A user can make it either by mouse click or keyboard navigation. When the user opens details by keyboard navigation the back button should be focused.

I have the following issue:

  1. A user openes the details by keyboard navigation(onKeyDown event on every li item)
  2. The Details page with back button is opened and closed immediately(back button that is is focused is triggered somehow(event shows 3 phase – bubbling)).

The behavior is not reproduced when using e.stopPropagation() or usinf onKeyPress.

Could someone tell why the back button is clicked?

The code representing the behavior: https://github.com/vmashnitskaya/focus-issue

plugin : force google translate to translate injected text

Im an amateur programmer, and recently i discovered how to make plugins for google chrome.
Im using google translate alot to translate between english dutch and arabic.
Now im trying to make a plugin for the google translate website so it will automaticly change the input characters to the correct ones depending on the field im typing in.
(changing keyboard layout is not possible)
Long story short: I managed to change the characters to the correct ones, but google translate doesn not translate the text, unless i press enter or another key that i didnt change.

the code is a bit messy not gone add the whole thing. basicly i used the keypressed and keydown functions to inject the correct characters in the textfield.

What code can i use to force google translate to translate the text?
No translation of injected teks

How to recalculate an object from a nested objects?

I have an object where Citems is an array of Object. Each object has status on or of and time.

{
  Chapter: [
    {
      _id: 624568b157da1d351910c576,
      Cname: 'chapter 1',
      Citems: [{status: 'on', time: 30},{status: 'on', time: 60}],
      
    },
    {
      _id: 62456a5857da1d351910c577,
      Cname: 'chapter 2',
      Mitems: [{status: 'on', time: 30},{status: 'off', time: 60}]
    }
  ],
  _id: 6245f975d17514e0eb9092f7,
  name: 'Something',
  description: 'jfdgljfgdfjgldfkjglfd'
}

I want to generate an array or object from it that show total time for each status like below

{
on: 120,
off: 60
}

I tried with map and reduce but getting confused.

Why JavaScript does not update .offsetWidth [duplicate]

I have a div, which changing its dimensions with transform: scale() on lower resolutions:

var px490 = document.getElementsByClassName("px490")[0];
console.log(px490.offsetWidth); // 490
.px490-parent {
  width: 490px;
  height: 50px;
  background: yellow;
}

.px490-parent>.px490 {
  width: 100%;
}

.px490 {
  transform: scale(0.6);
  /* Turns the object to 294px width */
}
<div class="px490-parent">
  <div class="px490">Hi i'm 490px!</div>
</div>

For some reason the value of var px490 will remain 490, and not 294.

Why?

why return “Promise { }” all the times? [duplicate]

exports.getNews = async (category) =>{ //get a promise from api for display it in mustach template

  exports.fetch_news_from_API =  async (category) => { // get data from api
    /* get data from api*/
    return data.articles; // promise
  }

  exports.getData = async (data) =>{ // add an id for every news
    let finalData = [];
    for(let i = 0; i < data.length; i++){
      let news = {
        id : i,
        title : data[i].title,  //api object
        author : data[i].author,
        description : data[i].description,
        publishedAt : data[i].publishedAt,
      }
      finalData.push(news);
    }
    return finalData; // news
  }
  
  let data = await this.fetch_news_from_API(category);
  let news = await this.getData(data);
  return news; // return pending all the time whene i use it in app.get
}

I would like to use “news” to display it but I can not because it returns all the time “pending”
thank you in advance

React With Other Javascript to Handle Iframe Events [duplicate]

I am rendering an iFrame developed by a different org using:

<script type="text/javascript" src="https://externalUrl/popup.js"></script>
<iframe ref={iframeRef} id="ImportantFrame" src={iframeURL}></iframe>

The iframe contains among other things a close button, which when clicked calls a non-existent ‘closePopUp()` function:

closePopUp function call screenshot

How can I insert my own function into my website which will handle this call if I cannot directly modify the code rendered by the iFrame?

Attempt 1

I tried embedding a function directly into my react code:

function closePopup() {
    console.log('called react script')
}

But that didn’t get called.

Attempt 2

I also tried creating a vanilla JS file with the following:

function closePopup() {
    console.log('called custom script')
}

document.addEventListener("DOMContentLoaded", function(){
    console.log('document loaded')
});

‘document loaded’ did appear on page load confirming that my custom vanilla JS works, but closePopUp() didn’t get called.

Is there a way I can handle the function call without directly modifying the source code inside the rendered iFrame?

How would I loop through two arrays getting all possible combinations to exchange things from each for each other? NodeJS

I’ve been making a bot to trade items on ROBLOX… because apparently that’s a market. Also sorry for the wordy title!

Let me explain a bit, you can trade up to 4 items for 4 other items on ROBLOX, and they all have different values but that’s not important for this.

Currently I have two arrays, my owned items and the other person’s owned items, I need a way of looping through every single possible combination of items that could be traded, for example: (letters represent an item)

  • My offers: a For their: b, d
  • My offers: c, d For their: a, c, d

Like I said, I need a way to find every possible combinations, not just 2 items for 2 items or one item for one item. It needs to be able to find combos like 3 items for 1 item or 2 items for 3 items.

Thanks for any help in advance!

Cheers,
Squid

You are a thief carrying a single bag with limited capacity S. The museum you stole had N artifact that you could stea

Again an Optimization Problem Ended

Description

You are a thief carrying a single bag with limited capacity S. The museum you stole had N artifact that you could steal. Unfortunately you might not be able to steal all the artifact because of your limited bag capacity.

You have to cherry pick the artifact in order to maximize the total value (<= 2000000) of the artifacts you stole.

Constraints

1 <= S <= 2000

1 <= N <= 2000

Output
Output Format

You should output a single integer on one line : the total maximum value from the best choice of artifacts you stole.

Sample Input 1

1
4 5
1 8
2 4
3 0
2 5
2 3
Sample Output 1

13

Hint

The artifact with value 8 and 5 should be picked, summing up the value to the maximum of 13.

index.tsx:24 Uncaught Error: useLocation() may be used only in the context of a component

I am using use location to hide the navbar if the pathname name is /admin, /employee, /publisher. but I got an error saying that Error: useLocation() may be used only in the context of a <Router> component.
This is My App.js

import { BrowserRouter as Router, Routes, Route, useLocation } from 'react-router-dom';
import Navbar from './components/Navbar';


function App() {
  const location = useLocation()

  return (
    <>
      
      <UserState>
      <Router>
      {!["/admin", "/employee", "/publisher"].includes(location.pathname) && <Navbar/>}  //For to hide the navbar if the pathname is /admin, /employee, /publisher
        <Routes onUpdate={() => window.scrollTo(0, 0)}>

          <Route exact path="/" element={<Home />} />
          <Route exact path="/service" element={<Service />} />
          <Route exact path="/contact" element={<Contact />} />
          <Route exact path="/login" element={<Login />} />
          <Route exact path="/reset" element={<Reset />} />
          <Route exact path="/reset/:token" element={<Newpassword />} />
          <Route path="*" element={<NoteFound/>} />

          {/* admin pages */}
          <Route  path="/admin" element={<Admin />}>
          <Route   path="add-project" element={<Addproject />} />
          <Route   path="all-user" element={<AllUser />} />
          </Route>

          {/* Publisher dasboard */}
          <Route  path="/publisher" element={<Publisher />}>
          <Route   path="project-status" element={<ProjectStatus />} />
          <Route  path="allpublise" element={<Allpublise />} />
          </Route>
          
          </Route>
        </Routes>
      </Router>
    </UserState>
    </>
  );
}

export default App;

any help will appreciated

How to toggle div properties by clicking it?

I want to make a window that expands when clicked and closes when clicked again. I am using flask to display all lines of data but that should not be a problem and can actually be ignored. Right now I have it set that when you click the div it expands but once you let go the div closes again. Is there any way I can turn this div into a toggle of some kind many using python or javascript or even CSS?

HTML/Python flask:

<div class="container">
  {%for i, value in verb_data.items() %}
  <div class="indevidual_verbs">{{ i }} . {{ value }}</div><br>
  {%endfor%}
</div>

CSS:

.indevidual_verbs {
    cursor: pointer;
}

.indevidual_verbs:active {
    padding-bottom: 300px;
}