Dev launcher setup that initializes twice on Android React Native app startup causes crash

My app crashes during startup.

When I use logcat I get the error
(reverse domain name deliberately obscured for security):

 E  FATAL EXCEPTION: main (Ask Gemini)
                                                                                                    Process: co.uk.*****.provisioner, PID: 11384
                                                                                                    java.lang.RuntimeException: Unable to create application co.uk.*****.provisioner.MainApplication: java.lang.IllegalStateException: DevelopmentClientController was initialized.
                                                                                                        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:7716)
                                                                                                        at android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2478)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:230)
                                                                                                        at android.os.Looper.loop(Looper.java:319)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8919)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:578)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)
                                                                                                    Caused by: java.lang.IllegalStateException: DevelopmentClientController was initialized.
                                                                                                        at expo.modules.devlauncher.DevLauncherController$Companion.initialize$expo_dev_launcher_debug(DevLauncherController.kt:404)
                                                                                                        at expo.modules.devlauncher.DevLauncherController$Companion.initialize(DevLauncherController.kt:438)
                                                                                                        at expo.modules.devlauncher.DevLauncherController$Companion.initialize$default(DevLauncherController.kt:437)
                                                                                                        at expo.modules.devlauncher.DevLauncherPackageDelegate$createApplicationLifecycleListeners$1.onCreate(DevLauncherPackageDelegate.kt:36)
                                                                                                        at expo.modules.ApplicationLifecycleDispatcher.onApplicationCreate(ApplicationLifecycleDispatcher.kt:20)
                                                                                                        at co.uk.*****.provisioner.MainApplication.onCreate(MainApplication.kt:50)
                                                                                                        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1316)
                                                                                                        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:7711)
                                                                                                        at android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0) 
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2478) 
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106) 
                                                                                                        at android.os.Looper.loopOnce(Looper.java:230) 
                                                                                                        at android.os.Looper.loop(Looper.java:319) 
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8919) 
                                                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:578) 
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103) 
2025-04-17 12:34:41.911 11384-11384 DevLauncher             co.uk.*****.provisioner              E  DevLauncher tries to handle uncaught exception. (Ask Gemini)
                                                                                                    java.lang.RuntimeException: Unable to create application co.uk.*****.provisioner.MainApplication: java.lang.IllegalStateException: DevelopmentClientController was initialized.
                                                                                                        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:7716)
                                                                                                        at android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0)
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2478)
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                        at android.os.Looper.loopOnce(Looper.java:230)
                                                                                                        at android.os.Looper.loop(Looper.java:319)
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8919)
                                                                                                        at java.lang.reflect.Method.invoke(Native Method)
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:578)
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)
                                                                                                    Caused by: java.lang.IllegalStateException: DevelopmentClientController was initialized.
                                                                                                        at expo.modules.devlauncher.DevLauncherController$Companion.initialize$expo_dev_launcher_debug(DevLauncherController.kt:404)
                                                                                                        at expo.modules.devlauncher.DevLauncherController$Companion.initialize(DevLauncherController.kt:438)
                                                                                                        at expo.modules.devlauncher.DevLauncherController$Companion.initialize$default(DevLauncherController.kt:437)
                                                                                                        at expo.modules.devlauncher.DevLauncherPackageDelegate$createApplicationLifecycleListeners$1.onCreate(DevLauncherPackageDelegate.kt:36)
                                                                                                        at expo.modules.ApplicationLifecycleDispatcher.onApplicationCreate(ApplicationLifecycleDispatcher.kt:20)
                                                                                                        at co.uk.*****.provisioner.MainApplication.onCreate(MainApplication.kt:50)
                                                                                                        at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1316)
                                                                                                        at android.app.ActivityThread.handleBindApplication(ActivityThread.java:7711)
                                                                                                        at android.app.ActivityThread.-$$Nest$mhandleBindApplication(Unknown Source:0) 
                                                                                                        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2478) 
                                                                                                        at android.os.Handler.dispatchMessage(Handler.java:106) 
                                                                                                        at android.os.Looper.loopOnce(Looper.java:230) 
                                                                                                        at android.os.Looper.loop(Looper.java:319) 
                                                                                                        at android.app.ActivityThread.main(ActivityThread.java:8919) 
                                                                                                        at java.lang.reflect.Method.invoke(Native Method) 
                                                                                                        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:578) 
                                                                                                        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1103)

