How to save XGBoost ML model in ipynb and load in javascript in order to call the model and prompt input from user and get predicted value?

How can I link the trained model(ipynb or python file in local) into javascript(Front-end) to use?

  • I have a trained XGB model using some features(float) to predict one
    vaule(carbon intensity).
  • I want to save the model as a file and load the model to use in
    javascript. It will ask user to input the one record(22 features) in javascript and pass to ML model, whuich finnaly return and print the predicted value(carbon intensity).
  • I have known the model can be saved as a json/pickle/joblib file.

Below is the model traning code in python:

# 1. Load the Data
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# Load the dataset from an Excel file
df = pd.read_excel(r"C:UsersRYDesktopJupitertest.xlsx", sheet_name="Sheet1")

# Keep only the relevant columns (excluding the first two columns)
df = df.iloc[:, 2:]

# Categorize features based on their module (boiler, turbine, power, coal, carbon emissions)
# Features: 1(date) + 7(boiler) + 6(turbine) + 3(power) + 5(coal quality) + 2(carbon emissions) + 1(runtime) + 1(predicted carbon intensity)

# Define feature names for each module (adjust based on your actual column names)
boiler_features = ['Boiler Feedwater Temperature', 'Air Supply Temperature', 'Oxygen Level',
                   'Air Preheater Leakage Rate', 'Calculated Flue Gas Temperature',
                   'Oxygen Content (%)', 'Flue Gas Flow Rate']

turbine_features = ['Main Steam Temperature', 'Main Steam Pressure', 'Reheat Steam Temperature',
                    'Exhaust Steam Temperature', 'Vacuum', 'Average Load']

power_features = ['Load', 'Plant Power Consumption Rate', 'Operating Hours']

coal_features = ['Carbon Content (Air Dry, %)', 'Volatile Matter (Received, %)', 
                 'Ash Content (Received, %)', 'Net Calorific Value (kJ/kg, Received)', 
                 'Moisture Content (%)']

carbon_emission_features = ['CO2 Concentration', 'Carbon Emission', 'Carbon Intensity']

# Combine features in the specified order
sorted_columns = boiler_features + turbine_features + power_features + coal_features + carbon_emission_features
df = df[sorted_columns]

# Split data into features (X1) and target (y1)
X1 = df.drop('Carbon Intensity', axis=1).drop('Carbon Emission', axis=1)
y1 = df['Carbon Intensity']

# 2. Split Data into Training and Testing Sets
from sklearn.model_selection import train_test_split
X1_train, X1_test, y1_train, y1_test = train_test_split(X1, y1, test_size=0.2, random_state=42)

# Display basic statistics of the feature dataset
X1.describe()

# 3. Train the Model
from xgboost import XGBRegressor
from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, mean_absolute_percentage_error

# Initialize the XGBoost regressor
xgb_model = XGBRegressor(
    n_estimators=300,        # Number of trees
    max_depth=3,             # Maximum tree depth
    learning_rate=0.1,       # Learning rate
    subsample=0.8,           # Fraction of samples per tree
    colsample_bytree=0.8,    # Fraction of features per tree
    random_state=42
)

# Train the model on the training data
xgb_model.fit(X1_train, y1_train)

# Make predictions on the test set
xgb_y1_pred = xgb_model.predict(X1_test)


# 4. Make Predictions on one record 
# Example: Predict carbon intensity for a single data point
xgb_model.predict([X1_train.iloc[0].values])

# 5. Save the Model
# Save the trained model as a JSON file
xgb_model.save_model("xgb_model.json")

how can I save and then load the model in javascript?

One record input and out put example:

[array([ 2.42860000e+02,  1.97800000e+01,  4.59000000e+00,  2.43000000e+00,
         1.27770000e+02,  9.60153257e-02,  6.51605003e+05,  5.42320000e+02,
         1.26000000e+01,  5.12910000e+02,  3.18000000e+01, -9.78800000e+01,
         1.97080000e+02,  1.93096475e+02,  5.45000000e+00,  2.40000000e+01,
         5.36500000e+01,  2.41800000e+01,  2.18900000e+01,  1.86225000e+04,
         1.53000000e+01,  3.33225000e+03])]

array([865.6147], dtype=float32)

Real-time Audio Streaming Not Playing on iOS with WebSocket and Audio APIs

