One-button interaction with the remote control

I created a button and now I need that when I open the control’s enter button it clicks on the button and when I press the arrows the course moves between the buttons

I’m having trouble knowing how to create the code, I’ve already looked at the documentation but I couldn’t understand how to create the code

Reactivity of a long to calculate prop in Vue.js

I have a Vue component that receives two props: values (an object containing various fields including name) and apiResponse (initially an empty object).
The component includes a name field that should display apiResponse.name when apiResponse is updated with data from an API call. If apiResponse.name is not available, the field should display values.name instead.
I would like to make the name field in the component dynamically update to show apiResponse.name once the API call completes and apiResponse is populated with data.

I am then working with these 2 props.
I tried to put apiResponse as a watch but the logs do not display in my console when apiResponse gets calculated. I know it does get calculated because I have a <div> that displays its value directly, and that correctly updates when apiResponse changes.

I tried to make accountValues a computed value that will be this.values.name or this.apiResponse.name based on wether the first one is empty or not.

But it does not work and I would greatly appreciate some help 🙂

Here is my Vue component that I simplified the most I could (I hope I did not forget unrelevant bits of code):

<template>
  <div v-if="apiResponse">
    <h3>Company Name: {{ apiResponse.company.name }}</h3>
  </div>
  <div v-else>
    <h3>Company Name: waiting for api response </h3>
  </div>
  <TextField
    :value="accountValues"
    :warning="displayNameWarning"
    v-model="name"
    name="account-name"
    label="Name"
    rules="required"
    class="col-span-6 sm:col-span-2">
    <template #warningMessage>
      {{ nameWarning.message }}
    </template>
  </TextField>
</template>

<script>
import { defineComponent } from "vue";
import TextField from "../TextField";
import TagsField from "../TagsField";
import TextareaField from "../TextareaField";
import SelectField from "../SelectField";
import { debounce, find, isEmpty, size } from "lodash";
import postApi from "../../../api";

export default defineComponent({
  components: {
    TextField,
    TextareaField,
    SelectField,
    TagsField,
  },

  props: {
    values: {
      type: Array,
      default: null,
    },
    apiResponse: {
      type: Object,
      default: ({}),
    },
  },

  data() {
    return {
      name: '',
      nameWarning: {},
      mlValues: {},
    }
  },

  mounted() {
    if (this.values) {
      if (this.values.record_type === this.accountTypes[1]) {
        this.showPortfolioCompanyId = false;
      } else if (this.values.record_type === this.accountTypes[2]) {
        this.showPortfolioCompanyId = true;
      }

      this.showOccupation = this.isLimitedPartner(this.values.record_type);
      this.showIndustry = !this.isLimitedPartner(this.values.record_type);
    }

  },

  watch: {
    name: {
      handler(newValue, oldValue) {
        this.checkName(newValue);
      }
    },
    apiResponse: {
      handler(newValue, oldValue) {
        console.log('apiResponse changed');
        console.log(newValue);
        console.log(oldValue);
        
        this.mlValues.name = newValue.company.name;
      }
    }
  },

  computed: {
    users() {
      return this.$page.props.users;
    },

    isFromUSA() {
      return find(
        this.$page.props.permissions,
        { name: 'pre-fill USA fields' }
      ) !== undefined;
    },

    displayNameWarning() {
      return !isEmpty(this.nameWarning);
    },

    accountValues() {
      
      const ret = this.values ? this.values : this.mlValues;
      console.log('accountValues', ret);
      return ret;
    }

  },

  methods: {
    handleAccountType: function(newValue) {
      this.showIndustry = !this.isLimitedPartner(newValue);
      this.showOccupation = this.isLimitedPartner(newValue);
      this.showPortfolioCompanyId = newValue === this.accountTypes[2];
    },

    checkName: debounce(async function(string) {

      this.nameWarning = {};

      if(string === "" || string.length <= 4) {
        return;
      }

      const response = await postApi("/nova-vendor/forms/check/account/name", { 'name': string });
      const result = await response.json();

      const nbResult = size(result);

      if(nbResult) {
        this.nameWarning = {
          message: nbResult + ' account(s) with a similar name',
          data: result
        }
      }
    }, 500),

  },

});
</script>

