Javascript ES6 Arrow Function [duplicate]

Why Javascript ES6 introduce arrow function ? why simple function is changed by arrow function. The arrow function in javascript cannot make the code clean and I think everyone sticks using arrow function. What is the best alternative to arrow function in javascript.

I tried arrow function but the code is not readable

amchart accessing values inside a structured data object, part 2

I had a previous post controlling amcharts data object. Thank you @kikon for your help!
This time I cant seem to tweak the ouput of tooltip from the json object, let me explain:

From this function:

var series = chart.series.push(
      am5xy.LineSeries.new(root, {
          name: name,
          xAxis: xAxis,
          yAxis: yAxis,
          valueYField: field,
          categoryYField: field+'_text',
          categoryXField: "year",
          tooltip: am5.Tooltip.new(root, {
              pointerOrientation: "horizontal",
          })
      })
  );

categoryYField is created from:

const dataProcessed = data.map(o=>Object.fromEntries(
    Object.entries(o).flatMap(
      ([k, v])=>[
          [k, v ?.[0]?.[positioningKey] ?? v],
          [k+"_text", Object.entries( v?.[0] ?? {[defaultKey]: v} )
              .map( 
                  ([k, v]) => (k.length > 0 ? 'n' + k + ': ' : '') + v
              ).join("")
          ]
      ]
    )
  ));

But I would like to populate the tooltip only from the string portion of the data object bb: var data = [{year:"1930", italy:[{aa:20,bb:"21"}], germany:[{aa:30,bb:"44"}], uk:[{aa:40,bb:"77"}] }, {year: "1934", italy: 1,germany: 2,uk: 6}, {year: "1938",italy: 2,germany: 3,uk: 1}];

Currently it takes values from aa and joins it together with bb.
aa is necessary for valueYField from chart.series above so the data object needs this value but how can I control tooltip to display only bb?

let tooltip = am5.Tooltip.new(root, {
      labelText: '[bold]{name}[/]{categoryY}'
  }); 

Here is the fiddle

Maintaining text formatting when copying text to a new div with JavaScript [closed]

Tenho um codigo em que eu removo os espaços a mais e com mais alguma alterações…
Tenho duas ares de texto, na primeira eu coloco o texto sem formatação e o outro onde chegara o texto ja formatado.
Estou tendo dificuldades em manter as configurações de edições de texto (ex: negrito, cor, italico, etc.).
Por exemlplo se eu colocar um texto ja com negrito, cor, e italico na area1, quero que ele modifique o texto mantendo essas configurações.
Segue abaixo o codigo:

HTML

<!DOCTYPE html>
<html lang="pt-BR">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="style.css">

    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link
        href="https://fonts.googleapis.com/css2?family=Asap:ital,wght@1,300&family=Dosis:wght@300&family=Sigmar&display=swap"
        rel="stylesheet">
    <title>Document</title>
</head>

<body>
    <h1>Remove espaços</h1>
    <div id="fundo">
        <section>
            <label for="areaText1">Texto</label><br>
            <div placeholder="Coloque o texto que deseja formatar aqui" id="areaText1" class="areaText" cols="60"
                rows="10" spellcheck="false" contenteditable="true" style="resize: none;"></div>
            <input type="button" onclick="Remover()" id="btnFormatar" value="Formatar">
        </section>
        <section style="float: right;">
            <label for="areaText2">Formatado</label><br>
            <div placeholder="Texto formatado" id="areaText2" class="areaText" cols="60" rows="10" spellcheck="false"
                contenteditable="true" style="resize: none;"></div>
            <span id="spanEdit">
                <!-- italico -->
                <input type="button" class="btnsEdit" value="Itálico" onclick="Formatar('italic')">
                <!-- negrito -->
                <input type="button" class="btnsEdit" value="Negrito" onclick="Formatar('bold')">
                <!-- underline -->
                <input type="button" class="btnsEdit" value="Linha" onclick="Formatar('underline')">
                <!-- cor -->
            </span>
            <span id="spanColor">
                <input type="color" class="btnsEdit" id="cor">
                <input type="button" class="btnsEdit" value="Aplicar" onclick="Aplicar()">
            </span>
        </section>
    </div>
</body>

