i18next will not load custom namespace

I have an instance of i18next running as it should if I include the translations inside the init:


i18next.use(httpAPI).init({
    lng: language,
    resources: {
      en: {
        translation: {
          "html1": "foo! ",
          "html2":"bar",
        }
      },
      de: {
        translation: {
          "html1": "de-foo",
          "html2":"de-bar",
    
        }
      }
  }
})

However, I expect to be expanding my translations, and placing them in the init would become unwieldy. So I would like to split them into multiple files. I have read about using i18next.http-backend. So when I re-write my init to include the backend my init looks like this:

i18next.use(httpAPI).init({
    lng: language,
    backend:{ loadPath: '/locales/de-DE/translate.json'}
})

the translate.json file looks like this:

{"translation": {
  "html1": "backend-de-foo",
  "html2": "backend-de-bar",
}}

My main script where I am calling the i18next is in the parent directory along with my locale folder.

It does not appear to be reading from the backend loadpath, as I am not getting any translations from it. Am I missing something from i18next or is my translate file not structured properly?

Is it possible to connect an html form with an online database website?

Is it possible to connect an html form with an online database website? I found the code below with the use of php but, my sql database is on a company website so, I cannot use localhost. Is there any other way to connect the html form with the url database? So, what I want to achieve is for customers to complete my form and then the data will be automatically updated in the database. Thank you in advance!

$con = mysqli_connect(“localhost”,”your_localhost_database_user”,”your_localhost_database_password”,”your_localhost_database_db”);

Please help figuring out BottleNeck. and events in Node

I am building a project. The part I am working on right now is supposed to do the following:

  1. log in to the platform using Id and Password (done)
  2. Take the array of data (hardcoded for now)
  3. perform an API call using each element of the array, get the result for each and put it to another array
  4. In a nutshell By passing an array of ids as an Input I should get an array of its results as output

To simplify the problem even more, I have decided to use one id and pass it 1000 times instead of array of 1000 different values.

LIMITATIONS:
I can call the API 300 times per minute or else I’d get the famous “429 problems” ->

My application does not use express. I was looking for alternatives and came across bottleNeck package Here
It does exactly what I need and is supposed to limit API calls as well as perform things as retries in case of failure or events management (see the documentation in the link above).

Here is a what I have so far:

const BottleNeck = require('bottleneck');
const logger = require('./functions/logger');
/**
 * this reservoir is allowed to execute 300 requests/ minute
 */
const limiter = new BottleNeck({
    reservoir: 300, // 300 requests per minute
    reservoirRefreshAmount: 249,
    reservoirRefreshInterval: 60 * 1000, // must be divisible by 250

    trackDoneStatus: true,

    minTime: 300//5 requests per second
});
limiter.on("debug", function (message, data) {
    // Useful to figure out what the limiter is doing in real time
    // and to help debug your application
});
limiter.on("depleted", function (empty) {
    logger.info(`BottleNeck() - reservoir is empty. Waiting... ${limiter.options}`);
    // This will be called every time the reservoir drops to 0.
    // The `empty` (boolean) argument indicates whether `limiter.empty()` is currently true.
});
limiter.on("dropped", function (dropped) {
    // This will be called when a strategy was triggered.
    // The dropped request is passed to this event listener.
});
limiter.on("empty", function () {
    // This will be called when `limiter.empty()` becomes true.
});
limiter.on("error", function (error) {
    /* handle errors here */
    logger.error(`Limiter : fetched error ${error.message}`);
});

// Listen to the "failed" event
limiter.on("failed", async (error, jobInfo) => {
    const id = jobInfo.options.id;
    console.warn(`Job ${id} failed: ${error}`);

    if (jobInfo.retryCount === 0) { // Here we only retry once
        console.log(`Retrying job ${id} in 25ms!`);
        return 25;
    }
});

limiter.on("idle", function () {
    // This will be called when `limiter.empty()` is `true` and `limiter.running()` is `0`.
});
limiter.on("queued", function (info) {
    // This event is triggered when a job transitions from one Lifecycle stage to another
});
// Listen to the "retry" event
limiter.on("retry", (error, jobInfo) => console.log(`Now retrying ${jobInfo.options.id}`));

module.exports = { bottleNeck: limiter };

