Prevent Close without Save of Iframe in Modal

I have a project to not allow a form to be closed unless the user saves their changes first. The way the page is set up having the parent page, cshtml, to have a modal and inside that modal is an Iframe that has the form, html. I tried just editing the form to have a beforeunload eventlistner however the that does not work since the Iframe can only be hidden not closed. I am currently trying to connect the parent and child up to talk to each other by having:
parent.cshtml

<div class="modal-content">
            <div class="modal-body" style="width:100%; height:75%;">
                <div id="complianceIframeBody" style=" width: 100%; height: 100%;">
                    <iframe id="IframeHtml" class="iframe;" frameborder="0" allowfullscreen src=""></iframe>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" id="closeBtn" class="btnOk btn btn-default" data-dismiss="modal">Close</button>
</div>
    <script>
        function preventNaigation() {
            window.onbeforeunload = function (e) {
                return "Are you sure you want to navigate away from this page ? Any unsaved changes will be lost.";
            }
        }
</script>

child.html

<script>
    $("#form0 :input").change(function () {
        preventNavigation();
        });
</script>

My question is how cna I have these two communicate in order for the Iframe to prompt the User they are leaving unsaved changes when they click a close button on the modal.

how to add image infront of image input field?

[![first image][1]][1]

second image

I have added two pictures for reference. I am trying to create a form like the one in that picture with 6 input fields as shown, one image input field another 4 character input fields, and the one integer field. I want the image input field to show the default logo/image first and when we click on that default logo/image we should able to upload our image and when we uploaded our image should it be shown instead of the default logo/image.

Upload a csv file duirng postman collection run. So that API ca upload a file to the system in runtime

I have an api, that initate a registration process by uploading a csv file along with other data. This api payload body is form-data. One key name is,”csv_file”. Using this key I have to upload a csv to the system. System expects a csv file from the API.
What I want to achieve is, I want to run this api in a collection run along with some other apis. So that, whatever the Iteration value I add in runner, say, 2 iterations. I want to run this api along with other apis twice. And each time,it will pick a csv file during runtime from the pc.

How to make a full code editor for coding tutorials?

So , I just finished W3Schools tutorial and trying to make such tutorials of my own. I need to make a coding editor like any IDE but its just too complicated.

I came here to ask for some source code an am a half way learner of js (ya , the whole things too much), I dont see any js that can help me . I have only learnt till arrays.

How to set up Coinpayments IPN in Nextjs 13 directory?

