MUI SparkLine Chart: How to remove the warning coming for xAxis value

I am using MUI to display 8 quarters of data as shown below,

import * as React from 'react';
import Stack from '@mui/material/Stack';
import Box from '@mui/material/Box';
import { SparkLineChart } from '@mui/x-charts/SparkLineChart';

export default function BasicSparkLineCustomization() {

  return (
    <Stack direction="column" sx={{ width: '100%' }}>
      <Stack direction="row" sx={{ width: '100%' }}>
        <Box sx={{ flexGrow: 1 }}>
          <SparkLineChart
            data={[10, 20, 15, 45, 44, 12, 55, 20]}
            xAxis={{
              scaleType: 'band',
              data: ['Q1', 'Q2', 'Q3', 'Q4', 'Q5', 'Q6', 'Q7', 'Q8'],
            }}
            height={50}
            width={150}
            showHighlight
            showTooltip
          />
        </Box>
      </Stack>
    </Stack>
  );
}

Whenever I hove my cursor on top of the chart showing the tooltip, I am getting this warning in my console.
enter image description here

https://stackblitz.com/run?file=Demo.js

I am not sure what am I doing wrong here.
Any help is much appreciated.

Thanks,

custom error messages for invalid form – js script uncaught typeError

I’m a newbie with javascript and have adapted a script from github to customise error messages on a 5-field form.

It worked in its original 3-field format, but now gets stuck with the error message:
Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’)
at form.js:20:19

I’ve followed a lot of advice on here, re. the script not waiting for the page to load (moving the script to just above the tag, moving the script to an external file, putting the link at the bottom of the page, adding async to the link), but nothing seems to work.

This is the script (I’m content that the html and field names are accurate):

const nameInput = document.querySelector('input[name="name"]');
const emailInput = document.querySelector('input[name="email"]');
const categoryInput = document.querySelector('input[name="category"]');
const messageInput = document.querySelector('input[name="message"]');
const privacyInput = document.querySelector('input[name="privacy"]');
const allInputs = [nameInput, emailInput, categoryInput, messageInput, privacyInput];


nameInput.addEventListener('invalid', function (event) {
  if (event.target.validity.valueMissing) {
    event.target.setCustomValidity('Remember to let us know your name');
    }
})

emailInput.addEventListener('invalid', function (event) {
  if (event.target.validity.valueMissing) {
    event.target.setCustomValidity('Remember to input a valid email address');
    }
})

categoryInput.addEventListener('invalid', function (event) {
  if (event.target.validity.valueMissing) {
    event.target.setCustomValidity('Remember to let us know what category your message falls into');
    }
})

messageInput.addEventListener('invalid', function (event) {
  if (event.target.validity.valueMissing) {
    event.target.setCustomValidity('Remember to ask your question');
    }
})
      
privacyInput.addEventListener('invalid', function (event) {
  if (event.target.validity.valueMissing) {
    event.target.setCustomValidity('Remember to confirm you are happy with our privacy policy');
    }
})      

allInputs.forEach(function (input) {
  input.addEventListener('change', function (event) {
    event.target.setCustomValidity('');
    })
})

how to configure webpack fullySpecified rule for a package in node_modules folder?

I have two javascript repos, one is “mpUtils”, a private npm repo, and the second one “main” that uses via npm the “mpUtils” repo.
In both, I am using .mjs as extension, and in both, I have a rule to set fullySpecified: false so in my imports I don’t need to put “.mjs” explicitly.
Both projects build well, but the problem is when “main” imports “mpUtils”, then I got the error:

BREAKING CHANGE: The request './iepModels/index' failed to resolve only because it was resolved as fully specified

How can I define in “main” project a rule that disables the fullySpecified flag but only in the node_modules/utils/index.mjs file?

I tried this in the “main” package.json, but is ignored:


  module: {
    rules: [
      // failed rule for the imported private package:
      {
        test: /.(js|mjs|jsx)$/,
        include: '/(node_modules/mpUtils)/', <-- this is where I need help
        resolve: {
          fullySpecified: false,
        },
      },
      {
        test: /.(js|mjs|jsx)$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env',
              {
                useBuiltIns: false, // alternative mode: 'entry', 'usage'
                targets: { browsers: 'last 2 versions, not IE 11, not dead' },
                loose: false,
              },
            ],
            '@babel/preset-react',
          ],
        },
        resolve: {
          fullySpecified: false, // disable the behaviour
        },
      },

Why my token (JWT) appears like undefined in React?

