Why has my array element been changed by this declaration?

Javascript code:

const bigArray2 = [
    [1, 2, 3],
    [2, 4, 6],
    [3, 6, 9],
  ];
  
  //creates single-layer array containing all elements of every array within bigArray2
  const combinedArray = bigArray2.reduce((accumulated, current) => {
    for (element of current) {
      accumulated.push(element);
    }
    return accumulated;
  });
  

  console.log(combinedArray);
  // outputs [ 1, 2, 3, 2, 4, 6, 3, 6, 9 ] as intended
  

  console.log(bigArray2); 
  // outputs [ [ 1, 2, 3, 2, 4, 6, 3, 6, 9 ], [ 2, 4, 6 ], [ 3, 6, 9 ] ]

Somehow bigArray2[0] is assigned a value of combinedArray. How and why? .reduce() is not supposed to change the original array

Asking for help please [closed]

Looking for information about black magic or some form of magic/witchcraft that does the following, even if only one or some:

  • See through the victim’s memories
  • Access the victim’s brain entirely, even in terms of knowledge (ie. being able to instantly speak the languages that the victim can speak)
  • Input and manipulate thoughts and dreams into the victim’s brain (prevents the victim from thinking properly as himself/herself/themselves)
  • Block the victim from accessing the full capacity of the victim’s own brain
  • See everything the victim sees (either through the victim’s eyes or what registers in the victim’s brain)
  • Control and manipulate the victim’s feelings/emotions (could be through the victim’s heart or brain)
  • Control the victim’s tear ducts (block them so no tears are able to flow, or force out the tears excessively)
  • Control the victim’s sweat glands
  • Talk/communicate with the victim by inputing voices into the victim’s brain (could feel like it’s in the victim’s brain or even in the surroundings)
  • Vibrations/energies
  • Making the victim smell specific smells
  • Induce pain in the victim (could feel it anywhere on the body)
  • Control the victim’s bodily movements (but for this, the victim has stronger control over his/her/their own body still)
  • ETC

I know it might be hard to believe but it’s real (countries like Indonesia have attempted to ban black magic/witchcraft so this is proof that such magic exists). Please, I’m begging for help! If you or anyone around you has any knowledge of the above magic, please reply.

Also, if it’s possible, could you please spread this to the people you know so there will be a higher chance for me to be helped. And if you happen to chance upon it any time down the line, please remember this message. If you hear of anyone who might know about it as well, I would greatly appreciate if you could connect me with that person. Please!

P.S. If you have been spreading this magic/witchcraft in any way, please note that you can still help me. Even if you are the one who spread this magic/witchcraft to the culprits, you will never be liable for their crime. Please help.

What obfuscation techniques are used in this JavaScript code snippet?

So I am working on a CTF titled “Javascript – Native code” on root-me.org, I couldn’t find much explanation on what kind of encryption this is anywhere. I am NOT looking for a solution on how to solve the challenge as I have already solved it, I am just curious as to what encryption/obfuscation method was used for this code snippet. Any help/guidance is greatly appreciated!

The Code Snippet

