Picking offset for pagination that grabs from two sources

I have a page to view notifications. My company created a new system for managing these notifications so now when fetching the notifications from the api we have to pull from two sources.

If the limit is set to 25, it grabs 25 from both sources, sorts them by created_at updates two variables called source_1_offset and source_2_offset with the number of each source that is in the first 25 items of the sorted list. For example if 10 items from source I and 15 items from source 2 are in the first 25 sorted items, source_1_offset = 10 source_2_offset = 15.

This works perfectly when stepping ahead one page at a time. The issue is when the user wants to jump pages i.e. from page 4 to page 8. If the notifications were coming from one source I would just do limit * page_num for the offset. But because it is coming from two sources I have no idea how many will have come from source 1 and how many from source two.

The way I am currently handling this is just by making a guess on the offsets by setting them both to limit (25) * page_num (8). This ensures that no row is shown twice and if they step back or forward they can still see all the elements. The issue here is if they are on page 3 and the date for the last notification on the page is 4/19/24 and they want to jump to 03/19/24 if they jump ahead 2 or more pages i.e. page 5, the offset will again be treated as a guess and be set to 5 * 25. This leads to some situations where you are the dates from the two sources are wildly separated. source 1 might be correctly grabbing notifications from around 03/19/24 but source 2 might be grabbing from 05/01/23, in which case only notifications from source 1 will be displayed even if in reality there are notifications from source 2 in March 2024.

Any suggestions on how to handle guessing the offset? I have considered making more specific predictions based on how many notifications from each source we have seen up until the page jump.

Below is the function that sets the offset on a page forward

 newNotificationsArray.sort((a, b) => {
                let aItem = a[sort.column]
                let bItem = b[sort.column]

                if (a.fields) {
                    aItem = a.fields[sort.column]

                    if (sort.column === 'created_at') {
                        aItem = new Date(aItem * 1000).toISOString()
                    }
                }

                if (b.fields) {
                    bItem = b.fields[sort.column]

                    if (sort.column === 'created_at') {
                        bItem = new Date(bItem * 1000).toISOString()
                    }
                }

                if (aItem < bItem) return sort.order === 'desc' ? 1 : -1
                if (aItem > bItem) return sort.order === 'desc' ? -1 : 1
                return 0
            })

            let notificationsCount = 0
            let eventNotificationsCount = 0

            for (var i = 0; i < self.limit; i++) {
                // only source one has property source
                if (newNotificationsArray[i].hasOwnProperty('source')) {
                    notificationsCount += 1
                }
                else {
                    eventNotificationsCount += 1
                }
            }

            self.notificationsOffset += notificationsCount
            self.eventNotificationsOffset += eventNotificationsCount

            return newNotificationsArray.slice(0, self.limit)

This is offset for page jumps

if (self.pageJump) {
               self.notificationsOffset = page * self.limit
               self.eventNotificationsOffset = page * self.limit
            }

Using express-rate-limit without reloading the entire page

I’m using express-rate-limit to limit the number of connection attempts.

homeController.js

const express = require('express');
const router = express.Router();

//limiter à 5 tentatives de log sur 5 minutes
const limitter = require("express-rate-limit");
const signInlimitter = limitter({ 
    windowMs: 5*60*1000, 
    limit: 1, 
    handler: (req, res, next) => {
        const date = new Date(req.rateLimit.resetTime);
        req.rateLimit.resetTime = date.toLocaleTimeString();
        res.status(429).send(`Trops de tentatives ! Vous pourez réessayer à ${req.rateLimit.resetTime}.`);
    }
});

const homeRegex = /^/(home)?$/;

const homeView = (req, res) => { res.render("home.ejs", { message: "" }); };

router.route(homeRegex).get(homeView).post(signInlimitter, homeView);

module.exports = router;

index.js

...
app.use('/', require('./controllers/homeController')); 
...

So far, not too complicated.
However, when the limit is exceeded, it refreshes the entire page, and only displays the message.

enter image description here
enter image description here

This doesn’t suit me because I would like to display the message in a textbox or an alert() without recalling everything, in the same idea as with a fetch (or ajax).

Thanks !

I have the ejs packages if that helps.

Displaying hidden element in a div moves the whole horizontal grid row down, how to make it only move the element BELOW the opening element move down?

I am practicing HTML, CSS and JavaScript and I encountered a problem while trying to create a container for company services. Every single service div has a button to show more text which “opens” the div down. I noticed that the whole row in a grid moves down.