I’m building a real-time audio streaming app using WebSocket and audio APIs, but I’m facing issues specifically on iOS. The app streams audio chunks received via WebSocket from the ElevenLabs API and plays them sequentially. It works fine on most platforms, but on iOS, the audio either doesn’t play or is delayed.

What I’ve Tried:

  1. Using Web Audio API: I attempted to play the audio chunks directly using AudioContext, but iOS had compatibility issues with real-time streaming.
  2. Converting to Blob: I converted the received audio chunks to a Blob and used an element to play them. This worked, but it introduced significant delays between consecutive chunks, which is not acceptable for real-time streaming.
let connectButton = null;
let disconnectButton = null;
let sendButton = null;
let receiveBox = null;
let inputText = null;
let audioPlayer = document.getElementById("audioPlayer");

let ws = null;
let audioQueue = []; 
let isPlaying = false; 

const ELEVENLABS_WS_URL = "wss://api.elevenlabs.io/v1/text-to-speech/XrExE9yKIg1WjnnlVkGX/stream-input?model_id=eleven_multilingual_v1&inactivity_timeout=30&language=English_American";

function startup() {
    connectButton = document.getElementById("connectButton");
    disconnectButton = document.getElementById("disconnectButton");
    sendButton = document.getElementById("sendButton");
    receiveBox = document.getElementById("receive-box");
    inputText = document.getElementById("inputText");
    audioPlayer = document.getElementById("audioPlayer");

    connectButton.addEventListener("click", initializeWebSocket, false);
    disconnectButton.addEventListener("click", closeWebSocket, false);
    sendButton.addEventListener("click", sendMessage, false);
}

function initializeWebSocket() {
    if (!ws || ws.readyState === WebSocket.CLOSED) {        
        ws = new WebSocket(ELEVENLABS_WS_URL);

        ws.onopen = () => {
            console.log("Connected to ElevenLabs WebSocket.");
            connectButton.disabled = true;
            disconnectButton.disabled = false;
        };

        ws.onmessage = handleWebSocketMessage;
        ws.onerror = (error) => console.error("WebSocket error:", error);
        ws.onclose = () => {
            console.log("Disconnected from ElevenLabs WebSocket.");
            connectButton.disabled = false;
            disconnectButton.disabled = true;
        };
    }
}

function closeWebSocket() {
    if (ws) {
        ws.close();
        console.log("WebSocket connection closed.");
    }
}

function sendMessage() {
    const text = inputText.value.trim();
    if (text) {
        const message = {
            text: text,
            voice_settings: {
                stability: 1,
                similarity_boost: true,
                optimize_streaming_latency: 0
            },
            flush: true,
            xi_api_key: "",
            streaming: true
        };

        if (ws && ws.readyState === WebSocket.OPEN) {
            ws.send(JSON.stringify(message));
        } else {
            console.error("WebSocket is not connected.");
        }
    }
}

function handleWebSocketMessage(event) {
    const audioData = JSON.parse(event.data);
    console.log('audioData: ', typeof audioData);
    
    if (audioData && audioData.audio) {
        const base64Audio = audioData.audio;
        addAudioChunkToQueue(base64Audio);
    } else {
        console.error("No audio data received.");
    }
}

function addAudioChunkToQueue(base64Audio) {
    const audioBuffer = base64ToArrayBuffer(base64Audio);
    audioQueue.push(audioBuffer);

    if (!isPlaying) {
        playNextChunk();
    }
}

function playNextChunk() {
    if (audioQueue.length > 0) {
        isPlaying = true;
        const audioBuffer = audioQueue.shift();

        const audioBlob = new Blob([audioBuffer], { type: 'audio/mpeg' });
        const audioUrl = URL.createObjectURL(audioBlob);
        audioPlayer.src = audioUrl;
        audioPlayer.play()
            .then(() => {
                console.log("Playing audio chunk...");
                audioPlayer.onended = () => {
                    isPlaying = false;
                    playNextChunk(); 
                };
            })
            .catch((error) => {
                console.error("Error playing audio:", error);
                isPlaying = false;
            });
    } else {
        isPlaying = false;
    }
}

function base64ToArrayBuffer(base64) {
    console.log('Converting to arraybuffer');
    const binaryString = window.atob(base64);
    const len = binaryString.length;
    const bytes = new Uint8Array(len);
    for (let i = 0; i < len; i++) {
        bytes[i] = binaryString.charCodeAt(i);
    }
    return bytes.buffer;
}
`
window.addEventListener("load", startup);```

