How can I perform bitwise operations in python exactly how javascript would?

I am trying to write the following javascript function in python

exports.hash = u => {
    u += 0xe91aaa35;
    u ^= u >>> 16;
    u += u << 8;
    u ^= u >>> 4;
    let a  = ( u + ( u << 2 ) ) >>> 19;
    return a ^ hashAdjust[ ( u >>> 8 ) & 0x1ff ];
};

Initially I came up with the following

def hash(u):
    u += 0xe91aaa35
    u ^= u >> 16
    u += u << 8
    u ^= u >> 4
    a = (u + (u << 2)) >> 19
    return a ^ hashAdjust[(u >> 8) & 0x1ff]

however I noticed the two functions return different results for large integer inputs. I did some debugging and realised its because javascript and python handle integers differently. Whilst python has unlimited precision integers, javascript uses 32 (signed) bit integers, meaning the maximum integer it can handle is 2^31 – 1, and the minimum is -(2^31 – 1), if an operation results in an integer exceeding these limits, the result gets truncated. I will be honest and admit I dont understand this completely, so I would appreciate if someone could explain this a bit more for me

my main question was how can I create a function for each of the bitwise operators (xor, left shift and right shift) used above to avoid this difference. I found one already for xor which works perfectly and kind of understood (again, would appreciate an explanation).

onMessage.addListener doesn’t always receive messages from sendMessage in google chrome extension

I communicate between my content script and my background script using chrome.runtime.onMessage.addListener to receive the message on the front in my content.js, and I send messages using chrome.tabs.sendMessage in the background.js script.

On the content.js script, at the start of the file, I have this:

chrome.runtime.onMessage.addListener((msg, sender) => {
  if (msg.command !== 'log') {
    console.log(msg);
  }

  // First, validate the message's structure.
  if (msg.command === 'Browse Startups') {
    // reset the list of startups browsed
    chrome.storage.local.set({'done': []}, function() {
      console.log('Startups Reset');
      chrome.runtime.sendMessage({'action': 'reset'});
    });
    browseStartups();
    return true;
  } else if ((msg.command === 'Check Startup')) {
    shouldStartupBeDone(msg.startup);
    return true;
  } else if ((msg.command === 'Do Startup')) {
    doStartupProfile(msg.url, msg.key, msg.total);
    return true;
  } else if ((msg.command === 'Do Teammate')) {
    doTeammateProfile(msg.startup, msg.teammate);
    return true;
  } else if ((msg.command === 'Save Startup')) {
    saveStartupProfile(msg.startup);
    return true;
  } else {
    console.log('ERROR: this command does not exist');
    return true;
  }
});

and on the background script I do this:

function startDoing(startup, tabId, key, total) {
    console.log('startDoing');
    chrome.tabs.sendMessage(tabId, { command: 'Do Startup', url: startup.url, key: key, total: total });
}

this function is called after the page finished loading like this:

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
    if (changeInfo.status == 'complete' && tab.active) {
        chrome.storage.local.get(['nextAction', 'startups', 'key', 'teammate', 'startup'], (request) => {
            console.log(request);

            chrome.storage.local.set({ nextAction: null }, () => {
                if (request.startups !== undefined && request.nextAction !== null) {
                    console.log('start');
                    setTimeout(() => {
                        startDoing(request.startups[request.key], tabId, request.key, request.startups.length);
                    }, 7000);
                }
            });
        });
    }
});

From the logs, I can see that when the page is loaded, my background script sends the message to the front, but the front does not receive it and nothing happens, the DoStartup function does not work and my script then breaks.

It does not happen all the time, maybe 1% of the time, but it’s enough to break everything.

Do you know why it happens? Is it the best way to launch a specific content.js script after the page finishes loading?

Here is my manifest:

{
    "manifest_version": 3,
    "name": "My App",
    "short_name": "My App",
    "description": "My App",
    "version": "1.0",
    "action": {
        "default_icon": "icon.png",
        "default_title": "My App",
        "default_popup": "popup/popup.html"
    },
    "icons": { 
        "16": "icon.png",
        "48": "icon.png",
        "128": "icon.png" 
    },
    "permissions": [
        "tabs",
        "activeTab",
        "cookies",
        "storage",
        "webNavigation"
    ],
    "background": {
        "service_worker": "background/background.js"
    },
    "content_scripts": [{
        "matches": [
            "http://*/*",
            "https://*/*"
        ],
        "js": [
            "vendors/jquery.min.js",
            "content/content.js"
        ]
    }]
}

