DiscordJS cannot get _roles field after fetching member

I am fetching a member as:

...
private user: GuildMember;
...

try { 
    this.user = await interaction.guild?.members.fetch(SomeUserId)
}catch (e: unknown) {
    return await interaction.editReply("Couldn't find the specific user the in server.")
}

this.user will contain all the information regarding that specific. It also includes a field _roles:['123456789', '123456789']. How can I get this specific field? Note that doing the following results in ‘_roles does not exist on type GuildMember’:

console.log(this.user._roles)

Any way to access this field?

Promise.all not working with mongoose query

I’m trying to write a function that loops through an array of JSON objects and based on those values query mongoDB with mongoose. I’m trying to save Booking.find as an array of promises and then resolve all of them using Promise.all so that I can pass the result to another function.

However when I try to run the code I have right now it gets stuck at Promise.all and never moves past it. The database query works as intended and I have tried running the code with node version 15 and 16.

The strange thing is that the code works as intended on mac but not windows and ubuntu.

function checkBookings(timeslots, clinicID) {

  const promises = [];

  for (let i = 0; i < timeslots.length; i++) {
    promises.push(
      Booking.find({
        clinic: mongoose.Types.ObjectId(clinicID),
        date: new Date(convertDate(timeslots[i].date))
          .toISOString()
          .slice(0, 10),
        startTime: timeslots[i].start + "-" + timeslots[i].end,
      })
    );
  }
  Promise.all(promises).then((bookings) => {   //doesn't move past this point
    timeslots = filterAvailabiltyZero(timeslots, bookings);
    forwardTimeslots(timeslots, clinicID);
  });
}

I have also tried to write the code with async/await but it has the same results.

async function checkBookings(timeslots, clinicID) {

  const promises = [];

  for (let i = 0; i < timeslots.length; i++) {
    promises.push(
      Booking.find({
        clinic: mongoose.Types.ObjectId(clinicID),
        date: new Date(convertDate(timeslots[i].date))
          .toISOString()
          .slice(0, 10),
        startTime: timeslots[i].start + "-" + timeslots[i].end,
      })
    );
  }
  const bookings = await Promise.all(promises); //doesn't move past this point
  timeslots = filterAvailabiltyZero(timeslots, bookings);
  forwardTimeslots(timeslots, clinicID);
}

How to manipulate DOM both after server-side and client-side rendering?

Here is my code:

<template>
  <div class="comment-editor" v-if="loggedIn">
    <div class="leftside">
      <!-- <client-only> -->
      <textarea
        ref="editor"
        v-model="content"
        placeholder="your comment"
      ></textarea>
      <!-- </client-only> -->
      <Message v-bind="message" />
    </div>
    <Button
      text="Publish"
      color="main"
      v-if="message.type != 'loading'"
      @click="publish"
    />
  </div>
  <div class="notLoggedIn" v-else>
    You should <nuxt-link to="/signup">register</nuxt-link> or
    <nuxt-link to="/login">log in</nuxt-link> to write comments.
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: {},
      content: "",
    };
  },
  computed: {/*not important*/},
  mounted() {
    const tx = document.querySelector("textarea");
    fh(tx);
    tx.style.overflowY = "hidden";
    tx.addEventListener("input", function () {
      fh(this);
    });
    function fh(x) {
      while (x.style.height + "" != x.scrollHeight + "px")
        x.style.height = x.scrollHeight + "px";
    }
  },
  methods: {/*not important*/},
  props: ["number"],
};
</script>

What you can see in the “mounted” function is used to dynamically change the height of a textarea. It works properly when the component is client-side rendered (i.e. when navigating from another page), but the app crashes after SSR (when directly opening the page with the component). How to make that code work properly in both cases?

How to remove a element while html embedding (Basically for WebView)

I have a custom html file in my android studio project which embeds widgetbot. My html file is as below:

<!DOCTYPE html>
<html>
<head>
    <title> <!-- title bar --> </title>
    <!-- header for the website -->
</head>
<body>

<widgetbot
  server="***"
  channel="***" 
  width="100%" height="100%" frameborder="0" allowfullscreen="" style="position:absolute; top:0; left: 0"
></widgetbot>

<script src="https://cdn.jsdelivr.net/npm/@widgetbot/html-embed"></script>

</body>
</html>

After the webpage loads, in inspect element, the webpage loads normally but it looks like another webpage loads inside element.

I want to remove this part as it the header which i dont want.

