Uploading images to IPFS… Initialization failed

Good afternoon.
Please tell me what the problem is, I run the yarn start command and it doesn’t upload files to Pinata, although my plan there allows it to be done there is an error and the code is below: saved because:

app.ts

import * as dotenv from "dotenv";

import { toNano } from "ton-core";
import { readdir } from "fs/promises";

import { openWallet } from "./utils";
import { waitSeqno } from "./delay";
import { NftCollection } from "./contracts/NftCollection";
import { NftItem } from "./contracts/NftItem";
import { updateMetadataFiles, uploadFolderToIPFS } from "./metadata";
import { GetGemsSaleData, NftSale } from "./contracts/NftSale";
import { NftMarketplace } from "./contracts/NftMarketplace";

dotenv.config();

async function init() {
  try {
    const metadataFolderPath = "./data/metadata/";
    const imagesFolderPath = "./data/images/";

    const wallet = await openWallet(process.env.MNEMONIC!.split(" "), true);

  console.log("Started uploading images to IPFS...");
  const imagesIpfsHash = await uploadFolderToIPFS(imagesFolderPath);
  console.log(
    `Successfully uploaded the pictures to ipfs: https://gateway.pinata.cloud/ipfs/${imagesIpfsHash}`
  );

  console.log("Started uploading metadata files to IPFS...");
  await updateMetadataFiles(metadataFolderPath, imagesIpfsHash);
  const metadataIpfsHash = await uploadFolderToIPFS(metadataFolderPath);
  console.log(
    `Successfully uploaded the metadata to ipfs: https://gateway.pinata.cloud/ipfs/${metadataIpfsHash}`
  );

  console.log("Start deploy of nft collection...");
  const collectionData = {
    ownerAddress: wallet.contract.address,
    royaltyPercent: 0.05, // 0.05 = 5%
    royaltyAddress: wallet.contract.address,
    nextItemIndex: 0,
    collectionContentUrl: `ipfs://${metadataIpfsHash}/collection.json`,
    commonContentUrl: `ipfs://${metadataIpfsHash}/`,
  };
  const collection = new NftCollection(collectionData);
  let seqno = await collection.deploy(wallet);
  console.log(`Collection deployed: ${collection.address}`);
  await waitSeqno(seqno, wallet);

  // Deploy nft items
  const files = await readdir(metadataFolderPath);
  files.pop();
  let index = 0;

  seqno = await collection.topUpBalance(wallet, files.length);
  await waitSeqno(seqno, wallet);
  console.log(`Balance top-upped`);

  for (const file of files) {
    try {
      console.log(`Start deploy of ${index + 1} NFT`);
    const mintParams = {
      queryId: 0,
      itemOwnerAddress: wallet.contract.address,
      itemIndex: index,
      amount: toNano("0.05"),
      commonContentUrl: file,
    };
    const nftItem = new NftItem(collection);
    seqno = await nftItem.deploy(wallet, mintParams);
    console.log(`Successfully deployed ${index + 1} NFT`);
    await waitSeqno(seqno, wallet);
    index++;
  } catch (error) {
    console.error(`Error deploying ${index + 1} NFT:`, error);
  }
}

  console.log("Start deploy of new marketplace  ");
  const marketplace = new NftMarketplace(wallet.contract.address);
  seqno = await marketplace.deploy(wallet);
  await waitSeqno(seqno, wallet);
  console.log("Successfully deployed new marketplace");

  try {
    const nftToSaleAddress = await NftItem.getAddressByIndex(collection.address, 0);
  const saleData: GetGemsSaleData = {
    isComplete: false,
    createdAt: Math.ceil(Date.now() / 1000),
    marketplaceAddress: marketplace.address,
    nftAddress: nftToSaleAddress,
    nftOwnerAddress: null,
    fullPrice: toNano("10"),
    marketplaceFeeAddress: wallet.contract.address,
    marketplaceFee: toNano("1"),
    royaltyAddress: wallet.contract.address,
    royaltyAmount: toNano("0.5"),
  };
  const nftSaleContract = new NftSale(saleData);
  seqno = await nftSaleContract.deploy(wallet);
  await waitSeqno(seqno, wallet);

} catch (error) {
  console.error('Error setting up NFT for sale:', error);
}
} catch (error) {
console.error('Initialization failed:', error);
}
}

void init();

my mistake:

% yarn start
yarn run v1.22.19
$ tsc –skipLibCheck && node dist/app.js
Started uploading images to IPFS…
Initialization failed: {
reason: ‘FORBIDDEN’,
details: ‘Account blocked due to plan usage limit’
}
✨ Done in 3.96s.

Center grid items in material UI

I tried to center the grid items of material UI but not able to achieve and document says you can make use of justifyItems and alignItems props but i could not achieve by using this one. Any help?

Items are not centered

i tried below sample but not sure what’s wrong here the grid items are started from the beginning itself

