MongoServerError: location object expected, location array not in correct format

I’ve built a nestjs application and in one of the schemas I defined a location field as follows:

the location field

  @Prop({ type: LocationSchema, required: isRequired, index: '2dsphere' })
  public location?: Location;

the LocationShcema

@Schema()
export class Location {
  @Prop({ type: String, required: true })
  public type = 'Point';

  @Prop({ type: [Number, Number], required: true })
  public coordinates: [number, number];
}

export const LocationSchema = SchemaFactory.createForClass(Location);

In production when requesting creation of a document it gives me this error:

MongoServerError: location object expected, location array not in correct format

I have two questions

  1. why does this error show up?
  2. why does it occur only in production?

MUI 5/6 border radius is different in default settings and when used with theme.shape.borderRadius

I am using Mui for my website and while constructing theme, I set my border radius to be

{
    palette: ...,
    shadows: ...,
    typography: ...,
    shape: {
      borderRadius: 3,
    },
  }

Now, when I import Button from MUI directly and use the buttton, it has border radius 3px checked in Chrome inspect. I have created another box using the theme.shape.borderRadius, it is more rounded having border radius: 9px.

Why is both different even though It should be referring to the same value I set in the theme.

<Button
  variant="contained"
    sx={{
     width: "100px",
     height: "36px",
     color: "black",
     backgroundColor: "white",
    }}
>
 Start now
</Button>
<Box
 sx={{
  width: "100px",
  height: "36px",
  color: "black",
  backgroundColor: "white",
  borderRadius: (theme) => theme.shape.borderRadius,

  display: "flex",
  alignItems: "center",
  justifyContent: "center",
  }}
 >
  Start now
</Box>

Settings px explicity works but that’s not what I want to do.

borderRadius: (theme) => theme.shape.borderRadius+'px'

Discord.js 14 – Bot Change “Everyone” Voice Permissions

I’ve hit a bit of a roadblock with an idea. There are no errors in the code, console wise, so I’m sure it’s just a matter of how I’m trying to do things.

The general idea is if an event is scheduled for a particular voice channel within the next 10 minutes then the channels status gets updated to reflect this. This portion doesn’t work, but isn’t a big deal.

What I do need to work and doesn’t is the “everyone” permissions for connect and speak. Currently I have them set to false so the event channel isn’t “open to the public”

In the event that an event is starting in the next 10 minutes or is currently active I’d like the connect and speak permissions for everyone to be true. This is the part that isn’t working either, but is the main purpose of this script. Again no errors in my console to go off of.

It is detecting an active event though because I have it set to set the channels status as the event name when active and this is working.

Am I doing something wrong permissions wise?

const voiceChannelId = '1284713593056661618'; // Your target voice channel ID

client.on(Events.GuildScheduledEventUpdate, async (oldEvent, newEvent) => {
    const guild = newEvent.guild;
    const voiceChannel = guild.channels.cache.get(voiceChannelId);

    if (!voiceChannel) {
        console.error(`Voice channel with ID ${voiceChannelId} not found.`);
        return;
    }

    // Ensure we only react to the relevant event with the specified channel
    if (newEvent.channelId !== voiceChannelId) return;

    // Handle 10 minutes before event start
    const now = new Date();
    const tenMinutesBeforeStart = new Date(newEvent.scheduledStartTimestamp - 10 * 60 * 1000);

    if (now >= tenMinutesBeforeStart && newEvent.status === 'SCHEDULED') {
        // Unlock the channel 10 minutes before the event starts
        await updateChannelPermissions(voiceChannel, true);
        await voiceChannel.setName('Event Starting Soon - Channel Unlocked');
    }

    // Handle when event becomes active
    if (newEvent.status === 'ACTIVE') {
        // Set channel name to event name and keep it unlocked
        await voiceChannel.setName(newEvent.name);
        await updateChannelPermissions(voiceChannel, true);
    }

    // Handle when the event is canceled or completed
    if (newEvent.status === 'COMPLETED' || newEvent.status === 'CANCELED') {
        const events = await guild.scheduledEvents.fetch();
        const activeEvents = events.filter(event => event.channelId === voiceChannelId && event.status === 'ACTIVE');

        if (activeEvents.size === 0) {
            // Lock the channel 10 minutes after the event ends if no other active events
            setTimeout(async () => {
                const currentEvents = await guild.scheduledEvents.fetch();
                const currentActiveEvents = currentEvents.filter(event => event.channelId === voiceChannelId && event.status === 'ACTIVE');
                if (currentActiveEvents.size === 0) {
                    await voiceChannel.setName('Event Ended - Channel Locking Soon');
                    await updateChannelPermissions(voiceChannel, false);
                }
            }, 10 * 60 * 1000); // 10 minutes
        }
    }
});

