Date.getTime is not a constructor

In a function I have the line:

const currentTime = new Date.getTime();

The code compiles just fine.
Also, ESLint displays neither warnings or
errors.
But when I run the code, I get an alert box giving the confusing
message Date.getTime is not a constructor.

What is wrong here?

Error message: 'Date.getTime is not a constructor'


I have noticed that there is no error if I don’t call the function
that contains the line above.

The following Stack Snippet reproduces the error.

function rightNow() {
  const currentTime = new Date.getTime();
  return currentTime;
}
console.log(rightNow().toString());
// ^^ No error if I comment out the previous line! ^^
.as-console-wrapper { max-height: 100% !important; top: 0; }

Scroll to the top list item without scrolling the view – ReactJS

I want to scroll to an item in the list, but when I click on the item my entire view scrolls. I would like the scroll to be only for the div with the list.

<AlertsList>
        {productInventoryAlert?.map((product, index) => {
          const itemRef = createRef<HTMLLIElement>();

          const handleScrollIntoView = (index: number) => {
            if (expandedCard === index) {
              setExpandedCard(-1);
            } else {
              setExpandedCard(index);
            }

            itemRef.current?.scrollIntoView(true);
          }

          return (
            <li ref={itemRef} key={index}>
              <DashboardInventoryAlertListItem
                handleScrollIntoView={handleScrollIntoView}
                product={product}
                index={index}
                expandedCard={expandedCard}
              />
            </li>
          );
        })}
</AlertsList>

export const AlertsList = styled.ul`
  max-height: 250px;
  overflow: scroll;
  list-style: none;
  scroll-behavior: smooth;
 `;

How to make parameters change in an equation in a function when calling it?

I want to create a function that can generate two balls that rise at different speeds. I used the parameters of the speed in which it rises called “change” and another parameter of its x coordinates called “x”, so that they don’t originate from the same place.

If I call the function, it works, and the ball moves according to the speed I set it to. However, if I call it twice, two balls are generated but both move at the speed that I call it with the second time. In this case, two balls were generated at x coordinates 150 and 450. The first ball was supposed to move at speed y-10, and the second ball at speed y-5, but both are moving at y-5.

Therefore, they move, but the whole purpose of the code which is making it change doesn’t work. Can someone help me make it change?

void setup(){
  size(600,600);
}
float y = 600;

 void risingball(float change, float x){
  noStroke();
  fill(30,0,30);
  y = y-change;
  ellipse(x,y, 50,50);
}
  void draw(){
  background(255);
  risingball(10, 450);
  risingball(5, 250);
}

Chartjs not giving ‘xLabel’ properly on tooltip

I have a line chart where data is displayed as point elements depending on the X axes (time axis) label.

enter image description here

    // Config chart
    const config = {
      type: "line",
      data: {
            labels: ['ene.', 'feb', 'mar.', 'abr.', 'may.', 'jun.', 'jul.', 'ago.', 'sep.', 'oct.', 'nov.', 'dic.'],
            datasets // ex --> [{ x: 'jun.', y: 90 }]
        },
      options: {
            tooltips: {
                callbacks: {
                    title: function(context) {
                             console.log(context); // Returning wrong xLabel 
                           }
                }
            }
      }
    }

The problem is when it shows the tooltip of, for example, June it takes it as index 3 so the title tooltip (xlabel) is shown as “April”.

enter image description here

How could I get the proper label on the tooltip, not depending on the index?

JavaScript : Matcher error: received value must be a function

My questions appear to be duplicates of other questions on stackoverflow. I tried every single solution, but none of them worked.

I have a sns lambda function which return void. I want to throw an error if the orderId does not exist.

When run the test suite. I am getting this error:

Matcher error: received value must be a function

Received has value: undefined

Here is my function

