SQL Exists clause in Supabase JS Client

In SQL the EXISTS clause is quite useful for checking specific conditions without having to join. For example looking for a user which doesn’t belong to a group :

SELECT * FROM users u WHERE NOT EXISTS 
   (SELECT 1 FROM users_groups ug WHERE ug.user_id = u.id)

Is there an equivalent to this type of query in the Supabase Javascript Client library ? I have looked at the docs but can’t seem to find anything.

need help working on a scratch node application which uses crud have done that part wanted to add authorization factor in it but getting error

Application Description:

The application is a web-based platform that allows users to register, log in, and interact with a list of user profiles. It includes user authentication for security and uses a database to store user information. Here are the key features and what has been created so far:

Features Implemented:

User Registration: Users can create accounts by providing a username and password. The password is securely hashed for protection.

User Login: Registered users can log in using their credentials.

User Profiles: Upon logging in, users can view a list of user profiles. These profiles contain personal information like username, age, gender, and income.

Sorting: Users can sort the list of profiles in either ascending or descending order based on income.

User Authentication: The application ensures that only authenticated users can access certain features, such as viewing user profiles.

Session Management: It uses session management to keep users logged in across different pages of the website.
now i am going to provide my code and for all the modules

const express = require('express');
const router = express.Router();
const usersController = require('./controllers/usersController');
const bodyParser = require('body-parser');
const session = require('express-session');
const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const mongoose = require('mongoose');
const User = require('./models/user'); // Replace with your actual User model

const app = express();
const port = process.env.PORT || 3000;
// Route to retrieve and display users using the controller
router.get('/users', usersController.getUsers);

module.exports = router;
app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');

// ----------------------------------------
// Connect to MongoDB
// ----------------------------------------

