Why am I not getting the innerText?

I am trying to retrieve the string for the number of google searches in order to use it with a cypress test.
Google search results

This is the code I am trying to use to get it.
It retrieves null.

let text = cy.get('#result-stats').innerText
    cy.log(text)

I have also tried with several other methods, like innerHtml or textContent.
I have tried getting the whole div, invoking the text, invoking the val, getting the children…
Nothing works…

What I want to get is the string “About 8.200.000.000.000 results”. At this point I don’t care if the HTML syntax is present or not, I just want the number.

Cannot add value to a nested array

I have the following array values at initial state:

const [chartData, setChartData] = useState([["Type", "Counts"]]);

And retrieve the following values from server:

response.data:Object

Bird: 4
Cat: 8
Dog: 5

I need the this array:

const piedata = [
  ["Type", "Counts"],
  ["Bird", 4],
  ["Cat", 8],
  ["Dog", 5]
];

I am trying something like that, but in each case I add these 3 elements as a 2nd element of the outer list, e.g. : [["Type", "Counts"], [["Bird", 4], ["Cat", 8], ["Dog", 5]]];


getData("/pets", body)
      .then((response) => {
       let array = Object.entries(response.data).map(([k, v]) => "[" + k + "," + v +"],")
       chartData.push(array)
      })

So, what is the proper way to achieve this? And should I use both setChartData hook and push element to outer array?

how can i create an array from another array?

I need to create an array like this:

var routes: [{
  locations: [
    [40.749825, -73.090443],
    [42.743244, -71.594375],
    [37.058435, -74.903842]
  ],
  color: 'red',
  opacity: 1
}]

starting from this:

var locations: [
  {location: "40.749825, -73.090443"},
  {location: "42.743244, -71.594375"},
  {location: "37.058435, -74.903842"}
]

using javascript/jquery.
Can anybody help me please?

thank you

React state hook ignores state change

Since i’m currently building an application which is both reliant to the TomTomAPI, and React, i’m not sure if i’m in the right place to get this question out, but ill try my luck i guess?

I’ve got an application, where if i select a certain space on my tomtom map, it shows some details about this selection. However i’ve got 3 issues. The first one is that once I try to select more than 1 item, it will only show the first selection, until after i’ve updated one of my selections. The first is that once I try to update my selection, the details don’t seem to update. The second issue is that once I delete a selection of mine, and I select a different part of the map, it somehow shows details of the selections I had previously deleted. I’m going to put some screenshots in for you to visualise my problem.

Application as normal

2 Selections, only 1 with details

2 selections after updating 1, however these details are incorrect

Deleted all selections, but somehow, still one of the selection details is there

Placed 1 selection, but somehow i now have 3 sets of details

My code

let [TestList, setTestList] = useState([])
    function deleteFeatures(features, map) {
    features.forEach(function(feature) {
        shapes = shapes.filter(function(shape) {
            if (feature.id === shape.id) {
                var object = null;
                shapeList.forEach(element => {
                    if(element.id === shape.id){
                        object = element;
                        innerstring = innerstring.replace(element.HTMLText, "")
                    }
                });
                // document.getElementById('listOfSelected').innerHTML = innerstring;
                shapeList[object.teller].HTMLText = ""
                let punten = shapeList[object.teller].punten
                punten.forEach(punt => {
                    filterAddMarker(punt, map)
                });
                shape.popup.remove();
                document.getElementById("markersOver").innerHTML = "<h1>Nog "+ markers.length +" locaties over</h1>"

                var tussenlijst = [];
                        TestList.forEach(element2 => {
                            if(element2.id === shape.id){
                                console.log(element2);
                                tussenlijst.push(element2)
                            }
                        });
                        var tussenlijst2 = []
                        console.log("Tussenlijst")
                        console.log(tussenlijst)
                        console.log("")
                        tussenlijst.forEach(x => {
                            tussenlijst2 = TestList.filter(y => y.id !== x.id)
                        })
                        console.log("Tussenlijst2")
                        console.log(tussenlijst2)
                        console.log("")

                        console.log("Testlist")
                        console.log(TestList)
                        setTestList(tussenlijst2)
                        console.log(TestList)

                
                return false;
            } else {
                return true;
            }
        });
    });

    innerstring.replace()
    // updateAndShowTotalArea();
}

