Downloading HTTP file from HTTPS site

I am attempting to get a file from a remote resource that does not have an SSL Certificate installed (HTTP). Once the user clicks the button, it sends some data to a PHP file on the server which performs some manipulation to create a link to the external resource: http://givememystuff.com/1/2/3/ABCS

The script then passes the link back to the client (JavaScript with jQuery) for the client to download the file. My latested attempt at getting this to work is using the code below which works great in Chrome. The issue is when this runs in Edge, MS blocks the download because it comes from an HTTP location.

Any thoughts on where I am going wrong?

complete: function(xhr) {
            if(xhr.status == 200) {
                var data = xhr.responseText;
                // console.log(data);
                
                window.open(data);
            } else {
                console.log(xhr);
                alert("Unable to pull Document");
            }

JS Algorithm: Spread X evenly between two dates, but only on weekdays

Let’s say I’m given a start date (3/17/2022) and an end date (3/31/2022).

If x = 3, how would I spread x equally over 3 separate dates between the start date and end date- also taking into consideration that I only want the values spread over weekdays?

The output I am looking for is three separate dates where the divided x is spread equally on.

Does this question make sense?

Thank you!

React setState in two Async functions, second overwrites first [duplicate]

I have an interesting problem here I will try to outline here. I have a state object in React state that is updated in two separate async functions in this way:

const [someState, setSomeState] = useState({})

const somefunction1 = async () => {
  const res1 = ///some api call
  setSomeState({...someState, res1: res1})
}

const somefunction2 = async () => {
  const res2 = ///some api call
  setSomeState({...someState, res2: res2})
}

await someFunction1();
await someFunction2();

console.log(someState); //{res2: res2}

Based on the above example, I am not sure why res1 is missing in this state object when they are called separately, the second call effectively overwrites the changes made from the first call. What I really need this to look like when its done is:

console.log(someState); //{res1: res1, res2: res2}

Is there a better way to write this scenario so I get the expected outcome? Since one somefunction2 is supposed to wait until somefunction1 is complete, I am not sure why it is overwriting it. Any help will be appreciated. Thank you.

fetching promise breaks in setInterval

So i’m a student in computer science , i’m kinda newbie , i ran into a problem that i couldn’t solve ,
so i want to fetch from my bdd mongo every x seconds , and show the result in the html.
i have a function called getItems that does that for me , it works perfectly , hence when i try to set call it with setIntervel it works ! but only for 30 or 40 seconds and then breaks.
this is my code :

setInterval(getItems , 1000 ) ; 


const getItems = async () => {
  const requestOptions = {
    method :'GET',
  };
  const response = await fetch('/user/listed', requestOptions);
  const response2 = await fetch('/user/me', requestOptions);
  items = await response.json(); 
  owned = await response2.json() ; 
   
  if (response.ok && response2.ok) {
    // delete all the old values in listed 
   var e =document.getElementById("listed") ; 
   var child = e.lastElementChild ; 
   while (child){
     e.removeChild(child) ; 
     child = e.lastElementChild ; 
   }
   // delete all the old values in boughts 
   var e2 =document.getElementById("bought") ; 
   var child2 = e2.lastElementChild ; 
   while (child2){
     e2.removeChild(child2) ; 
     child2 = e2.lastElementChild ; 
   }
    // adding new values 
    for (var key in items ){
     
      
      const node = document.createElement("li");
      const textnode = document.createTextNode(items[key].name + " : " + items[key].price);
      node.appendChild(textnode);
      node.setAttribute("id", items[key]._id)  ; 
      const buy = document.createElement("button") ; 
      const buytext = document.createTextNode("buy") ; 
      buy.setAttribute("id", items[key]._id) ; 
      buy.setAttribute("onClick" , "buy(this.id)")
      buy.appendChild(buytext) ; 
      node.appendChild(buy) ; 
      document.getElementById("listed").appendChild(node);


    }
    // adding new values 
    for (var o in owned.bought){
      
      const node = document.createElement("li");
      const textnode = document.createTextNode(owned.bought[o].name + " : " + owned.bought[o].price);
      node.appendChild(textnode);
      node.setAttribute("id", [o]._id)  ; 
      document.getElementById("bought").appendChild(node);
  }

  }
}

and here is a picture of the error :
enter image description here

Thank you in advance !

Express PUT route, with tedious connection to Azure database

I am trying to make a PUT request, updating the users e-mail.
I am testing the endpoint with Postman.

I am pretty sure the mistake is in line 7, but I can’t seem to get it working.
My final goal, is updating the user email to whatever is put into a input field in HTML.

Is somebody able to spot what I am missing?

/src/routes/userRoutes.js

const express = require("express");
var Connection = require("tedious").Connection;
const sql = require("mssql");
const config = require("../../config.json");
var connection = new Connection(config);
const router = express.Router();

router.post("/updateUser", (req, res) => {
  sql.connect(config, function (err) {
    if (err) console.log(err);
    // create Request object
    var request = new sql.Request();
    // query to the database and get the records
    const email = req.body.email;
    request.query(
      `update dbo.[user]
      set User_Email = '${email}'
      where User_ID = 6`,
      function (err, recordset) {
        if (err) {
          console.log(err);
        } else {
          console.log(`User has been updated!`);
          res.json("Updated user");
        }
      }
    );
  });
});

app.js

const express = require('express')
const app = express();
const PORT = 3000;
const userRoutes = require('./src/routes/userRoutes')
const path = require('path')

app.use(express.static('./src/views'));
app.use(express.json())


app.use('/', userRoutes)
app.use('/createUser', userRoutes)
app.use('/updateUser', userRoutes)
app.use('/deleteUser', userRoutes)

//app.get('/updateProduct', (req,res) => {
//    res.render(path.join(__dirname, '/src/views/updateProduct.html'))
//})



app.listen(PORT, () => {
    console.log(`Server is listening on ${PORT}`);
})

POSTMAN output

Cannot PUT /updateUser

Because I can’t run await on the top level, I have to put it into an async function – why can I then call that async function directly?

I have a short Node.js script where I require another package and call an async function from it and subsequently want to print the return value. If I simply await the return value from the top level, then I’ll get an error, saying that I can only use await inside an async function itself. So apparently the way to go is like this:

async function main() {
  foo = await someOtherAsyncFunc();
  console.log(foo);
}
main()

Or:

(async function() {
  foo = await someOtherAsyncFunc();
  console.log(foo);
})();

Or:

(async () => {
  foo = await someOtherAsyncFunc();
  console.log(foo);
})();

(Credit to VLAZ in chat https://chat.stackoverflow.com/transcript/message/54186176#54186176)

This works – but I want to understand the reasons behind it a little bit more: I’m used to not being able to directly use await from the top level. However, I’m also used to having to call some special library function to actually “venture” into async from the top level. In Python, see asyncio.run for example. What’s the point of requiring await to be inside an async function – if I can then call just any async function from the top level? Why then isn’t await available at top level, too?

change color of chosen ion-item if chosen

I’m relatively new to Ionic (Vue) so sorry if it’s a bit of a newbie question:

<template>
<base-layout page-title="Choose Players" page-default-back-link="/home">
  <ion-item v-for="contact in contacts" :key="contact.phoneNumbers[0]" @click="addContact(contact)">
    {{ contact.displayName }}
  </ion-item>
</base-layout>
</template>

The above code generates a list of Contacts, and I’d like to somehow highlight or change the background color only for the chosen (clicked) ones.

I also have the below method:

data() {
    return {
      contacts: [],
      chosenContacts: []
    };
  },

  methods: {
    async loadContacts() {
      Contacts.getContacts().then(result => {
        this.contacts = result.contacts;
      });
    },

    addContact(contact) {
      this.chosenContacts.push(contact);
    }
  },
  mounted() {
    this.loadContacts();
  }

I’d like to do either that or just adding an icon only for the chosen/selected ones.

Javascript trying to get value of an element not working

My code:

function $(selector){
    var self = {
        el:document.querySelector(selector),
        html:()=> self.el.innerHTML,
        on:(event, callback)=>{
            document.addEventListener(event, callback)
        },
        hide:()=> {
            self.el.style.display = 'none'
        },
        attr:(attr, value)=>{
            if(value == null){
                self.el.getAttribute(attr)
            }else{
            self.el.setAttribute(attr, value);
            }
        },
        setHTML:(code)=>{
            self.el.innerHTML = "";
            self.el.innerHTML = code;
        },
        createChld:(childElement, id, clss, innerHTML)=>{
            var el = document.createElement(childElement);
            el.setAttribute('id', id);
            el.setAttribute('class', clss);
            el.innerHTML = innerHTML;
            self.el.appendChild(el);
        },
        addClass:(clss)=>{
            self.el.classList.add(clss)
        },
        addId:(id)=>{
            self.el.id = id;
        },
        value:()=>{
            self.el.value;
        }
    }
    return self
}


When I try to use something like $(‘input’).value() it doesn’t work it just results to undefinded, I don’t know why but I think it has something to do with self.el.value.
Thanks.

Cypress and Cucumber reset the requests in Next Js

I am using in my next js application cypress to test a page. I need to test 2 scenarios: 1. Success and 2. Bad when user receives an error.

Before(() => {
  return void cy.server()
});

// first scenario
Given('the user access app', () => {
  ...
});

And('the user make request', () => {
  cy.route('GET', `${api}/cars`, 'fixture:good').as('goodRequest');
});

Then('the user should see good answer', () => {
  cy.get('[data-cy=ok]').should('exist')
})

//second scenario
Given('the user access app', () => {
  ...
});

And('the user make request', () => {
  cy.route('GET', `${api}/cars`, 'fixture:bad').as('badRequest');
});

Then('the user should see bad answer', () => {
  cy.get('[data-cy=bad]').should('exist')
})

The first test pass, but when the second starts, i anyway get the previous response from the first request and get on the page the good response and test fails because the bad text does not appear on the page.
Is there a solution to reset the response after each test or something like this? How to solve the issue?

How to get the circumscribed area of all DOM elements?

I have a lot of elements on the page. I need to draw a circumscribed rectangle that contains all DOM elements.

For that I iterate DOM elements and get rectangle:

Array.from(firstChild.children).forEach((child: Element) => {
      const rect = child.getBoundingClientRect();
});

Which props I need from rect to do that?
Logically I need to get minimal x,y of left-top corner and max bottom-right corner. But how?

How to use Navigation Events (navigationHide) on SwiperJS?

I would like to use navigationHide and navigationShow Event on SwiperJS.

I set the events but nothing happens when the navigation is disabled or hidden.

const swiper = new Swiper(".swiper", {
  initialSlide: 0,
  loop: false,
  spaceBetween: 24,
  slidesPerGroup: 2,
  slidesPerView: 'auto',
  navigation: {
    nextEl: ".swiper-button-next",
    prevEl: ".swiper-button-prev"
  },
  on: {
    navigationHide: function () {
      console.log(this);
    }, 
    navigationShow: function () {
      console.log(this);
    }
  }
});

https://codepen.io/nuno360/pen/MWOPgVB

Restrict table data value to 4 digits

I am trying to build a simple calculator using HTML, CSS and Vanilla Javascript. Where I want to make sure that the input field (display screen) does not have more than 4 digits in the first operand and similarly for the next operands to follow.

Story so far
index.html

<table class="calculator">
    <tr>
        <td colspan="4"><input class="display-box" type="text" id="result" disabled /></td>
    </tr>
    <tr>
        <td><input class="button" type="button" value="1" onclick="display('1')" /> </td>
        <td><input class="button" type="button" value="2" onclick="display('2')" /> </td>
        <td><input class="button" type="button" value="3" onclick="display('3')" /> </td>
        <td><input class="button" type="button" value="*" onclick="display('*')" /></td>
    </tr>
    ...
</table>

script.js

function display(value) {
    document.getElementById("result").value += value;
    var ops = ["+", "-", "%", "*", "/"];
    result=document.getElementById("result").value
    console.log(result)
    if(ops.includes(value)){
        result=0
        console.log("Ops found!")
    }
    result=document.getElementById("result").value
    result=result.replace(/[^0-9]/g, '');
    console.log(result)
    if(result>9999){
        document.getElementById("result").value = "Error"
        alert("Error: Entered more than 4 digits")
    }
}

Raycast not hitting a scene child using Three.js with GMaps

Im trying to hit a pin scene child with a click in GMaps, using Three.js and threejs-overlay-view but I can’t get the object clicked. Raycaster.intersectObjects only returns [].

Image of pin

Here’s a snippet of the code, everything works fine except the intersection part.

(async () => {        
  const map = await initMap();
  const mapDiv = map.getDiv();

  const mousePosition = new Vector2();
  const raycaster = new THREE.Raycaster();
  const overlay = new ThreeJSOverlayView(mapOptions.center);

  const scene = overlay.getScene();
  overlay.setMap(map);
  ...

  map.addListener('click', ev => {
    const {domEvent} = ev;
    const {left, top, width, height} = mapDiv.getBoundingClientRect();
    const x = domEvent.clientX - left;
    const y = domEvent.clientY - top;
    mousePosition.x = 2 * (x / width) - 1;
    mousePosition.y = 1 - 2 * (y / height);

    // dont get nothing here...
    raycaster.setFromCamera(mousePosition, overlay.camera);
    const intersects = raycaster.intersectObjects(scene.children, true);
    overlay.requestRedraw();
  });

  overlay.update = () => {
    // ... and here
    raycaster.setFromCamera(mousePosition, overlay.camera);
    const intersects = raycaster.intersectObjects(scene.children, true);
    ...
    overlay.requestRedraw();
  };
})();

Glad if any help, Thanks!