const parseOrdersFromSns = (event: SNSEvent): Payload[] => {
  try {
    return event.Records.flatMap((r) => JSON.parse(r.Sns.Message));
  } catch (error) {
    Log.error("New order from SNS failed at parsing orders", { event }, error);
    return [];
  }
};
export const handlerFn = async (event: SNSEvent): Promise<void> => {
  const orders = parseOrdersFromSns(event);

  if (orders.length === 0) return;

  const existingOrders = await Promise.all(
    orders.map(
      async (o) => await findOrderStateNode(tagOrderStateId(o.orderId))
    )
  );

  console.log({ orders });

  if (!existingOrders) {
    orders.forEach((o) => {
      throw new Error(
        `Failed to get exisiting order with this orderId: ${o.orderId}`
      );
    });
    
    // other code staff if there is existing order
  }
};

Here is my test suite function where I am passing random orderId which is not legit. So, I am expecting error.

describe('Making an order by random uuid', () => {
  integrationTest('should throw an error', async () => {
    const order = {
      orderId: '90073f29-d0df-4eca-b93d-ba1cce0d950a',
      roundName,
      startTime,
    }

    const event = {
      Records: [
        {
          Sns: {
            Message: JSON.stringify([order]),
          },
        },
      ],
    } as SNSEvent

// snsListen is my lambda function 

    expect(await snsListen(event)).toThrowError(
      `Failed to get exisiting order with this orderId: ${order.orderId}`,
    )
  })
})

Using string list as Chart.js label

I need to create a chart with two lists.

List<string> islemYapanOperatorler = new List<string>();
    List<int> interventionCounter = new List<int>();
        foreach (var item in itemList)
    {
        string Normalize = item.Key;
        for (int i = 0; i < turkishChars.Length; i++)
            Normalize = Normalize.Replace(turkishChars[i], englishChars[i]);
        islemYapanOperatorler.Add(Normalize);
        foreach (var item2 in item)
        {
            interventionCount++;
        }
        interventionCounter.Add(interventionCount);
        interventionCount = 0;
        operatorCount++;
    }

islemYapanOperatorler list is creates the label part and interventioncounter list is creating the data part for Chart.Js.

And javascript code for Chart.js below: (It’s a bit lazy but it gives the result I want.)

        const myChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels:
               ['@islemYapanOperatorler[0]', '@islemYapanOperatorler[1]', '@islemYapanOperatorler[2]', '@islemYapanOperatorler[3]', '@islemYapanOperatorler[4]', '@islemYapanOperatorler[5]', '@islemYapanOperatorler[6]', '@islemYapanOperatorler[7]', '@islemYapanOperatorler[8]', '@islemYapanOperatorler[9]', '@islemYapanOperatorler[10]']

                ,
            datasets: [{
                label: 'Haftalık',
                data: [@interventionCounter[0], @interventionCounter[1], @interventionCounter[2], @interventionCounter[3], @interventionCounter[4], @interventionCounter[5], @interventionCounter[6], @interventionCounter[7], @interventionCounter[8], @interventionCounter[9], @interventionCounter[10]],
                backgroundColor: [

                    'rgba(0, 26, 190, 0.8)'
                ],
                borderColor: [

                    'rgba(0, 26, 190, 1)'
                ],
                borderWidth: 1
            }

            ]
        },
        options: {
            tooltips: {
                callbacks: {
                    label: function (tooltipItem, data) {
                        return data['labels'][tooltipItem['index']] + ': ' + data['datasets'][0]['data'][tooltipItem['index']] ;
                    }
                }
            },

            scales: {
                y: {
                    beginAtZero: true
                }
            }
        }
    });

It’s working correctly and gives the result I want. (picture below)
enter image description here

But, as you can see

It works fine for 11 indices, but this number of indices may vary. In such a case, either it does not show the data in the 12th index because it is defined as a constant 11 index, or it fails because the 11th index is empty.

How can I solve this problem? Thanks for any suggestions.

I am writing the hangman game but with functions alone, how can I do that? [closed]

