Chess Rook Javascript

I define code for bishop but problem is I can’t define code for Rook, in attach file I will give code for bishop, if anyone can fix that code and make for rook

class Rook extends Rook {
    constructor(x, y, type, color) {
        super(x, y, type, color);
    }

    move_new(new_x, new_y) {
        var movement_x = new_x - this.x;
        var movement_y = new_y - this.y;

        if (Math.abs(movement_x) == Math.abs(movement_y)) return true;

        return false;
    }

    /*
     * Route
     */
    try_movement(novo_x, novo_y) {
        var movement_x = this.x - new_x;
        var movement_y = this.y - new_y;

        var i = parseInt(this.x);
        var j = parseInt(this.y);
        var no_figure = true;

        for (; ;) {
            if (movement_x < 0) i = i + 1;
            else i = i - 1;

            if (movement_y < 0) j = j + 1;
            else j = j - 1;

            if (i == new_x) break;

            $(".place_div").each(function () {
                if ($(this).attr("position_x") == i && $(this).attr("data-position_y") == j) {
                    if ($(this).hasClass("black") || $(this).hasClass("white")) {
                        // there is a figure
                        no_figure = false;
                    }

                    return;
                }
            });

            if (!no_figure) break;
        }

        return no_figure;
    }

}

Any code fix, because I try many thing but nothing I can work good with that

How I can import all js and all css that reside in resourced folder, in my vite config without need to define them one by one?

In my laravel 10 project I load a js as:

@vite(['resources/js/myjs.js'])

And my vite.config.js contains the follwoing settings

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import inject from "@rollup/plugin-inject";

export default defineConfig({
    plugins: [
        laravel({
            input: [
                'resources/css/style.css',
                'resources/css/another-style.css',

                'resources/js/main.js',
                'resources/js/my.js',
                'resources/js/myjs.js',

                'node_modules/jquery/dist/jquery.js',
                'node_modules/bootstrap/dist/css/bootstrap.css',
                'node_modules/@fortawesome/fontawesome-free/css/all.css'
            ],
            refresh: true,
        }),
        inject({
            $: 'jquery',
            jQuery: 'jquery',
            'common_functions':'resources/js/common_functions.js',
        }),
    ],
    build: {
        rollupOptions: {
            external: [
                "js/modules/*",
            ]
        }
    }
});

But if I need another js file I should place it in vite.config.js thus makes the divelopment kinda slow because I need to place any new ccs or js into the vite.config.js that due to rush of development I may forget it.

Is there a way to conveniently for the vite to look any files defined in resources/css and resources/js folders?

Validate and resolve a URL in express.js during redirect

I have a small link shortener service, where I store the original URL inputted from the user and I give it a short id. When I was redirecting the request like res.redirect(“google.com”), I noticed that it was taking as a relative path and it was redirecting to localhost:3000/google.com. When I put the protocol such as “https”, it works.

Now is there any libraries I can use to resolve a URL such as google.com into https://wwww.google.com?
What’s the best way to handle this?

How to solve Type Error: “Failed to fetch”

I am trying to run a query on localhost and display the result on the browser, but I’m repeatedly getting stuck on “Failed to fetch” error.
I’m sharing a snippet of my code:

<!-- Query Data Form -->
  <h2>Query Data</h2>
  <form onsubmit="return queryData()">
    <label for="selectColumn">Select Column:</label>
    <select id="selectColumn" name="selectColumn">
      <!-- Add options for each column in your table -->
      <option value="MAC Address">MAC Address</option>
      <option value="Local IP">IP Address</option>
      <!-- Add more options as needed -->
    </select>
    <br>
    <label for="enterId">Enter ID:</label>
    <input type="text" id="enterId" name="enterId">
    <button type="submit">Query Data</button>
  </form>

