Javascript API Fetch make a filter PokeApi

I´m studying Javascript. And for that I am making a Pokémon Game based on the PokéAPI

To make it simple, I want to retrieve – filter – Pokémons with types Fire, Water & Grass.

enter image description here

I understand I should go to data > types > (look in the slots 1 & 2) > search for grass, fire & water.

So this is my code, so far, and I was thinking if I could do it BEFORE retrieving the data to the API. Otherwise I´ll have to retrieve EVERY Pokémon and then filter them.

const baseUrl = 'https://pokeapi.co/api/v2/pokemon/?limit=150'
try {
    fetch(baseUrl)
        .then(response => {
            const responseJson = response.json()
            return responseJson
        })

    .then(async data => {
        const pokemons = data.results


        for (const pokemon of pokemons) {
            pokemon.data = await fetch(pokemon.url).then(res => res.json())
        }



        console.log(pokemons)
    })

    .catch(error => {
        console.error(error)
    })
} catch (error) {
    console.error(error)
}

Hugo: baseURL is applied to src in HTML files, but not in JS

In my Hugo website, baseUrl is set to “website.com/variable”.

If an image element is in an .html file (< img src=”/images/image.png” >), the baseUrl is applied and the final url is correct: website.com/variable/images/image.png/

If an image element is in a .js file (img.src = “/images/image.png”), the baseUrl is not applied correctly and the final url is this: website.com/images/image.png/

Is Hugo supposed to apply the baseUrl to .js files or only .html and .css? Is there a way to get baseUrl in .js files?

How to segment model from controller in a node api?

I’m trying to keep my node/express api clean, but am unable to keep code effectively separate.

Most tutorials cram the data operation + response into index.js like so:

app.post('/user', (req res) => {
   db.query("SELECT UserID, UserName FROM User", function (err, result, fields) {
      if (err) throw err;
      res.json(response);
   });
});

This is fine for simple tutorials, but once things get complex, I get a huge index.js file.

I’d prefer to separate User into its own class and call on it to perform data operations. However querying the database requires a promise – and I don’t know how to get the data back out to the original calling function. This leaves me passing the response function in, forcing the User class to behave as both model and a little controller in MVC.

app.post('/user', (req res) => {
   var user = new User(db);
   user.getUserList(res);
   // I wish I could get the userlist back and respond here...
   });
});

(User.js)

getUserList(res) {
   db.query("SELECT UserID, UserName FROM User", function (err, result, fields) {
      if (err) throw err;
      //...but since I don't know how to get data back out of this method, I'll respond here.
      res.json(response);
   });
}

Is this just how it is in node.js? Is there a design pattern to keep these separate in node?

Eslint with airbnb does not load when using .eslint.json

I’m trying to setup linting for a node project. I wish to use the airbnb style guide.

These are my dev dependencies in package.json:

  "devDependencies": {
    "eslint": "^8.2.0",
    "eslint-config-airbnb-base": "^15.0.0",
    "eslint-plugin-import": "^2.25.2"
  }

This is my .eslintrc.json file:
  {
    "env": {
      "es2021": true,
      "node": true
    },    
    "parserOptions": {
      "ecmaVersion": "latest",
      "sourceType": "module"
    },
    "extends": "airbnb",
    "rules": { /* ... */ }
  }

I keep getting this error (in the VSCode Output terminal):

[Info  - 9:24:00] Failed to load config "airbnb" to extend from. Referenced from: C:GitWorkspacelorand.eubackend.eslintrc.json

Note that eslint works just fine whenever using .yml or .js files as configuration.

How could I solve this error in the json config file?

P.S While this is a minimal reproducible error, the setup process that yielded the error came by following the instructions in this video:
https://www.youtube.com/watch?v=SydnKbGc7W8&t=1111s

Calculator Operations

Im making a calculator on JavaScript… but Im not able to think of any way to get a number, store it then after the operator is pressed get another number store it ….for n number of times