GitHub Copilot says:

The error DevelopmentClientController was initialized means that somewhere during the app’s startup, the Dev Launcher setup is happening twice. While the call ApplicationLifecycleDispatcher.onApplicationCreate(this) is standard, something it triggers, or perhaps another part of your native setup, is causing the duplicate initialization.

The crash log points to an issue within the Expo Dev Launcher’s initialization process, which is triggered by:

// This line triggers Expo's setup, including the Dev Launcher
ApplicationLifecycleDispatcher.onApplicationCreate(this) 

in your MainApplication.kt’s onCreate method:

package co.uk.*****.provisioner

import android.app.Application
import android.content.res.Configuration

import com.facebook.react.PackageList
import com.facebook.react.ReactApplication
import com.facebook.react.ReactNativeHost
import com.facebook.react.ReactPackage
import com.facebook.react.ReactHost
import com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load
import com.facebook.react.defaults.DefaultReactNativeHost
import com.facebook.react.soloader.OpenSourceMergedSoMapping
import com.facebook.soloader.SoLoader

import expo.modules.ApplicationLifecycleDispatcher
import expo.modules.ReactNativeHostWrapper

class MainApplication : Application(), ReactApplication {

  override val reactNativeHost: ReactNativeHost = ReactNativeHostWrapper(
        this,
        object : DefaultReactNativeHost(this) {
          override fun getPackages(): List<ReactPackage> {
            val packages = PackageList(this).packages
            // Packages that cannot be autolinked yet can be added manually here, for example:
            // packages.add(new MyReactNativePackage());
            return packages
          }

          override fun getJSMainModuleName(): String = ".expo/.virtual-metro-entry"

          override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG

          override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED
          override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED
      }
  )

  override val reactHost: ReactHost
    get() = ReactNativeHostWrapper.createReactHost(applicationContext, reactNativeHost)

  override fun onCreate() {
    super.onCreate()
    SoLoader.init(this, OpenSourceMergedSoMapping)
    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {
      // If you opted-in for the New Architecture, we load the native entry point for this app.
      load()
    }
    ApplicationLifecycleDispatcher.onApplicationCreate(this)
  }

  override fun onConfigurationChanged(newConfig: Configuration) {
    super.onConfigurationChanged(newConfig)
    ApplicationLifecycleDispatcher.onConfigurationChanged(this, newConfig)
  }
}

I’ve searched through all files in my Android directory that may be relevant, but I haven’t found anything that could be triggered by the suspect line in the code sample above. I also haven’t found any other part of my native Android system that could cause the duplication.

react date picker component fails with an error invalid hook call

I am trying to use React – Date picker npm module and below is my code.
using the datepicker in a class component fails with an invalid hook error.

