Using typeof() to get object value type – receiving string instead of array

I have an object where two parameters hold arrays as their values. When I try to output the types of these values using the typeof() function in a loop, for some reason, I always get a string type instead of the actual array value.

const add = "add"
const edit = "edit"
const required = {
  user: [add, edit],
  profile: [edit],
}

for (let p in required) {
  console.log(p, typeof(p))
}
Output:

string
string

React: How to Properly Render Table Rows as Components Within Table Body?

I’m encountering an issue in my React application where I’m rendering a table with dynamic rows using components. However, the rows are being treated as separate elements instead of components within the table body.

Despite generating the rows dynamically using components, they’re not aligning properly with the table headers. I’ve tried various approaches, including encapsulating each row within its own element, but the issue persists.

  1. TableHead Component:
function TableHead({ rowCount }) {
  return (
    <div className='table-container'>
      <table>
        <thead>
          <tr>
            <th>S. No</th>
            <th>Subject</th>
            <th>Grade</th>
          </tr>
        </thead>
        <tbody>
          <tr><InitialRender count={rowCount} /></tr>
        </tbody>
      </table>
    </div>
  );
}

  1. InitialRender Component:
function InitialRender({ count }) {
  const initialRows = [];
  for (let i = 0; i < count; i++) {
    initialRows.push(
      <TableRow key={i + 1} count={i + 1} />
    );
  }

  return initialRows;
}
  1. TableRow Component
function TableRow({ count }) {
  return (
    <tr>
      <td>{count}</td>
      <td><input type="text" placeholder='Enter subject' /></td>
      <td>
        <select name="" id="dropdown">
          <option value="">Grades</option>
          <option value="O">O</option>
          <option value="A+">A+</option>
          <option value="A">A</option>
          <option value="B+">B+</option>
          <option value="B">B</option>
          <option value="AB">AB</option>
        </select>
      </td>
    </tr>
  );
}

  1. App Component:
function App() {
  const [rowCount, setRowCount] = useState(6);

  const handleAddRow = () => {
    setRowCount(prevCount => prevCount + 1);
  };

  return (
    <div className='form-container'>
      <form action=''>
        <TableHead rowCount={rowCount} />
        <InitialRender count={rowCount} />
        <div className='buttons'>
          <AddRow onAddRow={handleAddRow} />
          <Submit />
        </div>
      </form>
    </div>
  );
}

Matter.JS Scaling textures automatically + sprites not on body

I am making a game where every time you click, a fruit falls down from the mouse coordinates. The game was working when I was working with plain colours, so then I decided to add textures. However, I encountered two issues.

  1. I have to manually add in xScale and yScale, which isn’t good since there are many different fruits and sizes and I don’t want to manually tune it for all of them. I tried to get the size of the body and divide it by the image size. My code is below:
// getting the size of the fruit by the type of fruit it is
radius = fruit_kinds.indexOf(kind)*6+10

// making the fruit, note that I already defined mouse_x before
fruit = Bodies.circle(mouse_x, 120, radius, { isStatic: false })

// getting the image
const path = '../static/assets/cherry.png';
const image = new Image();
image.src = path;

// getting the scales (this might not work). 
// Note that 2*radius = diameter = width of fruit
xscale = 2*radius/(image.width)
yscale = 2*radius/(image.height)

// adding it to the body parameters
fruit['render']['sprite']['texture'] = path
fruit['render']['sprite']['xScale'] = xscale
fruit['render']['sprite']['yScale'] = yscale

When I ran this code, the sprite became so small that I could barely see it. I suspect that the radius isn’t in the same units as the image size I got? But I am not sure. Help would be appreciated!

  1. The sprite I added was not appearing directly on the body. There seems to be some offset. I thought that the offset was due to xOffset and yOffset, so I made them zero.
fruit['render']['sprite']['xOffset'] = 0
fruit['render']['sprite']['yOffset'] = 0

However, when I tried this, the fruit disappeared.

I have checked many other StackOverflow posts, however none of these can help with my problem.

Could somebody please help? Thank you in advance 😀

How to send voice audio continuously using socket.io?

I am working on a project where I want to continuously transmit audio over my server using Socket.io. Currently, users can send audio, but there is a delay because the function waits for the key to be unpressed before sending the audio to the server. As mentioned earlier, I am using Socket.io along with JavaScript and Node.js for this project.

Here is the current code:

const socket = io();

const audioElement = document.getElementById('audioElement');

