How to read JSON using fs.readFile and push the result to an empty array [duplicate]

So i have a JSON file (let’s call it file.json) that looks like this

{"text": "sample text"}

And i was trying to read file.json using fs.readFile and push sample text to an empty array. Here’s my attempt at it

const fs = require('fs');

const file = './file.json'

let filledArray = [];

fs.readFile(file, 'utf-8', (err, data) => {
        if (err) {
                return console.log(`Error : ` + err);
        }
        filledArray.push(JSON.parse(data)['text']);
        });

console.log(filledArray)

But the resulting console.log(filledArray is :

object
[]

While what I wanted would be something like this :

['sample text']

Thank you in advance and I would very appreciate your input!

How can I make an input label clickable? (initiate text input)

I’m currently working on a project fiddling with animations on select and was creating a signup form (re-created it on my replit – https://replit.com/join/gzflphmalc-jeezgeorge
)

Everything seems to be working fine except for the fact that when I click on the name of the label (name, email, password) it doesn’t initiate the text input.

How can I wrap the label with the input so that when I click on the name as well it will initiate the input.

Thanks in advance. 🙂

How do I make a reusable component for this version of Autocomplete?

I am using this Autocomplete a few times. However I have this useStates that needs to be defined so I’m quite confused on how I can make this as a reusable component?

 <Autocomplete
        required
        value={firstName}
        onChange={(event, newValue) => {
          if (typeof newValue === "string") {
            setFirstName(newValue);
          } else if (newValue && newValue.inputValue) {
            // Create a new value from the user input
            setFirstName(newValue.inputValue);
          } else {
            setFirstName(newValue);
          }
        }}
        selectOnFocus
        clearOnBlur
        handleHomeEndKeys
        id="free-solo-with-text-demo"
        options={data}
        getOptionLabel={(option) => {
          // Value selected with enter, right from the input
          if (typeof option === "string") {
            return option;
          }
          // Add "xxx" option created dynamically
          if (option.inputValue) {
            return option.inputValue;
          }
          // Regular option
          return option.firstName;
        }}
        renderOption={(props, option) => <li {...props}>{option.firstName}</li>}
        sx={{ width: 300 }}
        freeSolo
        renderInput={(params) => <TextField {...params} label="First Name" />}
      />

How can I make two buttons with the same function work?

and thank you for your time. Since I’ve added two+ buttons (run the code and press the “add table” button), all it does is add two new rows to the first table, and the subsequent buttons don’t work. I’ve tried calling the classes, using the loop, and putting the code where it should be, but it still refuses. Here is my code:

<!DOCTYPE html>
<html>
<head>
  <link rel="stylesheet" type="text/css" href="WELPPproto.css">
</head>
<body>
<h1 style="font-family:verdana">Word List</h1>
<table id="list">
  <tr>
    <th scope="col">Word</th>
    <th scope="col">English</th>
    <th scope="col">Pronunciation</th>
    <th scope="col"><button class="deletethismaybe" id="deletethismaybe" type="button" title="delete this table">X</button></th>
  </tr>
  <tfoot>
    <tr>
      <div class="boxy_gril">
        <td><input type="text" id="w" class="w" required /></td>
        <td><input type="text" id="m" class="m" required /></td>
        <td><input type="text" id="p" class="p" /></td>
      </div>
    </tr>
    <tr>
      <td colspan="3"><div class="button_boi"><button type="button" class="button_boi" id="add">Enter</button>
</div></td>
    </tr>
  </tfoot>
</table>
<div id="ntable" class="ntable" >
  <section>
    
  </section>
</div>
  <br>
  <br>
  <button class="button_gril" id="addtable">Add Table</button>
<script>
document.getElementById("addtable").onclick = function() {
  let puttable = document.getElementById("ntable");
  let section = puttable.querySelector('section');

  let tableHTML = '<br><br>' + '<table id="list">' + '<tr>' +
    '<th scope="col">' + 'Word' + '</td>' +
    '<th scope="col">' + 'English' + '</th>' +
    '<th scope="col">' + 'Pronunciation' + '</th>' + '<th><button class="deletethismaybe" id="deletethismaybe" type="button" title="delete this table">X</button></th>' + 
    '</tr>' +
    '<tfoot><tr><div class="boxy_gril">' + 
    '<td><input type="text" id="w" class="w" required /></td>'+
    '<td><input type="text" id="m" class="m" required />' + 
    '</td><td><input type="text" id="p" class="p" /></td>' + 
    '</div></tr>' + '<tr>' + '<td colspan="3">' + '<div class="button_boi">' + '<button type="button" class="button_boi" id="add">Enter</button>' + '</div>' + '</td>'+ '</tr>' + '</tfoot>' + '</table>';
    
   section.insertAdjacentHTML('beforebegin', tableHTML);
  
}

document.addEventListener('click', (e) => {
  let thatTarget = e.target;
  let thatBtn = thatTarget.closest('.deletethismaybe');
  if (thatBtn) {
    e.preventDefault();
    thatTarget.closest('table').remove();
    thatTarget.closest('button').remove();
  }
})

var asdf = document.getElementsByClassName("button_boi");
for (var i = 0; i < asdf.length; i++) {

asdf[i].onclick = function() {
  let listTable = document.getElementById("list");
  let tfoot = listTable.querySelector('tfoot');

  let wordValue = document.getElementById("w").value;
  let engValue = document.getElementById("m").value;
  let pronunValue = document.getElementById("p").value;

  let trHTML = '<tr>' +
    '<td>' + wordValue + '</td>' +
    '<td>' + engValue + '</td>' +
    '<td>' + pronunValue + '</td>' + '<td><button class="deletethis" type="button" title="delete this row">X</button></td>' +
  '</tr>';
  
  tfoot.closest('tfoot').insertAdjacentHTML('beforebegin', trHTML);
}
}

document.addEventListener('click', (e) => {
  let thisTarget = e.target;
  let thisBtn = thisTarget.closest('.deletethis');
  if (thisBtn) {
    e.preventDefault();
    thisTarget.closest('tr').remove();
  }
})

document.getElementsByClassName('.deletethismaybe').onclick = function() {
let thatTarget = e.target;
let thatBtn = thatTarget.closest('.deletethismaybe')
  if (thatBtn) {
    e.preventDefault();
    thatTarget.closest('table').remove();
  }}
</script>
</body>
</html>

query mongo based on results of query

I have this mongoose query:

let rE = await cR.find({myid: "xxxxxx"});

now this query will return multiple results, in which I then need to query another model based off of the rE.class_id, which is returned through rE, the query above. So I do this:

let cla = await Cl.find({_id: rE.class_id});

however, that obviously doesn’t work because rE.class_id gets returned as multiple objects, so placing rE.class_id just wont work. How can I get this to work?

Submitting Form Data to Cloud Firestore using JavaScript

Good evening Firebase community! I hope you are having a blessed day! I building a website for a nonprofit organization and am hoping to gain some help. I am using Firebase hosting to serve a page that has a form in it, and want to use JavaScript to submit the form data to FireStore. When I click the “submit” button, the browser console shows that it captured the user’s input, but it is not sending it to Firestore Database. Could someone please point me on the right path? it would be greatly appreciated. The following is what I have so far:

   

//firebase.js
import {
  initializeApp
} from "firebase/app";
import {
  getAnalytics
} from "firebase/analytics";
import {
  getFirestore,
  collection,
  getDocs
} from "firebase/firestore";


// TODO: Add SDKs for Firebase products that you want to use

// https://firebase.google.com/docs/web/setup#available-libraries


// Your web app's Firebase configuration

// For Firebase JS SDK v7.20.0 and later, measurementId is optional

const firebaseConfig = {

  apiKey: "***********",

  authDomain: "***********",

  projectId: "***********",

  storageBucket: "***********",

  messagingSenderId: "***********",

  appId: "***********",

  measurementId: "***********"

};


// Initialize Firebase

const app = initializeApp(firebaseConfig);

// Initialize Cloud Firestore and get a reference to the service
const db = getFirestore(app);


const analytics = getAnalytics(app);


/////////////////////////////////////////////////////////
//partnerScripts.js

import {
  collection,
  addDoc
} from "firebase/firestore";

//Get Form Values
const prefix = document.getElementById('prefixes').value
const firstName = document.getElementById('givenName').value
const lastName = document.getElementById('surName').value
const title = document.getElementById('title').value
const organization = document.getElementById('organization').value
const website = document.getElementById('website').value
const email = document.getElementById('email').value
const phone = document.getElementById('areaCode').value + '-' + document.getElementById('lead3') + '-' + document.getElementById('last4')
const interests = `${document.getElementById('selectAll').value}n${document.getElementById('bolPantry').value}n${document.getElementById('FeedMySheep').value}n${document.getElementById('GiftedShop').value}n${document.getElementById('GoodNews').value}n${document.getElementById('KingdomsFlock').value}n${document.getElementById('OutdooBazaar').value}`

const description = document.getElementById('description')

const submitButton = document.getElementById('submit')

submitButton.addEventListener("click", (e) => {
  try {
    const docRef = await addDoc(collection(db, "partnerRequests"), {
      prefix: prefix,
      FirstName: firstName,
      LastName: lastName,
      Title: title,
      Organization: organization,
      Website: website,
      Email: email,
      PhoneNumber: phone,
      Interests: interests,
      TellUsWhy: description

    });
    console.log("Document written with ID: ", docRef.id);
  } catch (e) {
    console.error("Error adding document: ", e);
  }
})
//partners.html
<form id="partnerForm" autocomplete="on">
  <div class="w3-row w3-padding-large" id="row1">
    <div class="w3-container w3-quarter">
      <label for="prefix">Prefix:</label><br>
      <select class="w3-white" id="prefixes" name="prefix">
        <option value="not-selected"></option>
        <option value="mr">Mr.</option>
        <option value="mrs_and_ms">Mrs. / Ms.</option>
      </select>
    </div>
    <div class="w3-container  w3-quarter">
      <label for="givenName">First Name:</label>
      <input class="w3-white" style="max-width: 100%;" type="text" id="givenName"    name="gname" required>
    </div>
    <div class="w3-container w3-content w3-quarter">
      <label for="surName">Last Name:</label>
      <input class="w3-white" style="max-width: 100%;" type="text" id="surName" name="sname" required>
    </div>
    <div class="w3-container w3-quarter">
      <label for="Title">Title:</label>
      <input class="w3-white" style="max-width: 100%;" type="text" id="title" name="title">
    </div>
  </div>


  <div class="w3-row w3-padding-large" id="row3">
    <div class="w3-container w3-cell w3-left-align w3-half w3-mobile">
      <h2>Areas of Interest</h2>
      <input type="checkbox" id="selectAll" name="interests" value="all">
      <label for="selectAll">All Aspects of C.O.M.E.</label><br><br>
      <input type="checkbox" id="bolPantry" name="interests" value="bolPantry">
      <label for="bolPantry">Bread of Life Pantry</label><br><br>
      <input type="checkbox" id="FeedMySheep" name="interests" value="FeedMySheep">
      <label for="FeedMySheep">Feed My Sheep</label><br><br>
      <input type="checkbox" id="GiftedShop" name="interests" value="GiftedShop">
      <label for="GiftedShop">Gifted Shop</label><br><br>
      <input type="checkbox" id="GoodNews" name="interests" value="GoodNewsGiveaway">
      <label for="GoodNewsGiveaway">Good News Giveaway</label><br><br>
      <input type="checkbox" id="KingdomsFlock" name="interests" value="KingdomsFlock">
      <label for="KingdomsFlock">Kingdom's Flock</label><br><br>
      <input type="checkbox" id="OutdoorBazaar" name="interests" value="OutdoorBazaar">
      <label for="OutdoorBazaar">Outdoor Bazaar</label><br>

    </div>
    <div class="w3-container w3-cell w3-half w3-mobile">
      <p>Please describe your proposed partnership below.<br>Please include what <em>you and/or your organization</em>
        <br>(are/is) hoping to gain from our partnership,<br> what you are able to contribute, <br> how our missions and goals are aligned, <br> and any other details that will aid in getting to know you.
      </p>

      <textarea class="w3-white w3-col" style="height:200px; align-content:left;" cols="100" id="description" name="tellUsWhy" wrap="hard" required></textarea>
    </div>
  </div>
  <input class="w3-btn submit form w3-white w3-border we-border-black w3-round-xxlarge w3-hover-deep-purple" id="submit" type="submit" value="Submit">
</form>
<script src="firebase.js"></script>
<script src="partnerScripts.js"></script>

How to hard set position of div tags in ReactJS?

I have implemented the custom control code for the above map using ReactJS.

In the topright position I have a custom control for drawing and choosing colors. Between these two controls, they all use the same props from a parent component.

However, every time I click to select a color, the app re-renders and the positions of the controls are changed.

So is there a way I can prevent the position from changing every time I select the color and change the props of those two controls?

Link demo this bug: https://youtu.be/29mcGWykyoY

Link about my component: Image

How to Add specific values to an array? [duplicate]

I am creating a function which takes in a minimum and max value. The output should list all the even numbers between these two parameters. I have attempted at creating an array to display these numbers but I get this output:

evenNumbers(4,13) returns: undefined
evenNumbers(3,10) returns: undefined
evenNumbers(8,21) returns: undefined

How to fix my code so it shows the list properly?

var evenNumbers = function(minNumber, maxNumber){
      var list = [];
      for (let i = minNumber; i < maxNumber; i++){
        if (i % 2 == 0){
          for(let k = 0; k < maxNumber; k++){
           i = list[k];
          }
          
        }
      }
      return console.log(list);
    }
    
    console.log('evenNumbers(4,13) returns: ' + evenNumbers(4,13));
    console.log('evenNumbers(3,10) returns: ' + evenNumbers(3,10));
    console.log('evenNumbers(8,21) returns: ' + evenNumbers(8,21));

How to call this API using c# or Javascript?

How to call this API using C# OR JAVASCRIPT

 <Message>
    <Header>
        <SequenceNumber>37</SequenceNumber>
        <TransactionType>INC</TransactionType>
        <ReferenceType>S</ReferenceType>
        <Request>true</Request>
        <SiteCode>1</SiteCode>
    </Header>
    <Body>
        <InquiryRequest>
            <RevenueCenter>111</RevenueCenter>
            <Reference1>12345</Reference1>
            <MaxRecords>12</MaxRecords>
        </InquiryRequest>
    </Body>
</Message>

I’m using console application here using POST REQUEST

Detect When Angular Completes Data Insertion/Updating

In simple terms: I want to perform a callback of a custom typescript function AFTER Angular’s HttpClient acquires data and Angular appends that data to an ng template in the DOM. I have tried to set it up to call the function after the data is appended, but the issue is that the HttpClient and ng templating is asynchronous, so my custom function is called immediately after the HttpClient function is called. I want to wait for everything to finish before calling that custom function.

I would provide some code, but I don’t have anything definitive to show. I am hoping that there is an event I can subscribe to that tells me when everything is done, from which I can then perform the callback. Below is a stepped explanation of how I want the events to occur:

  1. User requests new data
  2. Angular performs HttpClient GET call
  3. Server sends new data to browser
  4. Angular retrieves data and appends it to ng template in DOM (updates DOM)
  5. Perform custom callback function

I have already tried adding basic JS event listeners, but they aren’t working correctly or get called too many times. I have also tried using Angular’s “ngOnChanges” and similar functions, but they either called the function too many times or I was using them incorrectly.

Using Angular v14.0.

Can’t add text node to div class using appendChild and getElementById

trying to add text to an existing div element using a script. It should add text to the element with the id “TopBarContainer, but nothing happens when I run the script.

I tested out creating the text and just adding it to the document body whenever the script is run to make sure it is not an issue with the script call, or the creation of the text/text container and this worked fine.

I am very new to html and javascript. This seems like it should be very simple, but I’ve looked at the tutorial on W3, searched on stack overflow, and looked at some info on the appendChild and getElementById and wasn’t able to figure out what I missed.

The relevant part of the script:

<div class="top" id= "TopBarContainer">
    <img src="webibarmax.png" id="topbar" title="The bar" alt="Superbar">
</div>

<script>
    myScript() {
    var TextContainer = document.createElement("p");
    var TextItem = document.createTextNode("textextext");
    TextContainer.appendChild(TextItem);

    document.getElementById("TopBarContainer").appendChild(TextContainer);
        

    document.body.appendChild(TextContainer);}

</script>

HTML Canvas blurry in Safari but not Chrome after translate3d

Running into an interesting canvas bug: after translating a canvas, the pixels appear blurry on Safari but not Chrome.

I’ve tried just about every image-rendering and imageSmoothing trick to no avail.

Here’s a codepen where I’ve been able to reproduce the issue: https://codepen.io/plillian/pen/RwQegyR

Is this a just Safari bug? Or is there a way to force nearest neighbor in Safari as well?

customization in react auth0

I am using @auth0/auth0-react library to handle authentication process. For an unauthorized user, it will redirect to back to initial screen (“/”) route with this query params. ?error=unauthorized... Then again if I am trying to execute the login it will stay on the same page. Maybe I need to find a way to clear the previous auth0 state.

const { loginWithRedirect, logout} = useAuth0();
const loginWithAuth0 = () => {
    logout({}); // clear previous auth 0 state
    loginWithRedirect({
        redirectUri: window.location.origin + "/dashboard"
    });
};

Above is my attempt. Using logout({}) I am trying to clear the previous auth0 state and going forward which doesn’t happen. For an authorized user there’s no issues. So what I need is to handle the unauthorized user behaviour. Currently it will not redirect to the dashboard which is correct for unauthorized. But what I need is to clear the previous auth0 state and redirect to the next attempt. How can I achieve it?

can I use both ‘unsafe-inline’ and ‘unsafe-eval’ in the same script-scr or do I need to add a new script-scr?

I am working with the gatsby-plugin-csp and want to understand if it is possible to add two keywords both ‘unsafe-inline’ and ‘unsafe-eval’ in the same script-scr and make them work? Or do I need to create two different script-scr? There are a few sources that I must use and some them of need eval() and others inline scripts.

Can I do this?

// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-csp`,
      options: {
        disableOnDev: true,
        reportOnly: false, // Changes header to Content-Security-Policy-Report-Only for csp testing purposes
        mergeScriptHashes: true, // you can disable scripts sha256 hashes
        mergeStyleHashes: true, // you can disable styles sha256 hashes
        mergeDefaultDirectives: true,
        directives: {
          "script-src": "'self' 'unsafe-inline' 'unsafe-eval' www.example.com",
          "style-src": "'self' 'unsafe-inline'",
          "img-src": "'self' data: www.google-analytics.com"
          // you can add your directives or override defaults
        }
      }
    }
  ]
};

