How to use useState to store multiple key objects?

I have a candlestick chart for a crypto and it has different timeframe for 1 minute, 30, minute, and so on. I currently have

const [data, setData] = useState[]
  useEffect(() => {

    const fetchPrice = async () => {
      const { data } = await axios.get(`/api/apii?slug=${poolName[0].pool_id}&timeframe=`${1h}``); // default is 1h

      const btcusd = data.data.results.map(
        (d) => {
          return {
            open: d.open,
            close: d.close,
            low: d.low,
            high: d.high,
            time: toDateStamp(d.datetime),
          };
        }
      );
      setData(btcusd)
    };

    fetchPrice()
  }, []);

The above is the initial state whenever a user visits which he or she will be shown a 1-hour chart data. So there is this onClick button which will fetch and set new state according to he chosen timeframe. It works if i setData for one timeframe but then if I set another timeframe, how do I separate them?

Object.assign value by using Key – JavaScript

I need to assign the below object to a specific object. as a example. how to assign this value object by using Object Key.

let testObject = {
    "001":{
        name:"John"
    },
    "002":{
        name: "Mike",
        age:35
    }
};

let newObject={
    age:35
};

//Output should be like this
//let testObject = {
//   "001":{
//        name:"John"
//    },
//    "002":{
//        name: "Mike",
//        age:35
//    }
//};

find max. leaf nodes of a binary tree

       50
     /     
   25      75
  /       / 
 15  27   62  79  

depth = 3
total nodes = 7
max leaf nodes = 4
       50
     /     
   25      75
  /       / 
 15  27   62  79  
 _    _   _    _ 
 1    1   1    1  = 4

in a case where the Tree is full this will find the total amount of leaf nodes, but if the tree is not full and only the depth of the tree is known how can i know the max. leaf nodes in that tree?

// if the tree is full
function total_leafs_nodes(node, level, mxlevel)
  {
      if (node == null) {
        return 1;
      }
      if (node.left == null && node.right == null)
          return 1;

      else if (level == mxlevel)
      {
          return 1;
      }
      return (total_leafs_nodes(node.left, level + 1, mxlevel)
      + total_leafs_nodes(node.right, level + 1, mxlevel));
  }

How do i make it display users name not @ since then it displays as unidentified if person dosen’t chat discord js v12

         let UserJSON = JSON.parse(Fs.readFileSync("./DataBase/users.json"));
        var Sorted = Object.entries(UserJSON).sort((a, b) => b[1].money- a[1].money);
        if (Sorted.length > 10) Sorted = Sorted.slice(0, 10);

        var LBString = "";
        Sorted.forEach(user => {
            LBString += `${client.users.cache.find(u => u.id == user[0])} - ${user[1].money}n`;
        });
        var LBEmbed = new Discord.MessageEmbed()
            .setColor('#FFFFFF')
            .setTitle("**Coins Leaderboard**")
            .setDescription(LBString);
        message.channel.send(LBEmbed);
        client.channels.cache.get('941016208940077086').send(`${message.author.username} has used $coinslb`)

{“599675959888707594”:{“money”:492,”lastbeg”:1644580691540,”lastwork”:1644580757380},”617797297924866093″:{“money”:0,”lastbeg”:0,”lastwork”:0}}

Using normal classes with vue composition api

how can I use framework-independent JavaScript class instances with reactive state on vue-composition-api.

Given following class:

// CounterService / counter-service.ts
//
// this is a normal javascript class which is independent of vue
export const counterService = new (class CounterService {
  private count: number = 0;

  // should cause all components that use `getCount` to react.
  addOne(): void {
    this.count++;
  }

  // should be reactive
  getCount(): number {
    return this.count;
  }
})()

Kind regards
Rozbeh Chiryai Sharahi

Generate a row with empty cells and a filled select

I need to generate in JavaScript a new row on a table but with empty cell without a select who need to be the same as the other row and i want the function to work no matter where is the input in the row
here’s my function to add empty row and cells

