How to Implement Pagination with API Using PHP [closed]

I’m working with the Clinical Trials API to retrieve study data using PHP. Currently, I can pull through the first 10 results as thats the default, but I’m struggling to implement pagination to access the remaining records.

I’ve tried using PHP sessions to handle the nextPageToken for pagination, but I’m having trouble utilizing the token properly. Ideally, I want to load more results incrementally (e.g 10 at a time) without fetching all the data at once, because it obviously causes my site to time out.

Here’s my code I’m currently working with


defined('ABSPATH') || exit;

// Enqueue custom CSS
function register_custom_styles() {
    wp_enqueue_style('custom-shortcode-style', get_template_directory_uri() . '/style.css', [], '1.0.0');
}
add_action('wp_enqueue_scripts', 'register_custom_styles');

// Register shortcode
add_shortcode('external_data', 'fetch_clinical_trials');

function fetch_clinical_trials($atts) {
    if (is_admin()) {
        return '<p>Shortcode [external_data] preview.</p>';
    }

    $atts = shortcode_atts(['title' => 'Clinical Trials Data'], $atts, 'external_data');

    $response = wp_remote_get('https://clinicaltrials.gov/api/v2/studies');
    if (is_wp_error($response)) {
        return 'Error fetching data.';
    }

    $studies = json_decode(wp_remote_retrieve_body($response), true)['studies'] ?? [];

    $html = '<h2>' . esc_html($atts['title']) . '</h2>';
    $html .= '<table>
                <tr><th>NCT ID</th><th>Organization</th><th>Title</th><th>Status</th><th>Start Date</th><th>Completion Date</th><th>Sponsor</th></tr>';

    foreach ($studies as $study) {
        $html .= '<tr>';
        $html .= '<td>' . esc_html($study['protocolSection']['identificationModule']['nctId'] ?? 'N/A') . '</td>';
        $html .= '<td>' . esc_html($study['protocolSection']['identificationModule']['organization']['fullName'] ?? 'N/A') . '</td>';
        $html .= '<td>' . esc_html($study['protocolSection']['identificationModule']['briefTitle'] ?? 'N/A') . '</td>';
        $html .= '<td>' . esc_html($study['protocolSection']['statusModule']['overallStatus'] ?? 'N/A') . '</td>';
        $html .= '<td>' . esc_html($study['protocolSection']['statusModule']['startDateStruct']['date'] ?? 'N/A') . '</td>';
        $html .= '<td>' . esc_html($study['protocolSection']['statusModule']['primaryCompletionDateStruct']['date'] ?? 'N/A') . '</td>';
        $html .= '<td>' . esc_html($study['protocolSection']['sponsorCollaboratorsModule']['leadSponsor']['name'] ?? 'N/A') . '</td>';
        $html .= '</tr>';
    }

    $html .= '</table>';
    return $html;
}

I understand there’s a nextPageToken for pagination, but I can’t figure out how to correctly use it to fetch subsequent results. How can I implement a proper pagination mechanism for this scenario?

Any advice or examples on how to properly handle this token for paginated requests would be greatly appreciated! Thank you !

Nextcloud error not logged in the server log [closed]

I’m migrating a Nextcloud server to another Rocky Linux server. At first I got this error in the browser:

Internal Server Error

The server encountered an internal error and was unable to complete your request.
Please contact the server administrator if this error reappears multiple times, please include the technical details below in your report.
More details can be found in the server log.

And found it in the data/nextcloud.log:

Failed to connect to the database: An exception occurred in the driver: could not find driver

Then I installed the missing driver but still I have an error but now there is nothing in the server log.

Already searched in /var/log/httpd and /var/log/php-fpm/

How to debug?

I solved the problem by installing missing php modules. But still the question about the log persists.

Laravel 11 – how to call the old ‘Handler.php’ class from app.php – withExceptions

I have recently created a new project in Laravel 11 and can not get my custom error handling class to work. I have a class I use throughout all my Larvael projects (laravel 10). I want to use this class in Laravel 11 to process all my errors, but it seems the new version relies on the withExceptions method in app.php