Here is the code

    import React, { Component ,useState } from "react";
    import logo from "./logo.svg";
    import { connect } from 'react-redux';
    import { bindActionCreators } from 'redux';
    import { withRouter } from 'react-router-dom';
    import "./App.css";
    import axios from 'axios';
    import "bootstrap/dist/css/bootstrap.css";
    import "react-bootstrap-table-next/dist/react-bootstrap-table2.min.css";
    import 'react-bootstrap-table-next/dist/react-bootstrap-table2.min.css';
    import 'react-bootstrap-table2-paginator/dist/react-bootstrap-table2-paginator.min.css';
    import BootstrapTable from "react-bootstrap-table-next";
    import paginationFactory from 'react-bootstrap-table2-paginator';
    import Select from 'react-select';
    import cellEditFactory from 'react-bootstrap-table2-editor';
  
    import "react-datepicker/dist/react-datepicker.css";
  
    import DatePicker from 'react-date-picker';
    import moment from 'moment';
  
 // class component     


    class App extends React.Component {
      constructor(props, context){
        super(props);  
        this.state={columns : [],schemaData: [] ,selectedDate:null,
    submittedValue:[],columnsList: [],schemaDataOriginal: [] ,selectedOption: null,selectedOptionNext: null, options: [{ value: null, label: 'Select...' }] , optionsNext: [{ value: null, label: 'Select...' }] ,
                colStyle : {
          backgroundColor: '#5F9EA0',
          width: '200px',
          fontSize: '13px'
        },
        paginationOption :{
      custom: true,
      marginLeft: '35px'
    }
        };  
        this.handleDateChange = this.handleDateChange.bind(this);
      
      this.state.selectStyles = {
      menuList: styles => ({
        ...styles,
        background: 'white',
      }),
      option: (styles, { isFocused, isSelected }) => ({
        ...styles,
        background: isFocused
          ? '#5F9EA0'
          : isSelected
            ? '#5F9EA0'
            : undefined,
        zIndex: 1,
      }),
      menu: base => ({
        ...base,
        zIndex: 100,
      }),
    }
    
    
    }
    fetchEdSource(tableNameFirst){
      var paramKey = {};
      paramKey['tableNameFirst']= tableNameFirst;
      
      axios.get("/apiEdSource",{responseType: 'json',params: paramKey}).then((res)=>{
      this.setState({schemaDataOriginal: res.data});
      this.state.schemaData= this.state.schemaDataOriginal;
       var sb = [];
       var ot = [];
      var otn = [];
        this.state.columnsList = Object.keys(this.state.schemaDataOriginal[0]);
        Object.keys(this.state.schemaDataOriginal[0]).map((key) =>{   
        sb.push({dataField: key,text: key, sort : true, headerStyle: this.state.colStyle});
       })
          this.state.columns = sb;
         this.state.schemaDataOriginal.map((arrayData) =>{   
        ot.push({value: arrayData["SOURCE_SYSTEM"]
    , label: arrayData["SOURCE_SYSTEM"]
    })
    })
      
        
    
        this.state.schemaDataOriginal.map((arrayData) =>{   
          otn.push({value: arrayData["TABLE_NAME"]
    , label: arrayData["TABLE_NAME"]
    });
      
        
    
    
       })
    
    
        const filtered = ot.filter(function({value, label}) {
    
      const key =`${value}${label}`;
    
      return !this.has(key) && this.add(key);
    
    }, new Set);
         console.log(this.state.options);
         for(var i=0;i<filtered.length;i++){
         this.state.options.push(filtered[i]);
       }
    
    
    
     const filteredotn = otn.filter(function({value, label}) {
    
      const key =`${value}${label}`;
    
      return !this.has(key) && this.add(key);
    
    }, new Set);
    console.log(this.state.optionsNext);
    
    for(var i=0;i<filteredotn.length;i++){
    this.state.optionsNext.push(filteredotn[i]);
    }
    

    
    
         
    }).catch(e=>{
    console.log(e)
    });
    
    }
    
    
    updateSelectList(selectedOption){
      
     var otn = [];
     this.state.optionsNext = [];
    
        this.state.schemaDataOriginal.map((arrayData) =>{  
    
    
        if(selectedOption!==null && selectedOption["label"]==arrayData["SOURCE_SYSTEM"]) { 
          otn.push({value: arrayData["TABLE_NAME"]
    , label: arrayData["TABLE_NAME"]
    });
    }
        else if(selectedOption["label"] == "Select..."){
    
        otn.push({value: arrayData["TABLE_NAME"]
    , label: arrayData["TABLE_NAME"]
    
    } )
     }
    
     })
        
    
    for(var i=0;i<otn.length;i++){
    this.state.optionsNext.push(otn[i]);
    }
    this.state.optionsNext.push({ value: null, label: 'Select...' });
    
    const filteredotn = this.state.optionsNext.filter(function({value, label}) {
    
      const key =`${value}${label}`;
    
      return !this.has(key) && this.add(key);
    
    }, new Set);
    
      this.state.optionsNext = filteredotn;
      
    
    }
      
    
    
    updateTableList(selectedOption, selectedOptionNext){
    var tempSchemaData = [];
    this.state.schemaDataOriginal.map((arrayData) =>{   
      if(selectedOption!==null || this.state.selectedOptionNext!== null){
        
     
          if(this.state.selectedOptionNext==null){
    
                       if(selectedOption["label"]==arrayData["SOURCE_SYSTEM"]){
                      tempSchemaData.push(arrayData);
                             }
                      else if (selectedOption["label"]=="Select..."){
                        this.state.schemaData=this.state.schemaDataOriginal;
    
                      }
          }
    
          else if(this.state.selectedOptionNext!==null && (selectedOption["label"]==arrayData["SOURCE_SYSTEM"]&&this.state.selectedOptionNext["label"]==arrayData["TABLE_NAME"])){
          tempSchemaData.push(arrayData);
          }
          else if(selectedOption["label"]=="Select..."){
                        this.state.schemaData=this.state.schemaDataOriginal;
    
                      }
    
      }
      if(selectedOption["label"]!=="Select..."){
      this.state.schemaData=tempSchemaData  ;
    }
    })
    
      }
    
    handleChange = (selectedOption) => {
        this.setState({ selectedOption }, () =>
          console.log(`Option selected:`, this.state.selectedOption)
    
        )
        this.state.selectedOption=selectedOption;
    this.updateSelectList(selectedOption);
    this.updateTableList(this.state.selectedOption,this.state.selectedOptionNext);
    
      };
    
    handleChangeNext = (selectedOptionNext) => {
        this.setState({ selectedOptionNext }, () =>
          console.log(`Option selected:`, this.state.selectedOptionNext)
        );
        this.state.selectedOptionNext=selectedOptionNext;
        this.updateTableList(this.state.selectedOption,this.state.selectedOptionNext);
      };
    
    submitCell=()=>{
      var paramKey = {};
    // paramKey['newValue']= this.state.submittedValue[0]["newValue"];
    // paramKey['fieldUpdated']= this.state.submittedValue[0]["TABLE_ID"]["dataField"];
    // paramKey['TABLE_ID']= this.state.submittedValue[0]["fieldUpdated"]["TABLE_ID"];
    if(this.state.submittedValue.length!==0){
    var params = new URLSearchParams();
    // for  (var i=0; i<this.state.submittedValue.length;i++){
    
    // params.append('newValue', this.state.submittedValue[0]["newValue"]);
    // params.append('fieldUpdated', this.state.submittedValue[0]["TABLE_ID"]["dataField"]);
    // params.append('TABLE_ID',this.state.submittedValue[0]["fieldUpdated"]["TABLE_ID"]);
    // }
    
    const encodedFilters = encodeURIComponent(JSON.stringify(this.state.submittedValue));
    console.log(encodedFilters.toString);

     let config = {
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded',
      } 
    } ;
    var url =`/apiEdSourceUpdate?filters=${encodedFilters}`;
    
     axios.post(url,params, config).then((res)=>{
         
    }).catch(e=>{
    console.log(e)
    });
    }
    this.state.submittedValue=[];
    }
    saveCell=(oldValue, newValue, fieldUpdated,TABLE_ID)=>{
     
    
    this.state.submittedValue.push({"oldValue": oldValue,"newValue":newValue,"fieldUpdated":fieldUpdated,"TABLE_ID":TABLE_ID});
    
    }
    
    handleDateChange(date) {
        this.setState({
          selectedDate: date
        });
        
      }

 //here is the render function 

  
    
     render()
     {
      const { selectedOption } = this.state;
      const {selectedOptionNext} = this.state;
    const {selectedDate}   = this.state;
      
    
    
      return (
        <div className="App">   
        {this.state.columns.length !==0 ? <div>
          <Select
          className="react-select"
            value={selectedOption}
            onChange={this.handleChange}
            options={this.state.options}
            styles={this.state.selectStyles}
            
          />
          <Select
          className="react-selectNext"
            value={selectedOptionNext}
            onChange={this.handleChangeNext}
            options={this.state.optionsNext}
            styles={this.state.selectStyles}
    
          />
          
          <DatePicker value={this.state.selectedDate} onChange={(date) => this.handleDateChange(date)} />
    
          <button className="label" onClick={()=>{this.submitCell(this.state)}}>SUBMIT</button>
          <BootstrapTable  className="react-bootstrap" boostrap4 keyField='TABLE_ID' data={ this.state.schemaData } columns={ this.state.columns } pagination={paginationFactory()} 
          cellEdit={cellEditFactory({ mode: 'click', blurToSave: false ,autoSelectText: false,
            afterSaveCell: (oldValue, newValue,row, column) =>{
              this.saveCell(oldValue, newValue,row, column)
            }
      })}/></div>:<div>    <ul class="notes">     
              <li onClick={() => {this.fetchEdSource('[ODIN_WORK.[dbo].[ed_source_table]')}}><a  href="#1a" id="notes-list" data-toggle="tab">ED Source Table</a></li>
        </ul>
        </div>}
        </div>
        
      );
    }
    }