// Insert new row in the table when clicking on the + button
// tableid: Id of the element to update
function AddRows(tableid){
    var table = document.getElementById(tableid);
    var rowCount = table.rows.length;
    var cellCount = table.rows[0].cells.length;
    var row = table.insertRow(rowCount);
     var editContent = !row.isContentEditable;
        row.contentEditable = editContent;
    row.setAttribute('onkeyup', "Disabled();");
    row.setAttribute('onclick', "SetSelectedRow(this)");
    row.setAttribute('id', 'Combo_row'+(row.rowIndex - 1)); //Set the id of the row
    row.setAttribute('class', 'default');


    for(var i =0; i < cellCount; i++){
        var cell = 'cell'+i;
        cell = row.insertCell(i);
        cell.id = 'Combo_cell' + i
    }

}

I also found this function but she copy the rows and keep the content of every cells not only the select

/* function to add row with a select */
    function addSelect(SelectTableId) {
  var T = document.getElementById(SelectTableId);

  var R = document.querySelectorAll('tbody .AddRowClass')[0];

  var C = R.cloneNode(true);

  T.appendChild(C);

    }

Mobile Safari shows keyboard after page is reloaded

I am struggling with the mobile Safari browser. I am showing a page with a search form via Next.js. When I click into input keyboard shows. When the form is submitted I prevent native submit event. Instead of the native event, I have my own function where I grab all existing query parameters and add new query parameter parsed from the input.

Then I reload the page with router.push function. After the page is reloaded input has still its focus so Safari shows the keyboard.

I tried calling blur on input but when input is blurred then it is immediately called focus event by the browser. This implies showing the keyboard.

Thanks in advance for any answer.

Update React MobX store not more often than 1 second

Our frontend React application gets multiple updates per second via web sockets that we then update the MobX store with. This causes multiple component’s rerenders and whole application to perform very poor.

What would be the most elegant solution we can develop in order to make it perform better? Is it somehow possible to gather all the data we collect within one second in some kind of temporary place and then after one second update store with it? Or is there any other better solution that can prevent multiple rerenders?

Function empty object check

I need help this task
You have to implement function that will
Check that object is empty.
Object considered to be empty when it has no properties or all its properties are false (I.e. 0, “”, false …)

Validation form does not work and has a strange behavior

I’m learning to use forms and I have a javascript code that when I click submit the page shows an error but it does it in a microsecond so I cannot read it and the page refresh it self, I have no idea about what is wrong here.
Here is my html

    <body>
    <h3>Formulario</h3>
    <form name="formName" action="#" onsubmit="return validaciones()">       
    <h4>Nombre:</h4>
    <input type="text" onkeypress="validateName(this)" name="campoNombre">
    <br>
    <br>
    <select id="opciones" name="opciones">
    <br>
    <br>
      <option value="1">Primer valor</option>
      <option value="2">Segundo valor</option>
      <option value="3">Tercer valor</option> 
      <option value="4">Cuarto valor</option>
    </select>
    <br>
    <br>
    <input type="radio" value="si" name="pregunta" id="pregunta_si"/> SI 
    <input type="radio" value="no" name="pregunta" id="pregunta_no"/> NO
    <input type="radio" value="nsnc" name="pregunta" id="pregunta_nsnc"/> NS/NC
    <br>
    <br>
    <input type="checkbox" value="condiciones" name="condiciones" id="condiciones"/> He leído 
     y acepto las condiciones
    <input type="checkbox" value="privacidad" name="privacidad" id="privacidad"/> He leído la 
    política de privacidad
    <br>
    <br>
    <textarea id="parrafo"></textarea>
    <br>
    <br>
    <input type="submit" value="submit">
    </form>

Javascript code

    function validaciones() {
      let valorNombre = document.forms["formName"]["campoNombre"].value;
      if (valorNombre == "") {
      alert("Name must be filled out");
      console.log('Ingresaste tu nombre: ' + valorNombre)
      }

      var elementos = document.getElementsByName("pregunta");
      for(var i=0; i<elementos.length; i++) {
      console.log(" Elemento: " + elementos[i].value + "n Seleccionado: " + 
      elementos[i].checked)
      }
      return false
      };    

      function validateName(item){
      value = item.value;
      console.log(value)
      };

How to return the difference between two Objects having array and return the difference value dynamically

Let’s say I have two objects of arrays:

const newObj = {
      description: "abcd",
      type: "anything",
      list: [
        { id: 1, name: "Peter" },
        { id: 2, name: "Cathenna" },
        { id: 3, name: "Chiyo" }
      ]
    }

   const oldObj = {
      description: "wwew",
      type: "anything",
      list: [
        { id: 1, name: "Amara" },
        { id: 2, name: "shinzo" },
        { id: 3, name: "Chiyo" }
      ]
    }

