GramJs `telegram` event handler takes too long to establish

I’ve noticed a weird behaviour lately with GramJs, according to the documentation here, it should be quite straightforward but as I have come to find out that my event handler takes about 5-10 seconds approximately to be established, and I have no idea why this is the case.
here’s my code

webSocketServer.on("connection", async (wsConnection, user) => {
 console.log(`User Connected`);
    wsConnection.isAlive = true;
    const me = {
      userId: user.entityId,
      username: user.entityFields.username._value,
      firstName: user.entityFields.firstName._value,
      phoneNumber: user.entityFields.phoneNumber._value,
      lastName: user.entityFields.lastName._value,
    };

const telegramSelf = JSON.parse(
      await redisHelper.getKey(`${me.userId}:telegram`)
    );
    if (
      telegramSelf?.telegramSession &&
      (await telegramService.checkSession(telegramSelf.telegramSession))
    ) {
      const telegramClient = await quickConnect(telegramSelf.telegramSession);
      console.log(`${me.username} Connected To Telegram`);
      telegramClient.addEventHandler(
        (event) => telegramService.eventHandler(event, wsConnection),
        new NewMessage({})
      );
    }
wsConnection.on("pong", function () {
      this.isAlive = true;
    });
 wsConnection.on("message", async (raw) => {
      const stringMessage = Buffer.from(raw).toString("utf8");
      const message = JSON.parse(stringMessage);
      if (message.event === "one-to-one-message") {
        if (
          !(await redisHelper.getKey(`${me.userId}:telegram`)) &&
          message.to === "Telegram"
        ) {
          wsConnection.send(
            JSON.stringify({
              event: "client-error",
              status: 403,
              message: "You are not linked to Telegram yet",
            })
          );
          return;
        }
        if (
          !(await redisHelper.getKey(`${me.username}:whatsApp`)) &&
          message.to === "WhatsApp"
        ) {
          wsConnection.send(
            JSON.stringify({
              event: "client-error",
              status: 403,
              message: "You are not linked to WhatsApp yet",
            })
          );
          return;
        }
      }
      events.eventHandler(message.event)(message, wsConnection, me);
    });
    wsConnection.on("close", async () => {
      // await redisHelper.deleteKey(`${me.username}:telegram`);
      console.log(`${me.username} Disconnected`);
    });
  });

so as it appears I’m triggering the message handler when a connection to my WebSocket server is made, and when that happens I check my redis key to see if the user has any sessions, if so I check the validity of the session and if it’s valid then I’m triggering the quickConnect function which simply initialises the client and connects it to Telegram, after that I establish the Event handler.
I’d appreciate the help as I’ve been suffering from this problem for weeks

Note: I’ve debugged the code multiple times and the async requests never seem to be holding the process at all, it takes less that one second for the code executer to be at the line where the eventHandler function is being triggered.

Why Autocomplete form in django doesn’t work

I have been trying several different kind of code for an autocomplte form with Django
Im new on this but here are the code:

Views.py

def search_ifsc(request):
    try:
        q = request.GET.get('q', '').capitalize()
        search_qs = InfoTrabajadores.objects.filter(documento__startswith=q)
        results = []
        print(q)
        for r in search_qs:
            dict_data = {'documento':r.documento,'nombres':r.nombres,'info':{
            'num_emergencia':r.num_emergencia,
            'prov_salud':r.prov_salud,
            'prov_salud_trabj':r.prov_salud_trabj,
            'rh':r.rh}}
            results.append(dict_data)
        data = json.dumps(results)
    except Exception as e:
        data = 'fail'+ f'n{e}'

    mimetype = 'application/json'
    return HttpResponse(data, mimetype)

This in the endpoint to filter te data with the document
Inside the document:

 <script type='text/javascript'>

  fetch('http://127.0.0.1:8000/ajax/search/')
  .then((response) => response.json())
  .then((data) => {
       document.getElementById('nombre').value = data.nombres;
      document.getElementById('num_emergencia').value = data.num_emergencia;
      document.getElementById('prov_salud').value = data.prov_salud;
      document.getElementById('prov_salud_trabj').value = data.prov_salud_trabj;
      document.getElementById('rh').value = data.rh;
    } )

And the urls.py

urlpatterns = [
    path('ajax/search/' , search_ifsc, name='search_view'),
] 

This is how the site looks with the actual code

I’ve been trying change de model and how the query works, but nothing change the response in the site

Prevent navigation defined in the element

