Setter in JavaScript class that can return

So I have a class XYZ in JavaScript, it has few functions:

class XYZ{
    constructor(){
        this.text=null;
    }
    f1(){
      // Do Something
      return this;
    }

    f2(){
      // Do Something
      return this;
    }

    f3(txt=null){
      if(txt){
          this.text=txt;
          this.show();
      }
      // Do Something
      return this;
    }

    show(){
      console.log(this.text)
    }
}

const obj = new XYZ();
obj.f1().f2().f3("Hello").f1();
obj.f1().f2().f3().f2();

What I want to achieve is that if there is no text to pass to f3, I want to skip the brackets and use it like a getter:

const obj = new XYZ();
obj.f1().f2().f3("Hello").f1();
obj.f1().f2().f3.f2();

I can achieve something similar like this using getter and setter, but I don’t want to break the chain calling. Is there a way where we can skip braces if not passing a value, or using the same name getter and method together?
Thanks

Cant do Put requests on API hosted on my laptop and executed on another laptop

i just couldnt find the answer to my problem online and i hope someone can help me.
I made an API with nodejs and express (with some help from youtube and google).
I was able to do some get and put requests on localhost.
I also was able to do a GET request on a different laptop.
But as soon as i tried the PUT request on a different laptop it doesnt even reach the server and it gives me a rejected promise.

  • I tried to turn of my firewall just to be sure.
  • I also tried postman, and postman was able to reach the api and do the PUT request.

Here is some code that might give some more context:
API (with an empty string sended it should give back a 418 code):

const { getAllSoftware, updateMachines } = require('./services/db');
const express = require('express');
const cors = require('cors'); // Import CORS middleware
const app = express();
const PORT = 98;

// CORS configuration
const corsOptions = {
    origin: ['http://192.168.1.99:94', 'http://localhost:94'], // Update with your client's domains
};

app.use(cors(corsOptions)); // Use CORS middleware

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

app.use(express.json());

app.put('/machines', async (req, res) => {
    console.log(req.body);
    if (req.body = {} || !req.body) {
        res.status(418).send({message:'We need a json'})
        return
    }

    res.status(200).send({
        machine: `dit is je machine met je json ${req}`
    })

});

API CALL from different laptop(localStorageData is an empty json string {})

    fetch('http://localhost:98/machines', {
        method: 'PUT',
        headers: {
            'Content-Type': 'application/json',
            'Accept': '*/*'
        },
        body: JSON.stringify(localStorageData)
        })
        .then(response => {
        // Handle the response here
        console.log(response);
        })
        .catch(error => {
        // Handle errors here
        console.error('Error:', error);
        });
}

If there is more information needed, please let me know 🙂
Api’s are a bit of new territory for me, and i am eager to learn how i can make this work correctly.

VueJS – navigating to a single item (without re-rendering all other components)

I have an ecommerce application and I am trying to re-write the frontend with vue js. I have a page that lists all the products and then a link for the users that takes them to a page where they can see details of a single product.

The users can navigate to this link via the ‘router-link’ handler.

However when this link is clicked, the users are taken to a ‘show’ template for a single product, but the rest of the products are continuing to be displayed.

Any ideas or thoughts as to what is missing from this scenario?

Thanks,

Robert

// ProductPage.vue // this shows all the products

<template>
<main>
    <div class="container">
        <div class="row">
            <div class="header col-sm-12 text-center">
                <h1>Products</h1>
            </div>
        </div>
        <div class="product-list text-center">
            <h5>Select a Product</h5>
            <table class="product-table">
                <tr class="products row">

                    <Product v-for="product in products" :product="product" :key="product.product_id" />

           
                </tr>
            </table>
        </div>
    </div>       
</main>
</template>

<script setup>
import { onMounted, ref } from "vue";
import { allProducts } from "../http/product-api";
import Product from "../components/products/Product.vue";

const products = ref([])




onMounted(async () => {
    const { data } = await allProducts()
    products.value = data.data
    console.log(products)
});





</script>

// Product.vue: this shows a single product on the products listing page

<template>



    <div class="col-sm-4 text-center">

        <h2 class="product-title"><router-link :to="'/show/' + product.product_id">{{ product.product_name }}</router-link></h2>


        <img class="single-product-image" src="/navy-dress.webp"/>

        <p class="single-product-price">{{ product.product_price }}</p>
    </div>    

</template>



<script setup>

        defineProps({
            product: Object
        })




</script>

// Show.vue // takes the user to the page where it should just render one product, but at the moment all products are being rendered

<template>
<div class="container">
    <router-link to="/index">&lt; Back</router-link>

    <h1 class="product-title">{{ product.product_name }}</h1>

    <h2>params id: {{ id }}</h2>

    <img class="single-product-image" src="/navy-dress.webp"/>

    <p class="single-product-price">{{ product.product_price }}</p>