`const HeaderCopy: React.FC = () => {
    const [anchorEl, setAnchorEl] = React.useState<null | HTMLElement>(null);

    const handleMenu = (event: React.MouseEvent<HTMLElement>) => {
        setAnchorEl(event.currentTarget);
    };

    const handleClose = () => {
        setAnchorEl(null);
    };
    return (
        <AppBar>
            <Grid container  alignItems="center" justifyContent="center">
                <Grid item xs={3}>
                    <img src="/public/logo.png" />
                </Grid>
                <Grid item xs={6}>
                    <Typography component="div">ALl IS WELL</Typography>
                </Grid>
                <Grid item xs={3}>
                    <IconButton
                        size="large"
                        aria-label="account of current user"
                        aria-controls="menu-appbar"
                        aria-haspopup="true"
                        onClick={handleMenu}
                        color="inherit"
                    >
                        <AccountCircle />
                    </IconButton>
                    <Menu
                        id="menu-appbar"
                        anchorEl={anchorEl}
                        anchorOrigin={{
                            vertical: "bottom",
                            horizontal: "right",
                        }}
                        keepMounted
                        transformOrigin={{
                            vertical: "top",
                            horizontal: "right",
                        }}
                        open={Boolean(anchorEl)}
                        onClose={handleClose}
                    >
                        <MenuItem>Home</MenuItem>
                        <MenuItem>My Profile</MenuItem>
                        <MenuItem>My Settings</MenuItem>
                        <MenuItem>Logout</MenuItem>
                    </Menu>
                </Grid>
            </Grid>
        </AppBar>
    );
}`

Why select2 search functionality is not working when dynamically dropdown value loaded

I have a dropdown division list when select division dynamically district loaded based on division .when select district, thana loaded dynamically.but problem is dynamic dropdown is select2 search not work

Here is my code that i have tried but search functionality not working.please give me a suggestion what have to modify to search dynamically dropdown value

<script>
        $(document).ready(function() {
            // Initialize Select2 for course dropdown
            $('#division_id').select2({
                placeholder: "Please Choose..",
                tags: true,
                allowClear: true,
                width: '100%'
            });

            // Initialize Select2 for subject dropdown
            $('#district_id').select2({
                placeholder: "Please Choose..",
                tags: true,
                allowClear: true,
                width: '100%',
                minimumInputLength: 0, // Allow searching immediately without any minimum length requirement
                ajax: {
                    url: function() {
                        // If division is not selected, return an empty string as URL
                        if (!$('#division_id').val()) {
                            return '';
                        }
                        return '/get-districts/' + $('#division_id').val();
                    },
                    dataType: 'json',
                    processResults: function(data) {
                        return {
                            results: $.map(data, function(district) {
                                return {
                                    id: district.id,
                                    text: district.name,
                                };
                            }),
                        };
                    },
                },
            });

            // Initialize Select2 for chapter dropdown
            $('#thana_id').select2({
                placeholder: "Please Choose..",
                tags: true,
                allowClear: true,
                width: '100%',
                minimumInputLength: 0, // Allow searching immediately without any minimum length requirement
                ajax: {
                    url: function() {
                        // If district is not selected, return an empty string as URL
                        if (!$('#district_id').val()) {
                            return '';
                        }
                        return '/get-thanas/' + $('#district_id').val();
                    },
                    dataType: 'json',
                    processResults: function(data) {
                        return {
                            results: $.map(data, function(thana) {
                                return {
                                    id: thana.id,
                                    text: thana.name,
                                };
                            }),
                        };
                    },
                },
            });

            // Handle district dropdown open event
            $('#district_id').on('select2:open', function() {
                $('#district_id').select2('open');
                $('.select2-search__field').focus(); // Focus on search input
            });

            // Handle thana dropdown open event
            $('#thana_id').on('select2:open', function() {
                $('#thana_id').select2('open');
                $('.select2-search__field').focus(); // Focus on search input
            });

            // Handle division change event
            $('#division_id').on('change', function() {
                $('#district_id').val(null).trigger('change');
                $('#thana_id').val(null).trigger('change');
            });

            // Handle district change event
            $('#district_id').on('change', function() {
                $('#thana_id').val(null).trigger('change');
            });

        });
    </script>

How to create a dynamic Stepper (timeline) in Js/jquery

I am looking for a solution to create a dynamic stepper. In the Snippet, when i select Heudebouville and then feedbackDo, all the checkboxes between should be checked, that’s good for the moment, but if i want to deselect one of the checkboxes between (for example : Babille) it should be deselect (checked=false without changing the classNames), but it’s not the case here.

in the example below, i checked the first checkbox and another one, the checkboxes between are checked (it’s good) but when i try to deselect them ( Post a contest or Provide feedback) they still checked.
Click here to see the Gif

I hope it’s clear Here my code :

// Switch cites
  $("#fluxLibreSwitchCity").click(function () {
    var fromCity = $(".FluxLibreStep2__From .FluxLibreStep2__City");
    var toCity = $(".FluxLibreStep2__To .FluxLibreStep2__City");

    // Inverse  cities
    var tempCity = fromCity.text();
    fromCity.text(toCity.text());
    toCity.text(tempCity);

    // Inverse passages
    var passages = $(".StepProgress > li");
    var reversedPassages = passages.toArray().reverse();
    $(".StepProgress").html(reversedPassages);
    $(".StepProgress").toggleClass("inverse");
    redrawSteps();
    CalculatePrice();
  });

  // Road
  // Calculate prices
  const CalculatePrice = () => {
    $('input[type="checkbox"]').change(function () {
      var totalPrice = 0;
      $('input[type="checkbox"]:checked').each(function () {
        var price = parseFloat(
          $(this).siblings("label").find(".infoORprice").text().trim()
        );
        totalPrice += price;
      });
      $("#totalPrice").text(totalPrice.toFixed(2) + " €");
    });
  };
  CalculatePrice();

  // order checkbox
  var checkboxes = document.querySelectorAll(
    '.StepProgress-item input[type="checkbox"]'
  );

  checkboxes.forEach((checkbox, index) => {
    checkbox.addEventListener("change", function () {
      redrawSteps();
    });
  });
  const redrawSteps = () => {
    const bluePath = document.querySelectorAll(".StepProgress-item");
    bluePath.forEach((li) => li.classList.remove("is-active"));

    const checked = document.querySelectorAll(
      '.StepProgress-item input[type="checkbox"]:checked'
    );

    if (checked.length > 1) {
      const first = checked[0].closest("li");
      const last = checked[checked.length - 1].closest("li");
      let started = false;
      let finished = false;

      bluePath.forEach((li) => {
        if (li === first) {
          started = true;
        } else if (li === last) {
          finished = true;
        }

        if (started && !finished) {
          const checkbox = li.querySelector('input[type="checkbox"]');
          li.classList.add("is-active");
          if (checkbox && !li.classList.contains("subItem")) {
            checkbox.checked = true;
          }
        }
      });
    }
    var allItems = document.querySelectorAll(".StepProgress-item");
    allItems.forEach(function (item) {
      var checkbox = item.querySelector('input[type="checkbox"]');
      if (checkbox && checkbox.checked) {
        item.classList.add("selected");
      } else {
        item.classList.remove("selected");
      }
    });
  };
