Web USB / Serial API + led strip KAA332-LH

I wonder if anyone has any experience with the Web USB and controlling a LED strip. I have a basic LED strip. I can connect the device from the browser js, but when I try to do device.open() I’m getting error:
DOMException: Failed to execute ‘open’ on ‘USBDevice’: Access denied.

Funnily enough, when I try to use the Web Serial API, I can open the port and getInfo(). I’m also trying to send some data, but I have no clue what payload to add to simply switch off/on the leds…

Ideally I’d like to stick to Web USB API… any idea how to overcome the Access denied problem?

manufacturerName: "Prolific Technology Inc."
productId: 9123
productName: "KAA332-LH"
serialNumber: "KAA332LH2207"
vendorId: 1659

enter image description here

Blur event flow and synchronization of DOM updates

The following code has this behavior when I focus on the input and then click the delete button:

  1. Mousedown callback function is triggered, however input does not blur immediately cause of ev.preventDefault()

  2. Container gets removed by (at least it should be) the mousedown function.

  3. Blur callback function is then triggered since the removal of the container caused the input to lose focus

  4. It prints the container element in the console, even though I was expecting null. Wasn’t it removed by the mousedown callback function?

  5. It then (in my understanding) removes the container element that for some reason was not removed by the mousedown func.

  6. the mousedown func then doesn’t find an element to remove so it throws a DOMException.

I am not sure if the process happens exactly like I described it. If I comment out the container.remove line in the blur func, first the element will be printed in the console by the blur func and after “null” will be printed by the mousedown func.

I cannot understand how the blur func is seemingly called before the mousedown one. For the blur func to be called the container has to be removed. So how does the blur func find it in the DOM again and how does it remove it if it’s already been removed?

const inp = document.querySelector("input");
const container = document.querySelector("#container");
const btn = document.querySelector("button");

btn.addEventListener("mousedown", (ev) => {
  ev.preventDefault();
  console.log('Before remove',document.querySelector("#container"));  
  container.remove();
  console.log('After remove',document.querySelector("#container"));
});

inp.addEventListener("blur", () => {
  console.log('In blur',document.querySelector("#container"));
  container.remove();
});
<div id="container">
  <input />
  <button>Delete</button>
</div>

using mui-file-input in react-hook-form using react hook form persist to storage data

i have issue when i change mui-file-input, useFormPersist save the
value in storage with array of empty objects and when i reload the
page, i got error because the value not true and the input expected
value be [] or array of objects and has file data, i tried also to prevent
useFormPersist from saving the file input value in storage, it’s not worked also
because this file inside array also

