How to push key as iterative value in js?

Hi i have a two for loop contains checking the each loop length and push into key value pair of array

for (var i=0; i<allTextLines.length; i++) {
        var data = allTextLines[i];
        if (data.length == headers.length) {

            var tarr = [];
            for (var j=0; j<headers.length; j++) 
            {
              
               ****tarr.push({headers[j]:data[j]})****
            }
            
             lines.push(tarr);

        }
        
    } 

i need to push headers[j] as key but i can’t.How to do that in JS ? I’m literally new . please bare me.THanks

React – Rerender a class component after the window pathname change

Greeting guys, I have an issue with a class component (that handle a list), the first time I mount the component works without any issue showcasing the expected values, unfortunately when I change the pathname while inside the class component it doesn’t updated.

render() {
        const service = this.state.services.find(service => service.link === window.location.pathname)
        if (service) {
            return <Service {...service} />
        }
      }

I would like to know if there is something to keep track of windows pathname in real time and maybe use the forceUpdate(); to refresh the component.

let me know if you need more information!

How to turn an object with object into array of objects [duplicate]

I want to turn an object with objects into an array of objects in javascript.

The objects looks like that

    
{
  "0": {
    "TASKCOUNT": 1,
    "ORDERID": null,
    "WORKSTATION": 1,
    "JOBSTATE": "finished"
  },
  "1": {
    "TASKCOUNT": 1,
    "ORDERID": null,
    "WORKSTATION": 1,
    "JOBSTATE": "finished"
  },
  "2": {
    "TASKCOUNT": 1,
    "ORDERID": null,
    "WORKSTATION": 1,
    "JOBSTATE": "finished"
  }
}

The Keys of the object could be just ignored, so that I have an outcome like that

[
 {
    "TASKCOUNT": 1,
    "ORDERID": null,
    "WORKSTATION": 1,
    "JOBSTATE": "finished"
  },
  {
    "TASKCOUNT": 1,
    "ORDERID": null,
    "WORKSTATION": 1,
    "JOBSTATE": "finished"
  },
  {
    "TASKCOUNT": 1,
    "ORDERID": null,
    "WORKSTATION": 1,
    "JOBSTATE": "finished"
  }
]

Thanks for any help! 

How to change title font size for excel export Datatable?

I need to add customized title for excel file exported from Datatable.
Tried this from a stackoverflow answer but it applies to whole sheet.

$("#datatable").DataTable({
          dom: "lBfrtip",
          buttons: [
            {
              extend: "excelHtml5",
              title: "Audit Trail Report",
              messageTop: `From ${this.start_date} To ${this.end_date}`,
              customize: function (xlsx) {
                var sheet = xlsx.xl["styles.xml"];
                var tagName = sheet.getElementsByTagName("sz");
                for (let i = 0; i < tagName.length; i++) {
                  tagName[i].setAttribute("val", "22");
                }
              },
            },
            {
              extend: "pdf",
              title: "Audit Trail Report",
              messageTop: `From ${this.start_date} To ${this.end_date}`,
            },
          ],
          searching: false,
        })

How to Maintain the HTML5 Video Aspect Ratio according to Div Size

I am using react with typescript. In my project, I have JSON data that contains the information of the faces detected on the video. Now I am creating bounding boxes on faces in the video, but I am facing one problem is that the bounding box information is for the video resolution 3840 x 2160, but my div has height is 500px and width is 800px and I am also using object-fill property as fill. Now when I am rendering the bounding boxes on video it displays out from the div.

How to do this so that bounding boxes display an accurate position on the div.

sample JSON data look like this:

[
  { "frame": 0, "x": 332, "y": 624, "width": 291, "height": 306 },
  { "frame": 1, "x": 1724, "y": 539, "width": 241, "height": 309 },
  { "frame": 2, "x": 2943, "y": 503, "width": 266, "height": 354 }

]

and my code:

<div ref={divRef}>
        <Video videoSource={source} ref={vRef}/>
        <svg id="svg" ref={sRef}>
        {!flag &&
            boundingBoxData.filter((x: IDataFrame) => currentFrame === x.frame).map((y: IData) => {
                return <BoundingBox x={y.x} y={y.y} height={y.height} width={y.width}/>
            })
        }
        </svg>
      </div>

I Want to retain the placeholder on left side while typing any kind of text in TextInput Field in React Native

