Hubspot form embed onFormReady function from hbspt.forms.create TypeError: e.serializeArray is not a function

I am trying to serialize an array for inputs in the Hubspot form to add or change cookies, but I keep getting the error onFormReady function from hbspt.forms.create TypeError: e.serializeArray is not a function and I don’t know what to do. I am trying to not use jQuery, what can I use to replace it?

<script>
  hbspt.forms.create({
  region: "",
  portalId: "",
  formId: "",
  redirectUrl: "/thank-you/",
  onFormReady: function(e){
    e.serializeArray().map(x=>{
      let cookie_val = Cookies.get(x.name)
      if (cookie_val && cookie_val != ''){
        e.find('input[name="'+x.name+'"]').val(cookie_val).change();
      }
    })
  }
});
</script>

Online learning management system [closed]

To integrate payment functionality into your PHP project and separate the roles of Registrar and Department Head from the Admin role, could you kindly provide guidance on the following steps:

  1. Integrating Payment Functionality:

    • Which payment gateways like PayPal, Stripe, or Square would be recommended for processing payments in a PHP project?
    • How can one effectively create an account with the chosen payment gateway and seamlessly integrate their API into the project?
    • What specific steps should be followed to set up payment forms, handle payment responses, and ensure secure transactions?
  2. Separating Roles:

    • What are the best practices for defining distinct user roles such as Instructor, Admin, Registrar, Student, and Department Head within a PHP project?
    • How can the authentication system be modified to assign precise permissions and access levels to each role, either through user roles and permissions management libraries or custom code?
    • What strategies should be employed to restrict certain actions to specific roles, ensuring that only Admins have access to critical operations like user management and financial transactions?
  3. Removing Registrar and Department Head from Admin:

    • What steps should be taken to create dedicated controllers or modules for Registrar and Department Head functionalities within the project?
    • How can the user interface be updated to display relevant options and features based on the user’s role, enhancing user experience and usability?
    • Could you elaborate on the implementation of role-based access control (RBAC) to manage permissions for each role independently, allowing for precise definition of actions permissible for each role?

Should you require further clarification or assistance with the implementation of these functionalities, or encounter any specific challenges during the process, please do not hesitate to provide additional details or seek guidance on next steps. Additionally, comprehensive resources and support related to PHP development can be explored to facilitate a smooth and efficient project execution.

How do I add structured data json script to Pug JS

I am trying to add in a script of json that is structured data for SEO into my Pug JS file. I am doing it the same way I do JavaScript with type="text/javascript", but it does not compile and I keep getting errors. Is it a syntax issue? Please tell me what I am doing wrong, thank you.