Cypress – iframe in iframe

I have a problem with my app. I am trying to type in an element that is in two iframes.

First I´m trying to load first iframe and type in elements that are visible – it works perfect!

cy.frameLoaded('iframe');
cy.enter('iframe').then(getBody => {
            cy.wait(2000);
            getBody().find('input[data-bind="value: name"]').type("Název");
            getBody().find('textarea[data-bind="value: perex"]').type("Perex");
});

After that there is one last element that is in new iframe and I can´t type in it. If I inspect that element it shows me this:
F12

If I try this in Cypress, it´s still not working and Cypress can´t type in it:

cy.frameLoaded('iframe'); 
        cy.enter('iframe').then(getBody => {
            cy.wait(2000); 
            getBody().find('input[data-bind="value: name"]').type("Název");
            getBody().find('textarea[data-bind="value: perex"]').type("Perex");
        
            getBody().find('iframe.k-content').iframe().then(getEditorBody => {
                const editorContent = getEditorBody.find('body[contenteditable="true"]');
                cy.wrap(editorContent).click().type("Zde bude váš text.");
            });
            getBody().find('button.btn.btn-default').click();
        });

I´m using Kendo components if it helps.

Is there some way to solve this?

Thanks for all answers!

React add and edit record using data grid

trying to follow the React tutorial at the following link to CRUD data but can’t find why my code getAction does not receive any ‘id’ because of that isInEditMode is not true so my button doesn’t change to Save and Cancel


import React, { useEffect, useMemo, useState } from 'react';
import axios from 'axios';
import {  Box, Typography,} from '@mui/material';
import Button from '@mui/material/Button';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Close';
import EditToolbar from './EditToolbar';

import {
  GridRowModes,
  DataGrid,
  GridToolbarContainer,
  GridActionsCellItem,
  GridRowEditStopReasons,
} from '@mui/x-data-grid';

const AdminView = ()=> {
  const [rows, setRows] = React.useState([]);
  const [rowModesModel, setRowModesModel] = React.useState({});

  useEffect(() => {
    // Fetch user data from the database using Axios
    axios.get('http://localhost:3001/users')
    
      .then(response => {
        setRows(response.data);
      })
      .catch(error => {
        console.error('Error fetching user data:', error);
      });
  }, []);
  
  const [columns, setColumns] = useState([
    { field: "id"},
    { field: "staff_number", editable: true },
    { field: "name", editable: true },
    { field: "surname", editable: true },
    { field: "email", editable: true  },
    { field: "password", editable: true },
    { field: "access_level", editable: true },
    {
      field: 'actions',
      type: 'actions',
      headerName: 'Actions',
      width: 100,
      cellClassName: 'actions',
      getActions: ({ id }) => {
        console.log('get action:', rowModesModel[id]);
        const isInEditMode = rowModesModel[id]?.mode === GridRowModes.Edit;

        if (isInEditMode) {
          return [
            <GridActionsCellItem
              icon={<SaveIcon />}
              label="Save"
              sx={{
                color: 'primary.main',
              }}
              onClick={handleSaveClick(id)}
            />,
            <GridActionsCellItem
              icon={<CancelIcon />}
              label="Cancel"
              className="textPrimary"
              onClick={handleCancelClick(id)}
              color="inherit"
            />,
          ];
        }

        return [
          <GridActionsCellItem
            icon={<EditIcon />}
            label="Edit"
            className="textPrimary"
            onClick={handleEditClick(id)}
            color="inherit"
          />,
          <GridActionsCellItem
            icon={<DeleteIcon />}
            label="Delete"
            onClick={handleDeleteClick(id)}
            color="inherit"
          />,
        ];
      },
    }
  ]); 

  const handleEditClick = (id) => () => {
    setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.Edit } });
  };
  const handleSaveClick = (id) => () => {
    console.log('handleSaveClick:', id);
    setRowModesModel({ ...rowModesModel, [id]: { mode: GridRowModes.View } });
  };
  const handleDeleteClick = (id) => () => {
    setRows(rows.filter((row) => row.id !== id));
  };

  const handleCancelClick = (id) => () => {
    setRowModesModel({
      ...rowModesModel,
      [id]: { mode: GridRowModes.View, ignoreModifications: true },
    });

    const editedRow = rows.find((row) => row.id === id);
    if (editedRow.isNew) {
      setRows(rows.filter((row) => row.id !== id));
    }
  };



  const handleModeRowsChange = (newRowModesModel ) => {
    console.log('newRowModesModel change to:', newRowModesModel);
    setRowModesModel(newRowModesModel);
  }
  const handleRowEditStop = (params, event) => {
    console.log('handleRowEditStop params:', params);
    if (params.reason === GridRowEditStopReasons.rowFocusOut) {
      event.defaultMuiPrevented = true;
    }
  };

  const processRowUpdate = (newRow) => {
    console.log('processRowUpdate newRow returned:', newRow);
    const updatedRow = { ...newRow, isNew: false };
    setRows(rows.map((row) => (row.id === newRow.id ? updatedRow : row)));
    console.log('updatedRow returned:', updatedRow);
    return updatedRow;
  };

  return (

        <div>
            <DataGrid
              rows={rows}
              columns={columns}
              editMode="row" // allow all row edit
              checkboxSelection
              rowModesModel={rowModesModel} // control modes of rows
              onRowModesModelChange={handleModeRowsChange} // set the variable to control the row modes rowModesModel edit, view, add
              onRowEditStop={handleRowEditStop} // stop the edit mode
              processRowUpdate={processRowUpdate}
              slots={{
                toolbar: EditToolbar,
              }}
              slotProps={{
                toolbar: { setRows, setRowModesModel },
              }}
            />
        </div>

  );
};