I have a component in React/NextJS like this:

import Link from 'next/link';

 <Link className={styles.slidercontentbottom} href="/projects" onClick={(event)=> console.log(event.target)}> 
                <button onClick={goToPreviousSlide}
                  className={styles.sliderbtnleft}>
                    <AiOutlineArrowLeft/>
                </button>
                <div className={styles.sliderfeature}>
                  <h1 className={styles.featuretitle}>Some text</h1>
                  <p className={styles.featuretext}></p>
                </div>
                <button onClick={goToNextSlide} className={styles.sliderbtnright}><AiOutlineArrowRight/>
                </button>
              </Link>

which looks like this:
enter image description here

So it’s a page with a slider background, where you can slide images. When I click anywhere on the screen it goes to /projects, which is my intention EXCEPT with the button left and right. When I click on them it slides the image and then immediately goes to /projects. Is there a way to prevent the navigation to /projects after clicking the button?

How to execute setInterval at a later time in the code inside conditional statements in javascript?

I am trying to change the background color of my html page, every 200 milliseconds using setInterval on event of click on the button id = ‘button4’. And I want the changing of background color to stop when user clicks on the same button again.

The code for setInterval is executing as soon as I am assigning it to the var x where as I want to execute it when a condition is satisfied inside the ‘goCrazy’ function when it is called.

The clearInterval is working fine and the changing of colors is stopped.

Below is my code.

var x = setInterval(()=> {
    const rndInt1 = randomIntFromInterval(0, 255);
    const rndInt2 = randomIntFromInterval(0, 255);
    const rndInt3 = randomIntFromInterval(0, 255);
    document.body.style.backgroundColor = `rgb(${rndInt1}, ${rndInt2}, ${rndInt3})`;
    }, 200);

function goCrazy(){

    if (document.getElementById('button4').innerText == 'Go Crazy'){
        document.getElementById('button4').innerText = 'stop';
        x;
    }
    else{
        clearInterval(x);
        document.getElementById('button4').innerText = 'Go Crazy';
    }
}


function randomIntFromInterval(min, max) { // min and max included 
    return Math.floor(Math.random() * (max - min + 1) + min)
  }
  

How to wait for slow child function to run before returning? [closed]

If one has slow sync computational-heavy child function (simulated using setTimeout below), how can one write run to make sure processedItems is set before function returns (via return { processedItems })?

const items = [1, 2, 3]

const run = () => {
  const processedItems = []

  for (const item of items) {
    setTimeout(() => {
      processedItems.push(item.toString())
    }, 10)
  }

  return { processedItems }
}

const { processedItems } = run()

console.log(items, processedItems, processedItems.length)

// [1, 2, 3] [] 0

Desired run output is [1, 2, 3] ["1", "2", "3"] 3.

How to specify remote in Module Federation with Vue3 and share third party dependencies?

There are two vue 3 apps which I am currently running in two different ports, namely in 9000 and 9004. I want to share third party packages of the app running in 9000 and share with 9004 one and I want the resource size of the App2 to be less. They are independent apps but I am using Module Federation and want to share resources. How can I achieve this through ‘Shared’ of Module Federation?

So, I tried this.Making my app2 as remote, but again as of now they are not connectedApp2 where I want to share

How can I group by multiple condition in javascript?

I have the data in the below format:

[
  {
    "Id": 1,
    "Title": "Title_1",
    "Positive": 5,
    "CreateTs": 1674231433428
  },
  {
    "Id": 2,
    "Title": "Title_1",
    "Positive": 8,
    "CreateTs": 1674288139000
  },
  {
    "Id": 3,
    "Title": "Title_2",
    "Positive": 5,
    "CreateTs": 1674633970000
  },
  
  {
    "Id": 4,
    "Title": "Title_1",
    "Positive": 12,
    "CreateTs": 1674649613000
  },
  
  {
    "Id": 5,
    "Title": "Title_1",
    "Positive": 10,
    "CreateTs": 1674649741000
  }
  ]

And I want the result as below:

  [
    // group by Title, and CreateTs in current week
    // Sum up the grouped number of Positive
    {
      "Title": "Title_1",
      "Positive_sum": 22
    },
    
    {
      "Title": "Title_2",
      "Positive_sum": 5
    }
  ]

I found similar question, but I am not able to interrupt it, it is too complex for me…

I tried to use array.slice method and get the first few terms. But it is not guarantee as the data is in different order every time. And I found some complex method on internet and it seems not work for me. So I would like to ask for help here.