let isPushed = false;
let mediaRecorder;
let chunks = [];

// Request access to the user's microphone
navigator.mediaDevices.getUserMedia({ audio: true })
    .then(stream => {
        // Create a MediaRecorder to record audio chunks
        mediaRecorder = new MediaRecorder(stream);

        // Handle data available event to collect audio chunks
        mediaRecorder.addEventListener('dataavailable', event => {
            chunks.push(event.data);
            // Send the audio chunk to the server immediately
            socket.emit('voiceMessage', event.data);
        });

        // Handle stop event to stop recording
        mediaRecorder.addEventListener('stop', () => {
            // Stop the recording and reset the chunks
            mediaRecorder.stop();
            chunks = [];
        });

        // Add an event listener to detect the 'N' key press
        document.addEventListener('keydown', (event) => {
            if (event.key === 'n' || event.key === 'N') {
                if (!isPushed) {
                    document.getElementById('tpt1').play();
                    mediaRecorder.start();
                    isPushed = true;
                }
            }
        });

        // Add an event listener to detect the 'N' key release
        document.addEventListener('keyup', (event) => {
            if (event.key === 'n' || event.key === 'N') {
                if (isPushed) {
                    setTimeout(() => {
                        document.getElementById('tpt2').play();
                        mediaRecorder.stop();
                        isPushed = false;
                    }, 250);  // Add a 500 ms (half-second) delay
                }
            }
        });
    })
    .catch(error => {
        console.error('Error accessing microphone:', error);
    });

// Handle receiving voice messages from the server
socket.on('voiceMessage', (audioBlob) => {
    const audioURL = URL.createObjectURL(new Blob([audioBlob], { type: 'audio/webm;codecs:vorbis' }));
    const audioElement = new Audio(audioURL);
    audioElement.controls = true;
    document.body.appendChild(audioElement);
    audioElement.play();
});

I was expecting it to send the audio over the server immediately after starting the media record. If more information is needed to assist me, I will be happy to send it over! Thanks in advance!

HTML text being set by JS is overlapping other elements

I’m having this issue where the distance between HTML elements seems to be static and I have zero clue how to change it. For example hereenter image description here, the text at the top takes up so much space, but then here it is almost intersecting with the next element.enter image description here

I’m setting the content like this.

document.getElementById('route').textContent = `${bus.routeInfo.route}- ${headsignData.shortHeadsign}`

I’ve tried setting padding to fix it, same with margins and it doesn’t seem to work. Everything stays the same.

Any help appreciated.

What is problem coming after running app.js?Showing error in MongoDB DNS ,hostname error ,I don’t what is these,What is DNS problem?

enter image description here
why this error is coming ??
I’ve ensured that MongoDB is properly started, but I’m still facing this error for the first time in a while. I’m relatively new to Node.js and MongoDB, and I’m having trouble pinpointing where exactly this error is coming from.

I’ve tried checking my MongoDB URI, network connectivity, and DNS configuration, but I’m not sure what I’m missing or if this is a system default issue.

Can someone please explain what might be causing this error and how I can resolve it? Any insights or guidance would be greatly appreciated. Thank you!

Keycloak doesnt send cookies

we are using keycloak as container (connected to another mysql container on same server) on hetzner ubuntu server. We have two stages – develop and staging. They differ in so far that staging has a nginx load balancer and uses HTTPS while develop doesnt have a load balancer and uses only HTTP.

This is my Dockerfile for develop:

FROM quay.io/keycloak/keycloak:21.0.0 as builder

ENV KC_DB=mysql

ADD ./themes/tediro /opt/keycloak/themes/tediro

RUN /opt/keycloak/bin/kc.sh build

FROM quay.io/keycloak/keycloak:21.0.0
COPY --from=builder /opt/keycloak/ /opt/keycloak/

ENV KC_HOSTNAME_STRICT=false
ENV KC_HOSTNAME_STRICT_HTTPS=false
ENV KC_HTTP_ENABLED=true
ENV KC_HOSTNAME=auth.d-tms.tediro.com
ENV KC_LOGLEVEL=ALL
ENV KC_DB=mysql
ENV KC_DB_URL=jdbc:mysql://mysql:3306/keycloak
ENV KC_DB_USERNAME=keycloak
ENV KC_DB_PASSWORD=xxx
ENV KC_ADMIN=admin
ENV KC_ADMIN_PASSWORD=xxx
ENV KC_FEATURES=admin-fine-grained-authz
ENV KC_CACHE=local

