can’t resolve getaddrinfo EAI_AGAIN error

I’m having this error after 20 min of running my NodeJS app, and it’s keeps appearing after that.. it’s hosted at AWS (EC2) I searched for getaddrinfo EAI_AGAIN errors, it’s probably caused by DNS issue, but i have no idea how to solve it.

WebSocket error: [object Object]
ErrorEvent {
  target:
   WebSocket {
     _events:
      [Object: null prototype] {
        message: [Function: incoming],
        disconnect: [Function],
        close: [Function: close],
        error: [Function] },
     _eventsCount: 4,
     _maxListeners: undefined,
     _binaryType: 'nodebuffer',
     _closeCode: 1006,
     _closeFrameReceived: false,
     _closeFrameSent: false,
     _closeMessage: '',
     _closeTimer: null,
     _extensions: {},
     _protocol: '',
     _readyState: 2,
     _receiver: null,
     _sender: null,
     _socket: null,
     _bufferedAmount: 0,
     _isServer: false,
     _redirects: 0,
     _url: 'wss://stream.binance.com:9443/ws/!bookTicker',
     _req: null },
  type: 'error',
  message:
   'getaddrinfo EAI_AGAIN stream.binance.com stream.binance.com:9443',
  error:
   { Error: getaddrinfo EAI_AGAIN stream.binance.com stream.binance.com:9443
       at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:56:26)
     errno: 'EAI_AGAIN',
     code: 'EAI_AGAIN',
     syscall: 'getaddrinfo',
     hostname: 'stream.binance.com',
     host: 'stream.binance.com',
     port: '9443' } }

Why does my text disappear in javascript?

Here is my code

const p = document.getElementById("looper");
function shiftright() {
    let temp = new String();
    for(var i = 1; i < p.textContent.length - 1; i++)
    {
        temp[i] = p[i-1];
    }
    temp[0] = p.textContent[p.textContent.length-1];
    p.textContent = temp;
}
window.setInterval(shiftright, 1000);

Whenever I run it the text within the element disappears once the interval expires. I am trying to make the text loop around.

Displaying PDF created with HttpContext.Current.Response in a div in asp.net page

My requirement is generating a itextsharp pdf file in button_click event on the fly without saving it in Local disk and there should be no save dialogue . Once the PDF is created we have to display it inside a div tag within the same asp.net page in a small size.
Below is the code in which I am able to generate the PDF:

protected void Button2_Click(object sender, EventArgs e)
    {
        string PDFfileName = Path.GetFileNameWithoutExtension(fileName);
        HttpContext.Current.Response.ContentType = "application/pdf";
        HttpContext.Current.Response.AddHeader("content-disposition", "inline;filename= " + 
        PDFfileName + ".pdf"); 
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Document pdfDoc = new Document(); PdfWriter.GetInstance(pdfDoc, 
        HttpContext.Current.Response.OutputStream); 
        pdfDoc.Open();
        pdfDoc.Close();
        HttpContext.Current.Response.Write(pdfDoc);
        HttpContext.Current.Response.End();
    }

Now the challenge which I am facing:

  1. The generated PDF is getting opened in entire page like redirection but the URL remains the same.(If we click back button of browser, it is going to the page where I clicked the button to generate pdf)
    2)I am not able to display the generated PDF inside the div as a small part.

Solution which I want is the same pdf which is generated without saving it in disk should directly appear inside div tag in middle of the page and also it should not show any save dialogue message.

Please help me.

Stuck on algorithmic string task in js [closed]

I need help on that string task for a intership program(i have already handed over the tasks),but i really stuck in the start of the task.
enter image description here

    const arr = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];

const getValue = (temp) => {
    for (i = 0; i < 10; i++) {
        if (temp === arr[i]) {
            return i;
        }
    }
    return;
}


const charToDigit = (digit) => {
    let index = digit - 48;
    return arr[index];
}

}
console.log(solve(“fiveplusfive”));

How can I prevent loading images from stuttering?

I want to indicate that the page is loading, but even the loading animation stutters because many scripts are already running.

Can i write the code to prioritize Animation over other actions?

Please understand that I cannot show the actual code.
That ‘s too much .

All I can say is that I am using React.

I tried animation in CSS, gif and svg.
All of theses are stutters.

How to parse duplicate data in a list of objects based on multiple keys having the same value, where one key has a value of an array of objects

As the title states, I am trying to store a list of duplicate objects based on specific key:value pairs being the same.

The goal is to parse the information and return a list of duplicate items. A duplicate item is when the ID , title, items are a match.
The main problem I’m having with this is that inside each object, one of the keys to compare is an array holding a list of objects as values.