.StepProgress {
  position: relative;
  display: flex;
  flex-direction: column;
  list-style: none;
  width: 100%;
  padding: 0;
}
.StepProgress:before {
  display: inline-block;
  content: "";
  position: absolute;
  top: 50%;
  left: 0;
  width: 10px;
  height: calc(100% - 90px);
  border-left: 4px solid gray;
  transform: translateY(-50%);
  z-index: 1;
}
.StepProgress__FromToCity {
  display: flex !important;
  align-items: center;
  gap: 5px;
  font-size: 14px;
  color: gray;
  margin-left: -6px !important;
  margin-bottom: 5px !important;
}
.StepProgress__FromToCity:before {
  content: "";
  display: block;
  background-image: url("data:image/svg+xml,%3Csvg width='18' height='18' viewBox='0 0 18 18' fill='none' xmlns='http://www.w3.org/2000/svg'%3E%3Cpath d='M15 7.5c0 4.5-6 9-6 9s-6-4.5-6-9a6 6 0 1 1 12 0' stroke='%23787878' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3Cpath d='M9 9.75a2.25 2.25 0 1 0 0-4.5 2.25 2.25 0 0 0 0 4.5' stroke='%23787878' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E");
  background-repeat: no-repeat;
  width: 18px;
  height: 18px;
}
.StepProgress__FromToCity:last-child {
  margin-top: -10px;
}
.StepProgress-item {
  position: relative;
  display: flex !important;
  padding-bottom: 20px !important;
  height: 100px;
}
.StepProgress-item input[type="checkbox"] {
  appearance: none;
  -webkit-appearance: none;
  width: 20px;
  height: 20px;
  border: 2px solid gray;
  border-radius: 50%;
  margin-right: 10px;
  background-color: white;
  position: relative;
  top: 6px;
  left: -8px;
  z-index: 2;
}
.StepProgress-item input[type="checkbox"]:checked {
  box-shadow: 0px 9px 17px -4px gray;
  border: 2px solid blue;
}
.StepProgress-item input[type="checkbox"]:checked:before {
  content: "";
  background-color: blue;
}
.StepProgress-item input[type="checkbox"]:checked:after {
  content: "";
  display: block;
  width: 100%;
  height: 100%;
  background: #e0f8ff;
  border-radius: 50px;
}
.StepProgress-item input[type="checkbox"]:before {
  content: "";
  display: block;
  width: 10px;
  height: 10px;
  background-color: gray;
  border-radius: 50%;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
.StepProgress-item__subItemPassageNum {
  display: contents;
}
.StepProgress-item__InfoPassage {
  display: flex;
  flex-direction: column;
  flex: 1;
  color: black;
  font-size: 16px;
  font-weight: 700;
  margin-bottom: 0;
}
.StepProgress-item__InfoPassage span {
  font-size: 14px;
  font-weight: 400;
}
.StepProgress-item__InfoPassage .infoORprice {
  color: gray;
}
.StepProgress-item__InfoPassage .icon {
  position: absolute;
  right: 0;
  color: blue;
  font-size: 14px;
  font-weight: 600;
  border-radius: 3px;
  background-color: rgba(204, 204, 204, 0.6);
  align-self: baseline;
  padding: 2px 3px;
}
.StepProgress-item__InfoPassage .icon::before {
  margin-right: 5px;
}
.StepProgress-item.selected > * {
  z-index: 1;
}
.StepProgress-item.selected:after {
  content: "";
  background-color: #f4f4f499;
  height: calc(100% - 10px);
  width: calc(100% + 10px);
  position: absolute;
  top: calc(50% - 10px);
  transform: translateY(-50%);
  left: 0;
  z-index: 0;
}
.StepProgress-item.subItem {
  margin-left: 40px;
}
.StepProgress-item.subItem.selected > * {
  z-index: 1;
}
.StepProgress-item.subItem.selected:after {
  content: "";
  left: -40px;
  width: calc(100% + 50px);
}
.StepProgress-item.subItem input[type="checkbox"]:checked {
  box-shadow: 0px 9px 17px -4px gray;
}
.StepProgress-item.subItem input[type="checkbox"]:checked + .StepProgress-item__InfoPassage:before {
  background-color: blue;
  left: -67px;
  width: 30px;
}
.StepProgress-item.subItem .StepProgress-item__InfoPassage {
  position: relative;
}
.StepProgress-item.subItem .StepProgress-item__InfoPassage:before {
  content: "";
  display: inline-block;
  position: absolute;
  left: -70px;
  top: 16px;
  width: 34px;
  height: 4px;
  transform: translateY(-50%);
  background-color: gray0;
  z-index: 1;
}
.StepProgress-item.subItem.is-active {
  position: relative;
}
.StepProgress-item.subItem.is-active:before {
  content: "";
  left: -40px;
  top: 14px;
  height: 100%;
}
.StepProgress-item.not-active * {
  color: #787878;
}
.StepProgress-item.not-active input[type="checkbox"]::before {
  width: 100%;
  height: 100%;
}
.StepProgress-item.not-active .StepProgress-item__InfoPassage + span {
  background-color: #f4f4f4;
}
.StepProgress-item:last-of-type {
  padding-bottom: 0;
}
.StepProgress-item.is-active:before {
  display: inline-block;
  content: "";
  position: absolute;
  top: 26px;
  height: calc(100% - 8px);
  width: 4px;
  background: blue;
  z-index: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<section class="FluxLibreStep2" id="step2">
                            <button class="FluxLibre__IconBackStep" id="returnToPreviousStep"></button>

                            <div class="FluxLibreStep2__top">
                                 

                                <div class="FluxLibreStep2__FromTo">
                                    <div class="FluxLibreStep2__From">
                                        <span>De</span>
                                        <div class="FluxLibreStep2__City">
                                            Paris </div>
                                    </div>
                                    <button type="button" class="FluxLibre__IconSwitch" id="fluxLibreSwitchCity"></button>
                                    <div class="FluxLibreStep2__To">
                                        <span>Vers</span>
                                        <div class="FluxLibreStep2__City">
                                            Caen</div>
                                    </div>
                                </div>
                            </div>


                            <div class="FluxLibreStep2__Road">
                                <ul class="StepProgress list-inline">
                                    <li class="StepProgress__FromToCity">
                                        Paris
                                    </li>
                                    <li class="StepProgress-item">
                                        <input type="checkbox" id="point1" name="passage" value="point1">
                                        <label for="point1" class="StepProgress-item__InfoPassage">
                                            Heudebouville
                                            <span class="infoORprice">
                                                12 €</span>
                                            <span class="icon icon-{{ iconPassage }}" aria-hidden="true">A10</span>
                                        </label>
                                    </li>
                                    <li class="StepProgress-item subItem">
                                        <input type="checkbox" id="point2" name="passage" value="point2">
                                        <label for="point2" class="StepProgress-item__InfoPassage">
                                            Montreuil
                                            <span class="StepProgress-item__subItemPassageNum">(n°6a)</span>
                                            <span class="infoORprice">
                                                12 €</span>
                                            <span class="icon icon-{{ iconSousPassage  }}" aria-hidden="true">A11</span>
                                        </label>
                                    </li>
                                     
                                    <li class="StepProgress-item">
                                        <input type="checkbox" id="point4" name="passage" value="point4">
                                        <label for="point4" class="StepProgress-item__InfoPassage">
                                            Babille
                                            <span class="infoORprice">
                                                12 €</span>

                                            <span class="icon icon-{{ iconPassage }}" aria-hidden="true">A12</span>
                                        </label>
                                    </li>
                                    <li class="StepProgress-item subItem not-active">
                                        <input disabled="disabled" type="checkbox" id="point5" name="passage" value="point5">
                                        <label for="point5" class="StepProgress-item__InfoPassage">
                                            Handover
                                            <span class="infoORprice">
                                                Ouverture du portic flux libre le 25/12/2024
                                            </span>
                                            <span class="icon icon-{{ iconSousPassage }}" aria-hidden="true">A13</span>
                                        </label>
                                    </li>
                                    <li class="StepProgress-item">
                                        <input type="checkbox" id="point6" name="passage" value="point6">
                                        <label for="point6" class="StepProgress-item__InfoPassage">
                                            Provide
                                            <span class="StepProgress-item__subItem-PassageNum">
                                                (n°6a)
                                            </span>
                                            <span class="infoORprice">
                                                6 €
                                            </span>
                                            <span class="icon icon-{{ iconPassage }}" aria-hidden="true">A51</label>
                                        </li>
                                    </li>
                                    <li class="StepProgress-item subItem">
                                        <input type="checkbox" id="point7" name="passage" value="point7">
                                        <label for="point7" class="StepProgress-item__InfoPassage">
                                             feedbackDo
                                            <span class="StepProgress-item__subItem-PassageNum">
                                                (n°6a)
                                            </span>
                                            <span class="infoORprice">
                                                6 €
                                            </span>
                                            <span class="icon icon-{{ iconPassage }}" aria-hidden="true">A51</label>
                                        </li>
                                    </li>
                                    <li class="StepProgress__FromToCity">
                                        Caen
                                    </li>
                                </ul>
                            </div>
                            <p>Selected option:
                                <span id="selectedOption"></span>
                            </p>

                            <div class="FluxLibreStep2__TotalPrice">
                                <p>{{ fluxLibreTotalPrice}}
                                </p>
                                <span id="totalPrice">0</span>
                            </div>
                        </section>

Pdf to Blob for Firebase Storage

i am trying to convert a Pdf to a Blob, so i can upload it to firebase storage. I can see in the firebase console the uploaded pdf but i can not open it. I get the error: Failed to Load Pdf file.

This is the conversion function:

const uriToBlob = async (uri) => {
    try {
      const response = await fetch(uri);
      if (!response.ok) {
        throw new Error('Failed to fetch resource');
      }
      const blob = await response.blob();
      return blob;
    } catch (error) {
      throw error;
    }
  };

and i make the conversion this way:

const userCredentials = getCredentials();
        if (!userCredentials) {
            console.error('User credentials not found');
            return;
        }

        try {
            // Convert file URI to Blob
            fileBlob = await uriToBlob(fileUri);
            console.log('Blob size:', fileBlob);
            // Upload file to Firebase Storage
            const storage = getStorage();
            const storageRef = ref(storage, 'notes/' + filename);

            // Get download URL of the uploaded file
            const metadata = {
                contentType: 'application/pdf'
            };
            const snapshot = await uploadBytes(storageRef, fileBlob, metadata);
            const fileUrl = await getDownloadURL(storageRef);

Applying zoom into point like Aseprite

Hello I need some help with applying an answer on another question to my code. I’m currently trying to recreate aseprite’s zoom functionality but, with my current code, when I zoom on different sides of the canvas it shifts a couple of pixels.

Previously I was told that my question was a duplicate of: Zoom in on a point (using scale and translate)

But I can’t seem to get their answer to work with my code. Please help me with this.

Here is a gif displaying what currently happens:

Zoom shift problem

And here is how it should work:

Aseprite zoom

Here is my relavant code:

<html>
  <body>
    <main>
      <section Id="canvas-panel">
        <section
          id="canvas"
          style="width: 256px; height: 256px; background-size: 12.5%"
        >
          <canvas width="256px" height="256px"></canvas>
        </section>
      </section>
    </main>
  </body>
</html>

<script>
  let canvasPanel = document.getElementById("canvas-panel");
  let canvas = document.getElementById("canvas");

  // Function to calculate the closest point on the border of the canvas to the click position.
  function calculateClosestBorderPoint(event) {
    const canvasRect = canvas.getBoundingClientRect();

    const clickX = event.clientX;
    const clickY = event.clientY;

    let closestX = canvasRect.left;
    let closestY = canvasRect.top;

    // Determine if the click is closer to the left or right side of the canvas.
    if (clickX < canvasRect.left) {
      closestX = canvasRect.left;
    } else if (clickX > canvasRect.right) {
      closestX = canvasRect.right;
    } else {
      closestX = clickX;
    }

    // Determine if the click is closer to the top or bottom of the canvas.
    if (clickY < canvasRect.top) {
      closestY = canvasRect.top;
    } else if (clickY > canvasRect.bottom) {
      closestY = canvasRect.bottom;
    } else {
      closestY = clickY;
    }

    return { x: closestX, y: closestY };
  }

  // Initialize scale.
  let scale = 1;

  // Define zoom limits
  const minScale = 0.5; // Minimum zoom limit.
  const maxScale = 4.0; // Maximum zoom limit.

  // Function to update the canvas transformation.
  function updateCanvasTransform() {
    canvas.style.transform = `scale(${scale})`;
  }

  canvasPanel.addEventListener("wheel", function (e) {
    e.preventDefault();

    const zoomDirection = e.deltaY < 0 ? 1 : -1;

    if (scale == minScale && zoomDirection == -1) return;
    if (scale == maxScale && zoomDirection == 1) return;

    const zoomFactor = 1.1;

    const closestPoint = calculateClosestBorderPoint(event);

    scale *= zoomFactor ** zoomDirection; // Apply zoom factor based on direction

    // Clamp scale to limits
    scale = Math.min(scale, maxScale);
    scale = Math.max(scale, minScale);

    // Update canvas position to keep the closest point centered relative to the viewport
    const canvasRect = canvas.getBoundingClientRect();
    const viewportCenterX = canvasRect.width / 2;
    const viewportCenterY = canvasRect.height / 2;

    // Convert closest point to relative position within the viewport (0-1 scale)
    let relativeX =
      ((closestPoint.x - canvasRect.left) / canvasRect.width) * 100;
    let relativeY =
      ((closestPoint.y - canvasRect.top) / canvasRect.height) * 100;

    canvas.style.transformOrigin = `${relativeX}% ${relativeY}%`;

    // Update canvas transformation using only scale
    updateCanvasTransform();
  });
</script>

<style>
  #canvas {
    position: fixed;
    overflow: hidden;
    padding: 0;
    margin: 0;
    transform: scale(1) translate(0px, 0px);
    background-color: #1d1d1d;
  }

  #canvas-panel {
    position: relative;
    width: 100%;
    height: 100%;
    background-color: #303030;
  }

  html,
  body {
    background-color: #161616;
    margin: 0;
    width: 100%;
    height: 100%;
  }
</style>

javascript: dropping folder how to get all sub folders and files?

im not quite sure what to do next, followed along a few other tutorials etc and cant seem to get this to work.

I have a folder full of subfolders and files and i want to drop them on my web app and from there read out the top level folder all sub folders and all files within said folders.

It works but only ever reads out the top folder never goes into subfolders OR files – maybe im missing something..

html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>File Drop Zone</title>
</head>
<body>
    <div id="drop-zone" style="width: 100%; height: 200px; border: 2px dashed #ccc; text-align: center; line-height: 200px;">
        Drop files here
    </div>
    <script src="app.js"></script>
</body>
</html>

Javascript

// Function to handle file drop
async function dropHandler(event) {
    event.preventDefault();
    console.log('Drop event triggered');
    const files = await getDroppedFilesFromFolder(event);
    console.log('Received', files.length, 'files from drop:', files);
    // Your logic here
}

async function getDroppedFilesFromFolder(event) {
    console.log('Getting files from dropped folders');
    const dataTransfer = event.dataTransfer;
    const fileList = [];

    for (let i = 0; i < dataTransfer.items.length; i++) {
        const item = dataTransfer.items[i];
        if (item.kind === 'file') {
            console.log('Found file:', item.getAsFile().name);
            fileList.push(item.getAsFile().name);
        } else if (item.kind === 'directory') {
            console.log('Found directory:', item.webkitGetAsEntry().name);
            const directory = await processDirectoryEntry(item.webkitGetAsEntry());
            fileList.push(...directory);
        }
    }

    console.log('Finished getting files from dropped folders:', fileList);
    return fileList;
}
async function processDirectoryEntry(directoryEntry) {
    const files = [];
    const directoryReader = directoryEntry.createReader();

    const readEntries = () => {
        return new Promise((resolve, reject) => {
            directoryReader.readEntries((entries) => {
                resolve(entries);
            }, reject);
        });
    };

    const processEntries = async () => {
        let entries;
        while ((entries = await readEntries())) {
            for (let entry of entries) {
                if (entry.isFile) {
                    console.log('Found file in directory:', entry.name);
                    files.push(entry.name);
                } else if (entry.isDirectory) {
                    console.log('Found subdirectory:', entry.name);
                    files.push(entry.name);
                }
            }
        }
    };

    await processEntries();
    return files;
}


// Prevent default behavior for drag events
function preventDefault(event) {
    event.preventDefault();
    event.stopPropagation();
}

// Initialize the application
function init() {
    console.log('Initializing application');
    const dropZone = document.getElementById('drop-zone');
    
    // Add event listeners for drag events
    dropZone.addEventListener('drop', dropHandler);
    dropZone.addEventListener('dragover', preventDefault);
    dropZone.addEventListener('dragenter', preventDefault);
    console.log('Event listeners added');
}

// Call the init function when the DOM is ready
document.addEventListener('DOMContentLoaded', () => {
    console.log('DOM content loaded');
    init();
});

Need advice for list of links, whose content is imported from external file (HTML, JS)

Even though this might is a simple question, I haven’t found yet a solution for how to set it up the best. The question is, how can I set up an external file for a list of links, which will get imported on every sub-domain. The goal is, to have just one list on which names + links can get added, but will get included on every subdomain. Till now everything is just built with html and vanillaJS. Would be thankful for any advice!! Focus: VanillaJS and NodeJS or basic HTML/CSS bridging
Till now just made everything workable with vanillaJS + CSS for the HTML. No experience with php nor NodeJS, but suggest this would be needful therefore.

How do I add a “copy code snippet” option in React Markdown files?

I currently wish to add a feature to copy code snippets in my documentation, which consists of several MD files that will render in the browser when the respective page is clicked.

I would appreciate assistance in implementing a code copy option for all MD files, as I am new to the React framework.

page1.md

welcome to my documentation.

    ```js
        <head> 
            <script type="text" src="https://cdn.js"></script>
        </head>
        ```

Why is button on sidebar is unclickable?

Button on sidebar isn’t unclickable. On my main page, button element works clearly but on sidebar, it is not working.

import { useContext, TouchableOpacity } from "react";
import { DataContext } from "../App";
import "./SideBar.css";

    const SideBar = () => {
      const [showModal, setShowModal] = useContext(DataContext);
      return (
        <div
          className={showModal ? "modal-dialog show" : "modal-dialog"}
          role="document"
        >
          <div className="sideBar">
            <div className="sideBarHeader">
              <h5>Add City</h5>
              <button >
                Trial
              </button>
            </div>
          </div>
        </div>
      );
    };
    export default SideBar;

How to prevent of automatic centering of webpage in IOS/Safary when an input element focus is enabled

An OTP input form was created using HTML/CSS/JS, which includes six input fields. It functions as expected, but when tested on iOS devices, it was observed that the page automatically centers around the input field that is in focus. This isn’t the desired behavior, and there’s a need to disable this automatic centering for input fields. Is there a way to achieve this on iOS?

css code below:

    #inputContainer{
        padding:0px;
        display: flex;
        font-size:28px;
        margin:auto;
        width: 216px; 
        height: 44;
    }
    
    #inputContainer input{
        margin: 0px 2px 0px 2px;
        display: inline-flex;
        border: 1px solid rgba(156, 150, 127, 0.24);
        width: 32px;
        height: 44px;
        border-radius: 8px;
        text-align: center;
        font-size:28px;
        caret-color: transparent;
    }
    
    #inputContainer input:nth-child(1){
        border: 1px solid rgba(255, 212, 3, 1);
    }
    
    #inputContainer input:focus { 
        outline: none;
    }
    
    #inputContainer input[disabled] { 
        color: black;
    }