`import { SetFieldValue } from ‘react-hook-form’;
import { MuiFileInput } from ‘mui-file-input’;

   interface FormPersistConfig {
   storage?: Storage;
   watch: (names?: string | string[]) => any;
   setValue: SetFieldValue<any>;
   exclude?: string[];
   onDataRestored?: (data: any) => void;
   validate?: boolean;
   dirty?: boolean;
   onTimeout?: () => void;
   timeout?: number;
  }

declare const useFormPersist: (name: string, { storage, watch, setValue, exclude,
onDataRestored, validate, dirty, onTimeout, timeout }: FormPersistConfig) => {
clear: () => void;
};

export { FormPersistConfig, useFormPersist as default };
const BookingVisa = () => {
       const {
         unregister,
         register,
          control,
          handleSubmit,
          watch,
          setValue,
          clearErrors,
          setError,
           getValues,
           reset,
           formState: { errors },
        } = useForm<BookingInfo>({

    resolver: yupResolver(bookingInfoSchema),
    mode: 'all',
   })

   const [excludeFields, setExcludeFields] = useState<string[]>([]);
   const passengers = watch('passengers') || [];

   useEffect(() => {
     const newExcludeFields = passengers.flatMap((passenger, index) => {
      return [`passengers[${index}].file`, `passengers[${index}].document`];
    });
     setExcludeFields(newExcludeFields);
    }, [passengers]);

   useFormPersist(`bookVisa-${searchId}`, {
       watch,
       setValue,
       exclude: [ ...excludeFields] ,    
})
     const handleFilesChange = async(files: any, index: number, name: any, field: 
         any, inputNum: any) => {
    if(files.length > 3){
        return showMessage(trans(`visa.file${index}.error.length`), 'error')
    }
    field?.onChange(files);
   const form = new FormData()
        for (let i = 0; i < files.length; i++) {
            const reader = new FileReader();
                form.append(`files[${i}]`, files[i]);
            reader.readAsDataURL(files[i]);
        }
        const data = await dispatch(SettingService().uploadImage(form))
        if (data.payload.urls) {
            setValue(`passengers[${index}].${name + 's'}`, data.payload.urls);
            // showMessage(trans(`visa.file${inputNum}.media.success`), 'success')
            if(name === 'file'){
                clearErrors(`passengers[${index}].file`);
            }
        }else{
            setValue(`passengers[${index}].${name + 's'}`, []);
            setValue(`passengers[${index}].${name}`, []);
            showMessage(trans(`visa.file${inputNum}.media.error`), 'error')
            if(name === 'file'){
                setError(`passengers[${index}].file`, { type: "manual", message: 
                      trans(`visa.file${inputNum}.error`) })
            }
            field?.onChange([]);
        }                    
};

return (
 <from id="fromId" method={'post'} onSubmit={handleSubmit(onSubmit)}>
<Controller
     name={`passengers[${index}].file`}
     control={control}
    // defaultValue={[]}
    render={({ field }: any) => {
          return(
              <MuiFileInput
                  label={trans('File Upload 122')}
                  {...field}
                   multiple
                  sx={{ width: '100%' }}
                  inputProps={{ accept: 'image/*,.pdf', maxFiles: 3 }} 
                  onChange={(values: any) => {
                         handleFilesChange(values, index, 'file', field, 1);
                    }}
                   value={field.value}                                            
                  clearIconButtonProps={{ children: <CloseIcon fontSize="small" /> }}
                  error={!!errors.passengers?.length ? 
                        !!errors.passengers[index]?.file : false}
                  helperText={(errors.passengers?.length && 
                                errors.passengers[index]?.file) ? 
                               trans(errors.passengers[index]?.file.message) : 
                               trans('visa.file1.helpertext')}

                 />
             )}}
         />
 </form>
)}

`

Building component library with nest folder structure using vite

I would like to build a a component library using vite.

But i do not want a single entry point, I want to produce nested folder structure similar to for example MUI. So that components can be imported

import MyComponent form 'library/foo/MyComponent'

as opposed having one massive index file with everytinh or having to do something like

import { foo } form 'library'
const { MyComponent } = foo

as I said, I would like folder structure, not a single compiled file. Similary to what mui does.

I have spend couple hours searching with no success, I only fond ‘vite-plugin-static-copy’ but that can not be used for source as it does not resolve aliases.

Error: R3F: AndroidProgressBar is not part of the THREE namespace! Did you forget to extend?

I’m working on a React Native project, and I’m using Three.js for rendering 3D content. I encountered the following error:

 Error: R3F: AndroidProgressBar is not part of the THREE namespace! Did you forget to extend? See: https://docs.pmnd.rs/react-three-fiber/api/objects#using-3rd-party-objects-declaratively

This error occurs when I try to render a progress bar while the 3D content is loading. I’ve already tried the following steps, but the issue persists:

  1. Verified that the three package is correctly installed and imported.
  2. Checked that all necessary components are correctly extended.
  3. Made sure that the component I’m trying to use is correctly registered and imported.

Environment:

  1. React Native version: 0.72.6
  2. Platform: Android/iOS

Other Libraries:

"@react-three/drei": "^9.97.5",
"@react-three/fiber": "^8.0.0-beta.10",
"expo": "^49.0.0",
"expo-gl": "~13.0.1",
"r3f-native-orbitcontrols": "^1.0.9",
"react": "^18.0.0-rc.3",
"react-native": "0.72.6",

