Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. ERROR HAPPENS SOMETIMES?

To preface, this is the error.

Promise { <pending> }
nodejsprojectnode_modulesfirebase-adminlibutilserror.js:44
        var _this = _super.call(this, errorInfo.message) || this;
                           ^
FirebaseAppError: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".
    
  errorInfo: {
    code: 'app/invalid-credential',
    message: 'Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".'
  },
  codePrefix: 'app'
}

From my understanding, this error is because my params are invalid or something causing an improper initialization of firebase.

Now I am initializing the app like this: initializeApp();.

So the initialization works. When I run a command such as const userInfo = await getAuth().verifyIdToken(authorization); the command works and I get userInfo but when I run a command such as const userInfo = await getAuth().getUser(uuid); it fails.

To my knowledge, the syntax is right and how I’m using the methods are right as well. I’m just unsure why I get an initializeApp error when using one method but not another.

Grouping a base64->buffer hex string by bytes in Javascript?

I’m trying to take a Base64 string, convert it to a hex string and group the output by bytes.

I’d like the output of console.log(bufferString) to be:

03 67 00 cf 04 68 61 00 ff 01 2d

But I’m stuck with this output:

036700cf04686100ff012d

What I’ve got so far…

let request = {
    "PayloadData": "A2cAzwRoYQD/AS0=",
    "FPort": 10
  }

let buffer = Buffer.from(request.PayloadData, 'base64');
let bufferString = buffer.toString('hex');

console.log(bufferString)

Upload pdf file to Firebase Storage, save link to firestore, and can download the pdf file after refresh with Nuxt & Vuetify

How can I upload a file (pdf) to Firebase Storage after a button is clicked and then get the URL (using getDownloadURL() I guess?). After that, whenever a user is logged in the next time, they can download the file on the same page that they upload it.

Currently I managed to upload the file to firebase storage. But I still cannot save the file URL into firestore user’s document. and how can I get the file from firebase so that I can download it later?

I’m using Nuxt.js and Vuetify to do it.

template

                        <v-card>                      
                            <v-file-input
                                outlined
                                show-size
                                counter
                                prepend-icon="mdi-file-upload-outline"
                                :rules="fileRules"
                                accept=".pdf"
                                v-model="ssm" 
                                style="margin: 1rem;">
                            </v-file-input>
                            <v-btn
                                @click="uploadFile">
                                Upload</v-btn>
                        </v-card>

script

    data: () => ({
        fileRules: [
            value => !value || value.size < 2000000 || 'File size should not exceeded 1MB!',
        ],
        ssm: '',
    }),

    methods: {
        saveToFirestore() {
            var data = {
                ssm: this.ssm,
            };
            firestore
                .collection('SubcontractorRegistration')
                .doc(firebase.auth().currentUser.uid)
                .update(data)
                .then(() => {
                    console.log('hello world!')
                })

        },

        uploadFile(file) {
            var uidRef = firebase.auth().currentUser.uid
            const filePath = `SubcontractorRegistration/${uidRef}/${file.name}`;
            const metadata = { contentType: this.ssm.type };
            FirebaseStorage.ref()
                .child(filePath)
                .put(this.ssm, metadata)
                .then(() => {
                    FirebaseStorage
                        .ref()
                        .child(filePath)
                        .getDownloadURL()
                        .then((url) => {
                            this.ssm = url;
                        })
                    this.saveToFirestore();
                    alert("success!")
                })
        }
    },

Just to add, it gives me these 2 error:

  1. Before and after the file is uploaded.
    => [Vue warn]: Invalid prop: custom validator check failed for prop “value”.

  2. after file is upload
    => Uncaught (in promise) FirebaseError: Function DocumentReference.update() called with invalid data. Unsupported field value: a custom File object (found in field ssm in document Subcontractor/9e0b2xsNqrhVn0Coukko3BTHlj93)

Thank you!

Mobile page’s hamburger menu and onClick issue

I hope the title properly described the situation I have.

I am a self-taught learner. Forgive me if the title is incorrect. I would appreciate hearing all your comments.

Symptom:
When I click the hamburger menu on the mobile page’s Navigation bar, it disappears and the menu popup function does not work either.

Here is the code or github

Navbar.js

import React, { Component } from "react";
import { MenuItems } from "./MenuItems";

import "./Navbar.css";

class Navbar extends Component {
    state = { clicked: false };

    handleClick = () => {
        this.setState({ clicked: !this.state.clicked });
    };