Problem with sending static js files to client browser with express.js

I want to develop a very basic blog app with express.js and I was trying to create a webpage where I could write a post from the browser and store it into a db after submitting it.

By searching on the internet I came upon the ckeditor package, which would allow me to format my blog post before submitting it to the database. I read the documentation and tried to integrate the package in the html code together with the javascript scripts necessary to load the software.

However, when I load the new_post page in my browser I see that the browser is not loading correctly the ckeditor even though I am serving the javascript script necessary to run it as a static resource through the express.static method.

Here you can find the necessary info to check my issue:

Project Structure:

project structure

app.js

const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");

const app = express();
const PORT = 5000;

const newPostRouter = require(".\routes\new_post.js");

app.set("view engine", "ejs");
app.use("/public", express.static(path.join(__dirname, "public")));
app.use(bodyParser.urlencoded({ extended: false }));

//Homepage
app.get("/", (req, res) => {
  res.render("homepage", { title: "My Express App", message: "Hello World!" });
});

//Write a new post
app.use("/new-post", newPostRouter);

//Listener
app.listen(5000, () => {
  console.log(`Server listening on port ${PORT}...`);
});

routes/new_post.js

const express = require("express");
const router = express.Router();
const path = require("path");


router.get("/", (req, res) => {
  res.render("new_post");
});

router.post("/", (req, res) => {
  const title = req.body.title;
  const content = req.body.content;
  res.redirect("/");
});

module.exports = router;

viewsnew_post.ejs

<!DOCTYPE html>
<html>
  <head>
    <script src="https://cdn.ckeditor.com/ckeditor5/35.4.0/classic/ckeditor.js"></script>
  </head>
  <body>
    <img src="..publicdog-img.jpg" alt="derp" />
    <h1>Classic editor</h1>
    <div id="editor">
      <p>This is some sample content.</p>
    </div>
    <script
      src="..publicjs_scriptsnew_post.js"
      type="applicationjavascript"
    ></script>
  </body>
</html>

publicjs_scriptsnew_post.js

ClassicEditor.create(document.querySelector("#editor")).catch((error) => {
  console.error(error);
});

As you can see I am trying to send the static resources to the client browser by using the express.static method in the app.js file. However when I try to load the page in the browser, this is the result I get:

result 1

The dog-img.jpg, also contained in the public folder, is correctly sent to the client yet the javascript file new_post.js is not.

I’ve also tried to modify the ejs file by substituting the script tag with

<script>
ClassicEditor.create(document.querySelector("#editor")).catch((error) => {
console.error(error);
});
</script>

When I do this the editor correctly loads in my browser:
result 2

Since I am trying to follow the best practices I’d like to keep my js files separated from the html/ejs files and therefore I’d like to call the scripts from an external source and not internally.

Can anybody help me understand what is wrong with my code?

Accessing and looping through data in Promise

I have a promise from Fetch that I use to get the list of countries from our API:

async fetchDataFromAPI () {
    console.log('fetchDataFromAPI')
    let response = await fetch(process.env.NEXT_PUBLIC_BRIDGEMAN_API_URL + '/countries',
        {
            method: 'GET',
            headers: {
                'Content-Type': 'application/ld+json',
                'Accept': 'application/json'
            }
        })
    let data = await response.json();
    return data
}

I call that promise inside of a class component in componentDidMount:

componentDidMount() {
    this.setState({countries: this.fetchDataFromAPI()})
}

Then when I pass it to the render function, Like this:

const {
    countries
} = this.state

console.log('state countries', countries)

I get the following output in my console:

Promise { <state>: "pending" }
                <state>: "fulfilled"
                    <value>: Array(244) [ {…}, {…}, {…}, … ]
                        [0…99]
                        [100…199]
                        [200…243]
                        length: 244
                        <prototype>: Array []
                            <prototype>: Promise.prototype { … }

All the data is there in the ”. I just dont know how to get at it?

I’ve tried countries.then((data) => {console.log('data', data)}) but I get the message that countries has no method .then. I’ve tried countries.map and that is the same error.

How can I loop through and output the data on the page?

WordPress: Ajax call doesn’t work (Error 400 Bad Request)

in simple words: Ajax is called from Javascript file, but php function doesn’t ‘hear’ the call.
In my case PHP and Javascript are in separate files. I proved that they are loaded correct in functions.php by:

    include get_stylesheet_directory() . '/custom/booking.php';
    wp_enqueue_script( 'script', get_stylesheet_directory_uri() . '/custom/booking.js', array( 'jquery' ), 1.1, true);