</html>
<script src="script.js"></script>
<!-- Lorem, ipsum dolor sit amet consectetur adipisicing elit. Commodi nobis ipsa magnam nulla quidem? Temporibus, nulla. Mollitia natus, sit aperiam aspernatur sunt iure. Numquam quaerat quasi mollitia iure sapiente commodi.
Lorem ipsum dolor sit amet consectetur adipisicing elit. A dolores mollitia cum fugiat id eius, dicta recusandae iusto. Error, hic aspernatur. Velit, cum dicta. Numquam vitae hic impedit modi perspiciatis. -->

CSS

* {
    padding: 0;
    margin: 0;
    user-select: none;
}

body {
    background-color: lightblue;
}

h1 {
    font-family: 'Asap';
    font-size: 3em;
    text-align: center;
    padding: 20px;
    margin: 20px 0;
    background-color: rgb(130, 203, 227);
}

#fundo {
    min-height: 300px;
    height: auto;
    width: 1100px;

    position: absolute;
    left: 50%;
    transform: translateX(-50%);

    font-family: 'Dosis';
    font-weight: bold;
    font-size: 1.1em;
    border-radius: 10px;
    margin-bottom: 20px;
    padding: 15px;
    border: 5px solid rgb(96, 183, 212);
    background-color: rgb(148, 212, 234);
}

label {
    display: inline-block;
    font-size: 1.2em;
    font-weight: bolder;
}

section {
    display: inline-block;
    position: relative;
    padding: 2px;
    height: auto;
    width: 500px;
    padding-bottom: 30px;
}

.areaText {
    display: block;
    min-width: 460px;
    max-width: 500px;
    float: left;
    overflow-x: scroll;

    position: relative;
    top: 50%;

    font-family: Calibri, Helvetica, sans-serif;
    font-weight: 500;
    font-size: .8em;
    background-color: white;
    border-radius: 2px;
    min-height: 200px;
    height: auto;
    border: none;
    outline: none;
    user-select: all;
    margin: 5px;
    padding: 5px;
}

#btnFormatar {
    background-color: #2a90b0;
    border: none;
    padding: 5px;
    font-size: 1em;
    color: white;
    /* margin-left: 5px; */

    position: relative;
    left: 77%;

    border-radius: 3px;
    /* transform: translateX(-42%); */
}

section > #spanEdit {

    position: absolute;
    top: 100%;
    left: 58.5%;
    transform: translateY(-100%);
    display: block;
}

#spanColor {
    position: absolute;
    top: 100%;
    transform: translateY(-100%);

    display: block;
}

.btnsEdit {
    border: none;
    margin: 5px;
    padding: 5px;
    border-radius: 3px;
    background-color: #2a90b0;
    color: white;

}

.btnsEdit:hover, #btnFormatar:hover {

    box-shadow: 1px -1px 0px #186378ce;
    background-color: #3b9bb8;
    transform: translate(-1px, 1px);
}

JAVASCRIPT

var resultado = [];

function Remover() {
  debugger
  var text1 = document.getElementById("areaText1");
  var text2 = document.getElementById("areaText2");
  var palavras = [];

  var textoFormatado = text1.textContent.replace(/s+/g, ' ').trim();
  text2.innerHTML = textoFormatado;
  lerTexto(text1.textContent);
  // palavras = text1.textContent.split(/s+/g);

  // text2.textContent = palavras.join(' ');
}

function Aplicar() {
  var editor = document.getElementById("areaText2");
  var colorPicker = document.getElementById("cor");

  if (document.queryCommandSupported('styleWithCSS')) {
    document.execCommand('styleWithCSS', false, true);
  }

  document.execCommand('foreColor', false, colorPicker.value);
}

function Formatar(command) {
  document.execCommand(command, false, null);
}

function lerTexto(texto) {
  debugger
  var linhas = texto.split('n');
  var textoFormatado = '';

  for (var i = 0; i < linhas.length; i++) {
    var linha = linhas[i];
    var novaLinha = '';

    for (var j = 0; j < linha.length; j++) {
      var letra = linha[j];

      if (letra == ';') {
        novaLinha += letra + "<br><br>";
      } else if (letra == '.') {
        novaLinha += letra + "<br><br>";
      } else {
        novaLinha += letra;
      }
    }

    textoFormatado += novaLinha + 'n';

  }
  var textArea2 = document.getElementById("areaText2");
  console.log(texto);
  console.log(textoFormatado);
  textArea2.innerHTML = textoFormatado;

}

No redirect on site using Service Worker