<script>
É=-~-~[],ó=-~É,Ë=É<<É,þ=Ë+~[];Ì=(ó-ó)[Û=(''+{})[É+ó]+(''+{})[ó-É]+([].ó+'')[ó-É]+(!!''+'')[ó]+({}+'')[ó+ó]+(!''+'')[ó-É]+(!''+'')[É]+(''+{})[É+ó]+({}+'')[ó+ó]+(''+{})[ó-É]+(!''+'')[ó-É]][Û];Ì(Ì((!''+'')[ó-É]+(!''+'')[ó]+(!''+'')[ó-ó]+(!''+'')[É]+((!''+''))[ó-É]+([].$+'')[ó-É]+'''+''+'\'+(ó-É)+(É+É)+(ó-É)+'\'+(þ)+(É+ó)+'\'+(ó-É)+(ó+ó)+(ó-ó)+'\'+(ó-É)+(ó+ó)+(É)+'\'+(ó-É)+(É+ó)+(þ)+'\'+(ó-É)+(É+ó)+(É+ó)+'\'+(ó-É)+(ó+ó)+(ó-ó)+'\'+(ó-É)+(ó+ó)+(É+É)+'\'+(É+ó)+(ó-ó)+'\'+(É+É)+(þ)+'\'+(ó-É)+(ó-ó)+(É+ó)+'\'+(ó-É)+(É+ó)+(ó+ó)+'\'+(ó-É)+(ó+ó)+(É+É)+'\'+(ó-É)+(ó+ó)+(É)+'\'+(ó-É)+(É+É)+(É+ó)+'\'+(ó-É)+(þ)+(É)+'\'+(É+É)+(ó-ó)+'\'+(ó-É)+(É+ó)+(É+É)+'\'+(ó-É)+(É+É)+(É+ó)+'\'+(É+É)+(ó-ó)+'\'+(ó-É)+(É+ó)+(É+ó)+'\'+(ó-É)+(É+ó)+(þ)+'\'+(ó-É)+(ó+ó)+(É+É)+'\'+(É+É)+(ó-ó)+'\'+(ó-É)+(É+É)+(É+É)+'\'+(ó-É)+(É+É)+(É+ó)+'\'+(É+É)+(ó-ó)+'\'+(ó-É)+(ó+ó)+(ó-ó)+'\'+(ó-É)+(É+É)+(ó-É)+'\'+(ó-É)+(ó+ó)+(ó)+'\'+(ó-É)+(ó+ó)+(ó)+'\'+(ó-É)+(É+É)+(É+ó)+'\'+(É+É)+(þ)+'\'+(É+ó)+(ó-É)+'\'+(þ)+(ó)+'\'+(ó-É)+(É+ó)+(ó-É)+'\'+(ó-É)+(É+É)+(ó+ó)+'\'+(É+ó)+(ó-ó)+'\'+(ó-É)+(É+É)+(ó-É)+'\'+(þ)+(É+ó)+'\'+(þ)+(É+ó)+'\'+(É+É)+(þ)+'\'+(ó-É)+(ó+ó)+(É+É)+'\'+(ó-É)+(É+ó)+(þ)+'\'+(ó-É)+(ó+ó)+(É+É)+'\'+(ó-É)+(É+ó)+(þ)+'\'+(ó+ó)+(ó-É)+'\'+(ó+ó)+(É)+'\'+(ó+ó)+(ó)+'\'+(ó-É)+(É+ó)+(É+É)+'\'+(ó-É)+(É+ó)+(þ)+'\'+(ó-É)+(É+ó)+(É+É)+'\'+(É+É)+(þ)+'\'+(É+ó)+(ó-É)+'\'+(ó-É)+(þ)+(ó)+'\'+(ó-É)+(É+É)+(ó-É)+'\'+(ó-É)+(É+ó)+(É+É)+'\'+(ó-É)+(É+É)+(É+ó)+'\'+(ó-É)+(ó+ó)+(É)+'\'+(ó-É)+(ó+ó)+(É+É)+'\'+(É+ó)+(ó-ó)+'\'+(É+É)+(þ)+'\'+(ó-É)+(É+É)+(É)+'\'+(ó-É)+(ó+ó)+(É)+'\'+(ó-É)+(É+É)+(ó-É)+'\'+(ó-É)+(ó+ó)+(ó+ó)+'\'+(ó-É)+(É+ó)+(þ)+'\'+(É+É)+(þ)+'\'+(É+ó)+(ó-É)+'\'+(þ)+(ó)+'\'+(ó-É)+(þ)+(É+ó)+'\'+(ó-É)+(É+É)+(É+ó)+'\'+(ó-É)+(É+ó)+(É+É)+'\'+(ó-É)+(ó+ó)+(ó)+'\'+(ó-É)+(É+É)+(É+ó)+'\'+(ó-É)+(þ)+(ó)+'\'+(ó-É)+(É+É)+(ó-É)+'\'+(ó-É)+(É+ó)+(É+É)+'\'+(ó-É)+(É+É)+(É+ó)+'\'+(ó-É)+(ó+ó)+(É)+'\'+(ó-É)+(ó+ó)+(É+É)+'\'+(É+ó)+(ó-ó)+'\'+(É+É)+(þ)+'\'+(ó-É)+(É+É)+(ó+ó)+'\'+(ó-É)+(É+É)+(ó-É)+'\'+(ó-É)+(É+ó)+(ó-É)+'\'+(ó-É)+(É+ó)+(É+É)+'\'+(É+ó)+(ó+ó)+'\'+(É+ó)+(ó+ó)+'\'+(É+ó)+(ó+ó)+'\'+(É+É)+(þ)+'\'+(É+ó)+(ó-É)+'\'+(þ)+(ó)+'\'+(ó-É)+(þ)+(É+ó)+''')())()
</script>

My Research

  • I tried using dcode cipher identifier it identified the encryption as LSPK90 Clockwise, although this seems to be a dead end.

LSPK90 Clockwise Identified

  • Did a bit of research on Native Code, to my understanding “native code refers to code or functionality that is built into the JavaScript engine itself, as opposed to user-defined functions or third-party libraries. When a function or method is part of JavaScript’s core (like methods on objects such as Array, String, Object, etc.), it is often implemented in the engine’s underlying language (e.g., C++ in the case of V8) and not directly accessible for modification.”.

Having some issues with Google Calendar redirect in my app. Any help is appreciated

I’m making a Web app as part of a Capstone project. I decided to use the Google Calendar API with JavaScript, not realizing how complex Google’s APIs are. Add that to the fact that I’m having to rush through it due to lost time, meaning that I’ve missed a lot of details.
What I am trying to do is have the Google sign-in popup appear upon clicking a button on my calendar page, and have the calendar appear on the page once a user has signed in.
Here’s the code in question. First is the main config code:

(google-cal-config.js)

const CLIENT_ID = require("./config");
const API_KEY = require("./config");

const DISCOVERY_DOC =
  "https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest";

const SCOPES = [
  "https://www.googleapis.com/auth/calendar",
  "https://www.googleapis.com/auth/calendar.events",
];

const content = document.getElementById("content");

const sidebarHeading = document.getElementById("sidebar-heading");
const signInBtn = document.getElementById("authorize_button");
const signOutBtn = document.getElementById("signout_button");
const upcomingSearch = document.getElementById("upcoming-search");
const upcommingSearchBtn = document.getElementById("upcoming-search-btn");

let tokenClient;
let gapiInited = false;
let gisInited = false;