In “booking.php” at the top:

//Define AJAX URL and requests
function define_ajax_url() {
   echo '<script type="text/javascript">
           var ajaxurl = "' . admin_url('admin-ajax.php') . '";
         </script>';
}
add_action('wp_head', 'define_ajax_url');

// Action hooks that work with the WordPress AJAX functionality
// wp_ajax_nopriv_ action Hooks bewirken, dass der Ajax-Request auch bei Website-Besuchern läuft,
// die nicht eingeloggt sind.
add_action( 'wp_ajax_AjaxSessionIDerzeugen', 'AjaxSessionIDerzeugen' );
add_action( 'wp_ajax_nopriv_AjaxSessionIDerzeugen', 'AjaxSessionIDerzeugen' ); 

Problem: Also in the file “booking.php” the function that should be called, but unfortunately is never called:

// Ajax Session ID erzeugen
function AjaxSessionIDerzeugen() {
    $ip_adresse = $_SERVER["REMOTE_ADDR"];

    global $wpdb;
    $wpdb->show_errors();
    
    // $_REQUEST contains the data sent via AJAX from the Javascript call
    if ( isset($_REQUEST) ) {
        $session_id = substr(md5(time()), 0, 10);
        $strsql = sprintf("INSERT INTO tbl_buchungen (session_id) VALUES session_id= '%s'",$session_id);
        $wpdb->query($strsql);

        // Callback
        callback:
        $arr = array();
        $arr['pruefergebnis'] = "ok";
        $arr['session_id'] = $session_id;

        $antwort_json = json_encode($arr);
        echo $antwort_json;
    }
    // Always die in functions echoing AJAX content
   die();
}

In the file “booking.js” there is the Ajax-Call that doesn’t work.
Error: Failed to load resource: the server responded with a status of 400 (Bad Request)

if ((session_id == '') || (session_id == null)) {
            $.ajax({
                url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
                data: {
                    'action':'AjaxSessionIDerzeugen', // PHP function
                },
    
                // Callback
                success:function(antwort) {
                    let object = JSON.parse(antwort);
                    pruefergebnis = object.pruefergebnis;
    
                    if (pruefergebnis == 'ok') {
                        session_id = object.session_id;
                        document.cookie = "session_id=" + session_id + "; expires=3600000; path=/";
                    } else {
                        window.alert(pruefergebnis);
                    }
                },
                error: function(errorThrown){
                    window.alert(errorThrown);
                }
            });

        }

I can’t find the reason why it’s not working.

Accounts Database

I am creating a website using html, js and css on Replit with a signup and login system and I am trying to figure out how to store the usernames and passwords.

I have tried making JavaScript arrays by doing:

usernames = ["username1", "username2", "username3"]
passwords = ["password1", "password2", "password3"]

and then checking if the user inputted username and passwords are in the array and the placement number of each are the same but then anyone could go into inspect element or view source and see the passwords which is very bad for the security of the site. I have also tried putting them into a json file but the same thing applies. How could I store and retrieve the passwords securely?

This expression is not callable. Type ‘Promise Promise>’ has no call signatures in Typescript Web component

I have a web component in which there is a toggleSelection function. In it, I use functions imported from another file.

#toggleSelection = async (button) => {
    const hierarchySelector = this.shadowRoot?.querySelector(
      "fc-hierarchy-selector"
    ) as HierarchySelector;

    const filteredList =
      hierarchySelector.shadowRoot?.querySelector(".filteredList");
    const accordion =
      hierarchySelector.shadowRoot?.querySelector("apux-accordion");

    if (filteredList && accordion) {
      const filteredElements = filteredList.querySelectorAll(".node[selected]");
      const accordionElements = accordion.querySelectorAll(".node[selected]");

      const allElements = [...filteredElements, ...accordionElements];
      console.log("allElements", allElements);

      for (const node of allElements) {
        const name = node.querySelector(".name");
        if (name?.textContent?.trim() === button.value) {
          const checkbox = node.querySelector("apux-checkbox");
          const label = checkbox?.shadowRoot?.querySelector("label span");
          if (checkbox?.hasAttribute("checked")) {
            checkbox.removeAttribute("checked");
            node.removeAttribute("selected");
            checkbox?.classList.remove("indeterminate");
            label?.classList.remove("checked");
            label?.classList.remove("indeterminate");
          }

          const configElement = findConfigElement(this.configuration)(
            name?.textContent?.trim()
          );

          this.selectedItems = await toggleChildren(
            this.configuration,
            this.selectedItems
          )(allElements, node);

          console.log(" update:", this.selectedItems);
        }
      
      }
    }