<header class="header css-1nvbkb4-Root e1gp86mg0">
   <div class="css-1xdpm0r-SingleChannel e1gp86mg1">
      <header class="header css-ftpwd8-Root e60jqxd0">
         <img src="https://cdn.discordapp.com/icons/436489103958343680/acb5fe057d2b727bb0d880a8dd4bb498.webp?size=64" class="icon css-1gbdayj-Icon e60jqxd2">
         <h1 class="name css-1xb0hmy-Name e60jqxd4">.:BlackLine Cops And Robbers:.</h1>
         <div class="count css-1tkboa1-Count e60jqxd6">11</div>
         <button class="css-yq6jfn-Close-focusable ey5ep3f1"></button>
      </header>
   </div>
   <div class="css-a39jwx-Inner e1gp86mg2">
      <button class="hamburger css-1xuxpa9-Ham ev6qi2a0">
         <div class="css-1jpnuep-Burger ev6qi2a1"></div>
      </button>
      <div class="css-ryqcd0-Stretch e1gp86mg3">
         <div class="css-1685ixl-Hash-name e1gp86mg4">chat-room</div>
         <div class="topic css-1hbm74v-Topic e1gp86mg6"></div>
      </div>
      <div class="css-zbom6h-SingleChannelAuthWrapper e1gp86mg10">
         <a class="auth css-msu8uw-Button-Button-Button-focusable-Auth ejjc4ok7" target="_blank" style="padding: 2px 0px; min-width: 28px;">
            <svg stroke="currentColor" fill="none" stroke-width="2" viewBox="0 0 24 24" stroke-linecap="round" stroke-linejoin="round" height="1em" width="1em" xmlns="http://www.w3.org/2000/svg">
               <path d="M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4"></path>
               <polyline points="10 17 15 12 10 7"></polyline>
               <line x1="15" y1="12" x2="3" y2="12"></line>
            </svg>
         </a>
      </div>
   </div>
</header>

Inspect elements looks like this:

enter image description here

How can I remove the header, I am using this in android studio, but it wont help.

@Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);
                myWebView.loadUrl("javascript:(function() { " +
                        "var head = document.getElementsByTagName('header')[0];"
                        + "head.parentNode.removeChild(head);" +
                        "})()");
            }

How to save fetched data to a variable [duplicate]

I am trying to fetch some data from a remote API, filter it and later display it, when I console.log it I see that it is present, however, I can’t figure out how to save the data in a variable once fetched, how can I do it? Here is my attempt:

  let newData = null

   const fetchedData = fetch('https://jsonplaceholder.typicode.com/posts')
     .then((response) => response.json())
      .then((json) => newData(json));


const orderEmployees = newData.filter(employee => employee.jobTitle === 'Sales Representative');
const initialFilterState = { };

orderEmployees.forEach(employee => {
    if(employee.fullName === 'Wait Peperell') {
        initialFilterState[employee.id] = false;
    } else {
        initialFilterState[employee.id] = true;
    }
});

Validate submit button not working in jquery

I am beginner web developer.
I have webpage with dynamic create search forms:

<form action="{{ pageTemplate.pageHeader.webUrl |raw }}ListaStron/Wszystkie" method="get" name="contactformXX" aria-hidden="false"
                      class="form validate clearfix validate-formX clickForm validate-formXXX1">
                    <div class="form-group ">
                        <div class="form-group has-feedback ">
                            <input required="required" name="query" type="text" class="form-control indexInputSzukaj input_id1"
                                   id="input_id1"
                                   placeholder="Znajdź" value="{{ pageTemplate.pageHeader.pageValue.searchQuery }}"/>
                                   
<button type="submit" class="form-control-feedbackXX glyphiconColor showActionAfterClick searchBtnSUbmit1" style="background-color: transparent;border: 0;top:2px" >
   <span class="glyphicon glyphicon-search"></span>
</button>


                        </div>
                    </div>
                </form>

Sometimes I have 1 or more this form on one view.

I have validate code:

$('.searchBtnSUbmit1').click(function (e) {
    e.preventDefault();

    $('#.validate-formXXX1 input[type="text"]').blur(function () {
        alert('1');
        if (document.getElementsByClassName("input_id1").value.length == 0) {
            e.preventDefault();
            alert('Proszę uzupełnić poprawnie wszystkie wymagane pola formularza!');
        } else {
            form.submit();
        }
    });
});

But it’s not working 🙁 How can I repair it?

vue-apollo – Property ‘value’ does not exist on type ‘Readonly<Ref<Readonly>>’

THE SITUATION:

I am trying to integrate vue-apollo v4 with Typescript.

I am fetching a simple query using useQuery and useResult.

useResult by default return this type: Readonly<Ref<Readonly<any>>>

THE CODE:

import { GET_COUNTRY } from '../graphql/queries'
import { Country } from '../types'

setup() {
  const route = useRoute()
  const code = route.params.code

  const { result, loading } = useQuery(GET_COUNTRY, {code: code}, { 
    clientId: 'default', 
    fetchPolicy: 'cache-first'
  });
  const country = useResult(result, {}, (data) => data.country);

  console.log(country.name) // Property 'name' does not exist on type 'Readonly<Ref<Readonly<any>>>'.ts(2339)

  return {
    country,
    loading
  }
}