Can credentials (cookies) be included from the destination site in a CORS request?

I have two different domains, and trying to share data between the two.

My plan was to have domain-1.com make a GET request to domain-2.com, which would use their logged-in status on domain-2.com.

domain-2 has appropriate HTTP headers:

response.headers["Access-Control-Allow-Origin"] = request.headers["Origin"]
response.headers["Access-Control-Allow-Credentials"] = "true"
response.headers["Access-Control-Allow-Methods"] = "GET, OPTIONS"
response.headers["Access-Control-Allow-Headers"] = "Content-Type"

if request.method == "OPTIONS"
    return head :ok
end

return render json: {user: user}, status: 200

domain-1 makes a fetch request:

fetch('https://domain-2.com/endpoint', {
    method: 'GET', 
    mode: 'cors', 
    credentials: 'include'
});

I can see the OPTIONS request shows 200 OK, and the GET request shows a 200.

But there is no Cookie header sent.

Is this because these are two different domains?

Why does this work when I have www.domain.com making requests to api.domain.com which contain cookies set on api.domain.com?

Terminated gulp watch

I am using jquery and express (maybe) project.

This project node version is 12

If I run

gulp watch

Then It work.
But after I change my script file because of editing code,

[10:47:42] Finished 'js' after 984 ms
[10:47:42] Starting 'js'...
[Browsersync] 21 files changed (artist-calendar.min.js, artist-register.min.js, client-list.min.js, contact-register-confirm.min.js, contact-register.min.js, editable.min.js, globals.min.js, invoice.min.js, login.min.js, popup-artist-confirm.min.js, popup-artist-modify.min.js, profile.min.js, staff-calendar.min.js, staff-schedule-register.min.js, studio-calendar.min.js, studio-register-confirm.min.js, studio-schedule-register.min.js, user-list-table.min.js, user-modify.min.js, user-register.min.js, utils.min.js)

Above message keep showing.

After about 2 hours, frontend is shutdown and show below error