</div>

</template>


<script setup>

import { onMounted, ref } from "vue";
import { useRouter, useRoute } from 'vue-router'
import { showProduct } from "../../http/product-api";
import Product from "../../components/products/Product.vue";
import axios from 'axios';


const product = ref([])

const route = useRoute()


onMounted(async () => {
    const uri = "http://localhost:8000/api/v1/products/" + route.params.id;
    axios.get(uri).then(response => {
        product.value = response.data;
    });
    console.log(product);
});





</script>

// router (index.js)

import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import ShowView from '../components/products/Show.vue'
import Index from '../pages/ProductsPage.vue'

const router = createRouter({


 history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue')
    },
    {
      path: '/show/:id',
      name: 'show',
      props: true,
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: ShowView
    },
    {
      path: '/index',
      name: 'index',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: Index
    }
  ]
})

I am trying to install this VAST JS Tag in Fluid Player and Node.js but I can’t

I am trying to install this VAST JS Tag in Fluid Player and Node.js but I can’t, the VAST video ads play underneath the node.js player! the format is different than the regular VAST XML url! and I can’t find any related documentation for it!

here’s the VAST JS tag:

<script async id="AV657b500ffe71a9305d04457e" type="text/javascript" src=" https://tg1.aniview.com/api/adserver/spt?AV_TAGID=657b500ffe71a9305d04457e&AV_PUBLISHERID=657b23783eea58772b01a098 "></script>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Video Player with VAST</title>
    <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
</head>
<body>
    <div id="player-container" class="video-js vjs-default-skin"></div>

    <script src="https://unpkg.com/video.js/dist/video.js"></script>
    <script async id="AV657b500ffe71a9305d04457e" type="text/javascript" src="https://tg1.aniview.com/api/adserver/spt?AV_TAGID=657b500ffe71a9305d04457e&AV_PUBLISHERID=657b23783eea58772b01a098"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var player = videojs('player-container');

            // YouTube video ID
            var youtubeVideoId = 'YOUTUBE_VIDEO_ID';

            // Construct the YouTube embed URL
            var youtubeEmbedUrl = 'https://www.youtube.com/embed/' + youtubeVideoId;

            // Set up the video source
            player.src({
                type: 'video/youtube',
                src: youtubeEmbedUrl
            });

            // Example: Listen for VAST ad loaded event
            document.getElementById("AV657b500ffe71a9305d04457e").addEventListener("onAdLoaded", function(event) {
                // Assuming videojs-contrib-ads plugin is used
                player.ads.startLinearAdMode();
            });
        });
    </script>
</body>
</html>

I tried different way in Fluid Player and Node.js

Why does the second code snippet give an error but the first one runs fine for JS?

I am learning about Lexical Environments in JavaScript and came across this error.
Code snippet with error:

let x = 1;

function func() {
  console.log(x); 
  let x = 2;
}

func();

But this code runs correctly:

let x = 1;

function func() {
  console.log(x);
}

func(); //logs out 2

I expected the first code snippet to log the value 1, and then give the error that x has already been declared but instead it gives me a reference error for the console.log(x) section.

Why can’t I pass INT ++ in a function parameter, but I can pass INT + 1 in AngularJS?

What is the reason why Index++ does not increment the value when passed to a function? I’m using AngularJS V1.6.6 and Index + 1 works, but Index++ does not.

I have a recursive function, taking an array and index as parameters. In order to increment the index on the recursive call, I was calling:

recursiveFunction(List, Index++);

No errors were thrown on the call itself, but a maximum call stack size exceeded error was thrown since the index never changed. Alternatively if I call:

recursiveFunction(List, Index + 1);

instead, the function works fine and increments the index properly. Another solution that works is:

Index++;
recursiveFunction(List, Index);

How can I implement a scroll effect like this?

Hello Stack Overflow community,

I’ve come across an interesting scroll effect on the website emanuelepapale.com and I’m wondering if anyone has a resource or knows how I can implement a similar effect on a website.

I’ve searched online and found various tutorials on scroll effects, but nothing that provides exactly the same result. If anyone has information or has worked on a similar implementation, I would greatly appreciate any help.

Additionally, if there’s a specific library or framework that would make this task easier, I would be grateful for any recommendations.

Thanks in advance for your help!

Null return when searching for id in dynamic route

To test, I’m making an array of users with id and name with a button that calls the onclick function and adds the element’s id to the page’s url, with the aim of building a dynamic route.
When getting the id data, using useSearchParams, the return is null.

My code that redirects the user