This is my first time implementing an authentication module, and I opted for JWT. The backend is functioning properly, and the access token is also working well. However, when I attempted to use the token on the client-side, it returned as undefined. I initially tried using cookies, but encountered the same problem, so I reverted to using LocalStorage.
I read in another question that if I don’t store it in a cookie, it’ll desappear, but is this true even in a SPA?

This is my code that make the request:

 static async login({ email, password }) {
    try {
      const response = await axios.post('http://api.com/api/authentication/login', {
        email,
        password,
      });

      const { token } = response.data;

      localStorage.setItem('token', token);

      axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;

      return response; 
    } catch (error) {
      throw new Error('Authentication error: ' + error.message);
    }
  }

And this is the client-side:

const Login = ({ onLogin }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const history = useHistory();  

  const handleTogglePassword = () => {
    setShowPassword(!showPassword);
  };

  const handleLogin = async () => {
    try {
      const response = await EntityClass.login({
        email,
        password,
      });
      console.log('Server response:', response);

      const { token } = response.data;

      localStorage.setItem('token', token);
      console.log('Login successful');
      onLogin();
      console.log('onLog');
      console.log('The token is:', localStorage.getItem('token'));
      history.push('/main'); 
    } catch (error) {
      console.error('Authentication error:', error);
    }
  };

Like I was saying, the request it’s good, the token and the credential validations are a prove. So I don’t know what I’m doing wrong or missing.

The console show this: enter image description here

Essentially, I intended to retain the token and utilize it until it expires, enabling me to make all necessary requests without any issues. Given that the token lasts for 24 hours, it provides ample time for the system’s daily activities, eliminating the need to request a refresh token.

Error: matching query does not exist (Django/Python/JS-RatingApp)

As a beginner, I’m working on a Django rating application. The uploaded pdf files get displayed on a rating site, where one can give two star-ratings. When there was only one rating option, everything worked fine. Now that I added the second one and changed some js code, none of them works anymore. pls help:)
my models:

from django.db import models
from django.core.validators import MaxValueValidator, MinValueValidator

class Rating(models.Model):
    file = models.FileField(upload_to='images/', null=True)
    relevanz = models.IntegerField(default=0,
        validators=[
            MaxValueValidator(6),
            MinValueValidator(0),
        ]
    )
    richtigkeit = models.IntegerField(default=0,
        validators=[
            MaxValueValidator(6),
            MinValueValidator(0),
        ]
    )

    def __str__(self):
        return str(self.pk)

my views:

from django.shortcuts import render
from .models import Rating
from django.http import JsonResponse

# Create your views here.

# def main_view(request):
#     obj = Rating.objects.filter(score=0).order_by("?").first()
#     context ={
#         'object': obj
#     }
#     return render(request, 'ratings/main.html', context)

def main_view(request):
    objs = Rating.objects.all()
    return render(request, 'ratings/main.html', {'objs':objs})


def rate_relevanz(request):
    if request.method == 'POST':
        el_id = request.POST.get('el_id')
        val = request.POST.get('val')
        print(val)
        obj = Rating.objects.get(id=el_id)
        obj.relevanz = val
        obj.save()
        return JsonResponse({'success':'true', 'relevanz': val}, safe=False)
    return JsonResponse({'success':'false'})

def rate_richtigkeit(request):
    if request.method == 'POST':
        el_id = request.POST.get('el_id')
        val = request.POST.get('val')
        print(val)
        obj = Rating.objects.get(id=el_id)
        obj.richtigkeit = val
        obj.save()
        return JsonResponse({'success':'true', 'richtigkeit': val}, safe=False)
    return JsonResponse({'success':'false'})

html:

{% extends "base_rate.html" %}

{% block title %}
rate 
{% endblock title %}

{% block content %}
    {% for obj in objs %}
        {% comment %} {% if object %} {% endcomment %}
        <div class="row">
            <div class="col text-center">
                <embed id="rate-view" src="{{ obj.file.url }}" width="100%" height="375" type="application/pdf">
                <a href="{% url 'main-view2' %}"></a>
            </div>
            <div class="col text-center">
                Relevanz
                <form class="rate-form" action="/rate-relevanz/" method="POST" id="rate-relevanz-{{obj.id}}">
                    {% csrf_token %}
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="first"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="second"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="third"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="fourth"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="fifth"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="sixth"></button>
                </form>
                <br>
                <div id="confirm-box-relevanz"></div> 
                Richtigkeit
                <form class="rate-form" action="/rate-richtigkeit/" method="POST" id="rate-richtigkeit-{{obj.id}}">
                    {% csrf_token %}
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="first"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="second"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="third"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="fourth"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="fifth"></button>
                    <button type="submit" class="fa fa-star fa-3x my-btn" id="sixth"></button>
                </form>
                <br>
                <div id="confirm-box-richtigkeit"></div>
            </div>
                
        </div>
        {% comment %} {% else %}
            <h1>No files to rate</h1>
        {% endif %} {% endcomment %}
    {% endfor %}  
    