There should be 3 service divs in a row and then there should be rows as much as there is service divs remaining and the first element in a horizontal row should be on the left side. I tried to make that when the hidden element is displayed, it would ONLY move down the service div below the opened element and not the whole row.
when hidden element is opened

when hidden element is not displayed

Multilevel dropdown in react-bootstrap , nested dropdown in react-bootstrap library

i want to achieve multilevel dropdown in with react-bootstrap or nested dropdown with react-bootstrap. can anyone know how can we achieve multilevel dropdown with react-bootstrap or is there any props which we can use?

i have tried this way but not working

const dropDownMenu = () => {
    <Dropdown>
        <Dropdown.Toggle as="div" role="button">
            <i className="bi bi-three-dots-vertical"></i>
        </Dropdown.Toggle>

        <Dropdown.Menu>
              <Dropdown.Item as="button" onClick={() => {}}>
                   Item 1
              </Dropdown.Item>

              <Dropdown.Item>
                   <Dropdown>
                         <Dropdown.Toggle as="div" role="button">
                              Item 2
                         </Dropdown.Toggle>

                         <Dropdown.Menu>
                               <Dropdown.Item href="#/action-1">Action</Dropdown.Item>
                               <Dropdown.Item href="#/action-2">Another action</Dropdown.Item>
                               <Dropdown.Item href="#/action-3">Something else</Dropdown.Item>
                        </Dropdown.Menu>
                </Dropdown>
           </Dropdown.Item>
      </Dropdown.Menu>
  </Dropdown>
}

i want to open children dropdown when we click on parent dropdown ** Item 2 **

How to stop button onclick event using javascript?

Is there anyone that can assist?

 <div class="select-button">
     <button type="button" class="button-1 select-billing-address-button" onclick="selectBillingAddress@(item.Id)()">@T("Checkout.BillToThisAddress")</button>
     
     <script asp-location="Footer">
         function selectBillingAddress@(item.Id)() {
             if ($('#@Html.IdFor(model => model.ShipToSameAddress)')
                 .is(':checked')) {
                 setLocation(
                     '@Html.Raw(Url.RouteUrl("CheckoutSelectBillingAddress", new {addressId = item.Id, shipToSameAddress = "true"}))');
             } else {
                 setLocation(
                     '@Url.RouteUrl("CheckoutSelectBillingAddress", new {addressId = item.Id})');
             }
         }
     </script>
 </div>

I would like to check a few conditions before making a call, but I am unable to modify the function or button at this time. Could you please provide a solution? I would like to use load new js.
Many thanks in advance.

I’m trying to add some code under the function and override the old one, but nothing is working. I want to use load new js to accomplish this, and I can only do that.

display:none not hiding the empty option in dropdown

I have running Angular 11 application. In the page I have 2 radio buttons and one dropdown. The behavior is that whenever I change the radio button selection, I want to reset dropdown value and show empty value in the dropdown.

Below code is working fine in Chrome. But in IE I can still see empty option in the dropdown. I don’t want to show empty option in the dropdown list.

test.component.html

<form [formGroup]="myForm">
    <select [id]="control.Id" [formControlName]="control.Id" [value]="control.Value">
      <ng-container *ngFor="let item of control.Items">                        
         <option [value]="item.Value">{{item.Key}}</option>
       </ng-container>
       <option hidden disabled value="" style="display:none;"></option>
     </select>
</form>

test.component.ts

this.myForm.controls['City'].valueChanges.subscribe(this.onCityChange.bind(this));

onCityChange()
{
   this.myForm.get['City'].patchValue('');
}

Chart.js Line Graph not displaying data for total Revenue for the past 15 days

I’ve been debugging this some time now and probably 2 hours now. I want to display the line graph of chart.js the revenue for the past 15 days.

I have a function to get the ajax result for the previous days. This is the js script I made.

// Function to fetch revenue data from PHP script
function fetchRevenueData() {
    $.ajax({
        url: '../config/tables/semi_weekly_revenue.php',
        dataType: 'json',
        success: function(data) {
            var revenueValues = labels.map(function(date) {
                return data[date] || 0; 
            });
        
            myLineChart.data.datasets[0].data = revenueValues;
            myLineChart.update();

        },
        error: function(xhr, status, error) {
            console.error('Error fetching revenue data:', error);
        }
    });
}

