Abstract common function behavior into higher order function

I have three pretty similar functions:

//for context there is also this part:
  const [colors, setColors] = useState(["#000000", "#ffffff"]);
// but the three functions start here:

 function updateColor(index, color) {
    const newColors = [...colors];
    newColors[index] = color;
    setColors(newColors);
  }

  function deleteColor(index) {
    const newColors = [...colors];
    newColors.splice(index, 1);
    setColors(newColors);
  }

  function duplicateColor(index) {
    const newColors = [...colors];
    newColors.splice(index, 0, newColors[index]);
    setColors(newColors);
  }

As you can see the first and third line of each of these are identical. Is there some method by which I can create a function that takes the middle line as a callback function and reproduces the first and third.

Something like:

const updateColor = functionMaker((index, color) => newColors[index]);
const deleteColor = functionMaker((index) => newColors.splice(index, 1));

I can’t quite get my head around how I would support different arguments for each, as in my example above.

jQuery scripts don’t reckon with the changes in HTML. How come? [duplicate]

In the code snippet below, you can press yellow buttons and make them green. However, if you click them again, they don’t become yellow again even though I have that covered in my script as well. I discovered a similar problem in my project (of course, it’s not just about the color). It appears, jQuery scripts “remember” the HTML they “saw” the first time the page was loaded and never consider any changes to the code a user may make. If the page is refreshed, my scripts work the other way too

enter image description here

enter image description here