ATTEMPT 1:

const country: Country = useResult(result, {}, (data) => data.country);
// Type 'Readonly<Ref<Readonly<any>>>' is missing the following properties from type 'Country': native, phone, capital, currency, and 6 more.ts(2740)

ATTEMPT 2:

const country = useResult(result, {}, (data) => data.country as Country);
console.log(country.name) // Property 'name' does not exist on type 'Readonly<Ref<Readonly<any>>>'.ts(2339)

ATTEMPT 3:

const country: Country = useResult(result, {}, (data) => data.country as Country);
// Type 'Readonly<Ref<Readonly<Country | {}>>>' is missing the following properties from type 'Country': native, phone, capital, currency, and 6 more.ts(2740)

THE QUESTION:

Is it possible to combine useResult with my own Typescript interface?

How to read configuration files and map them to typesafe models using Vue3?

I have a Vue3 app using TypeScript and want to load a configuration file and map it to a model.

Inside the public directory I added a subdirectory configurations with a config.json file

{
    "foo": "bar"
}

This json object should get mapped to the following model config.ts

export interface Config {
  foo: number;
}

Inside my Vue component I’m reading the configuration file from the public folder and try to map it to the model

<script lang="ts">
import { defineComponent } from "vue";
import { Config } from "./config";

export default defineComponent({
  setup() {
    fetch(process.env.BASE_URL + "configurations/config.json")
      .then((response: Response) => response.json())
      .then((jsonConfiguration: any) => {
        const config: Config = jsonConfiguration as Config;
        console.log(config.foo);
      });
  },
});
</script>

I would expect an exception, e.g.

“foo must be of type number”

but the logger simply logs “bar”, although it’s not a number.

What is a common (and typesafe) approach to

  • Put configuration files somewhere during deployment (e.g. customer config)
  • Read them
  • Map the content to a given model

using Vue3?

How to solve realm already opened on current thread with different schema?

What I’m trying to do is save a table and his following fields , but these table’s are defined by an API response and the fields are predeterminated, but I cannot figure out how to make it works properlly since the table is variable, I will show you some code:

Here is my model where I call the realm to open my table , as you can see there is a variable called table and this is where I send a string which is the name of the table that I want to open.

export const getRealm = async(table) => {
  const tabela = {
    name: table,
    properties: {
      field: "string",
      fieldtype: "string",
    }
  }
  try {
    return await Realm.open(
      {
        schema: [tabela],
        deleteRealmIfMigrationNeeded: true,
      }
    );
  } catch (error) {     
    console.log('ERRRRROOOOOOOR REALM',error.message);
  }
};

When I want to store some data into my realm, with the controller realmAction.js , my dados is a JSON and my objeto is the name of the table which is a string

export const FieldsSchema = async (dados,objeto) => { 
  try {  
    dados.map(
      async (item) => {
      await getRealm(objeto).then((realm) => {      
        const data = {
        field: item.field,
        fieldtype: item.fieldtype,
       };
        realm.write(() => {
        realm.create(objeto, data, 'modified'); 
        });
       // realm.close(); Closing results me in an error which is `Cannot access realm that has been closed` cause its a map function and send more than once the same table string
      });
      }
    )  
  } catch (error) {
    console.log('ERROOOR', error.message);
  }
};

What seems to be wrong is that realm cannot handle oppening two different tables in the same thread , but as I read in the mongo/realm documentation I need to seet a model schema , but my models are a variable which the users create , someone knows how can I handle this ?

Using local storage on Angular

I would appreciate someone’s help or opinion regarding a little problem I have since I am complete beginner in coding.
I am trying to make a simple phonebook using Angular, but I am having a bit hard time making my “app” store the information inserted to local storage.
Here is what I have so far, so if anyone has time to take a peak, I would appreciate it very much.
Kind regards 🙂

File input still required after upload

I have a file input which is required. I attach a file to it, submit the form, go back on the form and here is the problem. Instead of showing me the uploaded filename in the input, it’s just an empty input, so I have to fill it again as it’s a required input (otherwise I cannot submit the form).
Is there a way to “retrieve” the file and attach it to the input?

Thank you.

why is useMatch not working in React router?

I’m learning how to use useMatch() from "react-router-dom"
I am getting the error below and my web page is blank:

Uncaught TypeError: Cannot read properties of undefined (reading 'path')
    at matchPath (index.tsx:1148)
    at index.tsx:481
    at mountMemo (react-dom.development.js:15846)
    at Object.useMemo (react-dom.development.js:16219)
    at useMemo (react.development.js:1532)
    at useMatch (index.tsx:481)
    at About (About.js:7)
    at renderWithHooks (react-dom.development.js:14985)
    at mountIndeterminateComponent (react-dom.development.js:17811)
    at beginWork (react-dom.development.js:19049)