js code below:

const inactiveInputBorderColor = "1px solid rgba(156, 150, 127, 0.24)";
            const activeInputBorderColor = "2px solid rgba(255, 212, 3, 1)";
            const hoverInputBorderColor = "1px solid rgba(255, 212, 3, 1)";
            const inactiveBoxShadow = "none";
            const activeBoxShadow = "0 0 0 3px rgba(255, 154, 3, 0.15)";
            const inputs = document.querySelectorAll("#inputContainer input");
            
                        
            inputs.forEach((input, index) => {
                input.dataset.index = index;

                input.addEventListener("click", customClickInput);
                input.addEventListener("paste", customPastOtp);
                input.addEventListener("mouseenter", customEnterHover);
                input.addEventListener("mouseleave", customLeaveHover);
                input.addEventListener("keyup", customEnterAndRemoveOtp);
            });
            
            function submitOtp(){
                let otp = "";
                
                setTimeout(function() {
                    inputs.forEach((input) => {
                        otp += input.value;
                        input.disabled = true;
                        input.classList.add("disabled");
                    });
                }, 5000);

            }
            
            function customPastOtp(e){
                const data = e.clipboardData.getData("text");
                const value = data.split("");
                if(value.length === inputs.length){
                                        
                    inputs.forEach((input, index) => {
                        input.disabled = true;
                        input.value = value[index];
                        input.style.border = inactiveInputBorderColor;
                        input.style.boxShadow = inactiveBoxShadow;
                    });
                    submitOtp();
                } else if(value.length < inputs.length) {
                    
                    inputs.forEach((input, index) => {
                        if(index  < value.length){
                            input.disabled = true;
                            input.value = value[index];
                            input.style.border = inactiveInputBorderColor;
                            input.style.boxShadow = inactiveBoxShadow;
                        } else if(index === value.length){
                            console.log(index);
                            input.style.boxShadow = activeBoxShadow;
                            input.style.border = activeInputBorderColor;
                            input.focus();
                        }
                    });
                    submitOtp();
                }
                e.preventDefault();
            };
            
            function customEnterAndRemoveOtp(e){
                const input = e.target;
                let value = input.value;
                
                if(value.length === inputs.length){
                    inputs.forEach((input, index) => {input.value = value[index];});
                    submitOtp();
                }else if( 1 < value.length && value.length < inputs.length){
                    inputs.forEach((input, index) => {
                        if(index  < value.length){
                            input.disabled = true;
                            input.value = value[index];
                            input.style.border = inactiveInputBorderColor;
                            input.style.boxShadow = inactiveBoxShadow;
                        } else if(index === value.length){
                            console.log(index);
                            input.style.boxShadow = activeBoxShadow;
                            input.style.border = activeInputBorderColor;
                            input.focus();
                        }
                    });
                }else{
                    input.value = "";
                    input.value = value ? value[0] : "";                    
                    let fieldIndex = input.dataset.index;
                    
                    if(value.length > 0 && fieldIndex < inputs.length - 1){
                        input.style.border = inactiveInputBorderColor;
                        input.style.boxShadow = inactiveBoxShadow;
                        input.disabled = true;
                        input.nextElementSibling.style.boxShadow = activeBoxShadow;
                        input.nextElementSibling.style.border = activeInputBorderColor;
                        input.nextElementSibling.focus();
                    }else if(value.length > 0 && fieldIndex == inputs.length - 1){
                        input.style.border = inactiveInputBorderColor;
                        input.style.boxShadow = inactiveBoxShadow;
                        submitOtp();
                    }   
                    
                    if (e.key === "Backspace" && fieldIndex > 0){
                        input.style.border = inactiveInputBorderColor;
                        input.style.boxShadow = inactiveBoxShadow;
                        input.previousElementSibling.disabled = false;
                        input.previousElementSibling.style.boxShadow = activeBoxShadow;
                        input.previousElementSibling.style.border = activeInputBorderColor;
                        input.previousElementSibling.value = "";
                        input.previousElementSibling.focus();
                    } else if(e.key === "Delete" && fieldIndex > 0){
                        input.style.border = inactiveInputBorderColor;
                        input.style.boxShadow = inactiveBoxShadow;
                        input.previousElementSibling.disabled = false;
                        input.previousElementSibling.style.boxShadow = activeBoxShadow;
                        input.previousElementSibling.style.border = activeInputBorderColor;
                        input.previousElementSibling.value = "";
                        input.previousElementSibling.focus();
                    }
                }
            }
            
            function customClickInput(e){
                let valueFlag = 0;
                
                inputs.forEach((input) => {
                    if(valueFlag === 0 && input.value == ""){
                        input.removeEventListener("mouseenter", customEnterHover);
                        input.removeEventListener("mouseleave", customLeaveHover);
                        input.style.border = activeInputBorderColor;
                        input.style.boxShadow = activeBoxShadow;
                        input.focus();
                        valueFlag++;
                    }else{
                        input.removeEventListener("mouseenter", customEnterHover);
                        input.removeEventListener("mouseleave", customLeaveHover);
                        input.style.border = inactiveInputBorderColor; 
                        input.style.boxShadow = inactiveBoxShadow;
                    }
                }); 
            }
            
            function customEnterHover(e){
                const input = e.target;
                let fieldIndex = input.dataset.index;
                
                inputs.forEach((input) => {
                    if(input.dataset.index === fieldIndex){
                        input.style.border = hoverInputBorderColor; 
                        input.style.boxShadow = inactiveBoxShadow;
                    }else{
                        input.style.border = inactiveInputBorderColor;
                        input.style.boxShadow = inactiveBoxShadow;
                    }
                });
            }
            
            function customLeaveHover(e){
                const input = e.target;
                let fieldIndex = input.dataset.index;
                
                inputs.forEach((input) => {
                    input.style.border = inactiveInputBorderColor;
                    input.style.boxShadow = inactiveBoxShadow;      
                });
            }
            
            window.onload = function() {
                document.querySelector("#inputContainer input:nth-child(1)").focus();
                console.log("focused");
            };

