How to render vue components as AgGrid icons?

I have the following AgGrid configuration in my VueJS project:

<template>
    <div>
      <AgGridVue
        class="ag-grid-theme"
        :rowData="rowData"
        :columnDefs="colDefs"
        :icons="icons"
        style="width: 100%; height: 500px"
      />
    </div>
</template>

<script setup>
  import { h } from 'vue'
  import {
    XIcon
  } from 'lucide-vue-next'
  import { AgGridVue } from 'ag-grid-vue3'
  import {
    AllCommunityModule,
    ModuleRegistry
  } from 'ag-grid-community'
  ModuleRegistry.registerModules([AllCommunityModule])

  const icons = {
    filter: () => h(XIcon)
  }

  const colDefs = [
    {
      field: 'symbol'
    },
    {
      field: 'currency'
    },
    {
      field: 'quantity'
    }
  ]

  const rowData = [
    { symbol: 'AAPL', currency: 'USD', quantity: 10 },
    { symbol: 'GOOGL', currency: 'USD', quantity: 5 },
    { symbol: 'AMZN', currency: 'USD', quantity: 2 }
  ]
</script>

I’m trying to add a custom filter icon by injecting the XIcon component as a custom icon, as shown in the icon object, but it’s not working.

How would I go about rendering a Vue component as a custom icon?

How to create a react flow where you have 2 nodes with multiple edges?

I am trying to create a react flow where you have 2 nodes with multipule edges. I have the following set up but it renders only 1 edge. How do I render all 3 edges?

enter image description here

import ReactFlow from 'reactflow';
import 'reactflow/dist/style.css';

function MyFlow() {
  const initialNodes = [
    { id: '1', position: { x: 0, y: 0 }, data: { label: 'Node 1' } },
    { id: '2', position: { x: 200, y: 100 }, data: { label: 'Node 2' } },
  ];

  const initialEdges = [
    { id: 'e1-2a', source: '1', target: '2', label: 'Edge A' },
    { id: 'e1-2b', source: '1', target: '2', label: 'Edge B' },
    { id: 'e1-2c', source: '1', target: '2', label: 'Edge C' },
  ];

  return (
    <div style={{ width: '100vw', height: '100vh' }}>
      <ReactFlow nodes={initialNodes} edges={initialEdges} fitView />
    </div>
  );
}

export default MyFlow;

Why does `Array(3).map(x => 42)` return an empty array instead of `[42, 42, 42]` in JavaScript?

I was brushing up on Array for an implementation and I stumbled on this discovery, I expected the following code to give me an array filled with the number 42:

Array(3).map(x => 42)

But instead, the result is:

[empty × 3]

console output

If I try the same with fill, which I normally use, it works as I expected:

Array(3).fill(42) // [42, 42, 42]

Or if I create the array explicitly:

[1, 2, 3].map(x => 42) // [42, 42, 42]

So clearly map works normally on an array with values as I’ve also known.

But why does Array(3).map(...) behave differently, and what does [empty × 3] actually mean in JavaScript? It’s my first time coming across this.

Struggling with QR scanner implementation [closed]

I am using React Native 0.68.5 and I implemented Qr Scanner from react-native-qr-scanner library which worked fine on my laptop where I am using complete Android no iOS but as soon as I implement it on my office project which of course on iOS Android it fails to run.

React Native permissions and qr-scanner library working fine on that but whenever I install React-native-camera my build got stuck in between and without this library the errors pops up that ‘RNCamera is not found in Ulmanager. I can’t provide the images though but I can completely explain error.

PayPal Subscription TRANSACTION_REFUSED for $199/month but works for $1/month

I’m implementing PayPal subscriptions using the JavaScript
SDK. Small subscription amounts ($1/month) work perfectly
fine, but when I try to change the subscription priceenter image description here with higher
amounts ($199/month), they immediately fail with a
TRANSACTION_REFUSED error. The strange part is that
one-time payments of $1000+ work without any issues on the
same PayPal business account. Users see a generic “Things
don’t appear to be working at the moment” error from
PayPal, and the console logs show TRANSACTION_REFUSED when
attempting to create the subscription.

When users attempt to subscribe, they immediately see
PayPal’s error page stating “Things don’t appear to be
working at the moment.” The network tab shows a redirect to
PayPal’s genericError endpoint with the parameter
code=TRANSACTION_REFUSED. The browser console shows the
subscription.create() promise is rejected before any
payment modal appears. Interestingly, the error URL also
contains flow:”one-time-checkout” in the event state, even
though I’m using intent:”subscription” in my SDK
configuration. No additional error details are provided by
the PayPal SDK beyond the generic failure.