function Shape(id, coordinates, map) {
    let punten = pointCheck(coordinates)
    let puntenlengte = punten.length
    this.id = id;
    this.area = calcAreaFromCoordinates(coordinates);
    this.popup = new tt.Popup({
        closeButton: false,
        closeOnClick: false,
        className: 'tt-popup -black',
        anchor: 'top'
    })
        .setLngLat(calculatePopupPosition(coordinates))
        .setHTML(id)
        .addTo(map);
    let HTMLText = getAutoHTML(this.id, punten, areaToString(this.area))

    // let tussenlijst = TestList;
    TestList.push({id: this.id, Punten: punten, PuntenLengte: puntenlengte, AreaString: areaToString(this.area)})
    setTestList(TestList)
    setCounter(counter + 1)
    switchTheKey()
    punten.forEach(punt => {
        filterRemoveMarker(punt)
    });

    shapeList.push({id, HTMLText, teller, punten})
    innerstring += HTMLText
    // document.getElementById('listOfSelected').innerHTML = innerstring;
    document.getElementById("markersOver").innerHTML = "<h1>Nog "+ markers.length +" locaties over</h1>"
    teller++;

    this.update = function(coordinates) {
        let punten = pointCheck(coordinates)
        this.area = calcAreaFromCoordinates(coordinates);
        this.popup.setLngLat(calculatePopupPosition(coordinates));
        this.popup.setHTML(id);
        let HTMLText = getAutoHTML(this.id, punten, areaToString(this.area))
        console.log(this.id)
        let tussenlijst = []
        console.log("Kaas")

        tussenlijst = TestList.filter(x => x.id !== this.id )
        // TestList.forEach(element => {
        //     if(element.id !== this.id){
        //         tussenlijst.push(element)
        //     }
        // });
        console.log(tussenlijst.length)
        tussenlijst.push({id: this.id, Punten: punten, PuntenLengte: puntenlengte, AreaString: areaToString(this.area)})
        
        console.log("//Kaas")
        console.log(tussenlijst)
        console.log("///Kaas")
        setTestList(tussenlijst)
        // TestList.push({id: this.id, Punten: punten, PuntenLengte: puntenlengte, AreaString: areaToString(this.area)})
        var object = null;
        shapeList.forEach(element => {
            if(element.id === this.id){
                object = element;
                innerstring = innerstring.replace(element.HTMLText, HTMLText)
            }
        });
        // document.getElementById('listOfSelected').innerHTML = innerstring;
        shapeList[object.teller].HTMLText = HTMLText
        shapeList[object.teller].punten.forEach(punt => {
            filterAddMarker(punt, map)
        });
        punten.forEach(punt => {
            filterRemoveMarker(punt)
        });
        shapeList[object.teller].punten = punten
        document.getElementById("markersOver").innerHTML = "<h1>Nog "+ markers.length +" locaties over</h1>"
    };
}

Is there somebody here able to help me out?

Write a test for getServerSideProps()

I need to write a test for a server-side function, asserting whether it returns the correct data, if the user has permissions:

export const getServerSideProps = getServerSidePropsWrapper(async ({ locale, query }, { accessToken }) => {
    const { shopId, groupId } = query as IQuery;

    const [userResponse, customerGroupResponse] = await Promise.all([
        getUser(locale as string, accessToken as string),
        getCustomerGroup(
            locale as string,
            accessToken,
            shopId,
            groupId
        ) as Promise<Response>
    ]);
    let customerGroup = {} as IResponse<ICustomerGroup, null>;

    if (userResponse.ok && customerGroupResponse.ok) {
        const user = await userResponse.json() as IResponse<IUserInput, null>;
        customerGroup = await customerGroupResponse.json() as IResponse<ICustomerGroup, null>;

        if (!user.data?.permissions.includes('canUpdateTargetGroup')) {
            return {
                ok: false,
                status: statusCodes.unauthorized
            };
        }
    }
    //this statement needs to be covered
    return {
        ok: true,
        status: statusCodes.ok,
        data: {
            customerGroup: customerGroup.data,
            locale
        }
    };
}, ['customerGroup', 'common', 'validations']);

I need to test the last return statement. This is the test I came up with:

it('should return customer group data, if user has permissions', async () => {
    const result = await getServerSideProps(serverSideProps) as never as { props: { customerGroup: ICustomerGroup, locale: string } };

    //returns undefined
    expect(result.props.customerGroup).toEqual(customerGroup);
    expect(result.props.locale).toEqual('en_US');
});