Here is my code…please check the code and guide me….what i have to do for that

            <Input
            containerStyle={tailwind('mt-4')}
            label="Item Price"
            labelStyle={{fontWeight: '800'}}
            theme="secondary"
            keyboardType={'numeric'}
            type="underline"
            placeholder="$"
            clear={true}
            onBlur={onBlur}
            value={price}
            onChangeText={text => setPrice(text)}
            errorMessage={
              !/d+((,d+)+)?(.d+)?(.d+)?(,d+)?/.test(price) && price
                ? 'Invalid Price'
                : null
            }
          /> 
        )}
        name={'price'}

How to compare object to object from file in node?

I’m trying to compare an object that im receiving from a socket.io event, against an object thats in a file on my computer. I have most of it setup, i can get it to save to the file when it finds new data, however, the data seems to be string overlapping and im not sure why/how(see picture)

enter image description here

I tried reading this https://dmitripavlutin.com/how-to-compare-objects-in-javascript/ to see if it was an issue with reading the file, or actually comparing the two objects to see which item is new (which would be coming from the socket.io data)

        console.log(collection)
        const test = new Promise((resolve,reject) => {
            fs.access(collection, fs.F_OK, function (err) { //initial file access
                if (!err) {
                    fs.readFile(collection, 'utf8', (err, data) => { // read file for data,
                        if (err) throw err;
                        var dat = JSON.parse(data) 
                        var found = []
                          for(i in dat){
                              found.push(JSON.stringify(dat[i])) // This is the data that already exists, this is coming from the file.
                          }
                          
                          resolve(found)
                        // resolve
                    })
                }
            })
        })
            
    test.then(function(data){
        //console.log(data) // This is the data from above
        for(i in NFTCollection){ // NFTData that was just recieved from the https request (sent from socket.io)
            var item = JSON.stringify(NFTCollection[i]) // This is each new item
            var target = client.channels.cache
            //console.log(data)
            if(!data.includes(item)){ // This is where i have the issue, how do i compare the object to the object thats in the file?
                console.log("Found item! " + item) 
                var parsedItem = JSON.parse(item)
                data.push(JSON.parse(item))
            }
         
            //console.log(item)
        }
        fs.writeFileSync(collection,JSON.stringify(data)) // saves the data from, but it keeps overlapping? 
        })
    })
}) 

I commented in my code what each step is trying to accomplish, the issue is at the end. when im comparing if the items from the socket.io data, exist within the data that is the node.fs file.

View the file from base64 string instead of varbinary

This is my simple program on downloading file from a varbinary string on click.

Controller:

  public ActionResult Download(string StudentID, string SQNC)
      {
         string query = "exec spToGetVarbinaryString'" + StudentID + "','" + SQNC + "' ";
         string dataStr = GlobalFunction.DataTableToJSON(GlobalFunction.TableFromMSSQL(dbname, query));
         dynamic data = JsonConvert.DeserializeObject(dataStr);
         byte[] file = data[0].ImgVarbinary;

         return File(file, System.Net.Mime.MediaTypeNames.Application.Octet, (string)data[0].FileName);
      }

how I download the File:

<a type="button" href="ControllerName/Download?StudentID=${row.StudentID}&SQNC=${row.SQNC}" class="btn btn-primary btn-sm active" role="button" aria-pressed="true">View File</a>

Now, I want the file instead of being downloaded on click, It will appear on tab or new. I tried the method of converting my Varbinary to Base64 string, but it doesnt read the PDF file for this example below.

From VarBinary to Base64 in SQL

    update a set a.ImgStr=baze64
    from #mytemptable
    cross apply (select ImgVarbinary as '*' for xml path('')) T (baze64)
    where a.ImgVarbinary is not null

Displaying Base64 PDF File (Display doesn’t work)

<iframe width="500" height="500"
            src="data:application/pdf;base64,<base64stringhere>"

I found a sample base64 data in this JSFiddle link, I tried it on local and it works.

Image example (left one: my base64 string. Right one: base64 from the js fiddle)
enter image description here

How can I do this and why my base64 string isn’t working well? Thanks for answering.

Chrome extension proxy authentication

I’ve got problem in proxy authentication using chrome extension (due to problems with v3 my code is based on manifest v2). The connection works using the following curl command:

curl -v -x https://11.111.11.111:222 https://www.google.com/ --proxy-header "proxy-authorization: Basic abc" --proxy-insecure

And I tried to implement it in extension. Here’s what I have in background.js file:

chrome.runtime.onStartup.addListener(() => {
    const config = {
            mode: 'fixed_servers',
            rules: {
                singleProxy: {
                    host: '11.111.11.111',
                    port: 222,
                    scheme: 'https',
                },
            },
        }

        chrome.proxy.settings.set({ value: config, scope: 'regular' })
})

