Pass a variable from HTML Page to Form-Modal

I am trying to pass a variable from a table to Form-Modal, hence need a little guidance on snippet. Please refer to the HTLML section.
I need to pass {{rec.sys_id}} into a method as a parameter, which is inside this form-modal:

"myController.displayUserRecord(<rec.sys_id>)"

Please let me know about the approach.
Thank you.

<table>
    <tr ng-repeat="rec in myController.userRecord">
     <td><a ng-href="" target="" data-toggle="modal" data-target="#formUserRecord">Click Here</a></td>
     <td>{{rec.sys_id}}</td>
    </tr>
 </table>


 <div  class="modal fade" id="formUserRecord" tabindex="-1" role="dialog">
    <p>Check your Workday Record:</p>
    <button type="button" ng-click="myController.displayUserRecord(<rec.sys_id>)">Click here </button>
</div>

Node Stream API, pull function equivalent

I have earlier used the “Web Stream” API in order to continuously read items from a REST service and enqueue them in the stream according to something like this:

stream = new ReadableStream({
   start: controller => {
      //do some initialization
   },
   pull: controller => {
      fetch('http://restservice/to/fetch/items')
      .then(response => response.json())
      .then(item => controller.enqueue(item));
   }
}) 

Whenever I read from this stream with

stream.getReader().read().then(item => {
  console.log(item);
});

the pull function automatically fetches the next item and enqueues it.

I now need to use the same pattern for Node’s native “Stream” API, but I cant figure out how to implement it. There is no “pull” equivalent it seems. How do I keep pushing new items automatically onto the stream whenever I read from it?

How to trigger on change event on multi select using Vue js

this is my html multi select input:

<select id="invitees_list1" class="form-select" multiple name="multi">
    @foreach ($seatedTable->invitees as $invitee)
         <option>
            {{ $invitee['name'] }}
           </option>
       @endforeach

  </select>

and the vue js code:

<script src="{{ URL::asset('assets/admin/app-assets/js/scripts/vue2.min.js') }}"></script>
     <script>
         const app = new Vue({
             el: '#filtersContainer',
             data: {
                 invitees: [],
                 selectedInviteeIds: [],
                 inviteesList: [],
                 selectedTableInfo: null,
                 eventTables: [],
                 newTableName: "",
                 totalChairNumberEntered: 0,
                 confirmedInviteesRoute: "{{ route('invitee_tables.confirmed_invitees', $event) }}",
                 selectedInviteesRoute: "{{ route('invitee_tables.assignModalData', $event) }}",
                 assignTableRoute: "{{ route('invitee_tables.assign', $event) }}",
                 isDisabled: false
             },
             created() {
                 axios.get(this.confirmedInviteesRoute)
                     .then(({
                         data
                     }) => {
                         if (data?.status) {
                             this.invitees = data?.data || []
                         }
                     })
                     .catch((err) => console.log(err))
             },
             mounted() {
                 $("#name_filter").select2()
                 $('#side_filter').select2()
                 $('#caller_filter').select2()
                 $('#relation_filter').select2()
                 $('#invitees_list').select2()
                 $('#invitees_list1').select2()

                 $('#invitees_list1').show()

                 $("#invitees_list").show()

             },

I want to when ever the multi select changed ,i want to get the value of the multi select input and trigger an event.
I’ve tried javascript event but nothing happened .

Java timeout page function with fade animation

I’ve used this code from Sunny SM it works perfectly but is there a way a fade in can be added to the script please anyone?
The code works perfectly but ideally I want a fade transition in the code when it times out to go to the specified URL

<script type="text/javascript">
(function(){
   setTimeout(function(){
     window.location="http://brightwaay.com/";
   },3000); /* 1000 = 1 second*/
})();
</script>

Tampermonkey script update logic

I’m developing a userscript that runs continuously on a remote machine and needs to be up to date.

However, when the script auto-updates, it needs to reload the page to apply the update, so my script is also trying to predict when the update will happen, so that it can refresh the page afterwards.

This has proven to be difficult though: even though I set the period to the minimum of six hours, the script usually updates seven or more hours after it was last updated.

So how does the logic for uodates work? Is there a hook or a callback that I can use to reload the page after the update, in order to apply it? Or do you have some other tip for predicting the time the script will update more precisely?

Here’s the logic I currently use to do this:

function monitorScriptUpdates() {
    informUserIfScriptUpdated();
    var updateTimerSet = false;

    var timer = setInterval(() => {
        if (updateTimerSet) {
            clearInterval(timer);
        } else {
            checkForUpdates();
        }
    }, 60000);

    function checkForUpdates() {
        getNewestScriptVersion().then((newestVersion) => {
            const actualScriptVersion = GM_info.script.version;

            if (actualScriptVersion >= newestVersion) {
                return;
            }

            const currentTimeInMs = Date.now();
            const scriptLastUpdatedMs = GM_info.script.lastModified;
            const msSinceTheLastUpdate = currentTimeInMs - scriptLastUpdatedMs;
            const sixHoursInMs = 21600000;
            const fiftyMinutesBuffer = 3000000;

            updateTimerSet = true;
            if (localStorage.getItem('updateAttempted')) {
                localStorage.removeItem('updateAttempted');
                console.log('Automatic update failed, possibly because the update period is set to more than 6 hours! Disabling update check.');
                return;
            }

            const timeUntilUpdateIsAvailable = (sixHoursInMs - (msSinceTheLastUpdate % sixHoursInMs)) + fiftyMinutesBuffer;
            console.log('New script version detected! Automatic update will be attempted on ' + new Date(Date.now() + timeUntilUpdateIsAvailable));
            setTimeout(() => {
                console.log('Update should be available if the update period is set to 6 hours. Reloading...');
                localStorage.setItem('updateAttempted', true);
                location.reload();
            }, timeUntilUpdateIsAvailable);
        });
    }

    function informUserIfScriptUpdated() {
        var lastRecordedVersion = localStorage.getItem('scriptVersion');
        var actualScriptVersion = GM_info.script.version;

        if (lastRecordedVersion && lastRecordedVersion != actualScriptVersion) {
            localStorage.removeItem('updateAttempted');
            console.log('Script updated successfully from version ' + lastRecordedVersion + ' to version ' + actualScriptVersion);
        }

        localStorage.setItem('scriptVersion', actualScriptVersion);
    }
}

Thanks,
Dusan

Template rendering in backbone view

I am using backbone as a front end in rails 7 application. In view file I am not able to load template as a path.

rails view file code is

- content_for :javascript do
  - javascript_include_tag 'backbone/views/test/test_view'
#estimate-repair
%script{type: 'text/template', id: 'temp-fview'}
  .container

backbone view file code is
backbone/views/test/test_view

var FirstView = Backbone.View.extend({
  el: '#estimate-repair',
  template:_.template($("#temp-fview").html()),

  initialize: function(options){
    options = options || {}
    this.render()
  },
  
  render: function(){
    this.$el.html(this.template());
  }
});

If I use this way to render template code then it is working. It will replace #estimate-repair with code written in script. But I want to use separate template file inside of backbone folder.

backbone/templates/test/test.jst.hamljs

.container
    .modal.fade#cutomer-confirmation{style: "height:150px;"}

and want to call this template from view file.

template: JST['backbone/templates/maintenances/estimate_repair/estimate_repair'],

but this showing me error in console.
Uncaught ReferenceError: JST is not defined

I have got one error on the Cpannelafter hosting the node server Does any one can help to solve this error?

After hosting the next js app and the node js with express backend I got one error

The received data is wrong. Contact support for resolution. Traceback (most recent call last): File “/usr/share/l.v.e-manager/utils/cloudlinux-cli-user.py”, line 16, in cloudlinux_cli.main() File “/usr/share/l.v.e-manager/utils/libcloudlinux.py”, line 159, in main self.check_license() File “/usr/share/l.v.e-manager/utils/libcloudlinux.py”, line 370, in check_license if not self.licence.get_license_status(): ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File “/opt/cloudlinux/venv/lib64/python3.11/site-packages/cllicense/license_lib.py”, line 27, in get_license_status p = subprocess.Popen( ^^^^^^^^^^^^^^^^^ File “/opt/alt/python311/lib64/python3.11/subprocess.py”, line 1026, in _init_ self._execute_child(args, executable, preexec_fn, close_fds, File “/opt/alt/python311/lib64/python3.11/subprocess.py”, line 1883, in _execute_child self.pid = _fork_exec( ^^^^^^^^^^^BlockingIOError: [Errno 11] Resource temporarily unavailable

But hosting is working what do now?

I simply make one Folder on the cpannel FileManager and add myapp folder/File and At the first time when I hosted myapp it work but when I am trying it on second time At the node js server there is showing error but myapplication is running very smoothly.

CORS – Calling a REST Service on an other domain only works if I set CORS only within the REST service [duplicate]

This does not make sense to me.
I have an website that uses javascript to call a REST Service.
I got CORS errors so I added CORS settings to that REST Service to allow requests from my website domain.
The calls are now working but it got me thinking.

As far as I know the website does not have any CORS settings.
So if I create a service called “DoSomeVeryBadStuff” and set the CORS settings in that service to allow request from everywhere.
And then I successfully inject a script on the website that calls that service. The call will succeed just like the call to my normal service.

And this does not make sense to me. Isn’t this scenario exactly what CORS should be preventing? Do I miss some CORS setting on the website maybe? How can I check that beside checking the headers?

only one of the two sessions appear in the dev tools application and the Db instead of both at the same time?

the code is fully functional except the clearcookie after logout method which works only if delete the routing of one of the session / login files, i use unique secret keys and stores , i also tried the suggestions of bard and chatgpt but to no avail .

here is the server.js code :

const express = require("express");
const mongoose = require('mongoose');
const sessionRouter = require('./session.js');
const loginRouter = require('./login.js')
const app = express();

mongoose.connect("mongodb://127.0.0.1:27017/sessions")
.then((res) => {
 console.log("MongoDB Connected");
});

app.set("view engine", "ejs");
app.use(express.urlencoded({ extended: true }));
app.use('/login', loginRouter );
app.use('/', sessionRouter);
app.listen(4200, console.log("Server running on http://localhost:4200/"));

here is the session.js file :

const express = require("express");
const bcrypt = require("bcryptjs");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const MongoDBSession = require("connect-mongodb-session")(session);
const router = express.Router();
const UserModel = require("./src/app/shared/models/User.ts");
const mongoURI = "mongodb://127.0.0.1:27017/sessions" ;

const sessionstore = new MongoDBSession({
    uri : mongoURI,
    collection : "mySessions",
    });
        
    router.use(
        cookieParser('key that will sign cookie'),     
        session({
            secret: 'key that will sign cookie',  
            name: 'SessionCookie',          
            resave: false,
            saveUninitialized: false,
            store: sessionstore,
            cookie: {
                
                maxAge: 1000 * 60 * 60, 
            },
        })
    );

const isAuth = (req,res,next) => {
    if (req.session.isAuth){
        next()
     } else {
       res.redirect("landing");
     }
    }
    
    router.get("/",(req,res) => { 
        if (!req.session.sessionStartTime) {
            req.session.sessionStartTime = new Date();
        }
        res.render("landing");
        
       });
    
    router.get("/login",(req,res) => {
        res.render("login");
       });
    
    router.post("/login", async (req,res) => {
        const{ email, password} = req.body ;
        let user = await UserModel.findOne({ email });
        if(!user){
        return res.redirect("/login");
        }
       const isMatch = await bcrypt.compare(password, user.password);
       
       if(!isMatch){
        return res.redirect("/login")
       } ; 
       req.session.isAuth = true;
       req.session.username = user.username;
       req.session.loginTime = new Date();

    res.redirect("/dashboard");
     });
    
     router.get("/register",(req,res) => {
       res.render("register");
       });
    
       router.post("/register", async (req,res) => {
        
        const { username,email,password} = req.body;
        let user = await UserModel.findOne({ email });
       
        if(user){
            return res.redirect('/register');
        }
        const hashedPsw = await bcrypt.hash(password, 12) ;
    
        user = new UserModel({
          username,
          email ,
          password: hashedPsw
         });
    
       await user.save();
       res.redirect("/login");
    });
    
    router.get("/dashboard", isAuth , (req,res) => {
        res.render("dashboard")
    });
    
    router.post("/logout",(req,res) => {
        res.clearCookie("SessionCookie");
        req.session.endSessionTime= new Date(),
        req.session.logoutTime= new Date(),
       
     res.redirect("/") ; 
       
    });

module.exports = router;

here is the login file

const express = require("express");
const bcrypt = require("bcryptjs");
const session = require("express-session");
const cookieParser = require("cookie-parser");
const MongoDBSession = require("connect-mongodb-session")(session);
const router = express.Router();
const UserModel = require("./src/app/shared/models/User.ts");
const mongoURI = "mongodb://127.0.0.1:27017/sessions" ;

const loginstore = new MongoDBSession({
    uri : mongoURI,
    collection : "myLogins",
    });

        
    router.use(cookieParser('key to sign cookie'));

    router.use(session({
      secret: 'key to sign cookie',
      name: "LoginCookie",
      resave: false,
      saveUninitialized: false,
      store: loginstore,
      cookie: {
        maxAge: 1000 * 60 * 60 * 24 * 30,
      },
    }));
    
   
const isAuth = (req,res,next) => {
    if (req.session.isAuth){
        next()
     } else {
       res.redirect("landing");
     }
    }
    
    router.get("/",(req,res) => { 
        res.render("landing");
       });
    
    router.get("/login",(req,res) => {
        res.render("login");
    
       });
    
    router.post("/login", async (req,res) => {
        const{ email, password} = req.body ;
        let user = await UserModel.findOne({ email });
        if(!user){
        return res.redirect("/login");
        }
       const isMatch = await bcrypt.compare(password, user.password);
       
       if(!isMatch){
        return res.redirect("/login")
       }
        req.session.isAuth = true;
        req.session.username = user.username; 
        req.session.loginTime = new Date();
        res.redirect("/dashboard");
     });
    
     router.get("/register",(req,res) => {
       res.render("register");
       });
    
       router.post("/register", async (req,res) => {
        
        const { username,email,password} = req.body;
        let user = await UserModel.findOne({ email });
       
        if(user){
            return res.redirect('/register');
        }
        const hashedPsw = await bcrypt.hash(password, 12) ;
    
        user = new UserModel({
          username,
          email ,
          password: hashedPsw
         });
    
       await user.save();
       res.redirect("/login");
    });
    
    router.get("/dashboard", isAuth , (req,res) => {
        res.render("dashboard")
    });
    
    router.post("/logout",(req,res) => {
        res.clearCookie("LoginCookie");
        req.session.logoutTime = new Date();  
        res.redirect("/") ; 
       
    });

module.exports = router;

Issues with markers on Google Maps API – not always loading

I’m working on a website with Google Maps API, particularly with @ubilabs/google-maps-react-hooks.
I’m not very experienced so I’m having some difficulties understanding why there’s an issue.
When I load the website (either locally or online) the markers don’t always show up. It could be on loading the site at first or when I refresh, they disappear and reapper upon new refreshing of the page. This never happens if I have my developer tools open (docked or undocked) and I can’t figure out why! I’ve been trying for days.

index.txs

import { GoogleMapsProvider } from '@ubilabs/google-maps-react-hooks';
import React, { useState, useEffect, useCallback} from 'react';
import { useGeoReportState } from '../../context/GeoReportContext';
import { useMapContext, useMapDispatch } from '../../context/MapContext';
import { options } from './MapElements';
import TestMap from './TestMap';

const Index = () => {
    const [mapContainer, setMapContainer] = useState<HTMLDivElement | null>(null);

    const mapDispatch = useMapDispatch();
    const mapState = useMapContext();
    const reportState = useGeoReportState();
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const onLoad = useCallback((map: any) => {
        mapDispatch.setMap(map);
        google.maps.event.trigger(map, 'resize');
    }, [reportState]);
    return (
        <>
        <div className='flex flex-col w-full h-full'>
            <GoogleMapsProvider
                mapOptions={options(mapState)}
                googleMapsAPIKey={process.env.REACT_APP_API_KEY as string}
                mapContainer={mapContainer}
                version='beta'
                onLoadMap={onLoad}
                libraries={['places']}
            >
                <TestMap />
                <div ref={(node) => setMapContainer(node)} style={{ height: '100vh' }} />
            </GoogleMapsProvider>
        </div> 


    </>
    );
};

export default Index;

TestMap.tsx

import React, { useState, useEffect, SetStateAction } from 'react';
import { useGeoReportState } from '../../context/GeoReportContext';
import { useMapContext } from '../../context/MapContext';
import { findMode, formSubmitGeoCoder, getSoilTypeColor } from '../../utils/Util';
import Navbar from '../Navbar';
import { notificationHandler, surveyLengthHandler } from '../../utils/ContextHandlers';
import { MarkerClusterer, SuperClusterAlgorithm } from '@googlemaps/markerclusterer';
import Icon from '../../img/point.png';
import FileSubmit from '../Form/FileSubmit';
import Form from '../Form/Form';
import ThankYou from '../Form/ThankYou';
import { IconContext } from 'react-icons';
import { AiOutlineLeft, AiOutlineRight, AiOutlineReload } from 'react-icons/ai';
import { GeoReport, Survey } from '../../types/GeoReportTypes';
import { SurveyData } from '../../types/SurveyTypes';
import { useNotificationDispatch } from '../../context/NotificationContext';
import { useSurveyDispatch } from '../../context/SurveyContext';
import PointData from '../Form/PointData';
import { useGoogleMap } from '@ubilabs/google-maps-react-hooks';

const TestMap: React.FC = () => {

    const geoReportState = useGeoReportState();
    const notificationDispatch = useNotificationDispatch();
    const mapState = useMapContext();
    const surveyDispatch = useSurveyDispatch();
    const map = useGoogleMap();

    let formData = {};

    const [showFileSubmit, setShowFileSubmit] = useState(false);
    const [showSliderForms, showSlider] = useState(false);
    const [showThankYouForms, setShowThankYou] = useState(false);
    const [surveys, setSurveys] = useState<Survey[]>([]);
    const [email, setEmail] = useState<string>();
    const [thisMarkers, setThisMarkers] = useState<google.maps.Marker[]>([]);
    const [circles, setCircles] = useState<google.maps.Circle[]>([]);
    const [pointDataArray, setPointDataArray] = useState<GeoReport | null>(null);
    const [distanceBetween, setDistanceBetween] = useState<number | null>(null);
    const [surveyNumber, setSurveyNumber] = useState(surveys.length + 1);
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const [selectedImage, setSelectedImage] =useState<string>();

    const incrementCount = () => {
        setSurveyNumber(surveyNumber + 1);
    };

    const resetCount = () => {
        setSurveyNumber(1);
    };

    useEffect(() => {
        if (!map) return;
        if (thisMarkers.length == 0) {
            Object.entries(geoReportState.map).map(([, reports]) => {
                addMarkers(undefined, reports, thisMarkers, setThisMarkers, setPointDataArray);
                addCircles(undefined, setPointDataArray, reports, circles, setCircles);
            });
        }
        thisMarkers.forEach(marker => {
            marker.setMap(map);
        });
    }, [mapState]);

    useEffect(() => {
        if (!map) return;

        map.addListener('zoom_changed', () => {
            if (map.getZoom()! >= 11) {
                thisMarkers.forEach(marker => {
                    marker.setMap(null);
                });
                circles.forEach(circle => {
                    circle.setMap(map);
                });
            }
            if (map.getZoom()! < 11) {
                thisMarkers.forEach(marker => {
                    marker.setMap(map);
                });
                circles.forEach(circle => {
                    circle.setMap(null);
                });
            }
        });

    }, [map?.getZoom()]);

    thisMarkers.forEach(marker => {
        marker.addListener('click', () => {
            if (showSliderForms === true) {
                showSlider(false);
            }
        });
    });

    const handleOpenSlider = () => {
        showSlider(!showSliderForms);
        if (pointDataArray) {
            handleClosePointData();
        }
    };

    const handleOpenFileSubmit = () => {
        if (surveys.length === 0) {
            notificationHandler(2, 'Por favor introduza valores válidos', notificationDispatch);
        } else {
            setShowFileSubmit(!showFileSubmit);
        };
    };

    const handleOpenThankYou = () => {
        setShowThankYou(!showThankYouForms);
    };

    const handleClosePointData = () => {
        setPointDataArray(null);
        setDistanceBetween(null);
    };

    const handleSubmitNew = () => {
        setShowThankYou(!showThankYouForms);
        setShowFileSubmit(!showFileSubmit);
        setSurveys([]);
        resetCount();
        setSelectedFile(null);
        setSelectedImage('');
    };

    const handleExit = () => {
        setShowThankYou(!showThankYouForms);
        setShowFileSubmit(!showFileSubmit);
        showSlider(!showSliderForms);
        setSurveys([]);
        resetCount();
        setSelectedFile(null);
        setSelectedImage('');
    };

    const handleAddSurvey = (event: { preventDefault: () => void; }, lat: number, lng: number, nFreatico: boolean, inFreatico: number, nSPT: boolean, table: SurveyData[]) => {
        event.preventDefault();
        if (lat === 0 || lng === 0 || lat === undefined || lng === undefined || table.length === 0 || (nFreatico === true && (inFreatico === undefined || inFreatico === 0))) {
            notificationHandler(2, 'Por favor introduza valores válidos', notificationDispatch);
        } else {
            if(nSPT) {
                table.map(e => e.spt1 = 1000);
            }
            if (nFreatico === true) {
                const dummy = {
                    lat: lat,
                    lng: lng,
                    nFreatico: nFreatico,
                    inFreatico: inFreatico,
                    table: table,
                };
                surveys.push(dummy);
            } else {
                const dummy = {
                    lat: lat,
                    lng: lng,
                    nFreatico: nFreatico,
                    inFreatico: 0,
                    table: table,
                };
                surveys.push(dummy);
            };
            setSurveys([...surveys]);
            incrementCount();
            notificationHandler(1, 'Sondagem submetida com sucesso', notificationDispatch);
            surveyLengthHandler(surveys.length, surveyDispatch);
        }
    };

    const handleClearSurveys = (event: { preventDefault: () => void; }) => {
        event.preventDefault();
        setSurveys([]);
        resetCount();
    };

    const handleFileInput = (e: any, type: number) => {
        e.preventDefault();
        const file = e.target.files[0];
        if (type === 1) {
            if (file) {
                if (file.type === 'application/pdf') {
                    setSelectedFile(file);
                } else {
                    notificationHandler(
                        2,
                        'Por favor seleciona um ficheiro tipo PDF',
                        notificationDispatch,
                    );
                }
            }
        } else if (selectedImage) {
            setSelectedImage(file);
        } 
        // else {
        //  notificationHandler(
        //      2,
        //      'Por favor seleciona uma imagem do tipo PNG ou JPEG',
        //      notificationDispatch
        //  );
        //}
    };

    const handleUploadPDF = (e: any, filename: string) => {
        e.preventDefault();
        if (selectedFile) {
            const formPDFData = new FormData();
            formPDFData.append('filename', filename);
            formPDFData.append('file', selectedFile);
            fetch(process.env.REACT_APP_BACKEND + '/api/drive', {
                method: 'POST',
                body: formPDFData
            });
                //.then((response) => (console.log(response)))
                //.catch((error) => console.log(error));
        }
    };

    const handleUploadImage = (e: any, filename: string) => {
        e.preventDefault();
        if (selectedImage) {
            const formImgData = new FormData();
    //      formImgData.append('filename', filename);
            formImgData.append('image', selectedImage);
    //      fetch(process.env.REACT_APP_BACKEND + '/api/drive/image', {
    //          method: 'POST',
    //          body: formImgData,
    //      })
    //          .then((response) => console.log(response))
    //          .catch((error) => console.log(error));
        }
    };

    const handleSubmitForm = async (e: { preventDefault: () => void; }) => {
        e.preventDefault();

        if (!surveys[0]) {
            notificationHandler(
                2,
                'Não é possível submeter sem qualquer sondagem',
                notificationDispatch
            );
        }

        const lat = surveys[0].lat;
        const lng = surveys[surveys.length - 1].lng;

        const { adress, placeId } = await formSubmitGeoCoder(Number(lat), Number(lng), notificationDispatch);

        if(email) {
            if (selectedFile) {
                const fileName = selectedFile.name;
                const editedName = fileName.substring(0, fileName.length - 4);
                if (selectedImage) {
                //    const oldImgName = selectedImage.name;
                //    const imgExtension = oldImgName.substring(oldImgName.length - 4, oldImgName.length);
                //    const imgName = `logo_${editedName}${imgExtension}`;
                    formData = { adress, placeId, lat, lng, email, surveys, fileName, selectedImage };
                } else {
                    formData = { adress, placeId, lat, lng, email, surveys, fileName };
                }
                const requestOptions = {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                };
                const response = await fetch(process.env.REACT_APP_BACKEND + '/api/report', requestOptions);
                if (response.ok) {
                    handleOpenThankYou();
                    setSurveys([]);
                    resetCount();
                    handleUploadPDF(e, selectedFile.name);
                    if (selectedImage) {
                    //    const oldImgName = selectedImage.name;
                    //    const imgExtension = oldImgName.substring(oldImgName.length - 4, oldImgName.length);
                    //    const imgName = `logo_${editedName}${imgExtension}`;
                       handleUploadImage(e, selectedImage);
                    };
                }
                if (!response.ok) {
                    notificationHandler(
                        2,
                        'Erro',
                        notificationDispatch
                    );
                }

            } else {
                notificationHandler(
                    2,
                    'Para validação do relatório iremos necessitar do mesmo em formato PDF',
                    notificationDispatch
                );
            }
        } else {
            notificationHandler(
                2,
                'Insira um e-mail para poder submeter os dados',
                notificationDispatch
            ); 
        }
    };

    return (
        <>
            <div className='flex flex-col w-full h-full'>
                <Navbar setPointDataArray={setPointDataArray} setDistanceBetween={setDistanceBetween} />
                {showSliderForms ? (
                    <>
                        <div className='z-30'>
                            <div className='bg-white sm:absolute sm:right-0 h-auto max-h-full sm:h-full sm:w-[40%] overflow-y-scroll'>
                                {showThankYouForms ? (
                                    <>
                                        <ThankYou />
                                        <div className='justify-center mb-5 items-center flex space-x-2'>
                                            <button
                                                className='bg-blue-helica w-40 h-10 rounded-md text-xs text-white p-1'
                                                onClick={handleSubmitNew}
                                            >
                                                Submeter novo estudo
                                            </button>
                                            <button
                                                className='bg-blue-helica w-40 h-10 rounded-md text-xs text-white p-1'
                                                onClick={handleExit}
                                            >
                                                Sair
                                            </button>
                                        </div>
                                    </>
                                ) : (
                                    <>
                                        <button
                                            type='button'
                                            className='bg-white border ml-4 mt-4'
                                            onClick={handleOpenSlider}
                                        >
                                            <IconContext.Provider
                                                value={{
                                                    color: '#000000',
                                                    className: 'h-6 sm:h-9 w-6 sm:w-9',
                                                }}
                                            >
                                                <AiOutlineRight />
                                            </IconContext.Provider>
                                        </button>
                                        <form className='h-auto'>
                                            {showFileSubmit ? (
                                                <>
                                                    <FileSubmit setEmail={setEmail} surveys={surveys} handleFileInput={handleFileInput} selectedFile={selectedFile} selectedImage={setSelectedImage} />
                                                    <div className='justify-center mb-5 items-center flex space-x-2'>
                                                        <button
                                                            className='bg-blue-helica w-40 h-10 rounded-md text-xs text-white p-1'
                                                            onClick={() => {
                                                                handleOpenFileSubmit();
                                                            }}
                                                        >
                                                            Passo Anterior
                                                        </button>
                                                        <button
                                                            className='bg-blue-helica w-40 h-10 rounded-md text-xs text-white p-1'
                                                            onClick={(event) => {
                                                                handleSubmitForm(event);
                                                            }}
                                                        >
                                                            Enviar
                                                        </button>
                                                    </div>
                                                </>
                                            ) : (
                                                <>
                                                    <Form handleOpenFileSubmit={handleOpenFileSubmit} handleAddSurvey={handleAddSurvey} handleClearSurveys={handleClearSurveys} surveyNumber={surveyNumber} />
                                                </>
                                            )}
                                        </form>
                                    </>
                                )}
                            </div>
                        </div>
                    </>
                ) : (
                    <>
                        {pointDataArray ? (
                            <>
                                <div className='z-30'>
                                    <div className='bg-transparent right-[35%] absolute top-auto mt-3 h-auto max-h-full w-auto'>
                                        <button
                                            type='button'
                                            className='bg-white border'
                                            onClick={handleOpenSlider}
                                        >
                                            <IconContext.Provider
                                                value={{
                                                    color: '#000000',
                                                    className: 'h-6 sm:h-9 w-6 sm:w-9',
                                                }}
                                            >
                                                <AiOutlineLeft />
                                            </IconContext.Provider>
                                        </button>
                                    </div>
                                </div>
                            </>
                        ) : (
                            <>
                                <div className='z-30'>
                                    <div className='bg-transparent absolute right-4 top-auto mt-3 mr-12 h-auto max-h-full w-auto'>
                                        <button
                                            type='button'
                                            className='bg-white border mr-2 align-top'
                                            title='Recarregar pontos de sondagem'
                                        >
                                            <IconContext.Provider
                                            value={{
                                            color: '#000000',
                                            className: 'h-8 sm:h-10 w-8 sm:w-10',
                                        }}
                                    >
                                        <AiOutlineReload />
                                    </IconContext.Provider>
                                        </button>
                                        <button
                                            type='button'
                                            className='bg-white border'
                                            onClick={handleOpenSlider}
                                        >
                                            <IconContext.Provider
                                                value={{
                                                    color: '#000000',
                                                    className: 'h-12 sm:h-14 w-12 sm:w-14',
                                                }}
                                            >
                                                <AiOutlineLeft />
                                            </IconContext.Provider>
                                        </button>
                                    </div>
                                </div>
                            </>
                        )}
                    </>
                )}
                {pointDataArray ? (
                    <>
                        <div className='z-30'>
                            <div className='bg-white absolute sm:right-0 h-auto max-h-full sm:h-full sm:w-1/3 overflow-y-scroll'>
                                <PointData pointDataArray={pointDataArray} distance={distanceBetween} handleClosePointData={handleClosePointData} map={map} />
                            </div>
                        </div>
                    </>
                ) : (null)}
            </div>
        </>
    );
};

function addMarkers(
    map: google.maps.Map | undefined,
    reports: GeoReport[],
    thisMarkers: google.maps.Marker[],
    setThisMarkers: React.Dispatch<React.SetStateAction<google.maps.Marker[]>>,
    setPointDataArray: React.Dispatch<React.SetStateAction<GeoReport | null>>,
) {

    let isVisited = false;

    const markers = reports.map((report: GeoReport) => {

        const marker = new google.maps.Marker({
            position: { lat: report.lat, lng: report.lng },
            map: map,
            icon: Icon,
        });

        marker.addListener('click', () => {
            isVisited = !isVisited;
            if (isVisited === true) {
                setPointDataArray(report);
            }
        });

        thisMarkers.push(marker);
        setThisMarkers([...thisMarkers]);

        new MarkerClusterer({
            markers: thisMarkers,
            map,
            algorithm: new SuperClusterAlgorithm({ radius: 200 }),
        });

        return marker;
    });
}

const addCircles = (
    map: google.maps.Map | undefined,
    setPointDataArray: React.Dispatch<React.SetStateAction<GeoReport | null>>,
    reports: GeoReport[], circles: google.maps.Circle[],
    setCircles: React.Dispatch<SetStateAction<google.maps.Circle[]>>,
) => {

    let isVisited = false;
    const addresses: string[] = [];

    reports.map((report: GeoReport) => {

        report.surveys.map(survey => {
            survey.table.map(data => {
                addresses.push(data.soilType);
            });
        });

        let color = '#FFFFFFF';
        const soilType = findMode(addresses);
        if (soilType) {
            color = getSoilTypeColor(soilType);
        }
        const marker = new google.maps.Circle({
            center: { lat: report.lat, lng: report.lng },
            radius: 500,
            strokeColor: color,
            strokeOpacity: 0.8,
            strokeWeight: 2,
            fillColor: color,
            fillOpacity: 0.35,
            map,
        });

        marker.addListener('click', () => {
            isVisited = !isVisited;
            if (isVisited === true) {
                setPointDataArray(report);
            }
        });

        circles.push(marker);
        setCircles([...circles]);
        return marker;
    });
};

export default TestMap;

You can see here what I’m referring to! (I’m refreshing the website so it shows the problem)

Thanks in advance for any help!

Adding tags based on user search by JavaScript

I am working on a functionality that highlights text in a list of items using the <mark> tag based on user input. I cannot simplify the HTML code of the <li> tags. I have a version that works for simple cases. For example, when searching for Ba the result looks like this:

<li>
    <input type="checkbox" name="hide-balise" id="hide-balise">
    <label for="hide-balise"><mark>Ba</mark>lise</label>
</li>

However, I am facing challenges in making this form case-insensitive. If a user searches for css in lowercase, I want the <mark> tags to be added like this:<mark>CSS</mark>, while preserving the original uppercase letters from the HTML code. Additionally, the search does not work when the searched portion is at the end or in the middle. For instance, searching for Sheet does not result in the addition of the <mark> tag.

These issues seem also related to the regex. Can you assist me in improving it to handle these different scenarios in the search?

I have already reviewed this.

Below is my HTML and JavaScript code:

<!doctype html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <title>MWE</title>
</head>
<body>
<h1>MWE</h1>
<input type="text" name="search">
<br>
<ul>
    <li>
        <input type="checkbox" name="hide-balise" id="hide-balise"><label for="hide-balise">Balise</label>
    </li>
    <li><input type="checkbox" name="hide-div" id="hide-div"><label for="hide-div"><abbr lang="en"
                                                                                         title="division">div</abbr></label>
    </li>
    <li><input type="checkbox" name="hide-div" id="hide-div-with-entities"><label for="hide-div-with-entities"><abbr
            lang="en"
            title="division">&lt;div&gt;</abbr></label>
    </li>
    <li><input type="checkbox" name="hide-attribut" id="hide-attribut"><label
            for="hide-attribut">Attribut</label></li>
    <li>
        <input type="checkbox" name="hide-css" id="hide-css"><label for="hide-css"><abbr lang="en"
                                                                                         title="Cascading Style Sheets">mark</abbr>
        (<i lang="en">Cascading Style
            Sheets</i>)</label>
    </li>
    <li>
        <input type="checkbox" name="hide-attribut" id="hide-ancre"><label for="hide-ancre">Ancre (<i
            lang="en">Anchor</i>)</label>
    </li>
</ul>
<script type="module" src="./main.js"></script>
</body>
</html>
const items = document.querySelectorAll('li');

function addMarks(event) {
    const regex = new RegExp(`>[a-zA-Z]*${event.currentTarget.value}[a-zA-Z]*<`, 'gi');
    for (const li of items) {
        li.innerHTML.match(regex)?.forEach((match) => {
            li.innerHTML = li.innerHTML.replace(
                match,
                match.replaceAll(event.currentTarget.value, `<mark>${event.currentTarget.value}</mark>`),
            );
        });
    }
}

function clearMarks() {
    items.forEach((li) => {
        li.innerHTML = li.innerHTML.replaceAll('<mark>', '');
        li.innerHTML = li.innerHTML.replaceAll('</mark>', '');
    });
}

document.querySelector('input[type=text]').addEventListener('input', (event) => {
    clearMarks();
    if (event.currentTarget.value.trim() !== '') {
        addMarks(event);
    }
});




Cloudinary nodeJS

I’m trying to create a product in an e-commerce project, but the product is created without the images. What am I doing wrong?

I tried several console logging to see if the images are being passed like
console.log(productImage) in the Backend
and console.log(images) in the Frontend

Here’s the code:

Cloudinary utility (Backend):

import cloudinary from "cloudinary";

cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET,
});

export const upload_file = (file, folder) =>{
  return new Promise((resolve, reject) =>{
    cloudinary.uploader.upload(file, (result) =>{
      resolve({
        public_id: result.public_id,
        url: result.url,
      });
    },
    {
      resource_type: "auto",
      folder,
    }
    );
  });
};

export const delete_file = async(file) =>{
  const res = await cloudinary.uploader.destroy(file);

  if (res?.result === "ok") return true;
};

Creating a new product (Backend):

export const newProduct = asyncErrors(async(req, res, next) =>{
  const product = await Product.create(req.body);
  let productImage = [];

  if(!productImage){
    return next(new ErrorHandler("Product not found", 404));
  }
  const uploader = async(image) => upload_file(image, image.length > 1 ? `Products/${product.name}` : "Products");
  const urls = await Promise.all((req?.body?.images).map(uploader));
  productImage?.images?.push(...urls);
  await product?.save();

  res.status(200).json({ product });
});

Frontend Form:

import { useEffect, useState } from "react";
import { useNavigate } from "react-router-dom";
import { useSelector } from "react-redux";
import { Button, Col, FloatingLabel, Form, Row } from "react-bootstrap";
import { toast } from "sonner";

import { PRODUCT_CATEGORIES, PRODUCT_CONDITION } from "../../constants/productConstants";
import { useCreateProductMutation } from "../../redux/services/productApi";

import MetaData from "../../components/MetaData";
import UserSidebar from "../../components/storeComps/UserSidebar";

const NewProduct = () =>{
  const { user } = useSelector((state) => state.user);
  const [product, setProduct] = useState({
    name: "",
    description: "",
    price: "",
    category: "",
    seller: user?.name,
    stock: "",
    condition: ""
  });
  const { name, description, seller, price, category, stock, condition } = product;
  const [images, setImages] = useState([]);
  const [imagesPreview, setImagesPreview] = useState([]);

  const navigate = useNavigate();

  const theme = useSelector((state) => state.theme);
  const [createProduct, { error, isLoading, isSuccess }] = useCreateProductMutation();

  const productDataHandler = (e) => {
    setProduct({ ...product, [e.target.name]: e.target.value });
  };

  const validateProductImage = (e) =>{
    const files = Array.from(e.target.files);

    files.forEach((file) =>{
      const reader = new FileReader();
      const formData = new FormData();
      formData.append("images", images);

      reader.onload = () =>{
        if(reader.readyState === 2){
          setImagesPreview((oldArray) =>[...oldArray, reader.result]);
          setImages((oldArray) =>[...oldArray, reader.result]);
        }
      };

      reader.readAsDataURL(file);
    });
  }

  useEffect(() =>{
    if(error){
      toast.error(error?.data?.message);
    }
    if(isSuccess){
      toast.success("Product created");
      navigate("/");
    }
  }, [error, isSuccess, navigate, user?.role]);

  const createProductHandler = (e) =>{
    e.preventDefault();
    createProduct(product);
  };

  return(
    <>
      <UserSidebar>
      <MetaData title={"Create A New Product"}/>
        <Row>
          <Col lg={10} className="col-12 mt-lg-0">
            <Form onSubmit={createProductHandler} className={`product-form ${theme ? "shadow-lg" : "dark"}`}>

              <FloatingLabel data-bs-theme={theme ? "light" : "dark"} label="Product Name">
                <Form.Control type="text"
                name="name"
                placeholder="Product Name"
                value={name}
                onChange={productDataHandler}/>
              </FloatingLabel>

              <Form.Label className="mt-2"/>
                <Form.Control as="textarea" data-bs-theme={theme ? "light" : "dark"}
                rows={8}
                name="description"
                placeholder="Description"
                value={description}
                onChange={productDataHandler}/>

              <Row>
                <Col>
                  <Form.Label className="mt-2"/>
                  <Form.Control type="number" data-bs-theme={theme ? "light" : "dark"}
                  name="price"
                  placeholder="Price"
                  value={price}
                  onChange={productDataHandler}/>
                </Col>

                <Col>
                  <Form.Label className="mt-2"/>
                  <Form.Control type="number" data-bs-theme={theme ? "light" : "dark"}
                  name="stock"
                  placeholder="Stock"
                  value={stock}
                  onChange={productDataHandler}/>
                </Col>
              </Row>

              <FloatingLabel className="mt-4" data-bs-theme={theme ? "light" : "dark"} label="Seller">
                <Form.Control
                data-bs-theme={theme ? "light" : "dark"}
                name="seller"
                value={seller}
                onChange={productDataHandler}
                readOnly>
                </Form.Control>
              </FloatingLabel>

              <FloatingLabel className="mt-4" data-bs-theme={theme ? "light" : "dark"} label="Category">
                <Form.Select
                data-bs-theme={theme ? "light" : "dark"}
                name="category"
                value={category}
                onChange={productDataHandler}
                required>
                {PRODUCT_CATEGORIES?.map((category) =>(
                  <option key={category} value={category}>{category}</option>
                ))}
                </Form.Select>
              </FloatingLabel>

              <FloatingLabel className="mt-4" data-bs-theme={theme ? "light" : "dark"} label="Condition">
                <Form.Select
                name="condition"
                value={condition}
                onChange={productDataHandler}
                required>
                {PRODUCT_CONDITION?.map((condition) =>(
                  <option key={condition} value={condition}>{condition}</option>
                ))}
                </Form.Select>
              </FloatingLabel>

              <Form.Group className="mt-4">
                <Form.Control type="file" data-bs-theme={theme ? "light" : "dark"}
                name="product_images"
                onChange={validateProductImage}
                multiple/>
              </Form.Group>
              {imagesPreview.map(img =>(
                <img key={img} src={img} alt="Images Preview" className="mt-3 mr-2" width="55" height="52" />
              ))}
              <br />
              <Button type="submit" className="btn-danger my-3" disabled={isLoading}>Publish</Button>
            </Form>
          </Col>
        </Row>
      </UserSidebar>
      <div style={{ marginBottom: "4rem" }}/>
    </>
  )
}

export default NewProduct;

How to make a fluid responsive website while maintaining the original ratio? [closed]

I’ve been seeing websites with the responsiveness like you were resizing an image from the corner using an editing program when you make the width of the window smaller. How did they do this?

This GIF is an example of how it looks like.
https://www.softorbits.net/assets/img/how-to/en/resize-gifs/animagted.gif

I tried using clamp units like vw and % for CSS to get the same result, but it doesn’t work the same as them.

Swiperjs issue with pictures

I’m attempting to develop a new version of my website with a large picture slider, using SwiperJS. Unfortunately, I’ve encountered an issue while working with the images in this slider.
As you can observe on this CodePen, I’m struggling to display my images side by side with only the gutter space in between.
Instead, there’s always a large space after each photo, highlighted with an orange background.

Do you have any suggestions on how to resolve this issue?

Thank you in advance for your help.

PS.: Here is the result I try to achieve :
enter image description here

I’ve tried manipulating the .swiper-slide class in the CSS, but it consistently results in a malfunctioning slider.

React-native: How to create abstract package to work with all state management packages?

I am working on a user tracker package and want to make it abstract so it can be implemented with all the state management packages such as Redux, Mobx, and Zustland …

this package contains middleware, enums, and a bunch of interfaces that need to be implemented when using this package.

the problem is how can I make all the functions and methods abstract so they can be used with any state management package the developer is already working with.