How can I solve the error: Type ‘undefined’ is not assignable to type ‘File’

I am trying to make my variable of type File have the parameter undefined but I get the error: Type ‘undefined’ is not assignable to type ‘File’.

export class CreateProductoComponent implements OnInit {


  public producto:any = {};


  public file: File = undefined;
  
  
  constructor() { 

  }


  ngOnInit(): void {
    
  }

And when I want to use the variable in the method, I get an error saying that it cannot be undefined.

//Mètode obtenir imatge directe del input
  fileChangeEvent(event:any):void{
    //Validem imatge
    var file;

    if(event.target.files && event.target.files[0]){ //Validem si rebem imatge desde el input
      file = <File>event.target.files[0]; //Guardem l'arxiu en la variable file
      console.log(file);
    }else{  //Si no hi ha imatge
      iziToast.warning({
        title: 'ERROR',
        class: 'text-danger',
        color: 'red',
        position: 'topRight',
        message: 'No hay imágen'
      });
    }

    

    //Validem la mida de la imatge
    if(file.size <= 4000000){
      if(file.type ==){

      }
    }else{
      iziToast.warning({
        title: 'ERROR',
        class: 'text-danger',
        color: 'red',
        position: 'topRight',
        message: 'La imágen supera los 4MB'
      });
    }

  }

How to give secondary theme color to DatePicker

I am new to material UI and I was playing around with components but I got stuck in an issue.

<TextField type="email" name="email" id="email" label="Email" variant="outlined" color="secondary" required />

<DatePicker label="Basic date picker" />

Just like how I gave a color prop and variant prop to the TextField component, I want to give DatePicker the same props but the typescript gives me an error saying color doesn’t exist on this type. I opened the documentation. I found a slots prop but it didn’t help either. I can apply color via CSS but I wanna do things the right way. Using CSS will be redundant. Any idea how I cant solve this issue?

Link component in onClick func

im doing a website with antd and i want to do spa website. So, when user clicks on any btn in menu, the content would change. But i cant put my link component in onClick func. Code is there:

<Menu  theme="dark" defaultSelectedKeys={['9']} mode="inline" items={items} onClick={(item) => {
          if (item.key === '1'){
            console.log(1);
            //LINK THERE
          } 

        }}/>

I tried to put menu in link tag. it works, but its not what i wanted to.

Active class on re-injected html

I’m working on a booking web app. I’m trying to add “active” class on my buttons on click. The problem is that theses butons are re-injected when clicked so the JS is not reaching the buttons anymore.

The re-injection works with AJAX and renderview to get the availables dates and times without reloading the page.

I tried to aks Chat GPT for a clue on the situation and here is what I got

const buttons = document.querySelectorAll("#timeBtn");

buttons.forEach((button) => {
  const isButtonClicked = localStorage.getItem(button.id);

  if (isButtonClicked) {
    button.classList.add("active");
  }

  button.addEventListener("click", () => {

    button.classList.toggle("active");

    const isActive = button.classList.contains("active");
    localStorage.setItem(button.id, isActive ? "clicked" : "");
  });
});

Here is my twig

<h2 class="text-center">Midi</h2>

    <ul class="d-flex flex-wrap justify-content-center mx-auto mt-3 list-unstyled text-small">
        <div class="js-day" {% for index in time %} data-is-open="{{ index.isclosed ? 'false' : 'true' }}" {% endfor %}></div>


        {% for reservation in availableDateAm %}
            <li class="mx-1 my-1">
                <a class="btn btn-outline-secondary lexend" id="timeBtn">{{ reservation | date("H:i")}}</a>
            </li>
        {% endfor %}

    </ul>

    <hr class="mt-5">

    <h2 class="mt-1 text-center">Soir</h2>

    <ul class="d-flex flex-wrap justify-content-center mx-auto mt-3 list-unstyled text-small">
        {% for reservation in availableDatePm %}

            <li class="mx-1 mt-1 my-1">
                <a class="btn btn-dark lexend" id="timeBtn">{{ reservation | date("H:i")}}</a>
            </li>

