Expo OSM Map implementation

I want to implement a MapView into expo where I am using OSM as a source for free. The main thing I want is the display of the housenumbers on the map.

I am currenty using react-native-maps but with that I cant use google maps on IOS for free, and even if I cant really do everything i want to.

Worldchain Transaction execution reverted

I’m trying to create a code that sends Worldcoin through Worldchain using a master wallet that pays for the gas, but when I try to send it, I get an error. I’m not sure what’s causing it; this is the error:

(console.log for debug)
ETH balance in wei for paying fees: 453514483975334
Formatted ETH balance for paying fees: 0.000453514483975334
Current Worldcoin balance: 1.0 WLD
Data to transfer:
{
  "from": "0xD6C7481C875fBb69a07eC4e39Df6c690ABC69568",
  "to": "0x56Ef28F9F0c856ce37AC10A60B9Fd1152A45875F",
  "value": 1000000000000000000n,
  "gas": 500000,
  "deadline": 1731459014,
  "data": "0xa9059cbb0000000000000000000000009ab93ebb695c119efd89a0e44919fb0d6aba2dc10000000000000000000000000000000000000000000000000de0b6b3a7640000"
}
Transaction sent: 0xc32c9a7ddcfd29c84915ca77e8df885a70998d216725d5c48e435506e5d12161

Error: transaction execution reverted (action="sendTransaction", data=null, reason=null, invocation=null, revert=null, transaction={ "data": "", "from": "0x54c5c9FbFe99a6282dE10201b1c3254EAe8C9776", "to": "0x56Ef28F9F0c856ce37AC10A60B9Fd1152A45875F" }, receipt={ "_type": "TransactionReceipt", "blobGasPrice": null, "blobGasUsed": null, "blockHash": "0x05fe89a7c818f1d53c955eaeeb2879dc271457a3e6d1ca1373c82b6bb367c775", "blockNumber": 6059890, "contractAddress": null, "cumulativeGasUsed": "112698", "from": "0x54c5c9FbFe99a6282dE10201b1c3254EAe8C9776", "gasPrice": "1000264", "gasUsed": "25695", "hash": "0xc32c9a7ddcfd29c84915ca77e8df885a70998d216725d5c48e435506e5d12161", "index": 2, "logs": [  ], "logsBloom": "0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000", "root": null, "status": 0, "to": "0x56Ef28F9F0c856ce37AC10A60B9Fd1152A45875F" }, code=CALL_EXCEPTION, version=6.13.4)
    at makeError (/home/th3dgd/Dev/worldcoin-to-ars/nodo/node_modules/ethers/lib.commonjs/utils/errors.js:129:21)
    at assert (/home/th3dgd/Dev/worldcoin-to-ars/nodo/node_modules/ethers/lib.commonjs/utils/errors.js:149:15)
    at checkReceipt (/home/th3dgd/Dev/worldcoin-to-ars/nodo/node_modules/ethers/lib.commonjs/providers/provider.js:1127:35)
    at JsonRpcProvider.txListener (/home/th3dgd/Dev/worldcoin-to-ars/nodo/node_modules/ethers/lib.commonjs/providers/provider.js:1173:33)
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5) {
  code: 'CALL_EXCEPTION',
  action: 'sendTransaction',
  data: null,
  reason: null,
  invocation: null,
  revert: null,
  transaction: {
    to: '0x56Ef28F9F0c856ce37AC10A60B9Fd1152A45875F',
    from: '0x54c5c9FbFe99a6282dE10201b1c3254EAe8C9776',
    data: ''
  },
  receipt: TransactionReceipt {
    provider: JsonRpcProvider {},
    to: '0x56Ef28F9F0c856ce37AC10A60B9Fd1152A45875F',
    from: '0x54c5c9FbFe99a6282dE10201b1c3254EAe8C9776',
    contractAddress: null,
    hash: '0xc32c9a7ddcfd29c84915ca77e8df885a70998d216725d5c48e435506e5d12161',
    index: 2,
    blockHash: '0x05fe89a7c818f1d53c955eaeeb2879dc271457a3e6d1ca1373c82b6bb367c775',
    blockNumber: 6059890,
    logsBloom: '0x00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000',
    gasUsed: 25695n,
    blobGasUsed: null,
    cumulativeGasUsed: 112698n,
    gasPrice: 1000264n,
    blobGasPrice: null,
    type: 2,
    status: 0,
    root: undefined
  },
  shortMessage: 'transaction execution reverted'
}

Code that is generating the error:

const { ethers } = pkg;
import dotenv from 'dotenv';
import fs from 'fs';
import path from 'path';

dotenv.config();

const forwarderArtifact = JSON.parse(
    fs.readFileSync(path.resolve('./artifacts/contracts/ERC2771Forwarder.sol/ERC2771Forwarder.json'), 'utf-8')
);

