What factors might cause JS to view an iFrame and child as being from different origins when they are located in the same root folder?

Background: This question is in regards to an iFrame and its child document.

According to the MDN, HTMLIFrameElement.contentDocument when element.contentDocument returns null it indicates that JS considers that the document that contains the iFrame and the child document it references are not in the same origin.

If the iframe and the iframe’s parent document are Same Origin,
returns a Document (that is, the active document in the inline frame’s
nested browsing context), else returns null.

Same-origin policy indicates that two URLs have the same origin if they share the same “scheme/host/port tuple”.

Two URLs have the same origin if the protocol, port (if specified),
and host are the same for both.

However, in the simplified example below all of the documents are stored in the same root directory on my hard drive and accessed through an Express server.

Question: The variable interiorParagraph in experiment.js always ends up with the value null instead of a reference to the document. I believe this indicates they aren’t in the same origin, but I’m not entirely certain because I haven’t been able to make any headway. Why am I not getting the result I expected?

Express:

const express = require('express');
const app = express();
const cors = require('cors');
const path = require('path');

app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'views/public')));
app.use(cors({ origin: '*' }));

app.get('/', (req, res) => {
    res.render('index');
});

app.listen(8080, () => {
    console.log('app listening');
});

index.ejs

<head>
    <script src="/js/experiment.js" type="module" defer></script>
</head>
<body>
    
    <iframe src="/html/interior.html" data-iframe></iframe>

</body>

interior.html

<body>
    
    <p data-interior>Hello World</p>

</body>

experiment.js

const iframe = document.querySelector('[data-iframe]');
const interiorParagraph = iframe.contentDocument.querySelector('[data-interior]');

alert(interiorParagraph);

mapbox places the popup in a different location than the pin

My mapbox code when clicking on the point and approaching, places the popup in a different location than the pin.
What could I add to correctly center the popup

map.on('click', 'unclustered-point', (e) => {
            const coordinates = e.features[0].geometry.coordinates.slice();
            const mag = e.features[0].properties.mag;
            const tsunami =
                e.features[0].properties.tsunami === 1 ? 'yes' : 'no';

            // Ensure that if the map is zoomed out such that
            // multiple copies of the feature are visible, the
            // popup appears over the copy being pointed to.
            while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
            }

            map.flyTo({
                zoom: 18,
                center: e.features[0].geometry.coordinates
            });

Convert Discord Attachment to Binary

So I have a discord.js bot. And I want moderators to be able to run a slash command and upload an image to the bot’s directory (folder on my Raspberry Pi, where my bot is hosted). So I made a command,

const fs = require("fs");
const path = require("path");
const Discord = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("addimg")
    .setDescription("Allows Moderators to add needed images.")
    .addAttachmentOption((option) =>
      option
        .setName('image')
        .setDescription('The image you want to add.')
        .setRequired(true)
    ),
  async execute(interaction, client) {
    var image = interaction.options.getAttachment("image");
    console.log(image)
    if(path.parse(image.name).ext == ".png" || path.parse(image.name).ext == ".jpg"){
      await fs.writeFileSync(`../../../imgs/${image.name}`, /*Data*/)
      const embed = new Discord.EmbedBuilder()
        .setTitle(`Image Added!`)
        .setColor("000000")
        .setDescription(`Check it out by using the /img command and choosing ${image}`)

      interaction.reply({ embeds:  });
    }
    else{
      return interaction.reply({ embeds: [new Discord.EmbedBuilder()
        .setTitle(`Failed to Add Image.`)
        .setColor("000000")
        .setDescription(`This format of image is not allowed. Try again with a .png or .jpg image.`)] })
    }
  }
}

But I don’t know how/where to start with converting the Discord Attachment to binary (raw image data). And I know that the Discord Attachments have a .url which maybe should be used? But still I don’t know how I would do that.

How to loop through a subarray of input objects and access value – ReactJS, cannot type in input

I am working on this Form, which will allow to add multiple users and for each user is allowed add multiple goals. However each of these would be an input field. So far I have created the input field for users firstName and lastName and created a button to add more fields, however when I try to map through the goals I am not able to get the value from the goal array.

Here’s the code for each section


//code for setting state
    const [users, setUsers] = useState([ { firstName: '', lastName: '' , goals: [{ mainGoal:'', subTasks:[] }]  }])//empty users array set when we start