Code:

import React, { Suspense } from 'react';
import { Canvas } from '@react-three/fiber/native';
import { OrbitControls } from '@react-three/drei';
import { View } from 'react-native';
import { heightPercentageToDP } from 'react-native-responsive-screen';
import Loader from '../../../../components/loader';
import Model from './model';

const Male_Army_Model = () => {
 return (
   <View style={{ flex: 1 }}>
     <Canvas
       shadows
       gl={{ antialias: true }}
       style={{ marginBottom: heightPercentageToDP(3) }}
     >
       <ambientLight intensity={1} />
       <pointLight position={[10, 70, 70]} intensity={1.5} castShadow />
       <directionalLight
         position={[5, 5, 5]}
         intensity={1.5}
         castShadow
         shadow-mapSize-width={2048}
         shadow-mapSize-height={2048}
       />
       <directionalLight
         position={[-5, -5, -5]}
         intensity={1.5}
         castShadow
         shadow-mapSize-width={2048}
         shadow-mapSize-height={2048}
       />
       <directionalLight
         position={[2, -2, 1]}
         intensity={1.5}
         castShadow
         shadow-mapSize-width={2048}
         shadow-mapSize-height={2048}
       />
       <directionalLight
         position={[-2, 2, -1]}
         intensity={1.5}
         castShadow
         shadow-mapSize-width={2048}
         shadow-mapSize-height={2048}
       />

       <OrbitControls
         enableRotate
         enableZoom={false}
         rotateSpeed={1.0} // Consider reducing the rotate speed for smoother control
         enablePan={false}
         maxZoom={0.6}
         minZoom={0.6}
         maxPolarAngle={Math.PI / 3.5}
         minPolarAngle={Math.PI / 3.5}
       />

       <Suspense fallback={<Loader />}>
         <Model />
       </Suspense>
     </Canvas>
   </View>
 );
};

export default Male_Army_Model;

Any insights or suggestions would be greatly appreciated!

Read variable from a file via javascript in an html file (client side)

I’m having an html file location.html and a file with data location.data both on the same webserver in the same directory. the contens of location.data is always the current location data in the form

{"lat":"44.17027","lon":"15.595542","timestamp":"1723663819127","hdop":"2.394","altitude":"510.35","speed":"0.73396146"}

it is written via json_encode() in another php file.
Now I need to read this data in a javascript in location.html into an array to display it on a map via leaflet. (It has to be html)

I just can’t manage to get this done. I tried XMLHttpRequest() with no success. Would appreciate any other (elegant) method.

<script>
var locx = new XMLHttpRequest();

locx.open('GET', 'location.data');

locx.onreadystatechange = function () {
   if (locx.readyState === 4 && locx.status === 200) {
       var locationData = locx.responseText;
   }
};

xhr.send();
</script>

Unable to resolve “realm/dist/bundle” from “RealmRealmSchema.js”

first time Realm user trying to set up a React Native app, getting the error above after trying to set subscriptions, previously getting; ”Cannot write to class Produit when no flexible sync subscription has been created”.

Problem happens after I tried:

import {Subscription} from 'realm/dist/bundle';

I did install the lastest version with; npm install [email protected], but I’m still getting the error.

Here’s my code:

const {UUID} = Realm.BSON;
import Realm, {BSON} from "realm";
import {useRealm, useQuery} from '@realm/react';
import {Subscription} from 'realm/dist/bundle';
import React, {useState} from 'react';
import {Text, FlatList, View, Pressable, TextInput, Button} from 'react-native';

class Produit extends Realm.Object {
    static schema = {
        name: 'Produit',
        properties: {
          _id: 'uuid',
          nom: {type: 'string', indexed: true},
          description: 'string',
          prix: 'string',
          image: 'string'
        },
        primaryKey: '_id',
    };
}

export default Produit;