class WorldChain {
    async transfer(address, amount, privateKeyForGas, privateKeyForWLD) {
        try {
            const RPC_URL = process.env.ETHEREUM_RPC_URL;
            const CONTRACT_ADDRESS_WORLDCHAIN = "0x2cFc85d8E48F8EAB294be644d9E25C3030863003";
            const CONTRACT_ADDRESS_FORWARDER = "0x56Ef28F9F0c856ce37AC10A60B9Fd1152A45875F";
            const ABI_TRANSFER = [
                "function balanceOf(address owner) view returns (uint256)",
                "function decimals() view returns (uint8)",
                "function transfer(address to, uint256 amount) public returns (bool)"
            ];
    
            const providerForGas = new ethers.JsonRpcProvider(RPC_URL);
            const walletForGas = new ethers.Wallet(privateKeyForGas, providerForGas);

            const providerForWLD = new ethers.JsonRpcProvider(RPC_URL);
            const walletForWLD = new ethers.Wallet(privateKeyForWLD, providerForWLD);

            const forwarder = new ethers.Contract(CONTRACT_ADDRESS_FORWARDER, forwarderArtifact.abi, walletForGas);

            const wldContract = new ethers.Contract(CONTRACT_ADDRESS_WORLDCHAIN, ABI_TRANSFER, walletForWLD);

            const balance = await wldContract.balanceOf(walletForWLD.address);
            const decimals = await wldContract.decimals();

            const ethBalanceForGas = await providerForGas.getBalance(walletForGas.address);
            console.log("Saldo de ETH en wei para pagar comisiones:", ethBalanceForGas.toString());
            const formattedEthBalanceForGas = ethers.formatUnits(ethBalanceForGas, "ether");
            console.log("Saldo de ETH formateado para pagar comisiones:", formattedEthBalanceForGas);

            const formattedBalance = ethers.formatUnits(balance, decimals).replace('.', ',');
            console.log(`Saldo actual de Worldcoin: ${formattedBalance} WLD`);

            const amountInWei = ethers.parseUnits(amount, decimals);
            const deadline = Math.floor(Date.now() / 1000) + 3600;
            const forwardRequestData = {
                from: walletForWLD.address,
                to: CONTRACT_ADDRESS_FORWARDER,
                value: ethers.parseEther(amount),
                gas: 500000,
                deadline: deadline,
                data: wldContract.interface.encodeFunctionData('transfer', [address, amountInWei]),
            };

            console.log("Datos para transferir:", forwardRequestData);

            const domain = {
                name: 'ERC2771Forwarder',
                version: '1',
                chainId: 480,
                verifyingContract: CONTRACT_ADDRESS_FORWARDER
            };

            const types = {
                ForwardRequest: [
                    { name: 'from', type: 'address' },
                    { name: 'to', type: 'address' },
                    { name: 'value', type: 'uint256' },
                    { name: 'gas', type: 'uint256' },
                    { name: 'deadline', type: 'uint256' },
                    { name: 'data', type: 'bytes' },
                ]
            };

            const signature = await walletForWLD.signTypedData(domain, types, forwardRequestData);

            forwardRequestData.signature = signature;

            console.log("Firma para transferir:", forwardRequestData.signature);

            const tx = await forwarder.execute(forwardRequestData, {
                /*value: amountInWei,*/
                gasLimit: (500000).toString(),
            });
            console.log(`Transacción enviada: ${tx.hash}`);

            await tx.wait();
            console.log(`Transacción recibida: ${tx.hash}`);

            return {
                status: 'success',
                transactionHash: tx.hash
            };
        } catch (error) {
            console.error(error);
            return {
                status: 'error',
                error: error.message
            };
        }
    }
}

export default new WorldChain();

I am using the OpenZeppelin ERC2771Forwarder contracts to make the main wallet pay for the gas and the user’s private key pay for the WLD.

I tried deploying the contract on the Worldchain network; Worldscan indicates that it was deployed without issues. However, when I attempt to transfer, I get the previously mentioned error. The main wallet has ETH (which pays for the gas), and the user’s wallet (which transfers the WLD) also has tokens.

Plamistry Project [closed]

“Amazing Palmistry” Website

Three Important parts.

  1. USER

  2. EXPERT (Astrologers)

  3. ADMIN

  4. USER: USER is client who come to website or app to take service.

  5. EXPERT: Are Astrologers who provide their service and takes fees.

  6. ADMIN: Administrator of website. Admins provide website as platform for User and Experts to interact. Admin takes commission from Experts Income to provide this platform.

USER:
 Login Module (Sign In, Sign Up and Forgot Password)
 Welcome Email should send after successful signup.
 Multiple User

EXPERT:
 Login Separate Link for Expert
 Login Module (Sign in, Forgot password)
 Expert signup will do by Admin
 Email will send after Admin Signup for Expert.
 Limited Experts
ADMIN:
 Login separate link for Admin
 Login Module (Sign in and Forgot password)
 Only One Admin

Note: Study astrology websites which provides Experts on their Platform

i want help in this project

Don’t show the success message by using toastr.js after deleting the category with the sweetalert2.js, just showing the error: toastr is not defined

I want to show a successful delete message by using toastr.js when any user will click on the delete button, first it will show alert, so I use sweetalert2.js, but after confirming delete in sweetalert2.js, it is only deleting the category but it is not showing the success message in toastr.js rather than showing the error: Uncaught ReferenceError: toastr is not defined

In CategoryController:

#region API CALLS

// https://localhost:7230/Admin/Category/getall => to get all the propoerties of Category in json for using in datatable
[HttpGet]
public IActionResult GetAll()
{
    List<Category> objCategoryList = _unitOfWork.Category.GetAll().ToList();
    return Json(new { data = objCategoryList });
}