Code for the form input


 <label className="boldLabel">Add Member</label>
                                {users.map((input, index) => { //initially we are mappin through the empty users array and creating one field in the return section
                                return (
                                    <div className="singleOwnerField" key={index}>
                                        <Row>                                                                  
                                            <Col>       
                                                <input
                                                    name='firstName'
                                                    placeholder='First Name'
                                                    value={input.firstName}
                                                    onChange={event =>handleAddMore(index,event)}
                                                />
                                            </Col>
                                            <Col>                                        
                                                <input
                                                name='lastName'
                                                placeholder='Last Name'
                                                value={input.lastName}
                                                onChange={event =>handleAddMore(index,event)}
                                            />
                                            </Col>
                                            <Col>
                                            {input.goals.map((goal,i)=>{
                                                return( 
                                                    <input key={i}
                                                    name='mainGoal'
                                                    placeholder='Main Goal Name'
                                                     value={goal.mainGoal}
                                                    onChange={event =>handleAddGoal(index,i,event)}
                                                />
                                                )
                                            })}

Then the function I use to add firstName and lastName to the user object (this works as expected)

    const handleAddMore = (index,event)=>{

        let data=[...users]
        data[index][event.target.name]=event.target.value
        setUsers(data) 
       
    }

Below is the function that is written to pick the input value from the goal input field

const handleAddGoal = (index,goalIndex,event)=>{

        let goalsOfUser=[...users[index].goals]
        goalsOfUser[goalIndex][event.target.name]=event.target.value

          console.log("printing goalsOfUser: " + JSON.stringify(goalsOfUser))
 
        console.log("users" + JSON.stringify(users))
        
       
    }

However when I access goal.mainGoal in the input field (a snippet from the form above) it doesn’t show the value in the input field (ie. cant type in )

                                   <input key={i}
                                                    name='mainGoal'
                                                    placeholder='Main Goal Name'
                                                     value={goal.mainGoal}
                                                    onChange={event 
                                                            =>handleAddGoal(index,i,event)} />

I have tried console.logging in the handleAddGoal() function and it seems to print the user object with the first letter we type in the goal field but is not saved
enter image description here

Build an array of dates with cumulative sum

I am building a dashboard to compare the cumulative spending of the current month against the cumulative spending of the last month. This looks like this:
Expected output

As you can see below, my code is very naive and I am pretty sure it can be improved. Right now I loop many times over the arrays to fill each date of currentMonthSpend with the appropriate sum of transactions that happened on this date, cumulated with the previous values …

Would you be able to guide me with a smarter way of doing it? The current logic is the following:

  • Create the array date objects (with x = date and y = cumulative sum)
  • I already have my list of transactions (with date and amount for each entry which can obviously happen at the same date of another entry)
  • First, I iterate through currentMonthTransactions, I find the corresponding date in currentMonthSpend and I increment the y property
  • Then I iterate through currentMonthSpend and I apply a cumulative sum

Thanks for your help!

const startOfCurrentMonth = moment().startOf("month");
const endOfCurrentMonth = moment().endOf("month");
const currentMonthSpend = [];

while (startOfCurrentMonth.isSameOrBefore(endOfCurrentMonth)) {
  currentMonthSpend.push({ x: startOfCurrentMonth.format("YYYY-MM-DD"), y: 0 });
  startOfCurrentMonth.add(1, "days");
}

const currentMonthTransactions = [
  {
    date: "2022-10-03",
    amount: -50,
  },
  {
    date: "2022-10-04",
    amount: -100,
  },
  {
    date: "2022-10-05",
    amount: -20,
  },
  {
    date: "2022-10-05",
    amount: -10,
  },
  {
    date: "2022-10-08",
    amount: -40,
  },
];

for (let i = 0; i < currentMonthTransactions.length; i++) {
  let index = currentMonthSpend.findIndex((item) => {
    return item.x === currentMonthTransactions[i].date;
  });
  if (index !== -1) {
    currentMonthSpend[index].y += currentMonthTransactions[i].amount;
  }
}

const result = currentMonthSpend.map((obj, index, self) => {
  if (index == 0) {
    obj.y = 0;
    return obj;
  }
  const prevO = self[index - 1];
  obj.y += prevO.y;
  obj.y = +obj.y.toFixed(2);
  return obj;
});

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

Blockly (JS Library) help needed

I am working on Blockly as part of my final year project .
How can i Use JavaScript to assign values to the block of codes then use JavaScript popups(like the prompt() script) to insert the value into a textbox and return it as a blockly block on the blockly interface instead of drag and drop.
Thank you

Laragear / WebAuthn ERROR POST /webauthn/register 422 at webauthn.js:159

HELP

Please i am trying to use Laragear/WebAuthn in my app i have to upgrade to laravel 9 in other this package

after setting up i got an Issue registering Device…
I get 422 Error Code

Here is the response from console

POST https://example.com/webauthn/register 422
#fetch @ webauthn.js:159
register @ webauthn.js:317
await in register (async)
(anonymous) @ settings:1690
dispatch @ jquery.min.js:3
q.handle @ jquery.min.js:3

Response {type: 'basic', url: 'https://example.com/webauthn/register', redirected: false, status: 422, ok: false, …}

Here are my codes for registration

const webAuthn = new WebAuthn({
    registerOptions: '/webauthn/register/options',
    register: '/webauthn/register',
});

webAuthn.register()
.then(response => {
    console.log(response);
    //My Codes
})
.catch(response => {
    console.log(response);
   //My Codes
})

Please How will i solve this or what could be the problem

Android native method from Quasar JS framework

How to call native android Java method from Quasar? Example: NativeAndroid.pasteFromClipboard() in JS.
Perhaps someone knows how to implement this from Quasar. The fact is that the paste from clipboard function does not work in Quasar.
For the WebView, I use the call as in the example, and in the activity the following code:

import android.content.ClipData;
import android.content.ClipboardManager;
import android.webkit.JavascriptInterface;

public class MainActivity extends AppCompatActivity {

    private WebView webView;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        webView = new WebView(MainActivity.this);// webview in mainactivity
        setContentView(webView);// set the webview as the layout 
        webView.getSettings().setJavaScriptEnabled(true);
        webView.addJavascriptInterface(new WebAppInterface(), "NativeAndroid");
        webView.loadUrl("file:///android_asset/index.html");

    }
    
    public class WebAppInterface {
        @JavascriptInterface
        public String pasteFromClipboard() {
            ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
            String text = clipboard.getText().toString();
            return text;
        }
    }
}

( Check element in viewport ) for multi elements

This will be so much code in multi element check.

$(window).scroll(function() {
    let top_of_element = $("#element").offset().top;
    let bottom_of_element = $("#element").offset().top + $("#element").outerHeight();
    let bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
    let top_of_screen = $(window).scrollTop();

    if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        $('#element').addClass('in-view')
    }
    else{
        $('#element').removeClass('in-view')
    }
});

I created this function but was not work:

$(window).scroll(viewport("#element"));
function viewport(selector) {
    let top_of_element = $(selector).offset().top;
    let bottom_of_element = $(selector).offset().top + $(selector).outerHeight();
    let bottom_of_screen = $(window).scrollTop() + $(window).innerHeight();
    let top_of_screen = $(window).scrollTop();

    if ((bottom_of_screen > top_of_element) && (top_of_screen < bottom_of_element)){
        $(selector).addClass('in-view')
    }
    else{
        $(selector).removeClass('in-view')
    }
}

if replace parameter with your selector nothing happened.
Please tell me what I have to do…
Thanks.

i want to get the GST percentage of 10% in the total bill amount, how would i do that with javascript

I am creating a online estimator with vanilla js, now at the end i want to calculate after the total cost i want to add 10% on top that. How would I add the 10% in the total bill amount with JS?

Now how would I get the total bill amount which includes GST as well.

Please help me with this, I’ll be really thankful.

Thanks and Regards in Advance

Here is my code

 var product_total = document.getElementById('product_total');
        var call_cost = document.getElementById('call_cost');
        var gst = document.getElementById('tax') / 100;

        
        // Decrease Number //
        const decreaseNumber = (incdec,itemprice) => {
            var itemval = document.getElementById(incdec);
            var itemprice = document.getElementById(itemprice);

            console.log(itemval.value);

            if(itemval.value <= 0){
                itemval.value = 0;
                alert('Negative Quantity Not Allowed. Please Select Atleast One Service');
            }
            else{
                itemval.value = parseInt(itemval.value) - 1;
                itemval.style.background = '#fff';
                itemval.style.color = '#000';
                itemprice.innerHTML = parseInt(itemprice.innerHTML) - 70;
                product_total.innerHTML = parseInt(product_total.innerHTML) - 70;
                net_amount.innerHTML = parseInt(product_total.innerHTML) + parseInt(call_cost.innerHTML);
                document.getElementById("net_amount_total").value=  parseInt(product_total.innerHTML) + parseInt(call_cost.innerHTML);
//              document.getElementById("service_name").value
            }
        }
        
        //Increase Number
        const increaseNumber = (incdec,itemprice) => {
            var itemval = document.getElementById(incdec);
            var itemprice = document.getElementById(itemprice);

            if(itemval.value >= 10){
                itemval.value = 10;
                alert('Maximum Number of Services Upto 10 Allowed');
                itemval.style.background = 'red';
                itemval.style.color = '#fff';    
            }
            else{
                itemval.value = parseInt(itemval.value) + 1;
                itemprice.innerHTML = parseInt(itemprice.innerHTML) + 70;
                product_total.innerHTML = parseInt(product_total.innerHTML) + 70;
                net_amount.innerHTML = parseInt(product_total.innerHTML) + parseInt(gst.innerHTML) + parseInt(call_cost.innerHTML);
                // net_amount.innerHTML = parseInt(gross_amount.innerHTML) / 10%;
                document.getElementById("net_amount_total").value=  parseInt(product_total.innerHTML) + parseInt(call_cost.innerHTML);
                 
            }
        } 
  <div class="summery-list">
    <div class="icon">
      <img class="img-fluid" src="https://wefreelancer.in/love/ntcc/wp-content/themes/ntcc/images/bathroom-color-icon.png" alt="">
    </div>
    <div class="title">
       <h4>GST</h4>
    </div>
    <div class="price">
       <h4><span id="tax">10%</span></h4>
    </div>
</div>

How can i get the value of an object inside of array and put on the DOM but each time that i push the button change it to the next object

const btnReload = document.querySelector(‘#button’);

btnReload.addEventListener(‘click’, reload);

function reload () {

    const conjunto = words.map((word) => word.word);
    const conjunto2 = words.map((word) => word.palabra);
    const conjunto3 = words.map((word) => word.sentence);
    const conjunto4 = words.map((word) => word.oracion);

    wordy.textContent = conjunto[0]
    palabraHTML.textContent = conjunto2[0]
    sentence.textContent = conjunto3[0]
    oracion.textContent = conjunto4[0]

}

const words = [

{
word: “the”,
palabra: “El / Los”,sentence: “The sun is up”,
oracion: “El sol ha salido”
},
{
word: “be”,palabra: “Ser / Estar”,sentence: “Don’t be sad”,
oracion: “No estes trsite”
},
{
word: ‘as’,palabra: ‘como (adv.)’,sentence: ‘He used me as a guinea pig’,
oracion: ‘Me utilizó como conejillo de indias’
},
{
word: ‘will’, palabra: ‘(futuro), voluntad’, sentence: ‘Will she come?’,
oracion: ‘¿Vendrá? (Ella)’
}

MongoServerError: Can’t $out to internal database

enter image description here

I’m trying to filter a collection in mongo and then copy the result to a new collection. Working in the navigator UI’s mongo shell I tried:

db.test2.aggregate( [ { $match: {'Property Type': {pattern: 'Land',options: ''}} }, { $out: "test3" } ])

test2 is the source, I have created test3 in the ‘local’ db, as well

What am I doing wrong?

d3 (v7) Horizontal Bar Chart — unexpected offsetting of y-axis

I am trying to make a horizontal stacked bar chart, starting with this code snippet, updating to d3 v7. Instead of getting a neatly stacked bar chart, each subsequent bar in a stack is getting offset vertically down from where it should be. When I inspect the yScale value, I get the expected value, so I’m extra-confused about this behavior.

I’d include just the relevant piece of the puzzle, but I honestly don’t know where my problem is — am I appending to the wrong ‘g’ element? Using enter() on the wrong piece of data?

enter image description here

<script src="https://d3js.org/d3.v7.min.js"></script>

<body>
  <div id="bar_chart">
    <script>
      var data = [{
          dep_time: "5:30",
          risk: 100,
          details: [{
              time: 19,
              source: 'Drive'
            },
            {
              time: 10,
              source: 'Margin'
            },
            {
              time: 42,
              source: 'Full'
            },
            {
              time: 35,
              source: 'Crossing'
            },
            {
              time: 23,
              source: 'Drive'
            }
          ]
        },
        {
          dep_time: "6:20",
          risk: 80,
          details: [{
              time: 25,
              source: 'Drive'
            },
            {
              time: 1,
              source: 'Margin'
            },
            {
              time: 38,
              source: 'Full'
            },
            {
              time: 35,
              source: 'Crossing'
            },
            {
              time: 25,
              source: 'Drive'
            }
          ]
        },
        {
          dep_time: "7:10",
          risk: 5,
          details: [{
              time: 8,
              source: 'Drive'
            },
            {
              time: 28,
              source: 'Margin'
            },
            {
              time: 38,
              source: 'Full'
            },
            {
              time: 35,
              source: 'Crossing'
            },
            {
              time: 18,
              source: 'Drive'
            }
          ]
        }
      ];

      var chartContainer = '.chart-container';

      var units = [];
      var xMax = 0;
      data.forEach(function(s) {
        var total = 0;
        s.details.forEach(function(s) {
          s["x0"] = total; //Abs left
          s["x"] = s.time; //Width
          s["x1"] = total + s.time; //Abs right
          total = total + s.time;
          if (total > xMax) xMax = total;
        });
        s["y"] = s.dep_time;
        units.push(s.dep_time);
      });

      //Need it to look like: newdata = [(Drive) [19, 25, 32.]  Margin [0, 1, 28].  Full [42, 38, 38].  Crossing [35, 35, 35].  Drive [23, 25, 18].]
      //So it's a row in the array for each column of data.  
      //re-arrange the data so it makes more sense to d3 (and less sense to any sane human)
      var newdata = [];
      for (var i = 0; i < data[0].details.length; i++) {
        var row = [];
        data.forEach(function(s) {
          row.push({
            x: s.details[i].x,
            y: s.dep_time,
            x0: s.details[i].x0
          });
        });
        newdata.push(row);
      }
      console.log("newdata");
      console.log(newdata);

      var margins = {
        left: 50,
        bottom: 50,
        top: 25,
        right: 25
      };

      var sizes = {
        width: 500,
        height: 150
      };

      var width = sizes.width - margins.left - margins.right;
      var height = sizes.height - margins.bottom - margins.top;

      var svg = d3.select("#bar_chart")
        .append('svg')
        .attr('width', width + margins.left + margins.right)
        .attr('height', height + margins.bottom)
        .append('g')
        .attr('transform', 'translate(' + margins.left + ', ' + margins.top + ")");

      var yScale = d3.scaleBand()
        .domain(units)
        .rangeRound([0, height]);

      var yAxis = d3.axisLeft(yScale);
      var yAxisG = svg.append("g")
        .attr("transform", "translate(0,0)")
        .attr("id", "yaxis")
        .call(yAxis);

      const xScale = d3.scaleLinear()
        .domain([0, xMax])
        .range([0, width]);
      var xAxis = d3.axisBottom(xScale);
      var xAxisG = svg.append("g")
        .attr("transform", "translate(0, " + height + ")")
        .attr("id", "xaxis")
        .call(xAxis
          .ticks(8));

      var bar_colors = ['red', 'purple', 'green', 'lightblue', 'yellow'];
      var colors = function(i) {
        return bar_colors[i];
      }

      var groups = svg.selectAll('g')
        .data(newdata)
        //.exit()
        .append('g')
        .style('fill', function(d, i) {
          console.log("d");
          console.log(d);
          //console.log("i"); console.log(i);
          return colors(i);
        });

      console.log(groups);

      groups.selectAll('rect')
        .data(function(d) {
          //console.log(d); 
          return d;
        })
        .enter()
        .append('rect')
        .attr('x', function(d) {
          //console.log("x0"); console.log(d.x0);
          return xScale(d.x0);
        })
        .attr('y', function(d, i) {
          //console.log(yScale(d.y));
          //console.log(i);
          return yScale(d.y);
        })
        .attr('height', 10) //function (d) {return yScale.rangeBand();})
        .attr('width', function(d) {
          return xScale(d.x);
        });
    </script>
  </div>
</body>

And, for whatever reason, it doesn’t seem to work as a StackOverflow code snippet.

Handling data rendering on redux state change

I’m trying to setup a form. It has Edit feature where on edit I call an API and get the data into state.
I’m struggling to display data in the form after api call. There’s no problem utilizing the API or calling the redux functions. Problem is that my Form only displays last data in the redux state but not the updated data.

That’s how I’m doing the stuff.

  1. Calling API if isEdit===True at the same time Form is being displayed on component mount.

  2. Updateding state after success as an object called customer

  3. accessing the customer object like this

    const { customer } = useSelector((state) => state.customers)

Lets say I have a input field where I want to display the email of customer.

I’m handling this think like that:

email: isEdit ? customer?.email : '', // At this point there is some problem 

It loads the previous data that was stored in the state.customer but not the new one.
I believe my email field is rendering first and then doesn’t updated the value when change happens in state.customer.

So how I can fix this? So that email value should be changed at the same time if state.customer got changed