ENV PROXY_ADDRESS_FORWARDING=false

ENV JDBC_PARAMS="useSSL=false&allowPublicKeyRetrieval=true&connectTimeout=50000"
ENV JAVA_TOOLS_OPTIONS="-Djboss.as.management.blocking.timeout=30000"
ENV JAVA_OPTIONS="-Djboss.as.management.blocking.timeout=6000"

ENTRYPOINT ["/opt/keycloak/bin/kc.sh", "start-dev"]

This is for staging:

FROM quay.io/keycloak/keycloak:21.0.0 as builder

ENV KC_DB=mysql

ADD ./themes/tediro /opt/keycloak/themes/tediro

RUN /opt/keycloak/bin/kc.sh build

FROM quay.io/keycloak/keycloak:21.0.0
COPY --from=builder /opt/keycloak/ /opt/keycloak/

ENV KC_HOSTNAME_STRICT=false
ENV KC_HOSTNAME_STRICT_HTTPS=true
ENV KC_HTTP_ENABLED=false
ENV KC_HOSTNAME=auth.s-tms.tediro.com
ENV KC_LOGLEVEL=ALL
ENV KC_DB=mysql
ENV KC_DB_URL=jdbc:mysql://mysql:3306/keycloak
ENV KC_DB_USERNAME=keycloak
ENV KC_DB_PASSWORD=xxx
ENV KC_ADMIN=admin
ENV KC_ADMIN_PASSWORD=xxx
ENV KC_FEATURES=admin-fine-grained-authz
ENV KC_CACHE=local
ENV KC_PROXY=edge

ENV PROXY_ADDRESS_FORWARDING=true

ENV JDBC_PARAMS="useSSL=true&allowPublicKeyRetrieval=true&connectTimeout=50000"
ENV JAVA_TOOLS_OPTIONS="-Djboss.as.management.blocking.timeout=30000"
ENV JAVA_OPTIONS="-Djboss.as.management.blocking.timeout=6000"

ENTRYPOINT ["/opt/keycloak/bin/kc.sh", "start"]

While staging is working fine, we are experiencing problems on develop.

In application code we use keycloak-js and call keycloak.login() to open keycloak hosted login page. This page sets 2 cookies: AUTH_SESSION_ID_LEGACY and KC_RESTART . On clicking the login button these cookies are supposed to get send (thats at least happening on staging) but they are not getting sent on develop. This leads to a Cookie not found. Please make sure cookies are enabled in your browser. error.

Problem is unrelated to browser settings since its happening everywhere and for everyone. Cookies Secure / SameSite options seem correct.

What could be a reason for keycloak to not send the cookies?

Tried to play around with all the options in the keycloak dockerfile.

Singleton services in angular

  1. ProviderIn: ‘root’; makes Angular service singleton, and what I understood from word singleton is having one common instance for whole application.

  2. If I instantiate that service in constructor of two components(creating an object from a class) that means I am crating 2 diff object, it contradict the first statement.

Can someone please explain me what singleton means in this scenario?

Jump to contents page with epub.js

A user can upload a epub file which, after the user provides a few options (like whether they want it rendered continuous or not) I open and display with epub.js. Together with the epub in the web page I provide a few buttons that allow the user to do things like page forwards and backwards through the epub.

I was wondering how I could have a button which changes the location to the contents page for the epub. Searching tells me that I can jump to a page using

book.goto(some_cfi)

or

rendition.display(some_cfi)

but I’m not sure what a cfi is nor if there’s any way for epub.js to know the cfi for the contents page (if it even exists) is nor can I currently get it to do anything.

How can I create a button that jumps to the contents page in a epub file display with epub.js?

How to create a “gamut” diagram using chart.js

Do you have any ideas on how to create such charts?

enter image description here

enter image description here

Of course, the background can be set… but then these squares, dots in different colors, triangle line.

Do you have any ideas on how to utilize existing chart.js plugins? There’s always the option to create something new, but perhaps something like this already exists?

I’ve looked through the list of charts at https://github.com/chartjs/awesome?tab=readme-ov-file#charts, but I don’t really see anything similar.

Unable to fetch and preload post data using Rest Api in WordPress Multisite

I have a multisite setup in which both main site and subsite is using same theme. On the index.php page it should show 3 post per page using query loop. The posts are displayed on the main site but it is not being fetched on the subsite.

I am using a different approach to show the post data without loading the page. for which I have used lightbox. when the plus icon is clicked lightbox is opened and shows the post data. it works on the main site but on subsite it does not fetch data in the lightbox.