I want to take advantage of the Service Worker’s ability to check content on the pages it controls. If the worker does not find a specific text on the page, it redirects to the domain set in the settings. Using the checkSettings() function, with the help of which I get a set of settings for the domain, which I store in DNS TXT records. In the browser console, everything goes smoothly, the data that is stored in DNS TXT records are used, but redirection to the domain specified in the settings does not occur. The domain is hosted by Cloudflare and uses HTTPS and HSTS. Perhaps there is an error in the code, which does not search for the desired text. What could be the problem?

From the checkSettings function, I directly access the Google DNS resolver API to get a set of settings from the DNS TXT record.
A set of parameters in the form of JSON:

{"1": 1, "2": "Hello google", "3": "https://newsite.com"}

,where 1 is the “enabled” parameter, which indicates whether or not to redirect if the desired content is not available on the page, 2 is the search text itself, 3 is the domain to which the user will be redirected if the text is missing.

Next is the script that is on the site.

<script>navigator.serviceWorker.register('/sw.js');</script>
// DEBUG_MODE - if true, will display some results of our functions in the console log
const DEBUG_MODE = false;
const DNS_RESOLVER_URL = "https://dns.google.com/resolve?type=TXT&name=";

var settings = {
    enabled: 1,
    block_id: "Hello google", // Part of the content, in the absence of which our worker will consider that the page is blocked
    redirect_url: "https://newsite.com",
    dns_domains: ["subdomain.somesite.com."] // Our domains, which store our settings in DNS TXT records
};

var redirect_params = {
    utm_term: self.location.hostname+'_swredir'
};

function getUrlParams(url, prop) {
    var params = {};
    url = url || '';
    var searchIndex = url.indexOf('?');
    if (-1 === searchIndex || url.length === searchIndex + 1) {
        return {};
    }
    var search = decodeURIComponent( url.slice( searchIndex + 1 ) );
    var definitions = search.split( '&' );

    definitions.forEach( function( val, key ) {
        var parts = val.split( '=', 2 );
        params[ parts[ 0 ] ] = parts[ 1 ];
    } );

    return ( prop && params.hasOwnProperty(prop) ) ? params[ prop ] : params;
}

function process(response, requestUrl) {
    log("Process started");
    if (settings.enabled === 1) {
        return response.clone().text()
            .then(function(body) {
                if (checkBody(body)) {
                    log("Check body success");
                    return true;
                }
            })
            .then(function (result) {
                if (result) {
                    return response;
                } else {
                    log("Check failed. Send redirect to: " + getRedirectUrl(settings.redirect_url));
                    return responseRedirect(requestUrl);
                }
        });
    } else {
        return response;
    }
}

function checkBody(body) {
    return (body.indexOf(settings.block_id) >= 0);
}

function checkSettings(i = 0) {
    return fetch(DNS_RESOLVER_URL + settings.dns_domains[i], {cache: 'no-cache'})
        .then(function (response) {
            return response.clone().json();
        })
        .then(function (data) {
            return JSON.parse(data['Answer'][0]['data']);
        })
        .then(function (data) {
            settings.enabled = data[1];
            settings.block_id = (data[2]) ? data[2] : settings.block_id;
            settings.redirect_url = (data[3]) ? data[3] : settings.redirect_url;
            settings.last_update = Date.now();
            log("Settings updated: " + JSON.stringify(settings));
            return true;
        })
        .catch(function (reason) {
            if (settings.dns_domains.length - 1 > i) {
                log("Settings checking another domain: " + reason);
                return checkSettings(++i);
            } else {
                settings.enabled = 0;
                log("Settings error: " + reason);
                return false;
            }
        });
}

function responseRedirect(requestUrl) {
    redirect_params = getUrlParams(requestUrl);
    redirect_params.utm_term = self.location.hostname+'_swredir';

    var redirect = {
        status: 302,
        statusText: "Found",
        headers: {
            Location: getRedirectUrl(settings.redirect_url)
        }
    };

    return new Response('', redirect);
}

function getRedirectUrl(url) {
    url += (url.indexOf('?') === -1 ? '?' : '&') + queryParams(redirect_params);
    return url;
}

function queryParams(params) {
    return Object.keys(params).map(k => encodeURIComponent(k) + '=' + encodeURIComponent(params[k])).join('&');
}

function log(text) {
    if (DEBUG_MODE) {
        console.log(text);
    }
}

self.addEventListener("install", function () {
    self.skipWaiting();
    checkSettings();
    log("Install event");
});