async function queryData() {
  const selectedColumn = document.getElementById('selectColumn').value;
  const enteredId = document.getElementById('enterId').value;

  try {
    const response = await fetch(`http://localhost:3000/query?column=${selectedColumn}&id=${enteredId}`);
    
    if (response.ok) {
      const data = await response.json();

      // Display query results
      const queryResultsDiv = document.getElementById('queryResults');
      queryResultsDiv.innerHTML = ''; // Clear previous results
      data.forEach(result => {
        const resultString = JSON.stringify(result);
        const resultElement = document.createElement('div');
        resultElement.textContent = resultString;
        queryResultsDiv.appendChild(resultElement);
      });
    } else {
      const errorMessage = await response.text();
      console.error(`Server responded with status: ${response.status}, message: ${errorMessage}`);
      alert('Error during data query: ' + errorMessage);
    }
  } catch (error) {
    console.error('An error occurred during data query:', error.message);
    alert('Error during data query: ' + error.message);
  }

  return false; // Prevent form submission (which would reload the page)
}

Upon searching, I found this may be due to CORS error.
Some of the things I’ve tried I’m listing below:

app.js

const allowedOrigins = ['http://localhost:3000','http://127.0.0.1:5500'];
app.use((req, res, next) => {
  const origin = req.get('Origin');
  console.log('Request Origin:', origin);
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.header('Access-Control-Allow-Credentials', 'true');
  res.header('Access-Control-Expose-Headers', 'Content-Length');
  next();
  if (req.method === 'OPTIONS') {
    res.writeHead(200, {
        'Access-Control-Allow-Origin': 'http://localhost:3000',
        'Access-Control-Allow-Methods': 'GET, POST',
        'Access-Control-Allow-Headers': 'Content-Type, Authorization, openai-conversation-id, openai-ephemeral-user-id',
        'Access-Control-Allow-Credentials': 'false',
        'Cache-Control': 'no-store, max-age=0',
    });
    res.end();
    return;
}
})
app.use(cors({
  origin: function (origin, callback) {
    console.log('CORS Middleware Origin:', origin);
    // Check if the origin is in the allowed list or if it's undefined (e.g., for same-origin requests)
    if (!origin || allowedOrigins.includes(origin)) {
      console.log('Allowed origin:', origin);
      //callback(null, true);
    } else {
      console.log('Blocked origin:', origin);
      callback(new Error('Not allowed by CORS'));
    }
  },
  credentials: true, // Enable credentials (e.g., cookies, authorization headers)
}));

None of these have worked for me. When I’m trying to display the query results using node.js on cmd, it works, just the result data is not being fetched on the client side/browser js code.
I’m new to web dev. Any suggestion/feedback is appreciated!

Webpack Module federation configuration with different syntax for shared attribute

For a Module federation configuration, I have a syntax like below

module.exports = {
  name: "host",
  filename: "remoteEntry.js",
  shared: {
    ...dependencies,
    react: {
      singleton: true,
      requiredVersion: dependencies['react'],
    }
  }
};

I want to add the below “shared-context_shared-library” config into the above config that I have. How do I do that, since the “shared” attribute uses array syntax below V/s the object syntax that I want to have or use?

shared: [
        'react',
        'react-dom',
        {
          'shared-context_shared-library': {
            import: 'shared-context_shared-library',
            requiredVersion: require('../shared-library/package.json').version,
          },
        },
      ],

Why is the perceptron not training as expected?

I was trying to learn about neural network and I started with the perceptron.
I saw some tutorials and followed them exactly but it doesn’t work for me.

var canvas = document.querySelector('canvas')
canvas.width = innerWidth;
canvas.height = innerHeight;
var c = canvas.getContext('2d')



function sign(val) {
  if (val >= 0) {
    return 1
  } else {
    return -1
  }
}

class Perceptron {
  constructor(num) {
    this.weights = []
    this.lr = 0.1

    for (var i = 0; i < num; i++) {
      this.weights.push(Math.random() * 2 - 1)
    }
  }

  guess(inputs) {
    var sum = 0
    for (var i = 0; i < this.weights.length; i++) {
      sum += this.weights[i] * inputs[i]
    }
    var output = sign(sum)
    return output
  }