html code below:

<body>
    <div id="inputContainer">
        <input type="text" pattern="[0-9]*" inputmode="numeric" maxlength="6" autocomplete="off">
        <input type="text" pattern="[0-9]*" inputmode="numeric" maxlength="1" autocomplete="off">
        <input type="text" pattern="[0-9]*" inputmode="numeric" maxlength="1" autocomplete="off">
        <input type="text" pattern="[0-9]*" inputmode="numeric" maxlength="1" autocomplete="off">
        <input type="text" pattern="[0-9]*" inputmode="numeric" maxlength="1" autocomplete="off">
        <input type="text" pattern="[0-9]*" inputmode="numeric" maxlength="1" autocomplete="off">
    </div>
</body>

PrimeNG p-tree: How to get infos of the integrated filter?

I have a PrimeNG p-tree element in an Angular webapp.

<p-tree #tree [value]="nodes" selectionMode="single" [filter]="filt" [contextMenu]="cm" [(selection)]="nodesel" scrollHeight="500px">

I have also a ViewChild to #tree.

@ViewChild ("tree") tree;

[filter] is set to true.

So I have this top input-fielt that – if there is an input – filters the showed elements with respect to that.

With

this.tree.resetFilter ();

I can reset this input-element. Its value is the empty and the filter resets – all elements are shown again.

