How to set a Google Sheets’ Cell Note based off a Cell Value that begins with a Plus Sign

In a Google Apps script for the Google Sheet, I have this code with an OnEdit Trigger. It updates a cell’s Note based off the value I pick from a drop down list, which was created for the cell using a “Data Validation” (Dropdown from Range).

The values from a separate that the dropdown contain, some have a + in front of them
eg. +1 to modifier

I have tried formatting the values for the dropdown range
eg. =”+1 to modifier

Theerafter the dropdown chosen value itself does not cause an error when modified as above.

But then the following Apps Script, used to set the chosen dropdown value as a note, breaks and the note is not added, shows error:

function addNotescToRange() {
// Get the "GraveLayout" sheet
const sheet1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("GraveLayout");

// Define the range (A1:B2) (to set Notes for each cell based off its value)
const range1 = sheet1.getRange("A1:B2");

// Get the values in the range as a two-dimensional array
const values = range1.getValues();

// Loop through each cell in the range
for (let i = 0; i < values.length; i++) {
for (let j = 0; j < values[i].length; j++) {
const cell = range1.getCell(i + 1, j + 1); // +1 for zero-based indexing
const value = values[i][j];

      // Set the note for the cell using its value
      cell.setNote(value);
    }

}
}

I added the apostrophe manually to append it to the value in this final part of the code but the note still errors:

// Set the note for the cell using its value 
cell.setNote('"' & value);

Javascript var return: GETTING THE VALUE ONLY FROM A FORM (INPUT) [closed]

The function is taking the values of 2 inputs #modalidadeformacao and #modalidaderenovacao at the same time, I NEED it to only take the value of ONE or the OTHER.

Basically it would be:

IF
submit the form with id #curso-de-formacao-form
THEN
get the value of vmformacao and NOT get the value of vmrenovacao
OR IF
submit the form with id #curso-de-renovacao-form
THEN
get the value of vmrenovacao and NOT get the value of vmformacao


The forms and inputs are:

<script>
function() {
var vmformacao = document.querySelector('#curso-de-formacao-form #modalidadeformacao');
var vmrenovacao = document.querySelector('#curso-de-renovacao-form #modalidaderenovacao');

return (vmformacao ? vmformacao.value : '') + '' + (vmrenovacao ? vmrenovacao.value : '');
}
</script>
<div>Form 1</div>
<form action="" method="post" id="curso-de-formacao-form" >
<input type="text" name="modalidadeformacao" id="modalidadeformacao" value="Formação">
<input id="formacaosubmit" type="submit" value="send">
</form>

<div>Form 2</div>
<form action="" method="post" id="curso-de-renovacao-form" >
<input type="text" name="modalidaderenovacao" id="modalidaderenovacao" value="Renovação">
<input id="formacaosubmit" type="submit" value="send">
</form>

JS Sliding Panel: prevent delay of mouseleave event

I wrote a JS panel class that shows a sliding panel on top, bottom, left or right border of the page.

The panel is shown when the mouse comes near to the top, bottom, left or right edge of the page (or by default).

The panel hides when the mouse leaves it.

Please see my CodePen: https://codepen.io/Samwise_71/pen/MWRVaJb

You will notice that sometimes when mouse leaves the panel, it can take some seconds until the hiding animation starts (tested in Firefox):

// Hide panel on mouse leave
this.#panel.on("mouseleave", function (e) { panel.hide(e); });

/**
 * Slides the panel out of viewport.
 * @param {event object} e   
 */
hide(e) {
  if (!this.isVisible()) {
    return;
  }

  let ymax = this.#panel.height();
  let xmax = this.#panel.width();

  // Prevent leave to side of panels position
  if (this.#position == UserInterface.Panel.PositionTop && e.offsetY < 0 ||
    this.#position == UserInterface.Panel.PositionBottom && e.offsetY > ymax ||
    this.#position == UserInterface.Panel.PositionLeft && e.offsetX < 0 ||
    this.#position == UserInterface.Panel.PositionRight && e.offsetX > xmax) {
    return;
  }

  let margin = this.getMargin();
  let css = {};
  css[margin.key] = -1 * margin.pixels;
  let panel = this;
  this.#panel.animate(css, this.#speed, function () { panel.isVisible(false); });
}

I’m not sure what causes this delay, it seems to be independent from mouse movement.

What should I change to start the animation immediately after mouse crosses panels border?

Trying to use NodeJS to add an array to a JSON file [closed]

I am trying to find a way to append a new array to the end of a nested array located in a JSON file that looks like this

     [
       ["House", "0000000", 100],
       ["0000000", "0000002", 50],
       ["0000002", "0000000", 20]
     ]

I am trying to add something like this:

    ["0000003", "0000000", 20]

