Parse RemoveBG data results to Inner HTML element (eg. img.src)

I am trying to use the Remove.bg API in a plain JS file, with the goal of passing image URLS as parameters and then outputting the resulting image to an IMG tag within the HTML body.

Unfortunately, the project does not provide documentation for such usage, as the results.data is intended to be used by FileSystem’s writeFileSync, which I cannot use as I am running a static website.

Is there per chance, any way to parse the results as described and perhaps set an IMG tag’s src to the resulting, background-removed image?

Below is an example code that so far DOES return a response. Thank you in advance for your time!

   function removebackground(){    
            let formData = {
                "image_file_b64": "",
                "image_url": "https://meta.hapeprime.com/7386.png",
                "size": "preview",
                "type": "auto",
                "type_level": "1",
                "format": "auto",
                "roi": "0% 0% 100% 100%",
                "crop": false,
                "crop_margin": "0",
                "scale": "original",
                "position": "original",
                "channels": "rgba",
                "add_shadow": false,
                "semitransparency": true,
                "bg_color": "",
                "bg_image_url": ""
                };

            axios({
            method: 'post',
            url: 'https://api.remove.bg/v1.0/removebg',
            data: formData,
            responseType: 'arraybuffer',
            headers: {
                
                'X-Api-Key': 'API_KEY',
            },
            encoding: null
            })
            .then((response) => {
            if(response.status != 200) return console.error('Error:', response.status, response.statusText);
            console.log(response);
            
            })
            .catch((error) => {
                return console.error('Request failed:', error);
            });
        }

Why does it take so long to create an ObjectStore in IndexedDB?

I am learning and practicing the functions of the IndexedDB API according to the instructions of the site https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB

The problem that I still can’t figure out is why creating only one ObjectStore (without inserting data) takes so long.

enter image description here

As you can see, creating an ObjectStore with the name “06” took almost 2 minutes.

enter image description here

And in this operation of creating ObjectStore with the name “07”, it took nearly 3 minutes. As soon as I print the text “NOW”, the event IDBObjectStore.transaction.oncomplete will complete? Is this a browser bug or something?

enter image description here

enter image description here

Here is my code, it’s pretty simple. It consists of 5 basic functions :

  1. checkExistenceIDBDatabase
  2. createIDBDatabase
  3. checkExistenceObjectStoreInsideIDBDatabase
  4. getVersionIDBDatabase (IDBDatabase.createObjectStore can be called only within a versionchange transaction.)
  5. createObjectStoreInsideIDBDatabase
async function checkExistenceIDBDatabase (nameIDBDatabase)
{
    return new Promise(async function (resolve, reject)
                       {
                           let  IDBFactory = window.indexedDB;

                                IDBFactory
                                    .databases()
                                    .then
                                    (
                                        function (IDBDatabaseInfo)
                                        {
                                            for (let value of IDBDatabaseInfo)
                                            {
                                                if (value.name === nameIDBDatabase)
                                                {
                                                    return resolve(true);
                                                }
                                            }
    
                                            return resolve(false);
                                        }
                                    )
                       })
}

async function createIDBDatabase (nameIDBDatabase)
{
    let existenceIDBDatabase = await checkExistenceIDBDatabase(nameIDBDatabase);
    
        if (!existenceIDBDatabase)
        {
            let IDBFactory          = window.indexedDB;
            let IDBOpenDBRequest    = IDBFactory.open(nameIDBDatabase);
            
                IDBOpenDBRequest.onupgradeneeded = function ()
                {
                    console.log(`The IDBDatabase with name : ${nameIDBDatabase} has been created`);
                }
                
                /*
                * Then, event : IDBOpenDBRequest.onsuccess will be started.
                * */
        }
        else
        {
            console.log(`The IDBDatabase with name : ${nameIDBDatabase} already exist`);
        }
}