Or should I do this?

// In your gatsby-config.js
module.exports = {
  plugins: [
    {
      resolve: `gatsby-plugin-csp`,
      options: {
        disableOnDev: true,
        reportOnly: false, // Changes header to Content-Security-Policy-Report-Only for csp testing purposes
        mergeScriptHashes: true, // you can disable scripts sha256 hashes
        mergeStyleHashes: true, // you can disable styles sha256 hashes
        mergeDefaultDirectives: true,
        directives: {
          "script-src": "'self' 'unsafe-inline' www.example.com",
          "script-src": "'self' 'unsafe-eval' www.example.com",
          "style-src": "'self' 'unsafe-inline'",
          "img-src": "'self' data: www.google-analytics.com"
          // you can add your directives or override defaults
        }
      }
    }
  ]
};

I have tried using the first option with both ‘unsafe-inline’ and ‘unsafe-eval’ in this case half of them give errors like Refused to load the script 'http://embed.example.com/next/embed.js' because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval'

I also get this error Refused to execute inline script because it violates the following Content Security Policy directive: "script-src 'self' 'unsafe-inline' 'unsafe-eval' https://www.google-analytics.com https://www.googletagmanager.com

When I change the order of the keywords putting ‘unsafe-eval’ then ‘unsafe-inline’ I still get errors refusing to run other scripts.