My code works so that I receive an array from client side, and the node js server is supposed to append it to the end of a JSON. I have tried a couple of solutions from similar posts about objects and such but it either deletes everything in the file or messes up the networking code.

How to split up an image from base64 into smaller pieces

The goal is to have a function that takes a base64 string as input and if the image is longer than 8000px in length, split it up into multiple equally long pieces that are all below 8000px long. This is in javascript, or in this case typescript. In this specific case it’s just for jpeg images, but I’m not sure if that makes a difference.

The following is the function that I’ve tried:

async function splitImage(jpegBase64: string): Promise<string[]> {
    // Remove metadata header from base64 string
    const base64Data = jpegBase64.replace(/^data:image/jpeg;base64,/, '');

    // Decode base64 string to buffer
    const buffer = Buffer.from(base64Data, 'base64');

    // Use sharp to read the image buffer and get its dimensions
    const metadata = await sharp(buffer).metadata();

    // Check if the image length exceeds 8000 pixels
    if (metadata.height > 8000) {
        // Calculate the number of segments needed
        const numSegments = Math.ceil(metadata.height / 8000);

        // Calculate the height of each segment
        const segmentHeight = Math.ceil(metadata.height / numSegments);

        // Array to store the base64 encoded data of each segment
        const segmentBase64s: string[] = [];

        // Crop the image into segments and get the base64 of each segment
        for (let i = 0; i < numSegments; i++) {
            const segmentTop = i * segmentHeight;
            const segmentHeightToExtract = Math.min(segmentHeight, metadata.height - segmentTop);

            const segmentBuffer = await sharp(buffer)
                .extract({
                    left: 0,
                    top: segmentTop,
                    width: metadata.width,
                    height: segmentHeightToExtract
                })
                .toBuffer();

            const segmentBase64 = `data:image/jpeg;base64,${segmentBuffer.toString('base64')}`;
            segmentBase64s.push(segmentBase64);
        }

        return segmentBase64s;
    } else {
        // If the image length is within 8000 pixels, return its base64
        return [jpegBase64];
    }
}

I expected it to return an array of equally long images (in px) that are all under 8000px.

When running the function with an image that already is under 8000px, it does as it should and gives me a valid base64 image, however when it has to split them up, it returns an array of what appears to be base64 strings but they are all invalid. Even the first one.

How should i unite shapes using Paper.js

I have the following code, but it does not matches the expectationas of a paper.io like game. It fills new areas, but not correctly. The player should return to the original base and the base is not expanding. What can i do? The paper.js’s unite method is not good either, because it leaves holes in the base.