        {% endfor %}
    </ul>

So this solution use local storage to keep the “clicked” information but it doesn’t work. The problem seems to come from the re-injection of the buttons when clicked.

Any clues?
Thanks!

How to make Open Graph edit based on providen data?

I am wondeing how can I get the same thing as youtube on my site.

In the link below you can see that we have ?v=idOfVideo attached to the URL of the page. When I post it on Discord or Twitter I will have the video and title shown. I want to do the same thing. To be able to change Oprn Graph properties based on something attached to the URL. I tried it with PHP and that didn’t end up well. Code was half cut and the other half was shown on the page.

https://www.youtube.com/watch?v=dQw4w9WgXcQ

Why doesn’t my code work to solve this problem?

I apologise if this is something very simple I am not seeing, but I have only been coding for 3 weeks or so now in my spare time so stumble onto these scenarios often.

So basically, I was attempting a challenge on codewars as follows:

Story

YouTube had a like and a dislike button, which allowed users to express their opinions about particular content. It was set up in such a way that you cannot like and dislike a video at the same time. There are two other interesting rules to be noted about the interface: Pressing a button, which is already active, will undo your press. If you press the like button after pressing the dislike button, the like button overwrites the previous “Dislike” state. The same is true for the other way round.

Task

Create a function that takes in a list of button inputs and returns the final state.

Examples

likeOrDislike([Dislike]) => Dislike
likeOrDislike([Like,Like]) => Nothing
likeOrDislike([Dislike,Like]) => Like
likeOrDislike([Like,Dislike,Dislike]) => Nothing

Notes

If no button is currently active, return Nothing.
If the list is empty, return Nothing

I was stuck trying mutliple different ways to solve it for a couple of hours before checking the solutions and found one very similar to mine, albeit with one difference.

My code is as follows:

function likeOrDislike(buttons) {

  let answer = 'Nothing'
  
  for (let i=0; i < buttons.length; i++){
    if (buttons[i] !== 'Nothing'){
      answer = buttons[i]
    }
  }
  return answer
}

Working solution below:



function likeOrDislike(buttons) {
  let state = 'Nothing';

  for (let i = 0; i < buttons.length; i++) {
    if (buttons[i] === state) {
      state = 'Nothing'
    } else {
      state = buttons[i]
    }
  }

  return state
}

So its pretty much the same method used to solve it, however I don’t understand why in the working solution, you have to declare the variable ‘state’ as ‘Nothing’ again when it’s already been declared outside the loop. I thought that I could just create one condition for if buttons[i] is not equal to ‘Nothing’ and then assumed it it would default to ‘Nothing’ in any other case since it was declared outside of the loop.

when using a checkbox i can not use javascript to uncheck the checkbox

when making a simple form for a small project to make a fake photography page i was atempting to add a checkbox form that can be unchecked when you press the submit button after reaserch on outher posts i was unable to find a fix for my problem any help?

<div>
    <fieldset>
    <legend>Appointment scheduling</legend>
    
    <p>Your Name: <p>
    <textarea name="story" rows="1" cols="50" id='output1'> </textarea>
    <p>Your Email: <p>
    <textarea name="story" rows="1" cols="50" id='output2'> </textarea>
    <p>date:</p>
    <input type="date" id="start" name="trip-start" value="2023-06-17" min="2018-01-01" max="2035-12-31">
    <br>

    <div>
      <input type="checkbox" id="checkbox" >
      <label>Regular photoshoot</label>
    </div>

    <div>
      <input type="checkbox" id="checkbox" >
      <label>Nature/Outdoors</label>
    </div>
    
    <div>
      <input type="checkbox" id="checkbox" >
      <label>Wedding</label>
    </div>
    
    <div>
      <input type="checkbox" id="checkbox" >
      <label>senior photoshoot</label>
    </div>
    
    <div>
      <input type="checkbox" id="checkbox" >
      <label>Family photoshoot</label>
    </div>
    
    <div>
      <input type="checkbox" id="checkbox">
      <label>Pets/Animals</label>
    </div>
    
    <button class="button button1" type="button" onclick="javascript:eraseText();">Submit</button>
</fieldset>
</div>