export default AdminView;

my tooldbar button

import Box from '@mui/material/Box';
import Button from '@mui/material/Button';
import AddIcon from '@mui/icons-material/Add';
import EditIcon from '@mui/icons-material/Edit';
import DeleteIcon from '@mui/icons-material/DeleteOutlined';
import SaveIcon from '@mui/icons-material/Save';
import CancelIcon from '@mui/icons-material/Close';
import {
  GridRowModes,
  DataGrid,
  GridToolbarContainer,
  GridActionsCellItem,
  GridRowEditStopReasons,
} from '@mui/x-data-grid';
import {
  randomCreatedDate,
  randomTraderName,
  randomId,
  randomArrayItem,
} from '@mui/x-data-grid-generator';


function EditToolbar(props) {
  const { setRows, setRowModesModel } = props;

  const handleClick = () => {
    // Generate a unique ID for the new row.
    const id = randomId();  // Ensure `randomId` is a function that returns a unique ID.
  
    // Add a new row at the end of the grid with empty fields.
    setRows((oldRows) => [
      ...oldRows,  // Keep all existing rows.
      {
        id,  // Assign the new unique ID.
        name: '',  // Start with an empty name.
        surname: '',  // Start with an empty surname.
        email: '',  // Start with an empty email.
        password: '',  // Start with an empty password.
        access_level: '',  // Start with an empty access level.
        staff_number: '',  // Start with an empty staff number.
        isNew: true  // Flag this row as new for special handling like focusing.
      }
    ]);
  
    // Set the new row to be in edit mode, focusing on the 'staff_number' field.
    setRowModesModel((oldModel) => ({
      ...oldModel,  // Keep all existing row modes.
      [id]: { mode: GridRowModes.Edit, fieldToFocus: 'staff_number' }  // Set the new row to edit mode.
    }));
  };

  return (
    <GridToolbarContainer>
      <Button color="primary" startIcon={<AddIcon />} onClick={handleClick}>
        Add record
      </Button>
    </GridToolbarContainer>
  );
}

export default EditToolbar;

How to replace a div element in a string based on id with a tag [closed]

var str = `# Give utterance which should have Gdrive suggestions<br /># Now select one of the sheet from the dropdown<br /># Start asking questions on it<br /><br />*Actual* :<br /><br />GDriveLookup-When the user clicks on the relevant source chevron icon, noticed that it is displaying a Drive icon instead of displaying sheet icon on top of Drive icon<br /><br />*Expected* :<br /><br />It should display respective icons just like the icons displayed for sources<br /><br /><a href="https://twitter.com/hashtag/ *Screenshot* */ Video* : Attached<br /><br /><div  id="icon.png" data-name="icon.png" class="linear-background" style="width:'1154px';height:'527px';display: inline-block;" ></div><br />" class="linkMentionCls linkMentionCls-hashtag" target="*blank" rel="noopener noreferrer"># *Screenshot* */ Video** : Attached<br /><br /><div  id="icon.png" data-name="icon.png" class="linear-background" style="width:'1154px';height:'527px';display: inline-block;" ></div><br /></a>`