    render() {
        return(
            <nav className="NavbarItems">
                
                <h1 className="navbar__logo">
                    <a href="/" style={{ textDecoration: "none"}}>JW</a>
                </h1>

                <div className="menu__icon" onClick={this.handleClick}>
                    {/* for the hamburger (bar) menu animation */}
                    <i className={this.state.clicked ? "fas fa-times" : "fas fa-bars"}></i>
                </div>

                <ul className={this.state.clicked ? "nav__menu active" : "nav__menu"}>
                    {MenuItems.map((item, index) => {
                        return (
                            <li key={index}>
                                <a 
                                    className={item.cName} 
                                    href={item.url}>
                                    {item.title}
                                </a>
                            </li>
                        )
                    })}
                </ul>

            </nav>
        )
    }
}

export default Navbar;

MenuItems.js

export const MenuItems = [
    {
        title: 'Skills',
        url: '#skills',
        cName: 'nav__links'
    },
    {
        title: 'Projects',
        url: '#work',
        cName: 'nav__links'
    },
    {
        title: 'Contact',
        url: '#contact',
        cName: 'nav__links'
    },
]

Navbar.css

    .NavbarItems {
    /* background: linear-gradient(90deg, rgb(110, 94, 254) 0%, rgba(73, 63, 252, 1) 100%); */
    height: 80px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.2rem;

    overflow: hidden;
    background-color: white;
    position: fixed;
    top: 0;
    width: 100%;
}

.navbar__logo {
    color: #fff;
    justify-self: start;
    margin-left: 20px;
    cursor: pointer;
}

.fa__react {
    margin-left: 0.5rem;
    font-size: 1.6rem;
}

.nav__menu {
    display: grid;
    grid-template-columns: repeat(5, auto);
    grid-gap: 10px;
    list-style: none;
    text-align: center;
    width: 70vw;
    justify-content: end;
    margin-right: 2rem;
}

.nav__links {
    color: black;
    text-decoration: none;
    padding: 0.5rem 1rem;
    font-weight: bold;
}

.nav__links:hover {
    background-color: #6D76F7;
    border-radius: 4px;
    transition: all 0.2s ease-out;
}

.fa__bars {
    color: #fff;
}

.nav__links__mobile {
    display: none;
}

.menu__icon {
    display: none;
}

/* mobile start */
@media screen and (max-width: 960px) {
    .NavbarItems {
        position: relative;
    }

    .nav__menu {
        display: flex;
        flex-direction: column;
        width: 100%;
        height: 500px;
        position: absolute;
        top: 80px;
        left: -100%;
        opacity: 1;
        transition: all 0.5s ease;
    }

    .nav__menu.active {
        background: #6668f4;
        left: 0;
        opacity: 1;
        transition: all 0.5s ease;
        z-index: 1;
    }

    .nav__links {
        text-align: center;
        padding: 2rem;
        width: 100%;
        display: table;
    }

    .nav__links:hover {
        background-color: #7577fa;
        border-radius: 0;
    }

    .navbar__logo {
        position: absolute;
        top: 0;
        left: 0;
        transform: translate(25%, 50%)
    }

    .menu__icon {
        display: block;
        position: absolute;
        top: 0;
        right: 0;
        transform: translate(-100%, 60%);
        font-size: 1.8rem;
        cursor: pointer;
    }

    .fa-times {
        color: #fff;
        font-size: 2rem;
    }

    .nav__links__mobile {
        display: block;
        text-align: center;
        padding: 1.5rem;
        margin: 2rem auto;
        border-radius: 4px;
        width: 80%;
        background: #4ad9e4;
        text-decoration: none;
        color: #fff;
        font-size: 1.5rem;
    }

    .nav__links__mobile:hover {
        background: #fff;
        color: #6568F4;
        transition: 250ms;
    }

    Button {
        display: none;
    }
}

moment js bug for certain dates. moment.year(x).week(y).endOf(“week”)

I am getting some weird output for certain dates for moment js.
It is only for the dates 1st, 2nd and 3rd of Jan 2022 otherwise it works as expected.
I would expect the same output regardless of the current date.

Any idea why this is occurring?

console.log('Test 2019', moment().year(2019).week(48).endOf("week"));
console.log('Test 2020', moment().year(2020).week(48).endOf("week"));
console.log('Test 2021', moment().year(2021).week(48).endOf("week"));
console.log('Test 2022', moment().year(2022).week(48).endOf("week"));
console.log('Test 2023', moment().year(2023).week(48).endOf("week"));

// With date of device set to the future 3/Jan/2022
Test 2019 Sun Dec 09 2018 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2020 Sun Dec 08 2019 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2021 Sun Dec 06 2020 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2022 Sun Dec 04 2022 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2023 Sun Dec 03 2023 23:59:59 GMT+1300 (New Zealand Daylight Time)

