Is grid something defined on the JavaScript language? [duplicate]

I am confused about why this code works. Especially the part of grid.onclick = function(e) {...}; . At first, I thought it won’t work because the developer didn’t define grid first, but it works. Can someone explain it to me? I don’t think grid is something defined in the language.

<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
  <style>
    table {
       border-collapse: collapse;
     }
     th, td {
       border: 1px solid black;
       padding: 4px;
     }
     th {
       cursor: pointer;
     }
     th:hover {
       background: yellow;
     }
  </style>
</head>

<body>

  <table id="grid">
    <thead>
      <tr>
        <th data-type="number">Age</th>
        <th data-type="string">Name</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td>5</td>
        <td>John</td>
      </tr>
      <tr>
        <td>2</td>
        <td>Pete</td>
      </tr>
      <tr>
        <td>12</td>
        <td>Ann</td>
      </tr>
      <tr>
        <td>9</td>
        <td>Eugene</td>
      </tr>
      <tr>
        <td>1</td>
        <td>Ilya</td>
      </tr>
    </tbody>
  </table>

  <script>

    grid.onclick = function(e) {
      if (e.target.tagName != 'TH') return;

      let th = e.target;
      // if TH, then sort
      // cellIndex is the number of th:
      //   0 for the first column
      //   1 for the second column, etc
      sortGrid(th.cellIndex, th.dataset.type);
    };

    function sortGrid(colNum, type) {
      let tbody = grid.querySelector('tbody');

      let rowsArray = Array.from(tbody.rows);

      // compare(a, b) compares two rows, need for sorting
      let compare;

      switch (type) {
        case 'number':
          compare = function(rowA, rowB) {
            return rowA.cells[colNum].innerHTML - rowB.cells[colNum].innerHTML;
          };
          break;
        case 'string':
          compare = function(rowA, rowB) {
            return rowA.cells[colNum].innerHTML > rowB.cells[colNum].innerHTML ? 1 : -1;
          };
          break;
      }

      // sort
      rowsArray.sort(compare);

      tbody.append(...rowsArray);
    }
  </script>

</body>
</html>

How to correctly recalculate the height of the block when resize?

There are drop-down menus in which nested drop-down menus. To make the appearance animation I calculate the height of each block at load time, write it to the block attribute and hide the block. When resizing I try to do the same

function activeHeight() {
    let allAccordion = document.querySelectorAll('.accordion');

    allAccordion.forEach((item) => {
      let accordionParent = item.querySelectorAll('.accordion-parent');
      let accordionItem = item.querySelectorAll('.accordion-item');

      accordionItem.forEach((item) => {
        item.nextElementSibling.style.height = 'auto';
        item.nextElementSibling.dataset.height = item.nextElementSibling.offsetHeight;
        item.nextElementSibling.style.height = '0';
      });

      accordionItem.forEach((item) => {
        if (item.classList.contains('active')) {
          let element = item.closest('.accordion-parent');
          if (element?.querySelectorAll('.accordion-item.active')) {
            const allElement = element.querySelectorAll('.accordion-item.active');

            allElement.forEach((item) => {
              let innerElement = item.nextElementSibling.querySelectorAll('.accordion-item.active');

              let countInnerElement = +item.nextElementSibling.dataset.height;

              innerElement.forEach((element) => {
                countInnerElement += +element.nextElementSibling.dataset.height;
              });

              item.nextElementSibling.style.height = countInnerElement + 'px';
            });
          }
        }
      });
    });
  }

But the height begins to be calculated in different ways.
enter image description here

enter image description here

enter image description here

load an xml in javascript and convert it to string

during a project I found myself needing to modify a script in javascript but unfortunately I know very little about the language.
My goal would be to read an xml file saved locally and then convert it into a string to feed to a subsequent function. I have no problem performing this operation in Java but I have no idea how to do it in javascript.
I’m trying something like this:

var client = new XMLHttpRequest();
client.open('GET', 'C:UsersfabriDesktoptest.xml');
client.onreadystatechange = function() {
   var response = client.responseText,
       parser = new DOMParser(),
       xmlDoc = parser.parseFromString(response,"text/xml");
       var xmlString = new XMLSerializer().serializeToString(xmlDoc);
}
client.send();

but it’s not working.