script(type="application/ld+json"{ "@context": "https://schema.org", "@graph": [ { "@type": "WebPage", "@id": "https://www.example.io/some-page/", "url": "https://www.example.io/some-page/", "name": "Access Example's Knowledge Base", "isPartOf": { "@id": "https://www.example.io/#website" })
Unexpected character : expected `=`
Details:
    code: PUG:INVALID_KEY_CHARACTER
    msg: Unexpected character : expected `=`
    line: 14
    column: 53
Syntax Error: Unexpected token
Details:
    code: PUG:SYNTAX_ERROR
    msg: Syntax Error: Unexpected token
    line: 14
    column: 38

i want to create an ecommerce web page [closed]

I can make an ecommerce website and know some basic backend. I want to create a JSON file that contains all the data about the products in it. I know how to fetch that data, but I don’t know how to take the data to the next page. For example, if I click on a Nike shoe on the site. I want to open a new page with the data about the Nike shoe. I want fetch that data from the JSON file.

I don’t know where to start doing this. What should I search on the internet. and is there a better way to do this?

Thank You!

I have trouble with Promise {} in node js

const fs = require('fs');
const csv = require('csv-parser');
const axios = require('axios');
const { createObjectCsvWriter } = require('csv-writer');

console.time('ScriptExec');
let outputData = [];

const csvWriter = createObjectCsvWriter({path: 'output.csv'});

async function makeGraphQLRequest(apiUrl, query, variables) {
    try {
        const response = await axios.post(apiUrl, {
            query: query,
            variables: variables,
        });
        return response.data.data.price_trader_log
        .map(entry => entry.values[entry.values.length - 1].price_trader_new);
    } catch (error) {
        setTimeout(() => makeGraphQLRequest(), 2000);
    }
}


const apiUrl = 'https://wiki.cs.money/api/graphql';
const query = `
query price_trader_log($name_ids: [Int!]!) {
  price_trader_log(input: {name_ids: $name_ids}) {
    name_id
    values {
      price_trader_new
    }
  }
}
`;


fs.createReadStream('variables.csv')
.pipe(csv()).on('data', async (row) => {
    const nameIds = row.name_ids.split(',').map(id => parseInt(id.trim()));
    const scrapInfo = [];
    console.log(nameIds);

    for (const pickId of nameIds) {
        console.log(pickId);
        if ( pickId > 0 ) {
            const variables = { name_ids: pickId };
            makeGraphQLRequest(apiUrl, query, variables)
                .then(result => scrapInfo.push(result))  //console.log(result) is Promise {<pending>}
                .catch(err => console.error(err));
        } else {
            scrapInfo.push(pickId);
        }
    }
    outputData.push( {title: row.title, prices: scrapInfo} );
    console.log(outputData);
}).on('end', () => {    // this saver doesn`t work
    csvWriter.writeRecords(outputData) 
        .then(() => console.log('Data sucsesfully writed in output.csv'))
        .catch(err => console.error('ERROR in wrhite csv process:', err))
    console.timeEnd('ScriptExec');
  });

Example of variables.csv:
title,name_ids
usp-s|whiteout,”1087302,1086843,1086836,1087237,1087212″
usp-s|targetacquired,”1083799,1083764,1083692,1083800,1084013″
usp-s|killconfirmed,”942,896,1332,7411,1042″
usp-s|killconfirmed_stattrak,”13665,13822,2429,587,2595″
usp-s|printstream,”1092369,1092414,1092339,1092498,1092346″
usp-s|printstream_stattrak,”1092439,1092295,1092405,1092442,1092422″
usp-s|orangeanolis,”1087219,1087263,1087249,0,0″
usp-s|darkwater,”0,1581,10527,0,0″

I try await makeGraphQLRequest and block .then().catch()

Receiving data in chunks stops fetching before all data is received

I have a node application running on a Heroku server. On a specific route, its sending data in chunks.

This works well locally, it works after deploy to Heroku (when I visit the url directly in the browser) and it works when I sent a request using postman.

But when I want to fetch this data in React, it acts differently. I do receive data in chunks dynamically as supposed, but it suddenly stops.

I have an example, that returns 2505 objects in an array – which it does correctly – every time – using postman.
But using javascript, I receive between 600-1800 objects and then it stops fetching. Returns with a 200 and no errors – and my heroku says status 200 too!

Here is the function in React

import { parse } from "partial-json";
... 

const [matches, setMatches] = useState(null);
...

const getFeed = async () => {
    try {
      const response = await fetch(endpoint);

      if (!response.ok) {
        throw new Error("Failed to fetch data");
      }

      const reader = response.body.getReader();
      let partialResult = "";

      while (true) {
        const { done, value } = await reader.read();

        if (done) {
          break;
        }

        partialResult += new TextDecoder().decode(value);

        if (partialResult.startsWith("[") && partialResult.endsWith("]")) {
          const result = parse(partialResult);

          setMatches((prevResults) => {
            if (!prevResults) {
              return result.sort((a, b) => Number(a.price) - Number(b.price));
            }

            const mergedArray = [...(prevResults || []), ...(result || [])];
            const uniqueResults = Array.from(
              new Set(mergedArray.map((item) => beautifyURL(item.title)))
            )
              .map((productId) =>
                mergedArray.find(
                  (item) => beautifyURL(item.title) === productId
                )
              )
              .sort((a, b) => Number(a.price) - Number(b.price));

            return uniqueResults;
          });
          partialResult = ""; // Reset for the next chunk
        }
      }
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  };

So it is not completely broken since I do receive data and get status 200. But why does it stop? And I assume it is a frontend issue, since it works with postman and going straight to the url in the browser?

Is it possible to retrieve the body of the email being replied to in a conversation outlook add-in?

Is it possible to retrieve the body of the email being replied to in a conversation even we have multiple emails in conversation.

I am attempting to retrieve the email body in compose mode for an Outlook add-in using office.js/MS Graph. However, I’m not able to obtain the specific email body from the conversation when I click to reply. Can anyone help me to write JavaScript solution for this?

I tried this API https://graph.microsoft.com/v1.0/me/messages?$filter=conversationId eq '${conversationId}' but it is fetching whole conversation, but I want only body of the specific email which I want to reply.

Extract data from repeated and equal elements in XML, using Google Apps Script

The code below extracts data from XML files that are within a Drive directory:

function extrairDadosXML() {
  var pasta = DriveApp.getFolderById(pastaid); // Insira o ID da pasta onde estão os arquivos XML
  var arquivos = pasta.getFiles();
  var planilha = SpreadsheetApp.getActiveSpreadsheet();
  var abaExtracao = planilha.getSheetByName("Extração");
  var nomeAba = abaExtracao.getRange("A1").getValue(); // Obtém o valor da célula A1 da aba "Extração"

  // Cria uma nova aba com o nome obtido da célula A1
  var novaAba = planilha.insertSheet();
  novaAba.setName(nomeAba);

  var header = ["Manufacturer", "Model", "Serial", "Total Core", "Total CPUs", "Model CPU", "Total Memory", "Total Slots", "Free Slots", "Memory Type", "Interface HD", "Capacidade HD"];
  var values = [header];

  while (arquivos.hasNext()) {
    var arquivo = arquivos.next();
    if (arquivo.getName().split('.').pop() === 'xml') {
      var xml = XmlService.parse(arquivo.getBlob().getDataAsString());
      var root = xml.getRootElement();
      var hardwareReports = root.getChildren('report'); // Encontra todos os elementos 'report' no XML

      hardwareReports.forEach(function(hardwareReport) {
        var Data = hardwareReport.getChild('data');
        var HardwareReport = Data.getChild('hardware_report');
        var entries = HardwareReport.getChildren();

        var systemObj = entries.find(e => e.getAttribute("name").getValue() == "system").getChildren().reduce((o, e) => {
          var t = e.getChildren();
          if (t.length == 0) {
            var k = e.getAttribute("name").getValue()
            o[k] = o[k] ? [...o[k], e.getText()] : [e.getText()];
          } else {
            t.forEach(f => {
              var k = f.getAttribute("name").getValue();
              o[k] = o[k] ? [...o[k], f.getText()] : [f.getText()];
            });
          }
          return o;
        }, {});
        var processorObj = entries.find(e => e.getAttribute("name").getValue() == "processors").getChildren().reduce((o, e) => {
          var t = e.getChildren();
          if (t.length == 0) {
            var k = e.getAttribute("name").getValue()
            o[k] = o[k] ? [...o[k], e.getText()] : [e.getText()];
          } else {
            t.forEach(f => {
              var k = f.getAttribute("name").getValue();
              o[k] = o[k] ? [...o[k], f.getText()] : [f.getText()];
            });
          }
          return o;
        }, {});
        var memoryObj = entries.find(e => e.getAttribute("name").getValue() == "memory").getChildren().reduce((o, e) => {
          var t = e.getChildren();
          if (t.length == 0) {
            var k = e.getAttribute("name").getValue()
            o[k] = o[k] ? [...o[k], e.getText()] : [e.getText()];
          } else {
            t.forEach(f => {
              var k = f.getAttribute("name").getValue();
              o[k] = o[k] ? [...o[k], f.getText()] : [f.getText()];
            });
          }
          return o;
        }, {});
        var hdObj = entries.find(e => e.getAttribute("name").getValue() == "disks").getChildren().reduce((o, e) => {
          var t = e.getChildren();
          if (t.length == 0) {
            var k = e.getAttribute("name").getValue()
            o[k] = o[k] ? [...o[k], e.getText()] : [e.getText()];
          } else {
            t.forEach(f => {
              var k = f.getAttribute("name").getValue();
              o[k] = o[k] ? [...o[k], f.getText()] : [f.getText()];
            });
          }
          return o;
        }, {});

        var valuesForSystem = ["manufacturer", "model", "serial"];
        var valuesForProcessor = ["total_cores", "total_cpus", "model"];
        var valuesForMemory = ["total_memory", "total_slots", "free_slots", "type"];
        var valuesForHd = ["interface_type", "capacity"];
        var res = [
          ...valuesForSystem.map(e => systemObj[e] || ""),
          ...valuesForProcessor.map(e => processorObj[e] || ""),
          ...valuesForMemory.map(e => memoryObj[e] || ""),
          ...valuesForHd.map(e => hdObj[e] || ""),
        ];

        // 1st element is used.
        res = res.map(e => e[0]);

        // Dividir os valores das colunas "Total Memory" e "Capacidade HD" por 10^9 e extrair o inteiro quociente
        var totalMemoryIndex = header.indexOf("Total Memory");
        var hdCapacityIndex = header.indexOf("Capacidade HD");

        if (totalMemoryIndex !== -1 && hdCapacityIndex !== -1) {
          var totalMemoryValue = res[totalMemoryIndex];
          var hdCapacityValue = res[hdCapacityIndex];

          if (!isNaN(totalMemoryValue) && !isNaN(hdCapacityValue)) {
            var totalMemoryQuotient = Math.floor(totalMemoryValue / 1e9);
            var hdCapacityQuotient= Math.floor(hdCapacityValue / 1e9);

            res[totalMemoryIndex] = totalMemoryQuotient;
            res[hdCapacityIndex] = hdCapacityQuotient;
            res[totalMemoryIndex] = res[totalMemoryIndex] + " GB";
            res[hdCapacityIndex] = res[hdCapacityIndex] + " GB";
          }
        }

        values.push(res);
      });
    }
  }
  
  // Define os valores na nova aba
  novaAba.getRange(1, 1, values.length, values[0].length).setValues(values);
}

However, XML can contain several elements with the same attribute. As an example, there is the root element “disks” and within the root element, one or more “disk” elements. The code should read all “disk” elements and group the result in the same cell, but this does not happen.

Below is an excerpt from the XML:

<entries name="disks">
 <entries name="disk">
  <entry name="id" type="uint">1</entry>
  <entry name="internal_id" type="uint">69</entry>
  <entry name="interface_type" type="string">SATA/SSD</entry>
  <entry name="average_read_speed" type="uint">496951099</entry>
  <entry name="capacity" type="uint">256060514304</entry>
  <entry name="sectors" type="uint">500118192</entry>
 </entries>
 <entries name="disk">
  <entry name="id" type="uint">2</entry>
  <entry name="internal_id" type="uint">70</entry>
  <entry name="interface_type" type="string">SATA</entry>
  <entry name="average_read_speed" type="uint">0</entry>
  <entry name="capacity" type="uint">500107862016</entry>
  <entry name="sectors" type="uint">976773168</entry>
 </entries>
 <entries name="disk">
  <entry name="id" type="uint">3</entry>
  <entry name="internal_id" type="uint">71</entry>
  <entry name="interface_type" type="string">SATA</entry>
  <entry name="average_read_speed" type="uint">118517696</entry>
  <entry name="capacity" type="uint">500107862016</entry>
  <entry name="sectors" type="uint">976773168</entry>
 </entries>
  <entries name="disk">
  <entry name="id" type="uint">4</entry>
  <entry name="internal_id" type="uint">72</entry>
  <entry name="interface_type" type="string">SATA/SSD</entry>
  <entry name="average_read_speed" type="uint">498579606</entry>
  <entry name="capacity" type="uint">256060514304</entry>
  <entry name="sectors" type="uint">500118192</entry>
 </entries>
</entries>

The expected result is:

Interface HD Capacidade HD
SATA/SSD SATA SATA SATA/SSD 256GB 500GB 500GB 256GB

Rename a file before uploading using plupload.Uploader code and remove file from queue not working

I have two problems.
First of all the remove a file from queue is not working well. When I use remove link of the chosen file from queue, the link refresh the whole page. For example when I chose two files and I want to remove one of them with the remove link, with refreshing the page I lose both file in the queue. Do you have any suggestion what do I have to do differently?

Second problem:
I have an index with Java code from plupload.Uploader and a 2b-chunk.php as an upload file witch that code aloud me to upload large files and it works perfect.
But, I need to have the option rename the selected file before uploading it. So, I wrote an input code with ol to give the name as I wish there before I use the send button but I do not know what is the method sending it to 2b-chunk.php code for caching the new file name implanting to the code. Do you think my though is correct for my goal and what do I miss? If my code is correct what code do I have to change in my 2b-chunk.php to keep the chunk option with the new name of my file?

My plupload index code:

<title>Plupload - Custom example</title>
<link rel="stylesheet" href="css/x-dummy.css">
<!-- production -->
<script type="text/javascript" src="js/plupload.full.min.js"></script>



<!-- debug 
<script type="text/javascript" src="../js/moxie.js"></script>
<script type="text/javascript" src="../js/plupload.dev.js"></script>
-->
<style type="text/css">
#info_div_center {
    width:250px;
    height:auto;
    text-align: center;
    margin-top: -12px;
    }
ol.phpfmg_form{
    list-style-type:none;
    padding:2px 2px 2px 2px;
    font-family: 'Glyphicons Halflings', "Times New Roman", "serif";
    font-size: 12px;
    position: static;
    resize: vertical;
    width: 50%;
}
ol.phpfmg_form input{
    border: 1px solid #CCC;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 8px;
    padding:3px 3px 3px 3px;
    font-size: 12px;
    
}
.phpfmg_form input:hover {
    background:#E8E8E8;
}
input:focus::placeholder {
  color: transparent;
}
</style>

</head>
<body style="font: 13px Verdana; background: #eee; color: #333">

<h1>Custom example</h1>

<p>Shows you how to use the core plupload API.</p>

<div id="filelist">Your browser doesn't have HTML5 support.</div>
<br />
<form id="container" encType="multipart/form-data">
    <button id="pickfiles" href="javascript:;" multiple="false" />Select files</button>
    <button id="uploadfiles" href="javascript:;" type="submit">Upload</button>
</form>

<br />
<pre id="console"></pre>


<script type="text/javascript">
// Custom example logic

var uploader = new plupload.Uploader({
  runtimes: 'html5,flash,silverlight,html4',
  browse_button: 'pickfiles', // you can pass an id...
  container: document.getElementById('container'), // ... or DOM Element itself
  //max_retries: 1,
  //multipart: false,
  chunk_size: '1mb',
  //multiple_queues: false,
  //unique_names: true,
  url: "2b-chunk.php",

  filters: {
    max_file_size: '1000mb',
    mime_types: [
      { title: "Image files", extensions: "jpg,jpeg,gif,png" },
      { title: "Zip files", extensions: "zip" },
      { title: "Movie files", extensions: "mov,mp4" },
      { title: "Audio files", extensions: "mp3,wav" },
      { title: "Documents files", extensions: "pdf,doc,docx" }
    ]
  },
    flash_swf_url: 'js/Moxie.swf',    // Flash settings
    silverlight_xap_url: 'js/Moxie.xap',    // Silverlight settings

  init: {

    PostInit: function() {
            document.getElementById('filelist').innerHTML = '';
            document.getElementById('uploadfiles').onclick = function() {
                if (uploader.files.length < 1) {
                            document.getElementById('console').innerHTML = '<p style="color:#EA4335;">Please select a file to upload.</p>';
                    setTimeout(function () {
                    window.location.reload();
                    }, 2000)
                    return false;
                        }else{
                uploader.start();
                return false;
                }
            };
        },
      
      
      FilesAdded: function(up, files) {
            plupload.each(files, function(file) {
                document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b> '+'<a href="" class="remove btn error">Remove</a>'+'<ol class="phpfmg_form"><input type="text" name="newfilename" placeholder="Type the new filename and press Upload"></ol>'+'</div>';
                
            });
        },
BeforeUpload: function(up, file) {
    uploader.settings.multipart_params = { 'renamedFileName': 'yourRenamedFileName' };
});
      
      
    UploadProgress: function(up, file) {
            document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span style="color:red">' + file.percent + "%</span>";
        },

     FileUploaded: function(up, file, result) {
                    var responseData = result.response.replace('"{', '{').replace('}"', '}');
                    var objResponse = JSON.parse(responseData);
                    document.getElementById('console').innerHTML = '<p style="color:#198754;">' + objResponse.result.message + '</p>';
                },
      UploadComplete(up, file) {
      setTimeout(() => {
        window.location.reload();
      }, 3000);
    },
    
    Error: function(up, err) {
            document.getElementById('console').appendChild(document.createTextNode("nError #" + err.code + ": " + err.message));
            setTimeout(function () {
                    window.location.reload();
                    }, 2000)
                    return false;
        }
  },
});
uploader.init();
</script>
</body>

My 2b-chunk.php code

<?php 

// Settings 
$targetDir = 'uploads'; 
$cleanupTargetDir = true; // Remove old files 
$maxFileAge = 5 * 3600; // Temp file age in seconds 
 
// Create target dir 
if (!file_exists($targetDir)) { 
    @mkdir($targetDir); 
} 
 
// Get a file name 
if (isset($_REQUEST["name"])) { 
    $fileName = $_REQUEST["name"]; 
} elseif (!empty($_FILES)) { 
    $fileName = $_FILES["file"]["name"]; 
} else { 
    $fileName = uniqid("file_"); 
}
 
$filePath = $targetDir . DIRECTORY_SEPARATOR . $fileName;

// Chunking might be enabled 
$chunk = isset($_REQUEST["chunk"]) ? intval($_REQUEST["chunk"]) : 0; 
$chunks = isset($_REQUEST["chunks"]) ? intval($_REQUEST["chunks"]) : 0; 
 
 
// Remove old temp files     
if ($cleanupTargetDir) { 
    if (!is_dir($targetDir) || !$dir = opendir($targetDir)) { 
        die('{"jsonrpc" : "2.0", "error" : {"code": 100, "message": "Failed to open temp directory."}, "id" : "id"}'); 
    } 
 
    while (($file = readdir($dir)) !== false) { 
        $tmpfilePath = $targetDir . DIRECTORY_SEPARATOR . $file; 
 
        // If temp file is current file proceed to the next 
        if ($tmpfilePath == "{$filePath}.part") { 
            continue; 
        } 
 
        // Remove temp file if it is older than the max age and is not the current file 
        if (preg_match('/.part$/', $file) && (filemtime($tmpfilePath) < time() - $maxFileAge)) { 
            @unlink($tmpfilePath); 
        } 
    } 
    closedir($dir); 
}     
 
 
// Open temp file 
if (!$out = @fopen("{$filePath}.part", $chunks ? "ab" : "wb")) { 
    die('{"jsonrpc" : "2.0", "error" : {"code": 102, "message": "Failed to open output stream."}, "id" : "id"}'); 
} 
 
if (!empty($_FILES)) { 
    if ($_FILES["file"]["error"] || !is_uploaded_file($_FILES["file"]["tmp_name"])) { 
        die('{"jsonrpc" : "2.0", "error" : {"code": 103, "message": "Failed to move uploaded file."}, "id" : "id"}'); 
    } 
 
    // Read binary input stream and append it to temp file 
    if (!$in = @fopen($_FILES["file"]["tmp_name"], "rb")) { 
        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); 
    } 
} else {     
    if (!$in = @fopen("php://input", "rb")) { 
        die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}'); 
    } 
} 
 
