Creating a dictionary in JavaScript from a string

How can I convert this string [[1, 56000], [2, 55000]] into a dictionary where the numbers 1,2 etc are keys and 56000, etc are values.
The string might get bigger so I want to know how I can convert this string into a dictionary without knowing the number of iterations to be taken into consideration. Thanks.

Why do i get discord js command handler error?

Ive tried implementing a command handler, so i can make embed commands because ive got a lot of errors while coding embeds in my index.js file and everybody in all tutorials uses command handlers. So anyways i followed the command step by step and now i get Errors.
This is the bot code:

const express = require("express");
const app = express();

const discord = require("discord.js");
const client = new discord.Client({intents:["GUILDS","GUILD_MESSAGES"]});

const fs = require("fs");
var read_data = fs.readFileSync("./userdata.json");
var datafile = JSON.parse(read_data);

const levels_api = require("mee6-levels-api");

var bump_timeout = true;

var port = process.env.PORT || 3000;

var eventFiles = fs.readdirSync("./events").filter(file => file.endsWith('.js'));

for(const file of eventFiles){
  const event = require(`./events/${file}`);

  if(event.once){
    client.once(event.name, (...args) => event.execute(...args, commands));
  }
  else{
    client.on(event.name, (...args) => event.execute(...args, commands));
  }
}

app.listen(port, "0.0.0.0", function() {
console.log("Listening on Port 3000");
});


client.on("message", message => {
  var msg_value = message.content.toLowerCase();
  var username = message.author.username;
  var id = message.author.id;
  var user_joined = new Date(message.author.joinedTimestamp).toLocaleDateString();
  if(msg_value.includes('hello') && msg_value.includes('bot') || msg_value.includes('hi') && msg_value.includes('bot')){
    message.channel.send("hi dad");
  }
  if(message.content === "!d bump" && bump_timeout==true){
    if(!datafile[id]){
      datafile[id] = {coins: 100};
      fs.writeFileSync("./userdata.json", JSON.stringify(datafile, null, 2));
      message.channel.send(`<@${id}> got 100 coins!`);
    }
    else{
      var chillcoins = Number(datafile[id].coins) + 100;
      message.channel.send(`<@${id}> got ${chillcoins} coins!`);
      datafile[id] = {coins: chillcoins};
      fs.writeFileSync("./userdata.json", JSON.stringify(datafile, null, 2));
    };
    bump_timeout = false;
    setTimeout(bump_switchtimeout, 72000000);
  };
  if(message.content.startsWith('!squid') && message.content.includes('bal')){
    var mentioned_user = message.mentions.users.first() || message.member.user;
    var mentioned_user_id = mentioned_user.id;
    if(!datafile[mentioned_user_id]){
      datafile[mentioned_user_id] = {coins: 0};
      fs.writeFileSync("./userdata.json", JSON.stringify(datafile, null, 2));
      message.channel.send(`<@${mentioned_user_id}> has 0 coins`);
    }
    else{
      var coins = Number(datafile[mentioned_user_id].coins);
      message.channel.send(`<@${mentioned_user_id}> has ${coins} coins`);
    }
  }
  if(msg_value == "!squid help"){
    const help_embed = new discord.MessageEmbed
      .setTitle("Squid bot Commands")
      .addFields(
            { name: 'Hi Bot', value: 'You greet our bot' },
            { name: '!squid help', value: 'You call the ambulance' },
            { name: '!d bump', value: 'Bumping the server will give you chillcoins', inline: true },
            { name: '!squid bal', value: 'This command displays your chillcoins', inline: true },
      );
    message.channel.send({embeds: [help_embed]});
  }

  
})

function bump_switchtimeout(){
  bump_timeout = true;
}

client.on("ready", () => {
  console.log("bot is ready");
  client.user.setActivity({name: "chilling", type: "PLAYING"});
})


client.login("token");

This is the error Message:

ReferenceError: commands is not defined
    at Client.<anonymous> (C:UsersUserDocumentsGitHubSquidbot1index.js:23:65)
    at Object.onceWrapper (node:events:646:26)
    at Client.emit (node:events:538:35)
    at WebSocketManager.triggerClientReady (C:UsersUserDocumentsGitHubSquidbot1node_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:379:17)
    at WebSocketManager.checkShardsReady (C:UsersUserDocumentsGitHubSquidbot1node_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:362:10)
    at WebSocketShard.<anonymous> (C:UsersUserDocumentsGitHubSquidbot1node_modulesdiscord.jssrcclientwebsocketWebSocketManager.js:189:14)
    at WebSocketShard.emit (node:events:526:28)
    at WebSocketShard.checkReady (C:UsersUserDocumentsGitHubSquidbot1node_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:509:12)
    at WebSocketShard.onPacket (C:UsersUserDocumentsGitHubSquidbot1node_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:481:16)
    at WebSocketShard.onMessage (C:UsersUserDocumentsGitHubSquidbot1node_modulesdiscord.jssrcclientwebsocketWebSocketShard.js:317:10)

Using .map() to iterate over an array of Object values and reassign to new keys

I am trying to transform the data below from:

{
      title: 'The Promise',
      blurb: 'Lorem Ipsum',
      cover_image: 'Lorem Ipsum',
      pub_year: 2002,
      genre: 'Foobar'
    }

To:

[
 {
   col1: 'The Promise',
   col2: 'Lorem Ipsum',
   col3: 'Lorem Ipsum',
   col4: 2002
   col5: 'Foobar'
 },
]

I have been puzzling away at this for quite a while and can only get it looking like this, which is just seperate objects rather than a single object as part of an array of objects (there are other book objects in the returned JSON from my db the function needs to churn through)

{col1: 1} //this is an id
{col2: 'The Promise'}
{col3: 'Lorem ipsum'}
{col4: Lorem Ipsum}
{col5: '2002'}
{col6: Foobar}

Here is the code I have been working on:

 const data = React.useMemo(
    () =>
      props.tableData.map((object, i) => {
        Object.values(object).map((value, i) => {
          let col = `col${i + 1}`
          const obj = { [col]: value }
        })
      }),
    [props.tableData]
  )

Why doesn’t required work with inner.HTML?

HTML part:

<div id="sidePanel">
    <form>
      <div id="instrucions">
        Welcome to the learning activity! In this activity, you will learn
        about sampling processes through exploring a simulation of
        armadillos. Sampling processes are important for learning data
        literacy, so we hope you will find this activity useful!
      </div>
      <div id="feedback"></div>
      <button type="submit" onclick="explore()">Next</button>
    </form>
  </div>

JS part:

    function firstImp() {
  var element = document.getElementById("sidePanel");
  element.innerHTML =
    "Tell what you have noticed from your observations. What stood out?";
  element.innerHTML =
    element.innerHTML +
    "<br><input  type='text' id='colsTextArea' size='250' maxlength='250' required style='width: 500px;'/> <br><button type='submit' onclick='horizontal()'" +
    '"' +
    +element.id +
    '"' +
    ")' >Next</button><br>";
}

I am wondering what might be wrong with this code? Required doesn’t work. I am wondering if it’s something about using DOM?

Vue.js 3 input showing data not change when watch change the value

I have a TextInput component and based on Vue docs, I added v-model to my component.

It is my component:

<template>
    <div class="floating_input">
        <input type="text" :id="id" :name="name" :key="id" class="form_input"
               :placeholder="label" v-model="value">
        <label class="floating_label" :for="id">{{ label }}</label>
    </div>
</template>

<script setup>
    import { defineProps, defineEmits, computed } from "vue";

    const props = defineProps({
        label: {
            type: String,
            required: false
        },
        id: {
            type: String,
            required: true
        },
        name: {
            type: String,
            required: true
        },
        modelValue: String
    });
    const emit = defineEmits(['update:modelValue']);
    
    const value = computed({
        get() {
            return props.modelValue
        },
        set(value) {
            emit('update:modelValue', value)
        }
    })
</script>

In another component, I use a watcher to check that if the value is not numeric, use the oldValue as the value of this component.
Finally, when I enter a letter, everything is correct and the oldValue is considered as the currentValue, but the displayed value is wrong and shows the letters too.

It is what shows in Vue dev tools:
vue dev tools

and it is what shows in the browser
Browser

Bottle static file and download it to the browser with JS

I have a file that I want the user to download with his browser.
I am using backend of Bottle:

file = stdout.decode("utf-8")[stdout.decode("utf-8").rindex('/') + 1:stdout.decode("utf-8").find('xlsm') + 4]
new_path = stdout.decode("utf-8")[:stdout.decode("utf-8").rindex('/')]
return bottle.static_file(file, root=new_path)

and FE of JS:

    fetch(url, { // Your POST endpoint
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: jsonToSend // This is your file object
      }).then(
        response => {
            let p = response.json();
            p.then(value => {
                console.log(value);
                let text = 'the script returned: ' + value.text
                alert(text)
                }).catch(err => {
                  console.log(err);
                });
        }).then(
        success => console.log(success)
      ).catch(
        error => console.log(error) 

What do I need to change in order to download the file I am sending in the Bottle?

Thanks

Can anyone help me with this homework? I have trouble doing this [closed]

Create 2 files:

home.html
script.js

  1. Create an html page, add 3 text boxes in which the user will input 3 numbers :a,b,c
    Add a button that, on click, will calculate the maximum number of the three. The result will be displayed in an alert. The program should not crash if the user does not input one or two numbers.
    Cases:
    -If no number is introduced then a message should be displayed asking the user to input at least on number.
    -If only one number of the three is introduced, that number is the maximum number.
    -If two numbers are introduced then it should be displayed the maximum of the two.
    -If three numbers are introduced then it should be displayed the maximum of the three.

I’m unable to find a previous date by inputing a given date by a user using html and javascript. Can you please help me out

‘This is the HTML Code’

<form>
  <div class="input-field">
    <label>Choose Date</label>
    <input type="date" id="date" onchange="myDate();" required>
  </div>
  <div class="input-fields">
    <label>Previous Date</label>
    <input type="date" id="previous" readonly>
  </div>
</form>

‘This is the Javascript Code’

<script>
    function myDate()
      {
      const currDate = document.getElementById("date");
      const date = new Date(currDate)
      if (typeof date === 'object' && date !== null && 'getDate' in date) {
      console.log("The data type is", typeof date)
      console.log(date.getDate())}
      else {
        console.log("Invalid Date Object")
      }
      date.setDate(date.getDate()-1);
      const previous = document.write(date);
      document.getElementById("previous").value = previous;
      }
</script>

I’m trying to get previous date by using the myDate Function in Javascript and i was getting an error getDate is not a function then i tried to make getDate as function and now its showing the same error. I’m not able to make a getDate as function or getting previous date value

vuejs remove key and value from URL based on conditions

I am making a simple filter and In this filter I am pushing query parameters to URL and appending them. If user choose a particular option, I want to modify the query string and I need the help here.

My URL is like this : http://app.test/home?preference=onsite&place=Aus&place=Mus

and if user choose wfh instead of onsite for preference I want to remove place from URL and want this URL: http://app.test/home?preference=wfh

my code:

<template>
    <div>
        <div class="mt-2">
            <label>Job Preferences</label>
            <select class="form-control" v-model="filter.preference">
                <option value="">............</option>
                <option value="onsite" >Onsite</option>
                <option value="wfh">WFH</option>
            </select>
        </div>

        <div class="mt-2" v-if=" this.$route.query.preference == 'onsite'">
            <label>Available for work</label>
            <div class="form-control" >
                <input type="text">
                <div class="options" style="max-height:140px;overflow:scroll">
                    <ul class="" style="max-height:40px;">
                        
                        <li v-for="place in places" :key="place.id">
                           <input type="checkbox" v-model="filter.place" 
                           :value="place.name">{{ place.name }}
                        </li>
                    
                    </ul>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
export default {
    data() {
        return {
            places: [
                    {
                        id: 1,
                        name: "Aus",
                    },

                    {
                        id: 2,
                        name: "Mus",
                    }, 
            ],

            filter: {
                preference: this.$route.query.preference,
                place:[],
            },
        };
    },

    watch: {
        filter: {
            handler() {
                const query = this.filter
                if (this.$route.query.preference == 'wfh') {
                    this.$route.query.place='';
                    this.$router.replace({ query: query });
                }
                    
                this.$router.push({
                    query: query,
                });
                
            },
            deep: true,
        },
    },
};
</script>

I wrote below code to check if preference is wfh and update URL but this is not working

  if (this.$route.query.preference == 'wfh') {
     this.$route.query.place='';
     this.$router.replace({ query: query });
   }

Adding transform to carousel element breaks scroll

I recently came across this carousel Tailwind component (https://codesandbox.io/s/react-multi-item-carousel-uvmchp?file=/src/carousel.jsx).

I wanted the carousel items to enlargen on hover, so I made a change (namely adding hover:scale-125 transform-gpu transition duration-150 ease-in-out and removing overflow-hidden), but in doing so the left and right arrows of the carousel no longer work.

How can I fix this?

My code is here: https://codesandbox.io/s/react-multi-item-carousel-forked-jebmii?file=/src/carousel.jsx:0-4494

import { useState, useRef, useEffect } from "react";
import data from "./data.json";

const CollectionCarousel = () => {
  const maxScrollWidth = useRef(0);
  const [currentIndex, setCurrentIndex] = useState(0);
  const carousel = useRef(null);

  const movePrev = () => {
    if (currentIndex > 0) {
      setCurrentIndex((prevState) => prevState - 1);
    }
  };

  const moveNext = () => {
    if (carousel.current.offsetWidth * currentIndex <= maxScrollWidth.current) {
      setCurrentIndex((prevState) => prevState + 1);
    }
  };

  const isDisabled = (direction) => {
    if (direction === "prev") {
      return currentIndex <= 0;
    }

    if (direction === "next" && carousel.current !== null) {
      return (
        carousel.current.offsetWidth * currentIndex >= maxScrollWidth.current
      );
    }

    return false;
  };

  useEffect(() => {
    if (carousel !== null && carousel.current !== null) {
      carousel.current.scrollLeft = carousel.current.offsetWidth * currentIndex;
    }
  }, [currentIndex]);

  useEffect(() => {
    maxScrollWidth.current = carousel.current
      ? carousel.current.scrollWidth - carousel.current.offsetWidth
      : 0;
  }, []);

  return (
    <div className="carousel my-12 mx-auto">
      <div className="relative">
        <div className="flex justify-between absolute top left w-full h-full">
          <button
            onClick={movePrev}
            className="hover:bg-blue-900/75 text-white w-10 h-full text-center opacity-75 hover:opacity-100
            disabled:opacity-25 disabled:cursor-not-allowed z-10 p-0 m-0 transition-all ease-in-out duration-300"
            disabled={isDisabled("prev")}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-12 w-20 -ml-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M15 19l-7-7 7-7"
              />
            </svg>
            <span className="sr-only">Prev</span>
          </button>
          <button
            onClick={moveNext}
            className="hover:bg-blue-900/75 text-white w-10 h-full text-center opacity-75 hover:opacity-100
            disabled:opacity-25 disabled:cursor-not-allowed z-10 p-0 m-0 transition-all ease-in-out duration-300"
            disabled={isDisabled("next")}
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              className="h-12 w-20 -ml-5"
              fill="none"
              viewBox="0 0 24 24"
              stroke="currentColor"
              strokeWidth={2}
            >
              <path
                strokeLinecap="round"
                strokeLinejoin="round"
                d="M9 5l7 7-7 7"
              />
            </svg>
            <span className="sr-only">Next</span>
          </button>
        </div>
        <div
          ref={carousel}
          className="carousel-container relative flex gap-1 scroll-smooth snap-x snap-mandatory touch-pan-x z-0"
        >
          {data.resources.map((resource, index) => {
            return (
              <div
                key={index}
                className="carousel-item text-center relative w-64 h-64 snap-start hover:scale-125 transform-gpu
                transition duration-150 ease-in-out"
              >
                <a
                  href={resource.link}
                  className="h-full w-full aspect-square block bg-origin-padding bg-left-top bg-cover bg-no-repeat z-0"
                  style={{ backgroundImage: `url(${resource.imageUrl || ""})` }}
                >
                  <img
                    src={resource.imageUrl || ""}
                    alt={resource.title}
                    className="w-full aspect-square hidden"
                  />
                </a>
                <a
                  href={resource.link}
                  className="h-full w-full aspect-square block absolute top-0 left-0 transition-opacity
                  duration-300 opacity-0 hover:opacity-100 bg-blue-800/75 z-10"
                >
                  <h3 className="text-white py-6 px-3 mx-auto text-xl">
                    {resource.title}
                  </h3>
                </a>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
};

export default CollectionCarousel;

Using Array.map in nested object structure in Java Script

I have below object structure in array

[
  {
   "modules":set of modules here 
   "details": [
     {
       "name":"abc"
       "version":"1.2.3"
     },
     {
       "name":"def"
       "version":"2.3.4"
     },
     {
       "name":"ghi"
       "version":"4.5.6"
     }
   ]
  },
  {
   "modules":set of modules here 
   "details": [
     {
       "name":"jkl"
       "version":"7.8.9"
     },
     {
       "name":"mno"
       "version":"10.11.12"
     },
     {
       "name":"pqr"
       "version":"13.14.15"
     }
   ]  
  }
]

What I want to do is :
get details array transformed into below format for each root object in master array as

"details": [
     {
       module:"jkl:7.8.9"
     },
     {
       module:"mno:10.11.12"
     },
     {
       module:"pqr:13.14.15"
     }
   ]  

So final array would be :

[
  {
   "modules":set of modules here 
   "details": [
     {
       "module":"abc:1.2.3"
     },
     {
       "module":"def:2.3.4"
     },
     {
       "module":"ghi:4.5.6"
     }
   ]
  },
  {
   "modules":set of modules here 
   "details": [
     {
       "module":"jkl:7.8.9"
     },
     {
       "module":"mno:10.11.12"
     },
     {
       "module":"pqr:13.14.15"
     }
   ]  
  }
]

What I have tried and is working is :

rootArray.forEach((entry)=> {
    let line = entry.details.map((detailEntry)=>{
    //merge detailEntry into single line 
    })
    entry.details = line 
});

My question is : is this a right approach or is there any better solution available ?

In closures we know for each loop iteration variable “i” is a fresh copy, then why const “i” not work in a loop

/this code works and each callback is referencing to a different “i” it indicates that for each loop iteration a new copy of “i” is created, due to that the callback forms a closure with a distinct “i” each time/

const arr = [10, 12, 15, 21];
for (let i = 0; i < arr.length; i++) {
  setTimeout(function() {
  console.log('Index: ' + i + ', element: '+ arr[i]);
  }, 3000)
}

/This gives error: Assignment to constant variable.
Why not in this case a new constant “i” is created for each loop iteration
/

const arr = [10, 12, 15, 21];
for (const i = 0; i < arr.length; i++) {
  setTimeout(function() {
    console.log('Index: ' + i + ', element: '+ arr[i]);
  }, 3000)
}

Retrieve value from x++ outside of a function – JavaScript

I have a little problem!

I need to retrieve the value of score++ outside of its function.

For example, if the user clicks “button” 5 times I want the score result to be 5.

How to use this result in a new function?

I searched without finding a solution.

let score = 0;
let clickHere = document.getElementById("clickHere");

clickHere.addEventListener("click", () => {
score++;
// console.log(score)
// Add 1 when I click
});

console.log(score);
// Score = 0
#clickHere {
padding: 20px;
background-color: #000000;
color: #ffffff;
font-weight: bold;
text-transform: uppercase;
display: inline-block;
}
<div id="clickHere">Click here !</div>

:).

enter image description here

how to get mat select native attribute in angular

For an input we get attribute using and for example below , but how do we do this to a mat select ? I only manged to to this on an input.

The sample code below works on an input but I wanna use the same implementation to a mat select , how do we do this using mat select ? Thanks.

The goal is to close the mat select or close the focus when user select or user click outside the mat select.

here is a blitz we can play

https://stackblitz.com/edit/angular-z5kmt5?file=app%2Ftable-basic-example.html,app%2Ftable-basic-example.ts

#html

 <input matInput name="symbol" [(ngModel)]="element.symbol" (blur)="editRowId=-1"> 

#ts

@ViewChildren(MatInput,{read:ElementRef}) inputs:QueryList<ElementRef>;

 setTimeout(()=>{
      this.inputs.find(x=>x.nativeElement.getAttribute('name')==element).nativeElement.focus()
    })

#html select

<mat-select (selectionChange)="statusChange(item)" name="status" [(ngModel)]="item.status" class="inspection-status-dropdown">
  <mat-option (blur)="editRowId=-1" *ngFor="let statusItem of status | keyvalue" [value]="statusItem.value">
    {{statusItem.value}}
  </mat-option>
</mat-select>