VS Code – don’t see variables when debugging JS

I’m trying to debug a simple program in JS:

var a = [1,2,2,2,3];
        var b = [2];
        function arrayDiff(a, b) {
            console.log(a,b);
            for(var i = 0; i < b.length; i++) {
                if(a.includes(b[i])){
                    a.splice(b[i]);
                    console.log(a,b);
                }
            }
            return a,b;
        }
        
        var array1 = [1,1,2];
        var array2 = [1];
        console.log(arrayDiff(array1,array2));

and see how the variables act. I have a HTML file connected to this, downloaded Debugger for Firefox and created the following launch.json file:

{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [

    {
        "name": "Launch index.html",
        "type": "firefox",
        "request": "launch",
        "reAttach": true,
        "file": "${workspaceFolder}/index.html"
    },
    {
        "name": "Launch localhost",
        "type": "firefox",
        "request": "launch",
        "reAttach": true,
        "url": "http://localhost/index.html",
        "webRoot": "${workspaceFolder}"
    },
    {
        "name": "Attach",
        "type": "firefox",
        "request": "attach"
    },
    {
        "name": "Launch WebExtension",
        "type": "firefox",
        "request": "launch",
        "reAttach": true,
        "addonPath": "${workspaceFolder}"
    }
]}

However I still cannot see the variables when I put breakpoints and so on… I’ve tried everything from reinstalling the extension, setting up Firefox browser itself with the values recommended in the extension’s readme, localhost, attach, or opening directly the index.html file. Looked through stack overflow and none of the solutions have helped yet…

Running Pop!_OS 22.04 LTS.

Thanks!

How do I pass down props to another function using TypeScript?

I am not proficient with TypeScript but I am trying to pass down the {product.picture} which is a string to the function saveInfo() once the user clicked save. I can display the picture but I could not post it to the server once I clicked the save button. The error stated “Cannot find product”.

Appreciate any help on this.