<--- Last few GCs --->
5)[15816:000001E38D34A920]  2103240 ms: Mark-sweep 2041.6 (2059.4) -> 2038.3 (2060.9) MB, 295.0 / 1.7 ms  (+ 493.2 ms in 104 steps since start of marking, biggest step 15.6 ms, walltime since start of marking 81 1: 00007FF670833B5F napi_wrap+119263
 2: 00007FF6707DA4A6 v8::internal::OrderedHashTable<v8::internal::OrderedHashSet,1>::NextTableOffset+38102
 3: 00007FF6707DB2A6 node::OnFatalError+438
 4: 00007FF671019C1E v8::Isolate::ReportExternalAllocationLimitReached+94
 5: 00007FF671001DD1 v8::SharedArrayBuffer::Externalize+833
 6: 00007FF670EB358C v8::internal::Heap::EphemeronKeyWriteBarrierFromCode+1436
 7: 00007FF670EBE7D0 v8::internal::Heap::ProtectUnprotectedMemoryChunks+1312
 8: 00007FF670EBB2E4 v8::internal::Heap::PageFlagsAreConsistent+3204
 9: 00007FF670EB0AE3 v8::internal::Heap::CollectGarbage+1283
10: 00007FF670EAF154 v8::internal::Heap::AddRetainedMap+2500
11: 00007FF670ED049D v8::internal::Factory::NewFillerObject+61
12: 00007FF670C33A91 v8::internal::interpreter::JumpTableTargetOffsets::iterator::operator=+1665
13: 00007FF67146F4BD v8::internal::SetupIsolateDelegate::SetupHeap+546925
14: 00007FF6714703ED v8::internal::SetupIsolateDelegate::SetupHeap+550813
15: 000000DDDA80A38E

Why it is happen and I can I solve?

My gulp file is below

"use strict";

// Load plugins
const autoprefixer = require("gulp-autoprefixer");
const browsersync = require("browser-sync").create();
const cleanCSS = require("gulp-clean-css");
const del = require("del");
const gulp = require("gulp");
const header = require("gulp-header");
const merge = require("merge-stream");
const plumber = require("gulp-plumber");
const rename = require("gulp-rename");
const sass = require("gulp-sass");
const uglify = require("gulp-uglify");
const http = require("http");

// Load package.json for banner
const pkg = require('./package.json');

// Set the banner content
const banner = ['/*!n',
  ' * Start - <%= pkg.title %> v<%= pkg.version %> (<%= pkg.homepage %>)n',
  ' * Copyright -' + (new Date()).getFullYear(), ' <%= pkg.author %>n',
  ' * Licensed under <%= pkg.license %> (<%= pkg.name %>)n',
  ' */n',
  'n'
].join('');

// BrowserSync
function browserSync(done) {
  browsersync.init({
    ghostMode: false,
    notify: false,
    open: false,
    server: {
      baseDir: "./",
      index: "login.html"
    },
    port: 8080
  });
  done();
}

// BrowserSync reload
function browserSyncReload(done) {
  browsersync.reload();
  done();
}

// Clean vendor
function clean() {
  return del(["./vendor/"]);
}

// Bring third party dependencies from node_modules into vendor directory
function modules() {
  // Bootstrap JS
  var bootstrapJS = gulp.src('./node_modules/bootstrap/dist/js/*')
    .pipe(gulp.dest('./vendor/bootstrap/js'));
  // Bootstrap SCSS
  var bootstrapSCSS = gulp.src('./node_modules/bootstrap/scss/**/*')
    .pipe(gulp.dest('./vendor/bootstrap/scss'));
  // ChartJS
  var chartJS = gulp.src('./node_modules/chart.js/dist/*.js')
    .pipe(gulp.dest('./vendor/chart.js'));
  // dataTables
  var dataTables = gulp.src([
      './node_modules/datatables.net/js/*.js',
      './node_modules/datatables.net-bs4/js/*.js',
      './node_modules/datatables.net-bs4/css/*.css'
    ])
    .pipe(gulp.dest('./vendor/datatables'));
  // Font Awesome
  var fontAwesome = gulp.src('./node_modules/@fortawesome/**/*')
    .pipe(gulp.dest('./vendor'));
  // jQuery Easing
  var jqueryEasing = gulp.src('./node_modules/jquery.easing/*.js')
    .pipe(gulp.dest('./vendor/jquery-easing'));
  // jQuery
  var jquery = gulp.src([
      './node_modules/jquery/dist/*',
      '!./node_modules/jquery/dist/core.js'
    ])
    .pipe(gulp.dest('./vendor/jquery'));
  return merge(bootstrapJS, bootstrapSCSS, chartJS, dataTables, fontAwesome, jquery, jqueryEasing);
}

// CSS task
function css() {
  return gulp
    .src("./scss/**/*.scss")
    .pipe(plumber())
    .pipe(sass({
      outputStyle: "expanded",
      includePaths: "./node_modules",
    }))
    .on("error", sass.logError)
    .pipe(autoprefixer({
      browsers: ['last 2 versions'],
      cascade: false
    }))
    .pipe(header(banner, {
      pkg: pkg
    }))
    .pipe(gulp.dest("./css"))
    .pipe(rename({
      suffix: ".min"
    }))
    .pipe(cleanCSS())
    .pipe(gulp.dest("./css"))
    .pipe(browsersync.stream());
}

// JS task
function js() {
  return gulp
    .src([
      './js/*.js',
      '!./js/*.min.js',
    ])
    .pipe(uglify())
    .pipe(header(banner, {
      pkg: pkg
    }))
    .pipe(rename({
      suffix: '.min'
    }))
    .pipe(gulp.dest('./js'))
    .pipe(browsersync.stream());
}

// Watch files
function watchFiles() {
  gulp.watch("./scss/**/*", css);
  gulp.watch("./js/**/*", js);
  gulp.watch("./**/*.html", browserSyncReload);
}

// Define complex tasks
const vendor = gulp.series(clean, modules);
const build = gulp.series(vendor, gulp.parallel(css, js));
const watch = gulp.series(build, gulp.parallel(watchFiles, browserSync));

// Export tasks
exports.css = css;
exports.js = js;
exports.clean = clean;
exports.vendor = vendor;
exports.build = build;
exports.watch = watch;
exports.default = build;

counting filtered rows of a table with javascript code

how can i count the filtered rows of a table. The table has many rows. it is just normal containing many rows. With the help of following Javascript code. I filter data, by way of typing into input text, pasting the required value and also with a click to import the value from OptionList; and all these three ways are functioning perfectly. If it is possible to amend this code so as to get the count of filtered rows out of total rows, i.e. “Found….. rows out of……rows. at the top of table. I am totally a new user of javascript without any previous knowledge so sorry for that. The code is :



    const trs = document.getElementById("myTable").getElementsByTagName("tr");
document.getElementById("search").addEventListener("input", filterRows);
document.getElementById("search").addEventListener("change", filterRows);
document.getElementById("search").addEventListener("click", filterRows);

function filterRows(e) {
    const query = e.target.value.toLowerCase();
    for (const tr of trs) {
        
tr.style.display = tr.innerText.toLowerCase().includes(query) ? "" : "none";
    }
}


Enable Offline Functionality for Ionic Web App

I’m not a developer, but I do work on some small coding projects for my wife’s company. I’ve built a vehicle inspection SPA app in vanilla JS Ionic. A key requirement is that the app continue to work offline, and sync / submit collected data when a connection is restored. Her company has a dedicated PHP / MySQL developer who handles all the back-end functionality.

My app is largely working, but the offline portion isn’t. I created a service worker which was mostly working, but Ionic files weren’t getting properly cached if I linked to the files using the CDN links in my index.html file. I was able to get the app working and caching properly by copying all the files in my node_modules Ionic directory locally, but only by placing them in my public directory and not having them processed by Vite. I read that this likely wasn’t the best approach for app performance, and did notice a slight degradation. But at least it was working as expected, and I may revert back to that…

I’ve been going down a rabbit hole the last two days trying to import the Ionic components I’m actually using in my project into a JS module. That is partially working, but none of my components are having the hydration class applied. I basically have an app that is just a white screen, but if I inspect the HTML in dev tools all is working as expected, just not hydrating.

I’m wondering if it is possible to get this working by importing components, or if there is some way to cache local versions of the files served by the Ionic CDN as users interact with my app? Here’s a simplified / stripped down version of how I’m trying to import the components:

import { IonApp } from '../../node_modules/@ionic/core/components/ion-app.js';
import { IonContent } from '../../node_modules/@ionic/core/components/ion-content.js';

customElements.define('ion-app', IonApp);
customElements.define('ion-content', IonContent);

initialize();

How to correctly include SCSS mixin file in any SCSS file that is part of my Next.js app?

I have a working Next.js 14 app for which I am using SCSS. I have a main global.scss file in path:

my-project/src/app/globals.scss

and this file’s content is:

/* my-project/src/app/globals.scss */
@use 'styles/mixins'; /* <-this is the mixins file I intend to use in any scss file listed below, but it's not working */
@use 'styles/global';
@use 'styles/navigation';
@use 'styles/footer';

as you can see, I @use several scss files located in path and they are imported just fine.

The issue I am having is with the styles/mixins.scss file, who’s content looks like this:

/* my-project/src/app/styles/mixins.scss */
@mixin for-size($size) {
  @if $size == phone-only {
    @media (max-width: 899px) { @content; }
  } @else if $size == desktop-up {
    @media (min-width: 900px) { @content; }
  }
}

for example in styles/navigation.scss file I want to use the mixin like so:

header {
  &.navigation-bar {
    @include mixins.for-size(phone-only) {    
      padding: 0 1%;
    }
...

but I’m getting:

There is no module with the namespace "mixins".

the issue is that I simply do not know how to correctly import/include/use the mixins.scss file so that I can reference it’s mixins from any scss file in my scss tree…any advice is appreciated.

Styling Fluent UI checkboxes within a dropdown

I need to style a fluent UI checkbox using the style props. However based on the documentation it is unclear how to style the checkbox differently in its checked vs unchecked state. I am able to set the background color to black in the example below, but don’t see any change in background color when an item is selected.

const dropdownStyles = {
dropdown: { 
    width: '300px',
    color: 'white',
    backgroundColor: '#333333',
    borderWidth: '1px',
    borderColor: 'black',
    borderStyle: 'solid',
},
title: {
    backgroundColor: '#333333',
    color: 'white'
},
dropdownItem: {
    backgroundColor: '#333333',
    color: 'white'
},
dropdownItemSelected: {
    backgroundColor: '#333333',
    color: 'white',
    '.ms-Checkbox-checkbox': {
        backgroundColor: 'red'
    }
},
dropdownItemDisabled: {
    backgroundColor: '#333333',
    color: 'gray'
},
dropdownItemHeader: {
    backgroundColor: '#333333',
    color: 'white'
},
dropdownItemsWrapper: {
    backgroundColor: '#333333'
},
dropdownOptionText: {
    color: 'white'
},
subComponentStyles: {
    multiSelectItem: {
        root: {
            selectors: {
                '.ms-Checkbox-checkmark': {
                    color: 'white',
                },
                '.ms-Checkbox-checkbox': {
                    borderColor: 'black',
                    backgroundColor: 'black',
                    '& .dropdownItemSelected': {
                        backgroundColor: 'yellow'
                    }
                }
            },
        }
    }
}
};

Results in below enter image description here

Additionally, how would I be able to change the hover color to not be blue? Thank you

About the Behaviours OF JS ( V8 )

From this Page

JavaScript values in V8 are represented as objects and allocated on
the V8 heap, no matter if they are objects, arrays, numbers or
strings. This allows us to represent any value as a pointer to an
object.

in this code ( JS ( V8 ) ) :

let x=33.5;
let y=x;

As Far As i know 33.5 in V8 is not a small integer so 33.5 will not be treated as a smi so it will be treated as an object and will be allocated in the heap

in let x=33.5; x pointes to an object in the heap and that object will hold the value ( which is 33.5 )

My Question is :

in let y=x;

will that create another new object in the heap and that object will ( also ) hold the value ( which is 33.5 ) ( In other words : y will point to a different object of the object which x points to ) ?

OR what happens here is just y and x will point to the same object and Only when you try to change the value of y ( or when you try to change the value of x )
a new object ( that holds the new value ) will be created ( example of changing the value of y is this line ( if you add this line to my code ) y=83.5; ) ?

Is JS ( V8 ) Like Python?

From this Page

JavaScript values in V8 are represented as objects and allocated on
the V8 heap, no matter if they are objects, arrays, numbers or
strings. This allows us to represent any value as a pointer to an
object.

in python : ( From this Page ) every thing is an object and integers are immutable

if we try this code ( in Python ) :

x=333
r=x
print(id(x)==id(r)) #True
r=444
print(x) #333

What happens here is :
x=333 makes x points to an object in address ( for example ) A2 and the value of this object is 333

r=x makes r points to the same object which x points to . ( r points to the address A2 ( and x points to the same address ) )

in r=444 because integers in python are immutable by nature a new object will be created ( in another address ) and the value of the new object is 444 and the address A2 still has the value 333 and x is still pointing to the address A2

So My Question is in this code ( JS ( V8 ) ) :

let x=33.5;
let y=x;

As Far As i know 33.5 in V8 is not a small integer so 33.5 will not be treated as a smi so it will be treated as an object and will be allocated in the heap

in let x=33.5; x pointes to an object in the heap and that object will hold the value ( which is 33.5 )

in let y=x; will that create another new object in the heap and that object will ( also ) hold the value ( which is 33.5 ) ?

OR ( Exactly Like Python ) what happens here is just y and x will point to the same object and ( because primitives in JS ( and in V8 ) are immutable ) Only when you try to change the value of y ( or when you try to change the value of x ) a new object ( that holds the new value ) will be created ?

Note : I Do Not Say That JS Is Python or JS Is Like Python . I Am Just Talking About The Behaviours of JS And The Behaviours of Python

How to Collect Data Across Iframes on a Shared Domain Without Interacting With the Main Page?

I am working on an implementation involving hosted fields for securely handling credit card information. My setup includes the following:

  1. An HTML page containing 4 iframes:

    • 3 iframes for credit card details (card number, validity, and CVV).
    • 1 admin iframe for managing and collecting the data from the credit card iframes.
  2. All iframes are hosted on the same shared domain, ensuring the same-origin policy is not violated.

I want the admin iframe to directly collect data from the 3 credit card iframes without involving the main page. The main page should remain unaware of the data exchange between the admin iframe and the credit card iframes.

I am unable to implement this direct communication between the admin iframe and the credit card iframes without going through the main page.

  • The main page must remain entirely decoupled from the data flow between the admin iframe and the credit card iframes.
  • All iframes are on the same shared domain.

How can I implement direct communication between the admin iframe and the credit card iframes under these constraints? Are there any techniques or best practices for iframe-to-iframe communication that do not rely on the main page?

This is part of a hosted fields implementation for payment processing, so security is a top priority. The admin iframe acts as a controller to collect and manage sensitive information securely.

Any guidance, sample code, or recommended patterns would be greatly appreciated.

Let me know if you’d like any adjustments or additional details added!

I have tried the following approaches:

  • Using the window.parent and window.frames APIs, but this requires communication through the main page, which I want to avoid.
  • Exploring postMessage for iframe communication, but I can’t seem to bypass the main page effectively.

my horizontal scroll is visible but does not work

I am creating an app in ionic, I have a tab that shows a total of 7 cards but I want them to be displayed as horizontal scroll that only 4 can be seen and the others when scrolling, if the 4 are shown but the others do not because the scroll does not work.

actually I have this in my code, according to what I have seen that with overflow-x: auto it should work but it hasn’t worked for me.

My html:

<ion-header [translucent]="true">
  <ion-toolbar class="container">
   <!--  <ion-title>HOY</ion-title> -->
    <h2 class="hoy">HOY</h2>
    <h1 class="dia">{{day}}</h1>
  </ion-toolbar>
</ion-header>

<ion-content [fullscreen]="true">
  <ion-header collapse="condense">
    <ion-toolbar>
      <!-- <ion-title size="large">plan</ion-title> -->
    </ion-toolbar>
  </ion-header>

 


  <div class="cards-container">
    <ion-card *ngFor="let daycard of days" class="cards">
        <ion-card-content class="card-content">
            <div class="image-day">
                <img src="{{ daycard.image }}" alt="">
            </div>
        </ion-card-content>
    </ion-card>
</div>

  
  <app-maintabs></app-maintabs>
</ion-content>

My scss:

.cards-container {
    max-width: 100%;
    display: flex;
    overflow-x: scroll; 
    overflow-y: hidden;
    white-space: nowrap;
    background-color: red;
    padding: 10px;
    gap: 10px;
    -webkit-overflow-scrolling: touch;
    
    .cards {
        min-width: 25%;
        background-color: blue;
        scroll-snap-align: start;

        .card-content {
            width: 100%; 
            
            .image-day {
                width: 100%;
                height: 200px; 
                
                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }
        }
    }
}```

Struggling to store character positions in array

Very sorry about the ambiguous title as I simply don’t know how to describe my problem in one line.

I have a string that keeps changing at random intervals. I want to be able to track changes to that string and later be able to reconstruct the final string.

Example:

const text1 = 'Hello everyone, my name is Chris';
//12 seconds later it turns into:
const text2 = 'Hello everyone, my fame is gone';
//... Keeps changing...

I am using this outstanding library called fast-diff to compare the strings and store the diff array. Here is how it works:

const text1 = 'Hello everyone, my name is Chris';
const text2 = 'Hello everyone, my fame is gone';
const diff_array = diff(text1, text2, 1);
console.log(diff_array);

The result is:

[
  [ 0, 'Hello everyone, my ' ],
  [ -1, 'n' ],
  [ 1, 'f' ],
  [ 0, 'ame is ' ],
  [ -1, 'Chris' ],
  [ 1, 'gone' ]
]

Where 0 represents unchanged characters, 1 represents added characters and -1 represents removed characters.

Based on this diff array, I can easily reconstruct 'Hello everyone, my fame is gone' by running something like this:

diff_array.forEach(el => {
    if(el[0] !== -1)
        process.stdout.write(el[1]);
})

All I gotta do is store the array somewhere.

Problem: When dealing with large strings, the diff array, as currently constructed, stores a tremendous amount of redundancy as most times the changes to a 10,000 character strings are minimal.

Goal: What I want to do instead is store the original string AND turn the diff array from

[
  [ 0, 'Hello everyone, my ' ],
  [ -1, 'n' ],
  [ 1, 'f' ],
  [ 0, 'ame is ' ],
  [ -1, 'Chris' ],
  [ 1, 'gone' ]
]

to:

[
    [
        0,
        {
            start: 0,
            end: 19
        }
    ],
    [ -1, 'n' ],
    [ 1, 'f' ],
    [
        0,
        {
            start: 20,
            end: 27
        }
    ],
    [-1, 'Chris' ],
    [ 1, 'gone' ]

]

Where 0s instead make a reference to the start and end character positions of the unchanged original text. That will hugely lower my storage cost. I need a function that will accept the original text and the diff array and spit out a new diff array that looks like the above.

The reason I am struggling here is because it isn’t a simple matter of searching the original string for 'Hello everyone, my ' and 'ame is ' and finding their positions, because those substrings can be in other places as well. I have to search it sequentially while keeping track of where the current search position is.

Fill element with jQuery [duplicate]

Scenario: When the page is loaded it has e.g. users State in plain div and below there’s e.g. address form to be filled, so the existing State select list can be autofilled with correct State and save time.

HTML:

<div class="state-text">
Alabama
</div>

<select class="state">
  <option value="" selected="selected">- Select -</option>
  <option value="AL">Alabama</option>
  <option value="AK">Alaska</option>
</select>

jQuery:

if ($('.state-text').val() == 'Alabama') {
    $('select.state').val('AL');
} 
else {
    $('select.state').val(''); // default to "- Select -"
}

https://jsfiddle.net/cp2n4dtz/

Reference source If/else else if in Jquery for a condition but it doesn’t seem to work. What i missing?

Goal is if .state-text has Alabama, then the right value of AL should be selected, if Alaska then it’s AK and so on for all 50 states. On page load.

Thank you.

Error: Cannot read properties of undefined (reading ‘path’) when uploading files with Multer and Cloudinary

I’ve been following a tutorial from YouTube and encountered an error when trying to test my API with Thunder Client. Despite my debugging efforts, I haven’t been able to resolve it. I’d appreciate some help!

I’m getting the following error when testing my API:TypeError: Cannot read properties of undefined (reading 'path')

cloudinaryConfig.js:

import { v2 as cloudinary } from 'cloudinary';

const connectCloudinary = async () => {
    cloudinary.config({
        cloud_name: process.env.CLOUDINARY_NAME,
        api_key: process.env.CLOUDINARY_API_KEY,
        api_secret: process.env.CLOUDINARY_SECRET_KEY,
    });
};
export default connectCloudinary;

multer.js:

import multer from 'multer';
import path from 'path';

const storage = multer.diskStorage({
    destination: function (req, file, callback) {
        // Specify the directory for storing uploaded files
        callback(null, path.resolve('./uploads'));
    },
    filename: function (req, file, callback) {
        console.log("The file name is: ", file);
        // Use the original file name or customize it
        callback(null, new Date().toISOString() + file.originalname);
    },
});

const upload = multer({ storage });

export default upload;

adminRoute.js:

import express from 'express';
import { addDoctor } from '../controllers/adminController.js';
import upload from '../middlewares/multer.js';

const adminRouter = express.Router();

adminRouter.post('/add-doctor', upload.single('image'), addDoctor);

export default adminRouter;

adminController.js:

import validator from 'validator';
import bcrypt from 'bcrypt';
import { v2 as cloudinary } from 'cloudinary';
import doctorModel from '../models/doctorModel.js';
import path from 'path';

const addDoctor = async (req, res) => {
    try {
        const { name, email, password, speciality, degree, experience, about, fees, address } = req.body;
        const imageFile = req.file;

        if (!name || !email || !password || !speciality || !degree || !experience || !about || !fees || !address) {
            return res.json({ success: false, message: 'Missing some details' });
        }

        if (!validator.isEmail(email)) {
            return res.json({ success: false, message: 'Please enter a valid Email' });
        }

        if (password.length < 8) {
            return res.json({ success: false, message: 'Please, provide a strong password' });
        }

        const salt = await bcrypt.genSalt(10);
        const hashedPassword = await bcrypt.hash(password, salt);

        const imageUpload = await cloudinary.uploader.upload(imageFile.path, { resource_type: 'image' });
        const imageUrl = imageUpload.secure_url;

        const doctorData = {
            name,
            email,
            image: imageUrl,
            password: hashedPassword,
            speciality,
            degree,
            experience,
            about,
            fees,
            address: JSON.parse(address),
            date: Date.now(),
        };

        const newDoctor = new doctorModel(doctorData);
        await newDoctor.save();

        res.json({ success: true, message: 'Doctor added' });
    } catch (error) {
        console.log(error);
        res.json({ success: false, message: error.message });
    }
};

export { addDoctor };

When I send a POST request with a file (key: image) and form data, the doctor should be added successfully, and the image should be uploaded to Cloudinary.

I’m using Thunder Client to test the API.
The file upload key is named image.
What could be causing the path to be undefined in req.file?