Display API Response into an array

I’m making a Trivia Game and I’m using The Open Trivia Database to generate 10 random questions.
These 10 questions are separate strings and I want to place them into an array so that I can display them one by one (after the user guesses whether it’s True or False.)
Here is the console log of the questions:
enter image description here

Now here is what I’m trying: I have initialized an empty array and then, in the for loop, I’m pushing each question into the array but its not working.

Any help is appreciated and if I missed something, please let me know. Thank you in advance!
Code:

const api_url = "https://opentdb.com/api.php?amount=10&difficulty=easy&type=boolean";
const triviaQ = document.getElementById("triviaQuestion")
const question_array = [] // this is the empty array

async function getAPI(url) {
    const response = await fetch(url);

    var data = await response.json();

    justQuestions(data)
}
function justQuestions(data) {

/// loop to display all 10 questions
    for (let i = 0; i <= 9; i++) {
        display_all_questions = data.results[i].question
        current_question = triviaQ.innerHTML = display_all_questions /// the console log image
        let all_questions = question_array.push({ display_all_questions }) //this is where I attempt to add the questions into an array
    } ```

How to convert a string of numbers 5000000050000000500000000005, to an array of objects with dates going backwards 28 days?

I am receiving a string like: 5000000050000000500000000000

This is a representation of data over the past 28 days. I need to transform this into an array of objects like:

[
{“value”: 5,
“date”: “now”
},
{“value”: 0,
“date”: “now-1”
},
{“value”: 0,
“date”: “now-2”
},
etc…..
]

Now now-1 should be Date.now() minus 1 day, and then with each loop, and 1 to that minus #.

In hunting for a solution, I found:

const n = 123456;
Array.from(n.toString()).map(Number);
// [1, 2, 3, 4, 5, 6]

But this doesn’t seem to handle 0’s.

And I don’t know how to loop and set an additional key/value pair for the date?

How do I translate JS code to hex unicode?

So I found a project with a bunch of encrypted code that looked like this:

"u006eu0061u006du0065u0073u0070u0061u0063u0065": "u0063u0068u0065u0073u0074",

I pasted that into a JS Decoder, and got this:

"namespace": "chest",

My question is: How do I do the reveres of that, and compile my own json files to look like that? I found a reddit bot that does something like that, but im hoping for maybe a website, or even lightweight software to get the job done.

I found a script on StackOverflow for a similar issue, but that was for individual characters which is not what im looking for as im trying to convert entire files.
You can find the link to the above solution Here

So basically Im trying to make code that looks like this:

  "namespace": "chest",

  "chest_label": {
    "type": "label",
    "offset": [ 7, -1 ],
    "anchor_from": "top_left",
    "anchor_to": "top_left",
    "text": "$container_title",
    "size": [ "90%", "default" ],
    "color": "$title_text_color",
    "layer": 2
  },
  "[email protected]_item": {
    "$item_collection_name": "container_items"
  },
  "small_chest_grid": {
    "type": "grid",
    "size": [ 162, 54 ],
    "anchor_from": "top_left",
    "anchor_to": "top_left",
    "grid_dimensions": [ 9, 3 ],
    "grid_item_template": "chest.chest_grid_item",
    "collection_name": "container_items"
  },

Look like this:

  "u006eu0061u006du0065u0073u0070u0061u0063u0065": "u0063u0068u0065u0073u0074",

  "u0063u0068u0065u0073u0074u005fu006cu0061u0062u0065u006c": {
    "u0074u0079u0070u0065": "u006cu0061u0062u0065u006c",
    "u006fu0066u0066u0073u0065u0074": [ 7, -1 ],
    "u0061u006eu0063u0068u006fu0072u005fu0066u0072u006fu006d": "u0074u006fu0070u005fu006cu0065u0066u0074",
    "u0061u006eu0063u0068u006fu0072u005fu0074u006f": "u0074u006fu0070u005fu006cu0065u0066u0074",
    "u0074u0065u0078u0074": "u0024u0063u006fu006eu0074u0061u0069u006eu0065u0072u005fu0074u0069u0074u006cu0065",
    "u0073u0069u007au0065": [ "u0039u0030u0025", "u0064u0065u0066u0061u0075u006cu0074" ],
    "u0063u006fu006cu006fu0072": "u0024u0074u0069u0074u006cu0065u005fu0074u0065u0078u0074u005fu0063u006fu006cu006fu0072",
    "u006cu0061u0079u0065u0072": 2
  },

  "u0063u0068u0065u0073u0074u005fu0067u0072u0069u0064u005fu0069u0074u0065u006du0040u0063u006fu006du006du006fu006eu002eu0063u006fu006eu0074u0061u0069u006eu0065u0072u005fu0069u0074u0065u006d": {
    "u0024u0069u0074u0065u006du005fu0063u006fu006cu006cu0065u0063u0074u0069u006fu006eu005fu006eu0061u006du0065": "u0063u006fu006eu0074u0061u0069u006eu0065u0072u005fu0069u0074u0065u006du0073"
  },

  "u0073u006du0061u006cu006cu005fu0063u0068u0065u0073u0074u005fu0067u0072u0069u0064": {
    "u0074u0079u0070u0065": "u0067u0072u0069u0064",
    "u0073u0069u007au0065": [ 162, 54 ],
    "u0061u006eu0063u0068u006fu0072u005fu0066u0072u006fu006d": "u0074u006fu0070u005fu006cu0065u0066u0074",
    "u0061u006eu0063u0068u006fu0072u005fu0074u006f": "u0074u006fu0070u005fu006cu0065u0066u0074",
    "u0067u0072u0069u0064u005fu0064u0069u006du0065u006eu0073u0069u006fu006eu0073": [ 9, 3 ],
    "u0067u0072u0069u0064u005fu0069u0074u0065u006du005fu0074u0065u006du0070u006cu0061u0074u0065": "u0063u0068u0065u0073u0074u002eu0063u0068u0065u0073u0074u005fu0067u0072u0069u0064u005fu0069u0074u0065u006d",
    "u0063u006fu006cu006cu0065u0063u0074u0069u006fu006eu005fu006eu0061u006du0065": "u0063u006fu006eu0074u0061u0069u006eu0065u0072u005fu0069u0074u0065u006du0073"
  },

SlateJS How to Add Links / URLs

I’m wondering how to add links with SlateJS

A basic implementation would have a link button on the toolbar that lets the user highlight some text, click the link button (or press a hotkey like ctrl+k), and turn that text into a link.

Another implementation would enable one to paste in a URL, and have it automatically turn into a hyperlink.

The documentation has no mention of such a basic feature. Surely somebody has figured this out, is it documented anywhere? (and if it’s too difficult to do in SlateJS, are there any other libraries where it’s easier?)

An unexpected error, please what should i do?

Failed to compile.

Module not found: Error: Can’t resolve ‘react-icons/fa’ in ‘C:UsersDamola GbengaDocumentschat-appsrccomponents’
ERROR in ./src/components/Sidebar.jsx 7:0-44
Module not found: Error: Can’t resolve ‘react-icons/fa’ in ‘C:UsersDamola GbengaDocumentschat-appsrccomponents’

ERROR in ./src/components/Sidebar.jsx 8:0-47
Module not found: Error: Can’t resolve ‘react-icons/bi’ in ‘C:UsersDamola GbengaDocumentschat-appsrccomponents’

ERROR in ./src/components/Sidebar.jsx 9:0-40
Module not found: Error: Can’t resolve ‘react-icons/hi’ in ‘C:UsersDamola GbengaDocumentschat-appsrccomponents’

ERROR in ./src/components/Sidebar.jsx 10:0-42
Module not found: Error: Can’t resolve ‘react-icons/bs’ in ‘C:UsersDamola GbengaDocumentschat-appsrccomponents’

webpack compiled with 4 errors

Do I need to keep those variables global?

Once I reached out of scopes, from events, I need to keep referencing variables that was declared in the parent scope. In below code, fitAddon. In order to prevent JS’s GC to clean up my variable, do I need to keep it global like below? this isn’t much clear to me.

// do I need to keep this to use in handleResize() event or
// it would be fine if it was local, i.e., same scope as
// it was initialized?
 let fitAddon: FitAddon;

export const Terminal = () => {

  const id = 'xterm-container';
  useEffect(() => {
    const terminal = new TerminalType({
      cursorBlink: true,
      cursorStyle: window.api.isWindows ? "bar" : "underline",
      cols: DefaultTerminalSize.cols,
      rows: DefaultTerminalSize.rows,
    });

    fitAddon = new FitAddon();
    terminal.loadAddon(fitAddon);
    
    terminal.open(document.getElementById(id) as HTMLElement);
    fitAddon.fit();
    

    function handleResize() {
      fitAddon.fit();
    }

    window.addEventListener('resize', handleResize);

    return () => {
      return window.removeEventListener('resize', handleResize);
    }
  }, []);

  return (
    <div id={id}></div>
  )
}

When I click an anchor link, the word flashes purple [closed]

I am using anchor links for my nav bar, and the app is being served with express. So, every time you click an anchor link in my nav bar, express takes you to a different route. For example, clicking the about link takes you to www.mysite.com/about. The issue is, when I click an anchor link, the words flash purple and completely change styling for a split second while I’m being redirected to that page. I tried to select all the anchor links and prevent default on the function event, but this didn’t work. Any ideas?

isEven function wierd way

I was playing around with on of the excercises when I coded this:

function isEven(x){
   var m = x % 2
   var n = x / 2
   return m <= !n
}

The funny part is that it actually works, but I do not understand if !n makes the number negative or affects the boolean value itself. Can someone explain how my code works? Thanks.

Method call returning invalid data

I have this javascript (react) code using the .find() method to search through an array of objects to find one with a matching id to one gotten from useParams() method but when I console log to check it, It returns array with a corresponding id but with the data from the data from the first object in the array. could someone please point out what mistake I’m making?

Here’s the array of objects

    const Merchandise = [
{
    id: 5,
    productImage: "images/heroImage.png",
    productName: "Africhella Lip Gloss",
    productPrice: "3000",
    productDescription: "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Aliquam quidem deserunt id repellendus ratione reprehenderit animi qui quae repellat voluptatem, quisquam amet quo vel ullam odit minima architecto error tempore"
},
{
    id: 6,
    productImage: "images/lipBalm.png",
    productName: "Africhella Lip Butter",
    productPrice: "3000",
    productDescription: "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Aliquam quidem deserunt id repellendus ratione reprehenderit animi qui quae repellat voluptatem, quisquam amet quo vel ullam odit minima architecto error tempore"
},
{
    id: 7,
    productImage: "images/lipScrub.png",
    productName: "Africhella Lip Scrub",
    productPrice: "3000",
    productDescription: "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Aliquam 
    quidem deserunt id repellendus ratione reprehenderit animi qui quae repellat voluptatem, 
    quisquam amet quo vel ullam odit minima architecto error tempore"
},
{
    id: 8,
    productImage: "images/lipCareBundle.jpg",
    productName: "Africhella Lip Care Bundle",
    productPrice: "3000",
    productDescription: "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Aliquam 
    quidem deserunt id repellendus ratione reprehenderit animi qui quae repellat voluptatem, 
    quisquam amet quo vel ullam odit minima architecto error tempore"
},
{
    id: 9,
    productImage: "images/lashes.png",
    productName: "Africhella Lashes",
    productPrice: "3000",
    productDescription: "Lorem ipsum, dolor sit amet consectetur adipisicing elit. Aliquam 
        quidem deserunt id repellendus ratione reprehenderit animi qui quae repellat 
        voluptatem, quisquam amet quo vel ullam odit minima architecto error tempore"
}]

export default Merchandise 

The React Code

let id = useParams()
let productId = id.id
console.log(productId)

let product = Merchandise.find(M => M.id = productId)
console.log(product)

This Is What The Output Currently Looks Like

5
{id: '5', productImage: 'images/heroImage.png', productName: 'Africhella Lip Gloss', productPrice: '3000', productDescription: 'Lorem ipsum, dolor sit amet consectetur adipisicin…uo vel ullam odit minima architecto error tempore'}
6
{id: '6', productImage: 'images/heroImage.png', productName: 'Africhella Lip Gloss', productPrice: '3000', productDescription: 'Lorem ipsum, dolor sit amet consectetur adipisicin…uo vel ullam odit minima architecto error tempore'}
7
{id: '7', productImage: 'images/heroImage.png', productName: 'Africhella Lip Gloss', productPrice: '3000', productDescription: 'Lorem ipsum, dolor sit amet consectetur adipisicin…uo vel ullam odit minima architecto error tempore'}
8
{id: '8', productImage: 'images/heroImage.png', productName: 'Africhella Lip Gloss', productPrice: '3000', productDescription: 'Lorem ipsum, dolor sit amet consectetur adipisicin…uo vel ullam odit minima architecto error tempore'}
9
{id: '9', productImage: 'images/heroImage.png', productName: 'Africhella Lip Gloss', productPrice: '3000', productDescription: 'Lorem ipsum, dolor sit amet consectetur adipisicin…uo vel ullam odit minima architecto error tempore'}

MongoDB Problems while inserting nested data

I try to build a database for a giveaway bot using MongoDB. Once a new giveaway is created the bot runs the following code to write the new giveaway into the databank:

const {mongoose} = require("mongoose")
const mainSchema = require('../models/mainSchema')

module.exports = {
  async execute(interaction){

  await new mainSchema ({
    guild_id: 1234567890,
    giveaways: [{
      identifier: 34,
      destination: 987654321,                      
    }],                                                                        
  }).save()
}

Giveaways should be a nested document in the document with the server informations. My schemas for this looks like this:

const mongoose = require("mongoose");

const giveawaySchema = new mongoose.Schema({  
    identifier: String,
    destination: String,
    duration: String,
    price: String,
})

const mainSchema = new mongoose.Schema({
    guild_id: String,
    log_channel_id: String,
    twitterPreferncesType: String,
    twitterPreferncesFollowing: Boolean,
    giveaways: [giveawaySchema],
});

module.exports = mongoose.model("mainSchema", mainSchema);
module.exports = mongoose.model("giveawaySchema", giveawaySchema);

In my Mongo Atlas I have 2 collections mainSchema und giveawaySchema. If I run this code I only get an entry under ‘giveawaySchema’ constisting of this:

_id: ObjectId(62b4f6374894fb3e7826ca72)
__v:0

I dont get any data in the mainSchema collection. Does anyone know my error? Thank you for you help in advance.

Org afraid to use Bootstrap due to page slowing down

Someone needs to convince upper management this* is helpful for them… as the product looks 15 yrs old, but page load is a big problem for them already.

I am thinking CDN for Bootstrap(BS)* helps solve most of the problems since a customer will not need to redownload (BS).

  1. Can I assume the same for popper and jquery (BS) links to is also pre-existing on most people’s cache so the page is likely not slowing down for a very large customer base?
  2. Any suggestions on what else they can do to convince upper management?

Thanks

Rotating x-axis for bar chart with dc.js

I’m trying to rotate the x-axis label for my bar chart since if the names are too long, the labels overlap with each other. How do I rotate it at like 65 degrees so that it looks something like this.

I am using dc/d3.js with Angular and here is my code:

    let xAxis = data.key;
    let newData: any = [];

    for (let i = 0; i < xAxis.length; i++) {
        newData.push({
            'name': xAxis[i],
            'count': data.values[i]
        })
    }

    let ndx = crossfilter(newData);

    let nameDimension = ndx.dimension(function (d: any) {
        return d.name;
    });

    let countDimension: any = ndx.dimension(function (d: any) {
        return +d.count;
    });

    let countGroup = nameDimension.group().reduceSum(function (p: any) {
        return +p.count;
    });

    barChart
        .width(525)
        .height(450)
        .transitionDuration(1000) // Animation delay
        .margins({ top: 30, right: 50, bottom: 25, left: 40 })
        .dimension(nameDimension)
        .group(countGroup)
        .x(d3.scaleOrdinal().domain(xAxis))
        .xUnits(dc.units.ordinal)
        .y(d3.scaleLinear().domain([0, countDimension.top(1)[0].count * 1.1])) // Dynamic scale is 10% larger than max range
        .elasticY(false)
        .renderHorizontalGridLines(true)
        .colorAccessor(function (d: any, i: any) {
            return d3.schemePaired[i];
        })
        .ordinalColors(d3.schemePaired)
        .renderLabel(true)
        .label(function (p: any) {
            return p.y;
        });

    dc.renderAll(group);

Authorisation for HTML img src on cross origin

I’m trying to load some resource, in this example an image, in an HTML file, that has it’s source on another server, which requires a login.
So writing
<img src="https://somewebsite.com/images/test.png">
without any form of authorisation provided, will give me a 401 response.
When I request the image e.g. with Postman and set the authorisation header accordingly, the image is loaded.
Embedding the login information directly into the image src like
<img src="https://username:[email protected]/images/test.png">
works perfectly fine too. Though I don’t wan’t to have sensible information visible in the DOM.
So basically, what I want to achieve is, that the authorisation header is set for the requests invoked by the img elements.

I already tried to do it with a service worker like this

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker
        .register('/service-worker.js')
        .then(registration => {
            console.log('ServiceWorker registration successful with scope: ', registration.scope);
        })
        .catch(err => {
            console.log('ServiceWorker registration failed: ', err);
        });
    });
}

with the service-worker.js containing

self.addEventListener('fetch', event => {
  event.respondWith(
      fetch(event.request, {
          mode: 'cors',
          credentials: 'omit',
          headers: {
              "Authorization": "Basic " + btoa('cui-test:cui-testcui-test')
          }
      })
  )
});

though that solution only works if the image’s URL is hosted on the same server, not cross origin.
I’m wondering if there is any way to configure a service workers scope to another server.
Or a completely different way to set the header on all requests.