Youtube API Update the image of a scheduled broadcast

Hello i’m using the youtube api insert method https://developers.google.com/youtube/v3/live/docs/liveBroadcasts/insert to post a new broadcast to Youtube but i want to change the default image youtube is inserting on the broadcast here is the image youtube is giving by default

When i change the ‘thumbnail’ property on the livebroadcast it does not work can somebody please tell me how? and what’s the difference between slate and thumbnail please?

Is it possible to run Jest in Azure function runtime?

This might be a case of ‘you’re using the wrong tools for the job’ but I’m going to shoot my question anyways, because this is what I have to work with for now.

So, here goes:

I have to make relatively small applications that periodically run as functions in an Azure environment. These applications perform tasks like fetching data from an API and storing that data on a SFTP server. When I create these applications I use a TDD approach with Jest.

I’d like to react to any problems proactively and solve them before the function runs are scheduled. If I run Jest locally I would notice any of these problems but I’d like to automate this proces. Therefor I’d like to know if it’s possible to run these tests from an Azure function and have Azure Warnings notify me when one these runs fail.

What have I tried?

  • Created new function folder “Jest_Function”
  • Added an always failing test in a separate file.
/main_functions_folder
    /jest_function
        - index.js
        - function.json
        - failingTest.test.js
  • added the following code to index.js:
const { exec } = require('child_process');

function checkTests() {
  return new Promise((resolve, reject) => {
    exec('npm run test failingTest.test.js', (error) => {
      if (error) reject(error);
      else resolve();
    });
  });
}

module.exports = async function (context) {
  try {
    await checkTests();
  } catch (err) {
    context.log('tests failed!');
    throw err;
  }
};

Transforming the function and running it in the terminal results in expected behaviour:

const { exec } = require('child_process');

function checkTests() {
  return new Promise((resolve, reject) => {
    exec('npm run test failingTest.test.js', (error) => {
      if (error) reject(error);
      else resolve();
    });
  });
}

async function myTest() {
  try {
    await checkTests();
  } catch (err) {
    console.log('tests failed!');
    throw err;
  }
}

myTest();
tests failed!
node:child_process:399
      ex = new Error('Command failed: ' + cmd + 'n' + stderr);
           ^

Error: Command failed: npm run test failingTest.test.js
FAIL jest_function/failingTest.test.js
  ✕ short test (3 ms)

  ● short test

    expect(received).toBe(expected) // Object.is equality

    Expected: 1
    Received: 0

      1 | test('short test', () => {
    > 2 |   expect(0).toBe(1);
        |             ^
      3 | });
      4 |

      at Object.<anonymous> (jest_function/failingTest.test.js:2:13)

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 total
Snapshots:   0 total
Time:        0.227 s, estimated 1 s
Ran all test suites matching /failingTest.test.js/i.

    at ChildProcess.exithandler (node:child_process:399:12)
    at ChildProcess.emit (node:events:520:28)
    at maybeClose (node:internal/child_process:1092:16)
    at Process.ChildProcess._handle.onexit (node:internal/child_process:302:5) {
  killed: false,
  code: 1,
  signal: null,
  cmd: 'npm run test failingTest.test.js'
}

Azure

I deployed the function in Azure and manualy ran it. This resulted in a failing function as I expected, but for the wrong reason. It displayed the following error message:

Result: Failure Exception: Error: Command failed: npm run test failingTest.test.js sh: 1: jest: Permission denied

I’m not really sure where to go from here, any help or advice will be appreciated!

Remove Specific HTML Component After Successful Response With JavaScript Fetch API

I have an image component where the user has the option to delete the component (basically the image). The deletion in the MySQL database is handled by PHP, and I use the javascript fetch() API on form submission so that no hard refresh happens on the page when this happens. All of this works OK.

The Problem

The issue I have is there will virtually always be multiple instances of the component in the form, so after the fetch happens I obviously only want to remove the specific component that is tied to its related delete button. To do this I understand I need to use the remove() method on the component/HTML.