When I run the test, result.props.customerGroup returns undefined. How should I go about testing the last return statment?

How to style dots(ellipsis) depend on what text it hide

In this example, first row with dots must be red because it hide text with red color, and show black dots on second row, because there is no red text hidden by dots.
It need to be dynamic and change with resizing, div width is not constant and known.

<div>
  <div class="container1">
    <span>Text</span>
    <span class="red">Text</span>
    <span>Text</span>
  </div>
  <div class="container2">
    <span>Text</span>
    <span class="red">Text</span>
    <span>Text</span>
  </div>
</div>
.container1 {
    width:50px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}
.container2 {
    width:75px;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}
.red {
    color: red;
}

http://jsfiddle.net/gnjpq628/

Transcribe a text from speech and generate Audio from text

I am trying to make a user interface where a user would click a mic button and speak to it and then a live stream transcription would appear on the screen. I also need to generate an audio and play it to the user as a reply to the user’s input audio. There are already packages who do that(just need to npm install them), but I was wondering if I should use them or use AWS-SDK POLLY and client-transcribe-streaming packages offered by amazon web services. The already existing packages seem very easy to use but am not sure if that is reliable. Where as if I use AWS-SDK,it seems like setting up the mic and speaker of the browser and setting up the environment seems very complicated as I was trying it.
The following code shows AWS-SDK method of transcribing live speaking streams but I couldn’t see the transcribed texts. Is there something wrong with the code? Any suggestion would help

import { SECRET_ACCESS_KEY, ACCESS_KEY_ID } from "./transcribeGlobal.js";
import React, { useState } from "react";
import { TranscribeStreamingClient } from "@aws-sdk/client-transcribe-streaming";
import { MicrophoneStream } from "microphone-stream";

const accessKeyId = ACCESS_KEY_ID;
const secretAccessKey = SECRET_ACCESS_KEY;
const region = "us-east-1";
const languageCode = "en-US";

const transcribeClient = new TranscribeStreamingClient({
  region,
  credentials: { accessKeyId, secretAccessKey },
});

const request = {
  AudioStream: {},
  LanguageCode: languageCode,
  MediaEncoding: "pcm",
  SampleRateHertz: 44100,
};

function TranscribeClientSpeech() {
  const [transcription, setTranscription] = useState("");

  const handleStream = (stream) => {
    const micStream = new MicrophoneStream(stream);

    micStream.on("data", (chunk) => {
      const audioChunk = new TextEncoder().encode(chunk);
      request.AudioStream = { AudioEvent: { AudioChunk: audioChunk } };
      transcribeClient.send(request);
    });

    transcribeClient.on("data", (response) => {
      const transcript = response.TranscriptEvent.Transcript.Results.reduce(
        (acc, result) => acc + result.Alternatives[0].Transcript,
        ""
      );
      setTranscription(transcript);
    });

    transcribeClient.on("error", (err) => {
      console.error("Error with transcription stream", err);
    });
  };
  console.log(transcription)
  return (
    <div>
      <h1>Live Transcription</h1>
      <p>{transcription}</p>
      <button onClick={() => navigator.mediaDevices.getUserMedia({ audio: true }).then(handleStream)}>
        Start Transcription
      </button>
      <p>{transcription}</p>
    </div>
  );
}

export default TranscribeClientSpeech;

Thanks for the suggestions in advance

I am expecting for the transcribed texts to show up, but it’s still empty

JS) ‘mousemove’ event works with mouseclick. Does this work well or Did I miss something?

I tried addEventListener(‘mousemove’,()=>…) on JavaScript,
but, this works only with mouseclick. not mousemove

Did I miss something? or Do I try other function?

This is my code

const cursor = {}
cursor.x = 0
cursor.y = 0

window.addEventListener('mousemove', (event) => {
    console.log(event)
})

The problem is I can get console value only when I click my mouse, not just moving.
I want to get my console value while my mouse is moving.
Thanks

How to create Object of Object using Object.fromEntries

I want to insert all choosen_products from users, sometimes 5, could be 4 or 3. and put all information into an object, and then addDoc to Firebase.
Here is what I have below.

let tmp_ff = Object.fromEntries(              
this.choosen_products.flatMap((element, index) => [             
      [`q_p_fullname`, element.p_fullname],
      [`q_p_code`, element.p_code],
      [`q_p_category`, element.p_category],
      [`q_p_cost`, element.p_cost],
      [`q_p_margin`, element.p_margin],
      [`q_p_sell`, element.p_sell],
]),
);

