Updating three.js scene on window re-size

I used the following code for updating everything(camera, renderer etc) when I resize my window so that nothing distorts. It seems to work perfectly while manually resizing the window, however, when I maximize my window by just clicking the maximize icon, the images distort and the update loop breaks. Anyone familiar with this problem? thanks!

//resize
window.addEventListener('resize', () => {
  sizes.width = window.innerWidth
  sizes.height = window.innerHeight
  //update camera
  camera.updateProjectionMatrix()
  camera.aspect = sizes.width / sizes.height
  renderer.setSize(sizes.width, sizes.height)
})

const loop = () => {
  renderer.render(scene, camera)
  window.requestAnimationFrame(loop)
}

loop();

Express router middleware running multiple times

My router for paginate display list runs 4 times when executed and req.doc becomes undefined.

I’ve checked the request method and url path and everything seems fine. Could the mongoose aggregate function be causing the route to run multiple times?

Code from my app.js file:

        var displayList = require('./routes/displayList.js');

        app.get('/display_list/:encoded_id', displayList); 

code from file displayList.js:

    router.get('/display_list/:encoded_id', function(req, response,err){

if(err){

    console.log(err);
}

var listName = req.params.encoded_id;



let perPage = 10;
let currentPage = 1;


if(req.query.page){

    currentPage = parseInt(req.query.page, 10);
}



let query = {};

const skip = 10 * (currentPage - 1);
const limit = perPage;



const {userContext}  = req;




   book_list.aggregate([{$facet: { "Books":[
       {"$match":{"userId": req.userContext.userinfo.sub}}, {"$unwind":"$newList"}, {"$unwind":"$newList.books"},
            {"$match":{"newList.list_name": listName}}, {$group: {_id: "$newList.books", count: { $sum: 1 },books: {$push: "$newList.books"}} },{$project: {books: 1, _id: 0}}, {$skip: skip}, {$limit: limit}
   ],
           //write code to get count of books in list
            "Count": [ {"$match":{"userId": req.userContext.userinfo.sub}}, {"$unwind":"$newList"}, {"$unwind":"$newList.books"},
            {"$match":{"newList.list_name": listName}}, {$group: {_id: "$newList.books", count: { $sum: 1 }} }, {$count: "Total"}] }},

       {$unwind: "$Books"}, {$addFields: {"Books.Total": {$arrayElemAt: ["$Count.Total", 0]}}},
       {$replaceRoot: {newRoot: "$Books"}}
           ]).exec(function(err, doc, res,req){

            if(err){
                console.log(err)
            }


               let totalPages = Math.ceil(doc[0].Total/10);


                   response.render('display_list', {
                       userContext,
                       list_books: doc, listName: listName, currentPage: 
                        currentPage, totalPages: totalPages
                   });


               });

            });



 module.exports = router;



 

How to auto update reason based on request No using JavaScript ajax?

I work on asp.net mvc i face issue i can’t auto update reason using java script ajax

auto update meaning when user start writing on reason it will save on database table Automatically based on Request No

update i need will done without using update button it will auto save using java script ajax

my html as below

@model HR.WorkforceRequisition.Models.ResignationRequester
<table style="border: 1px solid 
black;width:100%;">




     <tr>
         <td style="width: 50%; font-weight: bold; padding-top: 10px;">
             <div class="form-group hover">
                 @Html.LabelFor(model => model.RequestNo, htmlAttributes: new { @class = "control-label col-md-5" })
                 <div class="col-md-7" id="RequestNo">
                     @Model.RequestNo
                 </div>
             </div>
         </td>
         <td>
<div class="col-md-7" id="Reason">
                @Html.TextAreaFor(model => model.Reason, new { id = "txtreason", @class = "form-control" })
</div>
        </td>

     </tr>
</table>

action name Edit will update on database on ResignationController will be as below