How would you go about this problem, looping through an array of objects to determine if the items array are duplicate?

Below is just a small example of the JSON data.

Should return :
whole object of pk:”0002″ and pk”0003″ since they are duplicate. Should not return Object pk:”0001″ and pk “0004” since their array of items:[{}] are not equal.

My attempt can determine if the ID and titles are a match but I can’t get the items to match:

var data = [
{ pk: "0001", ID: "1A", title: "Material 15", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, { title: "EXTRA", value: "55" }, ], }, 
{ pk: "0002", ID: "1A", title: "Material 1", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
{ pk: "0003", ID: "1A", title: "Material 1", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
{ pk: "0004", ID: "1A", title: "Material 15", items: [{ title: "Info", value: "" }, { title: "Type", value: "" }, ], }, 
];


let duplicates = [];
data.forEach((el, i) => {
  data.forEach((element, index) => {
    if (i === index) return null;
    if (element.ID === el.ID && element.title === el.title) {
      if (!duplicates.includes(el)) {
        //Issue here -> I want to compare the array of items but im not sure how to ?
        //Attempt:
        // I think I understand that this is wrong due to the indexes not sure how you would find this ?

        // if (element.items[i] === el.items[i]) {
        //   duplicates.push(el);
        //   console.log("Test");
        // }

        duplicates.push(el);
      }
    }
  });
});
console.log("duplicates", duplicates);

Is it possible to execute code after responding on a Cloudflare Worker?

I am starting workig with Cloudflare and I a m facing one of my first challenges.

I have some cached data, that I retrieve once I get it requested via a ‘fetch’ event. I would like after responding to this fetch, update the cache data that was requested.

I get this data from a third party API.

The workflow would be the following.

  1. Get the request and respond with cthe old cached item
  2. Refresh the cache for the requested item afterwards

I was thinking about using a cron timers and filling up a queue of items to update, but I think this list will not be persisted.

The ideal way would be having some sort of custom event I can register and fire just before I return the response, so while I am returning the old cached data the refresh cache job is already executing.

My current code is working (2 is not implemented yet), and I am not posting code, because I just would like to know some theories about how could this refresh be done.

Thanks in advance!

Login in Cypress without hardcoding

I don’t know how to rewrite this syntax correctly, because I get an error like “Invalid left-hand side in assignment expression.”

Cypress.Commands.add('logintest', (env,username) => {
    env(staging) = cy.visit('link')
    env(live) = cy.visit('link') 

    username (userone =
      cy.get('input[name="Parameter.UserName"]').type('userone'),
      cy.get('input[name="Parameter.Password"]').type('password')
    )
})

Where to import stylesheets for components in (`create-react-app`) React.js app?

I have created a new React.js app using create-react-app.

For each component (e.g. src/components/ComponentX.js), I have created a separate stylesheet (src/styles/ComponentX.css), and imported it as follows import "../styles/ComponentX.css".

This has in turn resulted in a separate <style>...</style> section for each imported stylesheet on every page. Thus, the stylesheets are global (which makes sense for SPA?), albeit not concatenated as described here:

In development, expressing dependencies this way allows your styles to be reloaded on the fly as you edit them. In production, all CSS files will be concatenated into a single minified .css file in the build output.

Since it doesn’t seem to affect the functionality of the React.js app, where stylesheets are imported, where should I import my stylesheets? Local to the components or in src/index.js?

Bonus: What about components sharing the same stylesheet? Should both import it, if following the local approach?

Map current array with values by index from another array in JavaScript

Let’s imagine I have to arrays:

const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const array2 = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];

array2.map((elem, index) => {
  // Looking here to return the value from array1 by index
});

In array2 I am looking to return value from array1, by the index position, but just in range 1 -10. The idea is that it should go in a kind of circle where start value is 1 and end is 10.

More examples of how it should work:

  • Index 1 from array2 -> return 1 from array1
  • Index 10 from array2 -> return 10 from array1
  • Index 12 from array2 -> return 2 from array1
  • Index 20 from array2 -> return 10 from array1
  • Index 999 from array2 -> return 9 from array1
  • Index 1225 from array2 -> return 5 from array1

cannot setState in onInputChange fuction in React-select?

I am using React-select Autocomplete search like the below screenshot. but I cannot collect input field value. there is no getting error or something. but I cannot type more than 1 letter after setState.

but only log this input value work log show porperly.

enter image description here