However, this is the objects I am looking for: 1 is the index and it contains object of object, so the tmp_ff contain these element below:
enter image description here

after I do fromEntries, I cannot access choosen_products‘s index anymore and it does not allow me to add an index with another object insides tmp_ff, how to declare object name (which is index) and how to loop and create object of object in my screenshot example. Any help would appreciate?

How to customize csv format data on Apex chart?

When we use x-axis type as category but it emits same x-axis data on csv format.

      xaxis: {
        type: 'category',
      }

One way to customize csv format date and time is using x-axis type as datetime this one works but in my case i have to show only 28 days in a month so it is not working in my case.

      xaxis: {
        type: 'datetime',
      }

Any suggestion are appreciate.

navigate Dosn’t match With React Router

I wrote a function that Change User’s Password and I want when the response istrue to navigate the user to the login page but my login route doesn’t match and my NoMatch route is rendered instead. When I reload the page my login route does then render, why?

this is my ChangeUserPassword Function :

const ChangeUserPassword =()=>{
// DO SOmthing 
       if (Response){
             navigate("/Login", { replace: true });
             return <Navigate to="/Login" replace/>
        }
}

this is My Routes :

import Loading from "./Component/Loading";
const Main = () => {
  const { token } = useAuthState();
  return (
        <>
      <BrowserRouter>
<Routes>
            <Route
              path="/"
              element={
                <Suspense fallback={<Loading />}>{<MainPage />}</Suspense>
              }
            />
             <Route
              path="/Login"
              element={
                <Suspense fallback={<Loading />}>
                  {!token ? <LoginStep1 /> : <Navigate replace to={"/"} />}
                </Suspense>
              }
            />
             <Route
              path="*"
              element={
                <Suspense fallback={<Loading />}>
                  <NoMatch />
                </Suspense>
              }
            />
</Routes>
      </BrowserRouter>
      

        </>
);

i want When Users Change their password ,be redirected to Login Page But My Router Doesn’t Match. How Can I Fix This Problem ?

using dayjs in worker thread with angular

I’m struggling to use dayjs in my worker thread in my angular 8 app.
I’m having the following error:

Module build failed (from ./node_modules/worker-plugin/dist/loader.js)

Property 'from' does not exist on type 'Dayjs'.

I had an error before with html type I fixed that by adding “dom” in lib,

here the following tsconfig.worker.json

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "skipLibCheck": true,
    "outDir": "./out-tsc/worker",
    "lib": [
      "es2018",
      "webworker",
      "dom",
    ],
    "types": [ "node" ]
  },
  "include": [
    "**/*.worker.ts"
  ]
}```

While commenting all my code in the worker file, every thing compile good and the code (I cannot share it because sensitive information) is not a problem since I can just delete the worker and put it in the app and then it works well.

this is my tsconfig.app.json

```json
{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "module": "esnext",
    "moduleResolution": "node",
    "outDir": "../out-tsc/app",
    "types": [
      "node"
    ]
  },
  "files": [
    "main.ts",
    "polyfills.ts"
  ],
  "include": [
    "src/**/*.d.ts"
  ],
  "exclude": [
    "test.ts",
    "**/*.spec.ts",
    "**/*.worker.ts"
  ],
  "angularCompilerOptions": {
    "fullTemplateTypeCheck": true,
    "strictInjectionParameters": true
  }
}

Thanks a lot !

Why does the getter/setter methods get inherited as a property in child object?

I was exploring the Object.create() method and came across something interesting. When I passed an Object with a getter method in it (made using get keyword), the getter method was implicitly present in the new Object alongside the Prototype object and also inside the Prototype object.

Why is it that a get method becomes a property in the new object because as per my understanding, the Object.create() method will simply create an empty object and put the passed argument as the new Object’s prototype.

Here’s my code :

let obj = {
    fname: "hello",
    lname: "world",
    get getName() {
        return `${this.fname} ${this.lname}`;
    },
};

let newObj = Object.create(obj);
console.log(newObj);

And here’s what it displays on the browser console :-
Console Image displaying the newObj

I tried accessing the getName method on the newObj and it printed "hello world". I am not sure if this is because of prototype chaining or is it because the newObj has getName as its property.

Please let me know whats happening in the context of Object Literals and not in case of Classes.