my code is below

import React from "react"
import { useMatch  } from "react-router-dom"
import { Link, Route } from "react-router-dom"
import SinglePage from "./SinglePage"

const About = () => {
  const { url, path } = useMatch()
  console.log("hello usematch!", useMatch())
  return (
    <div>
      <ul>
        <li>
          <Link to={`${url}/about-app`}>About App</Link>
        </li>
        <li>
          <Link to={`${url}/about-author`}>About Author</Link>
        </li>
      </ul>
      <Route path={`${path}/:slug`}>
        <SinglePage />
      </Route>
    </div>
  )
}
export default About

I’ve tried going through the api docs but unclear about why this is not working and how to make the page load. I am trying to return the nearest current route match within the context of where it’s called.

I am quite new to react and router apis.

Thanks so much

How to make a function work for multiple div’s with the same classes in javascript?

I’ve been trying to make a web-based tallying-application using javascript. I got it to work, but only for the first instance of a class (e.g. first tallying-element).

How do I make the function work for multiple the subsequent instances of the tallying-elements?

Also, I’m using Bootstrap v5.1.3 for the css, but did not add the lengthy code.

Your help is greatly appreciated!

let add = document.querySelector(".add");
let minus = document.querySelector(".minus");
let reset = document.querySelector(".reset");
let counter = document.querySelector(".counter");

add.addEventListener('click', addCounter);
minus.addEventListener('click', minusCounter);
reset.addEventListener('click', resetCounter);



function addCounter(item) {
    counter_num = counter.innerHTML
    counter.innerHTML = parseInt(counter_num) + 1
}

function minusCounter(){
    counter_num = counter.innerHTML
    if (counter_num == 0){
        return false
    }
    counter.innerHTML = parseInt(counter_num) - 1
}

function resetCounter(){
    if (counter.innerHTML == 0){
        return false
    }
    if (confirm("Weet je zeker dat je de telling wilt resetten?") == true){
        counter.innerHTML = 0;
        resetCounter = "De telling is gereset!"
    } else {}
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta  name="viewport" content="width=devide-width", initial-scale="1.0">
        <link rel="stylesheet" href="bootstrap.min.css">
        <title>Turf-app geadresseerd voorschrijven</title>

        <style>
            .counter{color:white; font-size: 25px; border-radius: 10%;max-width:50px;}
            .tally_container{background-color:lightgrey; border-radius: 10px; padding:20px;}
            .add{width: 38px; height: 38px;}
            .minus{width: 38px; height: 38px;}
            .title-text{color: white;}
            .counter2{color:white; font-size: 25px; border-radius: 10%;max-width:50px;}

        </style>
    </head>

    <body class="jumbotron bg-dark">
        <h1 class="text-center mx-4 mt-4 mb-5 title-text">Turf-app geadresseerd voorschrijven</h1>
        
        <div class="container" id="1">
            <div class="tally_container mt-3 mb-3" name="tally-element">
                <div class="vraag-container mb-3">
                    <h3>Patiënten zonder recept</h3>
                </div>

                <div class="counter-div text-center">
                    <div class="mx-2 text-center mb-2 counter bg-dark">0</div>
                </div>

                <div class="buttons">
                    <button class="btn btn-success mx-2 add">+</button>
                    <button class="btn btn-danger mx-2 minus">-</button> <br>
                    <button class="btn btn-primary mx-3 mt-4 reset">Reset</button>
                </div>
            </div>
        </div>

        <div class="container" id="2">
            <div class="tally_container mt-3 mb-3" name="tally-element">
                <div class="vraag-container mb-3">
                    <h3>No-shows</h3>
                </div>

                <div class="counter-div text-center">
                    <div class="mx-2 text-center mb-2 counter bg-dark">0</div>
                </div>

                <div class="buttons">
                    <button class="btn btn-success mx-2 add">+</button>
                    <button class="btn btn-danger mx-2 minus">-</button> <br>
                    <button class="btn btn-primary mx-3 mt-4 reset">Reset</button>
                </div>
            </div>
        </div>

     
        
        
    <script src="app.js"></script>
    </body>

</html>

Right way to iterate over record [duplicate]

I’m trying –

export function logError(paramsToLog?: Record<string, string>): void {
    const logData: LoggerData[] = [];
    if (paramsToLog) {
        for (const key of paramsToLog) {
            logData.push(LoggerData.create(key, paramsToLog[key]));
        }
    }
    ....
}

I see eslint complaining – (parameter) paramsToLog: Record<string, string> Type 'Record<string, string>' must have a '[Symbol.iterator]()' method that returns an iterator.

Could not find any iterator in record arg.