[HttpDelete]
public IActionResult Delete(Guid? id)
{
    if (!id.HasValue)
    {
        return Json(new { success = false, message = "Invalid ID" });
    }

    var categoryToBeDeleted = _unitOfWork.Category.Get(category => category.Id == id.Value);

    if (categoryToBeDeleted == null)
    {
        TempData["error"] = "Category not found or already deleted.";
        return Json(new { success = false, message = "Error while deleting" });
    }

    _unitOfWork.Category.Remove(categoryToBeDeleted);
    _unitOfWork.Save();

    return Json(new { success = true, message = "Category deleted successfully" });
}

#endregion

In Index.cshtml:

@model IEnumerable<Category>

<div class="container mt-4">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">Categories Data</h5>
            <a asp-controller="Category" asp-action="Upsert" class="btn btn-primary" style="box-shadow: none" data-bs-toggle="modal" data-bs-target="#categoryModal">
                <i class="fas fa-plus-circle"></i> &nbsp;Add Category
            </a>

            <!-- Modal for Create/Update Category -->
            <div class="modal fade" id="categoryModal" tabindex="-1" aria-labelledby="categoryModalLabel" aria-hidden="true">
                <div class="modal-dialog modal-dialog-centered" role="document">
                    <div class="modal-content">
                        <form asp-controller="Category" asp-action="Upsert" method="post">
                            <div class="modal-header">
                                <h5 class="modal-title" id="categoryModalLabel">
                                    @if (TempData["CategoryId"] != null)
                                    {
                                        <span>Edit Category</span>
                                    }
                                    else
                                    {
                                        <span>Add New Category</span>
                                    }
                                </h5>
                                <button type="button" style="box-shadow: none" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                            </div>
                            <div class="modal-body">
                                <!-- Hidden Field for Id -->
                                <input type="hidden" id="Id" name="Id" value="@(TempData["CategoryId"] ?? Guid.Empty.ToString())" />


                                <div class="mb-3">
                                    <label for="CategoryName" class="form-label fw-bold ms-1">Category Name</label>
                                    <input type="text" class="form-control" id="CategoryName" name="CategoryName"
                                           value="@TempData["CategoryName"]" required placeholder="Category Name" />
                                </div>
                            </div>
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Dismiss</button>
                                <button type="submit" class="btn btn-success">Save</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="card-body">
            <table id="tableData" class="table table-bordered table-striped" style="width: 100%">
                <thead class="thead-light">
                    <tr>
                        <th>S/N</th>
                        <th>Category Name</th>
                        <th>Created At</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    
                </tbody>
            </table>
        </div>
    </div>
</div>

@section Scripts {
    <script src="~/js/category.js"></script>
}

In category.js:

$(function () {
    loadDataTable();
});

var dataTable;

function loadDataTable() {

    dataTable = $('#tableData').DataTable({
        "ajax": { url: '/admin/category/getall' },
        "columns": [
            {
                "data": null, // Serial number column
                "render": function (data, type, row, meta) {
                    return meta.row + 1; // Display row index + 1 for serial number
                },
                "width": "10%"
            },
            { data: 'categoryName', "width": "30%" },
            { data: 'createdAt', "width": "25%" },
            //{ data: 'id', "width": "15%" },
            {
                data: 'id',
                "render": function (data) {
                    return `<div class="d-flex justify-content-center">
                                <div class="w-75 btn-group" role="group">
                                    <a href="/admin/category/upsert?id=${data}"
                                       class="btn btn-warning text-white me-2" style="box-shadow:none" data-bs-toggle="modal" data-bs-target="#categoryModal">
                                       <i class="fas fa-edit"></i> Edit
                                    </a>
                                    <a onClick="Delete('/admin/category/delete/${data}')" 
                                       class="btn btn-danger ms-2" style="box-shadow:none">
                                       <i class="fas fa-trash"></i> Delete
                                    </a>
                                </div>
                            </div>
                            `
                },
                "width": "35%"
            }
        ],
        "columnDefs": [
            { "className": "dt-left", "targets": 0 } // Apply left alignment to the serial number column (first column)
        ]
    });
}

function Delete(url) {
    Swal.fire({
        title: "Are you sure?",
        text: "You won't be able to revert this!",
        icon: "warning",
        showCancelButton: true,
        confirmButtonColor: "#3085d6",
        cancelButtonColor: "#d33",
        confirmButtonText: "Yes, delete it!"
    }).then((result) => {
        if (result.isConfirmed) {
            $.ajax({
                url: url,
                type: 'DELETE',
                success: function (data) {
                    /*to reload the page after delete*/
                    dataTable.ajax.reload();
                    //Error: Uncaught ReferenceError: toastr is not defined                          
                    toastr.success(data.message);
                }
            });
        }
    });


}

Error:

Uncaught ReferenceError: toastr is not defined
    at Object.success (category.js:65:21)
    at c (jquery.min.js:2:28327)
    at Object.fireWith [as resolveWith] (jquery.min.js:2:29072)
    at l (jquery.min.js:2:79901)
    at XMLHttpRequest.<anonymous> (jquery.min.js:2:82355)

How to display image from Strapi collection content

Im having trouble receiving the media attribute of my content in my collection from strapi on my 11ty project. Every time I try something with trying to recieve my image data it breaks my page.

Strapi collection

Below is a the portion of my eleventy.config.js file that is working on this collection:

// Cardio Exercises Collection
 eleventyConfig.addCollection("cardioExercises", async function() {
  try {
    const response = await axios.get("http://127.0.0.1:1337/api/exercises?filters[workout][Slug][$eq]=cardio", { timeout: 5000 });
    console.log("Fetched Cardio Exercises Data (Response):", response.data);

    if (!response.data.data || response.data.data.length === 0) {
      console.error("Cardio exercises data missing or empty:", response.data);
      return [];
    }

    const imageUrl = attributes?.Image?.data?.attributes?.url
  ? `http://localhost:1337${attributes.Image.data.attributes.url}`
  : null;
    return response.data.data.map((exercise) => {
      return {
        id: exercise.id,
        name: exercise.Name,
        exerciseSlug: exercise.Slug,
        description: exercise.Description?.[0]?.children?.[0]?.text || "No description available",
        image: imageUrl,
      };
    });
  } catch (error) {
    console.error("Failed to fetch strength training exercises from Strapi:", error);
    return [];
  }
});

and here is my page that displays the content of the collection :

---
layout: layout.hbs
pagination:
  data: collections.cardioExercises
  size: 1
  alias: exercise
permalink: "/workouts/cardio/exercises/{{ exercise.exerciseSlug }}/index.html"
---
<section class="exercise-detail-section">
  <div class="container exercise-container">
    
    <!-- Image Section -->
    <div class="exercise-image">
      <!-- Dynamically rendering images based on the exercise image field from Strapi -->
      {{#if exercise.image }}
        <img src="{{ exercise.image }}" alt="{{ exercise.name }} Exercise Image">
      {{else}}
        <img src="/css/default-exercise.png" alt="Default Exercise Image">
      {{/if}}
    </div>

    <!-- Text Section: Exercise Name and Description -->
    <div class="exercise-content">
      <div class="header">
        <h1>{{ exercise.name }}</h1> <!-- Exercise name -->
        <p>{{ exercise.description }}</p> <!-- Exercise description -->
      </div>

      <!-- Back Button to navigate back to the Cardio page -->
      <div class="back-button">
        <a href="/" class="button">
          Back to Home  <!-- Button text -->
          <span class="span"></span> <!-- Span for hover effect -->
        </a>
      </div>
    </div>

  </div>
</section>

Not sure if I’m doing this correctly…

Help will be appreciated!

How to correctly pass information through event listener?

I have a flask/javascript web app and I am having trouble with passing information through the event listener.

Here is my code:

fetch('/get_data')
  .then(response => response.json())
  .then(data => {
    const toggleValue1 = document.getElementById("toggleValue1");
    const toggleValue2 = document.getElementById("toggleValue2");

    // Initial render with both values displayed
    renderChart(data, toggleValue1.checked, toggleValue2.checked);

    // Update chart when checkboxes change
    toggleValue1.addEventListener("change", () => renderChart(data, toggleValue1.checked, toggleValue2.checked));
    toggleValue2.addEventListener("change", () => renderChart(data, toggleValue1.checked, toggleValue2.checked));
  })
  .catch(error => console.error("Error fetching data:", error));

/get_data is a flask endpoint defined like this:

@app.route('/get_data')
def timeseries():
    # Sample time series data
    data = [
        {"date": "2024-01-01", "value1": 10, "value2": 15},
        {"date": "2024-02-01", "value1": 20, "value2": 10},
        {"date": "2024-03-01", "value1": 15, "value2": 20},
        {"date": "2024-04-01", "value1": 30, "value2": 25},
        {"date": "2024-05-01", "value1": 25, "value2": 30},
    ]
    return jsonify(data)

I printed out the values of data and found that in the initial call to renderChart() and after the initial call to renderChart(), everything is correct. However, after a checkbox is toggled and the event listener calls renderChart(), data has null values for date and looks like this:

[
        {"date": null, "value1": 10, "value2": 15},
        {"date": null, "value1": 20, "value2": 10},
        {"date": null, "value1": 15, "value2": 20},
        {"date": null, "value1": 30, "value2": 25},
        {"date": null, "value1": 25, "value2": 30},
    ]

I can’t figure out why the dates are being turned to null. Does anyone know why this might be?

Here is my complete code:

visualization_app.py

from flask import Flask, render_template, jsonify

app = Flask(__name__)

@app.route('/data_visualizations', methods=["GET", "POST"])
def get_data_visualizations():
    return render_template('data_visualizations.html')


@app.route('/get_data')
def timeseries():
    # Sample time series data
    data = [
        {"date": "2024-01-01", "value1": 10, "value2": 15},
        {"date": "2024-02-01", "value1": 20, "value2": 10},
        {"date": "2024-03-01", "value1": 15, "value2": 20},
        {"date": "2024-04-01", "value1": 30, "value2": 25},
        {"date": "2024-05-01", "value1": 25, "value2": 30},
    ]
    return jsonify(data)

if __name__ == '__main__':
    app.run(host="0.0.0.0", port=8080, debug=True)
    #app.run(ssl_context=('cert.pem', 'key.pem'))

script.js

// Chart area and margins
const margin = { top: 20, right: 30, bottom: 50, left: 60 };
const width = 800 - margin.left - margin.right;
const height = 500 - margin.top - margin.bottom;

const svg = d3.select("#chart")
  .append("svg")
  .attr("width", width + margin.left + margin.right)
  .attr("height", height + margin.top + margin.bottom)
  .append("g")
  .attr("transform", `translate(${margin.left},${margin.top})`);

const color = { value1: "blue", value2: "orange" };

// Scales and axes
const x = d3.scaleTime().range([0, width]);
const y = d3.scaleLinear().range([height, 0]);

const xAxisGroup = svg.append("g")
  .attr("class", "x-axis")
  .attr("transform", `translate(0,${height})`);

const yAxisGroup = svg.append("g")
  .attr("class", "y-axis");

// Line generators
const lineValue1 = d3.line()
  .x(d => x(d.date))
  .y(d => y(d.value1));

const lineValue2 = d3.line()
  .x(d => x(d.date))
  .y(d => y(d.value2));

// Function to render the chart
function renderChart(data, displayValue1, displayValue2) {

  console.log("Data 1: ", data)

  // Parse dates and set up data bounds
  const parseTime = d3.timeParse("%Y-%m-%d");
  data.forEach(d => {
    d.date = parseTime(d.date);
    d.value1 = +d.value1;
    d.value2 = +d.value2;
  });

  console.log("Data 2: ", data)

  // Set domains for scales
  x.domain(d3.extent(data, d => d.date));
  y.domain([0, d3.max(data, d => Math.max(d.value1, d.value2))]);

  // Draw the axes
  xAxisGroup.call(d3.axisBottom(x));
  yAxisGroup.call(d3.axisLeft(y));

  // Clear existing lines
  svg.selectAll(".line-value1").remove();
  svg.selectAll(".line-value2").remove();

  // Draw lines based on checkbox selections
  if (displayValue1) {
    svg.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", color.value1)
      .attr("stroke-width", 2)
      .attr("class", "line-value1")
      .attr("d", lineValue1);
  }

  if (displayValue2) {
    svg.append("path")
      .datum(data)
      .attr("fill", "none")
      .attr("stroke", color.value2)
      .attr("stroke-width", 2)
      .attr("class", "line-value2")
      .attr("d", lineValue2);
  }

  console.log("Data 3: ", data)
}

// Apply zoom behavior to the SVG container
svg.on(".zoom", null);

// Fetch data from the Flask API and initialize the chart
fetch('/get_data')
  .then(response => response.json())
  .then(data => {
    const toggleValue1 = document.getElementById("toggleValue1");
    const toggleValue2 = document.getElementById("toggleValue2");

    // Initial render with both values displayed
    renderChart(data, toggleValue1.checked, toggleValue2.checked);

    console.log("Data 4: ", data)

    // Update chart when checkboxes change
    toggleValue1.addEventListener("change", () => renderChart(data, toggleValue1.checked, toggleValue2.checked));
    toggleValue2.addEventListener("change", () => renderChart(data, toggleValue1.checked, toggleValue2.checked));
  })
  .catch(error => console.error("Error fetching data:", error));

data_visualizations.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Time Series Line Graph with Toggle</title>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
  <div class="container">
    <h2>Time Series Data</h2>
    <div class="controls">
      <label><input type="checkbox" id="toggleValue1" checked> Value 1</label>
      <label><input type="checkbox" id="toggleValue2" checked> Value 2</label>
    </div>
    <div id="chart"></div>
  </div>

  <script src="{{ url_for('static', filename='js/script.js') }}"></script>
</body>
</html>

Heroku and Mailgun

I’m facing several problems with my API and WEB in production on Heroku. They have a unique system for reading the directory of things and this is returning several errors.

I have the current application in deploy, only the backend running:
https://github.com/Danmendua/disney-hub-fullstack

However, when sending emails to register the account, the following error is returning:

2024-11-12T17:18:13.064738+00:00 app[web.1]: [31merror[39m: Error to send email: Unauthorized {"details":"Forbidden","status":401,"timestamp":"2024-11-12T17:18:13.064Z","type":"MailgunAPIError"}

I thought it was the environment variables that contain the “path”, but I already tried to deal with it and I’m still getting the 401 (Unauthorized) error. So I tried to put Heroku’s IP range which, according to AWS IP Ranges (https://ip-ranges.amazonaws.com/ip-ranges.json) and Heroku’s IP, the ip should be from ” East-1″, so I added all the main ips in Mailgun:

3.224.0.0/12
18.232.0.0/14
34.192.0.0/12
52.0.0.0/15
54.144.0.0/14
54.156.0.0/14

Currently my API is running on “apidisney.mydomain.com” but Mailgun only allows me to register 1 domain and it is on “mydomain.com”, could this be the problem?

I’ve already tried registering the main IPs in the AWS range, I’ve also changed the API key and I’ve tried generating a new one, but it doesn’t work.

Filter a table using multi-checkboxes across multiple columns

I have a table that i need to filter based on multiple columns, the example i have uses checkboxes to filter on 5 columns, some of the columns are hidden and are not displayed in the table but can still be filtered on.

Example of how I need it to work:

  • all rows will show as a default if no filters are selected, currently the table is blank by default, and you need to check the boxes to show rows.

  • if MONTH filter ‘MAR’ is checked, the 4 rows that meet that criteria will show, I then add the LANGUAGE filter ‘French’ and ‘Spanish’ and the only the 3 rows that meet both filter criteria will show. I then uncheck the LANGUAGE filters and check the HOUSE filter ‘None’ only the 1 row that meets the new criteria is shown.

There are a few problems in my current attempt like the filter categories are not correctly ANDed together, so when ‘Ron’ and ‘Mar’ are selected the results include other Names that do not match ‘Ron’. Another issue it that when the filters are cleared, many rows that were hidden due to the previous filter do not become visible.

Usable example is here:
https://codepen.io/ashleigh-leader/pen/BaXvOqO

function filter(event, filterCol) {
  let element = event.target;
  let condt1 = document.getElementsByClassName(filterCol);
  for (let i = 0; i < condt1.length; i++) {
    if (condt1[i].innerHTML.toLowerCase() == element.value.toLowerCase()) {
      if (element.checked == true) {
        condt1[i].parentElement.style = ""
      } else {
        condt1[i].parentElement.style = "display:none"
      }
    }
  }
}

document.querySelectorAll('.option1')
  .forEach(input => input.addEventListener('input', ()=>filter(event,"check1")));
  
  
document.querySelectorAll('.option2')
  .forEach(input => input.addEventListener('input', ()=>filter(event,"check2")));
  
  
document.querySelectorAll('.option3')
  .forEach(input => input.addEventListener('input', ()=>filter(event,"check3")));
  
  
document.querySelectorAll('.option4')
  .forEach(input => input.addEventListener('input', ()=>filter(event,"check4")));
  
  
document.querySelectorAll('.option5')
  .forEach(input => input.addEventListener('input', ()=>filter(event,"check5")));
#myTable {
border-collapse: collapse;
width: 100%; 
border: 1px solid #ddd;
font-size: 14px;
margin: 5px;
}
  
#myTable th, #myTable td {
text-align: left;
padding: 12px;
}
  
#myTable tr {
border-bottom: 1px solid #ddd;
color: #58585B;
font-family: "museo-sans-rounded";
font-size: 14px;
font-weight: 300px;
}
  
#myTable tr.header {
background-color: #862B90;
background-size: contain;
color: white;
font-family: "museo-sans-rounded";
font-size: 16px;
font-weight: 300px;
}

#myTable tr:hover {
font-family: "museo-sans-rounded";
font-size: 16px;
font-weight: 300px;
}