`'use client'

import { useRouter } from "next/navigation";

const Users = () => {
  const { push } = useRouter()
  const users = [
    { id: 1, name: 'User 1', age: 15},
    { id: 2, name: 'User 2', age: 24}
  ]
  const handleEditUser = (id: number) => {
    push(`/pages/users/${id}`)
  } 
  return (
    <>
    <h1>Users</h1>

    {users.map((user) => {
      return (
      <div key={user.id}  onClick={() => handleEditUser(user.id)}  className="text-gray-200">
        <p>Id: {user.id}</p>
        <p>name: {user.name}</p>
        <p>age: {user.age}</p>
        <br />
      </div>
      )
    })}
    </>
  )
}
`

The code to show the id using useSearchParams is this:

`'use client'

import { useSearchParams } from "next/navigation";

const UserDetail = () => {
  const id = useSearchParams()
  const userId = id.get('id')

  return (
    <div className="text-gray-200">
      <h1>User Details</h1>
      <p>User ID from Router: {userId}</p>
    </div>
  );
};`

export default UserDetail;
`

The page structure is as follows:
app/pages/users/[id]/page.tsx

Rotate Array of coordinates inside a Page

I have a JavaScript app that handles documents with multiple pages. This app can add some drawings onto the page, these drawings are displayed as a Canvas, but internally stored as an Array of coordinates.

I want to rotate the Page and the drawing too, which kinda works, but the rotated drawing is not in the correct location, I cannot figure out why.

For the rotation, I cannot rotate the Canvas with rotate(), I have to rotate the drawing as coordinates, and I will have to store the drawings as coordinates, not as an Image.

Before rotation:

enter image description here

After rotating 90:

enter image description here

What I have tried:
Once I rotate the page itself, I rotate the coordinates for the given page too and then redraw the drawing. Since one page can have multiple drawings, I iterate through all of them and rotate each. PageDrawPoints is an Array (Pages), where every item is an Array (Specific nth Page Drawings).

function RotateDrawing(page, angle) {
  for (var i = 0; i < PageDrawPoints[page].length; i++){
    var origin = Center();
    for(var j = 0; j < PageDrawPoints[page][i].length; j++){
        var p = PageDrawPoints[page][i][j];
        var x = (p.x - origin.x) * Math.cos(angle * Math.PI / 180) - (p.y - origin.y) * Math.sin(angle * Math.PI / 180) + origin.x;
        var y = (p.x - origin.x) * Math.sin(angle * Math.PI / 180) + (p.y - origin.y) * Math.cos(angle * Math.PI / 180) + origin.y;
        PageDrawPoints[page][i][j] = { x: x, y: y };
    };
  }
}

As an origin, I try to use the Center of the Page.

function Center() {
    let pageX = PageInformation[pageCurrent].Width;
    let pageY = PageInformation[pageCurrent].Height;
    return {
        x: (pageX) / 2,
        y: (pageY) / 2
    };
}

The transformation itself looks fine to me, I suspect there is a problem with the Origin that I am using. The question is, for these kind of rotation, shall I use the Page center where the drawing is, or something else?

How to filter in deep nested array of objects

Could you please assist me on working out how can I filter for a specific property within a deep nested array of objects?

I want to be able to search for entire array (including parent itself and children) where _speciality is ‘can fly’. As such, in the above, I should get 2 values back (fruit1, fruit3).

I have tried to usual JS operations like .filter, .map but unable to work out how this can be achieved.

Here is what my object looks like:

const foo = {
    "fruits": [
        {
              "fruit1": [{
              "categories": { "shape": "square", "size": "large"},
              "factories": [{ "city": "delhi", "location": "23 new road"}],
              "capacity": [{ "weight": "10kg", "_speciality": "can fly"}]    
              }]
        },
        {
            "fruit2": [{
              "categories": { "shape": "round", "size": "small"},
              "factories": [{ "city": "bombay", "location": "13 new road"}],
              "capacity": [{ "weight": "14kg", "_speciality": "can sing"}]      
              }]        
        },
        {
            "fruit3": [{
              "categories": { "shape": "rectangle", "size": "medium"},
              "factories": [{ "city": "bombay", "location": "13 new road"}],
              "capacity": [{ "weight": "14kg", "_speciality": "can fly"}]      
              }]        
        }        
    ]
}

Express + Sqlite3: How to have statements execute in a certain order?

I am trying to create a table with an item inserted into it upon executing the following script using the node command. However, for some reason my code is inserting the item into the table before the table is even created. I tried swapping the indexes of my statements, but they were still executed in the same order. When I open up the database with sqlite3 and manually put in the commands, everything works as expected. Is there any way to specify which statement goes first in my script?

index.js

const express = require("express");
const cors = require("cors");
const sqlite3 = require("sqlite3").verbose();
const app = express();

app.use(cors());

let db = new sqlite3.Database("./database.db", err => {
    try {
        console.log("Successful connection to the database");
    } catch {
        console.error(err.message);
    }
});

statements = ["CREATE TABLE IF NOT EXISTS Products (product TEXT, price INTEGER);", "INSERT INTO Products (product, price) VALUES ('Apple', 5.99);"]
statements.forEach(statement => db.run(statement, err => {
    try {
        console.log(statement + ": successful!");
    } catch {
        console.error(err.message);
    }
}));

app.listen(3000, () => {
    console.log("Connection: http://localhost:3000/")
})

Output:

Connection: http://localhost:3000/
Successful connection to the database
INSERT INTO Products (product, price) VALUES ('Apple', 5.99);: successful!
CREATE TABLE IF NOT EXISTS Products (product TEXT, price INTEGER);: successful!

How can I prevent the experiment from stopping when clicking outside of the field the user is supposed to click on using NeuroTask Scripting?

I have created a function that provides a memory game using NeuroTask scripting (Java Script). Unfortunately, the experiment stops when the user clicks by accident outside of the squares the user is supposed to click on. I need help with finding a solution so the experiment does not stop and preferably ‘pretends’ like nothing happened. The game only continues when one of the squares is clicked that needs to be clicked.

Does anyone know how I can solve my proplem? Is it anything that needs to be changed inside the TheGame function or outside of the function? I was trying to use asynchronous programming, but I could’t make it work.

This is what I have so far…

var coords = [[28.5,53],[39.5,53],[50.5,53],[61.5,53],
         [28.5,64],[39.5,64],[50.5,64],[61.5,64],
         [28.5,75],[39.5,75],[50.5,75],[61.5,75],
         [28.5,86],[39.5,86],[50.5,86],[61.5,86]];
var blocks = [];

//var series = shuffle(range(16)); // no underlying pattern condition:
//var series = [1,3,12,8,9,7,4,15,13,14,0,5,11,2,6,10]; // pattern
//var series = range(16);

function Controller()
{
    for (i = 0; i < coords.length; i++) // Create block layout, use `i` as id
    {
        blocks.push(main.addblock(coords[i][0],coords[i][1],10,10,"black","",i));
    }
}


function TheGame(){
    
    var series = [];
    
    if (subject_id % 2 === 0)
    {
        log(0, "Condition");
        series = shuffle(range(16));
        log(series, "Series_Condition");
        
    } else {
        
        log(1, "Condition");
        series = [1,3,12,8,9,7,4,15,13,14,0,5,11,2,6,10];
    }
    
    
    for (u = 0; u < 15; u++)
    {
        var learning = [];
        //var series = [1,3,12,8,9,7,4,15,13,14,0,5,11,2,6,10];
        
        trial_block.text("Trail: " + (u+1));
        trial_block.style("italics");
        //await(1500);
        //s_block.clear();
        
        for (i = 0; i < 16; i++) // Have subject click series
            {
                s_block.showimage(stimulus[i]);
                
                e = await("click"); // Event `e` also contains target node
                b = parseInt(e.event.target.id); // parseInt turns a string into a number
                log(b, "ID");
                blocks[b].blink("green",250); // 250 ms blink to black
    
                if (series[i] !== b) // Count errors
                {
                    blocks[b].blink("red",250);
                    learning.push(b);
                    
                } 
                
            }
        
            var win = 16 - learning.length;
            log(win, "Score");
            //s_block.text("You have " + win + " correct!");
            //await(1500);
            //s_block.clear();
    }
}

Regexp or something else for string (JS)

The problem is writing a regular expression so that you could trim everything without typing in ‘[]’, for example, the string “Some string in square brackets [a lot of words inside brackets] there are a lot of words here, but one pair of brackets” I need to get from here only “a lot of words inside brackets” is nothing more, but it may be that there are no such brackets, and in this case if I write a regular expression and pass it to replace, it will return me an empty string, I did not stop at one regular, if you have a solution, which will help me, I will be very grateful to you

P.S. I need to do this without cycles and conditions 🙂

I’ve tried a lot of regular expressions
const regex = /[([^]]*?)]|[^[]]+/g; const regex = /(?:[([^]]*?)]|[^[]]+)/g;

Can I highlight a pdf and upload it to server on html+javascript?

I want to develop the following web application.
Is it possible?

  1. When a user accesses the web page, an embedded pdf content and a “Done” button are displayed. The pdf content is downloaded from server.
  2. The user highlights some texts in the pdf content.
  3. The user clicks the “Done” button, then the text-highlighted pdf content is uploaded to server.

I know that step 1 and 2 are possible.
On the Microsoft Edge, one of <object>, <embed> or <iframe> is available to display a pdf content. And it can be highlighted using pdf viewer on Edge.
But I don’t know how to implement step 3. I don’t know how to get binary stream of the text-highlighted pdf content.

Could you let me know if you have some advises about this matter?
I don’t stick to using Edge or the above html tags. I would like to know various way of thinking.

Thanks,

I tried to get the value of data attribute of <object> tag.
I expected text-highlighted pdf binary stream, but the result is not so.