Rust: Call `FnOnce` from `Fn`

I’m working with two different libraries (specifically napi-rs and callback-future) and want to invoke a FnOnce function from one library in a Fn function from another. Specifically, I’m trying to expose a Rust function to JavaScript which completes a Future when invoked.

Since the exposed JS function can technically be captured and invoked at any time, there is no way for Rust to guarantee that the function will only be called once, so it has to assume that the function will be called many times. However, callback-future requires that a Future is only completed once (via invoking an FnOnce). I can’t modify these two signatures, and they are both accurate for their respective use cases. How can I get the two to work together so I can resolve a Future in a Fn callback?

I understand that it’s not ok to invoke the FnOnce multiple times, and I’m ok with using unsafe code or otherwise enforcing at runtime that the function is only called once. Subsequent invocation attempts can be detected and rejected before calling the FnOnce, but I’m not sure how to communicate to the Rust compiler that I’m doing this and that it’s ok to allow the call to FnOnce. Currently what I have is:

// Create a `CallbackFuture` to wait for JS to respond.
// `complete` is an `FnOnce` to mark the `Future` as "Ready".
CallbackFuture::<Result<String, Error>>::new(move |complete| {
  thread_safe_js_function.call(Ok(Args {
    // Other arguments...

    // Callback for JS to invoke when done.
    // `Fn` because JS could theoretically call this multiple times,
    // though that shouldn't be allowed anyways.
    callback: Box::new(move |ctx| {
      let result = ctx.get::<JsString>(0)?.into_utf8()?.as_str()?.to_owned();

      // Complete the `Future` with the result.
      complete(Ok(result));

      ctx.env.get_undefined() // Return `undefined` to JS.
    }),
  }), ThreadsafeFunctionCallMode::Blocking);
}).await

This gives me the error:

error[E0507]: cannot move out of `complete`, a captured variable in an `Fn` closure
   --> node/src/lib.rs:368:15
    |
352 |           CallbackFuture::<Result<PathBuf, Error<BundleErrorKind>>>::new(move |complete| {
    |                                                                                -------- captured outer variable
...
358 |               callback: Box::new(move |ctx| {
    |  ________________________________-
...   |
368 | |               complete(Ok(result));
    | |               ^^^^^^^^ move occurs because `complete` has type `std::boxed::Box<dyn FnOnce(Result<PathBuf, Error>) + Send>`, which does not implement the `Copy` trait
369 | |     
370 | |               ctx.env.get_undefined()
371 | |             }),
    | |_____________- captured by this `Fn` closure

For more information about this error, try `rustc --explain E0507`.

While the error is complaining about moving between closures, my understanding is that this isn’t allowed because complete is FnOnce and I’m trying to call it from an Fn. If there’s another approach which solves the closure issue, then I guess that could be a viable solution too.

Also if there’s a way in N-API to accept a Promise result and await it instead of going through a callback, that could be a great alternative as well. I believe you can await a Promise in Rust, but AFAICT there’s no way to receive a synchronous result from a threadsafe N-API function as napi-rs seems to ignore the return value.

So far, the only solution I’ve found is to fork the callback-future API to change complete from an FnOnce to an Fn, which obviously isn’t a great solution. I also tried std::mem::transmute() from FnOnce to Fn thinking that forcing a cast that way would work as long as I only called the function once. However doing so segfaulted when invoked, so I don’t think it works the way I want it to here. Any ideas here are greatly appreciated!

Get name of an objetc while looping an array [duplicate]

So i have this:

const somObj = {
    whatever : 1,
}

const somObj2 = {
    whatever : 2,
}

const arrayOfObj = [somObj, somObj2]

Is there any way to get the name of the objects as strings while looping for the array like this?

for (i in arrayOfObj){
    something(arrayOfObj[i])
}

being the return the string “somObj”.

thank you

if (element.textContent.trim() === ‘Tea’) Does not exist?

I’m playing around with some code and I’m almost there but i can’t figure you this one last thing.

I’m using document.getElementsBy to look for a word in an Iframe, and it work.
And when it finds the word it goes on to another Function.

I want it to send an Alert(“not found”) if it does not find the word.
I really hope you can help me.

<script>function myFunction2() {
var iframe2 = document.getElementById("myFrame");
const allElements = iframe2.contentWindow.document.getElementsByTagName("li");
for (const element of allElements) {
console.log(element);
if (element.textContent.trim() === 'Tea') {
alert(element.textContent.trim());
}
}
}


</script>

DataTables not displaying data using ajax JSON data

i am using a function that take a JSON file and displaying the data in file into DataTable, using AJAX dataTables.

    $('#table4').DataTable({
        retrieve: true,
        processing:true,
        ajax: {
            url: "data.json",
            dataSrc: "Inventaire",
            crossDomain: true,
            dataType:"json"
        },
        columns: [
            { data: 'categorie' },
            { data: 'produitService' }
        ],
        "pageLength": 5
    });
});