<!DOCTYPE html>
<html>
<head>
    <title>Dynamic Path Drawing and Merging Game</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.12.11/paper-full.min.js"></script>
    <style>
        canvas {
            width: 800px;
            height: 600px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
<canvas id="gameCanvas"></canvas>
<script>
    paper.setup(document.getElementById('gameCanvas'));

    const player = new paper.Path.Circle({
        center: paper.view.center,
        radius: 5,
        fillColor: 'red'
    });

    let base = new paper.Path.Rectangle({
        point: [paper.view.center.x - 50, paper.view.center.y - 50],
        size: [100, 100],
        fillColor: 'lightblue'
    });

    let destination = player.position;
    let drawing = false;
    let playerPath;

    paper.view.onMouseMove = function (event) {
        destination = event.point;
    };

    paper.view.onFrame = function (event) {
        const vector = destination.subtract(player.position);
        if (vector.length > 1) {
            vector.length = 1;
            player.position = player.position.add(vector);

            if (!drawing && !base.contains(player.position)) {
                // Start drawing when moving out of the base
                drawing = true;
                playerPath = new paper.Path({
                    segments: [player.position],
                    strokeColor: 'lightblue',
                    strokeWidth: 2
                });
            } else if (drawing) {
                playerPath.add(player.position);

                // Check if the path intersects with the lightblue areas
                const intersections = base.getIntersections(playerPath);
                if (intersections.length > 0) {
                    // Complete the path
                    drawing = false;
                    playerPath.add(intersections[0].point); // Optional: refine to add intersection point
                    playerPath.closed = true;
                    playerPath.fillColor = 'lightblue';
                    playerPath = null; // Reset the path
                }
            }
            player.bringToFront();
        }
    };
</script>
</body>
</html>

I hope foe a solution for the problem

Mongoose search by nested model object

I have some kind of product filtering logic.

In the Products model, I search for certain products by query parameters, which are pushed into an array of settings (queryConditions), if such filtering exists

This is one of the objects that exists in the Products model

 {
            "_id": "660e867f26ef1583ee426c33",
            "name": "Iphone 15 pro max",
            "__t": "Phones",
            "price": "112000",
            "color": "Black",
            "memory": "128",
            "screen": "2480 x 1080",
            "fps": "240",
            "sim": "eSim",
            "preview": "cf4ab252-e117-4916-a1ee-d8c0db8b72d3.png",
            "images": [
                "6cb510fe-28ca-4ab0-8507-6e8139f05993.png",
                "9806ba4a-3484-43f1-a1dd-acc1d30e9f79.png",
                "a6e59955-05a5-4ce7-99d9-d88394c362ae.png",
                "3ceb7248-d094-47d6-887e-99df40e67d4d.png"
            ],
            "category": {
                "_id": "660c892cb65f2f1f584144ca",
                "name": "Phones",
                "preview": "phone.png"
            },
            "count": 1,
            "__v": 0
        },

Filtering logic

    async getAll(req, res) {
        // Filters
        const { search, color, date, category } = req.query
        const limit = 3
        const page = Number(req.query.page) || 1
        const skip = (page - 1) * limit

        const queryConditions = []

        if (search) {
            queryConditions.push({ name: new RegExp(search, 'i') })
        }

        if (color) {
            queryConditions.push({ color: color })
        }

        if (category) {
            queryConditions.push({ 'category._id': category })
        }

        const products = await ProductsModel.find()
            .populate({ path: 'category', select: ['name', 'preview'] })
            .and(queryConditions.length > 0 ? queryConditions : [{}])
            .skip(skip)
            .limit(limit)

        const length = products.length

        return res.json({ products, length })
    }

Filtering by search name and color works correctly, but when I try to get an object whose category is equal to the category that I pass through query, I get an empty array.

Actually, the question is how to properly implement a search for a nested category object and get an object whose category id corresponds to the id that I pass through query

nuxt 3 i18n strategy

// nuxt.config.ts
i18n: {
strategy: “prefix_except_default”,
locales: [
{
code: “en”,
file: “./locales/en.json”,
},
{
code: “ar”,
file: “./locales/ar.json”,
},
],
defaultLocale: “en”,
detectBrowserLanguage: false,
},
the url looks like that http://localhost:3000/ar/login
how to make /ar at end of the url

and when i want to go to any page i make code like this
navigateTo(/${locale.value}/dashboard);

expext http://localhost:3000/login/ar
and to type locale manually

styling layout for a react app using react-bootstrap

I am working on my frontend UI. I am using react-bootstrap 0.33.1 which supportsbootstrap v3.3.x.

This is how my UI looks like right now.
enter image description here

But, this is not something that I am expecting. I want to achieve something like this.

enter image description here

this is my jsx file:

import React from "react";
import { Grid, Row, Col, FormControl, Button, Image } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import "./ListComponent.css";

function ListComponent() {
  return (
    <div>
      <Grid>
        <Row className="list-header">
          <Col md={4}>
            <FormControl type="text" placeholder="Enter name to search" />
          </Col>
        </Row>
        <br />
        <Grid className="list-table">
          <Row className="item-row" style={{backgroundColor:'black', color:'white'}}>
            <Col sm={6} md={3}>
              Name
            </Col>
            <Col sm={6} md={3}>
              Address
            </Col>
            <Col sm={6} md={3}>
              Rating
            </Col>
            <Col sm={6} md={3}>
              Picture
            </Col>
            <Col sm={6} md={3}>
              Action
            </Col>
          </Row>
          <Row className="item-row">
            <Col sm={6} md={3}>
              Cox's Bazar
            </Col>
            <Col sm={6} md={3}>
              Cox's Bazar
            </Col>
            <Col sm={6} md={3}>
              5
            </Col>
            <Col sm={6} md={3}>
            <Image
                src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Cox%27s_Bazar_Sunset.JPG/186px-Cox%27s_Bazar_Sunset.JPG"
                rounded
                responsive
              />
            </Col>
            <Col sm={6} md={3}>
              <div className="action">
                <Button bsStyle="primary">Update</Button>
                <Button bsStyle="danger">Delete</Button>
              </div>
            </Col>
          </Row>
          <Row className="item-row">
            <Col sm={6} md={3}>
              Bandarban
            </Col>
            <Col sm={6} md={3}>
              Bandarban
            </Col>
            <Col sm={6} md={3}>
              5
            </Col>
            <Col sm={6} md={3}>
              <Image
                src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Cox%27s_Bazar_Sunset.JPG/186px-Cox%27s_Bazar_Sunset.JPG"
                rounded
                responsive
              />
            </Col>
            <Col sm={6} md={3}>
              <div className="action">
                <Button bsStyle="primary">Update</Button>
                <Button bsStyle="danger">Delete</Button>
              </div>
            </Col>
          </Row>
          <Row className="item-row">
            <Col sm={6} md={3}>
              Sundarban
            </Col>
            <Col sm={6} md={3}>
              Sundarban
            </Col>
            <Col sm={6} md={3}>
              5
            </Col>
            <Col sm={6} md={3}>
            <Image
                src="https://upload.wikimedia.org/wikipedia/commons/thumb/2/21/Cox%27s_Bazar_Sunset.JPG/186px-Cox%27s_Bazar_Sunset.JPG"
                rounded
                responsive
              />
            </Col>
            <Col sm={6} md={3}>
              <div className="action">
                <Button bsStyle="primary">Update</Button>
                <Button bsStyle="danger">Delete</Button>
              </div>
            </Col>
          </Row>
        </Grid>
        <br />
        <Button bsStyle="primary">Create New Tourist Place</Button>
      </Grid>
    </div>
  );
}

export default ListComponent;

And here is my css file:

.list-header input {
  flex: 2;
  border-top: 1px solid black;
  border-right: 0px;
  border-left: 1px solid black;
  border-bottom: 0px;
  border-radius: 15px;
  padding: 0.5rem;
  background-color: #efefef;
}


.list-table {
  display: flex;
  flex-direction: column;
  /* align-items:center; */
  justify-content: center;
  flex-wrap: wrap;
  border: 1px solid black;
}

.action {
  display: flex;
  gap: 1rem;
}

.item-row {
  /* padding: 1%; */
  display: flex;
  /* flex-wrap: wrap; */
  justify-content: center;
  border: 1px solid black;
  text-align: center;
  border-bottom: 1px
 solid white;
}

What should I change in order to achieve the desired design? I tried different ways but this is the best I can get to.

how can i use hooks like ‘useState’ in async , await server component?

'use client'
async function Teachers (){
    const response = await fetch('http://localhost:8000/teachers',
        
    })
    const data = await response.json();
    const [showNames , setShowNames] = useState(false);

    const teacherHandler = ()=>{
    setShowNames (!showNames)
}
    return (
        
    <div className="mt-10">
        <div className=" text-center font-DanaDemiBold text-3xl text-white">
            <h1 className="w-full bg-slate-900 mb-5">Teachres</h1>
            <button onClick={teacherHandler} className="p-3 bg-green-600 rounded-lg mt-5">Show/Hide Teachers Name</button>
     );
        </div>
        <div className=" flex justify-center items-center flex-wrap p-2 gap-3 my-10 ">
            {
            !showTeachers?null :
            data.map(item=>(      
            <div key={item.id} className=" w-1/3 h-[300px] flex justify-between items-center shadow-lg bg-slate-300 rounded-lg  ">
                <div className="flex flex-col m-10 gap-y-5">
                <div className="flex gap-x-2">
                    <h3> Name: </h3>
                    <span>{item.firstname}</span>
                    <span>{item.lastname}</span>
                </div>
                <div className="flex gap-x-2">
                    <h3>    Email: </h3>
                    <span>{item.email}</span>
                </div>
                <div className="flex gap-x-2">
                    <h3>  Date of Birth: </h3>
                    <span>{item.birthDate}</span>
                </div>
                <div className="flex gap-x-2">
                    <h3>   phone: </h3>
                    <span>{item.mobile}</span>
                </div>
                <div className="flex gap-x-2">
                    <h3>     Address: </h3>
                    <span>{item.address}</span>
                </div>
                </div>
                <div className="w-36 h-36 m-10">
                    <img className="rounded-full" src={item.profileImg} alt="profile"/>
                </div>
            </div>
     ))}
   </div>
    </div>
    
    )
}

