198. House Robber leetcode problem with javascript

https://leetcode.com/problems/house-robber/

I was trying to solve this leetcode problem with this approach but it keeps adding the first index in evenNumHouse and oddNumHouse array twice.

var rob = function(nums) {
  let oddNumHouse = [];
  let evenNumHouse = [];
  let sumOddHouse = 0;
  let sumEvenHouse = 0;
  
  for(let i = 0; i < nums.length; i++){
    if(i % 2 === 0){
      evenNumHouse.push(nums[i]);
      console.log('evenNumHouse = [' + evenNumHouse + ']');
      for(let i = 0; i < evenNumHouse.length; i++){
        sumEvenHouse += evenNumHouse[i];
        console.log('sumEvenHouse is ' + sumEvenHouse);
      }
    } else {
      oddNumHouse.push(nums[i]);
      console.log('oddNumHouse = [' + oddNumHouse + ']');
      for(let i = 0; i < oddNumHouse.length; i++){
        sumOddHouse += oddNumHouse[i];
        console.log('sumOddHouse is ' + sumOddHouse);
      }
    }
  }
  let maxMoney = Math.max(sumEvenHouse, sumOddHouse);
  return maxMoney;
};

rob([1,2,3,1]);

and this is what I got in my terminal

evenNumHouse = [1]
sumEvenHouse is 1
oddNumHouse = [2]
sumOddHouse is 2
evenNumHouse = [1,3]
sumEvenHouse is 2
sumEvenHouse is 5
oddNumHouse = [2,1]
sumOddHouse is 4
sumOddHouse is 5

I plan was sumEvenHouse has to be 1 + 3 = 4 but this code works like this 1+1+3 = 5
and sumOddHouse is the same. It has to work like 2+1=3 but it works 2+2+1=5
Why does it add the first index twice?

How can I use Speech Recognition in Django on the client side?

I am writing an application in Django. There should be a field to fill in, which the user should be able to fill in by voice. He should see what he dictated and, if an error occurs, be able to fix it quickly.

I wrote an html file with a small script in js inside. Here are its contents:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>

    <input id="the_button" type="button" value="Click to Speak">
    <input id="the_form" type="text" name="q" size=80 >

    <script type="text/javascript">
        var SpeechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition
         || window.mozSpeechRecognition || window.msSpeechRecognition)();

        const the_button = document.getElementById("the_button");
        the_button.addEventListener('click', function(event) {
            SpeechRecognition.start();
        })

        SpeechRecognition.onresult = function(event){
            var the_text = event.results[0][0].transcript;
            document.getElementById('the_form').value = the_text;
        };

        SpeechRecognition.onend = function(){
            SpeechRecognition.stop();
        };
    </script>
</body>
</html>

This html file works fine when I open it in the browser. But when I integrate this file into my Django project in the developer console I get an error in the line:

var SpeechRecognition = new (window.SpeechRecognition || window.webkitSpeechRecognition
   || window.mozSpeechRecognition || window.msSpeechRecognition)();   

I installed SpeechRecognition modules in my Django project, it doesn’t seem to have anything to do with my problem.

I would be grateful for any advice on how I can use SpeechRecognition on the client side

Use RTKQuery to fetch data in chunks

I have this code, that allow to fetch data from API but the response take long time if I retrieve all data, so to avoid timeout, I need retrieve data in chunks using pagination, this is my code

getDataWithDetails: builder.query<Data[], {size?: number; number?: number}>({
        async queryFn(_arg, _queryApi, _extraOptions, fetchWithBQ) {
            const { size, number } = _arg;

            const isFetchingFirstPage = !size && !number;

            const pageSize = size || 20;
            const pageNumber = number || 1;

            let partialResult = await fetchWithBQ({
                url: `data/details/all?page%5Bnumber%5D=${pageNumber}&page%5Bsize%5D=${pageSize}`,
                method: "GET"
            });

            let partialData = partialResult.data as {data:[], meta:[]};

            if (partialData.data.length >= pageSize) {
                const nextPage = pageNumber + 1;
                _queryApi.dispatch({ size: pageSize, number: nextPage });
            }

            return partialData.data
                ? { data: partialData.data as Data[] }
                : { error: partialResult.error as unknown as FetchBaseQueryError }

        },
        providesTags: [{type: "Data", id: "dataList"}]
    })