$(document).ready(function () {
    $('td a.btn-outline-warning').on('click', async function () {
        let username = $(this).closest('tr').children().eq(0).text();
        console.log(`username in disable event handler: ${username}`);
// ...

$(document).ready(function () {
    $('td a.btn-outline-success').on('click', async function () {
        let username = $(this).closest('tr').children().eq(0).text();
        console.log(`username in enable event handler: ${username}`);
// ...

Why does this happen and how do I fix it?

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
              integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
        <title>Admin Page</title>
    </head>
    <body>
    <div class="container">
        <div class="row">
            <table class="table table-hover text-center">
                      <thead>
                            <tr>
                                <th scope="col">Name</th>
                                <th scope="col">Last name</th>
                                <th scope="col">Department</th>
                                <th scope="col">Buttons</th>
                            </tr>
                      </thead>
                      <tbody>
                            <tr>
                                <td>John</td>
                                <td>Doe</td>
                                <td>IT</td>
                                <td class="btn-group btn-group-sm">
                                    <a class="btn btn-outline-warning" href="#">Yellow button</a>
                                </td>
                            </tr>
                            <tr>
                                <td>Jane</td>
                                <td>Doe</td>
                                <td>HR</td>
                                <td class="btn-group btn-group-sm">
                                    <a class="btn btn-outline-warning" href="#">Yellow button</a>
                                </td>
                            </tr>
                     </tbody>
              </table>
          </div>
    </div>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/jquery.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    <script>
$(document).ready(function () {
$('td a.btn-outline-warning').on('click', async function () {

    $(this).removeClass('btn-outline-warning')
        .addClass('btn-outline-success')
        .text('Green button');
});
});

$(document).ready(function () {
$('td a.btn-outline-success').on('click', async function () {
    $(this).removeClass('btn-outline-success')
        .addClass('btn-outline-warning')
        .text('Yellow button');
});
});
    </script>
    </body>
    </html>

How to extract code block substring from string

This is my first post here so hopefully I’m not posting incorrectly, but I’m basically looking to extract the code block (substring wrapped in backticks) from a string that was returned from an API request.

Here is the string:

const originalString = 'this is some string and I want to extract ```the code contained in the backticks```';

const whatIWant = 'the code contained in the back ticks';

I was thinking maybe I could use regex, but I wasn’t able to come up with anything that would work.

I also tried using something like this:

originalString.substring(originalString .indexOf("```"), originalString .lastIndexOf("```") + 3);

but it produces undesired results when the text contains a mix of normal text and multiple code blocks.

Any ideas?

Displaying map from MBTiles file using Leaflet and Flask results in only in map controls being displayed in web page

I’m trying to display a map from an MBTiles file using Leaflet, Flask and Sqlite3. I have an MBTiles file of the New Zealand map, and I want to display a location with latitude and longitude values on a web page. I am able to serve the tiles using a Flask route, but when I load the page in my browser, only the controls for the map are displayed, and the map itself is not visible.

Here is what the web page looks like:

Web page

Here’s my Flask app code (app.py):

import sqlite3
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def display_map():
    longitude = 175.6138189
    latitude = -40.34256356
    return render_template('map.html', lat=latitude, lon=longitude)

@app.route('/tiles/<int:z>/<int:x>/<int:y>.png')
def serve_tile(z, x, y):
    mbtiles_path = 'path/to/new-zealand.mbtiles'

    with sqlite3.connect(mbtiles_path) as conn:
        cursor = conn.cursor()
        cursor.execute(
            'SELECT tile_data FROM tiles WHERE zoom_level=? AND tile_column=? AND tile_row=?',
            (z, x, (2 ** z) - 1 - y)
        )
        tile = cursor.fetchone()
        if tile:
            return tile[0], 200, {
                'Content-Type': 'image/png',
                'Cache-Control': 'public, max-age=3600'
            }
    return 'Tile not found', 404

if __name__ == '__main__':
    app.run(debug=True)

And here’s my map.html file:

<!DOCTYPE html>
<html>
<head>
    <title>Location on Map</title>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
    <script src="https://unpkg.com/[email protected]/dist/leaflet.js"></script>
</head>
<body>
    <div id="map" style="width: 100%; height: 100vh;"></div>
    <script>
        var lat = parseFloat("{{ lat|tojson|safe }}");
        var lon = parseFloat("{{ lon|tojson|safe }}");
        console.log("Latitude: ", lat);
        console.log("Longitude: ", lon);

        var map = L.map('map').setView([lat, lon], 13);
        L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
            attribution: 'Map data &copy; OpenStreetMap contributors'
        }).addTo(map);

        L.marker([lat, lon]).addTo(map).bindPopup("<b>Location</b><br>Latitude: " + lat + "<br>Longitude: " + lon).openPopup();
    </script>
</body>
</html>

When I load the page in my browser, I get the following error in the console:

map.html:15 Latitude:  NaN
map.html:16 Longitude:  NaN
Uncaught Error: Invalid LatLng object: (NaN, NaN)
    at new D (LatLng.js:32:9)
    at j (LatLng.js:123:11)
    at i.setView (Map.js:181:30)
    at map.html:18:32. 

I suspect that the javascipt code is not receiving the latitude and longitude values from the app.py. That is probably why it is saying the above error.

How can I resolve this issue and display the map with the correct location using the MBTiles file?

I served the tiles using a Flask route, but encountered issues with displaying the map on the web page. I made changes to the Flask app code and HTML file to try to resolve the issue, such as passing the latitude and longitude values to the template using Flask’s render_template function and using the tojson filter to convert the values to JSON.

TinyMCE on react, using noneditable_regexp spec issue

i’m having an issue with my TinyMCE editor, where i’m setting this spec to my init function noneditable_regexp which gets every text that matches with the test and convert into a nonEditable component inside the editor (means it if someone backspace/delete, it will remove the whole block instead each character).

Show how it is

It is working fine to convert it to a ‘variable’ as you can see {{params.project_title}}, but whenever I try to apply style to the block, it does nothing, it doesnt apply the style to it.

Only if I delete the variable, select the styles before inserting, and finally insert it. then the variable should contain the style changes.

Wasn’t it supposed to work with pre defined span blocks with mceNonEditable class?

Trying to do a Tip Calculator

I am trying to do a Tip Calculator and I don’t even know how to start a function to calculate that.

<!DOCTYPE html> 
<html lang="eng">
 <head>
<title>Tip Calculator</title> 
<meta charset="utf-8"
</head>
<body>
<header>
  
   </header>
  <main>
    <form> 
      <fieldset>
      <legend>Tip Calculator</legend>
        
        <label for="costofdinner">
          Cost of the dinner:</label> 
        <input type="text" name="cost" id="cost" size="10">
        <br>
        <br> 
        <div>
        <button type="button" title="calculatetip">Calculate Tip</button>
        </div> 
        <br>
        <label for="tip15"> 15% of the dinner:</label>
        <input type="text" id="tip15" name="tip15" size="8">
        <br>
        <label for="20tip"> 20% of the dinner:</label>
        <input type="text" id="20tip" name="20tip" size="8">
        <br>
        <br>
        <label for="25tip">Dinner plus 25% tip</label> 
        <input type="text" id="dinnerplustip" name="dinnerplustip" size="12">    
        </fieldset> 
        
    </main> 
    <footer>
   </footer>
 </body> 
 </html> 
    

Electron.js Puppeteer css/js not loading

I have developed a form filling application using puppeteer with nodejs. my code normally only works in pure form. but when I combine it with electron the css and js files are not loaded on the site. All I did was get the data to be entered in the form from the electron html page. but i ran into such a problem in a way that i don’t understand. My research says it’s a cors problem, but I couldn’t find a solution.
I leave my code below.

const puppeteer = require('puppeteer-extra')
const request = require('request');
const RecaptchaPlugin = require('puppeteer-extra-plugin-recaptcha')
const useProxy = require('puppeteer-page-proxy');

var settings = {
    country: "Turkey",
    city: "Istanbul",
    namesurname: "name surname",
    username: "testusername",
    metin: "bla bla bla",
};

const sendForm = async (numOfPages, formProxy) => {
    const browser = await puppeteer.launch({
        headless: false,
        args: [
            '--disable-web-security',
            '--disable-features=IsolateOrigins',
            '--disable-site-isolation-trials'
        ]
    });
    for (let i = 1; i <= numOfPages; i++) {
        console.log(i + ". işlem başladı");
        try {

            const page = await browser.newPage();
            await useProxy(page, 'http://192.168.1.1:8080'); //random proxy

            const data = await useProxy.lookup(page);
            if (!data) throw console.error('No data');

            await page.goto('https:help.instagram.com/contact/1784471218363829', { waitUntil: 'networkidle2' });

           // click actions

            console.log(i + ". İşlem Tamamlandı")
        } catch (error) {
            console.error('Beklenmedik bir hata oluştu tekrar deneniyor.');
            console.error(error);
            i--;
            continue;
        }

        await new Promise(resolve => setTimeout(resolve, 1000));
    }
    await browser.close();
    console.log("Tüm işlemler tamamlandı");
};

This code block works when not in electron.

Electron main.js

function createWindow() {

  win = new BrowserWindow({
    autoHideMenuBar: true,
    frame: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, 
    }
  });

  win.loadURL(`file://${__dirname}/src/login.html`);

  initIPCMain();

  // Open the DevTools.
  win.webContents.openDevTools();

  win.on("closed", () => {
    win = null;
  });

  win.webContents.on('did-finish-load', () => {
    win.webContents.insertCSS('body::-webkit-scrollbar { display: none; }')
    console.log('Tüm kaynaklar yüklendi.');
  });
};

There is one thing I noticed, when I don’t use a proxy, it comes correctly and I don’t have a problem.

Sorry for my bad english.

my research says it’s a cors error. I tried some solutions I found on the internet but it didn’t work.
Solutions I tried;

Electron

    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false, // cors error fix
    }

Puppeteer

        args: [
            '--disable-web-security',
            '--disable-features=IsolateOrigins',
            '--disable-site-isolation-trials'
        ]

I tried these but it didn’t work

create one svg for mulitple line plots in D3

I want to create a plot of plots. That is, I want to a figure with multiple plots of data in the same image.

I can do this with the code below (thanks to an answer to another question) but each plot is its own SVG.

Is there any way to use D3 to plot this as one svg, so it is exportable as a complete image?

<!DOCTYPE html>
<meta charset="utf-8">
<title>Example</title>


<script src="https://d3js.org/d3.v7.min.js"></script>

<style>
    path {
  stroke: darkblue;
  stroke-width: 2px;
  fill: none;
}

svg {
    border: solid 2px red;
    width: 300px
    height: 150px;
}
#plotsHere{
  display: grid;
  grid-auto-flow: column;
  grid-gap: 0px;
  grid-template-rows: 150px 150px;
  grid-template-columns: 300px 300px;
}
</style>

<body>
    <div id="plotsHere">

    </div>
</body>

<script>
const signalData = [
  {
    name: "Signal 1",
    data: [1,2,3,4,5,6,7],
  },
  {
    name: "Signal 2",
    data: [2,3,1,4,5,1,3],
  },
  {
    name: "Signal 3",
    data: [1,7,2,6,3,5,4],
  },
];

// This is a line generator. Normally, you pass the x- and y-scales in,
// see also d3-scale on github
const line = d3.line()
  // The first argument is always the datum object, the second is the index
  // Note that I use the index to determine the x coordinate of each point here
  .x((d, i) => i * 50)
  // And the datum object for the y-coordinate
  .y(d => 150 - (15 * d));
  
// The term `datum` is unrelated to date, but is the singular value of `data`.
// One datum, many data.

d3.select("#plotsHere")
  .selectAll("svg")
  // Append one svg per array entry, look up the so-called enter, update, exit
  // cycle for this. It's the most complex part of d3
  .data(signalData)
  .enter()
  .append("svg")
  // Execute a custom function for each element. People who are new to d3.js
  // over-use this function, very often you don't need it!
  .each(function(d, i) {
    // I pass the current svg element, the datum object, and the index for convenience
    draw(d3.select(this), d, i);
  });

function draw(svg, data, index) {
  // Append a label, set the text to the name
  svg.append("text")
    .attr("x", 20)
    .attr("y", 20)
    .text(d => d.name);
  
  // Append a path, take the datum of the svg, pick it's `data` property,
  // which is the array of numbers, and set that as the datum of the path,
  // then call the line generator
  svg.append("path")
    .datum(d => d.data)
    .attr("d", line);
}

</script>

JavaScript how to for loop different elements as a variable to apply in same functions

I’m new to JavaScript,this question may looks very silly.

I have function like this:

  document.addEventListener('mouseup', function(e) {
        var container = document.getElementById('mySelectOptions');
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    });

And another almost same function like this:

  document.addEventListener('mouseup', function(e) {
        var container = document.getElementById('newSelectOptions');
        if (!container.contains(e.target)) {
            container.style.display = 'none';
        }
    });

The only difference is the id ,my question is how to add the 2 ids into this same function ?

maybe something like this:

for id in ['mySelectOptions','newSelectOptions']:
      document.addEventListener('mouseup', function(e) {
    var container = document.getElementById(id);
    if (!container.contains(e.target)) {
        container.style.display = 'none';
    }
});

The ‘const’ modifier can only be used in TypeScript files

I am following instructions from react-paypal-js to add Paypal buttons to JS React webpage.

https://github.com/paypal/react-paypal-js

I get the following error with

  const initialOptions = {
    "client-id": "AYTn1khGKSYyaSuXGWKl8OAPtqwV3v-EVlMHWaG3LsENDs6OvnVkXz0QLKjZ8fSnTU9PKYM1LDWJC0CT",
    currency: "USD",
    intent: "capture",
    "data-client-token": "abc123xyz==",
  };

and in Render() <PayPalScriptProvider options={initialOptions}>

If I use the const variable, the error is The 'const' modifier can only be used in TypeScript files.

If I remove the const variable, I get the error 'initialOptions' is not defined in <PayPalScriptProvider options={initialOptions}>

How do I fix this without switching to typescript?
And why does this error occur

Google Apps Script published web app doesn’t work if link link clicked in Gmail

I have tow problem regarding Gmail and my published app script web app, I’m receiving my customers registration data to my Google sheet, then I used app script to create suitable email to the customer according to his entries, but here are my problems:

  • Embedded PayPal code: Gmail doesn’t show PayPal buttons in the email sent to the customer, due this buttons created by JavaScript function, because of this problem, i have created new app script project containing PayPal codes, and it works correctly after has been published, here’s my PayPal code:

    
      function initPayPalButton() {
        var shipping = 0;
        var itemOptions = document.querySelector("#smart-button-container #item-options");
    var quantity = parseInt();
    var quantitySelect = document.querySelector("#smart-button-container #quantitySelect");
    if (!isNaN(quantity)) {
      quantitySelect.style.visibility = "visible";
    }
    var orderDescription = 'اختر المبلغ الذي تود دفعه من القائمة المنسدلة';
    if(orderDescription === '') {
      orderDescription = 'Item';
    }
    paypal.Buttons({
      style: {
        shape: 'pill',
        color: 'gold',
        layout: 'vertical',
        label: 'paypal',
        
      },
      createOrder: function(data, actions) {
        var selectedItemDescription = itemOptions.options[itemOptions.selectedIndex].value;
        var selectedItemPrice = parseFloat(itemOptions.options[itemOptions.selectedIndex].getAttribute("price"));
        var tax = (12 === 0 || false) ? 0 : (selectedItemPrice * (parseFloat(12)/100));
        if(quantitySelect.options.length > 0) {
          quantity = parseInt(quantitySelect.options[quantitySelect.selectedIndex].value);
        } else {
          quantity = 1;
        }

        tax *= quantity;
        tax = Math.round(tax * 100) / 100;
        var priceTotal = quantity * selectedItemPrice + parseFloat(shipping) + tax;
        priceTotal = Math.round(priceTotal * 100) / 100;
        var itemTotalValue = Math.round((selectedItemPrice * quantity) * 100) / 100;

        return actions.order.create({
          purchase_units: [{
            description: orderDescription,
            amount: {
              currency_code: 'USD',
              value: priceTotal,
              breakdown: {
                item_total: {
                  currency_code: 'USD',
                  value: itemTotalValue,
                },
                shipping: {
                  currency_code: 'USD',
                  value: shipping,
                },
                tax_total: {
                  currency_code: 'USD',
                  value: tax,
                }
              }
            },
            items: [{
              name: selectedItemDescription,
              unit_amount: {
                currency_code: 'USD',
                value: selectedItemPrice,
              },
              quantity: quantity
            }]
          }]
        });
      },
      onApprove: function(data, actions) {
        return actions.order.capture().then(function(orderData) {
          
          // Full available details
          console.log('Capture result', orderData, JSON.stringify(orderData, null, 2));

          // Show a success message within this page, e.g.
          const element = document.getElementById('paypal-button-container');
          element.innerHTML = '';
          element.innerHTML = '<h3>Thank you for your payment!</h3>';

          // Or go to another URL:  
          actions.redirect('https://www.alhuqebi.com/thank_you');

        });
      },
      onError: function(err) {
        console.log(err);
      },
    }).render('#paypal-button-container');
  }
  initPayPalButton();
  
    

and the Html code for this PayPal is as the following:

  <div id="smart-button-container">
      <div dir="rtl" style="text-align: center;">
        <div style="margin-bottom: 1.25rem;">
          <h4 style="text-align: right;">اختر المبلغ الذي تود دفعه من القائمة المنسدلة</h4>
          <select dir="rtl" Style="text-align:right;" id="item-options">
          <option value="البرنامج الرمضاني لتطوير المهارات" price="120">البرنامج الرمضاني لتطوير المهارات - 120 دولار</option>
                  <option value="البرنامج التدريبي المتكامل" price="200">البرنامج التدريبي المتكامل - 200 دولار</option>
          <option value="شراء كتاب دليلك الى رفع انتاجية النفط" price="25">شراء كتاب دليلك الى رفع انتاجية النفط - 25 دولار</option>
          <option value="برنامج الانتاج المتكامل" price="175">برنامج الانتاج المتكامل - 175 دولار</option>
          <option value="برنامج الانتاج المتكامل" price="90">برنامج الانتاج المتكامل - 90 دولار</option>
          <option value="جميع مستويات برنامج البايبسيم" price="75">جميع مستويات برنامج البايبسيم - 75 دولار</option>
          <option value="خدمة دعم رسالة الماجستير أو أطروحة الدكتوراه" price="400">خدمة دعم رسالة الماجستير أو أطروحة الدكتوراه - 400 دولار</option>
          <option value="خدمة دعم مشروعات التخرج" price="200">خدمة دعم مشروعات التخرج - 200 دولار</option>
          <option value="دفع قسط  في خدمة مشروع التخرج" price="100">دفع قسط  في خدمة مشروع التخرج - 100 دولار</option>
          <option id="abc" value="دورة تدريب خاصة حسب الطلب"price="300">دورة تدريب خاصة حسب الطلب - 300 دولار</option>
          <option value="دورة تدريب برنامج البتريل"price="25">دورة تدريب برنامج البتريل - 25 دولار</option>
          <option value="دورة تدريب برنامج الـ GAP"price="25">دورة تدريب برنامج الـ GAP - 25 دولار</option>
          <option value="دورة تدريب برنامج التكلوج"price="25">دورة تدريب برنامج التكلوج - 25 دولار</option>
          <option value="دورة تدريب برنامج الآي بي"price="25">دورة تدريب برنامج الآي بي - 25 دولار</option>
          <option value="دورة تدريب برنامج البايبسيم-مبتدئ"price="25">دورة تدريب برنامج البايبسيم-مبتدئ - 25 دولار</option>
                  <option value="دورة تدريب برنامج البايبسيم-متوسط"price="25">دورة تدريب برنامج البايبسيم متوسط - 25 دولار</option>
                  <option value="دورة تدريب برنامج البايبسيم-متقدم"price="25">دورة تدريب برنامج البايبسيم-متقدم - 25 دولار</option>
              <option value="جميع مستويات برنامج البايبسيم"price="75">جميع مستويات برنامج البايبسيم - 75 دولار</option>
              <option Selected value="دورة تدريب Kappa Emeraude 2020" price="30">دورة تدريب Kappa Emeraude 2020</option>
                  <option value="دورة تدريب برنامج البروسبار"price="25">دورة تدريب برنامج البروسبار - 25 دولار</option>
                  <option value="دورة تدريب برنامج الأولجا"price="25">دورة تدريب برنامج الأولجا - 25 دولار</option>
                  <option value="دورة تدريب برنامج الساب بمب"price="25">دورة تدريب برنامج الساب بمب - 25 دولار</option>
                  <option value="دورة تكنولوجيا حفر الآبار النفطية والغازية" price="25">دورة تكنولوجيا حفر الآبار النفطية والغازية - 25 دولار</option>
                  <option value="دورة تحكم وسيطرة آبار"price="25">دورة تحكم وسيطرة آبار - 25 دولار</option>
          <option value="دفع مبلغ" price="50">دفع مبلغ - 50 دولار</option>
          <option value="دفع مبلغ" price="40">دفع مبلغ - 40 دولار</option>
          <option value="30دفع مبلغ" price="30">دفع مبلغ - 30 دولار</option>
          <option value="25دفع مبلغ" price="25">دفع مبلغ - 25 دولار</option>
          <option value="20دفع مبلغ" price="20">دفع مبلغ - 20 دولار</option>
          <option value="10دفع مبلغ" price="10">دفع مبلغ - 10 دولار</option>
          <option value="320دفع مبلغ" price="320">دفع مبلغ - 320 دولار</option>
          <option value="156دفع مبلغ" price="156">دفع مبلغ - 156 دولار</option></select>
          <select style="visibility: hidden" id="quantitySelect"></select>
        </div>
      <div id="paypal-button-container"></div>
      </div>
    </div>
  • The second problem is that i was forced to send the payment link to the customer, so i entered the link into the sent email to the customer, but when he tries to click that link from Gmail, it shows him that script project isn’t available, although if we open that ink in any browser it works correctly, the button code I’ve used inside Html email message is as the following:
<form class="paypal_form" style="position: relative; text-align: center">
<h2 style="text-align: right;"><span style="color: #800180;">طريقة الدفع الالكتروني </span>
</h2>
    <div style="text-align: center; width: 90%;">
    <h3> للدخول الى صفحة الدفع الالكتروني، اضغط الزر التالي</h3>
  
  
  
    <a href="https://script.google.com/macros/s/AKfycbx9WPk-wrWwVjtoF9PBZPu49clWxQVbBm8IYEcohcKbtGuEuOLzr1zVBaoHsbcWxffW/exec" style="margin-left: 0; margin-right: 0;"><img type="button" alt="استخدام الدفع الالكتروني عبر الـ PayPal أو البطاقة" border="0" data-original-height="447" data-original-width="943" height="152" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKUBxftQyvvUlUTw-TelW_uvCPP0-N6jOj3dZ0iX6d-w8qG0-Ztp0IgUeCpEwcTDO-xf33mfWPe-Am8hrM9HuWilDsgX2D1CNrN-rdUiWlqN93uP0QGYs1nmMMWVqGAaXW3dITTMk52k6os7ioWbsyDhDF8wlwMpZHZTo04wwvjr5Wf25m65kLKLGB/w320-h152/IMG_20230412_000608.jpg" title="استخدام الدفع الالكتروني عبر الـ PayPal أو البطاقة" width="320" /></a>
    </br>
   <p>إذا لم ينجح الدخول معك بالأزرار العلوية ، اضغط الزر التالي</p>
   <div style="text-align: center;"><a href="https://script.google.com/macros/s/AKfycbx9WPk-wrWwVjtoF9PBZPu49clWxQVbBm8IYEcohcKbtGuEuOLzr1zVBaoHsbcWxffW/exec" rel="nofollow" relf="noreferrer" style="text-align: center;" target="new_tab"><input aba02="" id="btn" onmouseout="this.style.backgroundColor=" onmouseover="this.style.backgroundColor=" style="background-color: #2aba02; border-bottom-width: 1px; border-color: rgb(213, 213, 213); border-left-width: 1px; border-radius: 46px; border-right-width: 1px; border-top-width: 0px; border-width: 0px 1px 1px; color: black; cursor: pointer; margin-bottom: 5px; margin-left: 5px; margin-right: 5px; margin-top: 5px; margin: 5px; padding-bottom: 8px; padding-left: 8px; padding-right: 8px; padding-top: 8px; padding: 8px;" this.style.bordercolor="#d5d5d5" this.style.color="#000000" type="button" value="صفحة الدفع الالكتروني" /></a></div>
  
    </div>

<hr style="text-align: center; width: 90%;" />
</form>

Tried both things explained above then I’ve got error.

I am trying to pull one piece of an array out with Math.random to generate on my page, but it is saying unable to fetch [duplicate]

I am working on a class project, when I click the “zen” button, a random quote from the API should be pulled. Right now, I can see the array in my console.log, I am trying to pull out just one quote with the click of a button.

This is my code:

var zenUrl = 'https://type.fit/api/quotes'
var zenItem = zenUrl[Math.floor(Math.random()*zenUrl.length)]
function loadZen(){
fetch(zenItem)
    .then(response => response.json())

    .then (function(data){
    console.log(data)

    })

}

document.getElementById("zen").addEventListener("click", loadZen)

I’ve also tried this:

var zenUrl = 'https://type.fit/api/quotes'
var zenItem = Math.floor(Math.random()*zenUrl.length)
var newZenUrl = zenUrl[zenItem];
function loadZen(){

    fetch(newZenUrl)
    .then(response => response.json())

    .then (function(data){
        console.log(data)

    })
}

These are the error messages I’m getting:

script.js:71 GET file:///C:/ net::ERR_FAILED

Uncaught (in promise) TypeError: Failed to fetch
at HTMLButtonElement.loadZen (script.js:71:5)

for reference, line 71 is the fetch(newZenUrl) at the moment

I know I’m missing something for how to pull just one quote from it. Thank you in advance!
I am not finding my answer in other questions! It is not strictly a CORs issue, obviously the code is not working as well

How to define multiple handler for a single event on serverless?

I’ve a serverless function that accept N http events;

delivery:
    handler: src/DeliveryHandler.handler
    architecture: ${self:provider.architecture}
    events:
      - http:
          path: /deliveries/cancel
          method: post
          cors: true
          private: true
      - http:
          path: /deliveries/{id}
          method: get
          cors: true
          private: true

The solution that I came up was to use a switch on the default handler;

const handler = async (event) => {
    switch (event.resource) {
        case '/deliveries/cancel':
            return doSomething(event)
        case '/deliveries/{id}':
            return doSomethingElse(event)
        default:
            return Promise.reject(new Error('Not found'))
    }
}

Is it possible and if so, how can I define a different handler for each event so I can avoid the switch in a single handler?

Can’t use React link inside component with props

My React app has an Item component that should redirect users to the App component by clicking a button inside a react-router-dom Link component. I’ve followed lots of tutorials that have given clear examples of how to implement Link inside components that don’t pass props. My guts tell me that my Item component props might be causing the Cannot destructure property 'basename' of 'React__namespace.useContext(...)' as it is null.] error because running tests on Jest are only possible when Link is not present in the code.

What I tried

  • Moved the RouteSwitch code to index.js
  • Moved the scripts that live in the components to src
  • Double-checked that I followed the tutorials correctly
  • Saw if this reactjs – Uncaught TypeError StackOverFlow answer is related to my problem

Can anybody point out what I’m missing here please?

item.js

import { Link } from "react-router-dom";

const Item = ({info},{addCart}) => {

  return(
    <>
      <Link to="/" ><button>X</button></Link>
      <img src={info.pic} alt={info.title}></img>
      <h1>{info.title}</h1>
      <p>{info.description}</p>
      <button onClick={()=>{addCart(info)}}>Add</button>
    </>
  )
};

export default Item;

routeswitch.js

import React from "react";
import { BrowserRouter,Routes,Route } from "react-router-dom";
import App from "./App"

const RouteSwitch = () =>{
  return(
    <BrowserRouter>
      <Routes>
        <Route path="/" element={<App/>}/>
      </Routes>
    </BrowserRouter>
  );
}

export default RouteSwitch;

index.js

import React from 'react';
import ReactDOM from 'react-dom/client';
import RouteSwitch from "./routeswitch"
import './index.css';

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <RouteSwitch/>
  </React.StrictMode>
);

item.test.js

import React from 'react';
import { render, cleanup,screen, getByAltText} from '@testing-library/react';
import '@testing-library/jest-dom'
import userEvent from '@testing-library/user-event';
import Item from './item';

afterEach(cleanup);
const details = {pic: `a pic`, title:`a title`, description:`a description`}
const addCartMock =jest.fn(); 

test(`Content renders`,()=>{
  render(<Item info={details} addCart={addCartMock}/>);

  const image = screen.getByAltText(`${details.title}`);
  expect(image).toBeInTheDocument();
  expect(image).toHaveAttribute(`src`,`${details.pic}`);
  expect(screen.getByRole(`heading`, {name:details.title})).toBeInTheDocument();
  expect(screen.getByText(`${details.description}`)).toBeInTheDocument();
  expect(screen.getByRole(`button`, {name: `Add`})).toBeInTheDocument();
});

test(`Add button click event`,()=>{
  render(<Item info={details} addCart={addCartMock(details)}/>);

  userEvent.click(screen.getByRole(`button`), {name: `Add`});
  expect(addCartMock).toHaveBeenCalledWith(details);
});

corect way of using global variable to store image object

I am attempting to load an image file in 2 steps:

  1. select file from local computer using a FileUpload dialog, this calls a function where I need to store the image in a lobal variable
  2. after i store the image file in global variable use another function to upload image to backend.

What is the problem?
It seems like image file is not saved correctly in the global variable in the first function because when 2nd function is called later(by pressing a button) the global variable says is undefined(while debugging in vs code).

Below are the 2 functions in question and the global variable definition, setting and usage
const propreference = “reference1”;
var imageFile;

function addImageBtnFileChosen(event){
    imageFile = this.files[0]
    fileChosen.textContent = imageFile.name
}
function addPropertyImage(){
    resPostAddPropertyImage(propreference, imageFile)
}

Below is where the buttons where functions are called from
<div className={styles[‘button-container’]}>
Add Property Image

Add Image

As explained I tried saving the image file in the global variable imageFile within function addImageBtnFileChosen to then use later an send to backend within function addPropertyImage