and then do the operation..

I have written some code, it just takes the first number and stores it .. please give me some idea to do operations here.

HTML

 <div class="btns">
        <button class="viewBox">here</button>
     <button class="AC num">AC</button>
     <button class="Ce num">CE</button>
     <button class=" num blankBox"></button>
     <button class="buttonide num">÷</button>
     <button class="num7 num">7</button>
     <button class="num8 num">8</button>
     <button class="num9 num">9</button>
     <button class="Multiply num">×</button>
     <button class="num4 num">4</button>
     <button class="num5 num">5</button>
     <button class="num6 num">6</button>
     <button class="Minus num">−</button>
     <button class="num1 num">1</button>
     <button class="num2 num">2</button>
     <button class="num3 num">3</button>
     <button class="Plus num">+</button>
     <button class=" num blankBox"></button>
     <button class="num0 num">0</button>
     <button class=" num blankBox"> </button>
     <button class="Equal num">=</button>
    </div>

CSS

.calc{
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-auto-rows: 100px;
}
.num{
        /* -- HTML !-->
<button class="button-40" role="button">Button 40</button> */ 

  background-color: #111827;
  border: 1px solid transparent;
  border-radius: .75rem;
  box-sizing: border-box;
  color: #FFFFFF;
  cursor: pointer;
  flex: 0 0 auto;
  font-family: "Inter var",ui-sans-serif,system-ui,-apple-system,system-ui,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
  font-size: 1.125rem;
  font-weight: 600;
  line-height: 1.5rem;
  padding: .75rem 1.2rem;
  text-align: center;
  text-decoration: none #6B7280 solid;
  text-decoration-thickness: auto;
  transition-duration: .2s;
  transition-property: background-color,border-color,color,fill,stroke;
  transition-timing-function: cubic-bezier(.4, 0, 0.2, 1);
  user-select: none;
  -webkit-user-select: none;
  touch-action: manipulation;
  width: auto;
}

.num:hover {
  background-color: #374151;
}

.num:focus {
  box-shadow: none;
  outline: 2px solid transparent;
  outline-offset: 2px;
}

@media (min-width: 768px) {
  .num {
    padding: .75rem 1.5rem;
  }
}

.btns{

    font-size: 2rem;
    display:grid;
    grid-template-columns: repeat(4, 120px);
    grid-auto-rows: 120px;

}

.viewBox {
    background-color: #111827;
    border: 1px solid transparent;
    border-radius: .75rem;
    box-sizing: border-box;
    text-align: right;
    color: #FFFFFF;
    cursor: pointer;
    flex: 0 0 auto;
    font-family: "Inter var",ui-sans-serif,system-ui,-apple-system,system-ui,"Segoe UI",Roboto,"Helvetica Neue",Arial,"Noto Sans",sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";
    font-size: 2rem;
    font-weight: 600;
    line-height: 1.5rem;
    text-align: center;
    text-decoration: none #6B7280 solid;
    text-decoration-thickness: auto;
    transition-duration: .2s;
    transition-property: background-color,border-color,color,fill,stroke;
    transition-timing-function: cubic-bezier(.4, 0, 0.2, 1);
    user-select: none;
    -webkit-user-select: none;
    touch-action: manipulation;
    width: auto;
    display: flex; 
    align-items: center;
    grid-area: header;
    text-align: center;
    border: 1px solid black;
    grid-column-start: 1;
    grid-column-end: 5;
    grid-row-start: 1;
    grid-row-end: 2;
    ;
}
.num{
    display: flex;
    align-items: center;
    justify-content: center ;
    line-height: 1.6;
    font-size: 1.5rem;
    border: 1px solid black;
}

JavaScript

let runningTotal = 0;
let start = "";
const screen = document.querySelector(".viewBox");

document
.querySelector(".btns")
.addEventListener("click", function(event) {
    buttonClick(event.target.innerText) ;
});
 