export const Create = () => {
  const realm = useRealm();
  //const produits = useQuery(Produit);
  const [nomProduit, setNomProduit] = useState('');
  const [descProduit, setDescProduit] = useState('');
  const [prixProduit, setPrixProduit] = useState('');
  const [imgProduit, setImgProduit] = useState('');
  const addProduit = () => {
    realm.write(() => {
      realm.create(Produit, {
        _id: new UUID(),
        name: nomProduit,
        description: descProduit,
        prix: prixProduit,
        image: imgProduit
      });
    });
  };
  return (
    <View>
      <Text>Create</Text>
      <TextInput
        onChangeText={setNomProduit}
        value={nomProduit}
        placeholder="Produit name..."
      />
      <TextInput
        onChangeText={setDescProduit}
        value={descProduit}
        placeholder="description.."
      />
      <TextInput
        onChangeText={setPrixProduit}
        value={prixProduit}
        placeholder="prix..."
      />
      <TextInput
        onChangeText={setImgProduit}
        value={imgProduit}
        placeholder="img..."
      />
      <Button
        title="Add Produit"
        onPress={addProduit}
      />
    </View>
  );
};

This is where I am trying to use it:

import { StatusBar } from 'expo-status-bar';
import { StyleSheet, Text, View, Button } from 'react-native';
import React from 'react';
import { useEffect, useState } from 'react';
import { useApp, useRealm, AppProvider, UserProvider, RealmProvider} from '@realm/react';

import { Produit } from './Realm/RealmSchema.js';
import { Create } from './Realm/RealmSchema.js';

export default function App() {

  return (
    <AppProvider id={'application-pam2-ceyvopp'}>
    <UserProvider fallback={LogIn}>
      <RealmProvider
        schema={[Produit]}
        sync={{
          flexible: true,
          initialSubscriptions: {
            update(subs, realm) {
              subs.add(realm.objects(Produit));
            },
          },
        }}>
    <Create/>
    </RealmProvider>
    </UserProvider>
    </AppProvider>
  )
}

Thank you in advance!

How to test multiple missing columns for a generated CSV file to be uploaded to an API using mocha java test

With in my mocha tests, I have data-generation.js file that holds my functions and this code snippet creates my invalid csv.file. This file has 4 missing fields Clientid, recordlocator, last name, first name and email. I have removed this from my function so when the csv generates it will not add these rows which is what I expect for my tests to pass.

Then in my test-spec.js folder I have to test 4 invalid columns that generates the file, and validate if clientID is not there then show me 422 error, but I need to generate this for the other 3 missing columns, how can I manipulate my Data-generation.js folder to generate these scenarios?

Below Test.spec.js

 describe.only("Create Upload without ClientID, recordlocator,lastName,First name and Email Columns ", function (){
      it("Should throw unprocessable Entity Repoonse 422", async function (){
        getCreateUploadsRequestForInvalidColumnsTMCBulkUpload(clientId, clientOrg.id);
          response = await createBulkUploadsTMC({
            fileName: fileDestination,
            token: userAccessToken,
            delimiter: "COMMA",
            quote: "DOUBLE_QUOTE",
            dataResidency: "US",
          });
          expect(response.status).to.eql(422);
        });
        })
      })
    });