  train(inputs, target) {
    var guess = this.guess(inputs)
    var error = target - guess

    for (var i = 0; i < this.weights.length; i++) {
      this.weights[i] += error * inputs[i] * this.lr
    }
  }
}

var brain = new Perceptron(2)

var points = []


class Point {
  constructor(x, y) {
    this.x = x
    this.y = y
    this.label = 0

    c.lineWidth = 2

    if (this.y < canvas.height / 2) {
      this.label = 1
    } else if (this.y > canvas.height / 2) {
      this.label = -1
    }
  }
  draw() {
    c.beginPath()
    c.arc(this.x, this.y, 10, 0, Math.PI * 2, false)
    c.fill()
    if (this.label == 1) {
      c.stroke()
    }
  }
  update() {



    this.draw()
  }
}

for (var i = 0; i < 100; i++) {
  points.push(new Point(Math.random() * canvas.width, Math.random() * canvas.height))
}


function animate() {
  requestAnimationFrame(animate)
  c.clearRect(0, 0, canvas.width, canvas.height)
  points.forEach(point => {


    brain.train([point.x, point.y], point.label)
    var guess = brain.guess([point.x, point.y])
    if (guess == point.label) {
      c.fillStyle = "green"
    } else {
      c.fillStyle = "red"
    }
    point.update()
  })
}

animate()
* {
  margin: 0;
  padding: 0;
}

canvas {
  position: absolute;
}
<canvas></canvas>

This is my code

Can anyone tell me what is wrong with it?

I aim to make the perceptron classify the points where points above half the screen should have value of 1 while under half the screen should have value of -1

How can i click the element and get url of navigated page with puppeteer?

I’m building web scrapper for school web page.

I imported “puppeteer” to scrap client-side rendering html file.

Howerver I met some problems while developing.

My code is this:

const puppeteer = require("puppeteer");

async function scrapeData(url) {
  console.log("Target URL: ", url);

  const browser = await puppeteer.launch({ headless: "new" });

  try {
    const page = await browser.newPage();

    await page.goto(url);

    // wait for client-side loading
    await page.waitForSelector(".tit");

    // get texts from html. ignore this code.
    const titles = await page.$$eval(".tit a", (elements) => {
      return elements.map((element) => element.textContent);
    });

    console.log("before click");

    // click element which has ".tit" class.
    // that element have onclick event-listener (checked with chrome manually)
    // however, this code throws timeout exception from `page.waitForNavigation()`
    await Promise.all([page.waitForNavigation(), page.click(".tit")]);

    console.log("navigation success.");

    const newUrl = page.url();

    const result = {
      titles,
      newUrl,
    };

    return result;
  } finally {
    await browser.close();
  }
}

const targetUrl = "https://kau.ac.kr/web/pages/gc32172b.do";
scrapeData(targetUrl)
  .then((result) => {
    console.log("Scraped Titles:", result.titles);
    console.log("New URL after click:", result.newUrl);
  })
  .catch((error) => console.error("Error during scraping:", error));

Summary for my code:

  1. Puppeteer opens browser and move to “https://kau.ac.kr/web/pages/gc32172b.do”.
  2. Wait for rendering and then click the element(which has ‘.tit’ class).
  3. When client click the ‘.tit’ class element, browser navigates to new url. (There is no other option, cuz it navigates to new url dynamically)
  4. After navigation, get navigated url and return url value.

By the way, the code await Promise.all([page.waitForNavigation(), page.click(".tit")]); throws timeout exception.

===

What i tried:

  1. With chrome, i tried these codes in console.
const title = document.querySelector(".tit");
title.click();
// I checked this codes navigate browser
  1. I set timeout manually via puppeteer api instead of waitForNavigation. However, i could not get new url.

=> Does it mean page.click() occurs creation of new page and navigation to new url?

===

How to re-export a default export? [duplicate]

I have a React context hook mySharedDataContext.js as below;

export const MySharedDataContext = React.createContext();