while ($buff = fread($in, 4096)) { 
    fwrite($out, $buff); 
} 
 
@fclose($out); 
@fclose($in); 
 
// Check if file has been uploaded 
if (!$chunks || $chunk == $chunks - 1) { 
    // Strip the temp .part suffix off  
    rename("{$filePath}.part", $filePath);
}

echo('{"jsonrpc" : "2.0", "result" : {"status": 200, "message": "The file has been uploaded successfully!"}, "id" : "id"}');
?>

I need to have the option renaming my chosen file before uploading and need the option removing a file from queue before uploading.
Thanks in advance for your help

“Uncaught ReferenceError: a is not defined” instead of “ReferenceError: Cannot access ‘a’ before initialization”

In this simple code, since the variable b is a let variable and i am trying to log() its value, I was expecting a reference error that said: cannot access ‘a’ before initialization,

but instead i am getting the error:
Uncaught ReferenceError: a is not defined

console.log(a);
let a=10;
var b=19;

a screenshot of the code and the error–>

i ran the same code in online js editors and they give the expected error, i am confused now :
the same code on an online editor with different error

Check if module is already imported before doing async import()

I am creating a lazy loaded component. My question is about JavaScript itself, not any specific framework (React, Svelte, etc), so I’m showing some pseudocode.