export const toggleChildren =
 async (config, selectedElements) => async (nodes, node) => {
    const name = node.querySelector(".name")?.textContent?.trim();
    const isSelected = node?.hasAttribute("selected");
    const configElement = findConfigElement(config)(name);
    const children = findChildren(config)(configElement.id);
    console.log("od nowa");
    selectedElements = await toggleChildrenRecursive(
      config,
      children,
      isSelected,
      selectedElements,
      nodes
    );
    return selectedElements;
  };

export const toggleChildrenRecursive = async (
  config,
  children,
  isSelected,
  selectedElements,
  nodes
) => {
  let selectedElementsCopy = [...selectedElements];
  for (const node of nodes) {
    const name = node.querySelector(".name")?.textContent?.trim();
    for (const child of children) {
      if (name === child.name) {
        const childCheckbox = node.querySelector("apux-checkbox");
        const label = childCheckbox?.shadowRoot?.querySelector("label span");
        if (isSelected) {
          childCheckbox?.setAttribute("checked", "");
          node.setAttribute("selected", "");
          if (child.id && !selectedElementsCopy.includes(child.id)) {
            selectedElementsCopy.push(child.id);
          }
        } else {
          childCheckbox?.removeAttribute("checked");
          node.removeAttribute("selected");
          childCheckbox?.classList.remove("indeterminate");
          label?.classList.remove("checked");
          label?.classList.remove("indeterminate");
          selectedElementsCopy = [
            ...selectedElementsCopy.filter((el) => el !== child.id),
          ];
        }
        const childChildren = findChildren(config)(child.id);
        if (childChildren.length > 0) {
          selectedElementsCopy = (await toggleChildrenRecursive(
            config,
            childChildren,
            isSelected,
            selectedElementsCopy,
            nodes
          )) as string[];
        }
      }
    }
  }
  return new Promise((resolve) => resolve(selectedElementsCopy));
};

unfortunately when calling toggleChildren in toggleSelection it gets an error:(alias) toggleChildren(config: any, selectedElements: any): Promise<(nodes: any, node: any) => Promise>
import toggleChildren
This expression is not callable.
Type ‘Promise<(nodes: any, node: any) => Promise>’ has no call signatures.ts(2349)
Did you forget to use ‘await’?

I have an async before the toggleSelection function, what could the error be due to?

Three.js site displays black lines, caught problem only in one computer after trying in several different devices

I created a portfolio website with Threejs. After I published it, I tried accessing it in different browsers and devices and it worked fine.

I shared it with a few friends for feedback, and only one has gotten back to me with this strange shadow texture appearing throughout the canvas. See screenshot below:

enter image description here

He tried in different browsers, in the same device, and got the same result.

This is how it is supposed to look like, and how it looks everywhere I checked. See below:

enter image description here

Anyone has any idea why could this be?

I would like to make the site as compatible as possible.

Perhaps it is an issue with the rendered, or one of the tonemappings. I am using THREE.WebGLRenderer. Maybe it isn’t supported on his device which is a microsoft surfaces laptop.

Uncaught ReferenceError: writeFile is not defined when i tried to save a file

I am trying to save a txt file in the memory of the android phone using html/js and cordova, I have imported the plugin “cordova-plugin-file” and my code is as follows:

var fileName = "log_re.txt";
function guardararchivo(){

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fs) {
fs.root.getFile(fileName, {create: true}, function(fileEntry) {

    console.log("fileEntry is file?" + fileEntry.isFile.toString());

    writeFile(fileEntry, null);

    fileEntry.createWriter(function(fileWriter) {
        fileWriter.onwriteend = function() {
            console.log("Archivo guardado: " + fileName);
            readFile(fileEntry);
        };
    }, function(err) {
        console.log("Error al guardar el archivo: " + err.code);
    });


    if (!txt) {
        txt = new Blob(['some file data'], { type: 'text/plain' });
    }

    fileWriter.write(txt);


}, function(err) {
    console.log("Error al crear el archivo: " + err.code);
});
}, function(err) {
console.log("Error al obtener el sistema de archivos: " + err.code);
});

}

but when try it i have the error:
cordova.js:314 Uncaught ReferenceError: writeFile is not defined