the line graph:

// Area Chart Example
var ctx = document.getElementById("myAreaChart");
var myLineChart = new Chart(ctx, {
    type: 'line',
    data: {
        labels: labels, 
        datasets: [{
            label: "Revenue",
            lineTension: 0.3,
            backgroundColor: "rgba(2,117,216,0.2)",
            borderColor: "rgba(2,117,216,1)",
            pointRadius: 5,
            pointBackgroundColor: "rgba(2,117,216,1)",
            pointBorderColor: "rgba(255,255,255,0.8)",
            pointHoverRadius: 5,
            pointHoverBackgroundColor: "rgba(2,117,216,1)",
            pointHitRadius: 50,
            pointBorderWidth: 2,
            data: [],
        }],
    },
    options: {
        scales: {
            xAxes: [{
                time: {
                    unit: 'date'
                },
                gridLines: {
                    display: false
                },
                ticks: {
                    maxTicksLimit: 7
                }
            }],
            yAxes: [{
                ticks: {
                    min: 0,
                    max: 40000,
                    maxTicksLimit: 5
                },
                gridLines: {
                    color: "rgba(0, 0, 0, .125)",
                }
            }],
        },
        legend: {
            display: false
        }
    }
});

//The fetchRevenueData function will update the Linechart upon called.
fetchRevenueData();

my php query script looks like this:

 // Query to fetch total revenue for each of the past 15 days
    $query = "SELECT 
                DATE_FORMAT(sale_date, '%Y-%m-%d') AS date,
                SUM(total_amount) AS total_revenue
              FROM sales
              WHERE sale_date >= DATE_SUB(CURRENT_DATE(), INTERVAL 15 DAY)
              GROUP BY date
              ORDER BY date";

    $stmt = $pdo->query($query);

   // Fetch revenue data and populate the revenueData array
    while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
        $revenueData[$row['date']] = $row['total_revenue'];
    }

   // Return revenue data as JSON
   echo json_encode($revenueData);

Did I miss something? I’ve read the documentation about data passing and maybe I miss something. I’m still learning JavaScript now. Thanks!

I expect the result to show the Line Graph similar to the bar graph but it will on semi-weekly Forecast of revenue for the past 15 days.

Engine for Fingerprint matching/Auth-React.js

I am able to read fingerprint from hardware in React.js. However I need help in finding an engine for matching/auth fingerprint of user when they try to login. I have used @digitalpersona/devices to read fingerprint.

I have found an engine in Python but If anyone knows a library for react.js then It will be better.

whenever i hit run in visual studio code it opens another window

it’s been a a couple days of trying but I’m just too new to understand.
the same happens when i hit start debugging.
This is what im running just a very simple code to get started
enter image description here
enter image description here

console.log("-----------");
console.log("Hello world");
console.log("rise and shine!");
console.log("ready for a new day");
console.log("-----------");

i tried redownloading, rebooting, tutorials

Enforce naming convention of useState destructured variables [foo, setFoo]?

When using the useState hook, typically the two destructured array variables take the form: foo and setFoo.

Some examples that deviate from this template are:

const [foo, setfoo] = useState();    
const [foo, updateFoo] = useState();    
const [foo, fooSetter] = useState();    

During code review, I would recommend the above examples be changed to:

const [foo, setFoo] = useState();    

Is there a way of statically checking (ESLint) for this situation?

Auto input hidden value

I am trying to make a custom unsubscribe page (in pardot), I used the inspect tool and grabbed the current HTML code, I’m running into an issue with the input field, this is what the code currently looks like:

<input type="text" name="piEmailPrefEmail" id="piEmailPrefEmail"
 value="m******s@t*****x.com" class="text" readonly="readonly" >

The value needs to change so that it is not my email. Ideally I would like it to pull the users email the same way it does mine, with the hidden characters. Not sure what I need to update in the HTML and or what javascript code needs to be added.

I tried removing my email address and leaving the value field blank, which works when I remove “readonly” but ideally the user will not need to put in their own email address.

Using an async IIFE to run loops in the background in Javascript

Currently I am using an async IIFE like this:

(async () => {
  while(true) {
    ...game loop
  }
})()

The game loop is used to draw animations in a canvas element.
This works fine, (even though microtasks aren’t ran on a new thread), yet I have never seen it mentioned anywhere on the internet, so my question is, is this ok (will it run on all browsers, does it block something important), or should I use something like setTimeout?