How to propagate child component changes to the parent (or refresh it) component in React?

I have a page that passes a client item to a component, this component then passes the client item to its child component. This child component edits the client item. How can I make the child’s edits go directly to the parent item? Currently, after the edits in NewContactModal.jsx, the parent component is not affected and shows the data it had previously pulled.

Here is my code:

// Sale_resume.jsx
const { sale, selectedItems, setTotals, setCustomer } = useContext(SaleContext)

<ContactInfoModal
  client={sale.customer}
  show={showContactInfoModal}
  handleClose={handleCloseContactInfoModal}
/>

// ContactInfoModal.jsx
const ContactInfoModal = ({ client, show, handleClose, refreshContactList  }) => {
  // ...
  <p className='m-0 fw-bold'>Nome</p>
  <p>{client.short_name}</p>
  <p className='m-0 fw-bold'>CPF/CNPJ</p>
  <p>{client.federal_tax_id}</p>
  <NewContactModal
    contact={client}
    show={updateContactModalShow}
    handleClose={handleCloseUpdateContactModal}
  />
  // ...
}

// NewContactModal.jsx
const NewContactModal = ({ show, handleClose, contact, getContacts }) => {
  const handleSubmit = async () => {
    // ...
    let response = {}
    if (contact) {
      response = await gestupApi.putContact(contact.id, { name, federalTaxId, address, neighborhood, number, zip, complement, selectedState, selectedCity, phoneNumber, email, suframa, stateTax, cityTax, contributorType, channel, birthDate })
    } else {
      response = await gestupApi.postContact({ name, federalTaxId, address, neighborhood, number, zip, complement, selectedState, selectedCity, phoneNumber, email, suframa, stateTax, cityTax, contributorType, channel, birthDate })
    }
    if (response.code == 200) {
      resetStates()
      getContacts ? getContacts() : ""
      contact ? toast.success("Contato atualizado com sucesso") : toast.success("Contato criado com sucesso")
    } else {
      contact ? toast.error("Falha ao atualizar o contato") : toast.error("Falha ao criar o contato")
    }
    handleClose()
  }
  // ...
  <div className="form-group">
    <label className="control-label" id="full_name_label">{contributorType == "COMPANY" ? "Razão Social*" : "Nome*"}</label>
    <input type="text" className='form-control' maxLength={60} onChange={(e) => setName(e.target.value)} value={name} />
  </div>
  <button className='btn btn-gestup' disabled={isDisabled} onClick={() => { handleSubmit() }}>Confirmar</button>
  // ...
}

How do I show the user which person was selected?

https://stackblitz.com/edit/ionic-react-starter-bybk4x?file=pages%2FHome.js

I have a number of trips to different cities and each city is given its own card. On each card is a list of names of people that may have gone on that trip. I want the user to be able to click on a name to signify that that user went on the trip. Then I want the user to be able to see which user was selected. One approach I had is that below the list is text that says “selected: and next to it I wanted to have the name of the person selected to go on that trip.

Am I just supposed to create a state hook for each trip? As this grows more trips will be added am I just supposed to iterate out new state hooks for each one? Is there another way to do this?

CORS error while fetch public API in vanilla Javascript

I’m trying to make a simple html/css/js application which is supposed to fetch data from a public API (which I don’t have access).

When trying to access directly from the browser, I’m able to retrieve the data. But when trying to use javascript to get the data, it returns a CORS error.

After researching a bit about CORS, I concluded it is because the server didn’t include a Access-Control-Allow-Origin in the response, and since it’s a public API, I can’t change that. I’ve already tried the http://cors-anywhere.herokuapp.com/, but whenever I change IP, I have to opt in. Also, have caught the 429 error several times.

I’ve seen a solution which involves node.js. However, it seems that I have to somehow start the node js from the page, as this app will later be converted to an apk, so I’m not sure how to make it work.

Here’s the use of Fetch, if it is any usefull:

fetch(url, {
    method: "GET",
    headers: { "Access-Control-Request-Headers": "Origin, X-Requested-With" },
  })
    .then((response) => {
      return response.json();
    })
    .then((response) => { <Processing data code> }

The Access-Control-Request-Headers is because sometimes the herokuapp threw a 400 error where it claim this header was missing. No imports or functions are affecting this fetch call.

How to create hierarchy of tags from SASB taxonomy to prepare XBRL document?

I have downloaded zip file from SASB wesbite and the file contains xsd and multiple XML files.

In the xsd file, there are xsd:element which are a denotion of a tag. But I have to build a hierarchy similar to the screenshot attachedSASB sample.

I am unable to find a relation between xsd:element. Is there a way to build the hierarchy or any Javascript CDN that I use to build the XBRL tag hierarchy.

Appreciate your help, please comment if additional details are required to provide some information.

Canvas does not render chart correctly

I´m using these libraries:

but when render the labels are cut.

enter image description here

I expected this:

enter image description here

`const ctx_new = document.getElementById(‘grafica_nueva’);
window.Chart.defaults.global.showTooltips = false;

        grafica_new =  new window.Chart(ctx_new, {
            type: 'outlabeledDoughnut',
            data: dataPage.dataGraph,
            options: {
                zoomOutPercentage: 70,
                plugins: {
                    outlabels: {
                        text: (val)=>{
                            let valor  = val.dataset.data[val.dataIndex];
                            if(parseFloat(valor).toFixed(2) > 0.0){
                    
                                const saldoName = dataPage.saldos.filter((v,i) => v.saldo === valor);
                                const total_saldo = dataPage.saldos.reduce((total, elemento) => total + elemento.saldo, 0);
                                const porcentaje = (valor * 100) / total_saldo;
                                return `${saldoName[0].plan}n$${nWithCommas(parseFloat(valor).toFixed(2))}n${parseFloat(porcentaje).toFixed(2)}%`
                            }else{
                                return ''
                            }
                            
                        },
                        color: 'white',
                        font: {
                            resizable: true,
                            minSize: 12,
                            maxSize: 18
                        },
                    },
                },
                tooltips: {
                    enabled: false // <-- this option disables tooltips
                  }
              }
        });`

hmac from pyhton to js – when payload isn’t empty signatures are different

in Comeet Hires API Overview, I have to verify https requests in the server.

code request sampe is provided in pyhton
https://developers.comeet.com/reference/hires-api-overview

when payload is empty ({}) – signatures are equal and initial connection approved

when i mark candidate as hired -> payload on req.body isn’t empty ofcourse -> but signatures are not equal and throws an error.

I’ve tried both only stringify the payload and then update and also stringify and buffer (as shown in code snippet) – both gave me different signature values.

assume secret key is correct the issue is only in the lines added

const payloadString = JSON.stringify(payload);
const hmac = crypto.createHmac('sha256', secretKey);
hmac.update(Buffer.from(payloadString, 'utf-8'));
const generatedSignature = `sha256 ${hmac.digest('hex')}`;

if (generatedSignature !== signature) {
  throw new ApiError(httpStatus.FORBIDDEN, 'Signatures do not match!');
}

Calling a Javascript function from consecutive input fields [closed]

I have a javascript function that I need to call from an onBlur event for four consecutive input fields. On leaving the first field, the funnction is called OK but it’s not called on leaving the next field. It is called on leaving the third field but not on leaving the fourth.

When I put another field between the first and second, the function was called on leaving the second (now the third). Is there something I can put in the function to allow it to be called from consecutive onBlur events?

Creating a Qualtrics Survey with Sortable Table

I want to survey students on their course preferences using Qualtrics. I would like to have a table containing all the course information, and I want to allow students to sort the table according to different column headers. The thing is that I want the Likert scale (radio buttons with ratings 1-7) to move along with the table. It should look something like this

Course Name Course Code Instructor Schedule Your Rating
Intro to Economics ECON101 Prof. X TueThu 10am Radio buttons go here
Advanced Economics ECON305 Prof. X TueThu 1pm Radio buttons go here
Statistics STAT101 Prof. Y MonWedFri 11am Radio buttons go here

I want students to be able to click on, say, Course Name, and have the classes sorted by this column header.

Is there any way to implement this?

I have extensively experimented with Qualtrics and its standard interface does not allow this.

Online forums suggest using JavaScript to implement this, but sortable tables only allow the table to be sorted without the radio buttons as well, which means that I will have to have the ratings interface separate from the table of all classes, which is undesirable.

aws polly speaking using vuejs

i want to make application for text to speech in vuejs using aws polly

here is my code

<template>
  <div>
    <textarea v-model="textToSpeak" rows="4" cols="50"></textarea>
    <button @click="synthesizeSpeech">Synthesize Speech</button>
    <audio ref="audioPlayer" controls></audio>
  </div>
</template>

<script>
import { Polly,SynthesizeSpeechCommand } from "@aws-sdk/client-polly";

export default {
  data() {
    return {
      textToSpeak: "hello world",
    };
  },
  methods: {
    async synthesizeSpeech() {
      const accessKeyId = "YOUR_ACCESS_KEY_ID";
      const secretAccessKey = "YOUR_SECRET_ACCESS_KEY";
      const region = "us-east-1";

      const pollyClient = new Polly({
        region: region ,
        credentials: {
          accessKeyId: accessKeyId ,
          secretAccessKey: secretAccessKey ,
        },
      });

      try {
        const response = await pollyClient.send(
          new SynthesizeSpeechCommand({
            OutputFormat: "mp3",
            Text: this.textToSpeak,
            VoiceId: "Joanna", // You can change the voice ID as per your preference
          })
        );

        const audioBlob = new Blob([response.AudioStream], { type: "audio/mpeg" });
        const audioUrl = URL.createObjectURL(audioBlob);
        

        if (this.$refs.audioPlayer.canPlayType(audioBlob.type)) {
          this.$refs.audioPlayer.src = audioUrl;
          this.$refs.audioPlayer.play();
        } else {
          console.error("Unsupported audio format");
        }

      } catch (error) {
        console.error("Error synthesizing speech:", error);
      }
    },
  },
};
</script>


its throw error : Uncaught (in promise) DOMException: Failed to load because no supported source was found.

How Can i fix this error or play audio in browser

How to properly make a session token verification on reload?

I’m building a website using the Next.js framework and I wanted to know if there is any way for me to stop the reload effect from entering the login page (happens on the fraction of a second) before going back to the main page.

Here is the current code I have for that page.

const Home: React.FC<any> = ({ jsonHydration, contextHydration }) => {
  const [isUserLoggedIn, setIsUserLoggedIn] = useState(false);
  const [cookies, setCookie] = useCookies(["session_key"]);
  const session_key = cookies.session_key;

  useEffect(() => {
    setIsUserLoggedIn(!!session_key)
  }, [session_key]);

  useEffect(() => {
    const unloadCallback = (event: { preventDefault: () => void; returnValue: string; }) => {
      event.preventDefault();
      event.returnValue = "";
      return "";
    };
    window.addEventListener("beforeunload", unloadCallback);
    return () => window.removeEventListener("beforeunload", unloadCallback);
  }, []);

  function handleLogin(session_key: number) {
    setCookie("session_key", session_key, { path: "/", maxAge: 3600 });
  }

  if (isUserLoggedIn) {
    return (
      <CookiesProvider>
          <JsonStoreProvider hydrationData={jsonHydration}>
            <StoresProvider hydrationData={contextHydration}>
              <MainLayout/>
            </StoresProvider>
          </JsonStoreProvider>
      </CookiesProvider>
    );
  } else {
    return (
      <CookiesProvider>
        <JsonStoreProvider hydrationData={jsonHydration}>
          <StoresProvider hydrationData={contextHydration}>
            <LoginPage onLogin={handleLogin} />
          </StoresProvider>
        </JsonStoreProvider>
      </CookiesProvider>
    )
  }
};

I’ve searched on some posts and this was the closest I could get to my initial objective of maintaining the user on the main page when login in with a valid session key. The way this is working now is basically entering both pages on reload, running once, entering the login page and then the useEffect() kicks in and updates de variables isUserLoggedIn to 1 so it goes to the main page. This not only makes a “fresh start”, ignoring what the stores had before, and also makes that login page micro second display. Any help?