async function checkExistenceObjectStoreInsideIDBDatabase (nameIDBDatabase, nameObjectStore)
{
    return new Promise( async function (resolve, reject)
    {
        let existenceIDBDatabase = await checkExistenceIDBDatabase(nameIDBDatabase);
        
            if (!existenceIDBDatabase)
            {
                throw Error(`The IDBDatabase with name : ${nameIDBDatabase} don't exist. Infer, the IDBObjectStore with name : ${nameObjectStore} don't exist, too.`);
            }
            else
            {
                let IDBFactory          = window.indexedDB;
                let IDBOpenDBRequest    = IDBFactory.open(nameIDBDatabase);
                
                    IDBOpenDBRequest.onsuccess = function ()
                    {
                        let IDBDatabase = IDBOpenDBRequest.result;
                        
                            if (IDBDatabase.objectStoreNames.contains(nameObjectStore))
                            {
                                return resolve(true);
                            }
                            else
                            {
                                return resolve(false);
                            }
                    }
            }
    })
}

async function getVersionIDBDatabase (nameIDBDatabase)
{
    return new Promise(function (resolve, reject)
    {
        let IDBFactory  = window.indexedDB;
        
            IDBFactory
                .databases()
                .then
                (
                    function (IDBDatabaseInfo)
                    {
                        for (let value of IDBDatabaseInfo)
                        {
                            if (value.name === nameIDBDatabase)
                            {
                                return resolve(value.version);
                            }
                        }
                        
                        throw Error(`The IDBDatabase with name : ${nameIDBDatabase} don't exist. Infer, the version of this don't exist, too`);
                    }
                )
    })
}

async function createObjectStoreInsideIDBDatabase (nameIDBDatabase, nameObjectStore, inputKeyPath)
{
    let existenceObjectStoreInsideIDBDatabase = await checkExistenceObjectStoreInsideIDBDatabase(nameIDBDatabase, nameObjectStore);
        
        if (!existenceObjectStoreInsideIDBDatabase)
        {
            await console.log(`Step 01      existenceObjectStoreInsideIDBDatabase: ${existenceObjectStoreInsideIDBDatabase}`);
            
            let lastVersion             = await getVersionIDBDatabase(nameIDBDatabase);
            
            await console.log(`Step 02      lastVersion: ${lastVersion}`);
            
            let IDBFactory              = window.indexedDB;
            let IDBOpenDBRequest        = IDBFactory.open(nameIDBDatabase, lastVersion + 1);
            
                IDBOpenDBRequest.onupgradeneeded = function ()
                {
                    let IDBDatabase     = IDBOpenDBRequest.result;
                    let IDBObjectStore  = IDBDatabase.createObjectStore(nameObjectStore, {keyPath: inputKeyPath});
                    
                        IDBObjectStore.transaction.oncomplete = function ()
                        {
                            console.log(`IDBObjectStore.transaction.oncomplete`);
                            
                            console.log(`   nameIDBDatabase : ${nameIDBDatabase}`);
                            console.log(`   nameObjectStore : ${nameObjectStore}`);
                            console.log(`   inputKeyPath    : ${inputKeyPath}`);
                        }
                        
                        IDBObjectStore.transaction.error = function ()
                        {
                            console.log(`IDBObjectStore.transaction.error`);
                            
                            console.log(`   nameIDBDatabase : ${nameIDBDatabase}`);
                            console.log(`   nameObjectStore : ${nameObjectStore}`);
                            console.log(`   inputKeyPath    : ${inputKeyPath}`);
                        }
                        
                        IDBObjectStore.transaction.onabort = function ()
                        {
                            console.log(`IDBObjectStore.transaction.onabort`);
                            
                            console.log(`   nameIDBDatabase : ${nameIDBDatabase}`);
                            console.log(`   nameObjectStore : ${nameObjectStore}`);
                            console.log(`   inputKeyPath    : ${inputKeyPath}`);
                        }
                }
        }
        else
        {
            console.log(`The objectStore with name : ${nameObjectStore} already exists in the IDBDatabase with name : ${nameIDBDatabase}`);
        }
}

// await createObjectStoreInsideIDBDatabase("Babel", "08", "keyPath");