Below Data-generation.js folder where my csv gets generated with these columns and rows.

  clientId,
  organizationId
) {
  const data = [];
  const originAirport = "YUL";
  const destinationAirport = "YYR";
  const originRail = "TPA";
  const destinationRail = "WAS";
  const flightNumber = faker.airline.flightNumber();
  const phoneNumber = faker.phone.number("+1878540####");
  const employeeId = faker.string.numeric(5);
  // generate date
  const currentDate = moment();
  const departureDateTime = currentDate.format("YYYY-MM-DDTHH:mm");
  const arrivalDateTime = currentDate.add(2, "days").format("YYYY-MM-DDTHH:mm");
  const hotelName = faker.person.lastName();
  for (let i = 1; i < 6; i++) {
    let rowDetails;
    switch (i) {
      case 1:
        rowDetails = [
          `Organization,Phone Number,Employee ID,Person Type,Flight Origin,Flight Origin Date,Flight Destination,Flight Destination Date,Airline Code,Flight Number,Hotel Nearest Airport,Hotel Check-in Date,Hotel Check-out Date,Hotel Name,Hotel Address,Hotel Latitude,Hotel Longitude,Vehicle Origin,Vehicle Origin Date,Vehicle Destination,Vehicle Destination Date,Vehicle Company Name,Rail Origin,Rail Origin Date,Rail Destination,Rail Destination Date,Rail Carrier Code,Train Number,Action`,
        ];
        break;
      case 2:
        rowDetails = [
          organizationId,
          phoneNumber,
          employeeId,
          "VIP",
          originAirport,
          departureDateTime,
          destinationAirport,
          arrivalDateTime,
          "YUL",
          flightNumber,
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "Create",
        ];
        break;
      case 3:
        rowDetails = [
          organizationId,
          phoneNumber,
          employeeId,
          "VIP",
          "",
          "",
          "",
          "",
          "",
          "",
          originAirport,
          departureDateTime,
          arrivalDateTime,
          hotelName,
          "",
          "48.78",
          "-78.88",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "Create",
        ];
        break;
      case 4:
        rowDetails = [
          organizationId,
          phoneNumber,
          employeeId,
          "VIP",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          originAirport,
          departureDateTime,
          destinationAirport,
          arrivalDateTime,
          "HERTZ",
          "",
          "",
          "",
          "",
          "",
          "",
          "Create",
        ];
        break;
      case 5:
        rowDetails = [
          organizationId,
          phoneNumber,
          employeeId,
          "VIP",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          "",
          originRail,
          departureDateTime,
          destinationRail,
          arrivalDateTime,
          "2V",
          "92",
          "Create",
        ];
        break;
    }
    const row = [...rowDetails];
    data.push(row);
  }
  // Convert data to CSV format
  const csvContent = data.map((row) => row.join(",")).join("n");

  // Specify the file path and name
  const fileNameCSV = "tmc_upload.csv";
  const fileDestination = path.join(
    __dirname + `/../../../../../testData/testFiles/${fileNameCSV}`
  );

  // Write the CSV content to the file
  fs.writeFileSync(fileDestination, csvContent, "utf-8");

  console.log(`CSV file "${fileNameCSV}" created successfully.`);
return fileDestination
}```

JS / Jquery – Dynamically set text value to a Django form choicefield

I have this choicefield in a django form :

forms.py

sales_documents_description_1 = forms.ChoiceField(required=False, choices=list(models_products.objects.values_list( 'id_product','product_denomination')), widget=forms.Select(attrs={'id': 'sales_documents_editable_select_description_1','style': 'width:200px','onchange': 'populate_selected_product(this.id,this.value)'}))

In my template, how do I set this choicefield value by specifiying the text argument (NOT THE VALUE)

I tried with this :

Template.html

 $('#sales_documents_description_1').filter(function() {return $(this).text() == 'Neumann U87';}).prop('selected', true);

or

$("#sales_documents_description_1 option").filter(function(){return$(this).text() == 'Neumann U87';}).prop('selected', true);

But it’s not working.

Any JS or JQuery solution will be ok for me.

Thanks

Form.io dropdown URL response value based on conditional

Form.io dropdown URL API response value based on conditional i need to show the dropdown list
ex: I have list name = CONT only I need to show in the dropdown list where can I write condition

value  = data.filter(item => item.name === "CONT");
[
  {
    "name": "CONT",
    "description": {
      "ar-AE": "حاوية",
      "en-US": "Container"
    },
  },
  {
    "name": "GC",
    "description": {
      "ar-AE": "شحن عام",
      "en-US": "General Cargo"
    },
    "metadata": []
  },
  {
    "name": "CONT",
    "description": {
      "ar-AE": "رورو",
      "en-US": "werwtret"
    },
    "metadata": []
  }
]

How to prevent unused code from being excluded from a bundle?

I have an old project on Laravel with jquery code, I’m trying to transfer it to Vite.
I have a file auth.js with code:

let auth;
$(function () {
    console.log('123');
    auth = {
        email: null, password: null, logIn: function () {
            $(".btn-login").off('click');
....

I use this function in blade template like this:

<script>
        $(document).ready(function () {
            auth.signUp();
            cabinet.showPassword();
        });
    </script>

My webpack config in old project:

const { mix } = require('laravel-mix');
mix.js('resources/assets/js/app.js', 'public/js');
mix.babel(['resources/assets/js/Auth.js','resources/assets/js/Billing.js'], 'public/js/scripts.js');

and it works well.

my vite config:

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/app.css',
                'resources/js/app.js',
                'resources/js/Auth.js',
            ],
            refresh: true,
        })
]})

after build, I have this in Auth.js:

$(function(){console.log("123")});

how can i build my js code and call these functions from blade templates?

P.S I know about the method with the window, but maybe there is a more correct way?

window.auth = {
   email: null, password: null, logIn: function () {

Properly test JSX element in Stencil (Jest)

We have a big (very customizable) stencil.js component which loads text from a JSON (depending on locale), does several tranformations and eventually displays a dialog.

We have placeholders in the texts, like %MY_LINK_PLACEHOLDER%, which get transformed to branded link components (wrapper for <a>-elements from company branded Stencil library).

So, simplified:
Input (from JSON) "This is my text with a %MY_LINK%."
Output: This is my text with a <corp-link><a href="foo">link</a></corp-link>.

As JSX can’t render the link if it is passed back as a string (or at least I don’t know how), the method that does the replacement returns an Array like this ["This is my text with a", <corp-link><a href="foo">link</a></corp-link> as HTMLElement, "."]
(I’m not sure, if returning the link as HTMLElement is a good idea. I’d gladly take other suggestions!).

So, the “text elements” have the type: string | HTMLElement | Array<string | HTMLElement>

Now, the actual question:
I’m trying to test, that the links get properly replaced.
When logging the element I get something like this:

      '$flags$': 0,
      '$tag$': 'corp-link',
      '$text$': null,
      '$elm$': {},
      '$children$': [
        {
          '$flags$': 0,
   ...

So currently, my (working) test looks like follows:

    expect(jsonText.myText).toContain("%MY_LINK%");
    expect(processedTextObject.myText).not.toContain("%MY_LINK%");
    expect(processedTextObject.myText[1].$tag$).toBe("corp-link");

So far, so good. But I would

  1. Like to have it more flexible/generic
  2. Have the feeling that the typing is not ideal
  3. Don’t think that using the $-enclosed properties ($tag$) is a good idea

Any suggestions to improve this?
Thanks a lot! 🙂

Pulling Data from Messari with API key into Google Sheets

My JavaScript shows no errors in the logs but when I have input the function into Google Sheets my cell returns a blank. Here is the code:

function getFullyDilutedMarketCap(ticker) {
if (!ticker || typeof ticker !== 'string') {
return 'Error: Invalid ticker symbol provided';
}

const apiKey = 'Your Messari API key'; //
const url = https://data.messari.io/api/v1/assets/${ticker}/metrics/market-data;

const options = {
'method': 'get',
'headers': {
'x-messari-api-key': apiKey
}
};

try {
const response = UrlFetchApp.fetch(url, options);
const data = JSON.parse(response.getContentText());

    if (data.status && !data.status.error_code) {
      return data.data.market_data.marketcap_diluted_usd; // Return the fully diluted market cap in USD
    } else {
      return `Error: Ticker not recognized or API issue`;
    }

} catch (error) {
return Error fetching data: ${error.message};
}
}

function fetchFullyDilutedMarketCap(ticker) {
const marketCap = getFullyDilutedMarketCap(ticker);

const sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
sheet.getRange('A1').setValue('Fully Diluted Market Cap (USD)');
sheet.getRange('B1').setValue(marketCap);
}

Used ChatGPT to amend the code but I cannot get it to stop displaying blank cells.

How to put a game with multiple .swf (characters, audio, assets…) in Ruffle?

I’m trying to bring back an entire website from 2010 and its flash games with ruffle (https://onlinewinxclub.com/centro-web/?lang=en) and so far so good, even for someone like me who never really worked with flash, I changed a few scripts regarding the highscore in 5 other games to point to the my server instead of the old website and all the games followed the same logic thus far: all files inside their folders, the .xml for the languages and one .swf for the game only…

However, one of the games, which also happened to be the most successful one back then, has multiple .swf files that need to be pre-loaded and I have no clue how to run it. The “game.swf” which is in charge of everything doesn’t load past… the loading.

Is anyone able to do it? I was planning on releasing the website in a few weeks and this is actually the last thing I need to finish before finally releasing it and it’s unfortunately with the area I have less experience with – flash.

Here is the drive file with the game: https://drive.google.com/file/d/10XEXJ2VFfL8rBVsRPSTWsB_FsGQTrPuP/view

The MinigamePlayer.php is where I run the game. https://onlinewinxclub.com/centro-web/pages/Games/Flash/IceCream/MiniGamePlayer.php?lang=en

I tried a bunch of things.

First I went to waybackmachine to the old official website and see how their own code was:

<html>
<body style="background-color: black; text-align: center;">
    <object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="920" height="575" class="minigame-object" id="minigame-object" align="middle">
                    <param name="movie" value="MinigameWrapper.swf?lang=en">
                    <param name="base" value=".">
                    <param name="quality" value="high">
                    <param name="bgcolor" value="#ffffff">
                    <param name="allowFullScreen" value="true">
                    <param name="allowScriptAccess" value="always">
                    <param name="wmode" value="opaque">
                    <param name="FlashVars" value="gameId=8&amp;languageId=1&amp;userId=0&amp;sessionId=">
                    <!--[if !IE]>-->
                    <object type="application/x-shockwave-flash" data="MinigameWrapper.swf?lang=en" width="920" height="575" class="minigame-object" id="minigame-object" align="middle">
                        <param name="movie" value="MinigameWrapper.swf?lang=en">
                        <param name="base" value=".">
                        <param name="quality" value="high">
                        <param name="bgcolor" value="#ffffff">
                        <param name="allowFullScreen" value="true">
                        <param name="allowScriptAccess" value="always">
                        <param name="wmode" value="opaque">
                        <param name="FlashVars" value="gameId=8&amp;languageId=1&amp;userId=0&amp;sessionId=">
                        <!--<![endif]-->
                        <div class="FlashFallback">
                            <p>You need Flash plugin to play this game</p>
                        </div>
                        <!--[if !IE]>-->
                    </object>
                    <!--<![endif]-->
    </object>
</body>
</html>

This was it, but it didn’t help at all because it didn’t really have anything that different from what I have myself, which is:

MinigamePlayer.php:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Play Game</title>
    <script src="/ruffle/ruffle.js"></script> <!-- Path to Ruffle -->
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const langMap = {
                'en': 1,
                'it': 2,
                'fr': 3,
                'es': 6,
                'de': 7,
                'pt': 9
            };

            function getQueryParam(param) {
                const urlParams = new URLSearchParams(window.location.search);
                return urlParams.get(param);
            }

            const lang = getQueryParam('lang');
            const languageId = langMap[lang] || 1; 

            if (!window.gameLoaded) {
                const swfFiles = [
                    "game8/assets.swf",
                    "game8/characters.swf",
                    "game8/audio.swf",
                    "game8/interface.swf",
                    "game8/levels.xml"
                ];

                // Preload the SWF files
                swfFiles.forEach(function(file) {
                    const preloadObject = document.createElement("object");
                    preloadObject.setAttribute("type", "application/x-shockwave-flash");
                    preloadObject.setAttribute("data", file);
                    preloadObject.style.display = "none";
                    document.body.appendChild(preloadObject);
                });

                var gameContainer = document.createElement("object");
                gameContainer.setAttribute("id", "minigame-object");
                gameContainer.setAttribute("type", "application/x-shockwave-flash");
                gameContainer.setAttribute("data", "../../../../pages/Games/Flash/IceCream/MinigameWrapper.swf?gameId=8&amp;languageId=${languageId}&amp;userId=0&amp;sessionId=");
                gameContainer.setAttribute("width", "750");
                gameContainer.setAttribute("height", "480");

                gameContainer.setAttribute("style", "outline: 1px solid #7E7F7F;");

                gameContainer.innerHTML = `
                    <param name="base" value=".">
                    <param name="quality" value="high">
                    <param name="bgcolor" value="#ffffff">
                    <param name="allowFullScreen" value="true">
                    <param name="allowScriptAccess" value="always">
                    <param name="wmode" value="opaque">
                    <param name="FlashVars" value="gameId=8&amp;languageId=${languageId}&amp;userId=0&amp;sessionId=">
                    <div>
                        <p>You need Ruffle to play this game. <a href="https://ruffle.rs/#downloads" target="_blank">Download Ruffle here</a>.</p>
                    </div>
                `;

                document.body.appendChild(gameContainer);
                window.gameLoaded = true;
            }
        });
    </script>
</head>
<body>
</body>
</html>

I tried the preload of the files as you can see, but this appears on the console:

ERROR core/src/avm2/events.rs:433 Error dispatching event
EventObject(EventObject { type: “complete”, class:
flash.events::Event, ptr: 0x13ab200 }) to handler
FunctionObject(FunctionObject { ptr: 0x10111c8, name:
Ok(“components::GameBase/handleXMLLoaderComplete()”) }) : TypeError:
Error #1009: Cannot access a property or method of a null object
reference. (accessing field: playBtn) at
com.rm.icecream.ui::PauseScreen/initialize() at
com.rm.icecream::Game/initialize() at
components::GameBase/loadOrInitialize() at
components::GameBase/handleXMLLoaderComplete()
core.ruffle.4165d85befd59ccf80e4.js:1 [Violation]
‘requestAnimationFrame’ handler took 107ms
core.ruffle.4165d85befd59ccf80e4.js:1 [Violation]
‘requestAnimationFrame’ handler took 91ms
core.ruffle.4165d85befd59ccf80e4.js:1 [Violation]
‘requestAnimationFrame’ handler took 97ms

I also tried to search for any old website that still had the games there. 99% of them used the official website’s URL path, and the website closed in 2012. But I found one website, the only one, that actually has the game somehow running smoothly, but I wasn’t able to understand what they did

https://www.numuki.com/include/js/waflash/default/?loadurl=https://media.numuki.com/winx-club/games/game8/game.swf?lang=en&gameId=8&languageId=1&userId=0&sessionId=

Beginner Javascript – return function nightmare [closed]

I’m trying not to use the alert() function and instead create my own message. I have built a quiz, but when I test the error message, it works but won’t move on to the next question. I feel like it has something to do with the return statement but no matter where I put it, something else fails.
Could someone point me in the right direction? I’ve checked here, W3Schools, Shecodes, ChatGPT etc

if (submitButton) {
        submitButton.addEventListener("click", function () {
            var error = document.getElementById("error");
            
            if (!answerSelected && submitButton.innerText !== "Play Again?") {
                error.innerHTML = "<span style='color: red;'>" +
                    " Please choose an answer to proceed! ";
                // return;
            } else {
                //error = document.getElementById("error");
                error.style.display= "none";
            }

            if (submitButton.innerText === "Play Again?") {

                resetQuiz();
            } else {
                currentQuestion++;

                if (currentQuestion < questions.length) {
                    showQuestion();
                } else {
                    showResult();
                }
            }
        });
    }

I tried putting the return statement after the first else statement, but it just terminated early. I tried without any return statement and that just allows users to click “Next” without answering and no error message displays. I’m at a loss.