// With date of device set to the today 15/dec/2021
Test 2019 Sun Dec 08 2019 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2020 Sun Dec 06 2020 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2021 Sun Dec 05 2021 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2022 Sun Dec 04 2022 23:59:59 GMT+1300 (New Zealand Daylight Time)
Test 2023 Sun Dec 03 2023 23:59:59 GMT+1300 (New Zealand Daylight Time)

Paypal button terminates asp .net execution after approved purchase

When I test in the paypal sandbox with smart buttons with generated code from paypal, the purchase is successfully executed. BUT when I redirect to a successful purchase page, the asp .net engine in debug, crashes and then does not execute the server code (like sending successful purchase email to the customer, saving the paypal transaction id in the database, etc).
I tested with window.location, window.location.href, window.location.replace, etc … the page redirects but does not execute the code behind it. Maybe it executes 1 or 2 lines of code and then stops immediately, other times it gets the error that localhost rejects the connection.

By Example, this code not crash (debug and code behind of paypalok.aspx runs ok)

   <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"        
   Inherits="WebApplication8.WebForm1" %>

   <!DOCTYPE html>

   <html xmlns="http://www.w3.org/1999/xhtml">
   <head runat="server">
   <title></title>
   </head>
   <body>
  <form id="form1" runat="server">
    <div>

        <input id="Button1" type="button" value="button" onclick="redirect()" />
    </div>
  </form>

<script>
    function redirect() {
        window.location.href = 'paypalok.aspx';
    }
  </script>
   </body>
   </html>

You can try it yourself and you will see how the asp .net debug stops unexpectedly after the redirection to ‘paypalok.aspx’.

by Example, this code crash:…

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="paypal3.aspx.cs"               
                        Inherits="WebApplication7.paypal3" %>

      <!DOCTYPE html>

       <html xmlns="http://www.w3.org/1999/xhtml">
      <head runat="server">
      <title></title>
    </head>
  <body>
     <form id="form1" runat="server">
    <div>
        <div id="smart-button-container">
          <div style="text-align: center;">
            <div id="paypal-button-container"></div>
          </div>
        </div>
    </div>
</form>
    <script src="https://www.paypal.com/sdk/js?client-id=sb&enable-funding=venmo&currency=USD"       
     data-sdk-integration-source="button-factory"></script>
    <script>
        function initPayPalButton() {

      paypal.Buttons({
          style: {
              shape: 'rect',
              color: 'gold',
              layout: 'vertical',
              label: 'paypal',

          },

          createOrder: function (data, actions) {
              return actions.order.create({
                  purchase_units: [{ "amount": { "currency_code": "USD", "value": 0.81 } }]
              });
          },

          onApprove: function (data, actions) {
              window.location.replace ('paypalok.aspx');
          },

          onError: function (err) {
              console.log(err);
          }
      }).render('#paypal-button-container');
  }

        initPayPalButton();

        </script>



  </body>
  </html>

I would appreciate any help

Text not appearing when I use javascript FillText method

So, I’m trying to make a new year’s countdown timer so I can keep track of the time until it’s New Year’s. But now, one of the pieces of text isn’t blitting onto the screen. It’s the piece that is supposed to tell how much more time until New Year’s. Here’s my code so far:

text = countDown + "";
ctx.fillText(text, 450, 285);

How can I send data from a function to run multiple times in another function using a loop?

This might be a fool question but let me try to explain myself, I want to run a function multiple times (insertOffice()) and each time I run it, add a number to a const, this number will increase depending of the times I want to run the code (in this case is 5).
Here is what I have tried:

function insertOffice() {
    var y = loop(i);
    console.log(y)
}

function loop() {
    for (var i = 1; i < 5; i++) insertOffice(i);
}

loop();

As you can see, lopp() runs insertOffice() 5 times, and insertOffice() print the numbers, I expect to print

1
2
3
4
5

I used this question to build my loop() function.

How to detect when key is pressed down in Javascript

I tried:

document.onkeypress = function(event) {
        var key = event.key;
        if( key == 13 ) {
            //code here
        }
    };

and

window.addEventListener

etc. The problem is, it says “window is not defined” or “document is not defined”. I’m not quite sure what to do next as I am a beginner with javascript, please help!

Create a square from user inputs

I am attempting to create a square from user inputs.

I thought that having having the height and width in my style multiplied together would create the square after clicking my button.

My question is: How do I get the user inputs to be used for the height and width of the box?

HTML:

<input type="text" id="width">
<input type="text" id="height">
    