// Periodically check for upcoming events and handle permissions
setInterval(async () => {
    const guilds = client.guilds.cache;
    for (const guild of guilds.values()) {
        const events = await guild.scheduledEvents.fetch();
        const upcomingEvents = events.filter(event => event.channelId === voiceChannelId && event.scheduledStartTimestamp - Date.now() < 10 * 60 * 1000 && event.status === 'SCHEDULED');

        // Handle unlocking channels for any events starting in less than 10 minutes
        for (const event of upcomingEvents.values()) {
            const voiceChannel = guild.channels.cache.get(event.channelId);
            if (voiceChannel) {
                await updateChannelPermissions(voiceChannel, true);
                await voiceChannel.setName('Event Starting Soon - Channel Unlocked');
            }
        }
    }
}, 5 * 60 * 1000); // Check every 5 minutes

// Helper function to update permissions
async function updateChannelPermissions(channel, allowAccess) {
    const permissions = {
        Connect: allowAccess,
        Speak: allowAccess,
    };
    await channel.permissionOverwrites.edit(channel.guild.roles.everyone, permissions);
}

WordPress AJAX bad request 400

I’ve been trying to create an AJAX function for my custom WordPress theme. It’s supposed to fetch data of a custom post type and display it on a sidebar that pops up. I’ve separated the files; functions.php, main.js, sidebar.php. I just can’t seem to figure out why I’m getting a bad request 400 response. This is the code in the function.php

function add_scripts_styles($hook) {
        wp_enqueue_script('my_js_file', get_template_directory_uri(). '/assets/js/main.js', array('jquery'), 1);
        wp_localize_script('my_js_file', 'ajax_details', array(
            'ajax_url' => admin_url('admin.ajax.php'),
            'nonce' => wp_create_nonce('my_nonce'),
        ));
    }
    add_action("wp_enqueue_scripts","add_scripts_styles");

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

        ob_start();

        echo "Hello World";

        $out = ob_get_clean();
        $out = strtolower($out);

        var_dump($out);
    }

    add_action("wp_ajax_do_this","do_this");
    add_action("wp_ajax_nopriv_do_this","do_this");

this the code in main.js

document.addEventListener('DOMContentLoaded', () => {
    const cards = document.querySelectorAll('[id^=tagged]');
    function open(){
        document.querySelector('.sidebar').style.width = "25%";
    }

    function close(){
        document.querySelector('.sidebar').style.width = "0";
    }
    cards.forEach(card => {
        card.addEventListener('click', e => {
            open();
            var id_post = e.currentTarget.getAttribute('data-post_ID');
            console.log(id_post);

            jQuery.ajax({
                type: "post",
                url: `${window.location.origin}/wp-admin/admin-ajax.php`,
                data:{
                    action: "my_action",
                    post_id: id_post,
                },
                success: function(result) {
                    $('#pusha').html(result.data.html);
                }
            });
                        
        })
    })

    close();
})

and in sidebar.php

<?php
/*
Sidebar
*/
?>
<div class="sidebar">
  <button id="closed"><i class="fa fa-window-close" style="background-color: whitesmoke; color: black"></i></button>
  <div id="pusha">
    </div>
 <script>
  
  let cBtn =document.getElementById('closed');
  cBtn.addEventListener('click', e=> {
    document.querySelector('.sidebar').style.width = "0";
  })
 </script>
</div>

I expected to display the post data when the sidebar appears

I can’t seem to reflect my lists with my updated data whenever position is changing

I’ve been sitting with this problem for days, and I can’t quite figure out what’s wrong with my code.

My problem is that whenever my data gets re-ordered or change position, like changing the tabs position, the values don’t properly reflect. I’m so burnt out with this problem and I can’t really think straight anymore.

I regretted using index as my identifier, but in this case, which I’m really sure, doesn’t have any affect on how my data is being displayed. Please help! Thank you.

My popup.js

let data_placeholder = {};
initialize_data();

// Update the storage after the popup is closed
document.addEventListener("visibilitychange", () => {
    chrome.runtime.sendMessage({ message: "set_data", data: data_placeholder });
});

// Update data_placeholder everytime the checkbox is toggled
function update_data(checkbox, type, index, method) {
    if (checkbox.nodeName == "INPUT" && checkbox.type == "checkbox") {
        checkbox.addEventListener("change", () => {
            data_placeholder[type][index][method] = checkbox.checked;
        });
    } else {
        console.warn("This shouldn't be happening: Error(Incompatible type)");
    }
}