#myTable td.month-pill {
align-self: center;
background-color: #FFC52E;
border: none;
color: #FFC52E;
padding: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
margin: 4px;
border-radius: 16px;
}

#myTable td.month {
color: #FFC52E;
align-items: center;
}

.filter-container {
display: flex;
flex-direction: column;
align-items: flex-start;
width: 20%;
}

.filter-title {
font-family: "museo-sans-rounded";
color: #58585B !important;
font-size: 14px;
font-weight: 500px;
line-height: 1.25;
text-align: left;
}

.filter-option {
font-family: "museo-sans-rounded";
color: #58585B !important;
font-size: 13px;
font-weight: 300px;
line-height: 1.5;
text-align: left;
}

.checkbox.style-b {
display: inline-block;
position: relative;
padding-left: 30px;
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
margin: 0;
padding-top: 4px;
}

.checkbox.style-b input {
position: absolute;
opacity: 0;
cursor: pointer;
height: 0;
width: 0;
}

.checkbox.style-b input:checked ~ .checkbox__checkmark {
background-color: #fff;
}

.checkbox.style-b input:checked ~ .checkbox__checkmark:after {
opacity: 1;
}

.checkbox.style-b:hover input ~ .checkbox__checkmark {
background-color: #eee;
}

.checkbox.style-b:hover input:checked ~ .checkbox__checkmark {
background-color: #fff;
}