->withExceptions(function (Exceptions $exceptions) {

Does anyone know how I can get the withExceptions class to still use this (or any) external class for handling


use IlluminateFoundationExceptionsHandler as ExceptionHandler;

class Handler extends ExceptionHandler {

}

Cannot use Static dictionaries as keys of a dictionary

I have a class Unit where I define static Actions for a game

class Unit {
  static Actions = { 
    Idle: 0, 
    Move: 1, 
    Attack: 2
  }
}

I can then refer to this Actions by its name, instead of the value. So in my code I can do something like

if (soldier.action == Unit.Actions.Move) {
  // Moving logic
}

However I noticed that when creating a dictionary, I cannot use this as keys, neither using the dot syntax or the [] syntax.

let myDict= {
  0: "This is Action Idle"                           // Correct
  Unit.Actions.Move:  "This is Action Move",          // Incorrect
  Unit["Actions"]["Attack"]:  "This is Action Attack" // Incorrect
}

Uncaught SyntaxError SyntaxError: Unexpected token '.'

Uncaught SyntaxError SyntaxError: Unexpected token '['

Of course I can use the values of each action (0, 1, 2) but this defeats the purpose of the static dictionary, which is to refer to the Actions by their names, making the code much more clear.

How can I use this static Actions as dictionary keys?

Not recieving messages on clients in Meteor

So I am a newbie at Meteor and in Bigbluebutton 2.4 I have to make a simple message that goes to all the users in a meeting. even without the meeting criteria I still cant get them on my frontend In the code I can subscribe to the ptzmessage and I see it in Meteor.connection._subscriptions list on the browser

componentDidMount() {
    const { onVideoItemMount, cameraId } = this.props;

    console.log("subscribing")
    Meteor.subscribe('ptzmessage').ready()

    this.subscription = Meteor.subscribe('ptzmessage');
    // Retry after 5 seconds if not ready
    this.retryTimeout = setTimeout(() => {
        if (!this.subscription.ready()) {
            console.log("Retrying subscription...");
            this.subscription = Meteor.subscribe('ptzmessage');
        }
        console.log(" subscription completed...");
    }, 5000);

    this.tracker = Tracker.autorun(() => {
      console.log("Fetching messages...");
      const messages = PtzMessages.find({}).fetch();
      this.setState({ messages });
      console.log('Received Messages:', messages);
    });

this is the Api file in import/api/ptzmessage and imported in the frontend and the backend

import { Mongo } from 'meteor/mongo';

// Define PtzMessages collection
export const PtzMessages = new Mongo.Collection('ptzmessages');
if (Meteor.isServer) {
  PtzMessages._ensureIndex({ meetingId: 1 });
}

this is the server code when I press button send message it adds it in the collection

import { Meteor } from 'meteor/meteor';
import { PtzMessages } from '../index.js';

Meteor.publish('ptzmessage', function () {
  console.log(`Client ${this.connection.id} subscribed to ptzmessage`);

  return PtzMessages.find();
});

Meteor.methods({
  sendPtzMessage(message) {
    console.log("#####################################################################################api hit")
    PtzMessages.insert({ text: message, createdAt: new Date() }, (err, res) => {
      if (err) {
        console.error("Insert Error:", err);
      } else {
        console.log("Message inserted successfully:", res);
      }
    });
  }
});

infact in the frontend Meteor.connection._mongo_livedata_collections.ptzmessages.find().fetch();
get me the latest messages but I dont get them real time on the Tracker.
Stuff like this is done in other code that works what am I doing wrong?

Clear Firefox overlays after SPA login

Firefox provides autocomplete and other warning overlays on my SPA login form. After a successful login the overlays remain hovering over the page content, requiring a user interaction to remove them. I can’t get rid of them programmatically except with an annoying full-page reload which should not be necessary.

According to my coworker Chrome has similar artifacts for them but it doesn’t happen to me. Regardless, an SPA should be able to login without page reloads and not have pesky browser overlays hanging around long after the relevant forms disappear and even the page route changes.

example of firefox overlay

How can I use a persistent context with extensions when connecting remotely via Aerokube Moon in Playwright?

I am working with Playwright and setting up tests using Aerokube Moon. In my configuration, I connect remotely to the browser using chromium.connect, which allows me to pass additional parameters through the URL. Here’s an example of my code:

`if (moonConfig.enableMoon) {
console.log(“Starting test via Aerokube – Moon”);

const wsUrl = new URL(moonConfig.remoteUrl);
// For each key in capabilities:
// If the value is an array, add each element as a separate parameter,
// otherwise set the parameter directly.
for (const [key, value] of Object.entries(moonConfig.capabilities)) {
    if (Array.isArray(value)) {
        for (const item of value) {
            wsUrl.searchParams.append(key, item);
        }
    } else {
        wsUrl.searchParams.set(key, value);
    }
}

this.browser = await chromium.connect({ wsEndpoint: wsUrl.toString() });
this.context = await this.browser.newContext({ viewport: { width: 1920, height: 1080 } });
this.page = await this.context.newPage();

}`

The issue is that using newContext() creates an incognito context where I cannot use extensions. I need a persistent context (to load extensions), which is typically created using the launchPersistentContext method.

However, if I try to use launchPersistentContext, I get type errors because this method is not supported when using remote connections via chromium.connect.

My question:
Is there any workaround to use a persistent context (with extension support) when connecting remotely via Aerokube Moon? Or do I need to separate the launch logic based on the environment (i.e., local for persistent context and remote for incognito context)?

Any advice or alternative approaches would be greatly appreciated.

Thank you!

I attempted to use launchPersistentContext when connecting via Aerokube Moon, expecting to get a persistent context with extension support. Instead, I got type errors since persistent contexts aren’t supported with remote connections; chromium.connect only allows creating incognito contexts via newContext()

How to Embed Power BI Report to a Web App in Mobile Layout?

I am trying to embed a Power BI report into a Web App but I want it shown in a mobile layout. I have tried to follow this documentation by adding this parameter layoutType: models.LayoutType.MobilePortrait, but it didn’t work. For more context, to create the Web App and the embed logic, I used the Microsoft Power BI template that is available in their Github Repository. The report that I try to embed already has the mobile layout. Below is my index.js code that contains the embed configuration.

// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.


$(function () {
    var reportContainer = $("#report-container").get(0);

    // Initialize iframe for embedding report
    powerbi.bootstrap(reportContainer, {type: "report"});
    
    var models = window["powerbi-client"].models;
    var reportLoadConfig = {
        type: "report",
        tokenType: models.TokenType.Embed,
        settings: {
            layoutType: models.LayoutType.MobilePortrait,
            background: models.BackgroundType.Transparent,
            filterPaneEnabled: false,
            navContentPaneEnabled: false
        }
    };

    $.ajax({
        type: "GET",
        url: "/getembedinfo",
        dataType: "json",
        success: function (data) {
            embedData = $.parseJSON(JSON.stringify(data));
            reportLoadConfig.accessToken = embedData.accessToken;

            // You can embed different reports as per your need
            reportLoadConfig.embedUrl = embedData.reportConfig[0].embedUrl;

            // Use the token expiry to regenerate Embed token for seamless end user experience
            // Refer https://aka.ms/RefreshEmbedToken
            tokenExpiry = embedData.tokenExpiry;

            // Embed Power BI report when Access token and Embed URL are available
            var report = powerbi.embed(reportContainer, reportLoadConfig);

            // Triggers when a report schema is successfully loaded
            report.on("loaded", function () {
                console.log("Report load successful")
            });

            // Triggers when a report is successfully embedded in UI
            report.on("rendered", function () {
                console.log("Report render successful")
            });

            // Clear any other error handler event
            report.off("error");

            // Below patch of code is for handling errors that occur during embedding
            report.on("error", function (event) {
                var errorMsg = event.detail;

                // Use errorMsg variable to log error in any destination of choice
                console.error(errorMsg);
                return;
            });
        },
        error: function (err) {

            // Show error container
            var errorContainer = $(".error-container");
            $(".embed-container").hide();
            errorContainer.show();

            // Format error message
            var errMessageHtml = "<strong> Error Details: </strong> <br/>" + $.parseJSON(err.responseText)["errorMsg"];
            errMessageHtml = errMessageHtml.split("n").join("<br/>")

            // Show error message on UI
            errorContainer.html(errMessageHtml);
        }
    });
});

Based on my explanation, is there something that I missed or need to add to my code?

Thank you.

how to write a debounce which return exactly the same type as the passed function in typescript?

I hope that the debounce function can realize that the type of the returned function is exactly the same as the type of the passed function (whose return value is void or Promise<void>). I have write the following code

type VoidFunction = (...args: any[]) => void;
type PromiseVoidFunction = (...args: any[]) => Promise<void>;
export function debounce<T extends VoidFunction>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => void;

export function debounce<T extends PromiseVoidFunction>(
  fn: T,
  delay: number
): (...args: Parameters<T>) => Promise<void>;
export function debounce<T extends(VoidFunction | PromiseVoidFunction)>(fn: T, delay: number) {
  let timer: number | null = null;
  return function (this: ThisParameterType<T>, ...args: Parameters<T>): Promise<void> | void {
    if (timer) {
      clearTimeout(timer);
    }
    if (fn.constructor.name === 'AsyncFunction') {
      return new Promise<void>((resolve) => {
        timer = setTimeout(() => {
          timer = null;
          Promise.resolve(fn.apply(this, args)).then(resolve);
        }, delay);
      });
    }
    timer = setTimeout(() => {
      timer = null;
      fn.apply(this, args);
    }, delay);
  };
};

However, when I use this debounce and passed a function has a Promise<void>return type, typescript still infers the return type of the returned function as void

Uploading an image with AJAX after Heic2Any conversion

I am using the Heic2Any.js library to convert .heic files before uploading them. Once the file is converted I append it to a placeholder (#target) so I can see that the conversion worked, and it does. The image element has a JPG blob in it.

If the image is not .heic the form submits and it uploads as normal, using AJAX.

My question is, if it is a .heic file, how do I remove the .heic version from the FormData and replace it with the new JPG version, before submitting the form?

Also, what value do I put into the fetch call?

// HEIC to JPG Conversion

$('.image-input').on('change', function(e) {
    e.preventDefault();

    var fileextension = $(this).val().split('.').pop().toLowerCase();

    if (fileextension == 'heic') {
        fetch(????) 
            .then((res) => res.blob())
            .then((blob) => heic2any({
                blob,
                toType: "image/jpeg",
            }))
            .then((conversionResult) => {
                var url = URL.createObjectURL(conversionResult);
                $(".image-upload-form").find('.image-preview').append('<img src="' + url + '" />');
            })
            .catch((e) => {
                console.log(e);
            });
    } 

    // I want to add the new JPG to the form and then submit it to the AJAX uploader below. 
    $(this).closest(".image-upload-form").submit();
});

// AJAX uploader (this part works great already)

var form = $(this);

$.ajax({
    url: base_url + "upload-image",
    type: "POST",
    data:  new FormData(this),
    dataType: 'json',
    mimeType:"multipart/form-data",
    contentType: false,
    cache: false,
    processData: false,
    success: function(response) {
        if (response.message == 'error') {
            // show error
        } else {
            var src = base_url + 'assets/uploads/' + response.filename;
            form.find('.image-preview').append('<img src="' + src + '" />');
        }
    },
    error: function(error) {
      console.log(error);
    }
});

Safetest netflix implementation- import.meta.webpackContext is undefined – React

I have a react app with jest configuration already.

I am trying to setup netflix safe test. I changed my app as per instructions here at:
https://github.com/kolodny/safetest

I am facing some issue with: import_meta.webpackContext undefined.

`import React from ‘react’;
import { createRoot } from ‘react-dom/client’;
import { bootstrap } from ‘safetest/react’;

import App from ‘./App.jsx’;

const container = document.getElementById(‘app’);
const root = createRoot(container);
const isDev = process.env.NODE_ENV !== ‘production’;

bootstrap({
container,
element: (
<React.StrictMode>
<App />
</React.StrictMode>
),
webpackContext:
isDev &&
import.meta.webpackContext(‘.’, {
recursive: true,
regExp: /.safetest$/,
mode: ‘lazy’,
}),
render: (element) => root.render(element),
});
`

Error:

index.jsx:20 Uncaught TypeError: import_meta.webpackContext is not a function at eval (index.jsx:20:1) at 98963 (app.js:2978:1) at __webpack_require__ (app.js:9773:42) at app.js:9988:89 at __webpack_require__.O (app.js:9815:23) at webpackJsonpCallback (app.js:9974:40) at vendor.js:9:79

webpack version: 5.94.0
Node.js version: 18.20.2

I am wondering what is causing this issue and why my app is not loading:
Is webpack loader is causing this?

{ test: /.(js|jsx)$/, exclude: /node_modules/, loader: 'esbuild-loader', options: { loader: 'jsx', jsx: 'automatic', }, }, { test: /.tsx?$/, use: 'ts-loader', exclude: /node_modules/, },

I even tried using require.context (still didnt work)

Any help will be appreciated, thank you!!

Razorpay’s Blade Design System with Next.js for Server Side Rendering

I am new to Javascript and its frameworks. I am exploring Next.js for my complex website with SEO implications. I want to use Razorpay’s Blade design System for it.

I am not able to use Blade’s component without ‘use client’. So what I understood is that Blade is using some constructs that enforce it to be used on Client Side but I am not sure(as I am beginner). I read that Server Side Rendering is beneficial for SEO and using ‘use client’ I am making my page to render on client side. So I will lose the benefits of Next.

Is there any way that I can use server side rendering with blade?

Script to pull live sports scores [closed]

Hello I need help writing a script that pulls live sports scores and displays them in a program called OBS. I also need help finding were to pull this information and formatting it to fit into OBS the way I would like it to be.

ChatGPT but I just got basic information. Nothing that would actually pull that said information.

Google Maps API – “This API project is not authorized to use this API” (REQUEST_DENIED)

I’m currently working on integrating the Google Maps API into my project and have enabled all required APIs, including:

  • Maps JavaScript API
  • Directions API
  • Geocoding API
  • Places API
  • Distance Matrix API
  • Routes API (including Polyline features)

but the polyline features not working properly as well. even i have enabled every service in google map api. please check the attached image.

other features such as auto suggestion, real time location working perfectly.

it gives this error: Google Maps API – “This API project is not authorized to use this API” (REQUEST_DENIED)

enabled service

I suspect this could be related to API restrictions, billing issues, or something else I may have overlooked.

Has anyone encountered this issue before? Any insights on how to resolve it would be greatly appreciated!

Thank you in advance!

Webpack not exposing all the package.json dependencies in the generated library ( browser code )

I have a webpack config to bundle all the node_modules dependencies mentioned in the package.json file. The following config file generates a library which exposes only the last mentioned in dependency in dependencies list.

const { webpack, ProvidePlugin } = require("webpack");
const { dependencies } = require('./package.json');
const path = require('path');

const provideConfig = {};
Object.keys(dependencies).forEach(dep=>{
    provideConfig[dep] = dep;
});

module.exports = {
   mode: "development",
   target: ['web','es5'],
   entry:{
       vendor: Object.keys(dependencies) // Create a separate entry for each dependency
   },
   output:{
      filename: 'bundle.js',
      path: path.resolve(__dirname, '.'),
      library: 'myLibrary',
      libraryTarget: 'umd'
   },
   plugins: [
      new ProvidePlugin(providePlugin)
   ],
   devtool: 'source-map'
};

I am expecting this to expose the the dependency as,
myLibrary.<dependency_name>

This is only exposing the last dependency in dependencies list of package.json

I am using webpack 5.98