// Execute script
document.getElementById("execute-script").addEventListener("click", (e) => {
    chrome.runtime.sendMessage({
        message: "execute_methods",
        data: data_placeholder,
    });
});

// some code

function initialize_data() {
    chrome.runtime.sendMessage({ message: "get_data" }, (data) => {
        // Update data_placeholder with the latest data
        data_placeholder = structuredClone(data);
        console.log("Popup data: ", data_placeholder);
        if (data.extensions.length > 0) {
            let frag_ext = document.createDocumentFragment();
            data.extensions.sort((a, b) => a.ext_name.localeCompare(b.ext_name));
            data.extensions.forEach((extension, i) => {
                // Don't show self
                if (extension.ext_name == "Chroxt") {
                    return;
                }
                // Setting up the elements
                let container = document.createElement("div");
                let name = document.createElement("p");
                let reload = document.createElement("input");
                let uninstall = document.createElement("input");
                let disable = document.createElement("input");
                name.title = `Name: ${extension.ext_name}nID: ${extension.ext_id}nVersion: ${extension.version}nMatches: nt${extension.matches.join(",nt")}nPermissions: nt${extension.permissions.join(",nt")}`;
                name.textContent = extension.ext_name;

                frag_ext.appendChild(batch_append(container, [name, reload, uninstall, disable]));
                batch_set_attr([reload, uninstall, disable], "type", "checkbox");
                container.setAttribute("class", "ext-list-body");

                // Modifying the properties
                reload.checked = extension.reload;
                disable.checked = extension.disable;
                uninstall.checked = extension.uninstall;

                // Adding listeners for checkboxes
                update_data(reload, "extensions", i, "reload");
                update_data(uninstall, "extensions", i, "uninstall");
                update_data(disable, "extensions", i, "disable");

                // Stylization
                if (extension.enabled) {
                    name.style.opacity = "100%";
                } else {
                    name.style.opacity = "30%";
                }
            });
            document.getElementById("list-ext").appendChild(frag_ext);
        } else {
            // Add such empty
        }

        if (data.websites.length > 0) {
            let frag_site = document.createDocumentFragment();
            data.websites.forEach((website, i) => {
                // Setting up the elements
                let container = document.createElement("div");
                let name = document.createElement("p");
                let reload = document.createElement("input");
                name.title = `Title: ${website.site_name}nID: ${website.site_id}nURL: ${website.url}`;
                name.textContent = website.site_name;

                frag_site.appendChild(batch_append(container, [name, reload]));
                reload.type = "checkbox";
                container.setAttribute("class", "site-list-body");

                // Modifying the properties
                reload.checked = website.reload;

                // Adding listeners for checkbox
                update_data(reload, "websites", i, "reload");
            });
            document.getElementById("list-site").appendChild(frag_site);
        } else {
            // Add such empty
        }
    });
}

background.js

let storage = chrome.storage.local;

// Purpose: Get new extensions & tabs data, default if new, otherwise copy methods data from original
// Return: Return an object, not merged with old data, but with old data essential properties
// Nutshell: Returns new & updated data
function get_new_data(callback = null) {
    let data_placeholder = {
        extensions: [],
        websites: [],
        enabled: false,
        "show-popup": true,
    };
    return new Promise((resolve, reject) => {
        // Get the current strorage
        storage.get(null, (data) => {
            // Get new extensions and new extension properties
            chrome.management.getAll((extensions) => {
                extensions.sort((a, b) => a.name.localeCompare(b.name));
                extensions.forEach((ext, i) => {
                    // Since PWA is included, only allow extensions
                    if (ext.type == "extension") {
                        // Create an object inside an array of this object for every extension
                        data_placeholder.extensions[i] = {
                            // Brand new data
                            ext_name: ext.name,
                            ext_id: ext.id,
                            version: ext.version,
                            enabled: ext.enabled,
                            matches: ext.hostPermissions,
                            permissions: ext.permissions,
                            icon: ext.icons?.[0].url,

                            // Keep settings the same, if not initialized, set to default
                            reload: data.extensions?.[i]?.reload ?? false,
                            disable: data.extensions?.[i]?.disable ?? false,
                            uninstall: data.extensions?.[i]?.uninstall ?? false,
                        };
                    }
                });
                // After extension operation, get all open tabs
                chrome.tabs.query({}, (tabs) => {
                    tabs.forEach((tab, k) => {
                        // For each tab, add this object
                        data_placeholder.websites[k] = {
                            site_name: tab.title,
                            site_id: tab.id,
                            icon: tab.favIconUrl,
                            url: tab.url,

                            // Keep settings the same, if not initialized, set to default
                            reload: data.websites?.[k]?.reload ?? false,
                        };
                    });
                    // Finally, return the merged data through Promises or callback
                    if (typeof callback == "function") {
                        callback(data_placeholder);
                    } else {
                        resolve(data_placeholder);
                    }
                });
            });
        });
    });
}