enter image description here

How to come up with a unique AI plus web/mobile or real world problem solving project idea for final year? [closed]

I’m a 3rd-year software engineering student starting my final-year project, and I still have no idea. And I would like to do something unique, also solve a problem, and wanna give an impactful thing to the world. It should:

Use AI in a supporting role
Solve a real-world problem
Be doable in about 7 months

Question: What’s the best way to refine broad themes into a clear, practical, and unique project idea?

any ideas or suggestions

DataTables interprets numeric id as timestamp and throws “Invalid time value” error

I’m working with jQuery DataTables to dynamically display rows from a back-end API. The data includes a field called id with values like "288640". When I place this id field as the first column in the table, I get this error:

RangeError: Invalid time value
    at Date.toISOString (<anonymous>)

However, if I move the id column to a different position (e.g., second or third), the error goes away.

.then((json) => {
    const rows =
      (Array.isArray(json) && json) ||
      json.data ||
      json.rows ||
      (json.data && Array.isArray(json.data.data) && json.data.data) ||
      [];

    const thead = document.querySelector("#positionsTable thead tr");
    if ($.fn.DataTable && $.fn.DataTable.isDataTable("#positionsTable")) {
      $("#positionsTable").DataTable().clear().destroy();
    }

    if (thead) thead.innerHTML = "";

    if (!rows.length) {
      if (thead) thead.innerHTML = "<th>No positions</th>";
      return;
    }

    const columns = Object.keys(rows[0]);

    console.log("columns:", columns);

    columns.forEach((col) => {
      if (col === "id") return;
      const th = document.createElement("th");
      th.textContent = col;
      thead.appendChild(th);
    });

    if ($.fn.dataTable) $.fn.dataTable.ext.errMode = "throw";

    console.log("Sample row:", rows[0]);

    $("#positionsTable").DataTable({
      destroy: true,
      processing: true,
      data: rows,
      columns: columns,
    });
  })

Why does DataTables treat my numeric id (e.g., 288640) as a timestamp and crash when it’s the first column?

I’m looking for

  • A better understanding of why this happens
  • Best practices to prevent numeric fields from being interpreted as dates/timestamps

I tried converting the id field to a string, however I still had the same results.

Autocomplete for nested vars imported from a library

I’m building a Google Apps Script library and I’d like to expose some constants as a nested object.

var CONFIG = {
  LEVEL0: {
    LEVEL1_A: 'A',
    LEVEL1_B: 'B'
  }
};

When I use this library in another project, autocomplete detects CONFIG and CONFIG.LEVEL0, but not CONFIG.LEVEL0.LEVEL1_A and CONFIG.LEVEL0.LEVEL1_B.

Is there a way to make the Apps Script editor at script.google.com provide autocomplete for deeply nested constants in a library? Or is this simply a limitation of the Apps Script autocomplete engine?

Is it possible to create/simulate a custom pagination element to jump to a specific page?

I am using python and selenium to look through a table with a lot of pages. I was wondering if it is possible to jump to a specific page of that table to continue searching through it where i left off previously. My problem is that i have no knowledge about JavaScript or jQuery. The pagination looks like this:

<nav id="stat_pagination_nav">
    <ul id="stat_pagination" class="pagination pagination-sm noselect">
        <li class="first disabled"><a href="#">&lt;&lt;</a></li>
        <li class="prev disabled"><a href="#">&lt;</a></li>
        <li class="page active"><a href="#">1</a></li>
        <li class="page"><a href="#">2</a></li>
        <li class="page"><a href="#">3</a></li>
        <li class="page"><a href="#">4</a></li>
        <li class="page"><a href="#">5</a></li>
        <li class="page"><a href="#">6</a></li>
        <li class="page"><a href="#">7</a></li>
        <li class="next"><a href="#">&gt;</a></li>
    </ul>
</nav>

Inspecting these elements in the browser shows an event on click that looks like this:

function(x) {
  !g.options.href && x.preventDefault(), g.show(parseInt(m.data("page")))
}