public JsonResult  Edit(ResignationRequester req)
{
    dynamic responseData = new ExpandoObject();
    responseData.success = false;
    responseData.message = "";
    string query;
 
        ResignationRequester workforceRequest = ResignationupdateReason((int)req.RequestNo,req.Reason);
    return Json(responseData);
}

java script function will execute when auto update will be

<script type="text/javascript">
function changereasonbasedonrequestno() {
    console.log("fire event")
    var ResignationRequester = new Object();
    ResignationRequester.RequestNo = document.getElementById("RequestNo").innerHTML.trim();
    ResignationRequester.NoticePeriod = document.getElementById("Reason").innerHTML.trim();
}
</script

model used on asp.net mvc will be

public class ResignationRequester
{


    [Display(Name = "Request No")]

    public int RequestNo { get; set; }

    [Display(Name = "Reason")]

    public string Reason { get; set; }
}

Converting the server-requested XML format data into array and sending back to front-end

I am beginner in using JS/PHP for making license server request based webpage. Right now, I am requesting server’s customer information and make this into array and sends back to the front-end. I request with license ID and if it is valid, then the database sends back the customer information and number of license IDs. Which means that one customer ID can have multiple licenses. The server sends out the XML formatted data and I am trying to make this into array and send back to front-end. The license ID itself is not “sensitive” data so it is okay to be exposed to the front-end.

The XML formatted data is looks like this…

<CustomerData>
<Customer>
<FirstName>TEST FIRST</FirstName>
<LastName>TEST LAST</LastName>
</Customer>
<License>
<LicenseID>11223344</LicenseID>
<ProductID>5448</ProductID>
</License>
<License>
<LicenseID>11223345</LicenseID>
<ProductID>4444</ProductID>
</License>

I tried to make this into array using foreach inside the PHP, but it always gives back empty array of licenses.
I tried to solve with this code…

$xml = simplexml_load_string($result);
if (!empty($xml->CustomerData) && !empty($xml->CustomerData->License)) {
  foreach ($xml->CustomerData->License as $license) {
    $licenseID = (string) $license->LicenseID;
    $productID = (string) $license->ProductID;
    $licenses[] = [
      'licenseID' => $licenseID,
      'productID ' => $productID 
    ];
  }
} else {
error_log('Error');
}
echo json_encode(['licenses' => $licenses]);
 

Bug on casting Rays (Javascript)

I am casting rays through wall, every ray will contain informations about (objectHIT,pointIntersectionXY)

I was able to do some casting, but the collision is not always working as expected. I review the code many time but i still dont understand where could i go wrong.

First off all, the coordinates of my intersections along the others atributes are all organized and correct and stored in (listCollision) throught my other function that calculate the collisions.

*//listCollision[The ray that is casting][The Object that was hitted].OthersAtributes*
*//VisaoLimitada[Index of Ray].attributes*