const myLazyLoadedComponent() {

  let myComponent
  let isLoading = true
  import('/some/path.xx').then(c => {
    myComponent = c
    isLoading = false
  })

//this part is reactive with the variables above:

  return (
    if (isLoading) <div>Loading..<div/>
    else <myComponent/>
  )
}

This will work well the first time. But when I would close-reopen or open another instance of it, the Loading.. would show for a microsecond before the myComponent.

Is there a way to first check if the module was already imported, and based on that, either use it directly or async import()?

Something like this:

if (isAlreadyImported('/some/path.xx').) {
  import { myComponent } from '/some/path.xx'
} else {
  isLoading = true
  import('/some/path.xx').then(c => {
    myComponent = c
    isLoading = false
  })
}

Can’t integrate Nextjs with ChromaDB

I am having trouble connecting to the Chromadb vector database in Nextjs. My goal is to store user content in Chromadb. Here is the code I am using with the dependencies:

dependencies version:

  • next: “14.1.0”
  • chromadb: “1.8.1”

app/upload/action.tsx:

"use server"; 
import { ChromaClient } from "chromadb"; 

export async function createDocs(prevState: any, formData: FormData) { 
    const client = new ChromaClient({ path: "http://0.0.0.0:8000", }); 
    const collection = await client.getCollection({ name: "demo", }); 
    const response = await collection.add({ 
        ids: ['1'], 
        documents: [`${formData.get("content")}`], 
        metadatas: [{ user: 1, title: `${formData.get("title")}`}], 
    }); 
    return { message: `${response}` }; 
} 