I’m using : Google Chrome 101.0.4951.41 (Official Build) (64-bit)

Why useEffect is running two times on my local machine? [duplicate]

Simple code of useEffect

import {useEffect,useRef} from “react”;

function App() {

const rendering = useRef(0);   
   useEffect(()=>{
console.log("insider useeffect",++rendering.current)   },[])

return ( <>

hello{rendering.current}

</> ); }

export default App;

But output is:
enter image description here

Why there is two console.log with an increment value of rendering.current?

when I run the same in codesandbox its console.log only once
enter image description here

MQL5, Python, Javascript integration. Two (or more) computers

Any MetaTrader/MQL + python integration gurus here?

It is my understanding (please correct me if I’m wrong) that I can follow the instructions here to build the equivalent of a MetaTrader 5 EA (Expert Advisor) in python instead of MQL5, calling the python functions on that documentation page to handle all the broker interaction, and all the other logic and calculations and whatever else can be in my python code.

Assuming I’ve understood that correctly, I want to extend that in the following way.

  1. Set up all they python stuff as per that documentation page, on a Windows PC (of course, because it won’t run on a Mac or anywhere else) — this is computer #1
  2. Build a platform-independent (ie. PC, Mac, Linux) node/javascript app that can run on any other computer — computer #2
  3. Computer #2 needs to somehow call the python functions on computer #1 when the functionality they provide is needed (getting tick, order, deal, position, etc. info; sending orders; etc.), and do everything else an EA and indicators would do (all the math, decision making, etc), in the javascript code on computer #2.

So, two questions:

  • Question 1. I’m 99% certain this is possible. I think it means setting up a web/API server on computer #1 (with node/python/both?) and then the JS app on computer #2 is a simple web client (browser, command line node app, etc.) that sends instructions to the computer #1 web/API server, just like any other kind of web based client-server app. However, that’s just my best guess, so is that an ok approach? 1a. If it is, I don’t know where to start, what to look up, how to even research it, let alone do it, or 1b. if that approach is significantly flawed, then what is the best/correct approach?
  • Question 2. I could be reading it wrong, but that documentation page seems to be focussed on using those MT5 python functions to collect data for external analysis. The suggestion there might be that these functions are not intended for interactive live algo trading. Perhaps they’re too slow for the high paced information exchange and manipulation required for live trading…? Or… is the idea of using these python functions for live algo trading perfectly reasonable?

Has anyone done any of this kind of thing? Can anyone advise if it’s reasonable and how I should approach this?

Thanks!

Anonymous phone call from Ionic

In my Ionic app (with Angular), I give the ability to the users to call a phone number (using the Call Number Plugin), in 2 different ways:

  1. Either publicly
  2. Or anonymously to mask their phone number, by prepending #31# to the callee phone number

No issue for the first case.

However, it doesn’t work anymore for the second mode (dialer doesn’t even open) whereas it used to work for a long time without any problem.

I also tried from a plain window.open:

window.open('tel:#31#XXXXXXXX')
window.open('tel://#31#XXXXXXXX')

but still doesn’t work, either on iOS or Android.

Strangely, this does work from Safari on iOS (not tested on Android):

<a href='tel://#31#XXXXXXXX'>Call me</a>

although I have to use tel:// and not tel: to avoid having the following exception: Failed to launch 'tel:#31#XXXXXXXX' because the scheme does not have a registered handler.

Has anyone ever experienced the same issue?

Bottle.py | request.forms.get() returning NoneType using AJAX

I am trying to send javaScript information into a bottle.py server using AJAX. After trying nearly every solution I could find on stackOverflow, bottle docs, or Google in general. No solutions have worked.

For clarity sake, I have only included the parts of the code pertaining to the AJAX call. Can anyone explain why request.forms.get is returning None, and how to correct that?

This is the JS code:

let rawData = {"user0Name": users[0],
     "user0Bucks": userBetaBucks[0],
     "user1Name": users[1],
     "user1Bucks": userBetaBucks[1],
     "user2Name": users[2],
     "user2Bucks": userBetaBucks[2],
     "user3Name": users[3],
     "user3Bucks": userBetaBucks[3],
     "user4Name": users[4],
     "user4Bucks": userBetaBucks[4]
    };

$.ajax({
    url: "/updateValues",
    type: "POST",
    dataType: "json",
    data: rawData,
    contentType: "application/json;",
});

This is the python code:

@post('/updateValues')
    def updateValues():
    session = load_session(request)
    gameID = session['gameID']
    rawInfo = json.load(request.forms.get('data'))

Note: ‘session = load_session(request)’ is a custom function created for retrieving cookies and loading them for later modification within this function. Such as the gameID you see here.

How can i use map on FileList array?

can i use map on FileList? the object is iterable so maybe there’s some way to make it work with map?

for example:

    window.addEventListener('drop', e => {
      e.preventDefault();
      if(e.dataTransfer?.files) {
        const files = e.dataTransfer.files.map(f => f.path); // imaginary code
      }
    })

How to res.render react app routes from express js?

I am using reactjs and express js to build my application
see the folder structure below
enter image description here

I have my app.js like this

const express = require("express");
const path = require("path");
const { db } = require("../database/db.js");
const session = require("express-session");
const store = new session.MemoryStore();
dotenv.config();
const app = express();
const PORT = process.env.PORT || 3001;
app.use(express.json());

// session
app.use(
  session({
    secret: process.env.SECRET,
    resave: false,
    saveUninitialized: false,
    store,
    cookie: {
      maxAge: 20000,
      secure: false,
    },
  })
);

app.use("/api/admin", adminRoutes);
app.use("/api/employee", employeeRoutes);

app.get("/api", (req, res) => {
  res.send("Api is running");
});

app.listen(PORT, console.log("server is running"));

And I have my react routes like this,

function App() {
  return (
    <div className="App">
      <Routes>
        <Route
          path="/admin"
          element={
            <>
              <AdminHeader></AdminHeader>
              <AdminHome></AdminHome>
            </>
          }
        ></Route>
        <Route
          path="/employee"
          element={
            <>
              <EmployeeHeader></EmployeeHeader>
              <EmployeeHome></EmployeeHome>
            </>
          }
        ></Route>
        <Route
          path="/"
          element={
            <>
              <Header></Header>
              <Home></Home>
            </>
          }
        ></Route>
      </Routes>
    </div>
  );
}

Below code is just an example code to give context of this question. This is another node js app.


app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.set("view engine", "ejs");
 app.use(express.static(__dirname + "/public"));
app.set("views", ["./views", "./screens"]);

app.use(
  session({
    secret: "f4z4gs$Gcg",
    cookie: { maxAge: 10000, secure: false },
    saveUninitialized: false,
    resave: false,
    store,
  })
);

function ensureAuthentication(req, res, next) {
  // Complete the if statmenet below:
  if (req.session.authenticated) {
    return next();
  } else {
    // res.status(403).json({ msg: "You're not authorized to view this page" });
    res.redirect("/login");
  }
}

// Add your ensureAuthentication middleware below:
app.get("/shop", ensureAuthentication, (req, res) => {
  // Send the user object to the view page:
  console.log("INSIDE ensureAuthentication....");
  console.log(req.session);
  res.render("shop", { user: req.session.user });
});

app.get("/login", (req, res) => {
  res.render("login");
});
app.get("/register", (req, res) => {
  res.render("screen");
});

// POST request for logging in
app.post("/login", (req, res) => {
  const { username, password } = req.body;
  db.users.findByUsername(username, (err, user) => {
    if (!user) return res.status(403).json({ msg: "No user found!" });
    if (user.password === password) {
      req.session.authenticated = true;
      req.session.user = {
        username,
        password,
      };
      res.redirect("/shop");
    } else {
      res.status(403).json({ msg: "Bad Credentials" });
    }
  });
});

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

look here the folder structure of this example node js app
enter image description here