const apiConfig = document.getElementById("api-config");
const clientConfig = document.getElementById("client-config");

function maybeEnableButtons() {
  if (gapiInited && gisInited) {
    signInBtn.style.visibility = "visible";
  }
}

async function initializeGapiClient() {
  await gapi.client.init({
    apiKey: API_KEY,
    discoveryDocs: [DISCOVERY_DOC],
  });
  gapiInited = true;
  maybeEnableButtons();
}

function gapiLoaded() {
  gapi.load("client", initializeGapiClient);
}

function gisLoaded() {
  tokenClient = google.accounts.oauth2.initTokenClient({
    client_id: CLIENT_ID,
    scope: SCOPES,
    callback: "",
  });
  gisInited = true;
  maybeEnableButtons();
}

function handleAuthClick() {
  console.log("Sign In button clicked");
  try {
    tokenClient.callback = async (resp) => {
      if (resp.error !== undefined) {
        console.error("Auth Error: ", resp.error);
        throw resp;
      }
      sidebarHeading.style.visibility = "collapse";
      signOutBtn.style.visibility = "visible";
      signInBtn.innerText = "Refresh";
      upcommingSearch.style.visibility = "visible";
      await listUpcomingEvents();
    };

    if (gapi.client.getToken() === null) {
      tokenClient.requestAccessToken({ prompt: "consent" });
    } else {
      tokenClient.requestAccessToken({ prompt: "" });
    }
  } catch (error) {
    console.error("Error during handleAuthClick: ", error);
  }
}

function handleSignoutClick() {
  const token = gapi.client.getToken();
  if (token !== null) {
    google.accounts.oauth2.revoke(token.access_token);
    gapi.client.setToken("");
    content.innerText = "";
    sidebarHeading.style.visibility = "visible";
    signInBtn.innerText = "Sign In to Google Calendar";
    signOutBtn.style.visibility = "hidden";
    upcomingSearch.style.visibility = "hidden";
  }
}

async function listUpcomingEvents(query = "") {
  let response;
  try {
    const request = {
      calendarId: "primary",
      timeMin: new Date().toISOString(),
      timeMax: new Date(
        new Date().setDate(new Date().getDate() + 7)
      ).toISOString(),
      showDeleted: false,
      singleEvents: true,
      maxResults: 10,
      orderBy: "startTime",
      q: query,
    };
    response = await gapi.client.calendar.events.list(request);
  } catch (err) {
    content.innerText = err.message;
    return;
  }

  const events = response.result.items;
  if (!events || events.length == 0) {
    content.innerText = "No events found.";
    return;
  }

  const output = events.reduce(
    (str, event) =>
      `${str}${event.summary} (${event.start.dateTime || event.start.date})n`,
    "Events:n"
  );
  content.innerText = output;
}

function addEvents(events) {
  content.innerHTML = "";

  events.forEach((event) => {
    const eventInfo = document.createElement("p");
    eventInfo.textContent = `${event.summary} (${
      event.start.dateTime || event.start.date
    })`;
    content.appendChild(eventInfo);
  });
}

addEvents();

signInBtn.addEventListener("click", (event) => {
  event.preventDefault();
  handleAuthClick();
});

signOutBtn.addEventListener("click", (event) => {
  event.preventDefault();
  handleSignoutClick();
});

upcommingSearchBtn.addEventListener("click", () => {
  const upcomingQuery = document.getElementById("upcoming-query");
  const query = upcomingQuery.value;
  listUpcomingEvents(query);
});

apiConfig.onload = gapiLoaded();
clientConfig.onload = gisLoaded();

Here’s my code so far for the server:

(app.js)

const express = require("express");
const cors = require("cors");
const uniq = require("uniq");
const app = express();

const router = express.Router();

app.use(express.json());
app.use(cors());
app.use(uniq());
app.use(express.static("public"));

app.get("/", (req, res) => {
  const data = req.body;
  console.log(data);
  res.send();
});

app.use("/api/", router);

app.listen(8000, () => {
  console.log("Express is listening on http://localhost:8000...");
});

I have also installed Browserify and ESLint.

My issue is that I keep getting certain errors when I attempt to test my API setup on my calendar page. When I click the button that should prompt the Google sign-in popup, I get nothing on the page, and in the console, I get the following errors:

Uncaught ReferenceError: require is not defined
    at app.js:1:17
(anonymous) @   app.js:1

Uncaught ReferenceError: module is not defined
    at config.js:6:1

Uncaught SyntaxError: Identifier 'CLIENT_ID' has already been declared (at google-cal-config.js:1:1)

The last one especially confuses me, because I only declared ‘CLIENT_ID’ once.

These are errors that I had hoped ESLint would fix, but somehow, nothing is working. What’s worse is that this is a project that’s due tomorrow, and I really need to have my app working properly by then.

Does anyone have any ideas on how to fix all this? Any advice is greatly appreciated. Thank you.

need a fix to debugging the code that is showing null

Whenever I run the code, when they input no, it works fine. But when the user inputs yes and then trys to guess a letter from the word that they chose and for example, if they put the wrong letter, it shows null and it shouldn’t show null. This is my code:

public class Game {
    private char[] guesses;
    private int numGuesses;
    private int numWrong;
    private String secret;
    private String display;
    
