Attribute name to variavel javascript

I’m developing a dynamic page with javascript.

I’m not that advanced with the language, I’m trying to collect the name of the classes defined in the div through the html object variable,

so far I created a loop to repeat the structure created dynamically, assign a class: object to define as a class name for each block created through the objects variable

however I would like to use the name of each class summarized as a variable or if there is a way in which I could simply call the block and dynamically create html structure within it without the others clone the same.

// objs 
const html = [
    {
        id: 0,
        class: 'hero',
        titulo: "Teste",
    },
    {
        id: 1,
        class: 'section_1',
        titulo: "Teste 2",
    },
];

// main code
let section = document.createElement("section");
let el_page = document.getElementById("main");

const global = app => {

    const main = document.getElementById("main");
    const div = document.createElement("div");

    // get names and set div all class name
    for (let i = 0; i < html.length; i++) {
        div.setAttribute("class", app.class);
    }
    //creat el div
    main.append(div);
}

html.forEach(app => global(app));
    <main id="main">
teste
    </main>

Center columns with xAxis categories in highcharts

I intend to center the columns with the x-axis values ​​in the highcharts charts.

I have the following code:

Highcharts.chart('container', {
      chart: {
        type: 'column',
        options3d: {
          enabled: true,
          alpha: 0,
          beta: 0,
          viewDistance: 50,
          depth: 100
        }
      },

      title: {
        text: ''
      },

      xAxis: {
        type: 'category',
        labels: {
          skew3d: true,
          align: 'center',
          style: {
            fontSize: '16px'
          }
        }
      },

      yAxis: {
        allowDecimals: false,
        min: 0,
        title: {
          text: 'Total de Denúncias',
          skew3d: true,
          align: 'center',
          style: {
            fontSize: '16px'
          }
        }
      },

      plotOptions: {
        column: {
          stacking: 'normal',
          depth: 200,
        }
      },

      series: series
    });

The graph looks like this:

enter image description here

As I show in the image the dates of the x axis are misaligned with the columns generated in the series. Can they help to center with each other?

AWS SSM getparameters make behavior node js sync

Is there any way to make AWS SSM getparameters sync?
Requirement :
The secret key, id stored in the SSM store should be accessible on the server up.
Using Node and express in the backend as a reverse proxy, so we have a constant.js file, it stores all the API URLs, paths, etc.

constats.js file

const api1url = 'http://example.com/path1'
const api1_secretkey = 'secret_key'
..................

module.export = {api1url,api1_secretkey}

So we wanted to call the ssm stuff in here before setting the const variables

const SSM = require('aws-sdk/clients/ssm');
const ssm = new SSM();
const params = {
   Names: ['/secret_key_api_1', '/secret_key_api_2'],
   WithDecryption: true,
   };
 const parameterList = await ssm.getParameters(params).promise();

I understand that await cant be without async, I just wanted to convey what I am expecting, without it being an async call or whether it be in the callback of getparameters.

const api1url = 'http://example.com/path1'
const api1_secretkey = parameterList.Parameter[1].Value

But since it is an async call we are not able to wait for it ,tried doing it in a separate async function and then returning the data but since the function is still async having difficulties.

custom hook not returning the dimensions of DOM element through ref parameters

I’m trying to create a custom hook that calculates the width and height of a given DOM element through useRef.

It calculates the dimensions however I’m not seeing any dynamic output. Meaning that as I resize the window, current width and height of the DOM element are not being updated. I need to toggle a css class based on the DOM element’s width.

This is my custom hook, which takes a ref as its sole parameter:

  useDimensionObserver = refParam => {

    if (refParam === null) return false;

    const getDimensionsFromRef = refParam => ({ width: refParam.current?.getBoundingClientRect().width, height: refParam.current?.getBoundingClientRect().height }),
      [dimensions, setDimensions] = React.useState(getDimensionsFromRef(refParam));


    React.useEffect(() => {
      const handleResize = () => setDimensions(getDimensionsFromRef(refParam));
      window.addEventListener("resize", handleResize);
      return () => window.removeEventListener("resize", handleResize);
    }, []);

    return refParam ? dimensions : null;

  },

This is the component in which I make use of useDimensionObserver:

 GeneralTotals = (props = IGeneralTotals) => {


    const containerRef = React.useRef(null),
      d = useDimensionObserver(containerRef);

    console.log(d); // As I resize the window, the container is also being resized so d.width and d.height need to be made dynamic.


    //I shall take action with 'd' potentially something like this...
    //if(d !== null && d.width < 450) setToggleInvisibleClass(true)

    return (<div className="card-title-tags" key="cal" ref={containerRef}>
      .....
    </div>);
  };

How to fix syntax error . i have run this below script find next roll output…but it is showing syntax error [closed]

const = require(“crypto”);