export default Teachers;

Thank for Your Answers. Please help me, I cant use Button and the function that handle button and I receive this error: Error: async/await is not yet supported in Client Components, only Server Components. Error: async/await is not yet supported in Client Components, only Server Components.

MediaRecorder API – call .requestData multiple times to create multiple audio blobs

I’m trying to create a simple frontend microphone using the MediaRecorder browser API that only requests user’s permissions once – the first time they click the “start recording” button.

To do this I never actually turn the microphone off, instead I toggle a flag when the user starts/stops recording and then call mediaRecorderRef.requestData(), which triggers an ondataavailable event handler, passing a blob parameter containing the audio data since the last ondataavailable call.

In theory this should allow me to have blobs that only contain the audio data since the flag was last toggled. I’ve seen someone correctly implement the behaviour I want but I cant get the code for it. see https://restream.io/tools/mic-test (notice how even when not recording, we can see the mic is still picking up audio – the animated bars are still moving behind the recording button)

here’s an example: https://stackblitz.com/edit/react-starter-typescript-mbxbsz

the problem is that only the first audio gets created, when trying to create all others i get the following error:

DOMException: Failed to load because no supported source was found.

Why did the device orientation alpha event stop working, even though everything was working recently?

I wrote a simple code to test the correct operation of the device orientation alpha event. And when I started the server for the first time, the event worked, that is, the angle was displayed. But when I restarted the server, the event stopped working. What could be the reason?

Restarting the server does not help, the event still does not return the angle.