However, when I run the code, I get a strange error in webpack that says:

⨯ ./node_modules/onnxruntime-node/bin/napi-v3/darwin/arm64/onnxruntime_binding.node
Module parse failed: Unexpected character '�' (1:0)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
(Source code omitted for this binary file)

Import trace for requested module:
./node_modules/onnxruntime-node/bin/napi-v3/darwin/arm64/onnxruntime_binding.node
./node_modules/onnxruntime-node/bin/napi-v3/ sync ^./.*/.*/onnxruntime_binding.node$
./node_modules/onnxruntime-node/dist/binding.js
./node_modules/onnxruntime-node/dist/backend.js
./node_modules/onnxruntime-node/dist/index.js
./node_modules/@xenova/transformers/src/backends/onnx.js
./node_modules/@xenova/transformers/src/env.js
./node_modules/@xenova/transformers/src/transformers.js
./node_modules/chromadb/dist/chromadb.mjs
./app/upload/actions.tsx

Chromadb has trouble using ESM modules in ./node_modules/chromadb/dist/chromadb.mjs. However, it works fine with CommonJS.

I attempted various actions to troubleshoot the error, despite knowing that they may not be effective. These actions included:

  • installing different packages such as npm, yarn, bun, and pnpm.
  • I replaced server actions with API routes
  • tried initializing, exporting, and importing the client variable.