<AutoCompleteSearch
  isLoading={isLoading}
  options={filterOptions || []}
  className='w-full mr-3'
  onChange={(selectOption: any) => {
      handleFilterOptionChange(selectOption)
  }}
  onInputChange={(inputValue: any) => {
      console.log(event) //work properly
      setSelectedKeyWord(inputValue) //after added this not work cannot type and not set state
  }}
/>

in Storybook use component

import React, { FC, useState } from 'react'
import Select, { components } from 'react-select'
import CN from 'classnames'

export interface AutoCompleteSearchProps {
  [x: string]: any
  defaultValue?: { id: any; value: any; label: string | number }
  isClearable?: boolean | true
  isDisabled?: boolean
  isLoading?: boolean | false
  isMultiple?: boolean | false
  isSearchable?: boolean | true
  onChange?: any
  onInputChange?: any
  options: { id: any; value: any; label: string | number }[]
  placeHolder?: string | 'Search'
  value?: { id: any; value: any; label: string | number }
}

export const AutoCompleteSearch: FC<AutoCompleteSearchProps> = ({
  className,
  defaultValue,
  isClearable,
  isLoading,
  isMultiple,
  isSearchable,
  onInputChange,
  onChange,
  options,
  placeHolder,
  value,
  ...restProps
}: AutoCompleteSearchProps) => {
  const AutoCompleteSearchClasses = CN(`auto-complete-search`, className, {})

  const [keyword, setKeyWord] = useState('')

  function ValueContainer({ children, ...props }: any) {
    return (
      components.ValueContainer && (
        <components.ValueContainer {...props}>
          {!!children && (
            <i
              className='ri-search-line ri-lg text-N-500'
              aria-hidden='true'
              style={{ position: 'absolute', left: 14 }}
            />
          )}
          {children}
        </components.ValueContainer>
      )
    )
  }

  const styles = {
    valueContainer: (base: any) => ({
      ...base,
      paddingLeft: 40,
    }),
    control: (base: any) => ({
      ...base,
      'border': '1px solid #CCD6E1',
      'borderRadius': '3px',
      'boxShadow': '0px 1px 2px rgba(0, 45, 71, 0.05)',
      '&:hover': {
        border: '1px solid #CCD6E1',
      },
      '&:focus': {
        border: '1px solid #3570AB',
        boxShadow:
          '0px 0px 4px rgba(0, 89, 141, 0.24), inset 0px 0px 4px rgba(0, 58, 89, 0.5)',
      },
    }),
    menuPortal: (base: any) => ({ ...base, zIndex: 9999 }),
    option: (base: any, { isFocused }: any) => ({
      ...base,
      backgroundColor: isFocused ? '#EEF3F8' : '#fff',
      color: '#2E3849',
    }),
  }

  return (
    <div className={AutoCompleteSearchClasses} {...restProps}>
      <Select
        components={{
          ValueContainer,
          DropdownIndicator: () => null,
          IndicatorSeparator: () => null,
        }}
        defaultValue={defaultValue}
        isClearable={isClearable}
        isSearchable={isSearchable}
        isLoading={isLoading}
        isMulti={isMultiple}
        options={options}
        onChange={onChange}
        onInputChange={onInputChange}
        menuPosition='fixed'
        placeholder={
          <span className='select-placeholder-text text-N-500'>
            {placeHolder}
          </span>
        }
        styles={styles}
        value={value}
      />
    </div>
  )
}

AutoCompleteSearch.defaultProps = {
  defaultValue: undefined,
  isClearable: true,
  isSearchable: true,
  isLoading: false,
  isMultiple: false,
  onChange: () => {},
  onInputChange: () => {},
  options: [],
  placeHolder: 'Search',
  value: undefined,
}

export default AutoCompleteSearch

exactly I want to catch React input type value and set it useState.
anyone can help me or can you guys know another method do this?

Getting Undefined When Trying to Request Const Data From Reactjs File in my NodeJS Express API

I have a file named check-rates that holds some useStates() that the users will input in order for me to execute and return for them an estimated value for their shipment by using DHL API.

In my nodejs express server, I am trying to access these useStates() with req.body but when I console log the constants I always get them as undefined. I need these values that the user enters so that the API becomes dynamic for each customer/user that uses my website and not fixed values (as I have them now.)

What am I doing wrong?

here is my code:

Check-Rates.js:

const [fromCountires,setFromCountries] = useState("");
const [fromCountriesCode,setFromCountriesCode] = useState("");
const [fromCountriesCapital,setFromCountriesCapital] = useState("");
const [fromPostalCode,setFromPostalCode] = useState("");
const [toCountries,setToCountries] = useState("");
const [toCountriesCode,setToCountriesCode] = useState("");
const [toCountriesCapital,setToCountriesCapital] = useState("");
const [weight,setWeight] = useState("");
const [data,setData] = useState(null);

 const getRateEstimate = () => {
    
        axios.get('http://localhost:3001/api/dhl').then(response => {
            console.log(response)
            setData(response.data);
        }).catch(e => {
            console.log(e)
        });
    }