mongoose.connect('mongodb://localhost/user', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
  .then(() => {
    console.log('MongoDB Connected');
  })
  .catch((err) => {
    console.error('MongoDB Connection Error:', err);
  });

// ----------------------------------------
// Passport.js Configuration
// ----------------------------------------

app.use(session({
  secret: 'your-secret-key',
  resave: false,
  saveUninitialized: false
}));

app.use(passport.initialize());
app.use(passport.session());

passport.use(new LocalStrategy(
  (username, password, done) => {
    User.findOne({ username: username })
      .then((user) => {
        if (!user) {
          return done(null, false, { message: 'Incorrect username.' });
        }
        bcrypt.compare(password, user.password)
          .then((result) => {
            if (!result) {
              return done(null, false, { message: 'Incorrect password.' });
            }
            return done(null, user);
          })
          .catch((err) => done(err));
      })
      .catch((err) => done(err));
  }
));

passport.serializeUser((user, done) => {
  done(null, user.id);
});

passport.deserializeUser((id, done) => {
  User.findById(id)
    .then((user) => done(null, user))
    .catch((err) => done(err));
});

// ----------------------------------------
// CRUD Routes
// ----------------------------------------

// Create Route
app.post('/create', (req, res) => {
    const { username, age, gender, income } = req.body;
    // Replace this with your User model and database logic
    User.create({ username, age, gender, income }, (err, user) => {
      if (err) {
        console.error(err.message);
        return res.status(500).send('Create failed');
      }
      res.redirect('/');
    });
  });
  
  // Read Route
  app.get('/', (req, res) => {
    // Replace this with your User model and database logic to fetch and render data
    User.find({}, (err, users) => {
      if (err) {
        console.error(err.message);
        return res.status(500).send('Read failed');
      }
      res.render('index', { users });
    });
  });
  
  // Update Route
  app.post('/update/:id', (req, res) => {
    const userId = req.params.id;
    const { username, age, gender, income } = req.body;
    // Replace this with your User model and database logic
    User.findByIdAndUpdate(userId, { username, age, gender, income }, (err, user) => {
      if (err) {
        console.error(err.message);
        return res.status(500).send('Update failed');
      }
      res.redirect('/');
    });
  });
  
  // Delete Route
  app.get('/delete/:id', (req, res) => {
    const userId = req.params.id;
    // Replace this with your User model and database logic
    User.findByIdAndRemove(userId, (err, user) => {
      if (err) {
        console.error(err.message);
        return res.status(500).send('Delete failed');
      }
      res.redirect('/');
    });
  });

// ----------------------------------------
// Authentication Routes
// ----------------------------------------

app.post('/register', (req, res) => {
  const { username, password } = req.body;
  bcrypt.hash(password, 10)
    .then((hashedPassword) => {
      User.create({ username, password: hashedPassword })
        .then((user) => {
          res.redirect('/login');
        })
        .catch((err) => {
          console.error(err.message);
          res.status(500).send('Registration failed');
        });
    })
    .catch((err) => {
      console.error(err.message);
      res.status(500).send('Registration failed');
    });
});

app.post('/login', passport.authenticate('local', {
  successRedirect: '/profile',
  failureRedirect: '/login',
  failureFlash: true
}));

app.get('/logout', (req, res) => {
  req.logout();
  res.redirect('/login');
});

// ----------------------------------------
// Authentication Middleware
// ----------------------------------------

function isLoggedIn(req, res, next) {
  if (req.isAuthenticated()) {
    return next();
  }
  res.redirect('/login');
}

// ----------------------------------------
// Example: Protect a route
// ----------------------------------------

app.get('/profile', isLoggedIn, (req, res) => {
  res.render('profile', { user: req.user });
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

now for authentication

// passport-config.js

const passport = require('passport');
const LocalStrategy = require('passport-local').Strategy;
const bcrypt = require('bcrypt');
const User = require('./models/user'); // Replace with your User model import

// Configure Passport.js
passport.use(new LocalStrategy(User.authenticate()));

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

module.exports = (app) => {
  app.use(passport.initialize());
  app.use(passport.session());
};

index ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Personal Information</title>
    <link rel="stylesheet" href="/styles.css"> <!-- Include your CSS file -->
</head>
<body>
    <h1>Personal Information</h1>

    <!-- Form for creating a new entry -->
    <form action="/create" method="POST">
        <input type="text" name="username" placeholder="Username" required>
        <input type="number" name="age" placeholder="Age" required>
        <input type="text" name="gender" placeholder="Gender" required>
        <input type="number" name="income" placeholder="Income" required>
        <button type="submit">Add Entry</button>
    </form>

    <!-- Display personal information -->
    <table>
        <tr>
            <th>Username</th>
            <th>Age</th>
            <th>Gender</th>
            <th>Income</th>
            <th>Actions</th>
        </tr>
        <% data.forEach((entry) => { %>
            <tr>
                <td><%= entry.username %></td>
                <td><%= entry.age %></td>
                <td><%= entry.gender %></td>
                <td>$<%= entry.income %></td>
                <td>
                    <a href="/update/<%= entry.id %>">Edit</a> |
                    <a href="/delete/<%= entry.id %>">Delete</a>
                </td>
            </tr>
        <% }); %>
    </table>

    <!-- Sorting options -->
    <div>
        <p>Sort by Income:</p>
        <a href="/sort/asc">Ascending</a> |
        <a href="/sort/desc">Descending</a>
    </div>
</body>
</html>

login ejs

<h1>Login</h1>
<form action="/login" method="POST">
  <input type="text" name="username" placeholder="Username" required>
  <input type="password" name="password" placeholder="Password" required>
  <button type="submit">Login</button>
</form>

profile ejs

<h1>Welcome, <%= user.username %></h1>
<p>User-specific content goes here.</p>
<a href="/logout">Logout</a>

register ejs

<!-- Display flash messages for success and error -->
<% if (success) { %>
  <div class="alert alert-success">
    <%= success %>
  </div>
<% } %>

<% if (error) { %>
  <div class="alert alert-danger">
    <%= error %>
  </div>
<% } %>

<h1>Registration</h1>
<form action="/register" method="POST">
  <input type="text" name="username" placeholder="Username" required>
  <input type="password" name="password" placeholder="Password" required>
  <button type="submit">Register</button>
</form>
<h1>Registration</h1>
<form action="/register" method="POST">
  <input type="text" name="username" placeholder="Username" required>
  <input type="password" name="password" placeholder="Password" required>
  <button type="submit">Register</button>
</form>

for styles

body {
    font-family: Arial, sans-serif;
    margin: 20px;
    padding: 0;
}

h1 {
    font-size: 24px;
    margin-bottom: 20px;
}

form input {
    margin-right: 10px;
}

table {
    width: 100%;
    border-collapse: collapse;
    margin-top: 20px;
}

table, th, td {
    border: 1px solid #ccc;
}

th, td {
    padding: 10px;
    text-align: center;
}

th {
    background-color: #f2f2f2;
    font-weight: bold;
}

table tr:nth-child(even) {
    background-color: #f2f2f2;
}

a {
    text-decoration: none;
    color: #007BFF;
}

a:hover {
    text-decoration: underline;
}

div {
    margin-top: 20px;
}

p {
    margin-bottom: 10px;
}

and user js

const mongoose = require('mongoose');
const passportLocalMongoose = require('passport-local-mongoose');

const userSchema = new mongoose.Schema({
  username: String,
  // You can add more fields like 'name', 'email', 'profilePicture', etc.
});

// Add Passport-Local-Mongoose plugin to User Schema
userSchema.plugin(passportLocalMongoose);

// Create and export the User model
module.exports = mongoose.model('User', userSchema);

i have worked on this please if you can add more feature to it will be most welcomed but help me in adding authentication to this project
i will also add the previous code whose only function was to work on crud

const express = require('express');
const bodyParser = require('body-parser');
const sqlite3 = require('sqlite3').verbose();
const app = express();
const port = process.env.PORT || 3000;

app.use(bodyParser.urlencoded({ extended: false }));
app.set('view engine', 'ejs');

const db = new sqlite3.Database('./data.db');

db.serialize(() => {
  db.run(`
    CREATE TABLE IF NOT EXISTS personal_info (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      username TEXT,
      age INTEGER,
      gender TEXT,
      income INTEGER
    )
  `);
});

app.post('/create', (req, res) => {
  const { username, age, gender, income } = req.body;
  const stmt = db.prepare('INSERT INTO personal_info (username, age, gender, income) VALUES (?, ?, ?, ?)');
  stmt.run(username, age, gender, income, (err) => {
    if (err) {
      console.error(err.message);
      res.status(500).send('Internal Server Error');
    } else {
      res.redirect('/');
    }
  });
  stmt.finalize();
});

app.get('/', (req, res) => {
  db.all('SELECT * FROM personal_info', (err, rows) => {
    if (err) {
      console.error(err.message);
      res.status(500).send('Internal Server Error');
      return;
    }
    res.render('index.ejs', { data: rows });
  });
});

app.post('/update/:id', (req, res) => {
  const { username, age, gender, income } = req.body;
  const id = req.params.id;
  const stmt = db.prepare('UPDATE personal_info SET username = ?, age = ?, gender = ?, income = ? WHERE id = ?');
  stmt.run(username, age, gender, income, id, (err) => {
    if (err) {
      console.error(err.message);
      res.status(500).send('Internal Server Error');
    } else {
      res.redirect('/');
    }
  });
  stmt.finalize();
});

app.get('/delete/:id', (req, res) => {
  const id = req.params.id;
  db.run('DELETE FROM personal_info WHERE id = ?', id, (err) => {
    if (err) {
      console.error(err.message);
      res.status(500).send('Internal Server Error');
    } else {
      res.redirect('/');
    }
  });
});

app.get('/sort/asc', (req, res) => {
  db.all('SELECT * FROM personal_info ORDER BY income ASC', (err, rows) => {
    if (err) {
      console.error(err.message);
      res.status(500).send('Internal Server Error');
      return;
    }
    res.render('index.ejs', { data: rows });
  });
});

app.get('/sort/desc', (req, res) => {
  db.all('SELECT * FROM personal_info ORDER BY income DESC', (err, rows) => {
    if (err) {
      console.error(err.message);
      res.status(500).send('Internal Server Error');
      return;
    }
    res.render('index.ejs', { data: rows });
  });
});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

we were previously using sqlite for this project but now we have added mongo in it so i don’t know which should be easy to work or use it so make changes in it if possible

Chrome notifications using Javascript within Google Apps Script

I’m trying to use javascript from within a Google Apps Script project in order to display notifications to the user using chrome.notifications

However, this isn’t working. Whenever I query Notification.permission it returns ‘denied’, even if I explicitly ‘allow’ in settings for the page:

let permission = Notification.permission;
alert(permission);

…always returns ‘denied’.

I use HtmlService.createTemplateFromFile to create the HTML pages in my project, so I suspect this issue is happening because Chrome doesn’t allow notifications from within a cross-origin frame.

I was wondering if anyone had come up with a solution or work-around for this?

how to extract specific data from a leaflet variable/array

I have a variable created in leaflet and I need to extract a part of inside data that are gps coordinates, in order to use separately
This is my var and how it is generatared

var track = new L.GPX(‘tracce_gpx/Subit(via Porzûs)_Attimis.gpx’, {async: true, display_wpt:false, color: ‘#a539a8’,opacity:0.6,weight:6}).addTo(Video);

with “console.log(track);”

in browser console I obtain:

i {options: {…}, _gpx: 'tracce_gpx/Subit(via Porzûs)_Attimis.gpx', _layers: {…}, _initHooksCalled: true, _events: {…}, …}
options
: 
{async: true, display_wpt: false, color: '#a539a8', opacity: 0.6, weight: 6}

_events
: 
{click: Array(1)}

_gpx
: 
"tracce_gpx/Subit(via Porzûs)_Attimis.gpx"

_initHooksCalled
: 
true

_layers
: 
126
: 
i
options
: 
{async: true, display_wpt: false, color: '#a539a8', opacity: 0.6, weight: 6}

_bounds
: 
R {_southWest: D, _northEast: D}

_eventParents
: 
{125: i}

_events
: 
{click: Array(1), keypress: Array(1), remove: Array(1), move: Array(1)}

_initHooksCalled
: 
true

_latlngs
: 
Array(588)
[0 … 99]
[100 … 199]
[200 … 299]
[300 … 399]
[400 … 499]
[500 … 587]
length
: 
588
[[Prototype]]
: 
Array(0)

_leaflet_id
: 
126

_popup
: 
i {options: {…}, _source: i, _initHooksCalled: true, _content: '<p>12.0 km</p>'}

_popupHandlersAdded
: 
true
[[Prototype]]
: 
i
[[Prototype]]
: 
Object

_leaflet_id
: 
125
[[Prototype]]
: 
i

enter image description here

What a need is to extract and assign data from (_latlngs : ) to a new variable
this is a part of a more complicated question posted here:

How to create leaflet polyline, after loading Gpx track, with different colors

thanks for any suggestion

Why Am I Having NaN Error For Some Nutritional Values Within Nutritionix API Search?

Context:
I have a script that utilizes the Nutritionix API to retrieve nutritional values for various food items. While the API returns valid values for some nutrients, it returns ‘NaN’ for others. I suspect this issue could be due to my usage of the free version of the API or a potential error in my code, possibly related to the item IDs. (An example of what I mean by ‘item IDs’ includes ‘nf_biotin’ and ‘nf_iron,’ both of which should be returning values and working correctly.)

Script:


let table = base.getTable('Raw Meals 2')
let {records} = await table.selectRecordsAsync()
console.log(records)

for (let record of records){
 const url = 'https://trackapi.nutritionix.com/v2/natural/nutrients';
 const options = {
  method: 'POST',
  headers: {
      'Content-type' : 'application/json',
      'x-app-key':'--',
      'x-app-id': '--'
      },
   body: JSON.stringify({
     'query':`${record.name}`
   })
  }
 let Response = await fetch (url,options);
 let data = await Response.json();
//WORKING
 const calories = data.foods.reduce((acc, item) => acc + item.nf_calories, 0)
 const protein = data.foods.reduce((acc, item) => acc + item.nf_protein, 0)
 const carbs = data.foods.reduce((acc, item) => acc + item.nf_total_carbohydrate, 0)
 const fat = data.foods.reduce((acc, item) => acc + item.nf_total_fat, 0)
 const saturatedfat = data.foods.reduce((acc, item) => acc + item.nf_saturated_fat, 0)
 const sugars = data.foods.reduce((acc, item) => acc + item.nf_sugars, 0)
 const cholesterol = data.foods.reduce((acc, item) => acc + item.nf_cholesterol, 0)
 const fiber = data.foods.reduce((acc, item) => acc + item.nf_dietary_fiber, 0)
 const potassium = data.foods.reduce((acc, item) => acc + item.nf_potassium, 0)
 const sodium = data.foods.reduce((acc, item) => acc + item.nf_sodium, 0)
 //NOT WORKING (NaN)
 const addsugars = data.foods.reduce((acc, item) => acc + item.nf_added_sugars, 0)
 const vita = data.foods.reduce((acc, item) => acc + item.nf_vitamin_a, 0)
 const vitb1 = data.foods.reduce((acc, item) => acc + item.nf_thiamin, 0)
 const vitb2 = data.foods.reduce((acc, item) => acc + item.nf_riboflavin, 0)
 const vitb3 = data.foods.reduce((acc, item) => acc + item.nf_niacin, 0)
 const vitb5 = data.foods.reduce((acc, item) => acc + item.nf_panthothenic_acid, 0)
 const vitb6 = data.foods.reduce((acc, item) => acc + item.nf_vitamin_b6, 0)
 const vitb7 = data.foods.reduce((acc, item) => acc + item.nf_biotin, 0)
 const vitb9 = data.foods.reduce((acc, item) => acc + item.nf_folate, 0)
 const vitb12 = data.foods.reduce((acc, item) => acc + item.nf_vitamin_b12, 0)
 const vitc = data.foods.reduce((acc, item) => acc + item.nf_vitamin_c, 0)
 const vitd = data.foods.reduce((acc, item) => acc + item.nf_vitamin_d, 0)
 const vite = data.foods.reduce((acc, item) => acc + item.nf_vitamin_e, 0)
 const vitk = data.foods.reduce((acc, item) => acc + item.nf_vitamin_k, 0)
 const transfat = data.foods.reduce((acc, item) => acc + item.nf_trans_fat, 0) 
 const monofat = data.foods.reduce((acc, item) => acc + item.nf_monounsaturated_fat, 0)
 const polyfat = data.foods.reduce((acc, item) => acc + item.nf_polyunsaturated_fat, 0)
 const ftype = data.foods.reduce((acc, item) => acc + item.food_type, 0)
 const fcateg = data.foods.reduce((acc, item) => acc + item.food_category, 0)
 const calcium = data.foods.reduce((acc, item) => acc + item.nf_calcium, 0)
 const iron = data.foods.reduce((acc, item) => acc + item.nf_iron, 0)
 const selenium = data.foods.reduce((acc, item) => acc + item.nf_selenium, 0)
 const zinc = data.foods.reduce((acc, item) => acc + item.nf_zinc, 0)
 const magnesium = data.foods.reduce((acc, item) => acc + item.nf_magnesium, 0)
 const phosphorus = data.foods.reduce((acc, item) => acc + item.nf_phosphorus, 0)
 const omega3 = data.foods.reduce((acc, item) => acc + item.nf_omega_3_total, 0)
 const omega6 = data.foods.reduce((acc, item) => acc + item.nf_omega_6_total, 0)
 const aminos = data.foods.reduce((acc, item) => acc + item.nf_amino_acids, 0)
 const lysine = data.foods.reduce((acc, item) => acc + item.nf_lysin, 0)
 const leucine = data.foods.reduce((acc, item) => acc + item.nf_leucine, 0)
 const isoleucine = data.foods.reduce((acc, item) => acc + item.nf_isoleucine, 0)
 const valine = data.foods.reduce((acc, item) => acc + item.nf_valine, 0)
 const threonine = data.foods.reduce((acc, item) => acc + item.nf_threonine, 0)
 const phenylalanine = data.foods.reduce((acc, item) => acc + item.nf_phenylalanine, 0)
 const methionine = data.foods.reduce((acc, item) => acc + item.nf_methionine, 0)
 const histidine = data.foods.reduce((acc, item) => acc + item.nf_histidine, 0)
 const tryptophan = data.foods.reduce((acc, item) => acc + item.nf_tryptophan, 0)
 const betacarotene = data.foods.reduce((acc, item) => acc + item.nf_beta_carotene, 0)
 const lycopene = data.foods.reduce((acc, item) => acc + item.nf_lycopene, 0)
 const lutein = data.foods.reduce((acc, item) => acc + item.nf_lutein, 0)
 const zeaxanthin = data.foods.reduce((acc, item) => acc + item.nf_zeaxanthin, 0)
 const flavonoids = data.foods.reduce((acc, item) => acc + item.nf_flavonoids, 0)
 const polyphenols = data.foods.reduce((acc, item) => acc + item.nf_polyphenols, 0)
 const caffeine = data.foods.reduce((acc, item) => acc + item.nf_caffeine, 0)
 const alcohol = data.foods.reduce((acc, item) => acc + item.nf_alcohol, 0)
 const gi = data.foods.reduce((acc, item) => acc + item.nf_glycemic_index, 0)
 await table.updateRecordAsync(record, {
   'Calories' : calories,
   'Protein' : protein,
   'Total Carbohydrate' : carbs,
   'Total Fat' : fat,
   'Saturated Fat' : saturatedfat,
   'Dietary Fiber' : fiber,
   'Cholesterol' : cholesterol,
   'Sodium' : sodium,
   'Potassium' : potassium,
   'Sugars' : sugars
 })
}

Goal:
My goal is to have all nutritional values written within the //NOT WORKING section of script communicate actual values from the API not NaN.

How to make alignment for label text on left AND right to have same alignment?

I work on template using html and CSS . I face issue I can’t do alignment label text on left and right to be same .

as example

submit Date and Employee id not start from same point on left so I need all text on left have same alignment .

also on right also text not start from same point as رقم الهاتف and اسم الموظف

so I need all text on right have same alignment .

full html and CSS what I try as below :

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    </head>

    <style>
.label-container {
  display: flex;
  justify-content: space-between;
}

.left-label {
  text-align: left;
}

.right-label {
  text-align: right;
}
        .form-header {
            color: black;
            background-color: gray;
            text-align: center;
            width: 50%;
            padding: 20px;
            margin: 10px auto;
        }

        .form-header h2 {
            margin: 0;
            font-weight: 500;
        }

        .form-container {
            border: 2px dashed gray;
            border-bottom: none;
            max-width: 100%;
            padding-bottom: 10px;
            margin: 0 auto;
        }

        .form-info {
            font-size: 18px;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 0px 5px;
            background-color: gray;
        }

        .employee-info {
            display: flex;
            justify-content: space-around;
        }

        .id_container {
            display: flex;
            gap: 10px;
            margin-left:10px;
           
        }

        .name_container {
            display: flex;
            gap: 10px;
           
        }

        .table-border-end {
            height: 50px;
            border-top: 2px dashed gray;
            border-bottom: 2px dashed gray;
        }

        label {
            display: block;
            font-weight: bold;
            margin-bottom: 5px;
        }

        input[type="text"] {
            width: 100%;
            padding: 5px;
            border: 1px solid #ccc;
            border-radius: 3px;
        }

        h1 {
            text-align: center;
        }

        form {
            margin-top: 20px;
        }

        label {
            display: block;
            margin-top: 10px;
            font-weight: bold;
        }

        input[type="text"],
        textarea,
        input[type="date"] {
            width: 100%;
            padding: 5px;
        }

        input[type="submit"] {
            background-color: #4caf50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-top: 20px;
        }

        input[type="submit"]:hover {
            background-color: #45a049;
        }
.line-container {
  margin-top: 30px;
}

.line {
  border: none;
  border-top: 1px solid black;
  margin: 0;
}
.solid-table {
  border-collapse: collapse;
  width: 100%;
}

.solid-table th,
.solid-table td {
  border: 1px solid black;
  padding: 8px;
  text-align: center;
}
    </style>
    <body>
        <div class="form-header">
            <h2>
                نموذج تسجيل استقاله <br />
                Resignation Submission Form
            </h2>
        </div>
        <div class="form-container">
            <div class="form-info">
                <div class="form-section">
                    <label for="emp-input">To be filled by the Employee</label>
                </div>
                <div class="form-section">
                    <p class="fill-by-employee">يتم ملئها من الموظف</p>
                </div>
            </div>

            <div class="form">
                <form>
                    <div class="employee-info" style="margin-left:10px;">
                        <div class="id_container">
                            <label for="emp-id">Emp. ID:</label>
                            <label for="emp-id">-------------------</label>

                            <label for="dept-branch">:رقم الموظف</label>
                    
                        </div>

                        <div class="name_container">
                            <label for="submission-date">Emp Name:</label>
                            <label for="submission-date">-----------------------------------</label>

                            <label for="emp-sign">:اسم الموظف</label>
               
                        </div>
                    </div>

                  <div class="employee-info" style="margin-left:30px;">
                        <div class="id_container">
                            <label for="emp-id">Dept./Branch:</label>
                            <label for="emp-id">-------------------</label>

                            <label for="dept-branch">:الفرع/لاداره</label>
                    
                        </div>

                        <div class="name_container">
                            <label for="submission-date">Designation:</label>
                            <label for="submission-date">-----------------------------------</label>

                            <label for="emp-sign">:المسمى الوظيفى</label>
               
                        </div>
                    </div>
     <div class="employee-info">
                        <div class="id_container">
                            <label for="emp-id">Submittion Date:</label>
                            <label for="emp-id">-------------------</label>

                            <label for="dept-branch">:تاريخ تقديم الاستقاله</label>
                    
                        </div>

                        <div class="name_container">
                            <label for="submission-date">Mobile No:</label>
                            <label for="submission-date">-----------------------------------</label>

                            <label for="emp-sign">:رقم الهاتف</label>
               
                        </div>
                    </div>

<div class="employee-info">
                        <div class="id_container">
                            <label for="emp-id">Last Working Date:</label>
                            <label for="emp-id">-------------------</label>

                            <label for="dept-branch">:اخر يوم عمل</label>
                    
                        </div>

                        <div class="name_container">
                            <label for="submission-date">Employee Signature:</label>
                            <label for="submission-date">-----------------------------------</label>

                            <label for="emp-sign">:توقيع الموظف</label>
               
                        </div>
                    </div>

<div class="employee-info">
                        <div class="id_container">
                            <label for="emp-id">Reason:</label>
                            <label for="emp-id">-------------------</label>

                        
                    
                        </div>

                        <div class="name_container">
                          
                          <label for="emp-id">-------------------</label>
                            <label for="emp-sign">:سبب الاستقاله</label>
               
                        </div>
                    </div>
<div class="employee-info">
                        <div class="id_container">
                       
                            <label for="emp-id">-------------------------------------------------------</label>

                        
                    
                        </div>

                        <div class="name_container">
                          
                          <label for="emp-id">-------------------------------------------------------------</label>
             
               
                        </div>
                    </div>
  <div class="form-container">
            <div class="form-info">
                <div class="form-section">
                    <label for="emp-input">Important Note : </label>
                </div>
                <div class="form-section">
                    <p class="fill-by-employee">:ملاحظه هامه</p>
                </div>
            </div>
<div class="label-container">
  <label class="left-label" style="width:45%">Employee should work 14 days, 30 Days or 90 Days’ Notice 
period as per Labor contract from the date of submission of 
resignation. If the employee fails to do so, salary for 
unserved Notice period will be deducted from the final 
settlement (as per Labor Law). Employees are not eligible 
for any leave during the Notice period.
*Ensure to complete checklist for Separation with Branch/ 
Dept./Div. Dir. on your last Day.</label>
<label style="width:5%"></label>
  <label class="right-label" style="width:45%">يجب على الموظف اعطاء الطرف الاخر فتره انذار محدده 14 يوم هو 30 يوما او 90 يوما حسب عقد العمل من تاريخ تقديم الاستقاله فى حاله عدم الالتزام بفتره الانذار المحدده يتم خصمها من مستحقات نهايه الخدمه حسب قانون العمل لايحق للموظف الحصول على اى اجازه خلال فتره الانذار يرجى التاكد من قائمه التدقيق الخاصه بنهايه الخدمه مع الفرع/مدير الاداره/ القطاع فى اخر يوم عمل لك </label>
</div>


                        
                    </div>
 <div class="form-container">
            <div class="form-info">
                <div class="form-section">
                    <label for="emp-input">Line Manager Remarks: </label>
                </div>
                <div class="form-section">
                    <p class="fill-by-employee">:ملاحظات المدير المباشر</p>
                </div>
            </div>
<div class="line-container">
  <hr class="line">
  <hr class="line" style="margin-top: 30px;">
<hr class="line">
</div>
<table class="solid-table" style="margin-top: 30px;">
  <tr>
    <th>Signature</th>
    <th style="width: 20% ;"></th>
    <th>:التوقيع </th>
    <th>Date :</th>
    <th> ----/-----/---- </th>
    <th>: التاريخ</th>
  </tr>

</table>

 <div class="form-container">
            <div class="form-info">
                <div class="form-section">
                    <label for="emp-input">Dept./ Div. Dir. or Dept. Mgr. Remarks : </label>
                </div>
                <div class="form-section">
                    <p class="fill-by-employee">:ملاحظات مدير الاداره/مدير القطاع</p>
                </div>
            </div>
<div class="line-container">
  <hr class="line">
  <hr class="line" style="margin-top: 30px;">
<hr class="line">
</div>
<table class="solid-table" style="margin-top: 30px;">
  <tr>
    <th>Signature</th>
    <th style="width: 20% ;"></th>
    <th>:التوقيع </th>
    <th>Date :</th>
    <th> ----/-----/---- </th>
    <th>: التاريخ</th>
  </tr>

</table>
 <div class="form-container">
            <div class="form-info">
                <div class="form-section">
                    <label for="emp-input"> HR & Emiratisation Director Remarks : </label>
                </div>
                <div class="form-section">
                    <p class="fill-by-employee">:ملاحظات مدير اداره الموارد البشريه والتوطين</p>
                </div>
            </div>
<div class="line-container">
  <hr class="line">
  <hr class="line" style="margin-top: 30px;">
<hr class="line">
</div>
<table class="solid-table" style="margin-top: 30px;">
  <tr>
    <th>Signature</th>
    <th style="width: 20% ;"></th>
    <th>:التوقيع </th>
    <th>Date :</th>
    <th> ----/-----/---- </th>
    <th>: التاريخ</th>
  </tr>

</table>
 <div class="form-container">
            <div class="form-info">
                <div class="form-section">
                    <label for="emp-input"> CEO Remarks(if applicable)  : </label>
                </div>
                <div class="form-section">
                    <p class="fill-by-employee">:ملاحظات الرئيس التنفيذى اذا طلب</p>
                </div>
            </div>
<div class="line-container">
  <hr class="line">
  <hr class="line" style="margin-top: 30px;">
<hr class="line">
</div>
<table class="solid-table" style="margin-top: 30px;">
  <tr>
    <th>Signature</th>
    <th style="width: 20% ;"></th>
    <th>:التوقيع </th>
    <th>Date :</th>
    <th> ----/-----/---- </th>
    <th>: التاريخ</th>
  </tr>

</table>
                </form>
            </div>
            <div class="table-border-end"></div>
        </div>

    </body>
</html>

expected result as below :

expected result

How do I host my React js application with ONNX support?

I’m a beginner in web development, and I wanted to better understand how to host a React.js application with ONNX support. I used ‘create-react-app’ to build my React.js application, which is designed to recognize campus buildings. My application works as expected on localhost. However, when I upload my React build to hosting websites like Netlify and Firebase Hosting, it results in an error.

Here is the code on how I’m loading the model:

  async function loadModel() {
    const session = await InferenceSession.create("./model.onnx", {
      executionProviders: ["webgl"],
    })
    setModelSession(session)
    console.log("Model loaded")
  }

  useEffect(() => {
    loadModel()
  }, [])
  return (
    <div className="App">
      <DisplayPage predictImage={predictImage} theme={theme} />
    </div>
  )
}

Error when loading the website:

Uncaught (in promise) TypeError: e._nodes[t] is undefined

After conducting some research, I’ve learned that placing my ONNX model in the public folder isn’t the correct approach to storing the model. Therefore, I tried moving the model to an ‘assets’ folder within the ‘src’ folder. However, it’s resulting in the same issue. I’m assuming my problem is derived from my model not loading properly because my ‘App.js’ file can’t find it. I would appreciate any help that points me in the right direction, especially materials regarding this aspect of web development. Thanks!

ScrollView – detect only when scroll being dragged

(I’m currently only interested in iOS behaviour)

I’m importing ScrollView from react-native, and would like to detect when scrolling occurs, namely it’s dragging, and finishes dragging.

 <ScrollView
    onScrollBeginDrag={() => {
      console.log('dragging');
    }}
    onScrollEndDrag={() => {
      console.log('finished');
    }}
  >

This works completely fine, except for one use case: if the user scrolls and then tap with the finger to stop the scrolling (instead of just lifting the finger), then the onScrollEndDrag will trigger but the single tapping used to stop the scrolling will actually trigger another scrolling event, meaning the onScrollBeginDrag will trigger, and immediately after, onScrollEndDrag will trigger again.

Is it possible to prevent that second chain of scroll? When the user taps to stop the scrolling, I don’t want it to count as another scrolling event.

When loading tailwindcss in Laravel project javascript not working why

Welcome
When loading tailwindcss in Laravel project javascript not working why

When loading tailwindcss in a Laravel project, JavaScript does not work, only css works. Is there a solution to this problem? Thank you.

I downloaded the tailwindcss template in laravel and everything works except javascript does not work, knowing that I followed the steps to download tailwindcss in laravel vite

TypeError: io.emit is not a function

i have declared the io in the index.js file ( main file. and i want to emit the updates to the client inside the controllers/devices.js. but on testing it is is giving

TypeError: io.emit is not a function
    at handleUpdateDevice (/home/parthkamal/Documents/development/tekuncorked-server/controllers/device.js:84:12)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
(node:98489) Warning: Accessing non-existent property 'emit' of module exports inside circular dependency
(Use `node --trace-warnings ...` to show where the warning was created)
node:internal/errors:496
    ErrorCaptureStackTrace(err);
    ^

controllers/devices.js

const Device = require('../models/device');
const io = require('../index');

// other functions

const handlePostDevice = async (request, response) => {



    try {

        const { name, location, temperature } = request.body;

        console.log(request.body);


        console.log({ name, location, temperature });
        const newDevice = new Device({ name, location, temperature });

        await newDevice.save();

        response.status(200).json({ message: "device added successfully" });
        const devices = await Device.find();
        io.emit('data-created', { devices });

    } catch (error) {

        console.log(error);
        response.status(400).json({ error });
    }

}

const handleUpdateDevice = async (request, response) => {

    try {

        const { id } = request.params;
        const updates = request.body;
        console.log(updates);
        await Device.findByIdAndUpdate(id, updates);
        response.status(200).json({ message: "updated successfully" }); 

        const devices = await getDevices();
        io.emit('data-updated', { devices });

    } catch (error) {


        console.log(error);
        response.status(400).json({ error });
    }

}



module.exports = {
    getDevices,
    handleGetDevices,
    handleGetDevicesById,
    handlePostDevice, 
    handleUpdateDevice 
}


my directory structure is like thisenter image description here

index.js

const express = require('express');
const http = require('http');
const cors = require('cors');
const dotenv = require('dotenv');
const { getDevices } = require('./controllers/device')
const createDbConnection = require('./db');
const socketIo = require('socket.io');

const app = express();
const server = http.createServer(app);

const io = socketIo(server, {
  cors: {
    origin: "http://localhost:3000",
  }
});

dotenv.config();
const PORT = process.env.PORT;

const corsOptions = {
  origin: 'http://localhost:3000',
};


//middlewares
app.use(cors(corsOptions));
app.use(express.json());


//routes
const deviceRoute = require('./routes/device');
app.use('/device', deviceRoute);

io.on('connection', async (socket) => {
  console.log(`user with socket id ${socket.id} is connected`);

  try {
    const devices = await getDevices();
    socket.emit('data', { devices });

  } catch (error) {
    console.log('connection ke dauran devices fetch karne me error agya');
  }




  socket.on('disconnect', () => {
    console.log('a user got disconnected');
  });
});

//db connection
createDbConnection();

app.get('/', (req, res) => {
  res.send('hello from the tekuncorked server');
});

server.listen(PORT, () => {
  console.log(`server is listening on port ${PORT}`);
});

module.exports = io;

i think there is a problem in exporting the io module. to the controller. how can I achieve that?

DJANGO HTML Elements and Javascript

I’m trying to implement a “hover image” effect on a website drive by Django. Each model in my database contains 2 distinct images. I’d like to have the image change when the user hovers over the “default image” and have it change to the “hover image”. What’s happening instead is only the first image is changing to the hover image. If the user hovers over any other image on the page, the first image at the top of the page is the one that changes.

Here’s my HTML

{% for element in records %}
  <div class = "model">
   <img src="{{element.default_image}}" onmouseover="hoverImage();" onmouseout="defaultImage();" width="120"></div>

Here’s my JS

const imgElements = document.querySelectorAll('.model');
 
for (let i = 0; i < imgElements.length; i++) {                                   
     const currentElement = imgElements[i]; 
     function hoverImage() {
         currentElement.src = '{{element.hover_image}}';
      }
            
      function defaultImage() {
         currentElement.src = '{{element.default_image}}';
                   
       }
   }

This only changes the first element in the model no matter what image the user hovers over

How can I change the html of the popup from the content script of a Chrome extension?

I’m trying to build a Chrome extension. However, I’m running into a problem. To reload the UI of the popup when a webpage is loaded. I wanted to realize this by adding a listener to popup.js and sending a message from content.js. The problem is that the message is sent but not received. Can someone help me?

popup.js:

chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {
  document.body.innerHTML = "";
  if (request.text == "reloadSiteTab") {
    reloadSiteTab(request.url);
  }
});

content.js:

chrome.runtime.sendMessage(
    {
        "text": "reloadSiteTab",
        "url": location.href
    }
);

JS library recommendations for drag/resize/cut/copy/paste/align/group/etc WYSIWYG editor

I have been tasked to build a web interface that allows the user to drag, resize, cut/copy/paste, align, group, etc standard HTML elements including all FORM inputs (text, checkbox, radio, etc), and others (IMG, DIV, SPAN, etc) as well as custom HTML elements. The solution needs to provide all of the following:

  • Handles around items when seletect
  • Drag items around within a container
  • Resize items by dragging handles for all 8 directions
  • Lock resizing/dragging to horizontal or vertical by setting a flag or
    pressing a modifier key
  • Provide snap-to-grid functionality including always-on and modifier key enabled
  • Select multiple items and groups by holding a modifier key and/or
    dragging a lasso around the desired items
  • Group and ungroup items (and recursively, other groups)
  • Resize and move a group of items by dragging the group handles
  • Move items up and down the Z index
  • Align items to each other (center/left/right/middle/top/bottom) and
    align to grid
  • Cut/copy/paste items and groups onto the container and into other
    groups
  • Edit a group’s items by opening the group
  • Attach hotkeys to common actions (copy/cut/paste/align/z-index…)
  • Optional: rotate items and groups

See PowerPoint for an example of the desired functionality in moving/resizing/selecting elements.

First, I’m not sure what this functionality is called, as a group, other than “full WYSIWYG editor” so it’s nontrivial to search for libraries that provide all of it.

I have found partial solutions like interact.js and jQuery UI but they don’t offer the full functionality and require heavy modification.

To clarify, I am not looking for WYSIWYG editors like editor.js, quill, etc.

I am prepared to write this myself, but wanted to avoid reinventing the wheel if there is another library that already solves all (or most) of it.

Thank you for any advice.

Does Webpack expose information about the machine that used it?

I want to start using webpack, however I’m just a little paranoid because on some sites I can open chrome devtools and literally view the typescript source files of different bundled modules.

Also, the bundle that webpack produces is minified and hard to read, so does it expose any information about my computer? Such as OS, username, build path, etc. And does it expose the real source code?

Thanks.

Why the function areaRettangolo return Nan?

Why doesn’t the function areaRettangolo return a number?
I want to calculate the area of a rectangle using a function called areaRettangolo but it returns Nan

let base = document.getElementById('base');
let altezza = document.getElementById('altezza');
let bottone = document.querySelector('button');
let testo = document.querySelector('h1');
let area = 0;

function areaRettangolo(a, b) {
  let c = 0;
  c = a * b;
  return c;
}
bottone.addEventListener('click', () => {
  area = areaRettangolo(base, altezza);
  console.log(area);
});
<input type="number" id="base" placeholder="inserisci la base del rettangolo"><br><br>
<input type="number" id="altezza" placeholder="inserisci l'altezza del rettangolo"><br><br>
<button>Calcola l'area del rettangolo</button>
<h1>-</h1>