How to use array.push() inside of loop and show the result outside of loop?

Im trying to make query to my MongoDb and loop thru the response so I could have each user on its own object and push them to an array so I could send the response to client. But my array is empty if I use it outside of loop, if I try to use it inside of loop I get an error when trying to res.json() to client. I want to send finished array to client. How to do it so that the code runs the loop before the bottom console.log(s)

let placesArr = []

User.find({_id: getUser}).then( response => {
       
    response[0].placeId.forEach(item => {
        Place.find({placeId: item}).then(ress => {
            const getUsersFromPlace = ress[0].users
            getUsersFromPlace.forEach(element => {
                if(getUser != element._id){
                    placesArr.push(element)
                }
                //here I can see the result -> console.log(placesArr)
            })                 
        })
    })
     //How to see finished array in here
    //Array is empty here -> console.log(placesArr)
})
 //How to see finished array in here
//Array is empty here -> console.log(placesArr)

});

While installing any package npm throw a require stack error with code MODULE_NOT_FOUND

While i try to install anything from npm install command it will trow an error, “require stack” and “code MODULE_NOT_FOUND”


C:Usersdell>npm audit fix
node:internal/modules/cjs/loader:1075
  const err = new Error(message);
              ^

Error: Cannot find module '../package.json'
Require stack:
- C:UsersdellAppDataRoamingnpmnode_modulesnpmlibcli.js
- C:UsersdellAppDataRoamingnpmnode_modulesnpmbinnpm-cli.js
←[90m    at Module._resolveFilename (node:internal/modules/cjs/loader:1075:15)←[39m
←[90m    at Module._load (node:internal/modules/cjs/loader:920:27)←[39m
←[90m    at Module.require (node:internal/modules/cjs/loader:1141:19)←[39m
←[90m    at require (node:internal/modules/cjs/helpers:110:18)←[39m
    at createEnginesValidation ←[90m(C:Usersdell←[39mAppDataRoamingnpmnode_modules←[4mnpm←[24mlibcli.js:7:15←[90m)←[39m
    at module.exports ←[90m(C:Usersdell←[39mAppDataRoamingnpmnode_modules←[4mnpm←[24mlibcli.js:78:27←[90m)←[39m
    at Object.<anonymous> ←[90m(C:Usersdell←[39mAppDataRoamingnpmnode_modules←[4mnpm←[24mbinnpm-cli.js:2:25←[90m)←[39m
←[90m    at Module._compile (node:internal/modules/cjs/loader:1254:14)←[39m
←[90m    at Module._extensions..js (node:internal/modules/cjs/loader:1308:10)←[39m
←[90m    at Module.load (node:internal/modules/cjs/loader:1117:32)←[39m {
  code: ←[32m'MODULE_NOT_FOUND'←[39m,
  requireStack: [
    ←[32m'C:\Users\dell\AppData\Roaming\npm\node_modules\npm\lib\cli.js'←[39m,
    ←[32m'C:\Users\dell\AppData\Roaming\npm\node_modules\npm\bin\npm-cli.js'←[39m
  ]
}

Node.js v18.15.0

if someone has answer so please let me know.

if someone has answer so please let me know.

Uncaught TypeError: (0 , _reactRouterDom.useHistory) is not a function

I am working with a migration project, I do not have much idea about react-router-dom 4.3.1;
my React version is:

React.version '16.14.0' and the router dom is react-router-dom": "^4.3.1", when I use the goBack() from history getting an error as:

TypeError: (0 , _reactRouterDom.useHistory) is not a function any one help me to fix this?

code:

import { NavLink, useHistory } from 'react-router-dom';

 const goBackToPreviousPage = () => {
    const history = useHistory();
    history.goBack();
  };


 <button onClick={goBackToPreviousPage}>Back to previous page</button>

IFrame in Flutter web : remove header/footer

I’m using InAppWebView in my app to display webview.

I have to remove header and footer to prevent user from navigate inside it. It’s work fine for mobile using UserScript, but it’s not supported for web and evaluateJavascript() function don’t work either because of the cross-origin :

NOTE for Web: this method will have effect only if the iframe has the
same origin


static const script = "document.getElementsByClassName('header')[0].style.display='none';"
      "document.getElementsByClassName('header__toggle')[0].style.display='none';"
      "document.getElementsByClassName('footer')[0].style.display='none';";

 InAppWebView(
    initialUrlRequest: URLRequest(url: WebUri(viewModel.currentUrl!)),
    initialSettings: InAppWebViewSettings(
           useShouldOverrideUrlLoading: true,
           javaScriptCanOpenWindowsAutomatically: true,
     ),
    initialUserScripts: UnmodifiableListView([
           UserScript(
                 source: script,
                 injectionTime: UserScriptInjectionTime.AT_DOCUMENT_START,
            ),
     ]),
     onWebViewCreated: (controller) async {
            viewModel.setController(controller);
            viewModel.controller.complete(controller);
     },
     onLoadStop: (controller, uri) async {
            await controller
                     .evaluateJavascript(source: script)
                     .onError((error, stackTrace) => log(error.toString()));
     },
 ),

Is there an other way to do it for web ?

I try using IFrameElement with HtmlElementView, but I didn’t find how to remove element from here. Is it even possible ?

 final IFrameElement _iframeElement = IFrameElement();
 _iframeElement.height = '100%';
 _iframeElement.width = '100%';
 _iframeElement.src = url;
 _iframeElement.style.border = 'none';
 _iframeElement.id = "frameId";


 // ignore: undefined_prefixed_name, avoid_dynamic_calls
 ui.platformViewRegistry.registerViewFactory(
 'iframeElement',(int viewId) => _iframeElement,);


 HtmlElementView(
    viewType: 'iframeElement',
 ),

Thanks

Bootstrap Modal Backdrop Doesn’t Disappear for Some Users

I have a .Net 6 application that has a view with a partial view. The partial view contains a modal div that is repopulated dynamically depending upon the action taken in the partial view. I capture the submit from the modal with code similar to this:

$('#modal-content2').on('click', '.fileupload', function(e) {
   e.preventDefault();
   ......

There is an ajax call that performs the needed function, in the snippet above a file is uploaded. Once the ajax call completes it looks for a valid response in the return and then closes the modal and refreshes the partial view

}).done((response, textStatus, xhr) => {
   var isValid = $(response).find('[name="IsValid"]').val() == 'True';
   if (isValid) {
       $('body').find('#modal-container2').modal('hide');
       $("#DisplayFileContent").load('/Issue/GetUpdatedFiles');
   } else { .......

This works properly for most of the users of the application. However there is a small subset of the users where the modal disappears but the background does not. The ajax code is working because I have added logging to verify. In the case above, the file gets uploaded correctly. If the user refreshes their screen, it shows the uploaded file. I have added logging, looked for error messages, etc. but I can not recreate the issue nor has anything shown up in any error logs.

What can I do to fix this annoying issue for this small subset of users?

Javascript extended Array cannot change default constructor and inherited method behavior

I tried to implement MyArray extending built-in Array, and overrode annoying default constructor behavior when accepting only one argument. Below snippets showed two techniques, only the second one worked while both console are the same.

class MyArray1 extends Array {
  constructor(...strs) {
    super(...strs);
    this.tmpStore = {}; // for distinguishing purpose
    if (strs.length === 1) {
      this.length = 1;
      console.log("weird", strs, strs[0]);
      this[0] = strs[1]; // assignment didn't work
      /* this way is good
      this.length = 0;
      console.log("not weird", strs, strs[0]);
      Array.prototype.push.call(this, strs[0]);
      */
    }
  }
}

const myArrayMuiti = new MyArray1("1", "2");
console.log("myArrayMulti", myArrayMuiti);
const myArraySingle = new MyArray1("1");
console.log("myArraySingle", myArraySingle);

Then I tried to implement filter, more weird things happened. When I was trying to filter MyArray2, the constructor was called and strs is [0]

class MyArray2 extends Array {
  constructor(...strs) {
    super(...strs);
    this.tmpStore = {}; // for distinguishing purpose
    if (strs.length === 1) {
      this.length = 0;
      console.log("where did `[0]` suddenly jump out from??", strs, strs[0]); // here `strs` is [0]
      Array.prototype.push.call(this, strs[0]);
    }
  }
  
  filter(predicate) {
    return Array.prototype.filter.call(this, predicate);
  }
}

const myArray = new MyArray2("1", "2");
const filterRes = myArray.filter(str => str === "nonsense");
console.log("filterRes", filterRes);

The correct way to implement filter may be [...this].filter(predicate), but it will bring an extra copy, and I wonder the root reason.

maybe related question

How to keep fixed element with dynamic height at the bottom in react

I have a fixed element with dynamic height (changing when resizing the browser width ) like the example below :
https://stackblitz.com/edit/react-yuqarh?file=demo.tsx

the element working like a menu :

  • it should be opened in first load (it work)
  • hidden when user press hide (partially work)
  • when click on menu icon open (it work)

in hidden mode I used negative bottom value but this value is fixed while the element height changing if the user resize the browser which causes the element to disappear.

this element is actually a search component with some inputs but I simplified

API not working properly in JavaScript AJAX code

When I hit API directly in the browser then it is giving ResponseCode = 0 & when I tried to call same API from JavaScript Ajax code then it is giving ResponseCode = 1. Both way tried in same Mobile Device but result is different.

TXID of API is unique for each request. I just kept static here.

API as below

http://dot-jo.biz:8085/operator-he/?opId=81&TXID=3216465116846844324351844&PartnerId=svmobi-201850

My JavaScript Ajax loaded in different domain for example http://test.cc/test/api.php

Code as below

var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr) {
    // Most browsers.
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined") {
    // IE8 & IE9
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    // CORS not supported.
    xhr = null;
  }
  return xhr;
};

var url = 'http://dot-jo.biz:8085/operator-he/?opId=81&TXID=3216465116846844324351844&PartnerId=svmobi-201850';
var method = 'GET';
var xhr = createCORSRequest(method, url);

xhr.onload = function() {
  console.log(xhr);
};

xhr.onerror = function() {
alert('error fired!');
};
xhr.send();

With this code I am getting response with ResponseCode=1 but I am getting ResponseCode=0 where I hit API directly hit in Browser.

I expect ResponseCode=0 with my code but now getting it. Is there anything wrong in code or anything what I missed?

Python event trigger from JS package

Background

I have visualisation tool built within a Jupyter notebook (uses ipywidgets, itkwidgets, vtk).
I have made some modifications to some of the JS modules whereby I can see (through JS generated annotations) the data point which has been selected.

Issue / Question

However, I ideally would like the JS module to pass the point ID back to the Python code in some way so that it can be utilized. Is this possible?

I believe this could be possible through the use of a Flask app and ajax calls etc. but I need to run this in Jupyter.

How to fit a pdfdocument fully in pdfviewer

I want a pdfviewer where the pdf is fully matching the pdfviewer (so that no grey background is visible)

This is my code (with PDFObject):

<!DOCTYPE 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>PDFObject</title>

        <style>
            body {
                margin: 0;
                padding: 0;
            }
        </style>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.2.4/pdfobject.min.js" integrity="sha512-mW7siBAOOJTkMl77cTke1Krn+Wz8DJrjMzlKaorrGeGecq0DPUq28KgMrX060xQQOGjcl7MSSep+/1FOprNltw==" crossorigin="anonymous"></script>
    </head>
    <body>
        <main id="main">
            <div id="mypdf">
            </div>
        </main>

        <script>
            PDFObject.embed("myfile.pdf", "#mypdf", {width: "100vh", height: "100vh"});
        </script>
    </body>
</html>

This is actual

I want it like this also when I zoom in and out

Is there any solutions out there with PDFObject

How to use dynamic routes in Reactjs project

I am working with Reactjs and right now i am trying to use “dynamic routes”,
Right now i am working in “component file” (src/components/home/Myarticle.js) and here is my current code

const [users, setUsers] = useState([]);
    useEffect(() => {
        async function fetchData() {
            const res = await axios("https://jsonplaceholder.typicode.com/comments");
            console.log("RES", res.data);
            setUsers(res.data);
        }
        fetchData();
    }, []);
      return (
        <div>
            <h1>Dynamic Routingdd</h1>
                {users.map((user) => {
                return (
                    <div key={user.id}>
                        Click on the id to see the details :
                        <NavLink to={"/user/" + user.id}> {user.id}</NavLink>
                    </div>
                );
            })}
        </div>
    );

And here is my “User.js”(root) but i am getting “404 error” and url redirect to “http://localhost:3001/404”,Where i am wrong ?

import React, { useEffect, useState } from "react";
import { useParams, withRouter } from "react-router";
import axios from "axios";

const User = (props) => {
    const params = useParams();
    const [users, setUsers] = useState({});
    console.log(params);
    useEffect(() => {
        async function fetchData() {
            const res = await axios(
                `https://jsonplaceholder.typicode.com/comments/${params.id}`
            );
            console.log("INDI", res.data);
            setUsers(res.data);
        }
        fetchData();
    }, []);
    return (
        <div style={{ width: "80%", margin: "0 auto" }}>
            <div
                style={{
                    margin: "20px",
                    marginRight: "auto",
                    borderRadius: "20px",
                    border: "2px solid #000",
                    width: "50%",
                    padding: "10px",
                }}
            >
                <h1>Post Id : {users.postId ? users.postId : "Loading . . . . "}</h1>
            </div>
        </div>
    );
};

export default User;

nested array or objects

I’m practicing array and objects, though I’m still confusing about making nested objects and arrays.

So i have this type of array and i want to make it nested but i’m having a hard time to do it. I don’t know if it is possible.

const data = [
            {
              "Date":"3/24/23",
              "Course":"BASIC ENGLISH",
              "Examiner":"Juan Ponce",
              "Participants":"Nardo Putik",
              "Examiner Approach":"3",
              "Clear explanation of topics discussed":"3",
              "Well organized activity from start to finish":"3"
            },
            {
              "Date":"3/24/23",
              "Course":"BASIC ENGLISH",
              "Examiner":"Juan Ponce",
              "Participants":"Cardo Martinez",
              "Examiner Approach":"3",
              "Clear explanation of topics discussed":"3",
              "Well organized activity from start to finish":"3"
            },
            {
              "Date":"3/24/23",
              "Course":"BASIC ENGLISH",
              "Examiner":"Juan Ponce",
              "Participants":"Ippo Kazuya",
              "Examiner Approach":"3",
              "Clear explanation of topics discussed":"3",
              "Well organized activity from start to finish":"3"
            }
        ]
        
console.log(data);

Expected Output :

const data = 
  [
     "Date": "3/24/23",
     "Course": "BASIC ENGLISH",
     "Examiner": "Juan Ponce",
     {
          "Participants":"Ippo Kazuya",
          "Examiner Approach":"3",
          "Clear explanation of topics discussed":"3",
          "Well organized activity from start to finish":"3"
     },
     {
          "Participants":"Cardo Martinez",
          "Examiner Approach":"3",
          "Clear explanation of topics discussed":"3",
          "Well organized activity from start to finish":"3"
     },
     {
          "Participants":"Nardo Putik",
          "Examiner Approach":"3",
          "Clear explanation of topics discussed":"3",
          "Well organized activity from start to finish":"3"
     }
  ]

MUI toggle button selected input not being highlighted despite setting value

The MUI toggle is able to register the user input but the selected input does not get highlighted when clicked. I have added value parameter and did an onChange function to change the param on value change. It does get highlighted at “Not Final” initially, but once I toggle it, the highlight disappears and neither options are highlighted. What am I doing wrong?



 <ToggleButtonGroup
  color="primary"
  exclusive
  value={formData.isFinal}
  onChange={(e) => changeData(e.target.value,'isFinal')}
  aria-label="Platform"
            >
    <ToggleButton value={true} >Final</ToggleButton>
    <ToggleButton value={false}>Not Final</ToggleButton>
</ToggleButtonGroup>
 const changeData = (data, type) => {
      setFormData((prevData) => ({
        ...prevData,
        [type]: data,
      }));
  };
 const [formData, setFormData] = useState({
   name: '',
   description: null,
   isFinal: false,
 });