{% endblock content %}

js:

// Get all the stars
const stars = document.querySelectorAll('.fa-star');

// Get both forms, confirm boxes, and CSRF tokens
const formRelevanz = document.querySelector('rate-relevanz-form');
const formQuality = document.querySelector('rate-richtigkeit-form');
const confirmBoxRelevanz = document.getElementById('confirm-box-relevanz');
const confirmBoxQuality = document.getElementById('confirm-box-richtigkeit');
const csrf = document.getElementsByName('csrfmiddlewaretoken');

// Function to handle star selection
const handleStarSelect = (size, children) => {
    for (let i = 0; i < children.length; i++) {
        if (i <= size) {
            children[i].classList.add('checked');
        } else {
            children[i].classList.remove('checked');
        }
    }
}

// Function to get numeric value of the selection
const getNumericValue = (stringValue) => {
    const mapping = {'first': 1, 'second': 2, 'third': 3, 'fourth': 4, 'fifth': 5, 'sixth': 6};
    return mapping[stringValue] || 0;
}

// Function to handle form submission
const handleSubmit = (event, form, confirmBox, url) => {
    event.preventDefault();
    const val = event.target.id;
    const val_num = getNumericValue(val);
    const id = form.id;

    $.ajax({
        type: 'POST',
        url: url ,
        data: {
            'csrfmiddlewaretoken': csrf[0].value,
            'el_id': id ,
            'val': val_num ,
        },
        success: function(response) {
            confirmBox.innerHTML = `<h1>Successfully rated with ${response.val}</h1>`;
        },
        error: function(error) {
            confirmBox.innerHTML = '<h1>Oops... something went wrong</h1>';
        }
    });
}

// Event listeners for star hover and click
stars.forEach(star => {
    star.addEventListener('mouseover', (event) => {
        const form = star.closest('form');
        handleStarSelect(getNumericValue(event.target.id) - 1, form.children);
    });

    star.addEventListener('click', (event) => {
        const form = star.closest('form');
        const confirmBox = form === formRelevanz ? confirmBoxRelevanz : confirmBoxRichtigkeit;
        const url = form === formRelevanz ? '/rate-relevanz/' : '/rate-richtigkeit/';
        handleSubmit(event, form, confirmBox, url);
    });
});

error output

The whole Traceback:
Environment:

Request Method: POST
Request URL: http://localhost:8000/rate-relevanz/

Django Version: 4.2.6
Python Version: 3.11.7
Installed Applications:
[‘django.contrib.admin’,
‘django.contrib.auth’,
‘django.contrib.contenttypes’,
‘django.contrib.sessions’,
‘django.contrib.messages’,
‘django.contrib.staticfiles’,
‘docs’,
‘ratings’]
Installed Middleware:
[‘django.middleware.security.SecurityMiddleware’,
‘django.contrib.sessions.middleware.SessionMiddleware’,
‘django.middleware.common.CommonMiddleware’,
‘django.middleware.csrf.CsrfViewMiddleware’,
‘django.contrib.auth.middleware.AuthenticationMiddleware’,
‘django.contrib.messages.middleware.MessageMiddleware’,
‘django.middleware.clickjacking.XFrameOptionsMiddleware’]