I am trying to write the same game with functions instead. Based on the code below how would you turn “update game state” into a function?

var words = [
  "javascript",
  "monkey",
  "amazing",
  "pancake",
];
var word = words[Math.floor(Math.random() * words.length)];
var answerArray = [];
for (var i = 0; i < word.length; i++) {
  answerArray[i] = "_"
}

var remainingLetters = word.length

while (remainingLetters < 0) {

  alert(answerArray.join(" "));

  var guess = prompt("Guess a letter, or click Cancel to stop playing>");
  if (guess === null) {
    break;
  } else if (guess.length !== 1) {
    alert("Please enter a single letter.");
  } else {
    //update the game state with a guess
    for (var j = 0; j < word.length; j++) {
      if (word[j] === guess) {
        answerArray[j] = guess;
        remainingLetters--;
      }
    }
  }
}
alert(answerArray.join(" "));
alert("Good Job! The answer was " + word);

This is what I tried:

//Update the game state 

How to call useQuery fetch method for differenct API calls in one functional component?

How to call useQuery fetch method for differenct API calls in one functional component?
I am using React-query in my project. I use useQuery() to fetch data from API and I made two get api calls in one functional component. One for get products and second for get product details.
I use refetch function in useEffect to call the refetch function only once. and I also want to use this function for my second api call but I got error.
Here is my code:

  useEffect(() => {
    refetch();
  }, []);


  
     let {refetch}=useQuery(
    ["product", user],
    async (user) => {
      return await getProducts(user?.queryKey[1]?.jwtToken);
    },
    {
      enabled: false,
      onSuccess: (data) => {
        console.log(data.data);
        setApiProduct(data?.data);
        
      },
    }
  );

This api call get the data from db and it works perfectly. But I face problem to fetch data from 2nd api i.e getProductDetails
Here is the code for getDetailsProduct

 {refetch } = useQuery(
    ["detailProduct", user],
    async (user) => {
      ;
      return await getDetailsProduct(user?.queryKey[1]?.jwtToken, "6213738798dbb2ecf4c23ddf");
    },
    {
      enabled: false,
      onSuccess: (data) => {
        // console.log(data)
      },
    }
  );

it provides me an error. How can I handle this error. kindly help me out.

Filter on Dynamics JavaScript?

I picked up the following JavaScript I’m a novice on JS. Anyway I want to achieve if emailsignature isdefault not equals 0 then add the handler email signature, below is the code, how do I do this?, where would I insert this IF condition?

//find the users signature dynamically

var query = "?$select=title,safehtml&$filter=ownerid/ownerid eq " + signatureUserId;

Xrm.WebApi.retrieveMultipleRecords("emailsignature", query).then(
function success(result) {

//The below for each goes through all the email signatures and it looks like the code is grabbing the first signature on the list. How do I code a filter to add default? 
// I want to only add the isdefault signature to the email, i.e. if signarure not equal to NO add.

for (var i = 0; i < result.entities.length; i++) { //This is itterating through all the signature
var emailSig = result.entities[0];
if (emailSig != null) {
                                
if (emailDescription === "<p></p>" ||  emailSubject === null ) 
                {
                                var signatureDynamic = emailSig["safehtml"];
                                formContext.getAttribute("description").setValue("<br /><br />" + signatureDynamic);
}
else if (emailSubject .includes("RE:"))
{
 var signatureDynamic = emailSig["safehtml"];
                                formContext.getAttribute("description").setValue("<br /><br />" + signatureDynamic + emailDescription);
}
                            }
                            break;
                        }
                    },
                        function (error) {
                        alert("Error: " + error.message);
                    });
                    //end users signature
                
            }

            break; // We will grab the first one
        }
    },
        function (error) {
        alert("Error: " + error.message);
    });

 
}

REACT-Print child elements in th NavBar menu left side