But for unknown reason the dispatch is not working, can you help me?

File reader is replacing characters whose index is greater than 127 with question marks

I am trying to make a program that is able to read a UTF-8 encoded file containing characters with indexes from 0 to 255. I plan to have the program operate by having the user pick a file from their computer, and once the file is selected, the program reads its text contents. However, I am encountering a problem; the characters in the text content of the file that have an index greater than 127 seem to be getting replaced by question marks that look like this: �. Here is my code:

HTML:

<input type=file style=font-size:20px onchange="next(this)"></input>
<div id=data></div>

Javascript:

async function next(elem){
var content=await elem.files[0].text()
document.getElementById("data").innerText=content;
}

Please may you help me find a way to circumvent this issue?

Look up streaming links from ISRC

Basically, I’m looking to feed my website an ISRC number and then have it list as many possible streaming links on different services. I know that Link Fire and Linktree can do it.

So far I’ve found this post which details how to get it done for Apple music. But what about Spotify? Or Deezer? Or… Well, you get it. Is it a question of tediously finding dev kits for all of these websites or has someone come up with an automated way of finding a list of streaming links?

Many thanks.

How i get the previous url of a 301 response?

I has current problem:
urlA = “https://somethingA.me?someParams=somevalue123”
urlB = “https://somethingB.com”

When I access the urlA I am instantly redirected to the urlB. How do I do to get the origin URL? (the urlB)
When I try to use window.history there is nothing, document.referrer nothing too.
In-network tab of the browser in the document request type I can see the request made to urlA and redirect with 301 response.
There’s any way to get the origin URL? Please, any tips?

self invoking function loop vs. for loop performance and render blocking question

I am animating an element and when it reaches the bounds of the container it will stop. I am wondering if a self invoking function loop is better in performance or a for loop is better? Are they both render blocking or not? I am intending to use requestAnimationFrame in whichever I end up using, I just want to hear other’s input on which is better. Thanks.

Example of self invoking function loop:

(function loop_me(){
    //loop algorithm 
    ....
    //return null when element reach container bounds
    loop_me();
})();

vs.

for(i < elem.right; i < container.right; i++){
    //loop algorithm 
    ....
    //break when element reach container bounds
}

jquery pagination datable serializeArray only capture first 10 result

What I want to do is capture all the entries of my table, but with serializeArray I can only capture the first 10 that are pagination enabled, but I also want to capture the rest of the data

table_pedido = $("#view_pedido_nuevo").DataTable({
      processing: true,
      destroy: true,
      paging: true,
      lengthChange: true,
      searching: true,
      ordering: true,
      info: true,
      autoWidth: true,
      scrollX: true,
      scrollY: true,
      data: data,
      language: espanol,
      columns: [
        { data: "CODARTICULO", className: "text-center" },
        { data: "DESCRIPCION", className: "text-center" },
        {
          data: "CODARTICULO",
          render: function (data, type, datos, row) {
            return `<input type="number" value="0" class="form-control">
            <input type="text" value="${datos.CODARTICULO}" name="input_name_cod[]" class="form-control">
            <input type="text" value="${datos.DESCRIPCION}" name="input_name_des[]" class="form-control">
            `;
          },
        },
      ],
    });

button:

$("#btn_transferencia_grupo_enviar").on("click", function () {
let cod_articulo = $(
  "#view_pedido_nuevo tbody tr :input[name='input_name_cod[]']"
).serializeArray()});

consolo.log

    (10) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
0: {name: 'input_name_cod[]', value: '13532'}
1: {name: 'input_name_cod[]', value: '13533'}
2: {name: 'input_name_cod[]', value: '13534'}
3: {name: 'input_name_cod[]', value: '13537'}
4: {name: 'input_name_cod[]', value: '13538'}
5: {name: 'input_name_cod[]', value: '13539'}
6: {name: 'input_name_cod[]', value: '13541'}
7: {name: 'input_name_cod[]', value: '13543'}
8: {name: 'input_name_cod[]', value: '13544'}
9: {name: 'input_name_cod[]', value: '13545'}

But I’m missing the data on page 2 and 3