file.ts:

import {ChromaClient} from 'chromadb'

const client = new ChromaClient({
  path: 'http://0.0.0.0:8000'
});


export async function collection() {
  const collection = await client.getCollection({
    name: 'demo'
  })
}

is there a way that I can try using commonjs in nextjs?

Android Studio Iguana: ‘Build failed with 17 issues found’ outdated plugins how to fix this?

Today, I tried to manually export gdevelop project to apk using cordova cli and Android studio iguana but got these build failed error log:

17 issues were found when checking AAR metadata:

  1. Dependency ‘androidx.appcompat:appcompat-resources:1.6.1’ requires libraries and applications that
    depend on it to compile against version 33 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 33, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  2. Dependency ‘androidx.appcompat:appcompat:1.6.1’ requires libraries and applications that
    depend on it to compile against version 33 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 33, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  3. Dependency ‘androidx.core:core-splashscreen:1.0.0’ requires libraries and applications that
    depend on it to compile against version 31 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 31, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  4. Dependency ‘androidx.webkit:webkit:1.6.0’ requires libraries and applications that
    depend on it to compile against version 33 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 33, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  5. Dependency ‘androidx.activity:activity:1.6.0’ requires libraries and applications that
    depend on it to compile against version 33 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 33, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  6. Dependency ‘androidx.emoji2:emoji2-views-helper:1.2.0’ requires libraries and applications that
    depend on it to compile against version 32 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 32, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  7. Dependency ‘androidx.emoji2:emoji2:1.2.0’ requires libraries and applications that
    depend on it to compile against version 32 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 32, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  8. Dependency ‘androidx.lifecycle:lifecycle-viewmodel:2.5.1’ requires libraries and applications that
    depend on it to compile against version 31 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 31, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  9. Dependency ‘androidx.lifecycle:lifecycle-viewmodel-savedstate:2.5.1’ requires libraries and applications that
    depend on it to compile against version 31 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 31, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  10. Dependency ‘androidx.core:core-ktx:1.9.0’ requires libraries and applications that
    depend on it to compile against version 33 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 33, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  11. Dependency ‘androidx.core:core:1.9.0’ requires libraries and applications that
    depend on it to compile against version 33 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 33, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  12. Dependency ‘androidx.lifecycle:lifecycle-process:2.4.1’ requires libraries and applications that
    depend on it to compile against version 31 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 31, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  13. Dependency ‘androidx.lifecycle:lifecycle-runtime:2.5.1’ requires libraries and applications that
    depend on it to compile against version 31 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 31, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  14. Dependency ‘androidx.savedstate:savedstate:1.2.0’ requires libraries and applications that
    depend on it to compile against version 31 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 31, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  15. Dependency ‘androidx.startup:startup-runtime:1.1.1’ requires libraries and applications that
    depend on it to compile against version 31 or later of the
    Android APIs.

    :app is currently compiled against android-30.

    Recommended action: Update this project to use a newer compileSdkVersion
    of at least 31, for example 33.

    Note that updating a library or application’s compileSdkVersion (which
    allows newer APIs to be used) can be done separately from updating
    targetSdkVersion (which opts the app in to new runtime behavior) and
    minSdkVersion (which determines which devices the app can be installed
    on).

  16. Dependency ‘androidx.lifecycle:lifecycle-livedata-core:2.5.1’ requires libraries and applications that
    depend on it to compile against version 31 or later of the
    Android APIs.

    :app

How to fix this? Sorry I am new to developing apps and I want to learn.

I want to try to build debug apk using cordova cli and android studio.