I am trying to replace <div id="icon.png" data-name="icon.png" class="linear-background" style="width:'1154px';height:'527px';display: inline-block;" ></div> inside str from all occurences based on id=”icon.png” with a <img src="abcde"/> tag.

Publishing websockets to be used with domains

I have a web app that uses laravel/react. I needed websockets for some runtime data transport and I used them in my application. I can connect my websocket server using ws://server_ip:port combination. But I have also a domain and I want to use the facalities of my domain, so I want to connect my server with ws://my_domain:port combination but I can’t for some reason. I looked at CloudFlare settings, nginx configurations etc. nothing is worked. Can somebody tell which steps should be done for binding a websocket server to a domain which points to that server?

Bootstrap Carousel Not Working with Multiple Instances

I’m trying to implement multiple Bootstrap carousels on my website, one for desktop and another for mobile, but I’m encountering issues with getting them to work properly. Here’s my HTML code:

<div class="d-none d-lg-block" id="carouselExampleIndicators-desktop" class="carousel slide" data-bs-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="images/home.png" alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="images/home1.png" alt="Second slide">
    </div>
  </div>
  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators-desktop" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators-desktop" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </button>
</div>

<div class="d-block d-lg-none" id="carouselExampleIndicators-mobile" class="carousel slide" data-bs-ride="carousel">
  <div class="carousel-inner">
    <div class="carousel-item active">
      <img class="d-block w-100" src="images/mobile1.png" alt="First slide">
    </div>
    <div class="carousel-item">
      <img class="d-block w-100" src="images/mobile1.png" alt="Second slide">
    </div>
  </div>
  <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleIndicators-mobile" data-bs-slide="prev">
    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Previous</span>
  </button>
  <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleIndicators-mobile" data-bs-slide="next">
    <span class="carousel-control-next-icon" aria-hidden="true"></span>
    <span class="visually-hidden">Next</span>
  </button>
</div>

However, despite following the Bootstrap documentation, the carousels are not functioning as expected. The indicators and controls are not working, and the slides are not transitioning.

Additional Information:

  • I have verified that the IDs and classes are correctly assigned.

  • I have checked the browser console for any errors, but there are no apparent issues reported.

What I Tried: I attempted to implement two Bootstrap carousels on my website, one for desktop and another for mobile.

Expectation: I expected both carousels to function properly, with working indicators and controls, allowing users to navigate through the slides seamlessly. The desktop carousel should only be visible on screens larger than lg (large), while the mobile carousel should be visible on screens smaller than lg.

Result: Unfortunately, neither of the carousels are working as expected. The indicators and controls are unresponsive, and the slides do not transition as intended. I have ensured that I included the necessary Bootstrap JavaScript and CSS files, verified the correct assignment of IDs and classes, and checked the browser console for errors, but I haven’t been able to identify the root cause of the issue.

How to display dropdown menu in javascript

I’m using a javascript to display a table in a django template. If the receipt’s is_disbursed value is True and the paid_status is Settled, I want the dropdown menu to contain Print only. If is_disbursed is False and the paid_status is Settled, it should display the Print, Disburse and the Reverse options. If is_disbursed is True and paid_status is Partially Paid, I want to display the Print, Collect Balance, and the Reverse options. If is_disbursed is False and the paid_status is Unpaid, the dropdown should contain Print, Collect Balance, and Reverse

#html

<div class="card-body">
   <div id="table-receipts" data-rent-receipt-url="{% url 'agency_rent_receipt' pk='PLACEHOLDER' %}" data-disburse-rent-url="{% url 'disburse_rent' pk='PLACEHOLDER' %}" data-rent-bal-url="{% url 'rent_balance' receipt_id='PLACEHOLDER' %}"></div>
</div