chrome.runtime.onMessage.addListener((receive, _, send) => {
    switch (receive.message) {
        case "get_data":
            get_new_data().then((data) => {
                send(data);
                console.log("Background: ", data);
            });
            break;
        case "set_data":
            storage.set(receive.data);
            break;
        case "execute_methods":
            receive.data.extensions.forEach((extension) => {
                if (extension.reload) {
                    chrome.management.setEnabled(extension.ext_id, false);
                    chrome.management.setEnabled(extension.ext_id, true);
                }
                if (extension.disable) {
                    chrome.management.setEnabled(extension.ext_id, !extension.enabled);
                }
                if (extension.uninstall) {
                    chrome.management.uninstall(extension.ext_id);
                }
            });
            receive.data.websites.forEach((website) => {
                if (website.reload) {
                    chrome.tabs.reload(website.site_id);
                }
            });
            break;
        default:
            console.warn("UNHANDLED MESSAGE: ONMESSAGE");
            break;
    }
    return true;
});

I tried using ID as identifier using find(), but it produces the same result. I’m new with JS object concepts, and I’ve been trying to find a course or study materials on how to make data consistent everywhere and I couldn’t find any materials.

Laravel blade file data do not pass Vue 3

working with Laravel 10 and vue js 3 with vuex 4 in state management. I have following welcome.blade.php


    <script>
        (function () {
            window.Laravel = {
                csrfToken: '{{ csrf_token() }}',
                user: @json(Auth::user())
            };
            console.log('Laravel User:', window.Laravel.user);
        })();
    </script>
</head>
<body>


<div id="app">
             @if(Auth::check())
                <mainapp :user="{{Auth::user()}}"></mainapp>
            @else 
                <mainapp :user="false"></mainapp>
            @endif
         
</div>


    <script src="{{ mix('js/app.js') }}"></script>
</body>

and mainapp.vue file

<template>
  <div>
    
    <div v-if="$store.state.user">
      <!--========== ADMIN SIDE MENU one ========-->
      <div class="_1side_menu">
        <div class="_1side_menu_logo">
          <h3 style="text-align:center;">Logo Image</h3>
          <!--<img src="/img/logo.jpg" style="width: 108px;margin-left: 68px;"/>-->
        </div>

        <!--~~~~~~~~ MENU CONTENT ~~~~~~~~-->
        <div class="_1side_menu_content">
          <div class="_1side_menu_img_name">
            <p class="_1side_menu_name">Admin</p>
          </div>

          <!--~~~ MENU LIST ~~~~~~-->
          <div class="_1side_menu_list">
            <ul class="_1side_menu_list_ul">
              <li><router-link to="/"><Icon type="ios-speedometer" /> Dashboard</router-link></li>
              <li><router-link to="tags"><Icon type="ios-speedometer" /> Tags</router-link></li>
              <li><router-link to="category"><Icon type="ios-speedometer" /> Category</router-link></li>
              <li><router-link to="adminusers"><Icon type="ios-speedometer" /> Admin users</router-link></li>
              <li><a href="/logout"><Icon type="ios-speedometer" /> Logout</a></li>
            </ul>
          </div>
        </div>
      </div>
      <!--========== ADMIN SIDE MENU ========-->

      <!--========= HEADER ==========-->
      <div class="header">
        <div class="_2menu _box_shadow">
          <div class="_2menu_logo">
            <ul class="open_button">
              <li>
                <Icon type="ios-list" />
              </li>
            </ul>
          </div>
        </div>
      </div>
      <!--========= HEADER ==========-->
    </div>
    <router-view />
  </div>
</template>

<script>
export default {
    props: ['user'],
    data(){
       return {
          isLoggedIn : false, 
       }
    }, 
    created(){
      console.log(this.user)
       console.log('mainapp user',this.user);
        this.$store.commit('updateUser', this.user)
       
    }
}
</script>

and store.js

import { createStore } from 'vuex';