function buttonClick(value) {
if (isNaN(parseInt(value))) {
    symbolhandle(value) ;

} else { 
     numberhandle(value);
     
}
}

function symbolhandle(value){
    if (value = "+") {
       runningTotal =+ screen.innerText;
        screen.innerText = null ;
        console.log(runningTotal);
    }
}

function numberhandle(value){
if (start === 0 ) {
    start = value;
} else {
  start += value ;
} rerender();
}

function rerender(value){
 screen.innerText = start;
 runningTotal = start;
}

document
.querySelector(".AC.num")
.addEventListener("click", function(value){
    start = "";
    rerender();
})

TypeError: spawn is not a function using react native running in pc [duplicate]

 **spawn('expo-cli', process.argv.slice(2), { stdio: 'inherit' })
  ^
TypeError: spawn is not a function
    at run (D:testeasyClassroom-maineasyClassroom-mainnode_modules←[4mexpo←[24mbincli.js:19:3)
    at Object.<anonymous> (D:testeasyClassroom-maineasyClassroom-mainnode_modules←[4mexpo←[24mbincli.js:6:1)
←[90m    at Module._compile (internal/modules/cjs/loader.js:959:30)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:995:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:815:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:727:14)←[39m
←[90m    at Function.Module.runMain (internal/modules/cjs/loader.js:1047:10)←[39m
←[90m    at internal/main/run_main_module.js:17:11←[39m**

cryptonator api 503 when running in react, but works fine when called from browser

I am using this api https://api.cryptonator.com/api/ticker/btc-usd

if i paste this in the browser it works fine, and gives the required json

but when i call from my react application, it throws cors error, which is bypassed by using

fetch('https://api.cryptonator.com/api/ticker/btc-usd', {
      mode: 'no-cors', // 'cors' by default
})
.then(res => res.json())
.then(res => {
  console.log(res);
})
.catch(err => {
  console.log(err)
})

but now it says 503 error.

i tried the same in postman, it didnt work at first, but when i copied the ‘User-Agent’ and ‘Cookie’ field from the browser network tab to postman it did work on postman too

i tried doing the same thing in react, it says 503.

i even coped the entire fetch request from network tab, it still shows 503

any help on this will be much appreciated

Edit:
I even tried adding proxy in package.json like
“proxy”: “https://api.cryptonator.com”,

and called the api like fetch(/api/ticker/btc-usd)

but still does noot get resolved

External links keep getting blocked by ad blocker (WordPress site, cant use plugins) [closed]

I have a client who has requested this to be fixed. He wont let us install plugins.
I began to think of a creative solution, and coded up something to store external files locally. I was trying to use ob_start() to replace the links, but they seem to be loading later, probably aJax, from plugins. I don’t know. Another issue is that some aren’t getting loaded inline. The javascript files are getting loaded somewhere else.

Does anyone have any idea how I can solve this for my client?

Display express.js res.send() without overwriting current html

I am trying to create a calculator app using express.js to get request for an html file and a post request that takes the user’s input and responds with the answer. However, I want to display my answer inside a html container without the page redirecting. Is there a way to achieve this with vanilla javascript?

index.html

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="styles.css" />
    <link rel="shortcut icon" href="#" />
    <title>Calculator</title>
  </head>
  <body>
    <h1>Calculator App</h1>
    <form action="/" method="post" class="ajax">
      <label for="userInput">Enter Equation</label>
      <input type="text" id="equation" name="equation" />
      <button type="submit" id="btn_submit">Calculate</button>
    </form>
    <div class="container"></div>
  </body>
</html>

app.js

const express = require('express'); 
const app = express();
port = 3000;

app.use(express.urlencoded({ urlencoded : false }));
app.use(express.static('public'));

app.get('/', (req, res) => {
    res.sendFile(__dirname + public);
});

app.post('/', (req, res) => {
    let equation = req.body.equation;
    console.log(equation);
    let result = eval(equation);
    res.status(200).send('Result is ' + result);
    
});

app.listen(port, ()=> {
    console.log('Hosted on port: ' + port);
});

CalculatorApp
Evaluated Expression

How to take tf.Tensor type to number type in Typescript

I’m working with Tensorflow.js in typescript and I want to get the cosine similarity of two 1D tensors, but I am having trouble with dealing with the types that tensorflow uses.
When I calculate the cosine similarity, using this function I should be getting a number but instead I get a bunch of different other types including number.

function calculateCosineSimilarity(abstractEmbedding: tf.Tensor1D | Array<number>, queryEmbedding: tf.Tensor1D | Array<number>): number{
    const dotProd: tf.Tensor = tf.dot(abstractEmbedding, queryEmbedding);
    const lenAbstractEmbedding: tf.Tensor = tf.dot(abstractEmbedding, abstractEmbedding);
    const lenQueryEmbedding: tf.Tensor = tf.dot(queryEmbedding, queryEmbedding);
    const similarityScore: tf.Tensor = tf.div(dotProd, tf.mul(lenAbstractEmbedding,lenQueryEmbedding));
    return similarityScore.arraySync(); 
}

I get this error at the return statement:

Type 'number | number[] | number[][] | number[][][] | number[][][][] | number[][][][][] | number[][][][][][]' is not assignable to type 'number'.

I know when you take dot products of multidimensional arrays the dimensions/types of the resulting array will vary but for my case I know I will be getting a single value back, so I just want to return a single number. Is there a way to resolve this issue without having to change the return type of the function?

AJAX Action is not working or a PHP Hook is not working

My code works if I remove the hooks add_action() and remove 'action': 'contact' In AJAX. In this case it returns ‘Success’.
But once I add hooks to email.php and 'action': 'contact' it stops to return me anything. Can you give me an advice how to fix it? I believe I do it exactly as in the documentation.

This is my simple code:

Email.php:

<?php

 add_action( 'wp_ajax_nopriv_contact', 'contact' );
 add_action( 'wp_ajax_contact', 'contact' );

 function contact() {
  echo 'Success';
  wp_die();
 }

 ?>

Functions.php:

function load_script()
{
  wp_enqueue_script( 'contact_form', get_template_directory_uri() . '/contact_form/contact_form.js', array('jquery') );
  wp_localize_script( 'contact_form', 'ajax_object', array('ajaxurl' => get_template_directory_uri() . '/email.php')
  );
}

add_action('wp_enqueue_scripts', 'load_script');

And contact_form.js:

(function($){
$(document).ready(function() {
    $( '.mybtn' ).click( function(e) {
        e.preventDefault();
        $.ajax({
          url: ajax_object.ajaxurl,
          type: 'POST',
          data: {
              'action': 'contact'
          },
          success: function( response ) {
              console.log('The server responded: ',response);
          },
        });
   });
});
})(jQuery);

handleUnknownRoute using a subdirectory with Scully

In my Angular project I am using the following command to build the Angular project:

ng build --base-href='/mysubfolder/'

mysubfolder is the path from where the Angular site will be served i.e https:/myotherdomain/mysubfolder

myotherdomain == some other site
mysubfolder == site where Angular project will be served and deployed

ng build –base-href=’/mysubfolder/’ command will add the /mysubfolder/ text in base href tag of every page like this:

The site is working fine so far. The problem comes when I extend this application to use https://scully.io/ to prender the Angular app. When I use the following command to prender the app:

npx scully -- 

it complains for so many weird errors related handleUnknownRoute:

⚠ handleUnknownRoute: "/mysubfolder/runtime.1e1f2c39fa49cf1c.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/polyfills.f7e3195ab4ce45af.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/main.918200bb3d790082.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/scripts.c48a99ff2e89312c.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/styles.6869685dcbc594de.css", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/runtime.1e1f2c39fa49cf1c.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/polyfills.f7e3195ab4ce45af.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/runtime.1e1f2c39fa49cf1c.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/polyfills.f7e3195ab4ce45af.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/main.918200bb3d790082.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/scripts.c48a99ff2e89312c.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/styles.6869685dcbc594de.css", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/polyfills.f7e3195ab4ce45af.js", 404:""
  ⚠ handleUnknownRoute: "/mysubfolder/main.918200bb3d790082.js", 404:""

Scully fails to prerender ther app.

Can you share how to fix the part where I can prerender the app with Suclly having at the top?

Scully has no issues when I build the angular project with ng build command i.e without any sub directory, the issue comes only when I build the Angular project with ng build –base-href=’/mysubfolder/’ command.

Can you share which setting I am missng to let Scully pre render the Angular app with subdirectory serve?

How to overcome that handleUnknownRoute error?

CSS Doesn’t apply to nested react router links

I have this problem where a nav component that is outside the Routes component but inside the Router component (“Router” and “Routes” are both imported from “react-router-dom”) and it works fine. However, I have a Route component inside the Routes component and those fail to load css whenever I navigate to their link. I set h1’s in my website to be 10vw globally in the styles.css file, but nothing changes.

App.JSX

import React from "react";
import Nav from "./Nav";
import About from "./About";
import Contact from "./Contact";
import Home from "./Home";
import Error from "./Error";
import Compose from "./Compose";
import {BrowserRouter as Router, Routes, Route, Navigate} from "react-router-dom";

function App(){
    return (
        <Router>
            <Nav/>
            <Routes>
                <Route path="/home" element={<Home/>}/>
                <Route path="/" element={<Navigate to="/home"/>}/>
                <Route path="/compose" element={<Compose/>}/>
                <Route path="/about" element={<About/>}/>
                <Route path="/contact" element={<Contact/>}/>
                <Route path="*" element={<Error/>}/>
            </Routes>
            
        </Router>
    )
};

export default App;

Home.JSX

import React from "react";

function Home(){
    return (
        <div className="home-section">
            <h1>Edge</h1>
        </div>
    )
};

export default Home;

styles.css

body{
    margin: 0;
}

.nav-bar{
    background-color: #7fa832;
}

.nav-bar a{
    font-family: "Nuosu SIL", sans-serif;
    font-size: 1.25vw;
    margin-right: 2vw;
    text-decoration: none;
    color: white;
}

.nav-bar a:first-of-type{
    margin-right: 58vw;
    font-size: 3vw;
    text-decoration: none;
    color: #1a7521;
    font-family: "Roboto", sans-serif;
};

h1{ /*NOTICE THIS, THE H1 SHOULD BE HUGE*/
    font-size: 10vw;
}

index.html

<!DOCTYPE html>
<html>
    <head>
        <link rel="stylesheet" href="/styles.css"/>
        <link rel="preconnect" href="https://fonts.googleapis.com">
        <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
        <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&family=Nuosu+SIL&family=Roboto+Mono:wght@500&family=Roboto:wght@100;500&display=swap" rel="stylesheet">
        <title>Innovative Hub</title>
    </head>
    <body>
        <div id="root"></div>
    </body>
</html>

showing h1 doesn't change while nav-bar is styled

How send a telegram voice message to the discord chat?

I have two bots (discord, telegram). I want to send a telegram voice message to the discord chat. But due to the fact that the .oga format is there, I can’t do it properly. I know that oga ~= ogg and that discord supports ogg. But I am not downloading the file to change the resolution. When I add a file to a discord message via the link https://api.telegram.org/file/<bot_token>/voice/file_53.oga it automatically uploads it to my server and I don’t show the token, but I don’t know how change file extension. What options are there besides the most obvious – download the file, change the name and upload to discord? Is it possible to do this, for example, through streams, without creating a file in the directory?