<button onclick="calculate()">Click Me For Square</button>
<br>
<p id="box"></p>

Javascript:

    function calculate() {
        var w = document.getElementById("width").value;
        var h = document.getElementById("height").value;
        box = document.getElementById("box");
        box.innerHTML = " " + (w*h);
    }
    
    var square = document.createElement('div');
        square.className = 'square';
        document.body.appendChild(square);  

Style

 background: red;
  width: (h*w);
  height: (w*h);
  margin: 50px auto;
}

Any way to make functions use variables from the place it was imported to? [duplicate]

I’m trying not to repeat code and have a complicated function that’s used in at least 3 different components in react. I’m trying to put them all in one folder and importing them but there’s a ton of dependencies that I pass as function parameters and even after I’ve done that, I can’t figure out how to pass setState as a parameter because it keeps telling me it’s not a function.

export const doThing = (setState) => {
    code
}
import { doThing } from "./place"

doThing(setState)
TypeError: setState is not a function

Even if I can get setState working I still feel like there should be a better way. Really I’d just like it to act like a copy paste and use variables from the scope it was imported to. Any way to do that?

Storing ID’s in react router URL to extract ID and make api call

so I need to store two unique ID’s into the url and extract the id’s in another component to get data from the data base.

This task requires me to send an email with a link to complete a task. If the task is deleted I need to know who sent the task email.

Any information of the direction I should move in is appreciated.

import React from 'react';
// current setup
const Practice = () => {
    return (
      <div>
        <Router>
          <Something path="/task/:id" />
          <Something path="/task/:id/:action" />
        </Router>
      </div>
    );
  };
  
export default practice;


// desired setup
// I need to store Id's and make it not break the website. like lets say optional values or something.
// The only required value is the first /:id
const Practice = () => {
    return (
      <div>
        <Router>
          <Something path="/task/:id/:id?/:id?" />
        </Router>
      </div>
    );
  };
  
export default practice;
  
{ " desired output is = localhost:3000/task/111111?222222?33333" }
{ "so that I can store the last two id's in an array = "['localhost:3000/task/111111', '222222', '33333'] }

//component
const Task = ({ id, action, companyId, userId }) => {
const company = companyId
const user = userId
}

Flow React HOC typing (without HOC)

I need to type HOC for my component (and that was asked millions of times). But I need to do something opposite to the typical withSomething injection. I need to add an extra property to my outer component and pass all other (but unknown) properties to the inner component:

// @flow

import * as React from 'react'

// That's an example of a standard component doing nothing
type Props = {|  str: string,  num: number |}
const Hello = ({ str, num }: Props): React.Node => {
  console.log(str, num)
  return <div>'Hello'</div>
}

// That's the standard (and working) example of the component with injected prop.
// It's an equivalent of prop currying, I set str prop to some default value
type InnerInjected = {| str: string |}
const withInnerInject = <P>(
  Component: React.AbstractComponent<$Exact<{ ...P, ...InnerInjected }>>,
): React.AbstractComponent<P> => {
  return (props: P) => {
    return <Component str="aaa" {...props} />
  }
}

const InnerInjectHello = withInnerInject(Hello)


// And here is non-working example. 
export const withOuterInject = <P>(
  Component: React.AbstractComponent<P>,
): React.AbstractComponent<P> => {
  return (props: P) => {
    // I need to pass the bool (or some other variable) to my component to perform 
    // some action with it based on its value and return the standard component with all
    // that component properties that I don't know yet.
    const { bool, ...rest } = props
    return <Component {...rest} />
  }
}

const OuterInjectHello = withOuterInject(Hello)

const Example = (): React.Node => {
  return (
    <>
      {/* Both num and str props are set as intended */}
      <Hello num={25} str="something" >
      {/* str is injected with value of 'aaa' */}
      <InnerInjectHello num={25} />
      {/* Works, but typing is wrong */}
      <OuterInjectHello str="aa" num={25} bool />
    </>
  )
}

I tried several $Diff<> and $Rest<> approaches but they simply don’t work with generics.

How to add a whole section using JavaScript?

So I am trying to write a script to add a whole, newly added, section to Adobe Analytics. I am not sure I can do it though, so I will appreciate your help. I thought I should add a class name to the section and use document.getElementsbyClassName but it does not seem to work? I also need to add the nested divs and their styles again using JS?
Here is my code:

<section class="flex-columns" style="
    background-color: crimson;
    height: 450px;
    display: flex;
    justify-content: center;
    align-items: center;