When i try to run my files, i get the error below :

Access to XMLHttpRequest at 'file:///C:/Users/tifah/Documents/Bacc.%20Informatique%20et%20Genie%20logiciel%20Ete%202022/INF3190/publichtml/HTML/data.json?=1654390615223' from origin 'null' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, chrome-untrusted, https.

Moving a CSS Element Vertically Without JS

Is there anyway I can make an HTML div move down while scrolling instead of moving up without using javascript? I know you can use window.onscroll = function() { } and have that move the position of an object while scrolling, but is there anyway I can move an object down with just CSS and HTML?

How to add role to user after message is sent

I am using Discord.js to make my bot.
I want to add a role to a user after they use a command.
The command is !attack it will “kill” the person you pinged.

I think it might have something to do with Intents but I’m not sure. Here are my Intents right now,

const client = new Discord.Client({ 
    intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
  }, {
    partials: ["MESSAGE", "CHANNEL", "REACTION"]
  });

Also, here is the code for the !attack command,

var user;
var rollNum;
var role;

module.exports = {
  name: "attack",
  category: "info",
  permissions: [],
  devOnly: false,
  run: async ({client, message, args}) => {
    user = message.content.toLowerCase().split(" ");
    if(user[1] === `<@${message.author.id}>`){
      message.reply("You are not allowed to kill yourself.")
    }
    else{
      message.reply("Rolling...");
      rollNum = Math.floor(Math.random() * 10);
      if(rollNum >= 4){
        message.reply(`${user[1]} could not be killed. They are too strong for you lol.`);
      }
      else{
        message.reply(`${user[1]} is dead... R.I.P.`);
      }
    }
  }
}

how can I handle this type with only one parameter?

I have a model of these:

image: string;
redirect_option: 'PROFILE' | 'PRODUCT';
redirect: Product | User;

Now I render the list and want add a function:

const handleNavigateToRedirectedOption = ({ redirected_option, params }: { redirected_option: 'PROFILE' | 'PRODUCT'; redirect: Product | User;}) => {
    redirected_option === 'PROFILE' &&  navigation.navigate('UserProfile', params);
  };

const renderItem = ({ item }) => (
 <Pressable onPress={}>
   <Text>List</Text>
 </Pressable>
);

Now I get this error:

Argument of type 'IProduct | CurrentUser' is not assignable to parameter of type 'CurrentUser'.
  Type 'IProduct' is missing the following properties from type 'CurrentUser': user_id, profile_image, 

I know the problem but IDK how can I solve it. this comes at navigation…params

How to make changes immediately using MEAN stack?

problematic

Hello! I am wanting to make a (Like) button or I like it as it is commonly known for a social network, I already have the functions and services so that the user who is logged in can like and remove it, these changes are saved in the database data and I have a button with a counter of the stored likes of a publication, everything goes well when adding and removing the likes when clicking on the button but it takes time and the changes are asynchronous from the counter, that’s why I I want the changes to be made automatically without having to call the function (contarReacciones()) again

example