Using the debugger also in the browser it seems its a part of this:

          setupEvents: function () {
            var g = this;
            this.$listContainer.find('li').each(
              function () {
                var m = c(this);
                if (
                  m.off(),
                  m.hasClass(g.options.disabledClass) ||
                  m.hasClass(g.options.activeClass)
                ) {
                  m.on('click', !1);
                  return
                }
                m.click(
                  function (x) {
                    !g.options.href &&
                    x.preventDefault(),
                    g.show(parseInt(m.data('page')))
                  }
                )
              }
            )
          },

which is a part of a massive .js file.

It looks to me like this: g.show(parseInt(m.data("page"))) is the interesting part, where we jump to the page. But i find it really hard to understand this code using only single letters for names so i am probably missing something. However this led to my attempt:

myPage = 42
js = "arguments[0].g.show(" + str(myPage) + ");"
selector = "#stat_pagination > li:nth-child(7)"
element = WebDriverWait(driver, 3).until(EC.element_to_be_clickable((By.CSS_SELECTOR, selector)))
driver.execute_script(js, element)

i tried this using different selectors, thinking i might be in the wrong scope where g does not exist but everything yielded the same error.
JavascriptException: TypeError: can't access property "show", arguments[0].g is undefined

After some google research i also tried using js = "var keys = Object.keys(arguments[0]); return keys;" to understand the problem better and it returned a list containing a single string: "jQuery111306146748258537055"
Im obviously missing something essential here but i dont know what it is. This is my first question here, please let me know if i need to include more information.

Switch Statement Misbehaving with React.js

I’m trying to build a modal in React that has different buttons depending on the type of modal. (Alerts should just display an “OK” button, while Confirms should display “OK” and “Cancel.”) I’m trying to use a switch statement to render different button components depending on the type of prompt. However, on re-render, the alert buttons are rendered even if the popup.type property is updated to PopupType.CONFIRM instead of PopupType.ALERT.

At first, I suspected that the parent component wasn’t actually re-rendering. But I found that I can change the value of popup.text and it will be correctly updated on re-render. I was also originally passing popup.type as a prop to PopupButtons, but switching to useContext() did not solve the issue (despite probably being better practice regardless).

What’s more, when I added console.log() statements, the component will acknowledge that popup.type is equal to PopupType.CONFIRM, but then STILL render the AlertButtons component instead of the ConfirmButtons component.

Initial Render Console Output:

Rendering popup box with 1
Context updated, popup.type = 1
Alert buttons
1 is allegedly equal to 1

Next Render Console Output:

Rendering popup box with 2
Context updated, popup.type = 2
Alert buttons
2 is allegedly equal to 1

What is going on, why is it going on, and what is the best way to go about this? Below is all of the code that I understand to be relevant to this bug.

/* ********* *
 * CONSTANTS *
 *************/

const PopupType = Object.freeze({
    ALERT:   1,
    CONFIRM: 2
});

/* *************** *
 * CONTEXT BUILDER *
 *******************/
function usePopups() {
    const popupContext = useContext(PopupContext); // PopupContext is an object, { type: (int), text: (str) }.
    if(!popupContext) throw new Error(ERROR_CONTEXT);
    return popupContext;
}

export { PopupContext };

/* *************** *
 * REACT COMPONENT *
 *******************/
function AlertButtons() {
    return <div className="options">
        <Button>OK</Button>
    </div>
}

function ConfirmButtons({ onConfirm }) {
    return <div className="options">
        <Button onClick={onConfirm}>OK</Button>
        <Button buttonType={ButtonType.DANGEROUS}>Cancel</Button>
    </div>
}

function PopupButtons() {
    const { popup } = usePopups();

    console.log(`Context updated, popup.type = ${popup.type}`);
    switch(popup) {
        case PopupType.CONFIRM:
            console.log("Confirm buttons");
            return <ConfirmButtons onConfirm={popup.onConfirm} />;
        case PopupType.ALERT:
        default:
            console.log("Alert buttons");
            console.log(`${popup.type} is allegedly equal to ${PopupType.ALERT}`);
            return <AlertButtons />;
    }
}

function PopupBox() {
    const { popup } = usePopups();
    console.log(`Rendering popup box with ${popup.type}`);

    return <Modal className="popupModal">
        <form className="popupBox" method="dialog">
            {popup.text}
            <div className="options">
                <PopupButtons />
            </div>
        </form>
    </Modal>
}

export default PopupBox;

Why does the raw file fetched from GitHub through GET Request renders blank file when converted to Blob?

The Issue ?

I’m getting a blank file when opening the URL created from a Blob of the raw file content fetched from GitHub using the GitHub REST API.
Screenshot what exactly the issue looks like