//js
<script>
document.addEventListener("DOMContentLoaded", function () {
const table = document.getElementById("table-receipts");

if (table) {
    const printReceiptUrl = table.getAttribute("data-rent-receipt-url");
    const rentDisbursementUrl = table.getAttribute("data-disburse-rent-url");
    const rentBalanceUrl = table.getAttribute("data-rent-bal-url");

    fetch('/accounting/receipts_data/api')
    .then(response => response.json())
    .then(receipt_data => {
        new gridjs.Grid({
            columns: [
                { name: "Receipt Number", width: "180px" },
                { name: "Date", width: "120px" },
                { name: "Address", width: "120px" },
                { name: "Tenant", width: "120px" },
                { name: "Status", width: "120px" },
                {
                    name: "Action", width: "100px", formatter: function (cell, row) {
                        const receiptId = row.cells[5].data;
                        const finalprintReceiptUrl = printReceiptUrl.replace('PLACEHOLDER', receiptId);
                        const finalrentDisbursementUrl = rentDisbursementUrl.replace('PLACEHOLDER', receiptId);
                        const finalrentBalanceUrl = rentBalanceUrl.replace('PLACEHOLDER', receiptId);

                        const isDisbursed = row.cells[7].data;
                        const paidStatus = row.cells[4].data;

            let dropdownContent = '';

            if (!isDisbursed) {
              dropdownContent += `<li><a class="dropdown-item" href="${finalprintReceiptUrl}">Print</a></li>`;
            }

            if (!isDisbursed && (paidStatus === 'Partially Paid' || paidStatus === 'Unpaid')) {
              dropdownContent += `<li><a class="dropdown-item" href="${finalrentBalanceUrl}">Collect Balance</a></li>`;
            }

            dropdownContent += `
              <li><a class="dropdown-item" href="${finalrentDisbursementUrl}">Disburse</a></li>
              <li><a class="dropdown-item" data-bs-toggle="modal" data-bs-target="#reversemodal-{{receipt.id}}">Reverse</a></li>
            `;

            return gridjs.html(`
              <div class="btn-group" role="group">
                <button id="btnGroupDrop1" type="button" class="btn btn-primary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">
                  Quick Actions
                </button>
                <ul class="dropdown-menu" aria-labelledby="btnGroupDrop1">
                  ${dropdownContent}
                </ul>
              </div>
            `);
          }
        }
      ],
            pagination: { limit: 5 },
            search: true,
            data: receipt_data.receipt_data
        }).render(table);
    })
    .catch(error => {
        console.error('Error fetching data:', error);
    });
}

});
#receipts_data

{
"receipt_data": [
[
  "SO0569",
  "2024-04-02",
  "123 Moreleta",
  "Nyasha",
  "Settled",
  "2f7****-***-******-********6", //uuid
  "SO0569",
  false],

How do I change a form elements values and action url just before submit in onclick

There’s a need to update a form data and in the same function – submit if the data is correct.

a flow in an onClick function:

  1. get the data from the server and update input fields’ values (I use $.each( result.post_vals, function( entry, new_val ) {$('#' +entry).val(new_val);}))
  2. update an action url (i use $('#form').attr('action', response.result.new_form_action_url) )
  3. submit the form, the page should ‘redirect’ – open a payment gateway page using the data I just updated.

And I experience quite a weird behavior – the values, I supposedly just updated via the $('#' +entry).val(new_val) call are not submitted while form URL is updated.

I tried to use several approaches playing with it 3 days, but failed.

Any idea?

The code (a bit simplified) as follows
// HTML

<form name="cart_form" id="cart_form" class="form-inline" method="post">
<input type="hidden" name="pp_biz_id" value="">
     <input type="hidden" name="pp_user_guid" value="">
     <input type="hidden" name="pp_parm1" value="">
     <input type="hidden" name="orderid" value="">
     .....
     <input type="hidden" name="pp_doc_name" value="">
     <input type="button" name="checkout" value="DO IT">
</form>

// JS

    $(document).on('click','[name="checkout"]',function()   {
    //e.preventDefault();
        console.log('shopping_cart_save_addr')
    var form = $('#cart_form');
    var pageData = form.serialize()
        console.log(pageData); 
        $.ajax({
            type: "POST",
            url: "get_data.php",
            data: pageData,
            dataType: 'json',
            success: function(response) {
                console.log(response);
                if(response.success){
                    if(response.result){
                        if (response.result.form_url) {
                            $('#cart_form').attr('action', response.result.form_url);
                        }
                        if (response.result.post_vals) {
                            console.log(response.result.post_vals)
                            $.each( response.result.post_vals, function( entry, new_val ) {
                                $('#' +entry).val(new_val);
                                console.log(entry + ': ' + new_val);
                            });
                        }
                    }
                    $('#cart_form').submit();
                } else {
                    console.log(response);
                    if (response.result.html) {
                        $('#result').html = response.result.html;
            }}}
        });});});

PROBLEMS:

  • When I use onClick(), I’m unable to update input values just before the form submit.
  • When I use onSubmit(), I’m unable to update the action url before submit OR my call is performed in the background, what is not my intention