Normally with events such as click I would use something like e.target.closest('.element').querySelector('.child-element') but the issue I have is I need to link the remove() method to the e.submitter event, because I only want to remove that specific component that is linked to its delete button, and I want to do this after getting a 200 response to show the deletion happened in the database.

In the javascript below, the specific button used on delete submission is referenced using e.submitter, but I guess I need to find a way of storing that as a variable that I can then use in the if(response.status === 200) {} line of code ?

JavaScript

const forms = document.querySelectorAll('.upload-form-js'),
uploadDetailsComponent = document.querySelectorAll('.upload-details-component')

// URL details
const myURL = new URL(window.location.href),
pagePath = myURL.pathname

if (forms) {
    forms.forEach((form) => {
        form.addEventListener('submit', function (e) {
            e.preventDefault();
            
            const formData = new FormData(this);
        
            if (e.submitter) {
                formData.set(e.submitter.name, e.submitter.value);
            }
        
            fetch(pagePath, {
                method: "post",
                body: formData
            })
                .then(function(response){
                return response.text(); // stops hard refresh of the page
            })
                .catch((e) => console.error(e));
        });

        if(response.status === 200) {

            // remove the specific component linked to the 'submit' event using the 'remove()' method

        }

    });
} // end of if (forms)

HTML There are multiple instances of the image component inside the form. In the HTML below I’ve just shown two instances

<section>
    <form class="upload-form-js" enctype="multipart/form-data" method="post">
        <div class="upload-details-component">
            <div class="image-wrapper">
                <img src="image.jpg" alt="image">
            </div>
            <button type="submit" name="delete" title="delete" value="12" class="dl-button">Delete</button>
            <input type="hidden" name="image-id" value="12">
        </div>
        <div class="upload-details-component">
            <div class="image-wrapper">
                <img src="image.jpg" alt="image">
            </div>
            <button type="submit" name="delete" title="delete" value="13" class="dl-button">Delete</button>
            <input type="hidden" name="image-id" value="13">
        </div>
    </form>
</section>

Calls to external APIs in sequence from Node.js

I’ve been struggling for a couple of weeks trying to find the best pattern to implement this, but didn’t end up with a proper solution.

I have a back-end written in Node.js, which is required to perform a sort of initialization to gather some data from external APIs, before it can work properly.

The calls to the external APIs must be performed sequentially, as the data result of one call is required by the next one.

Furthermore I have a couple of these sort of “calls pipeline” which can run independently, on separate “threads”.

The last complication is that I need all these calls pipelines to be finished before I can consider completed the initialization phase and I finally can start with the regular work for the back-end (i.e. exposing some APIs).

I have investigated several ways.

For sure, using synchronous calls is the first thing that comes to mind, but we all know it is strongly discouraged.
Also using async functions with await doesn’t seem to work to me.
Actually the .then() chain already implements a sort of pipeline, but still it’s not clear how to “wait until all the pipelines are finished”.
I tried with chain of .then() + Promise.allSettled(), but it didn’t work as expected (maybe the array of Promise you pass to this method must include all the Promises, even those you create inside each then()….).

I guess there should be some standard pattern / best practise to implement this, as to me it doesn’t seem to be so an uncommon scenario.

Any hint highly appreciated.

I’m using axios as library for the HTTP calls (GET and POST).

–Thomas

Event triggered when user Resets location services permission

I am thinking about using the navigator.geolocation.getCurrentPosition to store the latitude and longitude of a user, obviously after he has accepted to.

I thought about storing this on local storage so that whenever he opens the browser again he appears on that position.

However, I thought of the other case. What happens if he goes on Location and resets the permission, or decides not to share his location anymore. Is there any event or way I can see if he did that? Because if he did that I need to delete those stored keys and values of lat and long from Local storage.

Thanks.
enter image description here

Why this function results in false?

Really basic question here, I’m new to JS and I’m trying to show a test message on a test website but this code returns always as false no matter if I test(true) or test(false)