export default App;

This code throws error:

enter image description here

Attached above the complete which is a webpage for uses react-bootstrap to render the table and react-search for the dropdowns. The error is to include a react datepicker

How to add a repeating header after injecting a page break at a specific table row?

I’m trying to generate a PDF using html2pdf.js from html that includes a dinamically filling table. The table may span multiple pages and since i don’t know where the page breaks are going to be, I can’t place the simple page-breaker div. On each page’s top I need to place a header. (not a but a custom )

I have a code that puts the header at a place where i manually place a page-breaker div, but i’d need this automated and I can’t get a hold of it for my life’s sake.

function injectHeadersForPDF() {

   document.querySelectorAll(".pdf-header-clone").forEach((el) => el.remove());


   const headerTemplate = document.querySelector(".header-content");
   const pageBreaks = document.querySelectorAll(".html2pdf__page-break");

   pageBreaks.forEach((breakEl) => {
       const clone = headerTemplate.cloneNode(true);
       clone.classList.add("pdf-header-clone");
       clone.style.marginBottom = "30px";
       breakEl.parentNode.insertBefore(clone, breakEl.nextSibling);
   });
}

document.getElementById("mentes").addEventListener("click", () => {
   const element = document.getElementById("card-body");

   injectHeadersForPDF();
   element.classList.add("pdf-mode");

   const opt = {
       margin: [10, 10, 10, 10],
       filename: "myfile.pdf",
       image: {
           type: "jpeg",
           quality: 0.99
       },
       html2canvas: {
           scale: 5,
           scrollX: 0,
           scrollY: 0,
           windowWidth: document.body.scrollWidth,
           windowHeight: document.body.scrollHeight,
       },
       jsPDF: {
           unit: "mm",
           format: "a3",
           orientation: "portrait"
       },
   };

   html2pdf()
       .set(opt)
       .from(element)
       .save()
       .then(() => {

           document.querySelectorAll(".pdf-header-clone").forEach((el) => el.remove());
           element.classList.remove("pdf-mode");
       });
});