with this kind of folder structure, here we can do res.render and render a view (login, shop, register).

So my question is, is there any way I could do the same using my original folder structure. Or more specifically, is thery any way I could do res.render(oneOfTheReactJsRouteHere).

Just in case you may be wondering why I want to do this? Here is why.
Right now everything is working properly and I am happy with that. Till now, I am using useEffect in reactjs to fetch data from backend and do the thing accordingly.
But there is one particular case, I want to login as admin and set the session accordingly and again I can check if the admin is logged in using useEffect in frontend to fetch data from backend and do the things. But this will be tedious to in every reactjs page, as I have to check if admin is logged in many different pages.
So, i was thinking if there is a better way. And I thought what if I could res.render(reactJSAdminLoginRoute) if the admin is not logged in right in the middleware of the backend. That would be convenient and I would not have to check about the admin login in the frontend.

That’s why I am asking this question.
I asked this question in many way and all downvoted and i had to delete. So here I am with this question. Thanks.

And I also want to know if am thinking correctly or if there is some better way to do this kind of checking.

Can check my github code here: https://github.com/amanc1248/aestheticproject

how to improve jquery javascript elements with equivalent id?

i have 5 modules with big equal js code, but only INT ID is different.

How to simple access to get one-style javascript jquery for all modules with dynamical id?
ok 3 int is num.
CODE eg:

$("#super_mod_519").find('form');
$("#super_mod_345").find('form');
$("#super_mod_430").find('form');
$("#super_mod_632").find('form');
$("#super_mod_234").find('form');
$("#super_mod_713").find('form');

$("#super_mod_519 .addtocart-button input").val('');
$("#super_mod_345 .addtocart-button input").val('');
$("#super_mod_430 .addtocart-button input").val('');
$("#super_mod_234 .addtocart-button input").val('');
$("#super_mod_632 .addtocart-button input").val('');
$("#super_mod_713 .addtocart-button input").val('');

Google Apps Script- Convert appendrow command to only fill in part of the target row

I have this code, which does a great job of grabbing data from scattered input cells and making them into a nice, tidy row.

function submitDataOhSoMuchFaster() {
  const ss = SpreadsheetApp.getActive();
  const values = ss.getActiveSheet().getRange('A1:Z13').getValues();
  const entry = [
    { column: 26, row: 12 }, // Z12
    { column: 3, row: 2 }, // C2
    { column: 14, row: 2 }, // N2
    { column: 3, row: 10 }, // C10
    { column: 6, row: 2 }, // F2
    { column: 3, row: 4 }, // C4
    { column: 5, row: 4 }, // E4
    { column: 3, row: 5 }, // C5
    { column: 5, row: 5 }, // E5
    { column: 12, row: 5 }, // L5
    { column: 12, row: 4 }, // L4
    { column: 26, row: 13 }, // Z13
    { column: 20, row: 4 }, // T4
    { column: 20, row: 5 }, // T5
    { column: 3, row: 6 }, // C6
  ];
  ss.getSheetByName('Master Log')
    .appendRow(entry.map(cell => values[cell.row - 1][cell.column - 1]));
  
};

However, as I am continuing on the project, I want to run some formulas on every row so that filter functions on other sheets have the information they need to know if they should show the rows or not. Those formulas will sit off to the right.

How do I convert the script above to put data into only the cells from column A until all the values have been entered, without minding that there are values to the right, rather than being defined as adding an entirely clean new row?

Turning irregular concave polygons to convex polygons when drawing polygons with google maps

I am writing some javascript code to draw polygons on a google map and I have a polygon that looks like below so far.

enter image description here

The problem I have is. I want a convex polygon. (Only an enclosed polygon). In other words, I want the polygon that I would get by connecting all the points I have marked with that red circles.

The trick to get such an enclosed polygon would be to remove the point that is marked as white from the polygon paths array. I attempted to do it and could not make it. Following is what I tried.