// and yes, it looks I read and tried all the materials here, including Changing name of keys,values and action url of form before submit

Openstreetmap: Get ‘best’ tile for a given bounded box

I’ve been experimenting with the OSM tile server (https://tile.openstreetmap.org/) and have been converting lat/long to tile coordinates for embedding the tile into a web page.

However, what I actually need to do is find the ‘best’ tile for a given bounded box. I currently have four coords for the min and max lat and long. What I would like to get is the most ‘zoomed in’ tile that includes these coordinates.

This may look like:

  1. Calculate the average coordinate for the centre of the tile
  2. Find the right zoom level to include all bbox coordinates

Is this possible? (I’m working in JS but all answers gratefully received)

Getting data from database instead of json file

My project is using Laravel, but it takes the data from Json in the javascript file, but I want to put the information in my database, how can I do this?

javascript file:

var dt_user_table = $('.datatables-users'),
    select2 = $('.select2'),
    userView = 'app-user-view-account.html',
    statusObj = {
      1: { title: 'waiting', class: 'bg-label-warning' },
      2: { title: 'active', class: 'bg-label-success' },
      3: { title: 'notactive', class: 'bg-label-secondary' }
    };

if (dt_user_table.length) {
    var dt_user = dt_user_table.DataTable({
      ajax: '../../../asset/assets/' + 'json/user-list.json', // JSON file to add data
      columns: [
        // columns according to JSON
        { data: '' },
        { data: 'full_name' },
        { data: 'role' },
        { data: 'current_plan' },
        { data: 'billing' },
        { data: 'status' },
        { data: 'action' }
      ],

????????????????????

Where does clear() method reside?

clear() is a method of the console object just like log(). console.log(), console.clear() work as expected but only writing clear() also works without prefixing with the object where it lives.
It seems like the clear() method also lives on the global object window. But I can’t find it in the window object.

mdn says console methods are instance methods on the sidebar but in the title, it says ‘console: clear() static method’.

Can something be a static and an instance method at the same time?
What is going on here?enter image description here

Why does scrolling get stuck after the 5th item in a long array on Vite, but not on CRA?(“react”: “^18.3.0” on both)

“I have an array with an average of 20 items displayed in my React application. When running the application with Vite, I encounter an issue where scrolling gets stuck after the 5th item for a fraction of a second. However, when I use Create React App (CRA), the scrolling works smoothly without any issues.

I’ve ensured that the same code is used in both projects, and there are no errors or warnings in the browser console. I’ve also checked for compatibility issues with dependencies and reviewed the Vite configuration, but I haven’t been able to identify the cause of the problem.

Has anyone else encountered similar scrolling issues with Vite, particularly when rendering a long array in a carousel component? Any insights or suggestions on how to troubleshoot and resolve this issue would be greatly appreciated. Thank you!”

Appwrite creates new user in Auth but doesnt create it in users database

export const createUser = async (email, password, username) => {
try {
    const newAccount = await account.create(ID.unique(), email, password, username) // try to create new acc

    if (!newAccount) throw Error; // if can't create

    const avatarUrl = avatars.getInitials(username) // if created new account, create an avatar

    await signIn(email, password)

    const newUser = await databases.createDocument(
        databaseId,
        userCollectionId, 
        ID.unique(),
        {
            accountId: newAccount.$id,
            email,
            username,
            avatar: avatarUrl
        }
    )

    return newUser;

} catch (error) {
    console.log(error);
    throw new Error(error)
}

}

This function creates a new user in Auth directory, but it fails to add a user to the database > users folder that i created. I double checked for any errors inside the appwrite folder config but i cant find any… All users are permitted to do anything with the database for now and it’s still not working.

When firing the click function by cliking the child div, how can get the parent event?

const onMenuItemClick = (event) =>{
    console.log("onMenuItemClick data-id",event.target.getAttribute('data-id'));
}

html (JSX) is like this below,

One parent div which has two children div

<div onClick={onMenuItemClick} data-id="show">
         <div className={styles['contextIconBox']}>
          <img src={btn_delete} className={styles['contextIcon']}/></div>
          <div className={styles['contextLabel']}> myarea</div>
         </div>
</div>

When cliking this div onMenuItemClick is called

However data-id is not fetched(data-id is null),

I guess maybe, this is becasuse onMenuClick is fired but event is not the parent div?

How can I get dhe data-id here?