Traceback (most recent call last):
File “/usr/local/lib/python3.11/site-packages/django/core/handlers/exception.py”, line 55, in inner
response = get_response(request)
^^^^^^^^^^^^^^^^^^^^^
File “/usr/local/lib/python3.11/site-packages/django/core/handlers/base.py”, line 197, in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/code/ratings/views.py”, line 24, in rate_relevanz
obj = Rating.objects.get(id=el_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/usr/local/lib/python3.11/site-packages/django/db/models/manager.py”, line 87, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File “/usr/local/lib/python3.11/site-packages/django/db/models/query.py”, line 637, in get
raise self.model.DoesNotExist(
^

Exception Type: DoesNotExist at /rate-relevanz/
Exception Value: Rating matching query does not exist.

Is there a way to locate a value on textfield inside a PDF using AppleScript, Javascript or shell script on macOS?

I want to create a service for Finder that works like this:

I select multiple PDF files, that are invoices, and it sums the values of specific fields and gives me the total.

This is the PDF model with dummy data for your reference: https://ufile.io/ygqavvvf

I want the PDF to do two sums.

  1. Sums all values that are after the field called VALOR BASE in all PDFs, in the dummy case 271,86.

  2. Sums all values that are after the field called IVA : IVA - regime de isenção [art.o 53.o] ; in all PDFs, that in the dummy case is 0,00 but may contain a value. The name of this field may vary, but always start with IVA:. Note that the field uses commas as a decimal point.

  3. Present the two sums, separately.

My question is, how do I scan the PDF using AppleScript and look for these fields?

Is there a way to obtain a list of text fields, boxes or whatever and enumerate them in AppleScript, JavaScript, or Bash Script?

Trouble with aliasing in TypeScript

I’m currently doing a wrapper over CQL and faced trouble with renaming property keys i.e. aliasing. Here’s playground with all needed code and 3 cases: Playground

If possible, change only type part of code. ‘1’ is db connection client, so ‘as unknown as ***’ will be anyway in code.
Here`s a real code:

public async findByField(params?: {
    select?: SelectFields<T>[];
    where?: WhereFields<T>[];
    limit?: number;
  }): Promise<T[]> {
    const { select, where } = params || {};
    const query = this.queryFactory.createQuery(select, where);
    const result = await this.client.execute(query);
    return result.rows as T[];
  }

My best try was by creating this type

type SelectResult<
  T,
  S extends SelectFields<T>[],
> = S[number]['alias'] extends string
  ? { [K in S[number]['field'] as S[number]['alias']]: T[K] }
  : { [K in S[number]['field']]: T[K] };

But got stuck with results.

Arguments object not working on Underscore first type function

For an exercise, I have to reproduce the first function from the Underscore.js library.

The code I wrote passes all the tests, except “should work on an arguments object”.

I passed these tests:

  • should return an array with the first n elements of the array
  • should return an array with the first element if n is not a number, is zero, or
    negative
  • should return the entire array if n is > length
  • should return an empty array if array is not an array

I failed this test: should work on an arguments object

_.first = function (array, n) {
  let arr = [];
  if (!Array.isArray(array)) {
    return [];
  } else if (isNaN(n) || n == null || n <= 0) {
    return [array[0]];
  } else {
    for (let i = 0; i < n && i < array.length; i++) {
      arr.push(array[i]);
    }
  }
  return arr;
};

I would be happy to get some guidance to understand why I am failing to pass the arguments object test. Thanks!

Why including all products in cart list? [closed]

I watched some tutorial video and they will included all products in the cart list.
For example, assume we have 5 products in total and user added product2 and product4 to cart.The cart list will be,

let cart={"product1":0,"product2":2,"product3":0,"product4":1,"product5":0}

Why don’t only included the product(s) that user added to cart?

let cart={"product2":2,"product4":1}

What is the advantages of including all products? Thank you.

Cookie not persisting from external JS file? (but does on my other sites)

I have a website on say domain1.com
I have a JavaScript file I call from domain2.com

The JavaScript file creates a cookie but when I refresh the page, the cookie is not there.

This seems to work fine for all my other websites but for some reason domain1.com it just doesn’t persist.
Any idea what could be causing this? No errors in the dev tools.
Just that the cookie cant be retrieved when refreshing.

I just cant seem to replicate the problem with other domains calling the JS.
Could there be a setting on the domain thats preventing this somehow?

Im wondering if these headers that are present on domain1.com are causing the issue??
Cross-Origin-Embedder-Policy: require-corp

Cross-Origin-Opener-Policy: same-origin

Cross-Origin-Resource-Policy: same-origin

Thanks

Getting random wav from flask and exchange src in audio

basic situation:
Starting from a HTML page with 3 buttons for 3 different types of sounds (sound0 (e.g. denial sound), sound1 (e.g. approval sound), sound2(e.g. laughing)), i want on “page load” to POST the file type to the Flask server, which should dynamically search for an individual instance of this sound type and return this path (this behavior is currently hard coded, since first the communication should work). I can receive this url in javascript, however this returns (in javascript) in the error of “Failed to load resource: the server responded with a status of 404 (NOT FOUND)”. Actually on receiving the path, the audio source should be exchanged. After doing this for all 3 buttons, a playback loop (iterating over every 3 files) should be triggered by playing sound0. The files are currently on the server in app/static/soundfiles/SOME_DEEPER_PATH_TO_CERTAIN_WAV.wav.
I currently don´t understand, whats going wrong and i would be very happy to get help with this issue.
My code so far:

button_page.html: (located in app/templates/button_page.html)

<!DOCTYPE html>
<html>
<head>
    <style>

        .button-row {
            display: flex;
            justify-content: center;
            margin-top: 30px;

        }

        .question {
            font-weight: bold;
            font-size: 20px;
            margin-bottom: 10px;
            color: white; /* Set the text color to white */
        }

        .error{
            color: red;
            display: none;
            margin-top: 5px;
        }

        .end_button {
            position: relative;
            bottom: -80px;
            margin-bottom: 100px;
            left: 125%;
            transform: translateX(-50%);
        }

        .button {
          min-width: 150px;
              min-height: 50px;
              font-family: 'Nunito', sans-serif;
              font-size: 16px;
              text-transform: uppercase;
              letter-spacing: 1.3px;
              font-weight: 700;
              color: #313133;
              background: #E592F6;
              z-index: 2;
              background: linear-gradient(90deg, rgba(229,146,246,1) 0%, rgb(196, 119, 213) 100%);
              border: none;
              border-radius: 1000px;
              box-shadow: 12px 12px 24px rgba(229,146,246,.64);
              transition: all 0.3s ease-in-out 0s;
              cursor: pointer;
              outline: none;
              position: relative;
              padding: 10px;
        }

        .wrapper_loading{
            width:200px;
            height:60px;
            position: absolute;
            left:50%;
            margin-top: 150px;
            transform: translate(-50%, -50%);
            visibility: hidden;
        }
        .circle{
            width:20px;
            height:20px;
            position: absolute;
            border-radius: 50%;
            background-color: #E592F6;
            left:15%;
            transform-origin: 50%;
            animation: circle .5s alternate infinite ease;
        }

        @keyframes circle{
            0%{
                top:60px;
                height:5px;
                border-radius: 50px 50px 25px 25px;
                transform: scaleX(1.7);
            }
            40%{
                height:20px;
                border-radius: 50%;
                transform: scaleX(1);
            }
            100%{
                top:0%;
            }
        }
        .circle:nth-child(2){
            left:45%;
            animation-delay: .2s;
        }
        .circle:nth-child(3){
            left:auto;
            right:15%;
            animation-delay: .3s;
        }
        .shadow{
            width:20px;
            height:4px;
            border-radius: 50%;
            background-color: rgba(148, 98, 160, 0.5);
            position: absolute;
            top:62px;
            transform-origin: 50%;
            z-index: -1;
            left:15%;
            filter: blur(1px);
            animation: shadow .5s alternate infinite ease;
        }

        @keyframes shadow{
            0%{
                transform: scaleX(1.5);
            }
            40%{
                transform: scaleX(1);
                opacity: .7;
            }
            100%{
                transform: scaleX(.2);
                opacity: .4;
            }
        }
        .shadow:nth-child(4){
            left: 45%;
            animation-delay: .2s
        }
        .shadow:nth-child(5){
            left:auto;
            right:15%;
            animation-delay: .3s;
        }
        .wrapper_loading span{
            position: absolute;
            top:75px;
            bottom:75px;
            font-family: 'Nunito', sans-serif;
            font-size: 20px;
            letter-spacing: 12px;
            color: #E592F6;;
            left:15%;
        }

        .submit-wrapper {
          display: grid;
          grid-template-columns: repeat(10, 1fr);
          gap: 10px;
          grid-auto-rows: minmax(100px, auto);
        }

        .wrapper {
          display: grid;
          grid-template-columns: repeat(5, 1fr);
          gap: 10px;
          grid-auto-rows: minmax(100px, auto);
        }
    </style>
</head>
<body>

<audio id="voice0" onended="playVoice1()" onpause="stop_ring_0()">
</audio><audio id="voice1" onended="playVoice2()" onpause="stop_ring_1()"></audio>
<audio id="voice2" onended="playVoice1()" onpause="stop_ring_2()"></audio>

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="{{url_for('static', filename='js/js_tmp.js')}}"></script>

<div class="wrap">
    <hr class="top-hr">
    <div class="wrapper_loading" id="wrapper_loading_id">
        <div class="circle"></div>
        <div class="circle"></div>
        <div class="circle"></div>
        <div class="shadow"></div>
        <div class="shadow"></div>
        <div class="shadow"></div>
        <!-- <span class="synthesizing_loader_text">Loading</span> -->
    </div>
</div>
<div class="button-row" id="button-container"></div>
    <div class="button-row">
        <button id="button-id1" class="button" onclick="playSoundType1()">Sound Type1</button>
        <button id="button-id2" class="button" onclick="playSoundType2()">Sound Type2</button>
        <button id="button-id3" class="button" onclick="playSoundType3()">Sound Type3</button>
    </div>
<script>
        init_button_sounds();
</script>
</body>
</html>

js_tmp.js located in static/js/js_tmp.js:


function init_button_sounds() {

    init_button_sound("voice0")
    init_button_sound("voice1")
    init_button_sound("voice2")
    playSoundType1();
}


function init_button_sound(audio_id, rd) {
    var route = '/getaudio'.concat(audio_id.slice(-1))

    var rd = String(Date.now())
    $.post(route).done(
        function(response) {
        var audio_path=response['audioFilePath']
        var audio_element=document.getElementById(audio_id);

        // assemble source.src & attach to audio
        var source = document.createElement('source');
        source.src = audio_path;
        // Append the source to the audio element
        audio_element.appendChild(source);

        // Load the new audio source
        document.getElementById(audio_id).load();

        }
    ).fail(
        function() {
            alert("Something failed. Please load again.");
        }
    );
}




function playSoundType1(){
    stopAllVoices()
    playVoice0()
}

function playSoundType2(){
    stopAllVoices()
    playVoice1()
}


function playSoundType3(){
    stopAllVoices()
    playVoice2()
}


function stopAllVoices(){
    stop_ring_0()
    stop_ring_1()
    stop_ring_2()
    document.getElementById('voice0').pause();
    document.getElementById('voice1').pause();
    document.getElementById('voice2').pause();
}


function playVoice0(){
  document.getElementById('voice0').play();
  stop_ring_1()
  stop_ring_2()
  start_ring_0()
}

function playVoice2(){
  document.getElementById('voice2').play();
  stop_ring_1()
  stop_ring_0()
  start_ring_2()
}



function playVoice1(){
  document.getElementById('voice1').play();
  stop_ring_2()
  stop_ring_0()
  start_ring_1()
}

function stop_ring_0(){
  var styleElem = document.head.appendChild(document.createElement("style"));
  styleElem.innerHTML = "#button-id1::after{animation:None;display:None;}";
}

function stop_ring_1(){
  var styleElem = document.head.appendChild(document.createElement("style"));
  styleElem.innerHTML = "#button-id2::after{animation:None;display:None;}";
}



function stop_ring_2(){
  var styleElem = document.head.appendChild(document.createElement("style"));
  styleElem.innerHTML = "#button-id3::after{animation:None;display:None;}";
}


function start_ring_0(){
  var styleElem2 = document.head.appendChild(document.createElement("style"));
  styleElem2.innerHTML = "#button-id1::after{    animation:ring 1.5s infinite;display: block;}";
}

function start_ring_1(){
  var styleElem2 = document.head.appendChild(document.createElement("style"));
  styleElem2.innerHTML = "#button-id2::after{    animation:ring 1.5s infinite;display: block;}";
}

function start_ring_2(){
  var styleElem2 = document.head.appendChild(document.createElement("style"));
  styleElem2.innerHTML = "#button-id3::after{    animation:ring 1.5s infinite;display: block;}";
}

routes.py in app/routes.py

@app.route('/')
def button_page():
    return render_template('button_page.html')

from pathlib import Path
sound1_path=Path('sound_files\sound1\a.wav')
sound2_path=Path('sound_files\sound2\b.wav')
sound3_path=Path('sound_files\sound3\c.wav')
@app.route('/getaudio<string:id>', methods=['GET','POST'])
def getaudio(id):
    from flask import url_for

    id_str = id
    sound_path=None

    if id_str=='0':
        sound_path=sound1_path
    elif id_str=='1':
        sound_path=sound2_path
    elif id_str=='2':
        sound_path=sound3_path

    audio_url = url_for('static', filename=str(sound_path))
    return(jsonify({'audioFilePath': str(audio_url) }))


def create_app():
    from flask import Flask
    app = Flask(__name__)
    app.secret_key = "random"
    return app

if __name__=="__main__":
    app=create_app()
    app.run(debug=True)

I tried playing around with different separators and / and also cutting the / before the static prefix. I really don´t know, where the error comes from

all edge cases of Doubly linked list Insertion at a given position is not working in JS

I have created a Doubly linked list Insertion at a given position programme using javascript append at the beginning, middle, and end of the node, so here is the problem: all test cases are not working fine, like for input 3.
2 4 5
2 6 My output is 2 6 4 5 and the expected output is 2 4 5 6, so can you please rectify my mistake and modify that so all the edge cases will work fine here? head, pos, and data are the starting pointers. Pos means in which position you want to enter the new node, and data is new data. The code is given below.
Input:
LinkedList: 2<->4<->5
p = 2, x = 6
Output: 2 4 5 6
Explanation: p = 2, and x = 6. So, 6 is
inserted after p, i.e, at position 3

Input:
LinkedList: 1<->2<->3<->4
p = 0, x = 44
Output: 1 44 2 3 4
Explanation: p = 0, and x = 44 . So, 44
is inserted after p, i.e, at position 1

class Solution {
    addNode(head, pos, data) {
        const newHead = { data: data, prev: null, next: null }; 

        if (head === null) {
            return newHead; 
        }
        let temp = head;
        for (let i = 1; i < pos - 1 && temp.next !== null; i++) {
            temp = temp.next;
        }

        if (pos > 1 && temp === null) {
            return head;
        }

        newHead.next = temp.next;
        if (temp.next !== null) {
            temp.next.prev = newHead;
        }

        temp.next = newHead;
        newHead.prev = temp;

        return head;
    }
}

Can’t figure how to get Input from html and set it inside js var

I Can’t seem to figure what how to get Input from html and set it inside js var

this is the JS:

///Colors
var GlobalcolorRED = '0';
var GlobalcolorGREEN = '255';
var GlobalcolorBLUE = '255';

//Set Colors
function getVal() {
    const val = document.querySelector('input').value;
    GlobalcolorRED = val;
    alert(val);
}
//Globalcolor
var GlobalcolorRGB = 'rgb('.concat(GlobalcolorRED + ',' + GlobalcolorGREEN + ',' + GlobalcolorBLUE + ')');
//Subtract
function GetColorSub(C, Amount) {
    const Color = parseInt(C, 10);
    return ((Color - Amount).toString());
}
//BGcolor
var SubColor = 0;
var BGcolorRED = GetColorSub(GlobalcolorRED, SubColor);
var BGcolorGREEN = GetColorSub(GlobalcolorGREEN, SubColor);
var BGcolorBLUE = GetColorSub(GlobalcolorBLUE, SubColor);
var BGcolorRGB = 'rgb('.concat(BGcolorRED + ',' + BGcolorGREEN + ',' + BGcolorBLUE + ')');
//Textcolor
SubColor = 125;
var TextcolorRED = GetColorSub(GlobalcolorRED, SubColor);
var TextcolorGREEN = GetColorSub(GlobalcolorGREEN, SubColor);
var TextcolorBLUE = GetColorSub(GlobalcolorBLUE, SubColor);
var TextcolorRGB = 'rgb('.concat(TextcolorRED + ',' + TextcolorGREEN + ',' + TextcolorBLUE + ')');
//Apply
document.body.style.backgroundColor = BGcolorRGB;
document.getElementById("Text-Color").style.color = TextcolorRGB;

This is the HTML:

<!DOCTYPE html>
<link rel="stylesheet" href="MainStyle.css">
<head>
    <meta charset="utf-8" />
    <title>Home</title>
</head>
<body>
    <div class="Title" id="Text-Color">Projects / Games:</div>
    <input type="text" placeholder="Enter text" onblur="getVal()">
    <script src="Main.js"></script>
</body>

I don’t know why it won’t apply the value to GlobalcolorRED, I am a beginner so pls help me.

I tried to make color picker for website

jQuery count the number of dynamic add element

Refer to attached screenshot, the div with id ‘item’ were added by

$("#items").prepend(template); 

where template is the html of each div with id ‘item’, if I get $(‘#item’).length but it always return 1, does anyone know why? How can I get the correct number of item?

var num = $('#item').length;
alert(num);

enter image description here

Is there a way to ignore null values in Google Earth Engine?

I am attemting to create 2 NDVI charts for the time range 2000 – 2021 based on ANDSAT/LE07/C01/T1_ANNUAL_NDVI data as follows:

var startyear = 2000
var endyear = 2021
var wetland_study = 'Athlone';
var years = ee.List.sequence(startyear, endyear);

// Function to compute annual NDVI and print chart
var L7 = ee.ImageCollection("LANDSAT/LE07/C01/T1_ANNUAL_NDVI")
               .filterDate('2000-01-01', '2021-01-01')
               .select('NDVI');
               
var computeAndPrint = function(wetlands, title) {
  var annual_collection = ee.ImageCollection.fromImages(years.map(function (y) {
    var annual = L7.filter(ee.Filter.calendarRange(y, y, 'year'))
                          .mean().clip(wetlands);
    return annual.set('year', y);
  }));

  print(annual_collection);

  var meanNDVI = L7.reduce(ee.Reducer.mean());
  var final_study = meanNDVI.clip(wetlands);

  var colorizedVis = {
    min: 0.0,
    max: 1.0,
    palette: [
      'FFFFFF', 'CE7E45', 'DF923D', 'F1B555', 'FCD163', '99B718', '74A901', 
      '66A000', '529499', '3E8601', '207401', '056201', '004C00', '023B01', 
      '012E01', '011D01', '011301'
    ], 
  };

  Map.addLayer(final_study, colorizedVis, 'NDVI_' + title);

  var chart = ui.Chart.image.series({
    imageCollection: L7, 
    region: wetlands, 
    reducer: ee.Reducer.mean(), 
    scale: 30,
    xProperty: 'system:time_start'
  }).setOptions({
    title: 'NDVI yearly chart of ' + title, 
    vAxis: {
      title: 'NDVI value',
      gridlines: {count: 0},
      baselineColor: 'black'},
    hAxis: {
      title: 'year', 
      gridlines: {color: 'black', count: 0},
      baselineColor: 'black'
    },
    trendlines: {0: {color: '#aa3319', visibleInLegend: true}}, 
    series: {0: {color: '#161616'}}
  });

  print(chart);
};

// Add layer and center map for the first region
var wetlands1 = MONOVALE;
Map.addLayer(MONOVALE);
Map.centerObject(wetlands1, 15);
computeAndPrint(wetlands1, 'Monovale');

// Add layer and center map for the second region
var wetlands2 = ROI.filter(ee.Filter.eq('name', wetland_study));
Map.addLayer(wetlands2, {color: 'blue'}, wetland_study);
Map.centerObject(wetlands2, 15);
computeAndPrint(wetlands2, wetland_study);

Some of the chats will plot but others will display the errors:

No features contain non-null values of “system:time_start”.
No images in the collection intersect the specified regions.
**

I assume the error comes about from years with no data available but I would just like to parse over these and still display what data is available.
I attempted to achive this b filtering out the null_values as follows:

var startyear = 2000;
var endyear = 2023;
var wetland_study = 'Epworth';
var years = ee.List.sequence(startyear, endyear);

// Function to compute annual NDVI and print chart
var L7 = ee.ImageCollection("LANDSAT/LE07/C01/T1_ANNUAL_NDVI")
               .filterDate('2000-01-01', '2021-01-01')
               .select('NDVI');

var computeAndPrint = function(wetlands, title) {
  var validYears = [];

  years.getInfo().forEach(function (y) {
    var annual = L7.filter(ee.Filter.calendarRange(y, y, 'year'))
                   .mean().clip(wetlands);

    var hasData = annual.reduceRegion({
      reducer: ee.Reducer.count(),
      geometry: wetlands,
      scale: 30,
    }).values().get(0);

    if (hasData !== 0) {
      validYears.push(y);
    }
  });

  if (validYears.length > 0) {
    var chart = ui.Chart.image.series({
      imageCollection: L7.filterBounds(wetlands), 
      region: wetlands, 
      reducer: ee.Reducer.mean(), 
      scale: 30,
      xProperty: 'system:time_start',
    }).setOptions({
      title: 'NDVI yearly chart of ' + title, 
      vAxis: {
        title: 'NDVI value',
        gridlines: {count: 0},
        baselineColor: 'black'
      },
      hAxis: {
        title: 'year', 
        gridlines: {color: 'black', count: 0},
        baselineColor: 'black'
      },
      trendlines: {0: {color: '#aa3319', visibleInLegend: true}}, 
      series: {0: {color: '#161616'}}
    });

    print(chart);
  } else {
    print('No data available for ' + title);
  }
};

// Add layer and center map for the first region
var wetlands1 = MONOVALE;
Map.addLayer(MONOVALE);
Map.centerObject(wetlands1, 15);
computeAndPrint(wetlands1, 'Monovale');

// Add layer and center map for the second region
var wetlands2 = ROI.filter(ee.Filter.eq('Name', wetland_study));
Map.addLayer(wetlands2, {color: 'blue'}, wetland_study);
Map.centerObject(wetlands2, 15);
computeAndPrint(wetlands2, wetland_study);

Now I am receiving a slightly different error:

The image collection is empty.

Could there be no data available for any of the requested years?