I am looping through an array of coordinates and drawing polygons like below,

        if(formattedCorrdinatesArr.length > 2) {

            const polygon = new google.maps.Polygon({
                paths: formattedCorrdinatesArr,
                strokeColor: color,
                strokeOpacity: 0.8,
                strokeWeight: 2,
                fillColor: color,
                fillOpacity: 0.35,
            });
                polygon.setMap(map);
        }

But I can not find a way to exclude that white point. Can someone please help?

How do I achieve live re-render without using state variables?

Consider the following array of objects:

const tasks = [
    {
      text: "Finish this page",
      deadline: new Date("05/01/2022"),
      status: "complete",
      // ToDo: Add priority fields
    },
    {
      text: "Finish Pierian UI/UX",
      deadline: new Date("05/10/2022"),
      status: "incomplete",
    },
    {
      text: "Finish Internship",
      deadline: new Date("05/05/2022"),
      status: "incomplete",
    },
    {
      text: "Anaadyanta",
      deadline: new Date("05/12/2022"),
      status: "incomplete",
    },
    {
      text: "Random task",
      deadline: new Date("05/19/2022"),
      status: "incomplete",
    },
  ];

Consider the following function:

{tasks.map((element) => {
        return (
          <p
            key={element.name}
            className={element.status === "complete" && "strike"}
            style={{ borderLeft: "2px solid red" }}>
            <Checkbox
              size="small"
              onClick={() => {
                if (element.status === "incomplete")
                  element.status = "complete";
                else if (element.status === "complete") {
                  element.status = "incomplete";
                }
                // ToDo : Add few things like popping
              }}
              color="success"
              checked={element.status === "complete" && true}
            />
            {element.text}
          </p>
        );
      })}

Now since element.status is not a state, changing its value doesnt re render the JSX element. How do I achieve this? I thought of using a state variable, but that when changed would reflect changes in all rendered elements and not only the current element.

Webpack 5 Module federation : Unable to Import the Remote app

I have a vanilla JS app and an Angular app. I am trying to link both these apps using module federation, both on my local environment. The following is webpack config file for vanilla js app which acts as remote

module.exports = {
    entry: ['./src/index.js'],
    output: {
        publicPath: config.get('publicPath')
    },
    module: {
        rules: [
            {
                test: /.js$/,
                exclude: /(node_modules)/,
                use: ['babel-loader'],
            }
        ]
    },
    plugins: [
        new HTMLWebpackPlugin({
            template: path.resolve(__dirname, 'demo/index.html')
        }),
        new ModuleFederationPlugin({
            name: 'remote',
            exposes: {
                './createWidget': './src/index.js'
            }
        }),
    ],

    devServer: {
        host: "localhost.remote.org",
        port: 8080
    }
};

I ran the webpack dev server, so hitting http://localhost.remote.org:8080/remote.js will give me the file. So this is the webpack of my Angular app which is consuming the remote app

module.exports = {
    devtool: 'source-map',
    context: __dirname,
    entry: {
        polyfills: './src/polyfills.ts',
        main: './src/main.ts'
    },
    ...
    ...
    plugins : [
        new ModuleFederationPlugin({
            name: "HostApp",
            remotes: {
                remote: "remote@http://localhost.finra.org:8080/remote.js",
            }
        }),
    ]
}

Not I am trying to import the dependency in my component.ts file as follows :

import * as Widget from 'remote/createWidget'

When I run ng serve, I get the module not found error. I’m not sure what exactly is going wrong. Can anyone help me in fixing this

Error: src/app/component1/component1.component.ts:30:28 - error TS2307: Cannot find module 'remote/createWidget' or its corresponding type declarations.

30 import * as Widget from 'remote/createWidget'

How to introspect elements kind in an array in V8

After reading this article: https://v8.dev/blog/elements-kinds. I was wondering if some of the arrays that are created in my code are packed or holey. Is there any way to check this at runtime in a browser environment(specifically Chrome)?
I am looking for something like a %DebugPrint() that works on Chrome.
Maybe there are some other clues that I can look for. For example, some info that is captured in heap snapshots, etc.