The registered user enters a publication and wants to like it but it takes a while to execute the functions of (darLike()—Enter the like of the user and of the publication in the database) and (contarReacciones() — -Shows the reactions counter of both the likes, comments and shares of the publication, the like is stored correctly in the database but until the contarReacciones() is executed, it takes at least 2 seconds until both functions are executed, so I want the changes to be reflected immediately.

publication.components.ts

Function that allows me to obtain the values ​​of Like, comments and shares of the publication

contarReacciones() {
    if (this.id != null) {
      this._reaccionesService.obtenerReacciones(this.id).subscribe(
        (data) => {
          if (data.likes != 0) {
            this.cont_likes = data.likes;
          } else {
            this.cont_likes = '';
          }

          if (data.comentarios != 0) {
            this.cont_comentarios = data.comentarios;
          } else {
            this.cont_comentarios = '';
          }

          if (data.compartidas != 0) {
            this.cont_compartidas = data.compartidas;
          } else {
            this.cont_compartidas = '';
          }
        },
        (error) => {
          console.log(error);
        }
      );
    }
  }

Function that allows me to verify if the registered user has already liked the publication, if it is true then it deletes it, otherwise it creates it.

verificarLike() {
    var usuario = localStorage.getItem('id');
    if (usuario != null && this.id != null) {
      this._reaccionesService.verificarLike(this.id,usuario).subscribe(
        (data) => {
         try {
          this.id_like = data[0]._id;
          this.eliminarLike();
         } catch (error) {
          console.log('No existe');
          this.darLike();
         }
        },
        (error) => {
          console.log(error);
        }
      );
    } else{
      console.log('Porfavor inicie sesión')
    }
    
  }

Function that saves the Like in the database

darLike() {
    var usuario = localStorage.getItem('id');
    if(this.id_like != ""){
      if (usuario != null && this.id != null) {
        const LIKES: Likes = {
          id_publicacion: this.id,
          id_usuario: usuario,
          fecha: this.fecha,
        };
        this._reaccionesService.agregarLike(LIKES).subscribe(
          (data) => {
            this.cambiarAspectoLike();
          this.contarReacciones(); 
            this.id_like = data._id;
          },
          (error) => {
            console.log(error);
          }
        );
      } else {
        console.log('Inicia sesión!');
      }
    }else{
        this.eliminarLike();
    }
    
  }

Function that allows me to delete the like in the case that I have already given it

 eliminarLike(){
    if(this.id_like !=null){
      this._reaccionesService.eliminarLikes(this.id_like).subscribe(
        (data) => {
          this.contarReacciones(); 
          this.defaultAspectoLike();
        },
        (error) =>{
          console.log(error);
        }
      )
    }
      
    

  }

Services (likes.service.ts)

 import { Injectable ,EventEmitter } from '@angular/core';
    import { HttpClient } from '@angular/common/http';
    import { Observable, ObservableLike } from 'rxjs';
    import { Likes } from '../models/likes';
    
    
    @Injectable({
      providedIn: 'root'
    })
    export class ReaccionesService {
      cambio = new EventEmitter<boolean>();
      url = 'http://localhost:4000/api/reacciones/'

  constructor(private http: HttpClient) { }

  agregarLike(likes:Likes): Observable<any>{
    return this.http.post(this.url,likes);
  } 

  obtenerReacciones(id: string):Observable<any>{
    this.cambio.emit(true);
    return this.http.get(this.url + id);
  }

  verificarLike(id_publicacion: string, id_usuario:string): Observable<any>{
        return this.http.get(this.url +id_publicacion + '/' + id_usuario )
  }

  eliminarLikes(id: string): Observable<any>{
    return this.http.delete(this.url + id);
  }
 
/*  editarLikes(id:string,usuario: string):Observable<any>{
      return this.http.put(this.url + id,usuario);
  } */
 

}

I was wanting to implement the emitter but I’m new to this and I don’t know how it can work for me.

ClearInterval() not working when clicking on another element?

I have 2 divs that are refreshed every 60 seconds. the run() function creates them both and is then put in an interval.

const interval = setInterval(function() {
    run();
}, 60000);

they look like so:

<div>
    <div class='Germany'></div>
    <div class='Italy'></div>
</div>

upon clicking either div, a small navigation bar is appended to a separate div with buttons like so. When each of these buttons are clicked, data about the div class is displayed. It looks like so:

<div>
    <div>Germany</div>
    <div>Italy</div>
</div>
<div class='navbar'>
    <button class='time'></button>                      //loads data about country clicked
    <button class='temperature'></button>               //loads data about country clicked
    <button class='vacation'></button>                  //loads data about country clicked
</div>

the API data in the buttons is updated every 60 seconds using setInterval(). Only the button with the class ‘clicked’ (applied through event listener) displays data.

Now if there was only a single country div, my program works perfectly. The issue is when I activate an interval for Italy and then click on Germany, the interval for Italy is still active and loads data for Italy every 60 seconds even though Germany is clicked. The elements for the Italy navbar are deleted when I click on Germany, but the interval still thinks the Italy navbar button has the ‘clicked’ class.

I have tried clearInterval(intID) when I click on the Germany div but the interval does not get cleared for whatever reason.

here is the appending and event listener adding for the button, this happens when a country is clicked.

let temperatureButton=document.createElement('button')
            temperatureButton.className='temperatureButton';
            temperatureButton.innerHTML='Temperature'
            navbar.appendChild(temperatureButton);

            temperatureButton.addEventListener("click", function(){ 
                temperatureButton.classList.add("active")
                temperatureButton.disabled=true
               

this is an example of the interval in one of the buttons:

const intTemp = setInterval(function() {
     if (temperatureButton.classList.contains('active')){
             runTempData();              // Append data to dom
     } else {
     clearInterval(intStat)
     }
     }, 10000);

I seriously cannot figure out why the interval does not get cleared after the button is deleted. Any help is appreciated.

How to use a MongoDB Search Index?

I am currently learning to build websites using Node JS, Express JS, MongoDB and Pug. I followed the Mozilla tutorial to understand the fundementals and now I want to add a search bar. I would like to profit from MongoDB search fonctionnalities, but after 3-4 days, I am still at basket case.

Can anyone explain how it is supposed to be done? The code is exactly as described in the tutorial/example website.

Also, I really don’t understand how this whole thing works, are there easier features to add or ways to ‘get it’ better? The debugger is an ocean of variables as I have never seen, and the slightest alterations to the example makes the whole thing sink. I am crying inside. Any help or resource is very welcomed.

Here is a link to a public repo (since it’s a lot of code for a blog post).

Public GitHub Repository

Image file upload with node.js

I’m trying to adapt my code to upload files, but I’m not getting it, I looked in the community and I didn’t understand, I’m still new to this. It always falls on the error json return, do you know what it can be?
File where you have the logic

async img(request, response){
    multer({
        storage: multer.diskStorage({
            destination: (req, file, cb) => {
                cb(null, "./Uploads")
        },
        filename: (req, file, cb) => {

            cb(null, Date.now().toString() + '-' + file.originalname)

        },
        fileFilter: (req, file, cb) => {
            const extensionImg = ['image/png', 'image/jpg', 'image/jpeg'].find
            (formatPermitted => formatPermitted == file.mimetype)

            if(extensionImg){
                return cb(null, true)
            }
                return cb(null, false)
            } 

       })

    }).single('image')

    if(request.file){
        return response.status(200).json({erro: false, message: "ok"});
    }else{
        return response.status(400).json({erro: true, message: "error"});
    }
} 

File where the route is

const IncidentsController = require('./controllers/IncidentsController');

const routes = express.Router();

routes.post('/uploads', IncidentsController.img)

Error: SQLITE_CANTOPEN: unable to open database file with electron-forge packed app

I’m using a sqlite database called sqlite.db in my app.
The database is located in the top directory of my app.

I test the app with npm start while developing. While testing, the database works fine.

After creating the app via npm run make (electron-forge), the database cannot be accessed with the following error: SQLITE_CANTOPEN: unable to open database file with electron-forge.

  • My first thought was a wrong directory in the code, but that doesn’t seem to be the issue after all.
  • Also the database itself is available in the packed application.
  • And it doesn’t seem to be a code issue as texting works fine:
    const sqlite3 = require('sqlite3');
    const { open } = require('sqlite');
    sqlite3.verbose();
    return open({
        filename,                    //filename='./sqlite.db' (actually a path)
        driver: sqlite3.Database
    });

This brings me to the conclusion, something must be wrong in the configuration for the app-building process via Electron Forge. But I have no clue if that assumption is correct – and if so, how to do that.

The closest I found to a fix was this similar issue but with Electron Builder – since I use Electron Forge, I wasn’t able to apply the suggested solution 1:1…

ViteJS aliased imports are not resolving

Converting a large monorepo ejected react app to vitejs, at least i am attempting to do so. However we use several aliased imports throughout the current app and i would like to leave that functionality there. We are currently using webpack.

ts.config file

  {
  "compilerOptions": {
    "target": "esnext",
    "allowJs": true,
    "skipLibCheck": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "noEmit": true,
    "jsx": "preserve",
    "lib": ["esnext", "dom"],
    "baseUrl": ".",
    "paths": {
      "src/*": ["src/*"],
      "@src/*": ["src/"],
      "@status/*": ["src/packages/status"],
      "@cli/*": ["src/packages/cli"],
    }
  },
  "include": [
    "./declarations.d.ts",
    "src",
  ],
}

vite.config file:


    import react from '@vitejs/plugin-react';
    import legacy from '@vitejs/plugin-legacy'
    import path from 'path';
    import { defineConfig } from 'vite';
    
    export default defineConfig({
      root: 'src',
      publicDir: './src/assets',
      plugins: [
        react({
          // Use React plugin in all *.jsx and *.tsx files
          include: '**/*.{jsx,tsx}',
          babel: {
            configFile: true,
          },
        }),
        legacy({
          targets: ['defaults', 'not IE 11']
        })
      ],
      resolve: {
        alias: {
          '@src': path.resolve(__dirname, './src'),
          '@status': path.resolve(__dirname, './src/packages/status'),
          '@cli': path.resolve(__dirname, './src/packages/cli')
        },
    
      },
      build: {
        outDir: 'build',
      },
      css: {
        preprocessorOptions: {
          scss: {
            quietDeps: true,
            javascriptEnabled: true,
          },
          sass: {
            quietDeps: true,
            javascriptEnabled: true,
          },
        },
      },
    });

Project structure is as follows:

 package.json
   vite.config
   ts.config
   src/
      packages/
      pages/
      index.html
      app/
         app.tsx

The specific error i am seeing in the console when i run vite serve src is

6:33:25 PM [vite] Internal server error: Failed to resolve import
“@cli/constants/ReviewText” from
“src/packages/cli/pages/review/Review.tsx”. Does the file exist?

Have scoured the interned and tried pretty much every variation of declaring the aliases in the vite.config and ts.config files. What is weird is that it seems that the ts compiler is at least recognizing the aliased path as it shows me it the full path when hovering over import statements, so i believe my problem is with the vite.config aliasing…

Issues trying to check a couple of RSS feeds (from a JSON config file) in Node.JS (using rss-parser)

I’m currently trying to make a node.js script to read a couple of RSS feeds from a JSON file (config.json), check everyone and send new items to it’s specific webhook for Discord.

The config file is the following:

[
  {
    "name": "r/aww",
    "avatar": "https://example.com/avatar.jpg",
    "rss_url": "https://www.reddit.com/r/aww/top/.rss",
    "webhook_url": "https://discord.com/api/webhooks/..."
  },
  {
    "name": "r/ImaginaryLandscapes",
    "avatar": "https://example.com/avatar.jpg",
    "rss_url": "https://www.reddit.com/r/ImaginaryLandscapes/top/.rss",
    "webhook_url": "https://discord.com/api/webhooks/..."
  }
]

And the code that i attempted to do, following sync examples from rss-parser npm package, is the following:

let Parser = require('rss-parser');

let parser = new Parser();

const config = require("./config.json");

config.forEach(element => {
    
    parser.parseURL(element.rss_url, function(err, feed) {
      console.log(feed);

      feed.items.forEach(function(entry) {
        console.log(entry.title + ':' + entry.link);
      });
    });

});

But trying to run it throws the following error:

undefined
/mnt/d/misc/feedchecker/script.js:28
          feed.items.forEach(function(entry) {
               ^

TypeError: Cannot read property 'items' of undefined
    at /mnt/d/misc/feedchecker/script.js:28:9
    at Timeout.setTimeout [as _onTimeout] (/mnt/d/misc/feedchecker/node_modules/rss-parser/lib/utils.js:63:29)
    at ontimeout (timers.js:436:11)
    at tryOnTimeout (timers.js:300:5)
    at listOnTimeout (timers.js:263:5)
    at Timer.processTimers (timers.js:223:10)

What I’m doing wrong on this code? Please note that i still didn’t wrote the webhook sending part, I’m focused still on fetching the feeds first.