limitDistance(listCollision,visaoLimitada) {   
            
            for (let i = 0; i < this.laser; i++) {
                var distanciaV = { 
                x1: visaoLimitada[i].x1, 
                y1: visaoLimitada[i].y1, 
                x2: visaoLimitada[i].x2, 
                y2: visaoLimitada[i].y2 };
                
                var originDistance = this.distanceC(distanciaV.x1,distanciaV.x2,distanciaV.y1,distanciaV.y2); //This function returns the distance of two given points
    
                for (let j = 0; j < listCollision[i].length; j++) {
                    var distanciaAtingida = { 
                    x1: distanciaV.x1, 
                    y1: distanciaV.y1, 
                    x2: listCollision[i][j].x, 
                    y2: listCollision[i][j].y };
                
                    var objectDistance = this.distanceC(distanciaAtingida.x1,distanciaAtingida.x2,distanciaAtingida.y1,distanciaAtingida.y2);
    
                    if(objectDistance<originDistance){
                    visaoLimitada[i] = distanciaAtingida;
                    originDistance = visaoLimitada[i]; //Para encontrar novo proximo objeto mais proximo
                    }

                }
            }
            return visaoLimitada;
        }
        
        calculateViewport(FOV){

            var intervaloX = (this.player[3].x - this.player[1].x)/this.laser;
            var intervaloY = (this.player[3].y - this.player[1].y)/(this.laser-1);
            
            //In the GAMELOOP, first call calculateViewport(), and set the casting rays to a straight line
            //After that is called calculateViewport(listCollisions), and the position of the final XY rays gonna be setup by the collisions
            if(FOV==null || this.isEmpty(FOV) == 1){

                for(let i=0;i<this.laser;i++){    

                this.visao[i].x1 = this.player[1].x+ 1*Math.cos(this.radians(this.aX)) + i * intervaloX;
                this.visao[i].y1 = this.player[1].y+ 1*Math.sin(this.radians(this.aX)) + i * intervaloY;
                this.visao[i].x2 = this.player[1].x+this.distanceView*Math.cos(this.radians(this.aX))+ i * intervaloX;
                this.visao[i].y2 = this.player[1].y+this.distanceView*Math.sin(this.radians(this.aX))+ i * intervaloY;
            }
            

        }
        else{

            this.visao = this.limitDistance(FOV,this.visao);

        }

        }

Double api request React

I have the following React Component

export default function Header () {
  const { isSessionActive, isMenuOpen, isProfileMenuOpen, setIsMenuOpen, closeMenu, URL } = useContext(AppContext)
  const [profileData, setProfileData] = useState({})

  useEffect(() => {
    if (!isSessionActive) return
    console.log('Enter in the useEffect')
    const token = window.localStorage.getItem('token')
    axios.get(`${URL}/users`, { headers: { Authorization: `Bearer ${token}` } })
      .then(result => setProfileData(result.data))
      .catch(error => console.log(error))
  }, [isSessionActive])

  const openMenu = () => {
    setIsMenuOpen(true)
  }

  return (
    //Rest of the Jsx code...
  )
}

As you can see, I have a useEffect to make a request to an API. The console.log(‘Enter in the useEffect’) pops out just one time (which is the expected behavior), meaning the component only makes the request once.

The problem is, if I log all the requests that arrive at my API, it looks like the application is making the request twice (I don’t make any requests to the API in any other part of the app).

Why is this happening? Is it normal? Because that means the server will have to handle twice the number of requests just because of this problem (imagine if I have multiple calls).

Am I doing something wrong?

Prevent line break on textarea when Shift + Enter is pressed

How to disable line breaks on the <textarea> when shift + enter is pressed.

The attached code here below disables line break when only enter is pressed. I want to disable shift + enter as well.

onKeyPress={(event) => {
   if (event.key === 'Enter' && !event.shiftKey) {
      onInputPressEnter(event, elementsRefs);
      setSubmitted(true);
   }
}}

Why is my form not working? My error reads [closed]

  <!-- email starts -->
    <form name="myemailform" id="myemailform">
    
    <input type="email" id="myemail"placeholder="Enter E-mail Address">      
          
    <input type="email"id="myemailconfirm" placeholder="Confirm E-mail Address">
    
    
    
</form>
  <!-- email ends -->
    
    
    <script> 
    
function SameEmail(   ){

var myemailform=document.getElementById (" myemailform ");
 var myemail=document.getElementById ("myemail");
  

  
if(myemailform.myemail.value == 
   
myemailform.myemailconfirm.value)
    
{ 
alert("Emails are the same")
 
 myemailform.myemail.focus();
 
 
 
 
 
 } 
 
 }
 </script>

I’m looking to match the email addresses and validate if they are the same. It looks like everything is coded right, but I’m getting an error saying

“Cannot read properties of null (myemail).”

Thanks for the help!

How can I connect to a secure web socket from a specific website [closed]

I want to automate actions on momio.me programmatically using python.

To do so I need to connect to wss://de.momio.me/pipe and then send the messages accordingly