I want to find all the updated data in newObj objects. Ex, description of oldObj is updated to “abcd” in newObj and in list name of two objects has been updated. So, my expected output is:

const extractObjDiff = {
      description: "abcd",
      list: [
        { id: 1, name: "Peter" },
        { id: 2, name: "Cathenna" }
      ]
    }

I have tried below code but it’s not working for array list.

function extractObjDiff(newObj, oldObj) {
  var r = {};
  for (var prop in newObj) {
    if (!oldObj.hasOwnProperty(prop)) {
      if (Array.isArray(newObj)) {
        r = newObj;
      } else {
        r[prop] = newObj[prop];
      }
    } else if (newObj[prop] === Object(newObj[prop])) {
      var difference = newObj[prop].length !== oldObj[prop].length ? newObj[prop] : extractObjDiff(newObj[prop], oldObj[prop], []);
      if (Object.keys(difference).length > 0) r[prop] = difference;
    } else if (newObj[prop] !== oldObj[prop]) {
      if (newObj[prop] === undefined)
        r[prop] = 'undefined';
      if (newObj[prop] === null)
        r[prop] = null;
      else if (typeof newObj[prop] === 'function')
        r[prop] = 'function';
      else if (typeof newObj[prop] === 'object')
        r[prop] = 'object'
      else if (Array.isArray(newObj))
        r = newObj;
      else
        r[prop] = newObj[prop];
    }
  }
  return r;
}

How to create an image file from Firebird blob data?

I have a Firebird DB table, which contains fields with image data (as blob sybtype -5). I need to get this data and convert it to an image file. Code example below creates a file (but size is very large, and while trying to open it – it is said, that file is not right BMP file). What am I missing here?

result[0].OBJ_IMAGE1((err, name, eventEmitter) => {
    if(err) throw err;

    let chunks = [];
    eventEmitter.on('data', chunk => {
        chunks.push(chunk);                
    });
    eventEmitter.once('end', () => {
        let buffer = Buffer.concat(chunks);         

        fs.writeFile('test.png',  buffer, err => {
            if(err) throw err;
            console.log('image file written');
        });            
    });
});

enter image description here

How do I catch ENOTFOUND/getaddrinfo (non-existent host) Error in Node.js Net?

I am writing a small status query library for Minecraft servers using a Net socket on nodejs.

According to the JSDoc and Node documentation, the error listener (socket.on('error', () => ...) should catch errors thrown and it does catch other errors such as when the server unexpectedly closes the connection. However I can not seem to catch host resolve errors which I have to.

client.connect(host.port, host.host, () => {
    //sending some
});

client.on('data', (chunk) => {
    //receiving some chunks
});

client.on('error', (err) => {
    client.end(() => reject(err));
});

here client is a new Net.Socket(); and the function is async returning a promise that either resolves to the final response or rejects errors.

However whenever I try to connect to a non-existent host my whole program crashes with an uncaught exception:

node:internal/process/promises:246
      triggerUncaughtException(err, true /* fromPromise */);
      ^

Error: getaddrinfo ENOTFOUND testhostmustfail12444.com
    at GetAddrInfoReqWrap.onlookup [as oncomplete] (node:dns:71:26) {
  errno: -3008,
  code: 'ENOTFOUND',
  syscall: 'getaddrinfo',
  hostname: 'testhostmustfail12444.com'
}

Ideally I want to catch this specific error and be able to return it to the caller function in order to use the information that the host is not resolvable!

Pdf Viewer download button not working as expected

I am trying to show pdf in iframe using dynamic form submit, that is working fine we see the pdf properly but now when any user wants to download it via clicking download but it is showing “.htm” file. Also when I do it outside iframe every thing working fine.

<iframe id="report" name="showreport" style="width: 100%;height: 100vh;border: 0;"></iframe>

to dynamically provide pdf to iframe we are creating dynamic form as below:

const mapForm = document.createElement('form');
mapForm.target = "showreport";
mapForm.method = 'POST';
mapForm.action = url;

const mapInput = document.createElement('input');
mapInput.type = 'text';
mapInput.name = 'user';
mapInput.value = 'Admin';

mapForm.appendChild(mapInput);
document.body.appendChild(mapForm);

// Just submit
mapForm.submit();

But when we hit download button it is shows “html” instead of “pdf”.

enter image description here