I have a Nextjs 13 app using app directory, and I’m trying to get [Coinpayments IPN]*(https://github.com/OrahKokos/coinpayments-ipn) configured for it.

Their documentation says to set up a file which you upload to your server to recieve the payments, which looks like this:

/**
 *
 * @param {String} hmac
 * @param {String} ipnSecret
 * @param {Object} payload
 * @returns {Boolean}
 * @throws {CoinpaymentsIPNError}
 */
const { verify } = require('coinpayments-ipn');
const CoinpaymentsIPNError = require('coinpayments-ipn/lib/error');

let isValid, error;

try {
  isValid = verify(hmac, ipnSecret, payload);
} catch (e) {
  error = e;
}
if (error) {
  if (error instanceof CoinpaymentsIPNError) {
    // handle invalid payload
  }
  // make bug report
}

if (isValid) {
  // valid
} else {
  // invalid
}

Now I’ve tried to adapt this to a Next JS server component, but to no avail. What I’m trying to do now is inside my app/api/ipn.ts is return the body of the request e.g:

import { NextResponse } from "next/server";

export async function POST(req:any) {

  if (req.method !== 'POST') {
    return NextResponse.json(
      { message: "Must be POST" },
      {
        status: 405,
      })
  }

  console.log('Received raw payload:', req);
  
}

But on Vercel, as with any combinination of code I try, I get the exact same error message:

IPN Error: SyntaxError: Unexpected token a in JSON at position 0
    at JSON.parse (<anonymous>)
    at parseJSONFromBytes (node:internal/deps/undici/undici:6662:19)
    at successSteps (node:internal/deps/undici/undici:6636:27)
    at node:internal/deps/undici/undici:1236:60
    at node:internal/process/task_queues:140:7
    at AsyncResource.runInAsyncScope (node:async_hooks:203:9)
    at AsyncResource.runMicrotask (node:internal/process/task_queues:137:8)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

What am I doing wrong here? In the Coinpayments dashboard I see the IPNs being sent but never recieved.

So I think that the IPN is correctly being uploaded to my server on Vercel but for some reason it’s not able to read the incoming requests?

Please help!

How map data in function?

I am trying to map data in Google Sheets using the following function:

    function convertDataRowsToString() {
    
      const ss = SpreadsheetApp.getActiveSheet();   let data = ss.getDataRange().getValues();
    
      data = data.map(row => row.join(";"));  

   console.log(data) }

In result ‘data’ contains information from all column. Finally I want to get data only from column A, column B. column C (First name, Last name, Surname). That is:

    [data = [ 'First name;Last name;Surname',
  'Oliver;Jake;Smith',
  'Jack;Connor;Johnson',
  'Harry;Callum;Williams',
  'Jacob;Jacob;Brown',
  'Charlie;Kyle;Jones',
  'Thomas;Joe;Miller',
  'George;Reece;Davis',
  'Oscar;Rhys;Garcia',
  'James;Charlie;Rodriguez',
  'William;Damian;Wilson']

I will be grateful for your tips

Run a simple A/B test based on the users browser

I’m looking for a way to do a simple A/B test based on some browser properties where I need a certain threshold to either run case A or case B. The method I use should be simple and results are measured somewhere else.

Basically I need a function which returns either true or false.

  • same result even if page reloads
  • no cookie or other storing mechanic
  • no “fingerprinting” as it’s to overkill

What I came up with is this method:

function consistentProbability() {
    // Collect browser-specific properties
    let screenWidth = window.screen.width;
    let screenHeight = window.screen.height;
    let pixelDepth = window.screen.pixelDepth;
    let userAgent = navigator.userAgent;

    // Create a string from the properties
    let combinedString = `${screenWidth}-${screenHeight}-${pixelDepth}-${userAgent}`;

    // Simple hash function
    let hash = 0;
    for (let i = 0; i < combinedString.length; i++) {
        let char = combinedString.charCodeAt(i);
        hash = (hash << 5) - hash + char;
        hash = hash & hash; // Convert to 32bit integer
    }
    // Use the hash to determine the probability
    return Math.abs(hash % 100) < 50;
}

The problem is that I most of the time get a true and it “feels” not 50/50.

Is something wrong with my function or is it just a wrong assumption?

To test run the snippet. You should always get the same result if you don’t resize your browser window or use a different browser:

function consistentProbability() {
    // Collect browser-specific properties
    let screenWidth = window.screen.width;
    let screenHeight = window.screen.height;
    let pixelDepth = window.screen.pixelDepth;
    let userAgent = navigator.userAgent;

    // Create a string from the properties
    let combinedString = `${screenWidth}-${screenHeight}-${pixelDepth}-${userAgent}`;

    // Simple hash function
    let hash = 0;
    for (let i = 0; i < combinedString.length; i++) {
        let char = combinedString.charCodeAt(i);
        hash = (hash << 5) - hash + char;
        hash = hash & hash; // Convert to 32bit integer
    }

    console.log('hash', hash);

    // Use the hash to determine the probability
    return Math.abs(hash % 100) < 50;
}
console.log('consistentProbability', consistentProbability());

Trouble with Setting defaultValue/value in Material-UI Autocomplete Component

I’m encountering an issue with setting the defaultValue or value in a Material-UI Autocomplete component. The goal is to programmatically set the default value based on certain conditions, but it doesn’t seem to reflect in the UI. Its also occured to me that if the component renders before the value is there, defaultValue would not work. So I did try the same with value rather than defaultValue.

Here’s the relevant part of my code:

<Autocomplete
  options={[{ value: true, label: FILTERS_ENUM.CHANGED }, { value: false, label: FILTERS_ENUM.UNCHANGED }]}
  renderInput={(params) => (
    <TextField
      size='small'
      placeholder='Changed & Unchanged'
      {...params}
    />
  )}
  PaperComponent={CustomPaper}
  onChange={(e, value) => {
    doFilter(value, FILTERS_ENUM.CHANGED)
  }}
  //does not work
  {...(
    filters[FILTERS_ENUM.CHANGED] === null ? null :
    filters[FILTERS_ENUM.CHANGED] && filters[FILTERS_ENUM.CHANGED].value
      ? { defaultValue: { value: true, label: FILTERS_ENUM.CHANGED } }
      : { defaultValue: { value: false, label: FILTERS_ENUM.UNCHANGED }}
  )}
  //does work
  defaultValue={{ value: false, label: FILTERS_ENUM.UNCHANGED }}
/>

The expected behavior is that the Autocomplete should display the label from FILTERS_ENUM based on the condition provided in the ternary operation. However, it always defaults to { value: false, label: FILTERS_ENUM.UNCHANGED }, regardless of the condition.

I have tried using both defaultValue and value props, but neither seems to work as expected. The onChange event works fine and updates the state correctly, but the initial value does not reflect the state.

Has anyone faced a similar issue or can spot what I might be doing wrong here? Any insights or suggestions would be greatly appreciated.

Searching for emails with empty subjects using IMAP

I am trying to search emails from my draft folder using node-imap package

So what my file does is, it uses an imap search function based on Subjects and since the number of subjects is dynamic, we build the search query on the go.

Here’s a sample search query

[
    'UNDELETED',
    [
      'OR',
      [
        'OR',
        [
          'OR',
          [ 'SUBJECT', '<My Subject 3>' ],
          [ 'SUBJECT', ' <My Subject 2>  ' ]
        ],
        [ 'SUBJECT', '<My Subject 1>' ]
      ],
      [ 'SUBJECT', 'abc' ]
    ]
]

Now, so far it is working fine. But if, in case, the subject field is blank and I rewrite the same code as given below, I get Error: infeasible query (Failure)

[
    'UNDELETED',
    [
      'OR',
      [
        'OR',
        [
          'OR',
          [ 'SUBJECT', '<My Subject 3>' ],
          [ 'SUBJECT', ' <My Subject 2>  ' ]
        ],
        [ 'SUBJECT', '<My Subject 1>' ]
      ],
      [ 'SUBJECT', '' ]
    ]
]

Any help in this matter would be greatly appreciated.

Authentication In MERN Project [closed]

is there anyone who has a good knowledge of MERN stack and is interested in helping me with an authentication problem in my application?

I tried all possible ways to do it, but it didn’t work, I even asked chatgpt.
I want when typing urls that I don’t have defined in the routes in react to return me to the login page and also when entering the application if the user is logged in to transfer him to the user page and if the admin is on the admin page or to the login if he is not logged in no one.

The browser keeps saying that one of my variables in my EJS code is not defined

I’m rendering an EJS file in a node js file, and i’m assuming that the data is not being passed because the variables in my EJS seem to not be defined, specifically a variable called blood_type

GET route in my node js

app.get('/donors', async (req, res) => {
  try {
 
    const bloodTypesResult = await db.query('SELECT DISTINCT blood_type FROM donors');
    const blood_type = bloodTypesResult.rows;
    const citiesResult = await db.query('SELECT * FROM city');
    const city = citiesResult.rows;
    res.render('donors.ejs', { blood_type: blood_type, city: city }); 
  } catch (error) {
    console.error('Error fetching data:', error);
    // Handle other errors if needed
    res.status(500).send('Internal Server Error');
  }
});

My EJS form

<form action="donors" method="post" class="d-flex flex-column flex-xl-row gap-3 text-center">   
            <div class="w-100">
              <select class="form-select form-select-lg" name="bloodType" required>
                <option selected hidden style="display:none" value="">Blood Type</option>
                <% blood_type.forEach(bloodType => { %>
                  <option value="<%= bloodType.blood_type %>"><%= bloodType.blood_type %></option>
                <% }); %>
              </select>
            </div>
          
            <div class="w-100">
              <select class="form-select form-select-lg" name="city" required>
                <option selected hidden style="display:none" value="">City</option>
                <% city.forEach(city => { %>
                  <option value="<%= city.city_id %>"><%= city.city_name %></option>
                <% }); %>
              </select>
            </div>

When the user selects values from two drop down lists, the page should dynamically change based on the users selected values, i’m trying to do that using Node, express, and EJS.
There seems to be a problem with the variables in my EJS
The browser says the following:

    50|               <select class="form-select form-select-lg" name="bloodType" required>

    51|                 <option selected hidden style="display:none" value="">Blood Type</option>

 >> 52|                 <% blood_type.forEach(bloodType => { %>

    53|                   <option value="<%= bloodType.blood_type %>"><%= bloodType.blood_type %></option>

    54|                 <% }); %>

    55|               </select>


blood_type is not defined

How to display a placeholder in MUI Select component?

I’m trying to apply a placeholder “Select a brand” in the select, but I can’t.
I’ve tried several options but without any success.
This is the code:

<FormControl fullWidth>
          <InputLabel id="demo-multiple-name-label" sx={{ color:'inherit' }}>Brand</InputLabel>
          <Select
            labelId="demo-multiple-name-label"
            id="demo-multiple-name-label"
            label="Brand"
            value={certificateData.brandName || ''}
            onChange={(e) => void setCertificateData((prevData) => ({ ...prevData, brandName: e.target.value }))}
          >
            {brands
              .sort((a, b) => a.brandName.localeCompare(b.brandName))
              .map((brand) => (
                <MenuItem key={brand.brandNumber} value={brand.brandName}>
                  {brand.brandName}
                </MenuItem>
              ))}
          </Select>
        </FormControl>
This is what I have so far:
[enter image description here][1]


  [1]: https://i.stack.imgur.com/JWEwU.png

Make part of a border invisible ? CSS

I’ve been struggling to reproduce this button :

button with round border which becomes transparent around the check icon

Specifically I can’t seem to find how to make the border invisible around the check icon. At the moment it’s “finished” except for this part.

It’s a nuxt3 component and it looks like this :

 <template>
  <div class="button-container">
    <nuxt-link :to="link.link">
      {{ link.title }}
    </nuxt-link>
    <div class="check-container">
      <svg-icon type="mdi" :path="mdiCheckBold" class="icon is-large" />
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineProps } from 'vue'
import SvgIcon from '@jamescoyle/vue-icon'
import { mdiCheckBold } from '@mdi/js'

type Link = {
  title: string;
  link: string;
};

interface Props {
  link: Link;
}

defineProps<Props>()
</script>

<style scoped lang="scss">
@import 'assets/style/_variables.scss';

.button-container {
  position: relative;
  border: dotted $white 0.24rem;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 18rem;
  height: 18rem;
  a {
    text-decoration: none;
    color: $white;
    font-size: 2rem;
  }
  .check-container {
    position: absolute;
    top: 11.5rem;
    left: 11.5rem;
    border: solid $white 0.24rem;
    border-radius: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    width: 7rem;
    height: 7rem;
    color: $white;
    background: $background-gradient;
  }
}
</style>

Any help would be great, thank you in advance !

npm start funktioniert nicht [closed]

bis vor kurzem hat alles einwandfrei funktioniert. Jetzt kommt auf einmal aber eine Fehlermeldung. Wenn ich npm start ausführe wird meine Seite nicht mehr aufgerufen.

<--- Last few GCs --->

[3460:0000026492D8FE00]    34481 ms: Scavenge 350.7 (396.6) -> 350.7 (396.6) MB, 106.0 / 0.0 ms  (average mu = 0.988, current mu = 0.885) allocation failure; 
[3460:0000026492D8FE00]    37737 ms: Scavenge 542.7 (588.6) -> 542.7 (588.6) MB, 139.7 / 0.0 ms  (average mu = 0.988, current mu = 0.885) allocation failure; 
[3460:0000026492D8FE00]    43519 ms: Scavenge 926.7 (972.6) -> 926.7 (972.6) MB, 228.6 / 0.0 ms  (average mu = 0.988, current mu = 0.885) allocation failure; 


<--- JS stacktrace --->

FATAL ERROR: invalid table size Allocation failed - JavaScript heap out of memory
 1: 00007FF721131B7F node_api_throw_syntax_error+203775
 2: 00007FF7210B1556 v8::internal::wasm::WasmCode::safepoint_table_offset+63558
 3: 00007FF7210B28C2 v8::internal::wasm::WasmCode::safepoint_table_offset+68530
 4: 00007FF721B547F4 v8::Isolate::ReportExternalAllocationLimitReached+116
 5: 00007FF721B3FB52 v8::Isolate::Exit+674
 6: 00007FF7219C1BBC v8::internal::EmbedderStackStateScope::ExplicitScopeForTesting+124
 7: 00007FF7213FE539 v8::internal::Isolate::FatalProcessOutOfHeapMemory+25
 8: 00007FF7217BC735 v8::internal::HashTable<v8::internal::NumberDictionary,v8::internal::NumberDictionaryShape>::EnsureCapacity<v8::internal::Isolate>+341
 9: 00007FF7217BA191 v8::internal::Dictionary<v8::internal::NumberDictionary,v8::internal::NumberDictionaryShape>::Add<v8::internal::Isolate>+81
10: 00007FF7218727E5 v8::internal::FeedbackNexus::ic_state+34837
11: 00007FF72186C702 v8::internal::FeedbackNexus::ic_state+10034
12: 00007FF7218183A9 v8::internal::JSObject::AddDataElement+1113
13: 00007FF7217C4743 v8::internal::StringSet::Add+1491
14: 00007FF721819C34 v8::internal::JSObject::DefineAccessor+804
15: 00007FF7218193AD v8::internal::JSObject::AddProperty+3357
16: 00007FF72181957B v8::internal::JSObject::AddProperty+3819
17: 00007FF7216CD469 v8::internal::Runtime::GetObjectProperty+3481
18: 00007FF721BF1E81 v8::internal::SetupIsolateDelegate::SetupHeap+558193
19: 00007FF721C21521 v8::internal::SetupIsolateDelegate::SetupHeap+752401
20: 00007FF721C0AF3F v8::internal::SetupIsolateDelegate::SetupHeap+660783
21: 00007FF721B75894 v8::internal::SetupIsolateDelegate::SetupHeap+48772
22: 00007FF6A2422789 

Ich habe schon alle Programme geschlossen und meinen PC heruntergefahren. Zudem habe ich bevor ich

npm start mache erst folgendes eingegeben:
set NODE_OPTIONS="--max-old-space-size=4096"
node server.js`

Aber dann kommt, dass das Modul nicht gefunden werden kann.