.checkbox.style-b .checkbox__checkmark {
position: absolute;
top: 3px;
left: 0;
height: 20px;
width: 20px;
background-color: #fff;
border: 1px solid #8F8F8F;
transition: background-color 0.25s ease;
border-radius: 4px;
}

.checkbox.style-b .checkbox__checkmark:after {
content: "";
position: absolute;
left: 8px;
top: 3px;
width: 7px;
height: 12px;
border: solid #862B90;
border-width: 0 3px 3px 0;
transform: rotate(45deg);
opacity: 0;
transition: opacity 0.25s ease;
}

.checkbox.style-b .checkbox__body {
color: #212529;
font-feature-settings: 'clig' off, 'liga' off;
font-size: 14px;
font-style: normal;
font-weight: 400;
line-height: 20px;
}
   
<div id="input">
<div class="filter-container" style="display: flex; flex-direction: column; align-items: flex-start; width: 20%;">
<p>CHECKBOX FILTERS</p>
<p class="filter-title">ID</p>
  <lable><input class="option1" type="checkbox" value="01">01</label>
  <lable><input class="option1" type="checkbox" value="02">02</label>
  <lable><input class="option1" type="checkbox" value="03">03</label>
  <lable><input class="option1" type="checkbox" value="04">04</label>
<p class="filter-title">Name</p>
  <lable><input class="option2" type="checkbox" value="Harry">Harry</label>
  <lable><input class="option2" type="checkbox" value="Ron">Ron</label>
  <lable><input class="option2" type="checkbox" value="Malfoy">Malfoy</label>
  <lable><input class="option2" type="checkbox" value="Hagrid">Hagrid</label>
<p class="filter-title">Month</p>
  <lable><input class="option3" type="checkbox" value="JAN">JAN</label>
  <lable><input class="option3" type="checkbox" value="FEB">FEB</label>
  <lable><input class="option3" type="checkbox" value="MAR">MAR</label>
  <lable><input class="option3" type="checkbox" value="APR">APR</label>
  <lable><input class="option3" type="checkbox" value="MAY">MAY</label>
  <lable><input class="option3" type="checkbox" value="JUN">JUN</label>