chrome.webRequest.onBeforeSendHeaders.addListener(
    (details) => {
        const requestHeaders = details.requestHeaders || []
        requestHeaders.push({
            name: 'proxy-authorization',
            value: 'Basic abc',
        })

        return { requestHeaders }
    },
    { urls: ['<all_urls>'] },
    ['blocking', 'requestHeaders', 'extraHeaders']
)

chrome.webRequest.onSendHeaders.addListener(
    (details) => {
        console.log('sending', details)
        return details
    },
    { urls: ['<all_urls>'] },
    ['requestHeaders', 'extraHeaders']
)

I have the following permissions in manifest.json:

"permissions": [
        "cookies",
        "storage",
        "tabs",
        "activeTab",
        "proxy",
        "webRequest",
        "webRequestBlocking",
        "<all_urls>"
    ]

And these are the headers that are printed in onSendHeaders function:

enter image description here

You see that proxy-authorization header is present. But I get ERR_PROXY_CERTIFICATE_INVALID while trying to browse any page. Proxy headers should be set in a different way? Because I use --proxy-header flag in the curl command, not --header.

PS. I tried using the method that is mentioned many times:

chrome.webRequest.onAuthRequired.addListener(function(details, callbackFn) {
    callbackFn({
        authCredentials: { username: username, password: password }
    });
},{urls: ["<all_urls>"]},['asyncBlocking']);

too, but this function is never called (I put console.log inside).

React useContext() default value has not changed even I provide a value

Why is the UserContext default value has not changed even I specify a value in <UserContext.Provider>? How can I override the default value of the Context?

this is the App.jsx

import './App.css';
import React, { createContext } from 'react';
import ComponentB from './components/hooks/context/ComponentC';

function App() {
  return (
    <div className="App">
      <ComponentB />
    </div>
  );
}

export default App;

this is the ComponentB

import React, { createContext, useState } from 'react';
import ComponentC from './ComponentC';

export const UserContext = React.createContext('default');
export const ChannelContext = React.createContext('default');

const provider = UserContext.Provider;

function ComponentB() {
  return (
    <div>
      <provider value='Username'>
        <ComponentC />
      </provider>
    </div>
  );
}

export default ComponentB;

this is the ComponentC

import React from 'react';
import ComponentE from './ComponentE';

const ComponentC = () => {
  return <ComponentE />;
}

export default ComponentC;

this is the ComponentE

import React, { Component, useContext } from 'react';
import { UserContext, ChannelContext } from './ComponentB';

const ComponentE = () => {
  const username = useContext(UserContext);
  const channel = useContext(ChannelContext);

  return <div>username : {username} channel : {channel}</div>;
}

export default ComponentE;

How to stream the streamed data from Websocket to another Websocket?

This is the image to help you understand what are the problems. I am trying to stream my data being streamed by Websocket to another Websocket.

ws.on('message', function (msg){
let off = msg.data.search(/st5/)
if (off !== -1) {
    //console.log(`${msg.data.slice(83,85)}`)
    if (msg.data.slice(83) === ',') {
        console.log(`${msg.data.slice(84,89)}`)



    }
    else {
            console.log(`${msg.data.slice(83,88)}`)
            var k = msg.data.slice(83,88)

            wss.on('connection', wss => {
                wss.send(`${k}`)

            })


    }
}
else{
    if (msg.data.search('~m~~h~') !== -1) {
        ws.send(`${msg.data}`)
        console.log(`TX: ${msg.data}`)
    }
  }
})

When the client connects to the websocket all the data I have received are automatically sent at the exactly same time. I want to keep sending my data not at the connection time with the load of data. Is there anything I have to do with wss.on(‘connection’)?

React: How do I use values from an object’s specific key?

I am new to React and am trying to figure out how to return a particular objects entry by it’s key.

So far, I have an object as such:

const questions = [
  {
    id: '1',
    section: 's1',
    answers: [
      "answer a",
      "answer b",
      "answer c",
      "answer d",
    ]
  },
  {
    id: '2',
    title: 'Question 2',
    answers: [
      "answer a",
      "answer b",
      "answer c",
      "answer d",
    ]
  },
  //etc

which I am currently iterating through and using parts of as props in a component, eg:

  return (
    <div>
      {questions.map((question) => (
        <Question
          key={question.id}
          questionNum={question.id}
          title={question.title}
          answers={question.answers}
        />
      ))}
    </div>
  );

This works fine and as expected.

But now I need to modify this so it only returns the values of 1 given particular key in the object.

I’ve been searching and experimenting with .get() but to be honest I’m really stumped with how to do this.

Would anyone know the best way to approach this?