 <script>
        function eraseText() {
          document.getElementById("output1").value = "";
          document.getElementById("output2").value = "";

          const checkbox = document.getElementById("checkbox");
          checkbox.removeAttribute('checked');
        }
  </script>

use of jquery as seen on this page Remove attribute “checked” of checkbox did not change the function and did nothing to the code

Why does my shopify function crash when I try to return it’s data from a promise

I have this function to grab data from the shopify API:

async function getProductsMetaData () {
    const productsQuery = client.graphQLClient.query((root) => {
        root.addConnection('products', { args: { first: 250 } }, (product) => {
            product.add('title');
            product.add('tags');
        });
    });
    let result = await client.graphQLClient.send(productsQuery);

    let metaData = {};
    result.data.products.edges.forEach(p => {
        let product = p.node;
        metaData[product.id] = {
            tags: product.tags,
        };
    });
    return metaData;
}

this works just fine if i try to grab it after my server has started, like this:

shopify.getProductsMetaData().then((metaData) => console.log('metadata:',metaData)).catch(e=>console.error('error:',e));

but i dont want this function to be run with every single page load, I want it only to run the first time, and subsequent times it should just grab the data it fetched initially.

I thought this would be a perfect case for a promise:

let productsMetaData = new Promise(async (resolve, reject) => {
    try {
        resolve(await getProductsMetaData());
    } catch (e) {
        reject(e);
    }
});

I could then just do await productsMetaData and it would return the data immediately (or run the function if it’s the first time).

But that promise is giving me a weird hard to understand error:

ReferenceError: fetch is not defined
    at Client.fetcher (project/node_modules/shopify-buy/index.unoptimized.umd.js:1874:5)
    at Client.send (project/node_modules/shopify-buy/index.unoptimized.umd.js:2076:19)
    at getProductsMetaData (project/modules/node/shopify/shopify.js:42:42)
    at project/modules/node/shopify/shopify.js:57:17
    at new Promise (<anonymous>)
    at Object.<anonymous> (project/modules/node/shopify/shopify.js:55:24)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)
    at Function.Module._load (node:internal/modules/cjs/loader:839:12)
    at Module.require (node:internal/modules/cjs/loader:1028:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (project/projects/pixel-school/routes/pixel-school.js:3:17)
    at Module._compile (node:internal/modules/cjs/loader:1126:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1180:10)
    at Module.load (node:internal/modules/cjs/loader:1004:32)

The 3rd line in the trace is the file this is declared in, pointing the line let result = await client.graphQLClient.send(productsQuery);, which is weird, because that line works just fine when it’s run later.

What could possibly be causing this?

Regex replacing couples of symbols by HTML tags

I’m trying to build a regex to replace all the couples of symbols “$$” with some HTML tag, say, <someTag></someTag>.

I use this regular expression but it doesn’t cover all the cases:

$$(S[^*]+S)$$
'aaa $$123$$ c$ ddd'.replace(/$$(S[^*]+S)$$/g, '<a1>$1</a1>') // works

'aaa $$123$$ c$ $$ddd$$'.replace(/$$(S[^*]+S)$$/g, '<a1>$1</a1>') // doesn't work, should be 'aaa <a1>123</a1> c$ <a1>ddd</a1>'

console.log('aaa $$123$$ c$ ddd'.replace(/$$(S[^*]+S)$$/g, '<a1>$1</a1>')) // works

console.log('aaa $$123$$ c$ $$ddd$$'.replace(/$$(S[^*]+S)$$/g, '<a1>$1</a1>')) // doesn't work, should be 'aaa <a1>123</a1> c$ <a1>ddd</a1>'

eCharts how to set specific xAxis for specific series data

I have the following code:

option = {
  xAxis: {
    type: 'category',
  },
  yAxis: {},
  series: [
    {
      type: 'line',
      encode: {
        x: 0,
        y: 2
      }
    }
  ],
  dataset : {
    source: [[100, 50, 400], [200, 50, 300], [300, 100, 200]]
  }
};

Currently it looks like:

Lina chart with visible axis to change

In x axis I have the following values: 100, 200, 300 – as it is visible in the image.
Instead of having values (100, 200, 300) for x axis I want to have values for first position from dataset.source : 50, 50, 100

How to do it?

Display the price of a coin after selecting its name in select

I use slim-select in which you can select the name of the coin, how to display its price after selecting the name (the price is in the database, i can find it by the name that is selected in the select)How can i do it(maybe i shoud use Ajax but how
)?

My form with select

<%= form_with(model: @investment, local: true) do |f| %>
      <div class="">
        <p class="very-mb-sm text-center"> <%= f.label :coin_name %></p>
        <%= f.select :coin_name, Coin.pluck(:name), {include_blank: true},{data: {controller: 'slim',class:'my-slim-select'}}%>
      </div>
      <p class="very-mb-sm very-mt-sm text-center"> <%= f.label :shopping_price %></p>
      <p class="text-center "><%= f.text_field :shopping_price, class: 'form-text-field'%></p>

      <p class="very-mb-sm very-mt-sm text-center"> <%= f.label :invest %></p>
      <p class="text-center"><%= f.text_field :invest, class: 'form-text-field'%></p>
        
      <div class="div-center mt-btn">
        <%= f.submit '+', class: "text-20" %>
      </div>
<% end %>

Rock, Paper, Scissor – Trouble keeping score (browser console)

I’m doing an Odin Porject (Javascript Basic): Rock, Paper, Scissor only in the browser console and I’m having trouble keeping score. I’m still a beginner so excuse my messy code. I’ve tried adding another function to keep the score but it didn’t work either.

choices = ['rock', 'paper', 'scissors']
let playerScore = 0
let computerScore = 0

function getComputerChoice() {
    return choices[Math.floor(Math.random() * choices.length)]
}

function getPlayerChoice() {
    let input = prompt('Pick Rock, Paper, or Scissor?')
    input = input.toLowerCase()
    return (input)
}

function playRound(playerSelection, computerSelection) {
    if (playerSelection === 'paper' & computerSelection === 'scissors' || 
            playerSelection === 'scissors' & computerSelection === 'rock' || 
            playerSelection === 'rock' & computerSelection === 'paper') {
        computerScore++
        return `You lose! ${computerSelection} beats ${playerSelection}`
        
    } if (playerSelection === 'rock' & computerSelection === 'scissors' || 
            playerSelection === 'paper' & computerSelection === 'rock' || 
            playerSelection === 'scissors' & computerSelection === 'paper') {
        playerScore++
        return 'You win!'
    } else
        return `You win! ${playerSelection} beats ${computerSelection}`
    
}

function game() {
    for (let i = 1; i <= 5; i++) {
        const playerSelection = getPlayerChoice();
        const computerSelection = getComputerChoice();
        console.log(playRound(playerSelection, computerSelection));
    }

    if (playerScore > computerScore) {
        return 'You beat the computer! You are a genius'
    } else if (playerScore < computerScore) {
        return `You got beat by the computer. Practice your throws!`
    } else {
        return `You tied with the computer!`
    }  
}

game();

Advanced slider, which show width between two indicators

Yesterday I had an idea to help myself at work.
Image
What’s going on?
I have an input value and a number of thumbs.
Input: 1400
Thumbs: 5
Section lengths: 20, 50, 100, 110, 130, 150, 260, 320, 340, 360, 380, 400, 420, 450, 500
I want to move my thumbs (left and right) to use the widths above and their sum is 1400.

I have no idea how to do it. Maybe you can help? Thank you

I was trying modify range slider from example source. No effect.

How to submit a form inside a into the same

I have 2 <div> in my JSP 
<div id="searchCriteria">
// included one search criteria JSP with search button. 
</div>
<div id="searchResult">
// included search result jsp with <previous> <next> navigation links
</div>

Question : on click of previous & next navigation link, i want to submit the form available inside the div (#mainContent) to the same div itself without disturbing the other div

Any help ?

document.querySelector(‘#searchResult form’).submit() – tried this but it submits the form to the whole content. But i want the submit to happen only inside the searchResult div