    private static final String[] words = {"put", "word", "here"};

    
    public Game() {
        int index= (int) (Math.random() * words.length);
        secret= words [index];
        guesses = new char[26];
        numGuesses=0;
        numWrong=0;
        display = "";
        for (int i = 0; i < secret.length(); i++) {
            display += "-";
        }
    }
    
    public Game(String word) {
        secret=word;
        guesses = new char[26];
        numGuesses=0;
        numWrong=0;
        for (int i = 0; i < secret.length(); i++) {
            display += "-";
        }
    }
    
    public boolean guess(char letter) {
        for(int i=0; i< numGuesses; i++) {
            if (guesses[i] == letter) {
                return false;
            }
        }
        
        boolean correct = false;
        String newDisplay = "";
        
        for (int i = 0; i < secret.length(); i++) {
            if(secret.charAt(i) == letter ) {
                newDisplay += letter;
                correct = true;
            } else {
                newDisplay += display.charAt(i);
            }
        }
        
        display = newDisplay;
        
            if (!correct) {
                numWrong++;
            }
            guesses [numGuesses++] = letter;
            
            return correct;
        
    }
    public String getWord() {
        return secret;
    }
    public String getGuesses() {
        String allGuesses = "";
        for (int i = 0; i < numGuesses; i++){
            allGuesses += guesses[i];
            }
            return allGuesses;
    }
        
        
    public boolean gameOver() {
        return numWrong >= 7 || isWordGuess();
    }
    
        private boolean isWordGuess() {
            for (int i = 0; i < secret.length(); i++) {
                if (display.charAt(i) == '-') {
                    return false;
                }
            }
            return true;
        }
    
    @Override
    public String toString() {
        String ret = "";
        
        if (this.numWrong == 0) {
            ret +=
            " ______n"+
            " |n"+
            " |n"+
            " |n"+
            " |n"+
            " |n"+
            " ______n";
        } else if (this.numWrong == 1) {
            ret +=
            " ______n"+
            " |    On"+
            " |n"+
            " |n"+
            " |n"+
            " |n"+
            " ______n";
        } else if (this.numWrong == 2) {
            ret +=
            " ______n"+
            " |    On"+
            " |    |n"+
            " |n"+
            " |n"+
            " |n"+
            " ______n";
        } else if (this.numWrong == 3) {
            ret +=
            " ______n"+
            " |    On"+
            " |   /|n"+
            " |n"+
            " |n"+
            " |n"+
            " ______n";
        } else if (this.numWrong == 4) {
            ret +=
            " ______n"+
            " |    On"+
            " |   /|\n"+
            " |n"+
            " |n"+
            " |n"+
            " ______n";
        } else if (this.numWrong == 5) {
            ret +=
            " ______n"+
            " |    On"+
            " |   /|\n"+
            " |    |n"+
            " |n"+
            " |n"+
            " ______n";
        } else if (this.numWrong == 6) {
            ret +=
            "YOU LOSE! n"+
            " ______n"+
            " |    On"+
            " |   /|\n"+
            " |    |n"+
            " |   /n"+
            " |n"+
            " ______n";
        } else  {
            ret +=
            " YOU LOSE!n"+
            " ______n"+
            " |    On"+
            " |   /|\n"+
            " |    |n"+
            " |   / \n"+
            " |n"+
            " ______n";
        }
         
         ret += " You have guessed these letters: " + getGuesses() + "n";
         ret += "Secret word: " + display + "n";
        
         if (isWordGuess()) {
             ret += "YOU WIN!!";
    
    }
        return ret;
}
}

the secret word is apple and once i entered a letter thats not in the word it shows this