What I am Trying To Do ?

I’m trying to access a raw file content (fetched from the GitHub) via a URL after converting the raw response into a Blob. Here’s the code for it.

async function getFile() {
  const response = await octokit.request("GET /repos/{owner}/{repo}/contents/{path}", {
    owner: "my-username",
    repo: "my-repo",
    path: "path/to/myfile.ext",
    headers: {
      accept: "application/vnd.github.raw+json",
      'X-GitHub-Api-Version': '2022-11-28'
    }
  });

  console.log(response.data); // shows raw-looking data that starts with

  const blob = new Blob([response.data]);
  const url = URL.createObjectURL(blob);
  window.open(url); // <- this opens a blank page
}

Screen Shot of response.data

response.data

In a chrome extension, I can’t create a connection betweeb background and content script files

I am new to developing chrome extensions and I can’t create a connection between background and content script files, I have tried so many solutions but nothing worked. I am trapped inside this trycatch block, I can’t get any resonse.

Background.js

chrome.tabs.onUpdated.addListener(async (tabId, tab) => {
  if (
    tab.url &&
    tab.url.includes(
      'schools.madrasati.sa/SchoolManagmentReports/StudentInfo/ClassStudentInfo'
    )
  ) {
    // const queryParameter = tab.url.split('/')[6];
    try {
      const response = await chrome.runtime.sendMessage(tabId);
      console.log(response);
    } catch (err) {
      console.log('An Error occurred');
      console.log(err);
    }
  }
});

contentScript.js

(() => {

  chrome.runtime.onMessage.addListener((obj, sender, response) => {
    console.log(obj);
    console.log(sender);
    console.log(response);
  });
})();

manifest.json

{
  "name": "Get Grades",
  "version": "0.1.0",
  "description": "Get students grades in seconds",
  "permissions": [
    "storage",
    "declarativeContent",
    "activeTab",
    "scripting",
    "tabs"
  ],

  "host_permissions": ["https://*.schools.madrasati.sa/*"],
  "background": {
    "service_worker": "background.js"
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["contentScript.js"]
    }
  ],
  "web_accessible_resources": [
    {
      "resources": ["assets/bookmark.png"],
      "matches": ["https://*.schools.madrasati.sa/*"]
    }
  ],
  "action": {
    "default_icon": {
      "16": "assets/ext-icon.png",
      "24": "assets/ext-icon.png",
      "32": "assets/ext-icon.png"
    },
    "default_title": "Get Grades",
    "default_popup": "popup.html"
  },
  "manifest_version": 3
}

I keep getting this error no matter what I do

Error: Could not establish connection. Receiving end does not exist.

Performance enhancements to connect 4 engine in JavaScript

I am creating a connect 4 negamax ai/engine in JavaScript and want to make it as fast as possible, that is search highest depth in shortest amount of time. Here is the current approach and implemented strategies:

  • Using 2 32-bit bitboards for each player since JS don’t have 64 bit version and BigInt is slower: this.bitboards = { 1: [0, 0], 2: [0, 0] }; // Bottom 32 bits, top 10 bits.
  • Negamax engine to recursively go through moves.
  • Alpha/beta pruning.
  • Ordered moves according to immediate wins first and then as close as center as second sorting.
  • Transposition table with Zobrist Hash to not search already searched positions.
  • Evaluation is just checking for wins, all other scores are 0

I let it run over night and it solved the game (depth 42) in around 8 hours. Benchmarking is done according to Pascal Pons blog using “Test_L2_R1” and result is like this at my current state:

Total cases: 1 000
Total nodes evaluated: 76 571 560
Average nodes per case: 76 572
Total time: 00:00:40.299
Average time per case: 00:00:00.040
Nodes per second: 1 900 086

Nodes per second is somewhere between 2 and 4 million depending on my computers current state. I think this is decent for JS but my main concern is that I get around 10-100 times more nodes searched than the blog with the same strategies implemented.

What I tried to make it faster or search deeper

  • Implement killer moves or history moves for better move ordering but it gives more explored nodes which tells me it is not a good strategy for connect 4.
  • Better evaluation with e.g. 3 in a row but this is too slow and doesn’t seem to improve pruning that much either.
  • Using BigInt for board representation but that slowed the nodes/second down.

Question

How can I make a JS connect 4 engine reach high depths in a shorter amount of time? What strategies could work other than what I tried?