function App() {
    
    const saveInfo = async (product) => {
    let response = await axios.post('https://localhost:3000', {
      data: {
        image: `https://image/${product.picture}.png`,
      },
    });

  return (
    <div className="App">
            <div>
                products.map((product: any) => (
                  <div className="product" key={product.id}>
                    <h5>{product.name}</h5>
                    <img
                      src={`https://image/${
                        product.picture as string
                      }.png`}
                      alt="symbol"
                    />
                  </div>
                ))
            </div>
            <button onClick={() => saveInfo(product)}>Save</button>
    </div>
  );
}

How do I authorize to work with Google forms?

When I want to get authorization data I get this error:

Error: listen EADDRINUSE: address already in use :::3200

This port is not busy. The error occurs only when it starts executing this request.

The request is executed at the address: http://localhost:3200/api/run

What am I doing wrong?

const path = require('path');
const { authenticate } = require('@google-cloud/local-auth');


module.exports.runSample = async function () {
    const auth = await authenticate({
        keyfilePath: path.join(__dirname, 'credentials.json'),
        scopes: 'https://www.googleapis.com/auth/forms.responses.readonly',
    });
    console.log(auth)
}

credentials.json:

{
    "web": {
...
        "redirect_uris": [
            "http://localhost:3200/oauth2callback/"
        ]
    }
}

chrome.tabs.onUpdated.addListener gives “Could not establish connection”-error

I’m learning how to make Chrome-extensions (manifest v3) and I’m trying to understand how “addListener” works, more specifically “chrome.tabs.onUpdated.addListener”.

One thing I don’t understand is why Chrome throws this error at me all the time:

*Uncaught (in promise) Error: Could not establish connection. Receiving end does not exist.
*

I feel that I’m missing something very important on how messages work between backgrounds.js and content.js. Any suggestions?

In backgrounds.js I have this code:

chrome.tabs.onUpdated.addListener ( function (tabId, changeInfo, tab) {

  if (changeInfo.status === 'complete' && tab.status === 'complete' && tab.url) {
    chrome.tabs.sendMessage(tab.id, { type: "RELOADED" });
    
  }
});

And in my content.js I have this code:

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "RELOADED") {

    let prismicUrl = document.location.href;
    
    const prismicUrlMustExist = /~b/; // Normal
    const prismicUrlMustExist2 = /&b=/; // Efter sökning
    const articleUrlMustExist = /--ec/;
   
    if (prismicUrlMustExist.test(prismicUrl) || prismicUrlMustExist2.test(prismicUrl)) {
      console.info("Hittade artikel. Väntar en sekund.");
      setTimeout(() => {  initiate(); }, 1000);
      console.info("Försöker hitta sidebar.");
    } else if (articleUrlMustExist.test(prismicUrl)) {
      console.info("Hittaden artikel på sajten.");
      setTimeout(() => {  initiate_article(); }, 1000);
    } else {
      console.warn("Error: hittade ingen kompatibel sida.");
    }
  }
});```

Feel free highlight any improvements I can make to do this in a more effective way, or tell if you need more information about the code.


Well, I'm stuck. I have tried reading on the subject and understand how to do it differently, but I didn't find anything that stuck well enough for me.

How to call my function inside another function

Im currently trying to implement functionality that deletes all translations within a project when a user deletes a project. However, when i try to call my deleteTranslations function within my deleteProject function, it says deleteTranslations is not defined.

deleteTranslations: async ({ user, projectId, trkeys }) => {
      const deletePromises = trkeys.map(async (trkey) => {
        const params = {
          ...getBaseParams(),
          Key: {
            PK: getPK('trans', user, projectId),
            SK: getSK('trans', user, projectId, trkey),
          },
        };
        return doDelete(params);
      });
      return Promise.all(deletePromises);
    },

    deleteProject: async ({ user, project }) => {
      const translationsParams = {
        user,
        projectId: project,
        trkeys: [],
      };
      await deleteTranslations(translationsParams);      // the problem is here

      const params = {
        TableName: table,
        Key: {
          PK: getPK('project', user),
          SK: getSK('project', user, project),
        },
      };
      return doDelete(params);
    },

Ive tried to implement this in a few ways but i cant wrap my head around this.

scrollIntoView on position:sticky only working in one direction

I have a navbar that scrolls (using scroll-behaviour: smooth) the required section of the website into view using this javascript:

    for (const liItem of navList) {
      liItem.onclick = () => {
        document.getElementById(liItem.getElementsByTagName('a')[0].dataset.target).scrollIntoView();
      };
    }

Tested on Chrome 112.0.5615.49 (ARM build) and Safari 16.3 it works exactly as expected on position: relative divs (Behaviour: http://miserylovescompanyfestival.co.uk/). Using position: sticky for the targeted elements results in scrollIntoView only working for elements later in the DOM tree than the currently visible element (Behaviour: https://theexactopposite.uk/test/index-card.html – using the menu it is possible to scroll down to ‘Upcoming Shows’ but not scroll back up to ‘About Us’ from there).

This is the css for the position: sticky element:

.card {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  width: 100vw;
  height: 100vh;
  color: white;
  display: flex;
  justify-content: center;
  align-items: center;
}

I have looked at the other questions regarding scrollIntoView and position: sticky here, but none seem to have had this specific issue. How can I get scrollIntoView to work in both directions?

Export GridView to excel without HiddenRows

I have this void to export a GridView rows to Excel and it works fine:

 protected void Button2_Click(object sender, EventArgs e)
    {
        
        DataTable tbl = GridView1.DataSource as DataTable;
        
        Response.Clear();
        Response.Buffer = true;
        Response.ClearContent();
        Response.ClearHeaders();
        Response.Charset = "";

        string fileName = "ConsultaSerialesFinishGoods_" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + ".xls";
        StringWriter stringWriter = new StringWriter();
        HtmlTextWriter htmlTextWriter = new HtmlTextWriter(stringWriter);
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
        
        GridView1.HeaderRow.Cells[0].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[1].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[2].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[3].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[4].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[5].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[6].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[7].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[8].BackColor = Color.Blue;
        GridView1.HeaderRow.Cells[9].BackColor = Color.Blue;
        GridView1.HeaderRow.ForeColor = Color.White;

        GridView1.AlternatingRowStyle.Reset();
        GridView1.RowStyle.Reset();

        GridView1.BackColor = Color.Transparent;
        GridView1.GridLines = GridLines.Both; //Si queremos que el excel tenga lineas
        GridView1.RenderControl(htmlTextWriter);
        Response.Write(stringWriter.ToString());
        Response.End();
    }

Also I have this other JS function to hide rows from the GridView1 using a Textbox:

function Search_Gridview(strKey) {
                var strData = strKey.value.toLowerCase().split(" ");
                var tblData = document.getElementById("<%=GridView1.ClientID %>");
                var rowData;
                for (var i = 1; i < tblData.rows.length; i++) {
                    rowData = tblData.rows[i].innerHTML;
                    var styleDisplay = 'none';
                    for (var j = 0; j < strData.length; j++) {
                        if (rowData.toLowerCase().indexOf(strData[j]) >= 0)
                            styleDisplay = '';
                        else {
                            styleDisplay = 'none';
                            break;
                        }
                    }
                    tblData.rows[i].style.display = styleDisplay;
                }
            }

I want to avoid export the hidden rows (when they are hidden using the textbox with the JS), because the Button2 is exporting all the Rows of the GridView even the hidden rows.
Do you know how can I do that? Thank you.

join two arrays into 1 array [closed]

I created arrays .push like this

netPurchArr.push({
    netPRchRAw: formatCurrency(tst),
    netKurang: formatCurrency(ntKrng)
});

and result

    [
       {
          netPRchRAw: "3,565,980",
          netKurang: "958,020"
       }
    ]
[
   {
      netPRchRAw: "2,348,264",
      netKurang: "253,724"
   }
]

can join this array be like this

[
    {
        netPRchRAw: "3,565,980",
        netKurang: "958,020"
    },
    {
        netPRchRAw: "2,348,264",
        netKurang: "253,724"
    }
]

Pricing Page With Unique Values

I have an worksheet with values that need to be displayed in a webpage depending on the user’s input.

This is a pricing page in WordPress with five different currencies. A user will input a value (amount of rooms in their hotel) and the return should be four different pricing options for the four different packages we offer.

The problem is, there is no arithmetic pattern between any of these values. Every single one of them for every different currency is unique.

https://roomraccoon.com/pricing/?_gl=1*1qm70xo*_ga*MjA5MzI2Nzk3MC4xNjgwNzA0Nzc0*_ga_C0JRNX0J8N*MTY4MTM3ODk5MS40LjAuMTY4MTM3ODk5MS42MC4wLjA.&_ga=2.99292318.1497637414.1681377154-2093267970.1680704774

Above is the pricing page.

The pricing on the page is currently incorrect as I am using a formula instead of the actual values.

# of rooms:

<script type="text/javascript" defer>
    document.querySelector(".switch-button-checkbox").addEventListener("click",function(){
    var entryText = document.querySelector(".entry-column .elementor-price-table__integer-part");
    var starterText = document.querySelector(".starter-column .elementor-price-table__integer-part");
    var premiumText = document.querySelector(".premium-column .elementor-price-table__integer-part");
    var enterpriseText = document.querySelector(".enterprise-column .elementor-price-table__integer-part");     
    if(document.querySelector(".switch-button-checkbox").checked == true){
        
            //Annual
           if(input.value<=18){
            //ENTRY PRICE
            entryText.innerHTML = Math.ceil(18*111.06);
            //STARTER PRICE
            starterText.innerHTML = Math.ceil(18*142.06);
            //PREMIUM PRICE
            premiumText.innerHTML = Math.ceil(18*208.28);
            //ENTERPRISE PRICE
            enterpriseText.innerHTML = Math.ceil(18*292.94);
           }else if(input.value>18){
            //ENTRY PRICE
            entryText.innerHTML = Math.ceil(input.value*112.76);
            //STARTER PRICE
            starterText.innerHTML = Math.ceil(input.value*141);
            //PREMIUM PRICE
            premiumText.innerHTML = Math.ceil(input.value*206.85);
            //ENTERPRISE PRICE
            enterpriseText.innerHTML = Math.ceil(input.value*291.55);
           }

    }else{
        
            //Monthly
            if(input.value<=18){
            //ENTRY PRICE
            entryText.innerHTML = Math.ceil(18*133.33);
            //STARTER PRICE
            starterText.innerHTML = Math.ceil(18*170.00);
            //PREMIUM PRICE
            premiumText.innerHTML = Math.ceil(18*250.00);
            //ENTERPRISE PRICE
            enterpriseText.innerHTML = Math.ceil(18*351.67);
           }else if(input.value>18){
            //ENTRY PRICE
            entryText.innerHTML = Math.ceil(input.value*135.50);
            //STARTER PRICE
            starterText.innerHTML = Math.ceil(input.value*169.37);
            //PREMIUM PRICE
            premiumText.innerHTML = Math.ceil(input.value*248.3);
            //ENTERPRISE PRICE
            enterpriseText.innerHTML = Math.ceil(input.value*350);
           }
    }
    });    
    
    
    const input = document.querySelector(".rooms-input");
    input.addEventListener('change', priceFunction);
    input.addEventListener('keyup', priceFunction);
    function priceFunction(){
        var entry = document.querySelector(".entry-column .elementor-price-table__integer-part");
        var starter = document.querySelector(".starter-column .elementor-price-table__integer-part");
        var premium = document.querySelector(".premium-column .elementor-price-table__integer-part");
        var enterprise = document.querySelector(".enterprise-column .elementor-price-table__integer-part");    
        var inputValue = input.value;
        if(inputValue>999){
            input.value = 999;
        }
        if(document.querySelector(".switch-button-checkbox").checked == true){
            //Annual
           if(inputValue<=18){
            //ENTRY PRICE
            entry.innerHTML = Math.ceil(18*111.06);
            //STARTER PRICE
            starter.innerHTML = Math.ceil(18*142.06);
            //PREMIUM PRICE
            premium.innerHTML = Math.ceil(18*208.28);
            //ENTERPRISE PRICE
            enterprise.innerHTML = Math.ceil(18*292.94);
           }else if(inputValue>18){
            //ENTRY PRICE
            entry.innerHTML = Math.ceil(inputValue*112.76);
            //STARTER PRICE
            starter.innerHTML = Math.ceil(inputValue*141);
            //PREMIUM PRICE
            premium.innerHTML = Math.ceil(inputValue*206.85);
            //ENTERPRISE PRICE
            enterprise.innerHTML = Math.ceil(inputValue*291.55);
           }
        }else{
            //Monthly
            if(inputValue<=18){
            //ENTRY PRICE
            entry.innerHTML = Math.ceil(18*133.33);
            //STARTER PRICE
            starter.innerHTML = Math.ceil(18*170.00);
            //PREMIUM PRICE
            premium.innerHTML = Math.ceil(18*250.00);
            //ENTERPRISE PRICE
            enterprise.innerHTML = Math.ceil(18*351.67);
           }else if(inputValue>18){
            //ENTRY PRICE
            entry.innerHTML = Math.ceil(inputValue*135.50);
            //STARTER PRICE
            starter.innerHTML = Math.ceil(inputValue*169.37);
            //PREMIUM PRICE
            premium.innerHTML = Math.ceil(inputValue*248.3);
            //ENTERPRISE PRICE
            enterprise.innerHTML = Math.ceil(inputValue*350);
           }
        }
    }
    

</script>

Why I can’t the items in the database using php and mysql

I am using php and mysql for my database but unfortunately I am encountering an error and it shows this error

DataTables warning: table id=example – Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

it seems that it has an error on the $sql = “SELECT * FROM user WHERE user_type =’admin”;

$output= array();
$sql = "SELECT * FROM user WHERE user_type ='admin";

$totalQuery = mysqli_query($con,$sql);
$total_all_rows = mysqli_num_rows($totalQuery);

$columns = array(
    0 => 'id',
    1 => 'username',
    2 => 'email',
    3 => 'mobile',
    4 => 'city',
    5 => 'password',
);

if(isset($_POST['search']['value']))
{
    $search_value = $_POST['search']['value'];
    $sql .= " WHERE username like '%".$search_value."%'";
    $sql .= " OR email like '%".$search_value."%'";
    $sql .= " OR mobile like '%".$search_value."%'";
    $sql .= " OR city like '%".$search_value."%'";
}

if(isset($_POST['order']))
{
    $column_name = $_POST['order'][0]['column'];
    $order = $_POST['order'][0]['dir'];
    $sql .= " ORDER BY ".$columns[$column_name]." ".$order."";
}
else
{
    $sql .= " ORDER BY id desc";
}

if($_POST['length'] != -1)
{
    $start = $_POST['start'];
    $length = $_POST['length'];
    $sql .= " LIMIT  ".$start.", ".$length;
}   

$query = mysqli_query($con,$sql);
$count_rows = mysqli_num_rows($query);
$data = array();
while($row = mysqli_fetch_assoc($query))
{
    $sub_array = array();
    $sub_array[] = $row['id'];
    $sub_array[] = $row['username'];
    $sub_array[] = $row['email'];
    $sub_array[] = $row['mobile'];
    $sub_array[] = $row['city'];
    $sub_array[] = $row['password'];
    $sub_array[] = '<a href="javascript:void();" data-id="'.$row['id'].'"  class="btn btn-info btn-sm editbtn" >Edit</a>  <a href="javascript:void();" data-id="'.$row['id'].'"  class="btn btn-danger btn-sm deleteBtn" >Delete</a>';
    $data[] = $sub_array;
}

$output = array(
    'draw'=> intval($_POST['draw']),
    'recordsTotal' =>$count_rows ,
    'recordsFiltered'=>   $total_all_rows,
    'data'=>$data,
);
echo  json_encode($output);
$(document).ready(function() {
                          $('#example').DataTable({
                            "fnCreatedRow": function(nRow, aData, iDataIndex) {
                              $(nRow).attr('id', aData[0]);
                            },
                            'serverSide': 'true',
                            'processing': 'true',
                            'paging': 'true',
                            'order': [],
                            'ajax': {
                              'url': 'fetch_data.php',
                              'type': 'post',
                            },
                            "aoColumnDefs": [{
                                "bSortable": false,
                                "aTargets": [5]
                              },

                            ]
                          });
                        });

i am expecting to show the data in the database in a table form

v-model not working with in Vue 3?

Why isn’t v-model binding to my input in the example below? Is there a limitation of <component>?

<script setup>
import { ref } from 'vue'

const config = ref({
  headers: [
    { field: 'id', label: 'Id', component: { type: 'input' } }, 
    { field: 'name', label: 'Name', component: { type: 'input' }  }
  ],
  data: [
    { id: 1, name: 'foo' },
    { id: 2, name: 'bar' }
  ]
})
</script>

<template>
  <table>
    <tr>
      <td v-for="header in config.headers">
        <b>{{ header.label }}</b>
      </td>
    </tr>
    <tr v-for="item in config.data">
      <td v-for="header in config.headers">
        <component :is="header.component.type" v-model="item[header.field]" />
      </td>
    </tr>
  </table>
  {{ config.data }}
</template>

Images not showing up in Vs Code folder or the browser when i link it on HTML or CSS from my path?

enter image description hereI want my images to show-up on my browser. But they don’t because for some reason the path is not either found or maybe writing it wrong.

I tried this multiple times, and not only in one project but multiple.
Usually on my CSS i would it as my background and it doesn’t show on the browser. I used developer tools but it show no error even the syntax. Also it does not show where the image folder is, i think that’s one of the problem.

React retain UI state of component instead of destroying and recreating every time

I have various components/sections on my page and at a time, only 1 section is supposed to be visible to the user. User clicks on different tabs to access the respective sections. As of now, my components are dynamically destroyed and shown based on the tab that is clicked.

{mySection1 && <div><MySection1 {...props} /></div>}
{mySection2 && <div><MySection2 {...props} /></div>}

Now the issue is within each section, there are different form fields and they even display inline error based on some validations (e.g. mandatory, regex, etc)

Now since I destroy and recreate the component on each tab click, I kind of loose the earlier component state and am finding it difficult to retain (e.g. retain the inline error on a field if user clears out a mandatory field)

I am trying to see if there can be another way to retain the UI state.

It would be great if someone could point out any reference example where I can try leveraging React.memo to somehow cache the UI state
Other is not sure if we can use visibility: hidden so that the component is not destroyed.