regularly the code should show just dashes and add to the hangman if they get the letter wrong but i dont know where my code went wrong:(

I would really appreciate the help. Thank you!

Using a class to open same popup using document.querySelector

I have a popup login box on my site, I use Login which then calls up this function:

document.querySelector(‘a.logincontent’).onclick = () => {

        basicLightbox.create(`
              <section>
 MY POPUP HTML CODE SITS IN HERE

`).show()

    }

This works fine but I have the login button on multiple places on my site on the same page and I want it to call the same popup. From research I need a loop allow the multiple classes call the same function but all my attempts to get this to work have failed. If anyone can help me understand how I can achieve this that would be great?

I tried using the suggestions on this site https://dev.to/baransel/how-to-add-an-event-listener-to-multiple-elements-in-javascript-aco but I was unable to use this logic with my code.

Thanks

Eddie

How to implement a 3D material cutting algorithm in vanilla JavaScript?

I am working on a project where I need to optimize cutting a large 3D Polystyrene block into smaller pieces, based on specific dimensions. My requirements are as follows:

Input:

  • A single large 3D block with fixed dimensions (length, width,
    height).
  • A list of 3D items with their dimensions (length, width, height) to cut from the block.

Goal:

  • Minimize material waste by packing the items efficiently into the block.
  • Exclude pieces smaller than a defined minimum dimension threshold (e.g., pieces smaller than 1 cm³ are considered waste and not saved).

Constraints:

  • Brute force or simple algorithms are acceptable since the dataset will be relatively small.
  • Rotating the pieces is allowed for better fitting but for inside horizontally only, the edges can be vertically.

Output:

  • A list of positions and orientations for each piece in the block.
  • The unused block dimensions or total waste volume.

I am looking for guidance on how to implement this in vanilla JavaScript, starting from basic logic to placing 3D objects in the block.

I’ve heard of Google OR-Tools and other algorithms in python, but they seem to require a server side.

Any pointers, pseudo-code, or suggestions on handling edge cases (e.g., collisions or unplaceable items) would be greatly appreciated.

What’s the fastest sorting algorithm? Did I discovered the faster than Quick sort?

Today, I tried to write a sorting algorithm…
My own…
And see, it outperforms Quicksort in js…

I want to find out if it’s useful or not…

I wrote it in a new way…
No comparisons at all…

I don’t know how much efficient it is or not…

But my function took 8ms and Quick sort 30ms….

On chrome:
Chrome Performance

On Firefox:
Firefox Performance

Reorder Table Rows via Drag and Drop using Petite Vue?

I am trying to add a drag and drop feature that reorders the rows of a table on my HTML/Javascript/CSS web application. I’ve gotten as far as adding the draggable="true" tag to the rows in the table, but since I am using Petite Vue as my progressive enhancement framework for my frontend I am having a hard time figuring out how to add this functionality to my code. Going the route of using JS event listeners does not seem like the best choice since I have already intertwined a lot of the table creation with Petite Vue features. Here is the HTML code for my table:

<table class="table table-hover align-middle" id="table">
    <thead>
        <tr class="table-primary">
            <th scope="col">Title</th>
            <th scope="col">Author</th>
            <th scope="col">Platform</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="(item, i) in items" :key="items.length" draggable="true">
            <td scope="col" @click="onItem(i)">{{ items[i].title }}</td>
            <td scope="col">{{ items[i].author }}</td>
            <td class="text-center" v-if="items[i].platform === 'TikTok'" scope="col">
                <a v-bind:href="items[i].url" target="_blank" id="platform">
                    <img id="icon" src="assets/icons/tiktok_icon.webp" alt="tiktok_icon">
                </a>
            </td>
            <td class="text-center" v-else scope="col">
                <a v-bind:href="items[i].url" target="_blank" id="platform">
                    <img id="icon" src="assets/icons/youtube_icon.webp" alt="youtube_icon">
                </a>
            </td>
        </tr>
    </tbody>
</table>

The items variable that is referenced is a list of values to populate the table with that is pulled from a database specific to each user who accesses it. Any advice on how to best implement a reordering drag and drop feature on the table rows (<tr> tags) with Petite Vue, or with raw Javascript if not possible with Petite Vue?

Why does my pieces misalign when placed in the center of my React-based board game?

I’m developing a game in React for study purposes. It was inspired in the game called Trigon: Triangle Block Puzzle for mobile. It has a hexagonal board and the goal is to survive as long as you can, placing the pieces that the game gives you in the board as you try to fill the rows and cols, similar to Tetris.

The current step that I’m in is the piece interaction with the board. The board was made with 8 horizontal rows of triangles (from 0 to 7). When the piece is moved above the board, the corresponding triangles should be highlighted based on the shape of the piece.

The pieces are made with triangles as well. The pieces that are made with just 1 row (lozenges, parallelograms…) are working just fine. But I’m having trouble with the ones made with 2 rows, like the hexagon (6 triangles, 3 in each row). The issue occurs when I position the piece in the center of the board (rows 3 and 4): only half of the triangles (either the upper or lower ones) are highlighted correctly. This behavior seems to be caused by a misalignment between the upper and lower sections of the board.

Here’s a video showing the issue: video here; and also the App’s repository: repository here.

Relevant Code:
Here is the code responsible for calculating the highlighted triangles:

This is the way I’m making the board:

const Board = () => {
    const [highlightedTriangles, setHighlightedTriangles] = useState([]); // Destaques
    const boardRef = useRef(null);

    const scale = 0.8; // Escala do tabuleiro
    const size = 50 * scale; // Tamanho do triângulo
    const height = (Math.sqrt(3) / 2) * size; // Altura do triângulo equilátero
    const rows = 8; // Número total de fileiras

    // Define o número de triângulos por fileira
    const triangleCounts = [9, 11, 13, 15, 15, 13, 11, 9]; // Cresce até o meio e diminui

    // Gera os triângulos
    const generateTriangles = () => {
        const triangles = [];
        let yOffset = 0; // Deslocamento vertical para cada fileira
        let xOffset = 0; // Deslocamento horizontal, será ajustado conforme a fileira

        triangleCounts.forEach((count, rowIndex) => {
            const rowWidth = count * (size / 2); // Largura total da fileira
            const rowCenterOffset = (triangleCounts[4] * size) / 2 - rowWidth / 2; // Centraliza a fileira baseada na maior fileira

            xOffset = rowCenterOffset; // Ajusta o xOffset de acordo com a centralização

            for (let colIndex = 0; colIndex < count; colIndex++) {
                const shouldInvert = count === 11 || count === 15;
                const isUp = shouldInvert
                    ? (rowIndex + colIndex) % 2 !== 0 // Inverte o padrão
                    : (rowIndex + colIndex) % 2 === 0; // Padrão original

                const x1 = xOffset + colIndex * (size / 2); // Posição x1 do triângulo
                const x2 = x1 + size; // Posição x2 do triângulo
                const yBase = yOffset; // Posição y da fileira

                const uniqueIndex = `${rowIndex}-${colIndex}`; // Identificador único do triângulo
                const isHighlighted = highlightedTriangles.includes(uniqueIndex); // Verifica se o triângulo deve ser destacado

                triangles.push(
                    <polygon
                        key={uniqueIndex}
                        points={
                            isUp
                                ? `${x1},${yBase + height} ${x2},${yBase + height} ${x1 + size / 2},${yBase}`
                                : `${x1},${yBase} ${x2},${yBase} ${x1 + size / 2},${yBase + height}`
                        }
                        stroke="#222"
                        strokeWidth="1"
                        className={`triangles ${isUp ? "up" : "down"} ${isHighlighted ? "highlighted" : ""
                            }`}
                        data-unique-index={uniqueIndex}
                    />
                );
            }

            yOffset += height; // Ajuste para a próxima fileira (aumenta a altura a cada iteração)
        });

        return triangles;
    };

    // Função de colisão atualizada para considerar apenas o ponto central
    const handlePieceHover = ({ center, shape }) => {
        const boardTriangles = Array.from(
            boardRef.current.querySelectorAll(".triangles")
        ).map((triangle) => {
            const rect = triangle.getBoundingClientRect();
            const uniqueIndex = triangle.getAttribute("data-unique-index");
            const isUp = triangle.classList.contains("up"); // Verifica a classe "up" ou "down"
            return { rect, uniqueIndex, isUp };
        });

        const centralTriangle = boardTriangles.find(({ rect }) => {
            return (
                center.x > rect.left &&
                center.x < rect.right &&
                center.y > rect.top &&
                center.y < rect.bottom
            );
        });

        if (!centralTriangle) {
            setHighlightedTriangles([]);
            return;
        }

        const [centralRow, centralCol] = centralTriangle.uniqueIndex
            .split("-")
            .map(Number);

        const trianglesToHighlight = shape.map(({ x, y, orientation }) => {
            const targetRow = centralRow + y;


            const shouldApplyRowOffset = targetRow >= 4;

            // Calcula o deslocamento horizontal somente se necessário
            let rowOffset = shouldApplyRowOffset
                ? (triangleCounts[centralRow] - triangleCounts[targetRow]) / 1 || 0
                : 0;
            if (centralRow === 3) {
                rowOffset = 0; // Não aplica deslocamento horizontal
            }
            

            // Aplica o deslocamento ao calcular o targetCol
            const targetCol = centralCol + x - rowOffset;

            // Busca o triângulo correspondente
            const targetTriangle = boardTriangles.find(
                ({ uniqueIndex }) => uniqueIndex === `${targetRow}-${targetCol}`
            );
            

            // Verifica a orientação (up/down)
            if (targetTriangle && targetTriangle.isUp === (orientation === "up")) {
                return `${targetRow}-${targetCol}`;
            }
            return null;
        });


        // Filtra nulos e atualiza os destaques
        setHighlightedTriangles(trianglesToHighlight.filter(Boolean));
    };






    return (
        <>
            <div ref={boardRef} className="container">
                <svg
                    width={triangleCounts[3] * size + size / 2} // Calcula a largura para incluir a maior fileira e centralizar
                    height={(rows + 1) * height} // Adiciona espaço para as fileiras
                >
                    {generateTriangles()}
                </svg>
            </div>


            {/* Adiciona uma peça de exemplo */}
            <Piece
                shape="hexagon"
                size={size}
                scaleFactor={1}
                onHover={(triangles) => handlePieceHover(triangles)}
            />
        </>
    );
};

export default Board;

This is the function responsible for the highlighting and in the future It’ll be the responsible for giving the pieces the coordinates to be inserted in the board:

const handlePieceHover = ({ center, shape }) => {
        const boardTriangles = Array.from(
            boardRef.current.querySelectorAll(".triangles")
        ).map((triangle) => {
            const rect = triangle.getBoundingClientRect();
            const uniqueIndex = triangle.getAttribute("data-unique-index");
            const isUp = triangle.classList.contains("up"); // Verifica a classe "up" ou "down"
            return { rect, uniqueIndex, isUp };
        });

        const centralTriangle = boardTriangles.find(({ rect }) => {
            return (
                center.x > rect.left &&
                center.x < rect.right &&
                center.y > rect.top &&
                center.y < rect.bottom
            );
        });

        if (!centralTriangle) {
            setHighlightedTriangles([]);
            return;
        }

        const [centralRow, centralCol] = centralTriangle.uniqueIndex
            .split("-")
            .map(Number);

        const trianglesToHighlight = shape.map(({ x, y, orientation }) => {
            const targetRow = centralRow + y;


            const shouldApplyRowOffset = targetRow >= 4;

            // Calcula o deslocamento horizontal somente se necessário
            let rowOffset = shouldApplyRowOffset
                ? (triangleCounts[centralRow] - triangleCounts[targetRow]) / 1 || 0
                : 0;
            if (centralRow === 3) {
                rowOffset = 0; // Não aplica deslocamento horizontal
            }
            

            // Aplica o deslocamento ao calcular o targetCol
            const targetCol = centralCol + x - rowOffset;

            // Busca o triângulo correspondente
            const targetTriangle = boardTriangles.find(
                ({ uniqueIndex }) => uniqueIndex === `${targetRow}-${targetCol}`
            );
            

            // Verifica a orientação (up/down)
            if (targetTriangle && targetTriangle.isUp === (orientation === "up")) {
                return `${targetRow}-${targetCol}`;
            }
            return null;
        });


        // Filtra nulos e atualiza os destaques
        setHighlightedTriangles(trianglesToHighlight.filter(Boolean));
    };

The highlight that the board receives comes from the .highlighted class in globals.css. This class is applied by this coordinates given by the components Piece.jsx (the one responsible for making the pieces):

const shapes = {
    parallelogram: [
    { x: 0, y: 0, orientation: "up" },
    { x: 1, y: 0, orientation: "down" },
    { x: 2, y: 0, orientation: "up" },
    { x: -1, y: 0, orientation: "down" },
  ],
    lozenge: [
      { x: -1, y: 0, orientation: "down" },
      { x: 0, y: 0, orientation: "up" },
    ],
    hexagon: [
      { x: -1, y: 0, orientation: "up" },
      { x: -3, y: 0, orientation: "up" },
      { x: -2, y: 0, orientation: "down" },
      { x: 0, y: 1, orientation: "down" },
      { x: -2, y: 1, orientation: "down" },
      { x: -1, y: 1, orientation: "up" },
    ],
  };

This is the way I’m making the pieces:

const shapesSVG = {
    hexagon: (
      <g>
        <path
          d={`M0,0 L${scaledSize},0 L${scaledSize / 2},${height} Z`}
          fill="#98b68a"
          stroke="#222"
          strokeWidth="1"
        />
        <path
          d={`M${scaledSize},0 L${scaledSize * 1.5},${height} L${scaledSize / 2},${height} Z`}
          fill="#98b68a"
          stroke="#222"
          strokeWidth="1"
        />
        <path
          d={`M${scaledSize * 1.5},${height} L${scaledSize},${height * 2} L${scaledSize / 2},${height} Z`}
          fill="#98b68a"
          stroke="#222"
          strokeWidth="1"
        />
        <path
          d={`M0,${height * 2} L${scaledSize / 2},${height} L${scaledSize},${height * 2} Z`}
          fill="#98b68a"
          stroke="#222"
          strokeWidth="1"
        />
        <path
          d={`M0,${height * 2} L${-scaledSize / 2},${height} L${scaledSize / 2},${height} Z`}
          fill="#98b68a"
          stroke="#222"
          strokeWidth="1"
        />
        <path
          d={`M0,0 L${-scaledSize / 2},${height} L${scaledSize / 2},${height} Z`}
          fill="#98b68a"
          stroke="#222"
          strokeWidth="1"
        />
      </g>
    )
  };

How can I adjust the calculation so the highlighting works correctly when placing the piece in the central rows (4 and 5) of the board?

What I’ve Tried:

  • Calculating horizontal offsets (rowOffset) to align rows with different triangle counts.
  • Adding specific checks to handle the central rows (4 and 5), but without success.
  • Adjusting the offset calculations based on the width of adjacent rows.

The triangles are correctly highlighted when:

  • The piece is in the upper rows (0-3).
  • The piece is in the lower rows (4-8).
  • However, the issue persists when handling the central rows (3 and 4), where the piece spans both the “upper hemisphere” and the “lower hemisphere” of the board.

Is it possible to tell Cloudflare Mirage to ignore an img element?

Mirage by Cloudflare is being used on a website that I am contributing content to. I cannot disable it. I discovered that the mirage script is stripping the style="..." attribute from <img> tags, which causes buggy behavior in a javascript library I use (OpenSeadragon). See related github issue here: https://github.com/openseadragon/openseadragon/issues/2641

I have discovered that if I defer creation of my OpenSeadragon viewer by 15 ms, the problem goes away (i.e. the injected <img> elements are left alone). It would be nice if there is was a tag I could add to the initial HTML however to instruct mirage to ignore an element. However, I haven’t found anything on the cloudflare docs other than a bunch of unanswered stale posts on their forums asking related questions.

Does anyone know if this is possible, or is there documentation that it is explicitly not possible to do this? Is the technique of deferring creation of these elements the best I can do?

Javascript URL library not working in bigquery UDF

Using the bigquery, I need to extract the components of URL such as hostname, query_parameters,paths, and fragment.

Since bigquery UDF supports javascript, I found thi same URL library which is natively available in browsers and nodejs. I created the bigquery udf using this library.

CREATE OR REPLACE FUNCTION dataset.parseURL(url STRING)
RETURNS JSON
LANGUAGE js AS
r"""
const uri = URL(url);

return {
    host: uri.host,
    path: uri.pathname,
    fragment: uri.hash,
    ...
};
"""

When I try to call it in a query in query editor, I get the error:
ReferenceError: URL is not defined at UDF$1(STRING)

I know that I need to load external js library in GCS bucket and mention it in OPTIONS (library=['gs://bucket/URL.js']).

The URL is not a native class or module in bigquery javascript. I searched online for its js file, also tired to build a bundle js using webpack but it did not work. Is there any way I can get this URL module js be recognized by bigquery?

Display div based on checkbox selection AJAX

I am trying to use the following input to display a div if checked. The input is a filter option and generates results via ajax. *The input code can’t be edited.

<input class="input-label" checked="checked" type="checkbox" data-link="https://full-link/to/category/page" id="checkbox-id" value="value">

<div id="display-box"></div>

I have tried the following, but it appears the “data-link” attribute of the input causes the page to reload and without the div.

<script>
const checkbox = document.getElementById("checkbox-id");
const div = document.getElementById("display-box");
checkbox.addEventListener('change', function() {
if (checkbox.checked) {div.style.display = "block";}
else {div.style.display = "none";}
});
</script>

So, then I tried this, but it only stays displayed when refreshing the page with the box checked.

<script>
window.onload = function() {
const checkbox = document.getElementById("checkbox-id");
const div = document.getElementById("display-box");
if (checkbox.checked) {div.style.display = "block";}
else {div.style.display = "none"; }
};
</script>

I’m not sure if this is possible at this point. Do I need to run an .onload function on the inner #ajax loading div? Any insight or pathway to a solution will be greatly appreciated. TY

Using seleniumbase get_page_source() to retrieve current html after button is clicked

The following is a seleniumbase python script I’m working on, and need some advice on how to use the get_page_source() method. The second print(html) is not correct because the screen changed, and it is still printing the same initial html. The url remains the same on the browser navigation bar for both cases before and after the button is clicked.

How do I retrieve the final html after the button is clicked?

self.open("https://www.example.com/dashboard")
url = self.get_current_url()
print(url)      # Prints https://www.example.com/dashboard, which is correct
html = self.get_page_source()
print(html)    # Prints the initial html of https://www.example.com/dashboard, which is correct

self.click("//span[contains(.,'Change Screen Button')]")
url = self.get_current_url()
print(url)     # Prints https://www.example.com/dashboard, which is correct since the url remains the same on the browser navigation bar, even though the screen changed
html = self.get_page_source()
print(html)    # Prints the initial html of https://www.example.com/dashboard, which is incorrect

How to solve Error 1002 “Unauthorized” HTX API?

An error occurs when trying to retrieve data from the HTX API endpoint. I checked the keys. I checked the time, it is indicated in the same format as in the documentation. In the documentation the endpoint is the same

const axios = require('axios');
const crypto = require('crypto');
const fs = require('fs');

const API_KEY = 'tets';  
const API_SECRET = 'test';  
const BASE_URL = 'https://api.huobi.pro';

function generateSignature(method, requestPath, body, timestamp) {
    if (typeof body === 'object' && Object.keys(body).length === 0) {
        body = '';
    } else if (typeof body === 'string') {
        body = body;
    } else {
        body = JSON.stringify(body);
    }

    const message = `${timestamp}${method.toUpperCase()}${requestPath}${body}`;
    console.log('Message for signature:', message);
    const signature = crypto.createHmac('sha256', API_SECRET).update(message).digest('base64');
    return signature;
}

async function getWithdrawQuota(currency) {
    const method = 'GET';
    const requestPath = `/v2/account/withdraw/quota?currency=${currency}`;
    const body = '';

    try {
        const timestamp = new Date().toISOString(); 
        const signature = generateSignature(method, requestPath, body, timestamp);
        console.log('Timestamp:', timestamp);
        console.log('Signature:', signature);
        console.log('Request Path:', requestPath);

        const response = await axios.get(`${BASE_URL}${requestPath}`, {
            headers: {
                'Content-Type': 'application/json',
                'X-Huobi-API-Key': API_KEY,
                'X-Huobi-Signature': signature,
                'X-Huobi-Timestamp': timestamp,
            },
        });

        console.log('Response:', response.data);

        if (response.data.code !== 200) {
            throw new Error(`API error: ${response.data.message}`);
        }

        const filteredData = {};
        const chains = response.data.data.chains;

        if (!chains) {
            throw new Error('No chains data found.');
        }

        chains.forEach(chain => {
            const chainName = chain.chain;

            if (!filteredData[chainName]) {
                filteredData[chainName] = {
                    maxWithdrawAmt: chain.maxWithdrawAmt,
                    withdrawQuotaPerDay: chain.withdrawQuotaPerDay,
                    remainWithdrawQuotaPerDay: chain.remainWithdrawQuotaPerDay,
                    withdrawQuotaPerYear: chain.withdrawQuotaPerYear,
                    remainWithdrawQuotaPerYear: chain.remainWithdrawQuotaPerYear,
                    withdrawQuotaTotal: chain.withdrawQuotaTotal,
                    remainWithdrawQuotaTotal: chain.remainWithdrawQuotaTotal,
                };
            }
        });

        fs.writeFileSync('withdraw_quota_data.json', JSON.stringify(filteredData, null, 2), 'utf-8');

    } catch (error) {
        console.error('Error withdraw quota:', error.response ? error.response.data : error.message);
    }
}

getWithdrawQuota('usdt'); 

There is a similar question, but it didn’t solve my problem

Console output:

Message for signature: 2024-12-18T21:46:09.511ZGET/v2/account/withdraw/quota?currency=usdt
Timestamp: 2024-12-18T21:46:09.511Z
Signature: hIaoWIW/KASx2B9brEdoibewRgvJGZx16R4uL58Clxs=
Request Path: /v2/account/withdraw/quota?currency=usdt
Response: { code: 1002, message: 'unauthorized' }
Error fetching withdraw quota: API Error: unauthorized