function test(myTest) {
  if (myTest) {
    showMessage("True");
  }
  showMessage("False");
}

I’ve tried executing with the following:

test();
test(true);
test(false);

They all give out false

Form needs to be submitted twice

I am trying to implement a super simple, super primitive authentication page for my website. The user sees just a single input field and a submit button. If the input matches the password (hashing remains to be added) the user is authenticated.

The problem is, however, that you always have to input the correct string and press the submit button twice. I don’t know why this is happening, and it is obviously quite annoying.

Is there any solution for this? All I’ve found is to use e.preventDefault(), which I am already using, but to no avail.

import { useState } from 'react'
import App from '../App'

export default function Password() {
  const [auth, setAuth] = useState(false)
  const [pass, setPass] = useState("")
  const secret = ""

  const handleChange = e => {
    setPass(e.target.value)
  }

  const handleSubmit = e => {
    e.preventDefault()
    e.nativeEvent.stopImmediatePropagation();
    if (pass === secret) {
      setAuth(true)
    }
  }

  if (auth) {
    return (
      <App/>
    )
  } else {
    return (
      <form onSubmit={handleSubmit}>
        <input style={{ border: "1px solid grey", borderRadius: "4px" }} type="text" value={pass} onChange={handleChange} />
        <input style={{ border: "1px solid grey", borderRadius: "4px" }} type="submit" value="submit" />
      </form>
    )
  }
  
}

about javascript callback example

a = [3, 1, 2];

function b(v1, v2) {
  console.log('c', v1, v2);
  return 0
};

a.sort(b);

console.log(a);

a result of this script is like this

c 31
c 12
[3, 1, 2]

my question is

  1. Why is the function b being called twice?

  2. And
    in the first log
    console.log(‘c’, v1, v2);

why the v1 value is the first array value of a. it’s “3”

also why v2 is the second array value of “a”

in the second log
console.log(‘c’, v1, v2);
Why are the 2nd and 3rd values of the array in v1, v2
the result is “c 1 2”

I can’t understand

React search filter not rerendering correctly on MY computer only?

This is really weird and my instructor is confused as well. I copied some code from my classmate — it worked fine on his computer. But it doesn’t work on mine.

The issue is with a search filter.

onChange={(e) => {
          if(!e.target.value) return setTransactions(allTrans)
          console.log(e.target.value)
          let search = transactions.filter((element) => {
            return element.description.includes(e.target.value)
          })
          if (search.length>0) setTransactions(search)
        }}

the stateful variable “transactions” is used here:

{transactions.map((transaction) => {
          return <Transaction key={transaction.id} transaction={transaction}/>
        })}

We figured out the issue is in the rerender. My instructor deleted this code and pasted it back in and that FIXED IT. But then it got messed up again when I edited something else (in a different file). And now I can’t fixed it.

What would be the reason identical React code works on my classmate’s computer but not mine?

Async Await with Mocha + Axios TrobuleShooting

we are using mocha + nodejs + axios

Below is the piece of code i have , they are all in different file.

File 1 : IT block

   it('Perform Post Payment Actions', function () {
    postPaymentController.triggerPostPaymentActions(params);
  });

File 2 : Controller

module.exports.triggerPostPaymentActions = function (params) {
  const actions = params.postAuthActionId.split('-');  // // 'PARTIALREFUND, 50, SUCCESS - PARTIALREFUND, 50, FAIL

  Object.entries(actions).forEach(([, action]) => {
    const actionAsArray = action.split(','); // 'PARTIALREFUND, 50, SUCCESS 

    switch (actionAsArray[0]) {. // PARTIALREFUND
      case 'PARTIALREFUND':
        paymentsPartialRefundApi.submitPaymentsPartialRefundApi(actionAsArray, params);
        break;
      default:
        break;
    }
  });
};

File 3: Acutal API Call using axios