html2pdf.js – How to add a repeating header after injecting a page break at a specific table row?

I’m trying to generate a PDF using html2pdf.js from html that includes a dinamically filling table. The table may span multiple pages and since i don’t know where the page breaks are going to be, I can’t place the simple page-breaker div. On each page’s top I need to place a header. (not a but a custom )

I have a code that puts the header at a place where i manually place a page-breaker div, but i’d need this automated and I can’t get a hold of it for my life’s sake.

function injectHeadersForPDF() {

   document.querySelectorAll(".pdf-header-clone").forEach((el) => el.remove());


   const headerTemplate = document.querySelector(".header-content");
   const pageBreaks = document.querySelectorAll(".html2pdf__page-break");

   pageBreaks.forEach((breakEl) => {
       const clone = headerTemplate.cloneNode(true);
       clone.classList.add("pdf-header-clone");
       clone.style.marginBottom = "30px";
       breakEl.parentNode.insertBefore(clone, breakEl.nextSibling);
   });
}

document.getElementById("mentes").addEventListener("click", () => {
   const element = document.getElementById("card-body");

   injectHeadersForPDF();
   element.classList.add("pdf-mode");

   const opt = {
       margin: [10, 10, 10, 10],
       filename: "myfile.pdf",
       image: {
           type: "jpeg",
           quality: 0.99
       },
       html2canvas: {
           scale: 5,
           scrollX: 0,
           scrollY: 0,
           windowWidth: document.body.scrollWidth,
           windowHeight: document.body.scrollHeight,
       },
       jsPDF: {
           unit: "mm",
           format: "a3",
           orientation: "portrait"
       },
   };

   html2pdf()
       .set(opt)
       .from(element)
       .save()
       .then(() => {

           document.querySelectorAll(".pdf-header-clone").forEach((el) => el.remove());
           element.classList.remove("pdf-mode");
       });
});