Question: But how can I find out if there is a filter enabled (something in the input-field)
AND how can I start a re-filtering if the p-trees data changed??

To configure Chart.js to display hours on the x-axis ticks when rendering charts in a Node.js

i am generating chart image in node using chart js how can i use hours on the ticks is there any idea for that

Error: This method is not implemented: Check that a complete date adapter is provided.

import chartjs-adapter-date-fns from ‘chartjs-adapter-date-fns’
var lineChartDetails: ChartConfiguration ={
type: ‘line’,
data: {
datasets: [{
label: ‘Sample Dataset’,
data: dataPoints,
borderColor: ‘rgb(75, 192, 192)’,
tension: 0.1
}]
},
options: {
scales: {
x: {
type: ‘time’,
time: {
unit: ‘day’,
tooltipFormat: ‘MMM dd, yyyy’
}
}
},
plugins: {
tooltip: {
callbacks: {
title: function(tooltipItems) {
return tooltipItems[0].label;
}
}
}
}
}
};

How to import fixtures in each Playwright test

I am writing some e2e tests using Playwright, and I have defined two fixtures:

  • one is for launching a browser with my chrome extension installed
  • other is for mocking an external api call so I can test an authenticated state

fixtures-auth.js

import { test } from './fixtures.js';
export { test, expect } from './fixtures.js';

