How to return the correct position in an array in Javascript?

I need to make a function so that it will return the starting and ending index of the widest pasture as well as the width.

It needs to return an array in this particular order.

[length, starting_index, ending_index]

As an example, for "_-___-__-____-______-_", the return value should be [6, 14, 19].

If there are multiple pastures that have the same length, return the position of the pasture towards the end of the array.

As an example, for "_-___-__-___-", the return value should be [3, 9, 11].

If the widest pasture length is 0, such as "---", return 0 for all the values [0, 0, 0].

var widestPasture = function (landscape) {
  // Implement your code below
  let array = landscape.split("-");
  let greatest;
  let tillGreatest = 0;
  let endIndex;
  let answer = [];

  for (let i = 0; i < array.length; i++) {
    if (array[i + 1] !== undefined) {
      greatest = array[i].length;
    }
  }
  
  for (let i = 0; i < array.length; i++) {
    if (array[i].length < greatest) {
      tillGreatest += array[i].length;
    }
  }
  
  let startIndex = tillGreatest += 1;
  
  tillGreatest += 2;
  
  endIndex = tillGreatest + greatest -1;

  answer = [greatest, tillGreatest, endIndex];
  
  return answer;
};

console.log(widestPasture("_-___-__-____-______-_"));
// -> [6, 14, 19]
console.log(widestPasture("_-___-__-___-"));
// -> [3, 9, 11]

The issue I’m running into is figuring out how to output the [3, 9, 11]. Currently the second output is [3, 6, 8]. It feels like the solution is something simple right in my face but I can’t grasp it and all my other attempts have resulted is breaking the currently working code.

Is my only option rewriting from the beginning?

How do I solve laravel livewire “Uncaught (in promise) SyntaxError: Unexpected token ‘<', " reponce error on host?

I have a laravel livewire project work will on local but on cpanel i get js error say:

DevTools failed to load source map: Could not parse content for https://op-target.com/crm/dashboard/assets/node_modules/bootstrap/dist/js/bootstrap.min.js.map: Unexpected token '<', "

`<!DOCTYPE "... is not valid JSON
VM94:2 

Uncaught (in promise) SyntaxError: Unexpected token '<', "
<!DOCTYPE "... is not valid JSON
    at JSON.parse (<anonymous>)
    at index.js:58:58`

when click wire:click=”–“

I try remove vendor and composer install
I try php artisan serve
I try take a copy deployed in another server from year
I detect paths and databaseyour text

Nextjs dev server stops a few seconds after running

I work on next js application and i start my project by typed npx create-next-app myapp
nextjs server stops a few seconds after running
my app is created with:
node : 18.16.0
next: 13.4.3
os: windows 8.1 32
but when i type npm run dev, the development just running but not compiling anything and down
My terminal
i upgrade node and restart my computer
i used buble instead swc
i cleaned node_modules and reinstall them
i cleaned json-lock and reinstall it
So, is there any solution to run my next application on dev server?

what to use so that the values in an array from user input get stored as numbers not strings?

Trying to take user input in an array. The values stored in array have single quotation mark on them while using prompt(). what to use so that the values in the array are numbers.

Code:

function processData() {
var myArray=[];
var n=prompt("Enter size: ");
    for(var i=0;i<n;i++)
        {
            var t=prompt("Enter element " + (i+1)+": ");
            myArray.push(t);
        }
        return myArray;
}

var result=processData();
console.log(result);

Output:

[Here, array formed has values with quotation marks.]

node /tmp/UiQZRJhP05.js
Enter size: 4
Enter element 1: 2
Enter element 2: 4
Enter element 3: 6
Enter element 4: 5
[ '2', '4', '6', '5' ]

Django get id of the selected checkbox on CheckboxSelectMultiple widget in Javascript

I have checkboxes in Django from a form :

testrever = forms.MultipleChoiceField(required=False,widget=forms.widgets.CheckboxSelectMultiple())

I would like to return only the ID (and then the value) of the last selected checkbox on .change event only when it’s checked (when it’s unchecked I don’t want anything to happen).