I’m struggling to print my child elements with their icons in my NavBar menu (left side) but only all the parents are printed… And for those where children is true, I want to print a chevron next to the parent icon so we can click on it and see all the child elements.

Here is my code for the NavBar.jsx :

import './NavBar.css'
import logo from "../Components/logo";
import { ITEMS } from "../Navigation";
import React from 'react'

export default function NavBar() {
    return (
        <div className="NavBar">
            <img className="logo" /> 
            <span className="textLogo">LOGO</span>
            <div className ="NavbarList">
                {ITEMS.map((item, i) => {
                    return (
                        <li key={i} className="row" id={window.location.pathname === item.href ? "active" : ""} 
                        onClick={() => {window.location.pathname = item.href;}}>                      
                            <div id="icon">{item.icon}</div>
                            <div id="title">{item.title}</div>   
                        </li>
                    );
                    
                })}
             
            </div>
        </div>
    );
}

And my ITEMS (in Navigation.js) that are shown in the NavBar :

import ConstructionIcon from '@mui/icons-material/Construction';
import GridViewIcon from '@mui/icons-material/GridView';

    export const ITEMS = [
        {
            icon: <GridViewIcon />,
            title: 'Dashboard',
            href: '/dashboard',
            children: []
        },
        
        {
            icon: < ConstructionIcon/>,
            title: 'Setup',
            href: '/setup',
            children: [
                { title: 'About', href: '/about' },
                { title: 'Contact', href: '/contact' },
            ],
    
        },
    ]

Any ideas please ?

How to send Camera Stream from Unity to the web browser?

I am trying to connect a unity client to a browser client using Webrtc. This step is complete the two clients are now connected (Signaling is complete). What I need to do next is to send the video stream from the c# Camera object to the other peer (browser). Here’s what have done which is not working and I do not know why?

The c# code :

var track = arCamera.CaptureStreamTrack(1280, 720, 3000);
localConnection.AddTrack(track);

Then I register the ontrack event for the RTCPeerConnection Object
The javascript code:

 function handleTrack (e) {
    console.log("Recieved a Track");
    remotePeerVideo.current.srcObject = e.streams[0];
}

When I
console.log(e.streams); this is the result:

[MediaStream]

0:{active: true, id: "9322aaa7-69b6-4ef4-8f49-c457ef4ffd16"}

I add this track to the srcObj of a video element, but it does not work. Any Ideas what might be wrong or if there is another way to get the video stream from the c# Camera Object?

How to use script tag in an ASP.NET Core MVC razor view

I want to use javascript in a razor view in the MVC project. I want to show a message to the user by clicking the post button. I put the script tag in Section below the page but on hitting F12 it shows 'btn' is null. I’m testing my project on IISExpress in Firefox

<form method="post">
--------a few input fields in a form-------
 <button id="button" type="submit" class="btn btn-lg btn-success">send</button>
</form>
<div class="submit-progress d-none">
    <label>be patient please...</label>
</div>
@section scripts{
    <partial name="_ValidationScriptsPartial" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-fileinput/5.2.7/js/fileinput.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/persian-date@latest/dist/persian-date.min.js"></script>
    <script type="text/javascript" src="https://unpkg.com/persian-datepicker@latest/dist/js/persian-datepicker.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            const btn = document.getElementById("#button");
            btn.addEventListener("click", function () {
                $(btn).prop("disabled", true);
                $(".submit-progress").removeClass("d-none");
            })
        });
    </script>
}

Why setInterval is called once?

I want to perform my api call every 2000 milliseconds… I’m new in javascript and through the web I read that I can use setInterval() method to execute a function every x seconds. But in my case it doesn’t work and my function is executed only once, and I don’t understand why and what it’s wrong.

My code is here:

<div class="col-1">
<div class="row fullrow">
    <a class="show-your-reports" href="#" data-toggle="modal"
       onclick="show_reports()"
       data-target="#yourReportsDialog">
        <script>

            function show_reports(){

                setInterval(function report_call(){
                     $.ajax({
                        type: 'GET',
                        url: api_url,
                        dataType: 'json',
                        success: function (data) {
                             # do some things...             
                         }, 2000)
                  }
             }
        </script>
    </a>
</div>

Thanks in advance!

how to use puppeteer $$eval

Is there a way to run a click event by getting only the list you want from the list?

let bc = await browser.createIncognitoBrowserContext();

  let page = await browser.newPage();
  
  //... omission
  
const value = await list_date.filter(async(element)=>{
      return await frame.evaluate((e)=>{
        return Number(e.getAttribute('date')) > 20220406 && Number(e.getAttribute('date')) < 20220408
      },element)
    })
<ul class="content scroll-y" tabindex="-1" style="right: -15px;"><div><li class="month dimmed"><div><span class="year">2022</span><span class="month">4</span><div></div></div></li><li data-index="0" date="20220404" class="day today selected"><a href="#" onclick="return false;"><span class="dayweek">월</span><span class="day">4</span><span class="sreader">선택됨</span></a><span class="today"></span></li><li data-index="1" date="20220405" class="day"><a href="#" onclick="return false;"><span class="dayweek">화</span><span class="day">5</span><span class="sreader"></span></a></li><li data-index="2" date="20220406" class="day"><a href="#" onclick="return false;"><span class="dayweek">수</span><span class="day">6</span><span class="sreader"></span></a></li><li data-index="3" date="20220407" class="day"><a href="#" onclick="return false;"><span class="dayweek">목</span><span class="day">7</span><span class="sreader"></span></a></li><li data-index="4" date="20220408" class="day"><a href="#" onclick="return false;"><span class="dayweek">금</span><span class="day">8</span><span class="sreader"></span></a></li><li data-index="5" date="20220409" class="day day-sat"><a href="#" onclick="return false;"><span class="dayweek">토</span><span class="day">9</span><span class="sreader"></span></a></li><li data-index="6" date="20220410" class="day day-sun"><a href="#" onclick="return false;"><span class="dayweek">일</span><span class="day">10</span><span class="sreader"></span></a></li><li data-index="7" date="20220411" class="day dimmed"><a href="#" onclick="return false;"><span class="dayweek">월</span><span class="day">11</span><span class="sreader">선택불가</span></a></li><li data-index="8" date="20220412" class="day dimmed"><a href="#" onclick="return false;"><span class="dayweek">화</span><span class="day">12</span><span class="sreader">선택불가</span></a></li><li data-index="9" date="20220413" class="day dimmed"><a href="#" onclick="return false;"><span class="dayweek">수</span><span class="day">13</span><span class="sreader">선택불가</span></a></li><li data-index="10" date="20220416" class="day day-sat dimmed"><a href="#" onclick="return false;"><span class="dayweek">토</span><span class="day">16</span><span class="sreader">선택불가</span></a></li><li data-index="11" date="20220417" class="day day-sun dimmed"><a href="#" onclick="return false;"><span class="dayweek">일</span><span class="day">17</span><span class="sreader">선택불가</span></a></li><li data-index="12" date="20220419" class="day dimmed"><a href="#" onclick="return false;"><span class="dayweek">화</span><span class="day">19</span><span class="sreader">선택불가</span></a></li><li data-index="13" date="20220424" class="day day-sun dimmed"><a href="#" onclick="return false;"><span class="dayweek">일</span><span class="day">24</span><span class="sreader">선택불가</span></a></li><li data-index="14" date="20220426" class="day dimmed"><a href="#" onclick="return false;"><span class="dayweek">화</span><span class="day">26</span><span class="sreader">선택불가</span></a></li><li data-index="15" date="20220430" class="day day-sat dimmed"><a href="#" onclick="return false;"><span class="dayweek">토</span><span class="day">30</span><span class="sreader">선택불가</span></a></li></div></ul>