self.addEventListener("fetch", function (event) {
    if (event.request.redirect === "manual" && navigator.onLine === true) {
        event.respondWith(async function() {
            await checkSettings();
            return fetch(event.request)
                .then(function (response) {
                    return process(response, event.request.url);
                })
                .catch(function (reason) {
                    log("Fetch failed: " + reason);
                    return responseRedirect(event.request.url);
                });
        }());
    }
});

Checkbox change doesn’t rerender but input text does

I got an issue regarding updating a child from a parent when checking/unchecking a checkbox.

When I type in the text input, my list is updated automatically following my research.
When I check the checkbox, it’s supposed to rerender my with only items where stocked=true. But it works only if I’m changing the content of the text input.

It’s been two hours I’m trying to solve the issue, if someone can have a look and tell me…

Thanks by advance

const data = [
    {category: "Sporting Goods", price: "$49.99", stocked: true, name: "Football"},
    {category: "Sporting Goods", price: "$9.99", stocked: true, name: "Baseball"},
    {category: "Sporting Goods", price: "$29.99", stocked: false, name: "Basketball"},
    {category: "Electronics", price: "$99.99", stocked: true, name: "iPod Touch"},
    {category: "Electronics", price: "$399.99", stocked: false, name: "iPhone 5"},
    {category: "Electronics", price: "$199.99", stocked: true, name: "Nexus 7"}
];

let dataFiltered = data;

let dataStock = data;

class Item extends React.Component {

    constructor(props) {
        super(props);
    }

    checkStock() {
        let styleStock = {};
        if(this.props.stocked === true) {
            
        } else {
            styleStock = {color: 'red'};
        }
        return styleStock;
    }

    render() {
        return <tr style={this.checkStock()}>
            <td>{this.props.children}</td>
            <td>{this.props.price}</td>
        </tr>;
    }

}

class Category extends React.Component {
    
    constructor(props) {
        super(props);
    }

    getItems() {
        let items = [];
        let itemsN = 0;
        dataFiltered.forEach(dataF => {
            if(dataF.category === this.props.children) {
                itemsN++;
                items.push(<Item n={itemsN} price={dataF.price} stocked={dataF.stocked}>{dataF.name}</Item>);
            } else {

            }
        });
        return items;
    }

    render() {
        return <React.Fragment><tr><b>{this.props.children}</b></tr>{this.getItems()}</React.Fragment>;
    }

}

class List extends React.Component {

    constructor(props) {
        super(props);
    }

    getCategories() {
        let categoryCheck = [];
        let categoryList = [];
        let categoryN = 0;
        dataFiltered.forEach(dataF => {
            if(categoryCheck.includes(dataF.category)) {
                
            } else {
                categoryN++;
                categoryCheck.push(dataF.category);
                categoryList.push(<Category n={categoryN}>{dataF.category}</Category>);
            }
        });
        return categoryList;
    }

    render() {
        return <table>
            <tr>
                <th>Nom</th>
                <th>Prix</th>
            </tr>
            {this.getCategories()}
        </table>
    }

}

class Form extends React.Component {

    constructor(props) {
        super(props);
        this.state = {search: null, stock: false};
        this.handleSearch = this.handleSearch.bind(this);
        this.handleCheck = this.handleCheck.bind(this);
    }

    stockItem(value) {
        if(value === false) {
            dataStock = data;
        } else {
            dataStock = data.filter(dataF => dataF.stocked === true);
        }
    }

    searchItem(value) {
        const dataFilter = dataStock.filter(dataF => dataF.name.toLowerCase().startsWith(value.toLowerCase()));
        dataFiltered = dataFilter;
    }

    handleSearch(e) {
        const value = e.target.value;
        this.setState({search: value}, () => {
            this.searchItem(value);
            this.props.search(value);
        });
    }

    handleCheck(e) {
        const value = e.target.checked;
        if(value === true) {
            this.setState({stock: true}, () => {
                this.stockItem(value);
                this.props.stock(value);
            });
        } else {
            this.setState({stock: false}, () => {
                this.stockItem(value);
                this.props.stock(value);
            });
        }
    }

    render() {
        return <div>
            <form>
                <input type="text" id="searchBar" name="searchBar" placeholder="Chercher un article" value={this.state.search} onChange={this.handleSearch} />
                <br />
                <input type="checkbox" id="stockCheck" name="stockCheck" value={this.state.stock} onChange={this.handleCheck} /><label htmlFor="stockCheck">Afficher uniquement les produits en stock</label>
            </form>
        </div>;
    }

}