I managed to do so with the following (thanks to this answer) :

Django How to get value of CheckboxSelectMultiple in Javascript in Template

$('#id_testrever_0').on("change", function() {
    var testrever =[]
    var a = $("#id_email").val();
    if ($('#id_testrever_0').is(':checked')) {
        testrever = $('#id_testrever_0').val();
        $("input[name=email]").val(a + testrever)
    }
})
    $('#id_testrever_1').on("change", function() {
    var testrever =[]
    var a = $("#id_email").val();
    if ($('#id_testrever_1').is(':checked')) {
        testrever = $('#id_testrever_1').val();
        $("input[name=email]").val(a + testrever)
    }
})

But I would like to achieve it in a more elegant way to minimise the code lenght and avoid the repetitions.

maybe by using

$("input:checkbox[name=testrever]").on("change", function() 

  $("input:checkbox[name=testrever]:checked").each(function()

if it’s possible.

amchart parse json object

How can I add extra data to the json object in AMchart?
When my obj is simple everything parses:
var data = [ {year: "1930",italy: 4,germany: 5.1,uk: 3}, {year: "1934",italy: 1,germany: 2,uk: 6}, {year: "1938",italy: 2,germany: 3,uk: 1} ];

But when it looks like this it does not:
var data = [ {year:"1930", italy:[{aa:20,bb:"21"}], germany:[{aa:30,bb:"44"}], uk:[{aa:40,bb:"77"}] } ];

This is the code that is responsible for parsing:

   var series = chart.series.push(
    am5xy.LineSeries.new(root, {
      name: name,
      xAxis: xAxis,
      yAxis: yAxis,
      valueYField: field, // << -- issue
      categoryXField: "year",
      tooltip: am5.Tooltip.new(root, {
        pointerOrientation: "horizontal",
        labelText: "[bold]{name}[/]n{categoryX}: {valueY}"
      })
    })
  );

I can get the correct values using this but when i enter the values and replace field above the code does not parse correct,

  if(chart.series._values[0]){
    var data1 = chart.series._values[0]._dataItems[0].dataContext;
    
    if(data1[field][0])
      var valY = data1[field][0].aa;
      
    //console.log( valY );
  }

here is my complete code:

am5.ready(function() {

var root = am5.Root.new("chartdiv");
root._logo.dispose();

root.setThemes([
  am5themes_Animated.new(root)
]);

var chart = root.container.children.push(
  am5xy.XYChart.new(root, {
    panX: true,
    panY: true,
    wheelX: "panX",
    wheelY: "zoomX",
    layout: root.verticalLayout,
    pinchZoomX:true
  })
);

// Add cursor
// https://www.amcharts.com/docs/v5/charts/xy-chart/cursor/
var cursor = chart.set("cursor", am5xy.XYCursor.new(root, {
  behavior: "none"
}));
cursor.lineY.set("visible", false);

// The data
var data = [    {year:"1930", italy:[{aa:20,bb:"21"}], germany:[{aa:30,bb:"44"}], uk:[{aa:40,bb:"77"}] } ];

/* var data = [ {year: "1930",italy: 4,germany: 5.1,uk: 3},
  {year: "1934",italy: 1,germany: 2,uk: 6},
  {year: "1938",italy: 2,germany: 3,uk: 1} ]; */

// Create axes
// https://www.amcharts.com/docs/v5/charts/xy-chart/axes/
var xRenderer = am5xy.AxisRendererX.new(root, {});
xRenderer.grid.template.set("location", 0.5);
xRenderer.labels.template.setAll({
  location: 0.5,
  multiLocation: 0.5
});

var xAxis = chart.xAxes.push(
  am5xy.CategoryAxis.new(root, {
    categoryField: "year",
    renderer: xRenderer,
    tooltip: am5.Tooltip.new(root, {})
  })
);

xAxis.data.setAll(data);

var yAxis = chart.yAxes.push(
  am5xy.ValueAxis.new(root, {
    maxPrecision: 1,
    renderer: am5xy.AxisRendererY.new(root, {
      inversed: false
    })
  })
);

function createSeries(name, field) { 

  if(chart.series._values[0]){
    var data1 = chart.series._values[0]._dataItems[0].dataContext;
    
    if(data1[field][0])
      var valY = data1[field][0].aa;
      
    //console.log( valY );
  }

  var series = chart.series.push(
    am5xy.LineSeries.new(root, {
      name: name,
      xAxis: xAxis,
      yAxis: yAxis,
      valueYField: field, // issue when replced with: valY
      categoryXField: "year",
      tooltip: am5.Tooltip.new(root, {
        pointerOrientation: "horizontal",
        labelText: "[bold]{name}[/]n{categoryX}: {valueY}"
      })
    })
  );
  
  series.bullets.push(function() {
    return am5.Bullet.new(root, {
      sprite: am5.Circle.new(root, {
        radius: 5,
        fill: series.get("fill")
      })
    });
  });


  series.set("setStateOnChildren", true);
  series.states.create("hover", {});

  series.mainContainer.set("setStateOnChildren", true);
  series.mainContainer.states.create("hover", {});

  series.strokes.template.states.create("hover", {
    strokeWidth: 4
  });

  series.data.setAll(data);
  series.show(1000);
}


createSeries("Italy", "italy");
createSeries("Germany", "germany");
createSeries("UK", "uk");


var legend = chart.children.push(
  am5.Legend.new(root, {
    centerX: am5.percent(90),
    x: am5.percent(90),
    centerY: am5.percent(105),
    y: am5.percent(105),
  })
);

// Make series change state when legend item is hovered
legend.itemContainers.template.states.create("hover", {});

legend.itemContainers.template.events.on("pointerover", function(e) {
  e.target.dataItem.dataContext.hover();
});
legend.itemContainers.template.events.on("pointerout", function(e) {
  e.target.dataItem.dataContext.unhover();
});

legend.data.setAll(chart.series.values);

chart.appear(1000, 100);

});

“react” was conflicted between “package.json PROBLEM

A morning my react code is well working but after running app on night it is showing error , i cannot find which type of error occur , and not found any type of solution ,help me for solving my error on react :

[eslint] Plugin enter image description here » eslint-config-react-app » D:LPWeb Development courseREact TutorialsReactlivecovidreportsnode_moduleseslint-config-react-appbase.js” and “BaseConfig » D:LPWeb Development courseReact TutorialsReactlivecovidreportsnode_moduleseslint-config-react-appbase.js”.

Can someone tell me why using one if condition works and the other doesn’t?

I’m a beginner and i need help understanding a method in javascript.

I want to know why using – if (mark.calcBMI > john.calcBMI) did not work, but using if (mark.bmi > john.bmi) did? i would think it should work because when i console.log both mark.calcBMI and john.calcBMI they both produce the correct BMI result so now its just a case of telling me which is higher.

So here is my first code, i created two objects and each object has a function that calculates the BMI of each person in the object. when i log it to the console it doesn’t look at the if statement and just goes straight to the else statement. No matter if i change Marks BMI result to calculate higher than Johns it still just goes to the else statement and doesn’t read the if condition. I have bolded the if condition which is basically saying to look at the results of each methods and work out which BMI calculation is greater. Attached is my console.log screen.

Here is my original code

const mark = {
    firstName: 'Mark',
    lastName: 'Miller',
    weight: 78,
    height: 1.69,
    calcBMI: function () {
        this.bmi = this.weight / (this.height * this.height);
        return this.bmi;
    },
}

console.log(mark.calcBMI());

const john = {
    firstName: 'John',
    lastName: 'Smith',
    weight: 92,
    height: 1.95,
    calcBMI: function () {
        this.bmi = this.weight / (this.height * this.height);
        return this.bmi;
    },
}


console.log(john.calcBMI());

if (**mark.calcBMI > john.calcBMI**) {
    console.log(`${mark.firstName} ${mark.lastName} (${mark.bmi}) is higher than John's`)
} else console.log(`${john.firstName} ${john.lastName} (${john.bmi}) is higher than Mark's`)type here

enter image description here

below code, I then changed it from mark.calcBMI to mark.bmi and it stated to look at my if statement and was giving the right result so i knew it works. below is the new code which is the exact same as above but the if condition changed, bolded.

const mark = {
    firstName: 'Mark',
    lastName: 'Miller',
    weight: 78,
    height: 1.69,
    calcBMI: function () {
        this.bmi = this.weight / (this.height * this.height);
        return this.bmi;
    },
}

console.log(mark.calcBMI());

const john = {
    firstName: 'John',
    lastName: 'Smith',
    weight: 92,
    height: 1.95,
    calcBMI: function () {
        this.bmi = this.weight / (this.height * this.height);
        return this.bmi;
    },
}


console.log(john.calcBMI());

if (**mark.bmi > john.bmi**) {
    console.log(`${mark.firstName} ${mark.lastName} (${mark.bmi}) is higher than John's`)
} else console.log(`${john.firstName} ${john.lastName} (${john.bmi}) is higher than Mark's`)type here

enter image description here

Help is hugely appreciated!

Multidimensional Arrays JavaScript Challenge

I’m doing a challenge on a website, as follows:

Complete the function createToDoList, so that the returned multidimensional array contains at least three tasks listed as nested arrays.

Step 1: Create the task sub-arrays.

The first element of each nested array should be a string describing the task.
The second element should be a number representing how long that task will take in minutes.

Step 2: Add the arrays to the toDoList.

Select an appropriate array method that will allow you to add to toDoList.

Here is what I have so far:

function createToDoList() {
    const toDoList = [];
    // Do not alter any code above here
    const tasks = [
        ['task 1', 45],
        ['task 2', 87],
        ['task 3', 83]
    ];

    toDoList.push(tasks);
    // Do not alter any code below here
    return toDoList;
}

Clearly I’m not understanding something here, I don’t know how to push the arrays into the variable (if that’s what it is asking me…), I really just don’t get it.

Thanks.

Image upload function not working Nodejs API

I am working with Nodejs/Expressjs, I am working with Rest API, I am creating Rest api with following format

const updateUser = async (req, res) => {
const firstparam = req.params.firstname;
const secondparam = req.params.secondname;
try {
        await User.functionName(firstparam,secondparam);

        return res.status(202).send({
            statusCode: 202,
        });
    } catch (err) {
        res.status(500).send({
            statusCode: 500,
        });
    }
};
module.exports = {
    updateUser,
    upload-avatar,
};

Above function is working fine but whenever i try to create function for image uploading then not working, giving me error “not defined”,Where i am wrong ?

app.post('/upload-avatar', upload.single('dataFile'), (req, res, next) => {
   const file = req.file;
   if (!file) {
      return res.status(400).send({ message: 'Please upload a file.' });
   }
   var sql = INSERT QUERY;
   var query = db.query(sql, function(err, result) {
       return res.send({ message: 'File is successfully.', file });
    });
});

send values of dynamic table to a flask app

sorry for this begginer question iam compeltly noob in JQuery i have a flask form thats contain a dynamic table i want to send values of the table to my backend its nearly done but i get values of secound td for etc if i enter the pizza in first td and enter 20 in secound td i get this in my back-end : { “” : “20”}
this is my html ( i cut most the flask form from my cod):

                    <div class="card-body">
                        <h1>New Cafe</h1>
                        <p class="text-muted">Add Your Cafe</p>

                        <form id="my-form" name="cafe" method="post" action=""
                              enctype="multipart/form-data">
                            {{ cafe_form.csrf_token }}
                            {{ ckeditor.load() }}
                            {{ ckeditor.config(name='about') }}
                            {{ cafe_form.name.label }}
                            <div class="input-group mb-3">
                                <span class="input-group-addon"></span>
                                {{ cafe_form.name(class="form-control") }}
                            </div>
                            <div id="data_container">
                                <div id="dynamic-fields">
                                    <table>
                                        <thead>
                                        <tr>
                                            <th>Menu item</th>
                                            <th>Menu item Price in USD $</th>
                                        </tr>
                                        </thead>
                                        <tbody class="p-4">
                                        <tr class="p-2">
                                            <td><input  type="text"></td>
                                            <td><input  type="text"></td>
                                        </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </form>
                        <div class="pt-2 pb-2">
                   <button id="submit-btn" class="btn btn-outline-primary px-4">Submit</button>
                            <button id="add_rows" class="btn btn-outline-dark">+</button>
                        </div>
                    </div>

and this is my js for adding extra rows :

$("#add_rows").click(function () {
    // each click on the `+` button adds a row to the table
    $("#data_container tbody").append(`<tr><td><input type="text"></td><td><input type="text"></td></tr>`);
});
$("#submit_rows").click(function () {
    // `obj` for storing the inputs, and the `n` to make unrepeated keys
    let obj = {}, n = 0;
    // loop over the rows
    $("#data_container tbody tr").each(function (ind, tr) {
        // add an array to the object
        obj[`r${n}`] = [];
        // loop over the inputs of this row
        $(this).find("input").each(function (ind, input) {
            // add the value of the input to the array and make sure to remove any semicolon since
            // we will use it to separate the inputs
            const val = input.value.replace(/;/g, "");
            obj[`r${n}`].push(val);
        });
        // no need for the array, just join it to a string of values separated by semicolons
        obj[`r${n}`] = obj[`r${n}`].join(";");
        // increase the value of `n`
        n++;
    });
    // log the object to the console so you can see what we are sending
    console.log(obj);
    // send the data to the server, see the console for a logging message for success
    $.post("", obj, (data, status) => console.log("Status: " + status));
});

and this is the part that i try to send the data to back-end:

    const weburl = "/owner-new-cafe";
    document.getElementById('submit-btn').addEventListener('click', function (event) {
        event.preventDefault();
        submitForm();
    });

    function submitForm() {
        // Collect static form data
        const formData = new FormData(document.getElementById('my-form'));

        // Collect dynamic form data
        const dynamicData = [];
        $('#dynamic-fields tbody tr').each(function () {
            const row = {};
            $(this).find('input').each(function (ind, input) {
                row[this.name] = this.value;
            });
            dynamicData.push(row);
        });

        // Add dynamic form data to FormData object
        formData.append('dynamicData', JSON.stringify(dynamicData));
        document.getElementById("test").innerHTML = formData;

        // Send form data to Flask app using AJAX
        $.ajax({
            url: weburl,
            method: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function (response) {
                // Handle response from Flask app
            },
            error: function (xhr) {
                // Handle error
            }
        });

    }

please dont give me just answer iam try to learn i want to know what is my mistakle and what is the best way for doing this thank you so much

How do you show multiple iframes when in full screen mode?

I am making a button which opens the browser to full screen mode. The content displayed in full screen mode are 5 iframe sources.

This is not a duplicate to this: “Full screen” <iframe>, this Full-screen iframe with a height of 100%, or this How to enable fullscreen in IFrame because it pertains to a single iframe being able to be shown in full screen.

The difference I’m attempting to accomplish is that I cannot open multiple, in this case 5 iframe sources, under 1 full screen.

Here’s my code:

JAVASCRIPT:

function toggleFullscreen() {
  var container = document.getElementById("fullscreen-container");
  var iframes = container.querySelectorAll(".fullscreen-iframe");

  if (!document.fullscreenElement) {
    if (container.requestFullscreen) {
      container.requestFullscreen();
    } else if (container.mozRequestFullScreen) {
      container.mozRequestFullScreen();
    } else if (container.webkitRequestFullscreen) {
      container.webkitRequestFullscreen();
    } else if (container.msRequestFullscreen) {
      container.msRequestFullscreen();
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    }
  }
}

document.addEventListener("fullscreenchange", function() {
  var container = document.getElementById("fullscreen-container");
  var iframes = container.querySelectorAll(".fullscreen-iframe");

  if (document.fullscreenElement) {
    container.style.display = "block";

    // Show iframes when already in full-screen mode
    iframes.forEach(function(iframe) {
      iframe.style.display = "block";
    });
  } else {
    container.style.display = "none";

    // Hide iframes when not in full-screen mode
    iframes.forEach(function(iframe) {
      iframe.style.display = "none";
    });
  }
});

CSS:

#fullscreen-container {
  display: none;
}

.fullscreen-iframe {
  position: fixed;
  top: 0;
  left: 0;
  width: 40%;
  height: 40%;
  border: none;
  display: none;
}

.fullscreen-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 10px;
}