module.exports.submitPaymentsPartialRefundApi = async function (actionDetails, params) {

  const postOptions = {
    url: partialRefundApiUri,
    method: 'POST',
    headers: restHeaders,
    data: params.partialRefundRequest,
  };

  try {
    const response = await axios(postOptions);
    params.partialRefundResponse = response.data;
    process.env.PARTIALREFUNDRESPONSE = JSON.stringify(params.partialRefundResponse);
  } catch (err) {
    process.env.ERRORCODE = err;
    process.env.SCRIPT_STATUS = 'failure';
    process.env.PARTIALREFUNDRESPONSE = 'Partial Refund request Failed';
    throw err;
  }



};

PROBLEM :

When the control is passed to submitPaymentsPartialRefundApi , then it builds the request for axios but rather than waiting for the axios call , it takes the control back to the switch case. my expectation was that since i am using async await it will execute and wait till the axios call is completed but rather than completing the call it returns the control back to the switch statement and from the switch it goes back to the IT block. so i have 2 problems.
1 Its not waiting for the axios call to end
2 Its not running switch twice in loop , its goes back to IT block and then comes back.

Solutions Tried :

I already tried using promises for this , with and without timeout but still it did not worked.
Any help on this is appreciated.

How do I make a button that, when clicked, displays data in node.js?

So I’ve created a button, along with a table that shows data from my database. However, I want that data to appear only when the button is clicked.enter image description here

`<button id="breakfast2">Breakfast</button>
 <table id="mealTableContainer2">
            <thead>
                <tr>
                    <th id="mealname">Meal Name</th>
                    <th id="mealcalories">Calories</th>
                    <th id="mealtype">Type of Meal</th>
                    
                </tr>
            </thead>

            <tbody id="mealContainer2"></tbody>
  </table>`

The only Javascript I currently have is for getting my database into that table, but I really only want it to appear when I click the breakfast button. I just can’t figure out how; if someone could explain it to me very simply, I’d be appreciate it a ton!

calculator does not work properly on mobile devices

I’ve been trying to solve this for hours and I can’t.

The problem is when you try to erase the numbers entered.

You have to first select the two fields and enter the dollar amount in the third field. Then enter a value in the first field.

On the computer it works normally, but on some cell phones it is not working properly.

On some iphone using safary in the latest version it works. Already on some android devices with Google no. I didn’t check the browser version, but I tried it on newer and older phones. Some new ones give a problem and some don’t, as well as old ones.

This code was not developed by me, it is a little old and uses a template language called Freemarker. Don’t care too much about this language, it’s used to get data from the form and insert it into the html code.

There’s a link for you to access and test. This page contains two calculators, it is the first one that is giving problems. I’ll post a print of it.

URL: https://www.smiles.com.br/p123kby0ocxqaelzcgszc9x6hsmwt59wbrftzbr5ovtgngq7cy
Print: enter image description here

Code:

<#assign
moduloSimulador = simulador_cobranded_separator
itemSimulador = moduloSimulador.getChild("item_simulador_separator").getSiblings()
>