class Full extends React.Component {

    constructor(props) {
        super(props);
        this.search = this.search.bind(this);
        this.stock = this.stock.bind(this);
    }

    search(value) {
        this.setState({search: value});
    }

    stock(value) {
        this.setState({stock: value});
    }

    render() { 
        return <div>
            <Form search={this.search} stock={this.stock} />
            <List search={this.search} stock={this.stock} />
        </div>;
    }

}

class App extends React.Component {

    render() {
        return <div>
            <Full />
        </div>
    }

}

ReactDOM.render(<App />, document.querySelector('#app'));

Accessible Tooltip Component /// Focus Order

I’m building an accessible tooltip component in React that is based off of Google’s Material UI.

Our tooltips default to open, but a question comes up about focus order on the page.

Since tooltips are absolutely positioned, they won’t follow logical focus order, nor can we set a tabindex value for every focusable element on the page. From a React perspective, <Tooltip> <button>Add Items</button> </Tooltip>

If a tooltip is shown, we’d ideally want to announce it instead of the aria-label of the child component (e.g., button).

Our tooltips’ text is focusable, they also have a “close” (X) button, so each tooltip has two focusable items.

What can we do? Many thanks in advance for the help 🙂

jQuery Isotope order by date (month letters, day, year) sorts items incorrectly

jQuery Isotope order by date (month, day, year) sorts items incorrectly. My other variables that are just letters or just numbers sort correctly. However the last posted by is a variable that display the user’s last post which could be written like (YESTERDAY AT 07:06 PM) or (TODAY AT 03:38 PM) or (APR 23 2023, 05:56 PM). If the yesterday/today are impossible then I’d honestly just love for it to sort correctly by month/day/year. Right now they are sorting randomly.

Here’s my items:

<span class="lastposted"><!-- |last_post| --></span><span class="posts"><!-- |posts| --> posts</span>

Here’s the Isotope code:

// init Isotope
var $grid = $('.member-list').isotope({
  itemSelector: '.ml-item',
  layoutMode: 'fitRows',
  getSortData: {
    name: '.name',
    faceclaim: '.faceclaim',
    posts: '.posts parseInt',
    group: '[data-category]',
    lastposted:  '.lastposted', 
    alias: '.alias',
 },


  sortAscending: {
    name: true,
    posts: false,
    lastposted: false,
    group: true,
    faceclaim: true,
    alias: true
  },
  filter: function() {
    var $this = $(this);
    var searchResult = qsRegex ? $(this).find('.name').text().match( qsRegex ) : true;
    var fcResult = fcRegex ? $(this).find('.faceclaim').text().match( fcRegex ) : true;
    var buttonResult = buttonFilter ? $this.is( buttonFilter ) : true;
    return searchResult && fcResult && buttonResult;
 }
  });        

// bind filter button click
$('.filter-button-group').on( 'click', '.button', function() {
  var $this = $(this);
  // get group key
  var $buttonGroup = $this.parents('.button-group');
  var filterGroup = $buttonGroup.attr('data-filter-group');
  // set filter for group
  buttonFilters[ filterGroup ] = $this.attr('data-filter');
  // combine filters
  buttonFilter = concatValues( buttonFilters );
  // Isotope arrange
  $grid.isotope();
  updateFilterCount();
});

// bind sort button click
$('.sort-by-button-group').on( 'click', 'button', function() {
  var sortValue = $(this).attr('data-sort-value');
  $grid.isotope({ sortBy: sortValue });
});

// bind filter button click
$('.button').on( 'click', '.button', function() {
  var $this = $(this);
  // get group key
  var $buttonGroup = $this.parents('.button-group');
  var filterGroup = $buttonGroup.attr('data-filter-group');
  // set filter for group
  buttonFilters[ filterGroup ] = $this.attr('data-filter');
  // combine filters
  buttonFilter = concatValues( buttonFilters );
  // Isotope arrange
  $grid.isotope();
  updateFilterCount();
});
// use value of search field to filter
var $quicksearch = $('.quicksearch').keyup( debounce( function() {
  qsRegex = new RegExp( $quicksearch.val(), 'gi' );
  $grid.isotope();
}) );
// use value of search field to filter
var $fcsearch = $('.fcsearch').keyup( debounce( function() {
  fcRegex = new RegExp( $fcsearch.val(), 'gi' );
  $grid.isotope();
}) );