test.beforeEach(async ({ context }) => {
    await context.route(
        'https://some.url.com/api/some-endpoint',
        async (route) => {
            if (route.request().serviceWorker()) {
                const json = {
                    //json content
                };
                await route.fulfill({ json });
            }
        },
    );
});

Currently I have two tests located in separate directories, but both of them having the same path to the fixture file. When I run them both, the fixture-auth is only applied to the first test and in the second one, despite the fixture being imported, it simply does not run the test.beforeEach.

import { test, expect } from '../fixtures-auth.js';

I want to run this beforeEach in every test to avoid code duplication, what am I doing wrong?

Input feild doesent work well with keydown event

I am trying to get my input feild to become bigger or smaller when I press the up and down arrows on my keyboard, However this only works when the input feild is not highlighted, otherwise it increases or decreases the number on it. How do I make it where the input feild doesent change the number but instead changes its scale everytime I press and or down.

In this case .${this.id} is the input feild

    draggable() {
  let isDragging = false;
  let offsetX, offsetY;
  let obj = this
  $('body').on('mousedown', '.'+this.id, (e) => {
    if (this.lock) {return}

    if(e.button !== 0) {return}

    const elementOffset = $(`.${this.id}`).offset()
    isDragging = true
    offsetX = e.pageX - elementOffset.left
    offsetY = e.pageY - elementOffset.top

  })
  $('body').on('mousemove', (e) => {
    if (this.lock) {return}

    if(e.button !== 0) {return}
    if(isDragging) {
      

      this.posX = e.pageX - offsetX
      this.posY = e.pageY - offsetY
      
      $(`.${this.id}`).css({'top': this.posY, 'left': this.posX});
    }
  })
  $('body').on('mouseup', (e) => {
    if (this.lock) {return}

    if(e.button !== 0) {return}
    isDragging = false
    offsetX = 0
    offsetY = 0
  })
  $(`body`).on('mousewheel', '.'+this.id, function(e) {
    if (this.lock) {return}

    if (isDragging) {
      if (e.originalEvent.deltaY < 0) {
        // Scrolling up
        obj.rotate += 15;
      } else {
        // Scrolling down
        obj.rotate -= 15;
      }
      $(`.${obj.id}`).css({'transform': `rotate(${obj.rotate}deg)`});
    }
    
  });
  let touchingElement = false
  
  $(window).on("keydown", (event) => {

    if(!touchingElement) return 
    let lastScale = this.scale
    if(event.key === 'ArrowUp') {
      if (this.lock) {return}
      this.scale += 0.02
      if(this.scale > 3) {
        this.scale = 3;
      }
      
      
    } else if (event.key === 'ArrowDown') {
      console.log('asdf')
      if (this.lock) {return}
      this.scale -= 0.02
      if(this.scale < 0.02) {
        this.scale = 0.02
      }

      
    } else if (event.key === 'l') {
      if(this.lock === true) {
        this.lock = false
      } else {this.lock = true}
   
    }
    let scaledWidth = ($(`.${this.id}`).outerWidth() * (1 / lastScale)) * this.scale
    let scaledHeight = ($(`.${this.id}`).outerHeight() * (1 / lastScale)) * this.scale
    $( `.${this.id}` ).off('mouseover').off('mouseout')
    $( `.${this.id}` ).css({
      'width': scaledWidth,
      'height': scaledHeight,
      'font-size': $(`.${this.id}`).innerHeight()
    })
    touchingElement = false
    $( `.${this.id}` ).on('mouseover', () => {

      touchingElement = true
    }).on('mouseout', () => {

      touchingElement = false
    })
    
  });
  $( `.${this.id}` ).on('mouseover', () => {

    touchingElement = true
  }).on('mouseout', () => {

    touchingElement = false
  })
}