<p class="filter-title">House</p>
  <lable><input class="option4" type="checkbox" value="Gryffindor">Gryffindor</label>
  <lable><input class="option4" type="checkbox" value="Slytherin">Slytherin</label>
  <lable><input class="option4" type="checkbox" value="None">None</label>
 <p class="filter-title">Language</p>
  <lable><input class="option4" type="checkbox" value="English">English</label>
  <lable><input class="option4" type="checkbox" value="Spanish">Spanish</label>
  <lable><input class="option4" type="checkbox" value="French">French</label>
</div>              
<p>FILTER TABLE</p>
  
<table id="myTable" class="myTable">
  <thead>
    <tr class="header">
    <th style="width: 3%; text-align: left; padding: 12px;">ID</th>
    <th style="width: 37%; text-align: left; padding: 12px;">Name</th>
    <th style="width: 5%; text-align: center; padding: 12px;">JAN</th>
    <th style="width: 5%; text-align: center; padding: 12px;">FEB</th>
    <th style="width: 5%; text-align: center; padding: 12px;">MAR</th>
    <th style="width: 5%; text-align: center; padding: 12px;">APR</th>
    <th style="width: 5%; text-align: center; padding: 12px;">MAY</th>
    <th style="width: 5%; text-align: center; padding: 12px;">JUN</th>
   </thead>
   <tbody>
      <tr>
        <td class="check1">01</td>
        <td class="check2">Harry</td>
        <td class="check3"></td>
        <td class="check3">FEB</td>
        <td class="check3">MAR</td>
        <td class="check3">APR</td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check4" style="display: none;">Griffindor</td>
        <td class="check5" style="display: none;">Spanish</td>
        <td class="check5" style="display: none;">French</td>
      </tr>
      <tr>
        <td class="check1">01</td>
        <td class="check2">Harry</td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check3">APR</td>
        <td class="check3">MAY</td>
        <td class="check3">JUN</td>
        <td class="check4" style="display: none;">Griffindor</td>
        <td class="check5" style="display: none;">Engligh</td>
        <td class="check5" style="display: none;">Spanish</td>
      </tr>
      <tr>
        <td class="check1">02</td>
        <td class="check2">Ron</td>
        <td class="check3">JAN</td>
        <td class="check3"></td>
        <td class="check3">MAR</td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check4" style="display: none;">Spanish</td>
      </tr>
      <tr>
        <td class="check1">03</td>
        <td class="check2">Hagrid</td>
        <td class="check3">JAN</td>
        <td class="check3">FEB</td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check3">JUN</td>
        <td class="check4" style="display: none;">None</td>
        <td class="check5" style="display: none;">Engligh</td>
      </tr>
      <tr>
        <td class="check1">03</td>
        <td class="check2">Hagrid</td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check3">MAR</td>
        <td class="check3">APR</td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check4" style="display: none;">None</td>
        <td class="check5" style="display: none;">Engligh</td>
      </tr>
      <tr>
        <td class="check1">04</td>
        <td class="check2">Malfoy</td>
        <td class="check3">JAN</td>
        <td class="check3">FEB</td>
        <td class="check3">MAR</td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check3"></td>
        <td class="check4" style="display: none;">Slytherin</td>
        <td class="check5" style="display: none;">Engligh</td>
        <td class="check5" style="display: none;">Spanish</td>
        <td class="check5" style="display: none;">French</td>
      </tr>
    </tbody>
</table>
</div>

Replace variables with values from a database in a JavaScript string containing HTML

I have a string received from an editor, which includes HTML tags, like this:

const htmlString = "<div>Account <span contenteditable="false">{{account}}</span></div>. 
<div>Hello <span contenteditable="false">{{hello}}</span></div>"

In this content, there are two variables with the format {{account}} and {{hello}}.

In my database, I store variable data in the format { key: string, value: string, isDefault: boolean }:

[
   { "key" : "account", "value" : "", "isDefault" : true, },
   { "key" : "hello", "value" : "Hello everyone", "isDefault" : false }
]

First, I use a function to remove HTML tags:

const blockTags = /<(div|h1|h2|h3|h4|h5|h6|p|ul|ol|li|br)[^>]*>/gi;
const inlineTags = /</?(span|a|strong|em|b|i|u)[^>]*>/gi;

let content = htmlString.replace(blockTags, 'n').replace(/</(div|h1|h2|h3|h4|h5|h6|p)>/gi, 'n');
content = content.replace(inlineTags, '');
content = content.replace(/<[^>]+>/g, '');
content = content.replace(/ns*n/g, 'n').trim();

Then, I extract the variables:

const variables = (content.match(/{{(.*?)}}/gi) || []).map((item) => item.replace(/{{|}}/g, ''));

Finally, I use a function to replace all variables with their corresponding values from the database, if variable is default (isDefault = true), i replace by dynamic value based on config by my system rule:

const objVariables = variables.reduce((acc, { key, value, isDefault }) => {
    acc[key] = { value, isDefault };
    return acc;
  }, {});

const result = content.replace(/{{(.*?)}}/g, (match, variable) => {
   const variableData = objVariables[variable];
   if (variableData && variableData.isDefault) {
      if (variable === "account") {
         return "ACCOUNT_NAME";
      }
    }
   return variableData ? variableData.value : match;
});

I want to replace all variables in the HTML string with the values stored in the database, but I think my code isn’t the best solution and may be slow. I’m looking for an optimized solution or any suggestions.

How can i make my javascript regex only accept a closing parentheses if it already matched an opening one