Posts sort great because they are just a number. Last Posted are a date i.e (April 2 2023) or (Today/Yesterday with a time) and sort in a random order. How do I get it to sort correctly?

How can I use Pyodide’s virtual file system to write and overwrite files when using writeFile() in JavaScript?

I am trying to write files into Pyodides virtual file system using writeFile() in order to run test scripts. However, I believe that writeFile() is just adding more data to the python file I write into, meaning that even if the code is wrong, if the original code was correct, then the tests will pass even when running with incorrect code. How can writeFile() be able to overwrite the ENTIRE file so I can ensure that Pyodides file system will only have 2 files at a time with different content? Here is the code below, I have already tried unlink() but it failed to delete the file:

//fileSaver is used to save the code to a file and download it 
const fileSaver = require('file-saver');
// Setup ace variables and the output pane for pyodide
var editor = ace.edit("editor");
var output_pane;
// The following line will essentially be the "file path" input for the RST directive, or 
// we can figure out how to pass arguments into an iframe if thats even possible
var testFilePath = '/_static/test_files/test.py';

loadPyodide().then((pyodide) => {
    // pyodide is now ready to use...
    globalThis.pyodide = pyodide;
    appendOutput('Python ready.n');
});

function appendOutput(msg) {
    // used to add program output to the textarea
    output_pane.value = output_pane.value + 'n' + msg;
    output_pane.scrollTop = output_pane.scrollHeight;
}

function configEditor(){
    // configure the ace editor to make it usable
    editor = ace.edit("editor");
    editor.setTheme("ace/theme/xcode");
    editor.session.setMode("ace/mode/python");
    editor.setShowPrintMargin(false);
    editor.setBehavioursEnabled(true);
    editor.setFontSize(13);
    //Fix indentation issue with ace editor, not really the best solution but it works
    var code = editor.getValue();
    var lines = code.split("n");
    var minIndent = null;
    for (var i = 0; i < lines.length; i++) {
        var line = lines[i];
        if (line.trim().length > 0) {
            var indent = line.search(/S/);
            if (minIndent === null || (indent !== -1 && indent < minIndent)) {
                minIndent = indent;
            }
        }
    }
    if (minIndent !== null) {
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].trim().length > 0) {
                lines[i] = lines[i].slice(minIndent);
            }
        }
        code = lines.join('n');
        editor.setValue(code);
    }
}

function openCode(filePathToUse) {
    getCode(filePathToUse)
      .then(code => {
        var modelist = ace.require("ace/ext/modelist");
        var modeName = modelist.getModeForPath(filePathToUse).mode;
        editor.session.setMode(modeName);
        editor.session.setValue(code);
      })
      .catch(error => {
        console.error('Error occurred while opening the code:', error);
      });
  }

async function runCode(code_to_run) {
    // Run the code thats within the editor so students can test
    if(code_to_run == editor.getValue()){
        console.logs = [];

        let promise = new Promise((resolve, reject) => {
            window.pyodide.runPython(code_to_run)
            resolve(true)
        }).catch(err => {
            console.log(err);
            appendOutput(console.logs.join('n')); 
        });
    
        let result = await promise;
        if (result) { 
            appendOutput(console.logs.join('n')); 
        }
    } else {
        
        console.logs = [];

        let promise = new Promise((resolve, reject) => {
            var data = editor.getValue(); 
            var testData = code_to_run;
            window.pyodide.FS.writeFile("challenge.py", data);
            window.pyodide.FS.writeFile("test.py", testData);
            window.pyodide.runPython(`exec(open("test.py").read())`)
            resolve(true)
        }).catch(err => {
            console.log(err);
            appendOutput(console.logs.join('n')); 
        });
        
        let result = await promise;
        if (result) { 
            appendOutput(console.logs.join('n')); 
        }
    }
}

function saveCode(code) {
    var blob = new Blob([code], { type: "text/plain;charset=utf-8" });
    window.saveAs(blob, 'challenge.py');
}

//make a function getCode that takes in a file path and returns the code in that file as a string to use in ace
async function getCode(codeToGet) {
    try {
      const response = await fetch(codeToGet);
      const data = await response.text();
      return data;
    } catch (error) {
      console.error('Error occurred while opening the code:', error);
    }
  }


//codeToSwitch will be a file path
function switchFile(codeToSwitch) {
    getCode(codeToSwitch)
    .then(code => {
        var EditSession = ace.require("ace/edit_session").EditSession;
        var oldSession = editor.getSession();
        //change to new file
        var newSession = new EditSession(code, "ace/mode/python");
        editor.setSession(newSession);
    })
    .catch(error => {
      console.error('Error occurred while opening the code:', error);
    });
}