main domain: https://www.bahai.in/
subsite: https://www.bahai.in/hi (data not fetched)

github directory: https://github.com/Trushar10/bahaiindia2024

Below is the code
index.php:

<div class="featured-stories">
                <div class="story-cards">
                    <?php
                    // Query to get 3 posts per page
                    query_posts('posts_per_page=3');

                    if (have_posts()) {
                        while (have_posts()) {
                            the_post();

                            get_template_part('template-parts/posts/content-stories');
                        }
                    }

                    // Reset Query
                    wp_reset_query();
                    ?>

                </div>
                <div class="light-box">
                    <div class="box-wrapper">
                        <div class="box">
                            <span class="close-btn">&times</span>
                            <h2></h2>
                            <!-- <p class="box-excerpt"></p> -->
                            <img src="" alt="" class="light-img" />
                            <p class="box-content"></p>
                        </div>
                    </div>
                </div>
            </div>

content-stories template:

<div>
    <figure>
        <div class="overlay"></div>
        <?php the_post_thumbnail(); ?>
    </figure>
    <div class="card-content">
        <h2><?php the_title(); ?></h2>
        <!-- <?php the_excerpt(); ?> -->
    </div>
    <?php $featured_img_url = get_the_post_thumbnail_url(get_the_ID(), 'full'); ?>
    <span class="close-btn view-btn" data-post-id="<?php the_ID(); ?>" data-src="<?php echo esc_url($featured_img_url); ?>">+</span>
</div>

function.php

// Add an action to handle the Ajax request
add_action('wp_ajax_get_post_data', 'get_post_data');
add_action('wp_ajax_nopriv_get_post_data', 'get_post_data');

function get_post_data()
{
  $post_id = $_POST['post_id'];

  // Get the post data by ID
  $post = get_post($post_id);

  if ($post) {
    $response = array(
      'title' => $post->post_title,
      'excerpt' => get_the_excerpt($post_id),
      'content' => apply_filters('the_content', $post->post_content),
    );

    echo json_encode($response);
  }

  wp_die();
}

app.js


// Lightbox
let lightImg = document.querySelector('.light-img');
let viewBtn = document.querySelectorAll('.view-btn');
let lightboxTitle = document.querySelector('.light-box h2');
// let lightboxExcerpt = document.querySelector('.box-excerpt');
let lightboxContent = document.querySelector('.box-content');

// Create an object to store post data
const postData = {};

// Preload data for all view buttons
viewBtn.forEach((el) => {
    const postId = el.getAttribute('data-post-id');
    const imgSrc = el.getAttribute('data-src');

    // Use the REST API to fetch post data in the background
    fetch(`/wp-json/wp/v2/posts/${postId}`)
        .then((response) => response.json())
        .then((data) => {
            postData[postId] = {
                title: data.title.rendered,
                // excerpt: data.excerpt.rendered,
                content: data.content.rendered,
                imgSrc: imgSrc,
            };
        });
});

viewBtn.forEach((el) => {
    el.addEventListener('click', (event) => {
        event.preventDefault(); // Prevent the default behavior of the anchor tag

        document.body.classList.add('effect');
        let postId = el.getAttribute('data-post-id');
        let imgSrc = postData[postId].imgSrc;

        lightImg.src = imgSrc;
        lightboxTitle.textContent = postData[postId].title;
        // lightboxExcerpt.innerHTML = postData[postId].excerpt;
        lightboxContent.innerHTML = postData[postId].content;
    });
});

window.addEventListener('click', (event) => {
    if (
        event.target.className == 'box-wrapper' ||
        event.target.className == 'close-btn'
    ) {
        document.body.classList.remove('effect');
    }
});

I used the chatgpt to solve the issue in which it suggested to use switch_to_blog(subsite-ID) in which the subsite ID is 3. I tried the code provided but it did not work either.

also checked the /wp-json/wp/v2/posts/${postId} in which the postId is 899.

you check it that the data is being fetched at https://www.bahai.in/hi/wp-json/wp/v2/posts/899.

but in console it shows:

{"code":"rest_post_invalid_id","message":"Invalid post ID.","data":{"status":404}}

Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'rendered')

Uncaught TypeError: Cannot read properties of undefined (reading 'imgSrc').

It will be helpful to if you can provide the learning to fix this issue.

Vue JS : Why the video created from a blob that I display on my website is not the same as the one when I download it ? (even if the URL is the same)