.center-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

HTML:

<div class="center-wrapper">
  <button onclick="toggleFullscreen()">Toggle Fullscreen</button>
</div>
<div id="fullscreen-container">
  <div class="fullscreen-grid">
    <iframe class="fullscreen-iframe" src="https://bing.com"></iframe>
    <iframe class="fullscreen-iframe" src="https://bing.com"></iframe>
    <iframe class="fullscreen-iframe" src="https://bing.com"></iframe>
    <iframe class="fullscreen-iframe" src="https://bing.com"></iframe>
    <iframe class="fullscreen-iframe" src="https://bing.com"></iframe>
  </div>
</div>

A working JSFIDDLE code snippet is available.

As you can see from the https://jsfiddle.net/oh8x6pet/ when the “Toggle Fullscreen” button is clicked on, full screen mode is entered and only one iframe is showing.

The problem I’m running into is that all 5 iframe sources should be displayed when in full screen mode, however, only 1 iframe source shows.

Here’s an image of roughly how it should look: Multiple iframes

I’m just using bing.com as a filler, but various sources will take their spot.

How do you show multiple iframe sources when in full screen mode? Thank you for the guidance.

Why push router is not defined?

I’m expecting to toggle the nav items with vue-router. And even though I’ve instaled the dependecies and views in the router index file, the nav isn’t routing the clint and throws the error push is not defined.