const roundSeed = “”; /YOUR SERVER SEED/

const clientSeed = “”; /YOUR CLIENT SEED/

const nonce = “”; /YOUR GAME’S NONCE/

function saltWithClientSeed(serverSeed, clientSeed) {

return crypto

.createHmac(“sha512”, serverSeed)

.update(clientSeed)

.digest(“hex”);

}

function generateHash(serverSeed) {

return crypto

.createHash(“sha256”)

.update(serverSeed)

.digest(“hex”);

}

function buildFinalHash(serverSeed, clientSeed, nonce) {

const noncedSeed = ${clientSeed} - ${nonce};

return saltWithClientSeed(serverSeed, noncedSeed);

}

function rollNumber(hash) {

let index = 0;

let lucky = parseInt(hash.substring(index * 5, index * 5 + 5), 16);

// keep grabbing characters from the hash while greater than

while (lucky >= Math.pow(10, 6)) {

index++;

lucky = parseInt(hash.substring(index * 5, index * 5 + 5), 16);

// if we reach the end of the hash, just default to highest number

if (index * 5 + 5 > 128) {

lucky = 9999;

break;

}

}

lucky %= Math.pow(10, 4);

lucky /= Math.pow(10, 2);

return lucky;

}

function verifyRoll() {

const hash = buildFinalHash(roundSeed, clientSeed, nonce);

return rollNumber(hash);

}

console.log(verifyRoll());

 

Merge two arrays with different set of strings using es6 functional programming

I’ve converted csv based text files to arrays containing headers and rows and now I want to convert them into given below solution. Can anybody do this using methods like .map(), .reduce() or whatever.

Arrays I have look alike:

let header = ['a', 'b', 'c', 'd'];
let rows = ['1,2,3,4', '5,6,7,8', '9,0,1,2'];

The result I want:

[
  {
    a: 1,
    b: 2,
    c: 3,
    d: 4,
  },
  {
    a: 5,
    b: 6,
    c: 7,
    d: 8,
  },
  {
    a: 9,
    b: 0,
    c: 1,
    d: 2,
  },
]

I was able to do this using for loop but that wasn’t the appropriate solution for es6.

Above I’ve mentioned some dummy arrays, right now the actual code is:

const recordReader = content => {
    let weatherRecords = [];
    let rows = content.split('n');
    let headers = rows.shift().split(',');

    for (let row = 0; row < rows.length; row++) {
        let weatherReading = {};
        if (!rows[row]) {
            continue;
        }
        let record = rows[row].split(',');

        for (let column = 0; column < headers.length; column++) {
            weatherReading[headers[column]] = record[column];
        }

        weatherRecords.push(weatherReading);
    }
    return weatherRecords;
};

Optional chaining doesn’t work on Node 16.4

I have tried this syntax in VSCode and Coderpad (both use Node version 16.4).

let x = {}
x?.something.foo

As far as my understanding goes, this code shouldn’t throw an error now, but return undefined. The feature optional chaining should be available in Node v14+ but for some reason it doesn’t work in my VSCode and also in Coderpad.

Thought why?

React change subdomain dynamically

I am using react to build an application and there is one API integrated which gives me subdomain in the response. I am saving the whole response in organization object variable.

How do I configure my application to switch to that subdomain once its retrieved? I went through some articles around the web but couldn’t figure it out. I have tried like this also:

  useEffect(() => {
    if (organization.org.subdomain !== null && organization.org.subdomain !== undefined) {
      window.location.assign(organization.org.subdomain)
    }
  },[organization.org.subdomain])

Note: I am using hash-router.

How to convert array to object and assign value in javascript

i have array value and object for data mapping. reduce method is not working for object mapping, here is sample data.

the array value is

let array = [ "payload", "offer", "application_id" ]

object value is

let data = {
                organization_id: 4002400004,
                organization_name: 'Velocity Global Integration Sandbox',
                action: 'offer_updated',
                payload: {
                    offer: {
                        id: 4524843004,
                        application_id: 31948577004,
                        user_id: 4123647004,
                        version: 1,
                        sent_on: null,
                        resolved_at: '2022-05-19T06:21:25.084Z',
                        start_date: '2022-05-17',
                        notes: null,
                        job_id: 4298940004,
                        offer_status: 'Accepted'
                    },
                    "resume": {
                        name: "manikandan"
                    }
                }
            }

need to form new object with the response

let payload = {
    offer: {
        application_id: 343645656
    }
}

Vue.js-Failed to load resource: the server responded with a status of 401 (Unauthorized)

I’m currently working on a project that collects payment info(like the products the client wants to buy, and how much that product costs) and client details(client name, client address, client credit card info, etc.) and I need to access Stripe’s online payment system for the purchase. However, during my trial run, every time I try to click all “Pay”, I keep getting notifications that something went wrong. I checked the terminal and it keeps displaying this error:

Failed to load resource: the server responded with a status of 401 (Unauthorized)

I’m also using Django’s rest framework for my backend development, and it keeps displaying this

 HTTP 401 Unauthorized
    Allow: POST, OPTIONS
    Content-Type: application/json
    Vary: Accept
    WWW-Authenticate: Token
    
    {
        "detail": "Authentication credentials were not provided."
    }

This is the code I think the problem is located in:

<template>
  <div class="page-checkout">
    <div class="columns is-multiline">
      <div class="column is-12">
        <h1 class="title">Checkout</h1>
      </div>

      <div class="column is-12 box">
        <table class="table is-fullwidth">
          <thead>
            <tr>
              <th>Product</th>
              <th>Price</th>
              <th>Quantity</th>
              <th>Total</th>
            </tr>
          </thead>

          <tbody>
            <tr v-for="item in cart.items" v-bind:key="item.product.id">
              <td>{{ item.product.name }}</td>
              <td>{{ item.product.price }}</td>
              <td>{{ item.quantity }}</td>
              <td>₱{{ getItemTotal(item).toFixed(2) }}</td>
            </tr>
          </tbody>

          <tfoot>
            <tr>
              <td colspan="2">Total</td>
              <td>{{ cartTotalLength }}</td>
              <td>₱{{ cartTotalPrice.toFixed(2) }}</td>
            </tr>
          </tfoot>
        </table>
      </div>

      <div class="column is-12 box">
        <h2 class="subtitle">Shipping Details</h2>

        <p class="has-text-grey mb-4">* All fields required</p>

        <div class="columns is-multiline">
          <div class="column is-6">
            <div class="field">
              <label>First Name*</label>
              <div class="control">
                <input type="text" class="input" v-model="first_name">
              </div>
            </div>

            <div class="field">
              <label>Last Name*</label>
              <div class="control">
                <input type="text" class="input" v-model="last_name">
              </div>
            </div>

            <div class="field">
              <label>E-mail*</label>
              <div class="control">
                <input type="email" class="input" v-model="email">
              </div>
            </div>

            <div class="field">
              <label>Phone*</label>
              <div class="control">
                <input type="text" class="input" v-model="phone">
              </div>
            </div>
          </div>

          <div class="column is-6">
            <div class="field">
              <label>Address*</label>
              <div class="control">
                <input type="text" class="input" v-model="address">
              </div>
            </div>

            <div class="field">
              <label>Zipcode*</label>
              <div class="control">
                <input type="text" class="input" v-model="zipcode">
              </div>
            </div>

            <div class="field">
              <label>Place*</label>
              <div class="control">
                <input type="email" class="input" v-model="place">
              </div>
            </div>
          </div>
        </div>

        <div class="notification is-danger mt-4" v-if="errors.length">
          <p v-for="error in errors" v-bind:key="error">{{ error }}</p>
        </div>

        <hr>

        <div id="card-element" class="mb-5"></div>

        <template v-if="cartTotalLength">
          <hr>

          <button class="button is-dark" @click="submitForm">Pay with Stripe</button>
        </template>
      </div>
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  name: "Checkout",
  data() {
    return {
      cart: {
        items: []
      },
      stripe: {},
      card: {},
      first_name: '',
      last_name: '',
      email: '',
      phone: '',
      address: '',
      zipcode: '',
      place: '',
      errors: []
    }
  },
  mounted() {
    document.title = ' The "GO BUY IT" page | Bjackets '

    this.cart = this.$store.state.cart

    if (this.cartTotalLength > 0) {
      this.stripe = Stripe('pk_test_51L3bhzFMIo7cZ677WbW384hMgVFcLs9E0x4sLocwajtGbnZIlplXoWSlSKr1IM89tWOCFYIBOWPpcF8OzBWGCnZR00MN1fPAGW')
      const elements = this.stripe.elements();
      this.card = elements.create('card', { hidePostalCode: true })

      this.card.mount('#card-element')
    }
  },
  methods: {
    getItemTotal(item) {
      return item.quantity * item.product.price
    },
    submitForm() {
      this.errors = []

      if (this.first_name === '') {
        this.errors.push('The First Name feild is empty. Please fill-out the space with your first name. For example, "Gaylord"')
      }

      if (this.last_name === '') {
        this.errors.push('The Last Name feild is empty. Please fill-out the space with your last name. For example, "Gaylord"')
      }

      if (this.email === '') {
        this.errors.push('The email feild is missing. Please fill-out the space with your email. For example, "[email protected]"')
      }

      if (this.phone === '') {
        this.errors.push('The phone feild is missing. Please fill-out the space with your contact number. For example, "123-456-7890"')
      }

      if (this.address === '') {
        this.errors.push('The address feild is missing. Please fill-out the space with your address. In other words, tell me where you live.')
      }

      if (this.zipcode === '') {
        this.errors.push('The zipcode feild is missing.')
      }

      if (this.place === '') {
        this.errors.push('Are you located in Lozun, Visayas, Mindanao?')
      }

      if (!this.errors.length) {
        this.$store.commit('setIsLoading', true)

        this.stripe.createToken(this.card).then(result => {
          if (result.error) {
            this.$store.commit('setIsLoading', false)

            this.errors.push('Something went wrong with Stripe. Please try again')

            console.log(result.error.message)
          } else {
            this.stripeTokenHandler(result.token)
          }
        })
      }
    },
    async stripeTokenHandler(token) {
      const items = []

      for (let i = 0; i < this.cart.items.length; i++) {
        const item = this.cart.items[i]
        const obj = {
          product: item.product.id,
          quantity: item.quantity,
          price: item.product.price * item.quantity
        }

        items.push(obj)
      }

      const data = {
        'first_name': this.first_name,
        'last_name': this.last_name,
        'email': this.email,
        'address': this.address,
        'zipcode': this.zipcode,
        'place': this.place,
        'phone': this.phone,
        'items': items,
        'stripe_token': token.id
      }

      await axios
        .post('/api/v1/checkout/', data)
        .then(response => {
          this.$store.commit('clearCart')
          this.$router.push('/cart/success')
        })
        .catch(error => {
          this.errors.push('Something went wrong. Please try again')
          console.log(error)
        })
      this.$store.commit('setIsLoading', false)
    }
  },
  computed: {
    cartTotalPrice() {
      return this.cart.items.reduce((acc, curVal) => {
        return acc += curVal.product.price * curVal.quantity
      }, 0)
    },
    cartTotalLength() {
      return this.cart.items.reduce((acc, curVal) => {
        return acc += curVal.quantity
      }, 0)
    },
  }
}
</script>