I created a video from an “Base64 string” images array which I display on a canvas.

const speed = ref(500);

function animVideoCreation() {
  const canvas = document.getElementById("myFinalCanvas");
  const ctx = canvas.getContext("2d");
  if (x >= size.value) {
    x = 0;
  }
  ctx.clearRect(0, 0, width.value, height.value);
  //  Give the current image to the canvas
  var img = new Image();
  var src = "data:image/png;base64," + bytesArray.value[x];
  img.src = src;
  img.addEventListener("load", () => {
    ctx.drawImage(img, 0, 0);
    x++;
    setTimeout(animVideoCreation, speed.value);
  });
}

The images are displayed well and the transition between them is perfect.
After that, I tried to record my canvas to create a video from it.

const videoDuration = ref((speed.value / 1000) * size.value);

let chunks = [];

function downloadAnimation() {
  x = 0;
  const canvas = document.getElementById("myFinalCanvas");
  let cStream = canvas.captureStream();
  let recorder = new MediaRecorder(cStream);
  recorder.start();
  recorder.ondataavailable = (e) => chunks.push(e.data);
  recorder.onstop = () => exportStream();
  setTimeout(() => {
    recorder.stop();
  }, videoDuration.value * 1000 + 500);
  console.log("oui");
}

function exportStream() {
  // combine all our chunks in one blob
  var blob = new Blob(chunks, { type: "video/mp4" });
  // do something with this blob
  var vidURL = URL.createObjectURL(blob);
  var vid = document.createElement("video");
  vid.controls = true;
  vid.src = vidURL;
  document.getElementById("app").appendChild(vid);
  let link = document.createElement("a");
  link.href = vid.src;
  link.download = "MyFlipBook";
  vid.addEventListener("loadeddata", () => {
    link.click();
  });
}

The video created with the vid variable is displayed well except when it is in full sreen mode, and the problem is the same as the one on the video downloaded with the link variable : the video flashs and looks to bug.

I tried to add a frame per second value for my recoder and nothing changed.

I hope someone will figure it out because I don’t and I’m completely blocked.

How to fetch images from Pixabay

I am trying to fetch images from pixabay and show them in my blog post using JavaScript. My code is like below.

function imageSelect_blog(evt) {
            const imageURL = event.target.getAttribute('src');           
            $('#showuploadedimage').attr('src', imageURL);

            var xhttp = new XMLHttpRequest();   
            var url = "/admin/upload_pixabay_image.php";
            var data = { url : imageURL, id: "<?php echo $_GET['id']; ?>" };
            var params = JSON.stringify(data);

            xhttp.open("POST", url, true);
            xhttp.setRequestHeader("Content-type", "application/json");

            xhttp.send(params);
            bootstrapModal.hide();
          }

But after some days images are disappeared from Server.

Why is this happening ?

is there a way to get sorted array from an array which has two-digit string numbers in js?

I need to convert an array with two-digit number strings and sort them at the end

const array = ['0', '1', '10', '11', '12-13', '2', '3', '4-5-6-7-8', '9'];

const desiredResult = ['0', '1', '2', '3', '4-5-6-7-8', '9', '10', '11', '12-13']

I used below the chatGPT solution but it gives wrong result. please help

array.sort((a, b) => {
// Parse strings to numbers if they are not two-digit numbers
a = parseInt(a, 10);
b = parseInt(b, 10);


// If both are two-digit numbers, maintain their relative order
if (a >= 10 && b >= 10) {
return 0;
}

// If 'a' is a two-digit number and 'b' is not, move 'a' to the end
if (a >= 10 && b < 10) {
return 1;
}

// If 'b' is a two-digit number and 'a' is not, move 'b' to the end
if (a < 10 && b >= 10) {
return -1;
}

// Otherwise, sort 'a' and 'b' as normal
return a - b;
});

console.log(array);  
// it is still the same and not sorted

I used nodemon to run server.js but an error occurred

enter image description here

const express=require('express');
const cors=require('cors');
const app=express();
app.use(cors());
app.all('/json-server',(request,response)=>{
    response.setHeader('Access-Control-Allow-Origin','*');
    response.setHeader('Access-Control-Allow-Headers','*');
    response.send('hello ajax');
});
app.listen(8000,function(){
    console.log("The service has been started and port 8000 is listening.");
});

I tried to check the node installation path and global variables, and also searched for answers in other forums, but I couldn’t find a solution.