I’m trying to make a regex that will only accept phone numbers in the listed formats. However if I end the first three-digit group with a closing parentheses without an opening one at the start, the test will come back true when I want it to return false. What can I do?

1 555-555-5555
1 (555) 555-5555
1(555)555-5555
1 555 555 5555
5555555555
555-555-5555
(555)555-5555

const validNumbers = /^[1]? ?[(]?[0-9]{3}[)]?s?[0-9]{3}[-s]?[0-9]{4}$/i

console.log(validNumbers.test("1 305) 9759003"))

I am getting error Error 429 too many requests on createIngress in Livekit even when not making many requests

I’m working on integrating LiveKit’s API to manage streams in my application, and I’ve run into an issue when attempting to create a new ingress. Every time I attempt to create an ingress with IngressClient.createIngress(), I receive the following error:

Error: Request failed with status 429: Too Many Requests
    at TwirpRpc.request (file://E%3A/codingfolder/pulseStream/pulsestream/node_modules/livekit-server-sdk/src/TwirpRPC.ts:51:12)

s in advance!

Here’s a breakdown of the issue:

I am using the IngressClient.createIngress() method from the livekit-server-sdk.
I’ve been getting the error even after attempting retries with increasing delay.
The rate-limiting message keeps repeating without successfully creating the ingress.


import { IngressClient, IngressInput } from "livekit-server-sdk";

const IgClient = new IngressClient(
  process.env.LIVEKIT_API_URL,
  process.env.LIVEKIT_API_KEY,
  process.env.LIVEKIT_SECRET_KEY
);

async function createIngress(Ingresstype, id) {
  try {
    const options = {
      name: id,
      roomName: id,
      participantName: id,
      participantIdentity: id,
    };
    const ingress = await IgClient.createIngress(Ingresstype, options);
    return ingress;
  } catch (error) {
    console.error("Error creating ingress:", error);
  }
}

What I’ve Tried:
I have confirmed that the API keys are correct.
I’ve tried adding retry logic with increasing delay (1s, 2s, 4s, etc.), but the error persists.
I’ve reviewed the LiveKit documentation and could not find a solution regarding rate limits.
My Question:
why i am getting error even i am not makng many requests just one request as i am building it

Thank

JavaScript: Can’t set value to textarea with custom class on the first load

Question: I am trying to programmatically set a value inside a textarea with the following code:

function setTextareaValue(textareaId, value) {
  // Recursive function to wait until the element is available
  function waitForTextarea() {
    const textareaElement = document.getElementById(textareaId);
    if (textareaElement && textareaElement.querySelector('.hwt-input')) {
      // Once the element is available, set the value
      const textareaInput = textareaElement.querySelector('.hwt-input');
      textareaInput.value = value;
      textareaInput.dispatchEvent(new Event("input", { bubbles: true }));
      textareaInput.dispatchEvent(new Event("change", { bubbles: true }));
    } else {
      // If the element is not available, try again after 100ms
      setTimeout(waitForTextarea, 100);
    }
  }

  // Start the recursive function
  waitForTextarea();
}

// Use the function to set the value to the textarea
setTextareaValue('MarcEditorPresenter.textArea.050.Left.6', 'Value set by code');

However, this doesn’t work the first time I open the form. If I manually click and type in the field, then run the script again, it still doesn’t work. It only works when I open the “Inspect” tool, click on the textarea code in the inspector, and then the value is set correctly.

I’ve tried debugging, simulating the textarea activation in code, but it still doesn’t work. Any ideas on why this might happen and how to solve it?

Code and textarea im trting to set

Memory overflow can’t figure it out

So I am trying to answer this exercise from Eloquent Javascript Chapter 4 (The sum of a range) (check the bottom of the page).

My problem is I am getting “Uncaught out of memory” error when running certain combinations like for the example I pasted here.

I don’t see anything wrong with the code. If I changed the range call to a start/end from 35, 30, -1 to, for example, 30, 35, 2 I would get a result so I am confused.

Appreciate any help.

https://eloquentjavascript.net/04_data.html

let all = [];

function range (start, end, step = 1) {

  if (start < end) {
    for (let i = start; i <= end; i += step) 
      all.push(i);
  }
  else if (start > end) {
    for (let i = start; i >= end; i -= step) 
      all.push(i);
  }
  else 
    throw new Error 
    ("Start is equal to End or something else went wrong! Check your input"); 
  
  return all;
}

range(35, 30, -1);

console.log(all);

Get **all** css background image URLs with puppeteer

Think the title says it all. I have seen this post which is helpful but it requires you to know the selector of the element with the background image. I am looking for a way to find all the css background images without prior knowledge of the sites structure.

const backgroundImage = await page.evaluate(el => window.getComputedStyle(el).backgroundImage, await page.$(DON'T KNOWN THIS INFORMATION))

Ideally I would like a solution that fits with the puppeteer paradigm but otherwise the only ways forward I see are: by iterating over all the reasonable tags and checking for background images; or using some regex on the sites HTML to extract image URLs.

Thanks

Get **all** background image URLs with puppeteer

Think the title says it all. I have seen this post which is helpful but it requires you to know the selector of the element with the background image. I am looking for a way to find all the background images without prior knowledge of the sites structure.

Ideally I would like a solution that fits with the puppeteer paradigm but otherwise the only ways forward I see are: by iterating over all the reasonable tags and checking for background images; or using some regex on the sites HTML to extract image URLs.

Thanks