How to fix SSL error with NodeJS HTTPS server?

I’m new to Stack Overflow and this is my first question, so please bear with me. I never had to ask a question until I had a problem and couldn’t find a solution. Anyways, my problem is my Node JS HTTPS server that I use to host my website has a problem where when the client requests a resource such as a video or an image, it’s a 50% chance that the resource will properly load for the client. The times it doesn’t load I get an SSL error in the console (for example, net::ERR_SSL_PROTOCOL_ERROR 200 (OK)). Sometimes it will load, sometimes it won’t. I don’t know if I have a misconfiguration with my server or not, but I need to get this fixed. I need the resource to load for the client 100% of the time. Any help would be great.

Here’s how my server is configured.

// Redirect HTTP traffic to HTTPS
http.createServer((req, res) => {
    if (req.headers.host === 'domain.com') {
        let redirectUrl = `https://${req.headers.host}${req.url}`;
        res.statusCode = 301;
        res.setHeader('Location', redirectUrl);
        res.end();
        return;
    }
    reqHandler(req, res);
}).listen(80);

// HTTPS server
const server = https.createServer({
    cert: readFileSync('/path/to/cert.pem').toString(),
    key: readFileSync('/path/to/key.pem').toString(),
    ca: readFileSync('/path/to/chain.pem').toString()
}, reqHandler);
server.listen(443);

Git – Renaming a Branch Name, Encounter an error

I have given the branch name as below while creating the new branch:

git checkout -b "working_with_controllers(APIs_Logic)"

At them time of creation it didn’t throw an error stating

this is the wrong format

But when trying to switch or rename a branch using command

git branch -m working_with_controllers(APIs_Logic)  new-branch working_with_controllers

Showing the error

bash: syntax error near unexpected token `('

Can any one help me with the solution please

How to hide DIV’s parent in JS with a specific content

I’m trying to hide a DIV’s parent when a certain DIV contains a specific text.

An example. This DIV I want to stay:

<div class="report-per-day">
<div class="report-day">26 May 2022</div>
<div class="status-report-rows">
<p class="report__headline">This is our report</p>
</div>
</div>
</div>

But I want to hide this whole DIV, because there’s a DIV .mt-2, which contains “No new incident.”

<div class="report-per-day">
<div class="report-day">25 May 2022</div>
<div class="mt-2" style="display: none;">
<small class="text-muted">No new incident.</small>
</div>
</div>
</div>

I have this Java Script, but it only hides the .mt-2. I’d also like to hide its 2 parents, .report-per-day and .report-day

Do you guys happen to have any suggestions? Thanks a lot!

const divs = document.getElementsByClassName('mt-2');

for (let x = 0; x < divs.length; x++) {
    const div = divs[x];
    const content = div.textContent.trim();
  
    if (content == 'No incidents reported.') {
        div.style.display = 'none';
    }
}