Can you help me?
Thanks

Get a AST node with a given line range

I want to get an AST node that has the given line inside. I am using the espree (Node.js Script) to parse the code and get the AST tree nodes and doing a recursive function to do that, but I think that I’m reinventing the wheel…

Is there a package/snippet that do this?

Unique items array from arrays with specific order

I have two arrays

const first = [12, 14, 0, 56, 100, 21]
const second = [0, 14]

I want to make first array like this [0, 14, 12, 56, 100, 21]

Second array always has items that are already in the first array. I need to create an array that combines them both but only contains unique items and first items of that array will be items of the second array as this – [0, 14, 12, 56, 100, 21]

I could do something like:

const combined = [...second, ...first]
const unique = [...new Set(combined)

Just wondering if there are better solutions to achieve the result above?

JavasScript number changes after assigning to new variable

Here’s a piece of code that I have in one of my functions. But I noticed that value of number changes once I assign to new variable. Attaching picture, will attach code snippet if needed

For example:
value.price = 333.45. First console logs it correclty

Assign value.price to newItems[index].unitPrice

Logging newItems[index].unitPrice prints 333

Why is this doing floor on assignation. I tried to search but couldn’t figure out. I also know that there is something about numbers in JS thats different.

enter image description here

Best way to check an attribute of an object that might be undefined

I have an object (oUsed) containing “blocked” fields of a grid. If a field is blocked, it’s “true”. If it’s not blocked, it’s undefined.

What can happen now is, that a whole line (x coordinate value) is not blocked. So the following code will fail, as it checks the attribute of an undefined object.

    let oUsed = {
      "x1":{
        "y2": true; 
        "y3": true;
      }
      "x3":{
        "y2": true;
      }
    }
    let iY = 2;

    for (let iX=1;iX <= 3; iX++) {
        if (oUsed[`x${iX}`][`x${iY}`]) {
          break;
        }
    }

Doing it in two steps works, but it’s not very pretty.

    for (let iX=1;iX <= 3; iX++) {
      if (oUsed[`x${iX}`]) {
        if (oUsed[`x${iX}`][`x${iY}`]) {
          break;
        }
      }
    }

What’s the best practice for this kind of check?

Different events on clicking strings in a textarea

I have created a textarea (html) where the user can either type in identifiers, or load them from a file, and they are always separated by a new line. Is it possible to target every identifier (every new line) with a separate event listener and say, display it in the console? I do have functions in my typescript that can target every identifier (simply by splitting the textarea in lines) and work with them, not sure how to do it for my case though. I appreciate the help!

$ajax beforesend is not working with async

$.ajax({
            url: "<%=request.getContextPath()%>/url.do",
            type:'GET',
            data: data,
            cache: false,
            dataType:'text',
            async: false,
            beforeSend: function() {
                $.blockUI({theme: true, fadeIn: 0, title: "Personal Information", message: "Saving information...", timeout: 3000});
            }

In the above code, I am not able to open the dialog box of Personal Information which is under the beforeSend function. But if I removed async=false then I am able to see that.

Is there any other alternative for async that I can use?

Thanks in advance !!

Displayed data does not update in nested loop on state

I have an object looking like this:

categories : [
    { 
        name: "General Information",
        rows: [
            {
                information1 : "",
                information2 : "",
            }
        ]
    }
]

And I am displaying the rows content using a loop like this:

{formData?.categories?.map(c => (
    <div>
        {c.name}
        {c.rows.map((row) => (
        <div>
            <input value={field.information1} />
            <textarea value={field.information2}></textarea>
            <button onClick={() => addRow(c.name)}>Add Row here</button>
        </div>
    ))}
    </div>

))}

When I press one of these buttons (that should add a row to rows array) the formData state does update, but the displayed data does not.

function addRow(category) {

    const updatedFormData = formData

    for (const cat of updatedFormData.categories) {
        if (cat.name === category) {
            cat.fields.push({
                information1 : "test",
                information2 : "this is a test"
            })
        } 
    }

    setFormData(updatedFormData)
} 

golang timer synchronize to multiple clients

I have a go webserver running that has a websocket to localhost, this waits for a message to be received and then starts a timer. I want the timer to be synchronized across n different clients.

My code is working for only 1 client.

here is my go code:

package main

import (
    "fmt"
    "log"
    "net/http"
    "strconv"
    "time"

    "github.com/gorilla/mux"
    "github.com/gorilla/websocket"
)

type Message struct {
    StartTime string `json:"StartTime"`
}

var (
    wsUpgrader = websocket.Upgrader{
        ReadBufferSize:  1024,
        WriteBufferSize: 1024,
    }

    wsConn *websocket.Conn
)

func WsEndpoint(w http.ResponseWriter, r *http.Request) {

    wsUpgrader.CheckOrigin = func(r *http.Request) bool {

        return true
    }
    var err error
    wsConn, err = wsUpgrader.Upgrade(w, r, nil)
    if err != nil {
        fmt.Printf("could not upgrade: %sn", err.Error())
        return
    }
    t, _ := time.ParseDuration("1s")
    tk := time.NewTicker(t)

    defer wsConn.Close()

    for {
        var msg Message

        err := wsConn.ReadJSON(&msg)
        if err != nil {
            fmt.Printf("error reading JSON: %sn", err.Error())
            break
        }

        fmt.Printf("Message Received: %sn", msg.StartTime)
        handleTimer(msg.StartTime, tk)
    }

}

func handleTimer(msg string, tk *time.Ticker) {

    i, _ := strconv.Atoi(msg)
    for range tk.C {

        SendMessage(strconv.Itoa(i))

        i -= 1

    }
}

func SendMessage(msg string) {
    err := wsConn.WriteMessage(websocket.TextMessage, []byte(msg))
    if err != nil {
        fmt.Printf("error sending message: %sn", err.Error())
    }
}

func main() {

    router := mux.NewRouter()

    router.HandleFunc("/socket", WsEndpoint)

    log.Fatal(http.ListenAndServe(":9100", router))

}

and my vue.js app:

<template>
<div>
  <div class="w-full max-w-xs">
    <form class="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4" :action="sendMessage" @click.prevent="onSubmit">
    <div class="mb-4">
      <label class="block text-gray-700 text-sm font-bold mb-2" for="something">
        Enter Something
      </label>
      <input v-model="message" class="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline" type="number" placeholder="Start Time">
    </div>

    <div class="flex items-center justify-between">
          <input type="submit" value="Send" class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded focus:outline-none focus:shadow-outline" @click="sendMessage">
    </div>
  </form>
  </div>
  <div class="text-center mt-60">
    <h1 class="text-7xl">{{ this.received }}</h1>
  </div>
</div>
</template>

<script>


export default {
  name: 'App',
  data() {
    return {
      message: "",
      socket: null,
      received: "",
      hours: null,
      minutes: null,
      seconds:null
    }
  },
  mounted() {
    this.socket = new WebSocket("ws://localhost:9100/socket") 
    this.socket.onmessage = (msg) => {

      let hours = Math.floor(msg.data / 3600) 
      let minutes = Math.floor(msg.data / 60)
      let seconds = msg.data % 60


      if(minutes < 10)
      {
        minutes = "0" + minutes
      }

      if(minutes == 60)
      {
        minutes = "00"
      }
      
      if(seconds < 10) {
        seconds = "0" + seconds
      }

      if(seconds == 0) {
        seconds = "00"
      }
      this.received = "0" + hours + ":" + minutes + ":" + seconds

      if(this.received == "00:00:00")
      {
        alert('times up!')
        this.socket = null
      }
    }
  },

As i said before, this works perfectly on only 1 client. But if I connect another client to localhost:8080 which is the server ran up by npm run serve, the original client stops counting and the new client takes over the counting. How do I handle multiple clients?

Why do i get two “407 Proxy Authentication Required” SIP responses?

I am working on a softphone solution with Golang and Freeswitch. The register works and on Freeswitch I can see my softphone code is registered. I also can send an INVITE from a other softphone (3CX) to my code. But if I try to call the 3CX i always get two “407 Proxy Authentication Required”.3

What I expect:

  1. Send INVITE
  2. Receive the Proxy Authentication Required
  3. Put the Auth into the second INVITE and send again
  4. Call will be setup

What I get:

  1. Send INVITE
  2. Receive the Proxy Authentication Required
  3. Put the Auth into the second INVITE and send again
  4. Receive the Proxy Authentication Required
  5. Nothing

(I deleted SIP Body (offer) because it’s to big)

2022/07/14 09:34:29.300373 invite.go:42: ↑↑↑
INVITE sip:[email protected]:5066 SIP/2.0
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REGISTER, SUBSCRIBE, NOTIFY, REFER, INFO, MESSAGE 
Content-Type: application/sdp
CSeq: 1 INVITE
Call-ID: b31a98fa-c7d2-46a0-9d3b-ffbe60331dcf
Via: SIP/2.0/WS 192.168.1.108;branch=z9hG4bKe92e138a-709b-4329-ac37-1ec2f88a5cb4
To: <sip:[email protected]:5066>
Supported: replaces
User-Agent: Pion WebRTC SIP Client
From: "Agent 41201"<sip:[email protected]:5066>;tag=1693e249-a531-4012-964e-f9b4133cf6e5
Contact: 41201 <sip:[email protected]:5066>
Content-Length: 4265
Max-Forwards: 70

2022/07/14 09:34:29.327669 websocket_freeswitch.go:47: ↓↓↓
SIP/2.0 407 Proxy Authentication Required
Via: SIP/2.0/WS 192.168.1.108;branch=z9hG4bKe92e138a-709b-4329-ac37-1ec2f88a5cb4;received=192.168.1.110;rport=57576
From: "Agent 41201" <sip:[email protected]:5066>;tag=1693e249-a531-4012-964e-f9b4133cf6e5
To: <sip:[email protected]:5066>;tag=5He1p5m60a5DF
Call-ID: b31a98fa-c7d2-46a0-9d3b-ffbe60331dcf
CSeq: 1 INVITE
User-Agent: FreeSWITCH-mod_sofia/1.6.20~64bit
Accept: application/sdp
Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY, PUBLISH, SUBSCRIBE
Supported: timer, path, replaces
Allow-Events: talk, hold, conference, presence, as-feature-event, dialog, line-seize, call-info, sla, include-session-description, presence.winfo, message-summary, refer
Proxy-Authenticate: Digest realm="192.168.1.108", nonce="81f85e27-b5d0-4b27-9358-5eded4524e3a", algorithm=MD5, qop="auth"
Content-Length: 0

2022/07/14 09:34:29.328234 invite.go:42: ↑↑↑
INVITE sip:[email protected]:5066 SIP/2.0
Call-ID: b31a98fa-c7d2-46a0-9d3b-ffbe60331dcf
Via: SIP/2.0/WS 192.168.1.108;branch=z9hG4bK69967eaa-911f-4b89-8566-7b835b4d3b32
To: <sip:[email protected]:5066>
Supported: timer, path, replaces
Allow: INVITE, ACK, CANCEL, OPTIONS, BYE, REGISTER, SUBSCRIBE, NOTIFY, REFER, INFO, MESSAGE 
Content-Type: application/sdp
CSeq: 4 INVITE
From: "Agent 41201"<sip:[email protected]:5066>;tag=1693e249-a531-4012-964e-f9b4133cf6e5
Contact: 41201 <sip:[email protected]:5066>
Proxy-Authenticate: Digest username="41201", realm="192.168.1.108", nonce="81f85e27-b5d0-4b27-9358-5eded4524e3a", uri="sip:[email protected]:5066", response="b7aae35c040dc1f25484eb96d725d6f3",algorithm=MD5,cnonce="0e6758e1adfccffbd0ad9ffdde3ef655",qop=auth,nc=00000001
User-Agent: Pion WebRTC SIP Client
Content-Length: 4265
Max-Forwards: 70


2022/07/14 09:34:29.348968 websocket_freeswitch.go:47: ↓↓↓
SIP/2.0 407 Proxy Authentication Required
Via: SIP/2.0/WS 192.168.1.108;branch=z9hG4bK69967eaa-911f-4b89-8566-7b835b4d3b32;received=192.168.1.110;rport=57576
From: "Agent 41201" <sip:[email protected]:5066>;tag=1693e249-a531-4012-964e-f9b4133cf6e5
To: <sip:[email protected]:5066>;tag=6t7Sr059XKU0a
Call-ID: b31a98fa-c7d2-46a0-9d3b-ffbe60331dcf
CSeq: 4 INVITE
User-Agent: FreeSWITCH-mod_sofia/1.6.20~64bit
Accept: application/sdp
Allow: INVITE, ACK, BYE, CANCEL, OPTIONS, MESSAGE, INFO, UPDATE, REGISTER, REFER, NOTIFY, PUBLISH, SUBSCRIBE
Supported: timer, path, replaces
Allow-Events: talk, hold, conference, presence, as-feature-event, dialog, line-seize, call-info, sla, include-session-description, presence.winfo, message-summary, refer
Proxy-Authenticate: Digest realm="192.168.1.108", nonce="edbe6f39-3aa5-4034-8df8-aae050b77e1a", algorithm=MD5, qop="auth"
Content-Length: 0

What would be the best approach to show a message to user when a process is done in react?

A user uploads a file and in background I would import some data from that file into DB, after the process is done or failed I would like to show a message to user.

What would be the best approach to show the message even user goes to another pages?
Should I add an interval in my root component to check the status of that file? or is there any other solution?

Google Scripts – Copy the text from source google sheet into the “Next Blank Row” of the destination google sheet

I tried to copy the text from source google sheet into the Next Blank Row of the destination google sheet by using the “destinationSheetLastRow” to identify the new row. However, it’s not working. It will be great if you give me some help. My script is in below

//
function importRange(sourceID, sourceRange, destinationID, destinationRangeStart){

  const sourceSS = SpreadsheetApp.openById(sourceID);
  const sourceRng = sourceSS.getRange(sourceRange)
  const sourceVals = sourceRng.getValues();

  const destinationSS = SpreadsheetApp.openById(destinationID);
  const destStartRange = destinationSS.getRange(destinationRangeStart);
  const destSheet = destinationSS.getSheetByName(destStartRange.getSheet().getName());

  const destRange = destSheet.getRange(
      destStartRange.getRow(),
      destStartRange.getColumn(),
      sourceVals.length,
      sourceVals[0].length,
    );
    
  destRange.setValues(sourceVals);
  SpreadsheetApp.flush();
//

Thousand thanks in advance.
Cheers Mate, Have a great day 🙂

Node script won’t run – syntax error with unexpected “=”

I try to start a simple node script and this is what I get in the terminal. It works on my local machine and on another server as well, so what could be wrong with this new server that keeps on giving me this error? I think I’m a little out of my depth with this one and it’s making me nervous.

I’m running v11.15.0

(node:63800) UnhandledPromiseRejectionWarning: /home/ulman/nodevenv/app/11/lib/node_modules/next/dist/server/next-server.js:90
    compression = this.nextConfig.compress && this.nextConfig.target === "server" ? (0, _compression).default() : undefined;
                ^

SyntaxError: Unexpected token =
    at Module._compile (internal/modules/cjs/loader.js:760:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Module.require (internal/modules/cjs/loader.js:723:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at Timeout.getServerImpl [as _onTimeout] (/home/ulman/nodevenv/app/11/lib/node_modules/next/dist/server/next.js:59:71)
    at listOnTimeout (internal/timers.js:535:17)
    at processTimers (internal/timers.js:479:7)
(node:63800) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)(node:63800) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate theNode.js process with a non-zero exit code.
(node:63800) UnhandledPromiseRejectionWarning: /home/ulman/nodevenv/app/11/lib/node_modules/next/dist/server/next-server.js:90
    compression = this.nextConfig.compress && this.nextConfig.target === "server" ? (0, _compression).default() : undefined;
                ^

SyntaxError: Unexpected token =
    at Module._compile (internal/modules/cjs/loader.js:760:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:827:10)
    at Module.load (internal/modules/cjs/loader.js:685:32)
    at Function.Module._load (internal/modules/cjs/loader.js:620:12)
    at Module.require (internal/modules/cjs/loader.js:723:19)
    at require (internal/modules/cjs/helpers.js:14:16)
    at getServerImpl (/home/ulman/nodevenv/app/11/lib/node_modules/next/dist/server/next.js:59:71)
    at NextServer.createServer (/home/ulman/nodevenv/app/11/lib/node_modules/next/dist/server/next.js:127:44)
    at serverPromise.loadConfig.then (/home/ulman/nodevenv/app/11/lib/node_modules/next/dist/server/next.js:137:42)
(node:63800) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 3)