Reference

Here is my ai code for reference:

import { COLS, ROWS } from '../utils/constants.js';

let tt;
const boardSize = COLS * ROWS;
const CENTER_ORDER = [3, 2, 4, 1, 5, 0, 6];

// TT flags semantics
const FLAG_EXACT = 1;
const FLAG_LOWER = 2; // lower bound: true score >= stored score
const FLAG_UPPER = 3; // upper bound: true score <= stored score

class TranspositionTable {
    constructor(size = 1 << 24) {
        this.size = size;
        this.keys = new Uint32Array(size);
        this.scores = new Int16Array(size);
        this.depths = new Int8Array(size);
        this.flags = new Uint8Array(size); // FLAG_EXACT, FLAG_LOWER, FLAG_UPPER
    }

    put(hash, score, depth, flag) {
        const index = hash & (this.size - 1);
        this.keys[index] = hash;
        this.scores[index] = score;
        this.depths[index] = depth;
        this.flags[index] = flag;
    }

    get(hash, depth, alpha, beta) {
        const index = hash & (this.size - 1);
        if (this.keys[index] === hash && this.depths[index] >= depth) {
            const score = this.scores[index];
            const flag = this.flags[index];
            if (flag === FLAG_EXACT) return { score, flag };
            if (flag === FLAG_LOWER && score >= beta) return { score, flag };
            if (flag === FLAG_UPPER && score <= alpha) return { score, flag };
        }
        return null;
    }
}

// Move ordering
function getOrderedMoves(board) {
    const moves = [];
    const heights = board.colHeights;

    // 2. Center-priority moves
    for (const col of CENTER_ORDER) {
        if (heights[col] >= ROWS) continue;

        board.makeMove(col);
        if (board.checkWin()) {
            board.unmakeMove();
            return [col]; // Immediate win
        }
        board.unmakeMove();

        moves.push(col);
    }

    return moves;
}

// Negamax
export function negamax(board, depth, alpha, beta) {
    let nodes = 1;
    const originalAlpha = alpha;

    const cached = tt.get(board.zobristHash, depth, alpha, beta);
    if (cached) {
        return { score: cached.score, nodes: 1, move: null };
    }

    // Terminal checks
    if (board.checkWin()) {
        return { score: Math.ceil(board.moveCount / 2) - 22, nodes, move: null };
    } else if (board.moveCount >= boardSize || depth === 0) {
        return { score: 0, nodes, move: null };
    }

    let bestScore = -100;
    let bestMove = null;
    let flag = FLAG_UPPER;

    for (const col of getOrderedMoves(board)) {
        board.makeMove(col);
        const child = negamax(board, depth - 1, -beta, -alpha);
        board.unmakeMove();

        nodes += child.nodes;
        const score = -child.score;

        if (score >= beta) {
            bestScore = score;
            bestMove = col;
            flag = FLAG_LOWER;
            break;
        }
        if (score > bestScore) {
            bestScore = score;
            bestMove = col;
        }
        if (score > alpha) alpha = score;
    }

    if (bestScore <= originalAlpha) flag = FLAG_UPPER;
    else if (bestScore >= beta) flag = FLAG_LOWER;
    else flag = FLAG_EXACT;

    tt.put(board.zobristHash, bestScore, depth, flag);
    return { score: bestScore, nodes, move: bestMove };
}

// Entry point
export function findBestMove(board, depth) {
    tt = new TranspositionTable();
    const result = negamax(board, depth, -100, 100);
    return { move: result.move, score: result.score, nodes: result.nodes };
}

Why should I choose DSSD for a digital marketing course in Rohini?

DSSD course in Rohini is a reputed institute offering:

100% practical training

Industry-recognized certifications

Experienced trainers

Live projects

Placement assistance
These features make it ideal for students, working professionals, and entrepreneurs.

I researched various institutes both online and offline. I tried free YouTube tutorials and attended demo classes at multiple centers. I was expecting an institute that offers practical learning, real-time project work, and placement support. DSSD met those expectations with its detailed course structure and hands-on teaching approach.

How to apply theme toggle?

I’m working on a ticketing system and want to add theme toggle to my react app but I can’t seem to do it. I’m using tailwind CSS so theme switching based on the system is easy, I can’t seem to make the manual toggle work

I’ve tried doing the following:

const {darkMode,SetDarkmode} = useState(false)

const ToggleDarkMode = ()=>{
   SetDarkmode(!darkMode)
}