how to define an empty class in jquery?

image table

Currently, I’m doing a system where is manager can assign the job to workers. I have a table listing. In this table listing, when I click at Job Order Number, there will be a popup modal. What I’m having right now is, if the job status is pending, I want to show a different popup modal . Do you guys have any idea how can I achieve that ?

Currently, I’m doing like this where I declare the modal popus using php class.

 <td id="testing" data-id="<?php echo $row['jobregister_id'];?>" class = "<?php echo $row["job_status"]; ?>" data-target="doubleClick-info"  onClick="document.getElementById('doubleClick-info').style.display='block'"><?php echo $row["job_order_number"]; ?></td>
    <td><?php echo $row["job_priority"]; ?></td>
    <td"><?php echo $row["job_status"]; ?></td>

and here is my ajax for job status pending

 <div id="doubleClick-info" class="modal">
<div class="tabInfo">

    <input type="radio" name="tabDoingInfo" id="tabDoingInfo1" checked="checked">
    <label for="tabDoingInfo1" class="tabHeadingInfo"> Job Info </label>
    <div class="tab" id="JobInfoTab">
    <div class="contentJobInfo">
    <div class="techClose" data-dismiss="modal" onclick="document.getElementById('doubleClick-info').style.display='none'">&times</div>
    <form action="homeindex.php" method="post">
    <div class="info-details">
    
    </div></form></div></div>

    <script type='text/javascript'>
        $(document).ready(function () {
        $('body').on('click','.Pending',function(){
        // $('.JobInfo').click(function () {
        var jobregister_id = $(this).data('id');

        // AJAX request
        $.ajax({
        url: 'ajaxhomepending.php',
        type: 'post',
        data: { jobregister_id: jobregister_id },
        success: function (response) {
        // Add response in Modal body
        $('.info-details').html(response);
        // Display Modal
        $('#doubleClick-info').modal('show');
                    }
                });
            });
        });

    </script>

it all seems fine. i define the javascript using class. but when the class have no value, how do i define it ? do you guys have any idea how to do it. thank you so much.