<#list itemSimulador as cur_item>
<#assign
imagemItem = cur_item.getChild("imagem_item").getData()
textoImportanteItem = cur_item.getChild("texto_importante_item").getData()
>
 <div data-simulador-mod021 class="canta-mod021-simulador">
  <div>
      <div>
      <#if imagemItem?has_content>
        <img src="${imagemItem}" alt="Imagem Simulador" />
      </#if>
          
      </div>
      <div>
          <div class="content-input">
              <label for="lblSeg">Assinante Clube Smiles</label>
              <select data-mod021-assinante id="lblSeg">
                  <option value="">Escolha</option>
                  <option value="sim">Sim</option>
                  <option value="nao">Não</option>
              </select>
          </div>
      </div>
      <div>
          <div class="content-input">
              <label for="lblCart">Tipo de Cartão</label>
              <select data-mod021-cartao id="lblCart">
                  <option value="">Escolha</option>
                  <option value="infinite">Infinite</option>
                  <option value="platinum">Platinum</option>
                  <option value="gold">Gold</option>
                  <option value="inter">Inter</option>
              </select>
          </div>
      </div>
      <div class="break-sm"></div>
      <div>
          <div class="content-input rs">
              <label for="lblValorGasto">Valor gasto no cartão</label>
              <input value="0" min="1" maxlength="12" data-mod021-valor class="style2" type="text" id="lblValorGasto" placeholder="0" />
          </div>
      </div>
      <div>
          <div class="content-input">
              <label for="lblConversor">Conversor</label>
              <input data-mod021-conversor readonly class="style2" type="text" id="lblConversor" placeholder="0" />
          </div>
      </div>
      <div>
          <div class="content-input rs">
              <label for="lblDolar">Cotação do Dólar</label>
              <input value="0" min="1" maxlength="5" data-mod021-cotacao class="style2" type="text" id="lblDolar" placeholder="0" />
          </div>
      </div>
      <div class="sep">=</div>
      <div>
          <div class="content-input">
              <label for="lblAcumulo">Acúmulo</label>
              <input data-mod021-acumulo readonly class="style2" type="text" id="lblAcumulo" placeholder="0" />
          </div>
      </div>
  </div>
  <p class="p-jur">
      ${textoImportanteItem}
  </p>
</div>
</#list>


<script>
(function(window) {
  "use strict";

  let $items = document.querySelectorAll("[data-simulador-mod021]");
  if ($items.length > 0) {
    for (let a = 0; a < $items.length; a++) {
      engine($items[a]);
    }
  }

  function isValidKey(key) {
    if (
      (key >= 49 && key <= 57) ||
      (key >= 97 && key <= 105) ||
      key == 8 ||
      ((key == 48 || key == 96) &&
        milesInput.value !== '' &&
        milesInput.value !== '0')
    ) {
      return true;
    }
  }

  //mascara de valor
  function mascaraValor(valor) {
    valor = valor.toString().replace(/D/g, "");
    valor = valor.toString().replace(/(d)(d{9})$/, "$1.$2");
    valor = valor.toString().replace(/(d)(d{6})$/, "$1.$2");
    valor = valor.toString().replace(/(d)(d{3})$/, "$1.$2");
    return valor;
  }

  function getValorMoneyBr(valor) {
    let value = valor
      .toFixed(2)
      .toString()
      .split(".");
    let formatFirstPart = mascaraValor(value[0]);
    let formatSecondPart = "," + value[1];

    let formatedValue = formatFirstPart + formatSecondPart;
    return formatedValue.toString();
  }

  //mascara de mordas
  function moeda(v) {
    v = v.toString().replace(/D/g, ""); //permite digitar apenas números
    v = v.toString().replace(/[0-9]{12}/, "inválido"); //limita pra máximo 999.999.999,99
    //v = v.toString().replace(/(d{1})(d{8})$/, "$1.$2"); //coloca ponto antes dos últimos 8 digitos
    //v = v.toString().replace(/(d{1})(d{1,2})$/, "$1.$2"); //coloca ponto antes dos últimos 5 digitos
    v = v.toString().replace(/(d{1})(d{1,2})$/g, "$1,$2"); //coloca virgula antes dos últimos 2 digitos
    return v.toString();
  }

  //define o valor do conversor
  function changeConversor(c, a) {
    let valueConversor = "";
    let cartao = c.value;
    let assinante = a.value;

    if (cartao && assinante) {
      if (cartao === "infinite") {
        if (assinante === "sim") {
          valueConversor = 4;
        } else {
          valueConversor = 2.2;
        }
      } else if (cartao === "platinum") {
        if (assinante === "sim") {
          valueConversor = 3;
        } else {
          valueConversor = 2;
        }
      } else if (cartao === "gold") {
        if (assinante === "sim") {
          valueConversor = 2.5;
        } else {
          valueConversor = 1.5;
        }
      } else {
        if (assinante === "sim") {
          valueConversor = 2;
        } else {
          valueConversor = 1.35;
        }
      }

      return valueConversor;
    } else return "";
  }

  function engine(item) {
    let assinante = item.querySelector("[data-mod021-assinante]");
    let cartao = item.querySelector("[data-mod021-cartao]");
    let valor = item.querySelector("[data-mod021-valor]");
    let conversor = item.querySelector("[data-mod021-conversor]");
    let cotacao = item.querySelector("[data-mod021-cotacao]");
    let acumulo = item.querySelector("[data-mod021-acumulo]");
    let conversorValor = "";

    function calc() {
      let nValor = valor.value.toString().replace(/(D)/g, "");

      let nCotacao = moeda(cotacao.value);

      nCotacao = nCotacao.replace(",", ".");

      nCotacao = parseFloat(nCotacao);

      let nConversor = parseFloat(conversor.value.toString().replace(",", "."));

      if (nValor <= 0 || nCotacao <= 0) {
        valor.value = "";
        cotacao.value = "";
        acumulo.value = "";
      } else {
        let v = (nValor / nCotacao) * nConversor;
        // acumulo.value = getValorMoneyBr(v);
        acumulo.value = Math.round(v);
      }
    }

    valor.addEventListener("keyup", function(event) {
      if(!event.keyCode) return;

      let v = this.value;
      valor.value = mascaraValor(v);

      if (valor.value && conversor.value && cotacao.value) {
        calc();
      }
    });

    cotacao.addEventListener("keyup", function() {
      if(!(event.keyCode)) return;

      if (valor.value && conversor.value && cotacao.value) {
        calc();
      }
    });

    cotacao.addEventListener("keyup", function() {
      if(!event.keyCode) return;

      let v = this.value;
      cotacao.value = moeda(v);
    });

    //define valor conversor
    if (assinante && cartao) {
      cartao.addEventListener("change", function() {
        conversorValor = changeConversor(cartao, assinante);
        conversor.value = conversorValor.toString().replace(".", ",");

        valor.value = "";
        cotacao.value = "";
        acumulo.value = "";
      });

      assinante.addEventListener("change", function() {
        conversorValor = changeConversor(cartao, assinante);
        conversor.value = conversorValor.toString().replace(".", ",");

        valor.value = "";
        cotacao.value = "";
        acumulo.value = "";
      });
    }
  }
})(window);
</script>