React: How can I refresh a select dropdown after an API Get call?

so I am trying to populate a select dropdown after making a GET call to my api. What I have so far displays a textbox and an empty drop down. After user enters in 4 numbers, the application makes a get call to my api (this part works and returns a list of carriers). I then want to populate the dropdown with those carriers. Currently, if I were to fill the carriers[] array with something like “PAAF”, “EXLA” the list would be populated, but I only want it to populate after the GET call updates the list of carriers.

import React from 'react';
import axios from 'axios';


export default class FetchCarrierList extends React.Component {

  state = {
    carriers: []
  }

  render() {

    function loadCarriers(url) {
      axios({
        method: "get",
        url: url
      }).then((response) => {
        let carriers = response.data;
        console.log(carriers);
      }).catch((response) => {
        console.log(response);
        alert('Error communicating with server');
      });
    }

    function getData(val) {
      let location = val.target.value;
      let baseUrl = "http://localhost:6012/carrierApi/" + location;
      if (location.length === 4) {
        loadCarriers(baseUrl);
      }
    }

    return <div className="editPro">
      <h1>Edit Pro Numbers</h1>
      <div id="carrierSelection">
        <input type="text" id="locationEntry" onChange={getData}></input>
        <select id="carrierDropDown">
          {this.state.carriers.map(option => <option key={option} value={option}>{option}</option>)}
        </select>
      </div>
    </div>
  }
}

Would appreciate any help! Thank you

How come returned inner functions reference the same outer function variable even when the outer function is fired multiple times?

I am trying to understand how this debounce function works:

const myInput = document.getElementById("myInput");

myInput.addEventListener(
    "keyup",
    debounce( helloWorld, 2000 )
);

function debounce( callback, delay ) {
    let timeout;
    return function() {
        clearTimeout( timeout );
        timeout = setTimeout( callback, delay );
    }
}

From my understanding, every time someone performs a “keyup” action, a new debounce function is fired and added to the call stack. Now it is my belief that each one of these debounce functions has its own independent notion of “timeout” which the inner function acts on. However, the actual case it seems is that when “keyup” is performed many times, multiple inner functions are returned that all seem to share a reference to the same “timeout” variable, which allows this function to work.

My question is, where does my understanding fall apart? When “keyup” is fired multiple times, is it true that there are multiple debounce functions going to the call stack? Or is it just one function with one timeout variable, but with multiple returned functions?

Javascript to reset mobile viewport zoom level

I have a site where mobile users often zoom in on photos which is very much intended. However, I have a need to reset the zoom when certain links are accessed or specific javascript events fire. Specifically targeting mobile Safari.

Please note:

  • Various solutions to read meta[name="viewport"] and then set its content are ignored by mobile Safari. Maybe that worked years ago, but it doesn’t now.

The best idea I’ve have so far that works for links is to point them all to a different domain (which does reset the viewport) and then have that domain instantly redirect back to my site. I’d pass the actual intended URL as a GET param. I tested it and it works, but sheesh. It also only helps for links, I want to be able to do it for javascript events where there is no navigation taking place.

How can I retrieve the result value from stripe.redirectToCheckout()?

I am trying to get the result value from
a stripe.redirectToCheckout(). It is said to return a Promise https://stripe.com/docs/js/checkout/redirect_to_checkout.
Here is the code that I thought would work but it doesn’t

    stripe.redirectToCheckout({
      lineItems: [
        {
          price: stripePrice,
          quantity: token,
        },
      ],
      mode: "payment",
      successUrl: someurl
      cancelUrl: someurl
    }).then(result => {
        if (result.error) {
            alert(result.error.message);
        }
    })

Excel Export with Table Formatting

I am working with export to excel in a React Application.
I am currently using XLSX package.

I have a requirement to export the excel in table formatting. XLSX doesnt have this feature. is there any other package I can use to export the data in excel which will be in table formatting.

By table format I mean,

enter image description here

Thank you

“this” not referring to global in non-strict Node.js

My question is pretty simple. In my non-strict mode Node.js file, the this keyword called in the global execution context is not referring to global. Instead, it resolves to undefined. I thought this only happens when strict-mode is turned on … what’s going on here?

  console.log(this === globalThis); //called in the global scope, resolves to false