export default ({children}) => {
    const [mysharedData, setMySharedData] = useState({});

    return (
        <MySharedDataContext.Provider value={[mysharedData, setMySharedData]}>
            {children}
        </MySharedDataContext.Provider>
    );
}

I want to have an index.js from which I want to re-export the above hook. In another module, I want to consume as below:

import MySharedDataContextProvider from 'mySharedModule/mySharedDataContext';

// ...

In the index.js of the module containing the hook, how do I write the export statements (which would export the default export)?

Javascript: Response of HTTP request – can`t get information from JSON

In my script I make an HTTP request. That works fine. I get f. e. this JSON response:

[
    {
        "body": "...",
        "status": 200,
        "headers": [
            {
                "key": "valid",
                "value": "31.12.2026"
            },
            {
                "key": "video",
                "value": "mit Handycam-Video"
            },
            {
                "key": "vouchervalue",
                "value": "274"
            }
        ]
    }
]

I can handle the status for some if clauses and alerts with

response.status

but I´m struggling to get the data in the additional headers. For example I thought, that

alert(JSON.stringify(response.headers[0].value))

should popup an alert with “31.12.2026”. But nothing appears and the console tells me, that “headers” is undefinied.

Thank you for your patience and support. Best,

getting the headers data from HTTP call JSON response to use it for alerts or to display them below some inputs as user message or information

Symfony 6.4 use encore webpack instead asset mapper

In Symfony version 6.4 for using css and javascript is deault use symfony/asset-mapper. But in my application I try use Webpack Encore instead asset-mapper but in javasctipt console i see error

Failed to load module script: Expected a JavaScript module

How I completely disable asset-mapper or completely remove and use Webpack Encore?

Loading failed for the with source “file:///js/joke.js” how to fix this error that I am getting in the console?

I am Aviral Yadav I recently made a project which displayed random jokes by fetching it from a free api. The css and js scripts are working fine with vs code’s live server extension but when I am opening the html file I am getting an error i.e.Loading failed for the with source “file:///js/joke.js”.
enter image description here

I have tried giving the path of the files by opening it in chrome but in vein…..please help me.

how to enable a button when the from hour and minutes starts and disabled when the to hour and minutes ends

how to enable a button when the Fromhour and Fromminutes starts and disabled when the tohour and tominutes ends

@if(Convert.ToDateTime(CurrentDate) == Convert.ToDateTime(DeadlineDate)) {
  if (DateTime.Now.Hour >= Model.FromTimeHour && DateTime.Now.Hour < Model.ToTimeHour) {
    if (DateTime.Now.Minute >= Model.FromTimeMinutes) { <
      input type = "button"
      id = "btn_save"
      style = "width:auto"
      name = "submit"
      value = "Submit Discount"
      class = "btn btn-info"
      onclick = "SubmitForm()" / >
        <
        input type = "submit"
      id = "btn_save1"
      name = "submit"
      value = "Submit Discount"
      style = "display:none" / >
    } else { <
      input type = "submit"
      class = "btn btn-info"
      name = "submit"
      value = "Submit Discount"
      disabled style = "width:180px;"
      onchange = "preventMultipleSave()" / >
    }
  } else if (DateTime.Now.Hour == Model.FromTimeHour && DateTime.Now.Hour == Model.ToTimeHour) {
    if (DateTime.Now.Minute >= Model.FromTimeMinutes && DateTime.Now.Minute <= Model.ToTimeMinutes) { <
      input type = "button"
      id = "btn_save"
      style = "width:auto"
      name = "submit"
      value = "Submit Discount"
      class = "btn btn-info"
      onclick = "SubmitForm()" / >
        <
        input type = "submit"
      id = "btn_save1"
      name = "submit"
      value = "Submit Discount"
      style = "display:none" / >
    } else { <
      input type = "submit"
      class = "btn btn-info"
      name = "submit"
      value = "Submit Discount"
      disabled style = "width:180px;"
      onchange = "preventMultipleSave()" / >
    }
  } else if (DateTime.Now.Hour >= Model.FromTimeHour && DateTime.Now.Hour <= Model.ToTimeHour) {
    if (DateTime.Now.Minute >= Model.FromTimeMinutes && DateTime.Now.Minute <= Model.ToTimeMinutes) { <
      input type = "button"
      id = "btn_save"
      style = "width:auto"
      name = "submit"
      value = "Submit Discount"
      class = "btn btn-info"
      onclick = "SubmitForm()" / >
        <
        input type = "submit"
      id = "btn_save1"
      name = "submit"
      value = "Submit Discount"
      style = "display:none" / >
    } else if (DateTime.Now.Hour > Model.FromTimeHour && DateTime.Now.Hour == Model.ToTimeHour) {
      if (DateTime.Now.Minute <= Model.FromTimeMinutes && DateTime.Now.Minute <= Model.ToTimeMinutes) { <
        input type = "button"
        id = "btn_save"
        style = "width:auto"
        name = "submit"
        value = "Submit Discount"
        class = "btn btn-info"
        onclick = "SubmitForm()" / >
          <
          input type = "submit"
        id = "btn_save1"
        name = "submit"
        value = "Submit Discount"
        style = "display:none" / >
      } else { <
        input type = "submit"
        class = "btn btn-info"
        name = "submit"
        value = "Submit Discount"
        disabled style = "width:180px;"
        onchange = "preventMultipleSave()" / >
      }
    } else { <
      input type = "submit"
      class = "btn btn-info"
      name = "submit"
      value = "Submit Discount"
      disabled style = "width:180px;"
      onchange = "preventMultipleSave()" / >
    }
  } else { <
    input type = "submit"
    class = "btn btn-info"
    name = "submit"
    value = "Submit Discount"
    disabled style = "width:180px;"
    onchange = "preventMultipleSave()" / >
  }

}
else { <
  input type = "submit"
  class = "btn btn-info"
  name = "submit"
  value = "Submit Discount"
  disabled style = "width:180px;"
  onchange = "preventMultipleSave()" / >
}

I tried using if condition but failed during minutes checking

Calculation for Row Product Data

I want to add a function to ‘calculaterowproductdata’. The ‘sub_total’ should be calculated by adding ‘lens’ and ‘cutting_charge’ multiplied by ‘quantity’, and then updating ‘lens’, ‘cutting_charge’ value to the field.

   function calculateRowProductData(quantity) {
       if(product_type[pos] == 'standard')
           unitConversion();
       else
           row_product_price = product_price[rowindex];

       $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.discount').text((product_discount[rowindex] * quantity).toFixed({{$general_setting->decimal}}));
       $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.discount-value').val((product_discount[rowindex] * quantity).toFixed({{$general_setting->decimal}}));
       $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.tax-rate').val(tax_rate[rowindex].toFixed({{$general_setting->decimal}}));


       if (tax_method[rowindex] == 1) {
           var net_unit_price = row_product_price - product_discount[rowindex];
           var tax = net_unit_price * quantity * (tax_rate[rowindex] / 100);
           var sub_total = (net_unit_price * quantity) + tax;

           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.net_unit_price').text(net_unit_price.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.net_unit_price').val(net_unit_price.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.tax').text(tax.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.tax-value').val(tax.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.sub-total').text(sub_total.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.subtotal-value').val(sub_total.toFixed({{$general_setting->decimal}}));
       } else {
           var sub_total_unit = row_product_price - product_discount[rowindex];
           var net_unit_price = (100 / (100 + tax_rate[rowindex])) * sub_total_unit;
           var tax = (sub_total_unit - net_unit_price) * quantity;
           var sub_total = sub_total_unit * quantity;

           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.net_unit_price').text(net_unit_price.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.net_unit_price').val(net_unit_price.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.tax').text(tax.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.tax-value').val(tax.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.sub-total').text(sub_total.toFixed({{$general_setting->decimal}}));
           $('table.order-list tbody tr:nth-child(' + (rowindex + 1) + ')').find('.subtotal-value').val(sub_total.toFixed({{$general_setting->decimal}}));
       }

       calculateTotal();
   }