const store = createStore({
    state : {
        conuter : 1000, 
        deleteModalObj : {
            showDeleteModal: false, 
            deleteUrl : '', 
            data : null, 
            deletingIndex: -1, 
            isDeleted : false,

        }, 
        user: false, 
        
    }, 
    getters: {
        getCounter(state){
           return state.conuter
        }, 
        getDeleteModalObj(state){
            return state.deleteModalObj;
        },
       
      
        
    },

    mutations: {
        changeTheCounter(state, data){
            state.conuter += data
        }, 

        setDeleteModal(state, data){
            const deleteModalObj = {
                showDeleteModal: false, 
                deleteUrl : '', 
                data : null, 
                deletingIndex: -1, 
                isDeleted : data,
            }
            state.deleteModalObj = deleteModalObj
        },
        setDeletingModalObj(state, data){

            console.log('setDeletingModalObj mutation called');
        console.log('Data received:', JSON.parse(JSON.stringify(data))); // Convert Proxy to plain object for logging


            state.deleteModalObj = data

            console.log('Updated deleteModalObj state:', JSON.parse(JSON.stringify(state.deleteModalObj)));
        },
        // updateUser(state, data) {
        //     console.log('updateUser mutation called with data:', data); // Debugging line
        //    // state.user = data || false;
        //     state.user = data;
        //     console.log('state.user after update:', state.user); // Debugging line
        //   },
        updateUser(state, data){
            state.user = data
        },
        
        
    }, 
     actions :{
        changeCounterAction({commit}, data){
            commit('changeTheCounter', data)
        }
    }

});

export default store;

my logged user data print on Laravel blade file but not passed it to vue file and as the result of that not showing menus as well. what is the problem with not passing data with vue file

How detect was clicked Win+Shift+S (made scren) JavaScript

How can I determine that the combination “Win +Shift+ S” was pressed?
I’m trying to do so, but the screenshot window comes out faster. Does anyone know how to fix this?

KeyCode for:
Win - 91
Shift - 16
S - 83

We can’t use shiftKey and metaKey because they only fire when we release them last

Here is my code:

<script>
    const set = new Set();

    window.addEventListener('keydown', event => {
        set.add(event.keyCode)
        console.log(set)
    });

    window.addEventListener('keyup', event => {
        if (set.has(91) && set.has(16) && set.has(83)) {
            alert('made screen')
        }
        set.delete(event.keyCode);
        console.log(set)
    });
</script>

“How to implement a dynamic subtask input field with icons that change and subtasks list below?”

I’m trying to implement a dynamic subtask feature similar to what I’ve attached in the images below. Here’s what I’m aiming for:

The input field has a + icon by default.
When the user starts typing in the input field, the + icon should change to X (cancel) and ✓ (confirm) buttons.
When the user confirms (✓), the entered text should be added as a subtask below the input field.
There should be options to edit and delete each added subtask.
I’ve attached screenshots for reference:

The initial state has a + icon next to the input field.
After typing, the input should change to show an X and ✓ to either confirm or cancel the action.
Added subtasks appear below, with each one having a pencil (edit) and trash can (delete) icon.