I have tried connecting to the websocket directly but as soon as I sent a message it immediately closed the connection.

I could use selenium as an alternative to achieve the automation but I would not be able to learn much this way.

onClick event.detail is not resetting after React component replaced

The onClick event.detail contains the number of clicks: double-click has event.detail = 2.

When the clicked React component is replaced, the event.detail does not reset. I suspect this is because React has optimized this & kept the same div in the page, so the browser has not reset the event.detail counter.

How can I force this event.detail counter to reset when the component is changed? I want to be able to double-click items in the list multiple times while navigating.

Issue reproduction: https://codesandbox.io/p/sandbox/react-on-click-event-detail-6ndl5v?file=%2Fsrc%2FApp.tsx%3A44%2C12

App.tsx:

const ListItem: React.FC<{
  content: string;
  onClick: (event: React.MouseEvent<HTMLDivElement>) => void;
}> = ({ content, onClick }) => {
  return (
    <div
      onClick={onClick}
      style={{ background: "rgba(0,0,0,0.5)", userSelect: "none" }}
    >
      {content}
    </div>
  );
};

const ListRenderer: React.FC = () => {
  // n tracks the number of double clicks
  const [n, setN] = useState(0);

  // items simulates an updating list of items when double-clicking
  const items = useMemo(
    () => Array.from({ length: 10 }, (_, i) => `${n}: item ${i}`),
    [n]
  );

  const handleClick = useCallback((event: React.MouseEvent<HTMLDivElement>) => {
    console.log(`Click: event.detail: ${event.detail}`);
    if (event.detail === 2) {
      // Double-clicked an item.
      setN((prev) => prev + 1);
    }
  }, []);

  return (
    <>
      <div>
        {items.map((item, index) => (
          <ListItem
            key={`items-${n}-${index}`}
            content={item}
            onClick={handleClick}
          />
        ))}
      </div>
    </>
  );
};

Token undefined on first render in next-auth causes useSuspenseQuery to fetch with no bearer token set

I am using the new useSuspenseQuery from react-query and I noticed that the enabled property is not present on this hook. My useGetApiToken returns null on first render and because of this, the suspenseQuery fetches with null as value for the bearer token.

One way to solve this is to put the refetchInterval property very low (500ms – 1000ms), but this comes at the cost of constantly polling my api with requests.

flickity: how to use contain: true with wraparound

I have an image carousel, I want the carousel start with the first image aligned to the left using contain:true but at the same time I want to be able to use wrapAround:true so that it creates a loop.

On the document it says contain:true doesn’t work with wrapAround:true but is there a way to work around it?

My current flickity CSS looks like this:

$('.carousel').flickity({
  // options
  lazyLoad: 2,
  contain: true,
});

enter image description here

.cy.js file can not symbolized as js at my vscode. How I can make this file seems as js?

.cy.js file seeming as cy format. I want it to seems as js

seeming as .cy but want to see it as js. It seems like I’ m encountering an issue with a file or folder named .cy.js that is not recognized as a JavaScript file. If I’ m working with a project using Cypress (commonly abbreviated as “cy”), it’s possible that this file or folder is causing confusion.

How to make addEventListener affect multiple divs [duplicate]

I am new to code, so please don’t be too harsh on me. I am using this code to create a button that would store and load edited data from localStorage, and make divs with the class “content” editable. Whenever I click the button, however, it only makes the first div editable. Is there a way to make it apply to all divs with the class “content”?

window.onload = function() {
    if(localStorage.getItem('content')) {
        document.querySelector('.content').innerHTML = localStorage.getItem('content');
  }
}

let editBtn = document.querySelector('#edit_content');
let content = document.querySelector('.content');

editBtn.addEventListener('click', () => {
    content.contentEditable = !content.isContentEditable;
  if(content.contentEditable === 'false') {
    localStorage.setItem('content', content.innerHTML);
  }
});

I tried using querySelectorAll(), but that just made the button not work at all.