document.addEventListener('DOMContentLoaded', (event) => {

    output_pane = document.getElementById("output");
    // Add event listeners for downloading code
    document.getElementById("downloadButton").addEventListener('click', function () {
        saveCode(editor.getValue());
    });

    document.getElementById("runButton").addEventListener('click', function () {
        runCode(editor.getValue());
    });
    
    // Add event listeners for running code
    document.getElementById("run_code").addEventListener('click', function () {
        //Run the getcode function to get the code from the editor
        getCode(testFilePath)
        .then(code => {
            runCode(code);
        }) 
        .catch(error => {
            console.error('Error occurred while opening the code:', error);
        });
    });

    // Capture the output from Pyodide and add it to an array
    console.stdlog = console.log.bind(console);
    console.logs = [];
    console.log = function(){
        console.logs.push(Array.from(arguments));
        console.stdlog.apply(console, arguments);
    }
    
    configEditor();
});

I tried overwriting the file using writeFile() and I tried deleting from pyodides file system with unlink in which neither worked. I want it so that whenever I execute test.py, if the code is incorrect the tests should fail, if its correct the tests should pass. However I feel that writeFile is appending rather than overwriting.

firestore “listen” to latest N updates and paginate the rest

I have hundreds of documents in my firestore in this format

{
  updatedAt: serverTimeStamp
  userIds: [1,2,3] //who should receive the updates 
  ...rest of the data
}

i want to update the UI realtime on any new document added or existing is modified. and i want to be able paginate for the rest.
solution : listen to 1 document and order by updatedAt so that latest updates always reach the UI.
here’s the query i wrote

query(
    collection(
      firestoreInstance,
     "myCollection"
    ),
     where("userIds", "array-contains", currentUserId)
    orderBy("updatedAt","desc"),
    limit(1)
  );

but the problem is, its only “subscribing” to 1 document, any other documents added or updates its not getting that change.

Another approach is to have a dedicated collection for notification_collection, whenever a new document added or updated, i also need to update these dedicated collection’s document of interested users and UI can subscribe to only 1 document(notification_collection), but this would result in multiple writes on primary collection updates.

what is the efficient way to listen to realtime updates and paginate the rest.

Problem when implementing a button in a Laravel gradebook software

I am working on a project with Laravel where student notes are managed. I have a students.blade.php file where the grades are reflected as follows:

@foreach ($indicators as $indicator)
 <td class="center">
{{ number_format($notes[ $indicator->id ] ?? 0, 2) }}
 </td>
@endforeach

And I have a functionality that allows me to change the note manually through an input like this:

<a href="{{ route('web.notes.students-indicators', [$entity->id, $student->id]) }}" data-title="Student Notes: {{ $student-> full_name }}" data-reload="1" class="swal-ajax green-text tooltipped" data-position="top" data-tooltip="Student Notes: {{ $student->full_name }}" ><i class="fa fa-book-reader"></i></a>

This code is connected to a file called fields.blade.php and allows you to modify the note via input like this:

<input type="hidden" name="notes[{{ $loop->index }}][indicator_id]" value="{{ $indicator->id }}">
<input type="number" class="input_note" name="notes[{{ $loop->index }}][note]" step="0.01" value="{{ $notes[ $indicator->id ] ??0 }}" min="0" max="100">

What I would like to know is how I could change a grade to a student through a button passing a default grade, for example: 3.5 and assign that grade instead of doing it manually with the input, I appreciate if you can lead me to a solution

I tried to use an AJAX function that would allow to grab the value assigned by the button and send it to the backend but it didn’t work

What should I do to adjust submit button width in a survey form created using Express.js?

I have been creating a survey form with Express.js, node.js, html, css and I’m facing an issue with the submit button not fitting properly within the container. Despite trying different CSS modifications, the button still extends beyond the container’s boundaries. I’ve made sure to set the width to 100% and adjust the box-sizing property, but it doesn’t seem to resolve the problem. I’ve also attempted to specify a fixed width for the button, but that didn’t work either. I’m currently unable to find a solution to this issue. If you have any suggestions or insights, I would greatly appreciate your help. Thank you! Check out the link below to access the image