(assume that logger is defined using logs4js or any other.

The main piece of code :

const { logger } = require("./functions/logger");
const { moment } = require("moment");
const { toCloudLogin, youOnlyHadOneJob } = require("./functions/toCloud");
const { bottleNeck } = require("./apiBottleNeck");



const go = async () => {
    try {

        logger.info(`hello`);
        await toCloudLogin();


        logger.info(`starting the bottleneck`);
        let counter = 0;
        for (let x = 0; x < 310; x++) {                           //calling same job through bottleneck many times
            counter+=1;
            let reservoir = await bottleNeck.currentReservoir(); // returns integer of the current 
                                                                 // reservoir api calls left
            const result = await bottleNeck.schedule(async () => youOnlyHadOneJob(reservoir));

        }
        logger.info(`finished the bottleneck` + counter)

    } catch (e) {
        console.log(e);
        logger.error(`error: ${e.message} stack :${e.stack}`);
    }
}
go();

Here are my questions:

  • If bottleNeck is supposed to filter the amount of API calls , why do I still get Maximum call stack size exceeded knowing that I launch with 300 storage (which is actually 301 with 0) and 300 recharge

  • how should I implement all these events ( for example depleted:

limiter.on("depleted", function (empty) {
    logger.info(`BottleNeck() - reservoir is empty. Waiting... ${limiter.options}`);
    // This will be called every time the reservoir drops to 0.
    // The `empty` (boolean) argument indicates whether `limiter.empty()` is currently true.
});

) In my main function so that it sends me anything when reservoir is empty. I have read on event Emitters and i assume that i should limiter.emit(depleted) somewhere but I do not understand how to properly integrate it.

JavaScript callback / async problem? Background script of Chrome Extension stops function before finishing

I am trying to create a small crawler as a chrome extension. How it works is:
Open new window or tab.
Perform a search for Google / Google News / YouTube with given keywords.
Store information of the results in a small database

I first created and tested the functions with a popup.html. There it works perfectly.You click on a button and all pages are visited and the results are stored in a database. But I want to start the program without clicking anything first. That’s why I migrated it to background.js. There it also works, but only if the Service Worker / DevTool console is open. Only then it runs completely.

I would be grateful for any helpful answer.

const keywords = [
    "Keyword1",
    "Keyword2",
    // ...
    "Keyword13"
];

chrome.runtime.onStartup.addListener(() => {
    chrome.tabs.onUpdated.addListener(loadingWindow);
    openWindow();
});

// Opens new Window or Tab with the correct URL
function openWindow() {
    chrome.tabs.onUpdated.addListener(loadingWindow);
    if (runs == 0) {
        chrome.windows.create({ url: getUrl(keywords[runs]), type: "normal" }, newWindow => {
            window_id = newWindow.id;
        });
    } else {
        chrome.tabs.update(tab_id, { url: getUrl(keywords[runs]) });
    }
}

// Wait to load the new tab
function loadingWindow(tabId, changeInfo, tab) {
    if (changeInfo.status === 'complete' && tab.status == 'complete' && tab.windowId == window_id) {
        tab_id = tabId;
        console.log(tab.windowId);
        chrome.tabs.onUpdated.removeListener(loadingWindow);
        chrome.tabs.sendMessage(tab.id, { text: source }, doStuffWithDom);
    }
};

// Get information from content script -> payload and then send to database
function doStuffWithDom(domContent) {
    let payload = {... }
    var data = new FormData();
    data.append("json", JSON.stringify(payload));
    fetch(".../store.php", { method: "POST", body: data });
    crawlDone();
}

// open new window / tab or close the open window
function crawlDone() {

    runs++;
    if (runs < keywords.length) {
        openWindow();
    } else if (runs == keywords.length) {
        chrome.windows.remove(window_id);
    }
};

If the value in the price class in HTML is equal to a string, how can it be discarded and not counted and sum the rest of the values of type Number

I have this code, but I want to add it in case if the value in the price field is equal to a string, how can this value be discarded and not counted and sum the rest of the values of type number

var theSummry = 0;
$(".price").each(function() {
  theSummry += parseInt($(this).text());
})
$(".the-total").text(theSummry);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table style="width:70%;text-align: center;margin: 30px auto;">
  <tr>
    <th>Person 1</th>
    <th>Person 2</th>
    <th>Person 3</th>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td>Linus</td>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td class="price">10</td>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td class="price">qwe</td>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td class="price">10</td>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td class="price">30</td>
  </tr>
  <tr>
    <td>Emil</td>
    <td>Tobias</td>
    <td class="price">10</td>
  </tr>
  <tr class="the-total"></tr>
</table>

I have Fetched Value from Ajax to the Input but when I put in alert after that, It shows NaN, Even I can See the Value in input box [closed]

I have used code of ajax to fetch the value, It appears in input box, but when I pass value to alert it show NaN and If I inspect the Input Box in code, Value not showing.

In Html Page I can see value in input box but not in inspect element, So I am unable to use this value further as its showing NaN in alert.

VSCode’s Find all references/Go to definition does not work

I have:

  • mono repository, more projects inside
  • js/ts, react
  1. When Find all references is tried on react component (I suppose on anything) that is imported in another project inside monorepo, it starts finding references.
  2. Initializing JS/TS language features starts – from Typescript and Javascript Language Features built-in extension.
  3. It takes about 2 minutes (depends on project size)
  4. After that references outside project/folder are not found
  5. During that process I cannot use Go to definition

I have also solution and will be written in answer below to help other folks (maybe my future me :D) to not waste halfday as I did on this 😉

How can I export images path with require() from one index.js file in react naitve?

I want to export all images from one file which index.js so that If in future I have to change the path of image then I have to only make changes in one file.

like this:

export {default as avatar} from './avatar.png';
export {default as career} from './PsychoScreenImages/career.jpeg';
export {default as application} from './redeemIcons/application.jpeg';
export {default as featured} from './redeemIcons/featured.jpeg';

But I can’t do like this require(avatar) as it requires the only a path. So, How can I export and import images from just one js file?

How to add Redis environmental variables in virtual event starter kit by vercel (NextJS)

I just started next.js and javascript as a whole. I am stuck in a problem, that if anyone explains would be cool. So, I started using the virtual event starter kit template in vercel which is made using NextJS. I was able to set up everything, except the redis (Upstash) part. I am not sure on how to set it up, if anyone could go through the docs and explain me would be really cool

Thanks

Download files automatically through firefox with nodeJS and webdriverio

I want to verify file download using NodeJS and Webdriverio. The file to download is of PDF format. When WebDriverIO clicks on “Download” Firefox opens up the following download confirmation window:download confirmation pop-up

I want Firefox to download the file automatically without showing above confirmation window, so I used the below code:

 conf_firefox.js file
require('dotenv').config();
const path = require('path');
const merge = require('deepmerge');
const baseConfig = require('./wdio.conf_base');

exports.config = merge(baseConfig.config, {
  services: ['selenium-standalone'],
  capabilities: [
    {
      maxInstances: 2,
      browserName: 'firefox',
      'moz:firefoxOptions': {
        prefs: {
          'browser.download.dir': path.join(__dirname, '../test-data/tmp/download/firefox'),
          'browser.helperApps.neverAsk.saveToDisk': 'application/pdf',
        },
      },
      acceptInsecureCerts: true,
    },
  ],
});

but still Firefox shows the same window. How can I set Firefox profile so that PDF files are downloaded automatically without showing the confirmation dialogue?
For chrome everything works correctly. Thanks!

Vue JS setting image through file uploader on v-model applies empty object

I’m using Vue JS 2 to create an image uploader. My input has a change function which runs a function and sets my file on v-model property.

When I console.log my data, all what’s set is an empty object rather than the image, this is also causing my Vee Validate rule to fail as it thinks it’s empty.

What am I missing?

My HTML for uploading a logo

<div>
  <validation-provider
    name="base64_logo"
    rules="mimes:image/jpeg,image/png"
    v-slot="{ errors, classes, validate }"
  >
    <label for="base64_logo" class="block text-sm font-medium text-gray-500 mb-2">
      Brand logo <em>(PNG or JPG)</em>
    </label>
    <div class="mt-1 relative rounded-md shadow-sm">
      <input @change="selectFilesToUpload('base64_logo', $event.target.files[0]); validate()" type="file" name="base64_logo" id="base64_logo" :class="classes" class="focus:ring-green-500 focus:border-green-500 block w-full py-3 px-4 sm:text-sm border border-gray-300 rounded-md" accept="image/png, image/jpeg">
    </div>
    <span class="text-xs text-red-500">{{ errors[0] }}</span>
  </validation-provider>
</div>

The following function runs:

/*
** Select files to upload (file uploader)
*/
selectFilesToUpload (model, file) {
  try {
    this.form[model] = file
  } catch (err) { }
},

Which form should now contain everything associated with my image, but when adding an image, it shows as an empty object (see attached)

enter image description here

I’ve also tried a JSON.stringify before setting my model, no luck here either.

How to use wildcard characters in ts typeorm?

I’m coding a query in my NestTs project, so I would like to retrieve information matched with LIKE clause values. the problem with my query is the table has three types of records ‘_INFORMED’, ‘_UNINFORMED’ and ‘WITHOUT’. If I use the sentence .where(“user.firstName like :name”, { name:%_INFORMED% }) It matches with _INFORMED and _UNINFORMED records, then I tried to use the wildcard character as to standard SQL ‘%_INFORMED%’ but it looks wrong. Do you have any idea? Thanks!