How do I pass mapped props to a component using useState?

I have a shopping cart component that I’ve passed a useState prop to update the number of items within the shopping cart / the amount of money that the cart is worth:

import { data } from "./data";

export default function StoreItems({ addToCart, Total, setTotal }) {
  const addToTotal = (data) => {
    addToCart();
    setTotal(Total + data.price);
  };
  return (
          <Grid container spacing={3}>
            {data.map((data) => (
              <Grid item key={data.id} xs={12} sm={6} md={3}>
                <Card>
                  <CardMedia
                    image={data.image}
                  />
                  <CardActions>
                    <div>
                      <Button>Buy</Button>
                      <Button
                        size="small"
                        sx={{ marginLeft: "5px" }}
                        onClick={addToTotal}
                      >
                        Add to Cart
                      </Button>
                    </div>
                  </CardActions>
                </Card>
              </Grid>
            ))}
          </Grid>
  );
}

The Data is a JavaScript object that looks like:

export const data = [
  {
    id: 1,
    title: "item 1",
    content: `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam ac aliquam nunc. 
    Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.`,
    image: "https://source.unsplash.com/random/1",
    price: 5000,
  },
];

And the props are passed down from:

function Store() {
  const [cartCount, setCartCount] = useState(0);
  const [Total, setTotal] = useState(0);

  const addToCart = () => {
    setCartCount(cartCount + 1);
  };

  return (
    <>
      <div>
            <StoreItems
              Total={Total}
              setTotal={setTotal}
              addToCart={addToCart}
            />
      </div>
    </>
  );
}

export default Store;

Why is it that I am unable to add the price of data.price to the useState – Total object