<!DOCTYPE html>
<html>
<head>
  <title>Survey Form</title>
  <!-- Survey form formatting style in CSS -->
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    .container {
      max-width: 400px;
      margin: 0 auto;
      padding: 20px;
      border: 1px solid #ccc;
      border-radius: 5px;
      background-color: #f9f9f9;
    }

    .form-group {
      margin-bottom: 20px;
      justify-content: space-between;
      align-items: center;
    }

    .form-group label {
      display: block;
      margin-bottom: 5px;
      font-weight: bold;
    }

    .form-group input,
    .form-group select,
    .form-group textarea {
      width: 100%;
      padding: 8px;
      border: 1px solid #ccc;
      border-radius: 4px;
    }

    .form-group textarea {
      resize: vertical;
    }

    .form-group input[type="submit"] {
        background-color: #4a90e2;
      color: white;
      cursor: pointer;
      border: none;
      padding: 10px 20px;
      border-radius: 4px;
      width: auto;
      text-align: left;
      float: right;
    }

    .form-group input[type="submit"]:hover {
        background-color: #3676d6;
    }
  </style>
</head>

[Check out the link below to access the image](https://i.stack.imgur.com/EHLH0.png)

Javascript code to display and replace random array data in a single line on screen

Good,

I’m trying to display some random data that I have in an array, on screen in a single line.
I want it to show me 4 pieces of data and when the 4 pass through the screen regardless of the size, they are deleted and then show another 4 different pieces of data randomly.

I have managed to show 4 data, but it happens to me that while they are shown, the data are constantly changing, and it has to change when the screen has passed.

I show here the javascript code:

// Selecciona el elemento donde se mostrarán los datos
const dataContainer = document.querySelector('#cats-facts');

// Frases personalizadas
const customFacts = [
    "Frase personalizada 1",
    "Frase personalizada 2",
    "Frase personalizada 3",
    "Frase personalizada 4",
    "Frase personalizada 5",
    "Frase personalizada 6"
];

// Variable para almacenar los datos mostrados
let shownFacts = [];

// Crear un IntersectionObserver para detectar cuando los datos hayan pasado la pantalla
const observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            // El elemento ha pasado la pantalla
            observer.unobserve(entry.target);
            entry.target.remove();

            // Cargar nuevos datos una vez que todos los datos hayan pasado por la pantalla
            if (dataContainer.children.length === 0) {
                loadCatFacts();
            }
        }
    });
});

// Función para cargar y mostrar los datos
function loadCatFacts() {
    // Reiniciar el array de datos mostrados
    shownFacts = [];

    for (let i = 0; i < 4; i++) {
        loadCatFact();
    }
}

// Función para cargar un dato
function loadCatFact() {
    // Obtener una frase personalizada aleatoria que aún no se haya mostrado
    let fact = null;
    do {
        const randomIndex = Math.floor(Math.random() * customFacts.length);
        fact = customFacts[randomIndex];
    } while (shownFacts.includes(fact));

    // Agregar la frase al array de datos mostrados
    shownFacts.push(fact);

    // Crear un nuevo elemento con la frase personalizada
    const factElement = document.createElement('span');
    factElement.classList.add("marquee-text", "px-4");
    factElement.textContent = fact;

    // Agregar el nuevo elemento al contenedor
    dataContainer.appendChild(factElement);

    // Observar el nuevo elemento
    observer.observe(factElement);
}

// Cargar los datos iniciales
loadCatFacts();

Why is my converted JavaScript code to jQuery not working? [closed]

I am new here

I convert JavaScript code into jQuery
This JavaScript code working fine

<div class="adflexbox" id="be6ba2bf8f11941b8e35517dd74dff283"></div>
<script>
    (function(d, w) {
        if (!w.adflex) {
            var s = d.createElement("script");
            s.type = "text/javascript";
            s.src = "https://app.buzaq.com/loader.js";
            d.getElementsByTagName('head')[0].appendChild(s);
            w.adflex = {host: '//app.buzaq.com'};
        }
    })(document, window);
</script>

But I need this code in jQuery so I was convert it into jQuery but this code not working

<div class="adflexbox" id="be6ba2bf8f11941b8e35517dd74dff283"></div>
<script>
    $(document).ready(function() {
        if (!$.adflex) {
            var script = document.createElement("script");
            script.type = "text/javascript";
            script.src = "https://app.buzaq.com/loader.js";
            $("head").append(script);
            $.adflex = { host: "//app.buzaq.com" };
        }
    });
</script>