How to filter out a key from a second level object of a nested array of objects

I am trying to filter out a key, in this case, count from a nested array of objects.

I have

let test  = [
 {
  "id": "c3c6f410f58e5836431b473ebcf134756232d04f2bf35edff8",
  "label": "Sector2",
  "options": {
   "62f92fab79ac81d933765bd0bbc4a1f5ea26cb3a088bcb4e6e": {
    "index": 0,
    "value": "Bob",
    "label": "Bob",
    "count": 1
   },
   "2fe91aa3567c0d04c521dcd2fc7e40d7622bb8c3f594d503da": {
    "index": 1,
    "value": "Student",
    "label": "Student",
    "count": 1
   },
   "c59ea1159f33b91a7f6edc6925be5e373fc543e4": {
    "index": 2,
    "value": "BBB",
    "label": "BBB",
    "count": 1
   },
   "c59ea1159f33b91a7f6edc6925be5e373fc54AAA": {
    "index": 3,
    "value": "Orange Duck",
    "label": "Orange Duck",
    "count": 1
   }
  }
 },
 {
  "id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e951709485",
  "label": "Brown Cow"
 },
 {
  "id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e95170ZZZ",
  "label": "Red Fish"
 }
]

 test = test.filter(item => item[0].options['count']);

but I am getting Cannot read properties of undefined

I am trying to filter out count from all elements of test that have options

desired output is

Thanks

[
 {
  "id": "c3c6f410f58e5836431b473ebcf134756232d04f2bf35edff8",
  "label": "Sector2",
  "options": {
   "62f92fab79ac81d933765bd0bbc4a1f5ea26cb3a088bcb4e6e": {
    "index": 0,
    "value": "Bob",
    "label": "Bob"
   },
   "2fe91aa3567c0d04c521dcd2fc7e40d7622bb8c3f594d503da": {
    "index": 1,
    "value": "Student",
    "label": "Student"
   },
   "c59ea1159f33b91a7f6edc6925be5e373fc543e4": {
    "index": 2,
    "value": "BBB",
    "label": "BBB",
    "count": 1
   },
   "c59ea1159f33b91a7f6edc6925be5e373fc54AAA": {
    "index": 3,
    "value": "Orange Duck",
    "label": "Orange Duck"
   }
  }
 },
 {
  "id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e951709485",
  "label": "Brown Cow"
 },
 {
  "id": "f794c6a52e793ee6f5c42cd5df6b4435236e3495e95170ZZZ",
  "label": "Red Fish"
 }
]

Javascript loaded but not working on Elementor backend

Good evening everybody
I’m writing an addon for Elementor to display a map and a graph, based on a kml file.
The addon works on the frontend, so I believe that the JS is pretty ok.

The JS code has some problem in the backend. I believe that something happens too late.

The render function of my addon is very simple:

protected function render() {
    $settings = $this->get_settings_for_display();
    $kmlUrl = $settings['kml_url'] ? $settings['kml_url'] : null;

    echo "<div id='kgm-map-container' data-kml='{$kmlUrl["url"]}' >";
        echo '<div id="kgm-map">loading map...</div>';
        echo '<div id="kgm-elevation_chart">loading chart...</div>';
    echo '</div>';
}

$kml_url is taken from a addon control, as you can see, then added as a meta attribute to my output.

The part of the JS that uses this information is this one:

jQuery(document).ready(function () {
  kmlFile = jQuery("#kgm-map-container").data("kml");

  console.log(document.getElementById("kgm-map-container"));
  
  var latlng = new google.maps.LatLng(0, 0);
  var mapOptions = {
    zoom: 15,
    center: latlng,
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    mapTypeControlOptions: {
      style: google.maps.MapTypeControlStyle.DEFAULT,
    },
  };
  mapInstance = new google.maps.Map(document.getElementById("kgm-map"), mapOptions);
  ... and so on

Pay attention now: the line “console.log(document.getElementById(“kgm-map-container”));” returns null, that’s why the map is not shown in the backend.

I see that jQuery(document).ready(..) is not the correct place to read my data, because they’re not available yet.

So, how can I patch this code? Is there a good Elementor hook that runs at the right time?
I tried with “elementor/frontend/init” but it’s clearly not working in the backend.
I tried with “elementor/frontend/init”, but it breaks both frontend and backend.

I need your help!
Thanks