https://stackblitz.com/edit/vue-fsg2l2?file=src%2Fcomponents%2FHeader.vue,src%2Frouter%2Findex.js

<template>
  <div class="container">
      <nav class="nav">
        <span class="nav__item" @click="toHome">Logo</span>
        <span class="nav__item" @click="toShopsView">Shops</span>
      </nav>
  </div>
</template>

<script>
export default {
  name: 'Header',
  methods: {
    toShopsView() {
      this.$router.push('/shops');
    },
    toHome() {
      this.$router.push('/');
    },
  },
};
</script>

python dict to json and sending to HTML using Flask

I need to print a big python dictionary in HTML with neat format to read using Flask.

Lets take this dict as example

a={'a':True, 'b':False}
a_json=json.dumps(a) # {"a": true, "b": false}
return render_template("index.html", a_json=a_json)

in html,

  <div class="w3-container">
      <pre id="dict"></pre>
  </div>

  <script>
    var data = {{a_json}}
    document.getElementById("dict").innerHTML = JSON.stringify(data, undefined, 2);
  </script>

This does not showing the data, when I checked the open the “view page source”, I seen the json data is different, and there are extra characters are available

like this,

page_source

When, I give the json data directly in the script tag, I got the dictionary visible in the web page.

How to make this json data visible in the web page (or)
How to make the dict visible in html in neat format?

Thanks

Extending the static class : Uncaught TypeError: Super expression must either be null or a function

I am confused with extended class and static.

There are two static classes Main1 Main2, both are extended from Base class.

And each has the variable val. Manin1.val and Main2.val should be different value independently.

These are my source code below.

class Base{
    static val;
    static initialize(x){
        this.val = x;
    }
}
class Main1 extends Base{
    static showVal(){
        return this.val;
    }
}

class Main2 extends Base{
    static showVal(){
        return this.val * 2
    }
}


var main1 = new Main1();
var main2 = new Main2();

main1.initialize(1);
main2.initialize(2);

console.log(main1.showVal());// should show 1
console.log(main2.showVal());// should show 4

Howeber this code shows the error like this below.

How can I solve this?

    Uncaught TypeError: Super expression must either be null or a function