return (
 //example of how i am setting my needed useStates...
<Form.Group controlId="exampleForm.ControlInput1">
   <Form.Label className={'fw-bold'}>Weight</Form.Label>
   <Form.Control type="text" placeholder="" onChange={(e)=> {
     setWeight(e.target.value)}}/>
 </Form.Group>

  <button className={'btn-orange fw-bold py-2 px-3 px-4 rounded getRateBtn'}
  type={'submit'} onClick={getRateEstimate}> Check
  </button>
)

NodeJS Server

index.js:

app.get('/api/dhl', (req, res) => {

    const accountNum = req.body.accountNum
    const fromCountriesCode = req.body.fromCountriesCode
    const fromCountriesCapital = req.body.fromCountriesCapital
    const toCountriesCode = req.body.toCountriesCode
    const toCountriesCapital = req.body.toCountriesCapital
    const weight = req.body.weight
    const plannedShippingDate = req.body.date
    const len = "5"
    const width = "5"
    const height = "5"
    const isCustomsDeclarable = 'false'
    const unitOfMeasurement = 'metric'

    console.log(weight)//logs undefined
    console.log(fromCountriesCapital)//logs undefined

    var options = { method: 'POST',
    url: 'https://express.api.dhl.com/mydhlapi/test/rates',
    headers: 
     { 'postman-token': '',
       'cache-control': 'no-cache',
       authorization: 'Basic AUTH',
       'content-type': 'application/json' },
    body: 
     { customerDetails: 
        { shipperDetails: 
           { postalCode: '19010',
             cityName: 'Dubai',//need this
             countryCode: 'BH',//need this
             addressLine1: '0' },//end Shipper DETAILS
          receiverDetails: 
           { postalCode: '76321',
             cityName: 'Riyadh',//need this
             addressLine1: '0',
             countryCode: 'SA' }//end Reciever DETAILS
             },
       accounts: [ { typeCode: 'shipper', number: 'myAccountNumbeer' } ],
       plannedShippingDateAndTime: '2021-08-25T13:00:00GMT+00:00',//need thiss
       unitOfMeasurement: 'metric',
       isCustomsDeclarable: true,
       monetaryAmount: [ { typeCode: 'declaredValue', value: 10, currency: 'BHD' } ],
       requestAllValueAddedServices: false,
       returnStandardProductsOnly: false,
       nextBusinessDay: false,
       packages: [ { weight: 25, dimensions: { length: 5, width: 5, height: 5 } } ] },
    json: true };
  
  request(options, function (error, response, body) {
    if (error) throw new Error(error);
    res.send(body)
    console.log(body);
  });
});

Getting PostgresSQL 42703 error (invalid column error)

I am working on a React project with PostgreSQL database, this is the first time I am using it, and I am getting 42703 error on querying a particular column.

Below is the code I have written to query

const getList = (userId) => {

    return new Promise(function (resolve, reject) {
        pool.query(`SELECT items FROM public."user" where id=${userId}`, (error, results) => {
            if (error) {
                reject(error)
            }
            resolve(results);
        })
    })
}

I have defined this getList function and then I am making an api call to call this function by passing the userId like this

app.get(`/expenses`, verifySession(), async (req, res) => {
    const userId = req.session.userId;
    database.getList(userId)
        .then(response => {
            res.status(200).send(response);
        })
        .catch(error => {
            res.status(500).send(error);
        })
})

I even tried passing the userId directly as shown below , still it gives me the same error , which probably means I am querying in a wrong way

app.get(`/expenses`, verifySession(), async (req, res) => {
    //const userId = req.session.userId;
    database.getList('17a6dea6-a63e-4da7-9910-df7eddb672e6')
        .then(response => {
            res.status(200).send(response);
        })
        .catch(error => {
            res.status(500).send(error);
        })
})

Only when I directly write the string in the query it works properly like this

const getList = (userId) => {

    return new Promise(function (resolve, reject) {
        pool.query(`SELECT items FROM public."user" where id='17a6dea6-a63e-4da7-9910-df7eddb672e6'`, (error, results) => {
            if (error) {
                reject(error)
            }
            resolve(results);
        })
    })
}

Can someone please help we with what is exactly going wrong and if my syntax is correct or not ?