What to do next in Javascript [closed]

recently I learned arrays , string , objects , functions – hof , closures , carrying , function methods , now what I need to do . I mean how can I master in these topics . And how should I be improved in javascript. Please help me .. what to practice what problem and what kind of projects should I work.

Can’t render a PDF page on node-canva – NodeJS, pdfjs-dist

I’m trying to use this lib to render a PDF page at certain dimensions, but I can’t manage to make it work, could you tell me what I do wrong ?

Modules I use:

“canvas”: “Automattic/node-canvas#master”
=>Because of incompatibility problems with node 22, I also tried with “^3.1.0” and node 20 but the issue is still here.

“pdfjs-dist”: “^5.1.91”

My code is the following:

import pdfjs from "pdfjs-dist/legacy/build/pdf.mjs";
import Canvas from "canvas";

...code

const pdf = await pdfjs.getDocument(new Uint8Array(file_.file)).promise;
const page = await pdf.getPage(1);

const viewport = page.getViewport({
  scale: thumbnailWidth / page.getViewport({ scale: 1 }).width,
});

const canvas = Canvas.createCanvas(
  Math.floor(viewport.width),
  Math.floor(viewport.height)
);
const context = canvas.getContext("2d") as any;

await page.render({
      canvasContext: context,
      viewport,
    }).promise;

...code

And I get this output on the last instruction:

err: {
"type": "TypeError",
"message": "Image or Canvas expected",
"stack":
gestion-documentaire:dev:           TypeError: Image or Canvas expected
    at drawImageAtIntegerCoords (_project_location_/node_modules/pdfjs-dist/legacy/build/gestion-documentaire:dev: 
   at CanvasGraphics.paintInlineImageXObject (_project_location_/node_modules/pdfjs-distgestion-documentaire:dev: 4:5)
    at CanvasGraphics.paintImageXObject (_project_location_/node_modules/pdfjs-dist/legacgestion-documentaire:dev: 
  at CanvasGraphics.executeOperatorList (_project_location_/node_modules/pdfjs-dist/leggestion-documentaire:dev: )
  at InternalRenderTask._next (_project_location_/node_modules/pdfjs-dist/legacy/build/gestion-documentaire:dev: 
  at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
}

I do the canvas.getContext(“2d”) as any; workaround because if I don’t, I get this error (translated from french by my own) on the await page.render… instruction:

Type 'CanvasRenderingContext2D' don't have following properties of the 'CanvasRenderingContext2D' type: isPointInStroke, createConicGradient, filter, imageSmoothingQuality and 10 others.ts(2740)
api.d.ts(420, 5): The awaited type comes from the 'canvasContext' property, which is declared on the 'RenderParameters' type.

Thank you.

An error occurred while rendering Collection: Invalid version. Must be a string. Got type “undefined” [closed]

throw new TypeError(‘argument handler must be a function’)
^

TypeError: argument handler must be a function
at Route. [as post] (C:Desktopbackendsearchnode_modulesrouterlibroute.js:228:15)
at Router. [as post] (C:Desktopbackendsearchnode_modulesrouterindex.js:448:19)
at Object. (C:DesktopbackendsearchRouterssearchRouter.js:5:8)
at Module._compile (node:internal/modules/cjs/loader:1554:14)
at Object..js (node:internal/modules/cjs/loader:1706:10)
at Module.load (node:internal/modules/cjs/loader:1289:32)
at Function._load (node:internal/modules/cjs/loader:1108:12)
at TracingChannel.traceSync (node:diagnostics_channel:322:14)
at wrapModuleLoad (node:internal/modules/cjs/loader:220:24)
at Module.require (node:internal/modules/cjs/loader:1311:12)

Node.js v22.14.0
[nodemon] app crashed – waiting for file changes before starting…

Can’t get JSON response from fetch request – getting “.json() is not a function” error [closed]

I am trying to post JSON to a Webhook and then parse the JSON the webhook sends back.

This is what I have for so far but I get the error:

resp.json is not a function

What is wrong?

const data = "{"Customer": "My Company"}";
const resp = fetch("https://my.apiserver.org", {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
    "Content-type": "application/json; charset=UTF-8"
    }
});

const json = await resp.json();

How to sort a 2d array in Apps script (google sheet) base on a 1d array

I have a script that I have been using for some time, but I recently had a bug on a data spell and since then I have been unable to fix the problem.

I transpose arrays because they are normally horizontal.

function test() {
var objects = spreadsheet.getSheetByName("Feuille 121").getRange("A1:GG2").getValues()
var order = spreadsheet.getSheetByName("Feuille 121").getRange("A3:GG3").getValues().flat()

objects = Object.keys(objects[0]).map(function (c) { return objects.map(function (r) { return r[c]; }); });
order = Object.keys(order[0]).map(function (c) { return order.map(function (r) { return r[c]; }); });

// organise dans l'ordre des paramètre
let orderIndex = {}
order.forEach((value, index) => orderIndex[value] = index);

// Sort
objects.sort((a, b) => orderIndex[a[0]] - orderIndex[b[0]]); 

var length = objects.length

objects = Object.keys(objects[0]).map(function (c) { return objects.map(function (r) { return r[c]; }); });
console.log(objects)
spreadsheet.getSheetByName("Feuille 121").getRange(1,1,2,length).setValues(objects)

}

`strip_tags` not working with pretty simple string in PHP

I have a long HTML code that contains <script>, <style>, <div>… tags and strip_tags usually works fine. But with the string below, it’s buggy:

$string = '

    <div>BEGINNING</div>

    <script>
    for (let i=0;i<resultado4448.length;i++) {

    }
    </script>

    <div>END</div>

';

echo strip_tags($string);

The code above outputs:

BEGINNING


for (let i=0;i

Which is incorrect, because the END div was not displayed. I think strip_tags got confused with <resultado4448 believing it is a tag and since it didnt find the closing one, it kept searching till the end of the string.

So, if strip_tags is not reliable for this case, is there any other native function or thing that I can do? I dont want to parse the entire document just to get the tags stripped, I have to parse millions of HTML strings each day and strip_tags is being very good and has a good performance, but if I had to parse all HTML codes, it would take forever.

PHP lib google/apps-chat upload document failed with Service Account permission error

        ...
        // Create a client.
        $chatServiceClient = new ChatServiceClient([
                'credentials' => "$keyPath/songanhbot-sa-02.json",
            ]
        );

        // Prepare the request message.
        $request = (new CreateMessageRequest())
            ->setParent($space)
            ->setMessage((new Message())->setText($messageText));

        // Call the API and handle any network failures.
        try {
            $chatServiceClient->createMessage($request);

            $request = (new UploadAttachmentRequest())
                ->setParent($space)
                ->setFilename($filePath);

            try {
                $response = $chatServiceClient->uploadAttachment($request);
            } catch (ApiException $ex) {
                printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
            }
        } catch (ApiException $ex) {
            printf('Call failed with message: %s' . PHP_EOL, $ex->getMessage());
        }

I have coded this to send message and upload attachment to a Space within a Workspace.

The code can send the message successfully but failed for uploading the attachment, here is the error print from the code:

Call failed with message: {
    "message": "This method doesn't support service account authentication. Authenticate with a user account.",
    "code": 7,
    "status": "PERMISSION_DENIED",
    "details": [
        {
            "@type": "type.googleapis.com/google.rpc.Help",
            "links": [
                {
                    "description": "See article Authenticate as a user.",
                    "url": "https://developers.google.com/chat/api/guides/auth/users"
                }
            ]
        }
    ]
}

The json key file is for a service account which has already been added to Domain wide delegation via Workspace Admin(Api Controls).

The scopes enables:

I use PHP yii2 framework version: 2.0.51 and google/apps-chat version: 0.10

Please help!

Why does PHP not find ini files even though it scanned the directory they’re in?

I’m trying to run composer install but it’s not finding my extensions. It suggests I run php --ini as a debug step, and it reports “(none)” additional .ini files parsed:

  - Running `php --ini`

      Loaded Configuration File:         /my_dir/etc/php/php.ini
      Scan for additional .ini files in: /my_dir/etc/php/conf.d

      Additional .ini files parsed:      (none)

But when you look at that directory there are clearly additional .ini files in there:

  - Running `ls -1 /my_dir/etc/php/conf.d`

      000-my.ini
      010-ext-zend_opcache.ini
      100-ext-gmp.ini
      110-ext-imap.ini
      120-ext-intl.ini
      130-ext-ldap.ini
      140-ext-raphf.ini
      150-ext-pq.ini
      160-ext-redis.ini
      170-ext-sqlite3.ini

Any ideas why PHP isn’t finding the .ini files in the directory it claims it’s looking in? What other debugging information could I provide?

Debugging output

The files exist and is loadable:

  - Running `php -c /my_dir/etc/php/conf.d/000-my.ini --ini`

      Loaded Configuration File:         /my_dir/etc/php/conf.d/000-my.ini
      Scan for additional .ini files in: /my_dir/etc/php/conf.d

      Additional .ini files parsed:      (none)

But another file gave me an error as it couldn’t load the so. I think that’s the problem:

Warning: Failed loading Zend extension 'opcache.so' 
(tried: /does/not/exist/php/lib/php/extensions/no-debug-non-zts-20230831/opcache.so 
(/does/not/exist/php/lib/php/extensions/no-debug-non-zts-20230831/opcache.so: 
cannot open shared object file: 
No such file or directory), /does/not/exist/php/lib/php/extensions/no-debug-non-zts-20230831/opcache.so.so 
(/does/not/exist/php/lib/php/extensions/no-debug-non-zts-20230831/opcache.so.so: 
cannot open shared object file: 
No such file or directory)) in Unknown on line 0

Thanks Alex Howansky. Please upvote the comment that suggested this debug method.