[enter image description here](https://i.sstatic.net/pkYpJUfg.png)

How to handle external dependencies like Moment.js in unit tests for stub implementation?

I am currently learning unit testing in JavaScript, particularly focusing on stubs, from “The Art of Unit Testing”. The author talks about making code more testable by removing dependencies, but I’m confused about how to apply this concept when using stubs with external dependencies like moment().

Here’s my situation: I have a password verification function that throws an error if it’s called on a weekend. There is also a wrapper function, verifyPasswordForCurrentDay, which uses moment().day() to get the current day of the week:

const SUNDAY = 0, SATURDAY = 6;

const verifyPassword = (input, rules, currentDay) => {
  if ([SATURDAY, SUNDAY].includes(currentDay)) {
    throw new Error("It's the weekend!");
  }
  // more code here...
  return [];
};

const verifyPasswordForCurrentDay = (input, rules) => {
  const currentDay = moment().day();
  return verifyPassword(input, rules, currentDay);
};

I’ve been able to test the verifyPassword function using a stub, passing the day of the week as a parameter. Here’s the test:

describe("verifier", () => {
  test("on weekends, throws exceptions", () => {
    expect(() => verifyPassword("any input", [], SUNDAY)).toThrow(
      "It's the weekend!"
    );
  });
});

However, I’m having trouble testing verifyPasswordForCurrentDay, as it has a dependency on moment().day(). In The Art of Unit Testing, the author suggests removing dependencies to make code testable.

I’m also concerned that we’ve merely moved the problem up one level. verifyPasswordForCurrentDay still has an external dependency (moment), making it difficult to test. By using parameter injection, we make a testable function (verifyPassword), but we’re only moving the problem up a level, meaning the wrapper function (verifyPasswordForCurrentDay) becomes untestable or harder to test. Is this correct?

Exceution of simple Javascript in Rails app doesn’t work

I am new to this topic and online resources didnt help. I am trying to set up a simple button which onClick executes something in JavaScript. I wanted to implement on the front-end to add html to the DOM. It seems I am doing something wrong with regards to referencing the programmed JS Code.

  1. I modified my application.js to add require("./invoices/invoice_positions"):

    // present in this directory. You're encouraged to place your actual application logic in
    // a relevant structure within app/javascript and only use these pack files to reference
    // that code so it'll be compiled.
    
    require("@rails/ujs").start()
    require("turbolinks").start()
    require("@rails/activestorage").start()
    require("popper.js")
    require("bootstrap")
    require("jquery")
    require("inputmask")
    require("channels")
    require('./nested_forms/addFields')
    require('./nested_forms/removeFields')
    
    require("./invoices/form")
    require("./invoices/select")
    require("./payments/form")
    require("./header_menu")
    require("./invoices/invoice_positions")
    // Uncomment to copy all static images under ../images to the output folder and reference
    // them with the image_pack_tag helper in views (e.g <%= image_pack_tag 'rails.png' %>)
    // or the `imagePath` JavaScript helper below.
    //
    // const images = require.context('../images', true)
    // const imagePath = (name) => images(name, true)
    
    
  2. I added the function under app/javascript/invoices/invoice_positions.js with some dummy code:

function increaseInvoicePositions() {window.alert("BAM");}
  1. I added this to my view because of some online help:
<%= content_for :head do %>
  <%= javascript_include_tag "/invoices/invoice_positions" %>
<% end %>
  1. I added this button to the view:
<%= button_tag t('invoice_positions.increase'), type: "button", onclick: "increaseInvoicePositions()", class: "btn btn-secondary" %>

Result

In theory after reloading the page I assume it works but it fails with a browser error in Chrome. I restarted the server but it didnt help. What am I missing?
JS Error

Cookies can only be modified in a Server Action or Route Handler

In the backend, I send the access token and refresh token in the response by jwt, and in the nextjs 14 app router, I save them in the cookie after the user login.
Now, the problem I have is when the user’s access token expires, I generate a new token for him by refreshing the token, but I encounter the same error.

this is my refreshAccessToken function for get a new access toke:

    'use server'


import {cookies} from "next/headers";
import {isTokenExpiringSoon} from "@/app/utils/utils";
import {modifiedCookie} from "@/app/_actions/modifiedCookie";


export async function refreshAccessToken(refreshToken) {
    console.log("Attempting to refresh access token...");

    if (!refreshToken) {
        console.error('Refresh token not found');
        throw new Error('Refresh token not found');
    }

    const refreshResponse = await fetch(`http://localhost:8000/api/token/refresh/`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify({
            refresh: refreshToken,
        }),
    });

    if (!refreshResponse.ok) {
        console.error('Failed to refresh token:', refreshResponse.statusText);
        throw new Error('Failed to refresh token');
    }
    console.log('working on it')

    const data = await refreshResponse.json();
    const newAccessToken = data.access;
    console.log(`newAccessToken in refresh: ${newAccessToken}`)

    modifiedCookie(newAccessToken)

    console.log("New access token set:", newAccessToken);
    return newAccessToken;
}

and this is my fetchUserData function for get user data:

    export async function fetchUserData() {
    const cookieStore = cookies();
    const accessToken = cookieStore.get('access_token')?.value;

    console.log("Current access token in fetch:", accessToken);

    if (isTokenExpiringSoon(accessToken)) {
        console.log("Access token is expiring soon, refreshing...");
        try {
            const refreshToken = cookieStore.get('refresh_token')?.value;
            console.log("Refresh Token:", refreshToken);
            await refreshAccessToken(refreshToken);
        } catch (error) {
            console.error('Error refreshing access token:', error);
            throw new Error('Unable to refresh access token');
        }
    }

    const newAccessToken = cookieStore.get('access_token')?.value;
    console.log("New access token to use:", newAccessToken);

    const response = await fetch(`http://localhost:8000/api/user/user-profile/`, {
        method: 'GET',
        headers: {
            'Authorization': `Bearer ${newAccessToken}`,
            'Content-Type': 'application/json',
        },
    });

    if (!response.ok) {
        console.error('Failed to fetch user profile:', response.statusText);
        throw new Error('Failed to fetch user profile');
    }

    const user = await response.json();
    console.log("Fetched user data:", user);
    return user;
}

After this i get this error:

Current access token in fetch: ey…
Access token is expiring soon, refreshing…
Refresh Token: ey…
Attempting to refresh access token…
working on it
newAccessToken in refresh: ey…
New access token set: ey…
New access token to use: ey…
tA [Error]: Cookies can only be modified in a Server Action or Route Handler. Read more: https://nextjs.org/docs/app/api-reference/functions/cookies#cookiessetname-value-options
at Proxy.callable (/home/comiser/Desktop/tasteproject/frontend/tastecoffee/node_modules/next/dist/compiled/next-server/app-page.runtime.dev.js:36:13455)
at modifiedCookie (webpack-internal:///(rsc)/./app/_actions/modifiedCookie.js:14:61)
at refreshAccessToken (webpack-internal:///(rsc)/./app/_actions/actions.js:41:80)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async fetchUserData (webpack-internal:///(rsc)/./app/_actions/actions.js:54:13)
at async RootLayout (webpack-internal:///(rsc)/./app/layout.js:38:16)
Failed to fetch user profile: Unauthorized
Error fetching user profile: Failed to fetch user profile

Supabase is not redirecting to my desired url with google oauth

I am using Supabase for my authentication. With Google OAuth, instead of redirecting to http://localhost:5000/dashboard, it redirects to http://localhost:5000/. How can I fix this?

In the Supabase authentication settings I have set the Site URL as http://localhost:5000/dashboard and have also added it as a redirect URL. In my Google Cloud console, I have set http://localhost:5000/dashboard as an authorised redirect URI and authorised JavaScript origin.

This is my client side code when the user clicks the ‘Sign up with Google’ button:

const { data, error } = await supabase.auth.signInWithOAuth({
    provider: 'google',
    options: {
        redirectTo: '/dashboard'
    }
});

Audio to Video Conversion using FFmpeg in React

Upon running my code, the audio successfully gets converted into a video and saved in the bucket, however, the video size is just 9 bytes.

Here’s my utility.

import { FFmpeg } from '@ffmpeg/ffmpeg';
import { fetchFile } from '@ffmpeg/util';
import { ref, uploadBytes, getDownloadURL } from 'firebase/storage';
import { storage } from '../firebase'; 

export async function generateAndStoreVideo(audioPath, imagePath, userId) {
  try {
    const ffmpeg = new FFmpeg({ log: true });
    await ffmpeg.load();

    console.log('Fetching audio and image...');
    ffmpeg.writeFile( 'input.mp3', await fetchFile(audioPath));
    ffmpeg.writeFile('input.jpg', await fetchFile(imagePath));
    
    console.log('Running FFmpeg...');
    await ffmpeg.exec(['-i', 'sound.mp3', '-i', 'image.png', 'output.mp4']
    );

    console.log('FFmpeg completed!');
    
    const data = ffmpeg.readFile( 'output.mp4');
    const videoBlob = new Blob([data.buffer], { type: 'video/mp4' });

    console.log('Uploading video to Firebase...');
    const videoRef = ref(storage, `videos/${userId}/${Date.now()}_generated_video.mp4`);
    const uploadSnapshot = await uploadBytes(videoRef, videoBlob);

    const videoURL = await getDownloadURL(uploadSnapshot.ref);

    console.log('Video uploaded successfully! URL:', videoURL);

    return videoURL;
  } catch (error) {
    console.error('Error generating or uploading video:', error);
    throw new Error('Video generation or upload failed.');
  }
}

After uploading, I also got this error:

ErrnoError: FS error
    at handleError (http://localhost:3000/static/js/bundle.js:98427:58)
    at http://localhost:3000/static/js/bundle.js:98450:7

I’ve made sure I’m using the new FFMPEG version and syntax, but the issues persist.

I need to know how to return the numbers assciated with the attached code line

I use this code to create a list of clickable img ids

$('.cycler').each(function() {
  var container = $(this);
  container.append('<div class="cycler_controls"><a href="#" id="pause_resume" class="active">pause</a>');
  for (var j = first_pic; j < last_pic;) {
    if (j < 10) {
      container.find('.cycler_controls').append('<a class="page" href="#" rel="' + '0' + j + '">' + ('0' + j) + '</a>');
    } else {
      container.find('.cycler_controls').append('<a class="page" href="#" rel="' + j + '">' + (j + 1) + '</a>');
    }
    j++
  }

I want to highlight the id associated with each image as the slide show proceeds but don’t know how to extract the relevant number or what code I need to use to cvhange each background as the slide show progresses

The show is driven by :

function cycleImages(container) {
  var $active = container.find('img.active');
  var $next = ($active.next('img').length > 0) ? $active.next('img') : container.find('img:first');
  $next.css('z-index', 2); //move the next image up the pile
  $active.fadeOut(1500, function() { //fade out the top image
    $active.css('z-index', 1).show().removeClass('active'); //reset the z-index and unhide the image
    $next.css('z-index', 3).addClass('active'); //make the next image the top one
  });
  var timer = setTimeout(function() {
    cycleImages(container)
  }, 3000);
  container.data('timer', timer);
}

I think I need code with the above function the sets the relevant cycler_control rel or attr appropriately.

I should add that whilst pretty experience in javascript I am not yet fluent in JQuery!

To see the background of the id nbumber change as the slides do

My texture is not rendering properly in WebGL

So I was trying to make a render function and I ran into a problem that I have been pulling my hair out over trying to find the source of. The DrawElements function doesn’t execute yet when I try to use it neither does the texturebind function. However,no other error and error checks pop up.The texture loads correctly and stuff.In the main.js,the mainmenu texture loads correctly but when it goes into the Gilgamesh rendering one,not even the background is drawn it’s pure white.All of the console.log checks are passed too.
The Texturebind function is:

        gl.activeTexture(WhichTextureunit);
        gl.bindTexture(gl.TEXTURE_2D, texture);
        var uSampler = gl.getUniformLocation(shaderProgram, usamplerString);
        if(uSampler === null){
            console.log("uSampler not found");
            throw new Error("USampler not found");
        }
        gl.uniform1i(uSampler, Textureunitinint);
    };

The Render function:

Gilgamesh.prototype.RenderPick = function (sprite, texturemanager, gl) {
        if(sprite === "Stand"){
                if(gl.useProgram(shaderProgram) === null){
                    console.log("Hawk Tuah");
                    throw new Error("shader program not able to use");
                }
                if(texturemanager.texturebind(gl, Gilgameshrightneutralhead, shaderProgram, "Textures1", gl.TEXTURE1, 1)){
                    console.log("Bind?");
                }
                this.Imageselect = 0;
                gl.uniform2f(DieOffset, this.Headoffset[0], this.Headoffset[1]);
                gl.uniform1i(Imageselectuniformlocation, this.Imageselect);
                gl.activeTexture(gl.TEXTURE1);
                console.log("Texture:", Gilgameshrightneutralhead);
                gl.bindTexture(gl.TEXTURE_2D, Gilgameshrightneutralhead);
                if (gl.getError() !== gl.NO_ERROR) {
                    console.error("WebGL Error occurred");
                }
                gl.drawElements(gl.TRIANGLES, this.Indices.length, gl.UNSIGNED_SHORT, 0);
        }
    };

The main.js rendering part:

if (Mainmenu === true) { //replace that with real domain when real domain exists
    var MainmenuTexture = textureManager.TextureLoad(gl, "https://localhost:8080/textures/Main menu map.png", 0, 441, 361, function () {
        gl.useProgram(shaderProgram);
        gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
        textureManager.initTextureBuffer2DVec2(gl, ZOTZTThimagevertices, shaderProgram, "a_texcoord");
        textureManager.texturebind(gl, MainmenuTexture, shaderProgram, "u_texture", gl.TEXTURE0,0);
        var TransformMatrix = gl.getUniformLocation(shaderProgram, "transform");
        var scaleMatrix = [2.0, 0, 0, 0, 0, 2.0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
        gl.uniformMatrix4fv(TransformMatrix, false, scaleMatrix);
        // Step 5: Get the location of the `coordinates` attribute of the vertex shader
        var coordinates = gl.getAttribLocation(shaderProgram, "coordinates");
        gl.vertexAttribPointer(coordinates, 2, gl.FLOAT, false, 8, 0);
        var DieOffset = gl.getUniformLocation(shaderProgram, "Offset");
        gl.uniform2f(DieOffset, Offsett[0], Offsett[1]);
        gl.enableVertexAttribArray(coordinates);
        gl.useProgram(shaderProgram);
            gl.viewport(0, 0, canvas.width, canvas.height);
            gl.clearColor(0.0, 0.5, 0.5, 1.0);
            console.log("down in the west texas town of El Paso");
            gl.enable(gl.DEPTH_TEST);
            if (gl.clear(gl.COLOR_BUFFER_BIT) === null)
                throw new Error("uncleared");
            console.log("I fell in love with a Mexican girl");
            gl.activeTexture(gl.TEXTURE0);
            console.log("Running and shooting");
            gl.bindTexture(gl.TEXTURE_2D, MainmenuTexture);
            console.log("Fenina has found me");

            if(gl.drawElements(gl.TRIANGLES, ZOTZTThindices.length, gl.UNSIGNED_SHORT, 0)){
                console.log("jdjdosj");
            }
        console.log("before gilgamesh");
        var gilgamesh = new Gilgamesh(gl, textureManager, ()=> {
            gilgamesh.RenderPick("Stand", textureManager, gl);
            console.log("Dhfioa");
        },shaders);
    });
}