"> 
   <div style="
    top: 132px;
    left: 340px;
    width: 400px;
    height: 400px;
    background: #FFFFFF 0% 0% no-repeat padding-box;
    border-radius: 10px;
    opacity: 1;
    margin-left: 5px;
    margin-right: 15px;
">
    <p style="
    top: 187px;
    left: 391px;
    width: 31px;
    height: 138px;
    text-align: left;
    font: normal normal bold 120px/36px Value;
    letter-spacing: 0px;
    opacity: 1;
    margin-top: 65px;
    margin-left: 30px;
    color: black;
    border-style: solid;
    border-color: black;
">1</p>
    <p style="
    top: 326px;
    left: 391px;
    width: 298px;
    height: 152px;
    text-align: left;
    font: normal normal bold 45px/50px Value;
    letter-spacing: 0px;
    color: #888888;
    opacity: 1;
    margin-left: 30px;
">Find your nearest store</p>
</div>
    <div style="
    top: 132px;
    left: 340px;
    width: 400px;
    height: 400px;
    background: #FFFFFF 0% 0% no-repeat padding-box;
    border-radius: 10px;
    opacity: 1;
    margin-left: 5px;
    margin-right: 15px;
"> 
<p style="
    top: 187px;
    left: 811px;
    width: 66px;
    height: 138px;
    text-align: left;
    font: normal normal bold 120px/36px Value;
    letter-spacing: 0px;
    color: black;
    opacity: 1;
    margin-top: 65px;
    margin-left: 30px;
">2</p>
<p style="
    top: 326px;
    left: 811px;
    width: 298px;
    height: 152px;
    text-align: left;
    font: normal normal bold 45px/50px Value;
    letter-spacing: 0px;
    color: #888888;
    opacity: 1;
    margin-left: 30px;
">Book a free hearing test</p>
</div>
    <div style="
    top: 132px;
    left: 340px;
    width: 400px;
    height: 400px;
    background: #FFFFFF 0% 0% no-repeat padding-box;
    border-radius: 10px;
    opacity: 1;
    margin-left: 5px;
    margin-right: 15px;
">
    <p style="
    top: 187px;
    left: 1231px;
    width: 68px;
    height: 138px;
    text-align: left;
    font: normal normal bold 120px/36px Value;
    letter-spacing: 0px;
    color: black;
    border: 2px;
    border-color: black;
    margin-top: 65px;
    margin-left: 30px;
">3</p>
    <p style="
    top: 326px;
    left: 1231px;
    width: 298px;
    height: 152px;
    text-align: left;
    font: normal normal bold 45px/50px Value;
    letter-spacing: 0px;
    color: #888888;
    opacity: 1;
    margin-left: 30px;
    /* margin-bottom: 0px; */
">Get supported by our experts</p>
</div>
</section>

How to custom format Chart.js ticks based on dynamic data?

I’m trying to make a chart that displays cryptocurrency prices using the CoinGeckoAPI and Chart.js. The data will be updated about every minute or so. I want my chart x-axis to look similar to this: enter image description here

My x-axis data is an array of unix time values that I need to convert to Date before setting them as labels in the chart. I’m using SignalR and a background task in an ASP.NET Core MVC application to periodically send CoinGeckoAPI data to the client.

How can I set specific dynamic values as the x-axis ticks? Ideally the ticks would be set to something like every third hour within my dataset.

HTML:

<canvas id="myChart" width="400" height="400"></canvas>

JavaScript:

<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script type="text/javascript">

        //Establish SignalR connection
        var connection = new signalR.HubConnectionBuilder().withUrl("/hub").build();

        //Set up chart and initial empty configuration
        const config = {
            type: 'line',
            data: {},
            options: {}
        };
        const myChart = new Chart(document.getElementById('myChart'),
            config);

        //Pass data from SignalR Hub to client
        connection.on("CryptoPriceUpdated", function (unixTimeArray, priceArray) {

            //Convert unix time array to Date array with desired date formatting
            var formattedDateArray = new Array();
            for (var i = 0; i < unixTimeArray.length - 1; i++) {
                var dateTemp = new Date(unixTimeArray[i]);
                formattedDateArray[i] = dateTemp.getHours() + ':' + dateTemp.getMinutes();
            }

            //Configure chart with new data
            var labels = formattedDateArray;
            var data = {
                labels: labels,
                datasets: [{
                    label: 'Price',
                    backgroundColor: 'rgb(255, 99, 132)',
                    borderColor: 'rgb(255, 99, 132)',
                    radius: 1,
                    data: priceArray
                }]
            };
            var options = {
                responsive: true,
            }

            //Update chart
            myChart.data = data;
            myChart.options = options;
            myChart.update();
        });

        connection.start();
    </script>