Discord Bot – DirectMessage Command

I’m coding a discord bot in JavaScript.
I try to make commandss that work in Direct Message but when I execute commands in Direct Message, the bot does not respond (as if it does not detect messages sent in DM). Which blocks the progress of the script.

I set the intents when the bot starts.

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,
        GatewayIntentBits.DirectMessages
    ]
});

I tried the “if (message.channel.type === ‘DM’)”

client.on('messageCreate', async message => {
    if (message.channel.type === 'DM' && message.content === '-hi') {
        try {
            await message.channel.send(':white_check_mark: | You have enabled the `-hi` command in server mode.');
        } catch (error) {
            console.error('error :', error);
        }
    }
});

I also tried “if (!message.guild)”

client.on('messageCreate', async message => {
    if (!message.guild && message.content === '-hi') {
        try {
            const user = message.author;
            await user.send(':white_check_mark: | You have enabled the `-hi` command in server mode.');
        } catch (error) {
            console.error('error :', error);
        }
    }
});

How to implement unique codes/ids to allow for remote participants?

I am currently working on a website that researchers at universities can use to set up and run participant-based studies. The current MVP is out, however I have noticed a big flaw in how the website is set up, and I am unsure how to solve it to fit my users’ needs.

Currently the website is set up as follows:

  1. Someone who wants to do a research study can make an account and setup a study. Their study’s information is stored in the MySQL database tied to their research project id and that project id is associated with their account id.

  2. When the researcher is ready to do their study, they can sign into the website (this grabs their study information) and go to the “start splash screen” which is meant for participants. Then, they can bring in participants into their lab/classroom/etc. and sit them down at the computer. The participant goes through the study that the researcher sets up.

  3. When they are done and click submit, the participant’s information is stored on the database yet again tied to the research project id. The backend knows what the research project id is because the browser is logged in to the researcher’s account.

This method works great for those doing in-person, in-lab studies where they can control the laptop the participant uses, etc. However, I’ve gotten feedback about how researchers want to be able to send out links to participants so that they can complete the study on their own. Due to the way the backend is set up, I am not sure how to modify the website to allow this.

Ideally, I would have a separate webpage for participants to be directed to and they would put in some sort of unique ID/code that would link them to the correct study. That special code would have to pull the correct study information from the database for the participant to see, and then submit the participant’s answers to the database under the correct research project.

My question is how would you go about this change? How would you generate unique ids that would allow specific study information to be pulled from the database while also keeping in mind security? I think it would be best to have a one-time use code so random people cannot get ahold of a code and use it multiple times.

I might also be thinking of this completely wrong. Any advice, technologies, or solutions you may have would be amazing. Please let me know if I need to provide any more context! Thank you!

P.S I am using vanilla HTML, CSS, JS (Knockout) for frontend. Node/Express js, MySQL for backend.

Errors in Setting JavaScript Cookies

I am placing a cookie to stop showing an offensive jokes warning alert if someone has already seen it but Adobe Brackets is showing 51 problems and 1 error and my JavaScript is not up to scratch. Don’t worry the cookie will not be used in identifying users and I have a cookie policy showing.

code below is there any way I can clear the error and problems. I have placed 100% of the code and the errors Brackets had identified following this.

Error is ESLint terminated with error:timeout

function writeCookie(name, value, hours) 
{}
function readCookie(name)
{}
function alert1()
{}

function writeCookie(name, value, hours)
{
    var expire = ""; 
    if(hours != null)
    {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expire;
}

function readCookie(name)
{
    var cookieValue,offset = "";
    var search = name + "=";
    if(document.cookie.length > 0)
    { 
        offset = document.cookie.indexOf(search);
        if (offset != -1)
        {
            offset += search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) end = document.cookie.length;
            cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
}

function alert1()
{
    var seen = readCookie("viewed"); 
    if(seen !== "yes") 
    { 
        if(confirm("***WARNING*** n Some of these jokes MAY be offensive. n  n If you do not wish to be offended n Please Press Cancel to return n Please note this will place a cookie on your computer"))
        {
            writeCookie("viewed", "yes", 9999); 
        }
        else 
        {
            window.location="index.htm" 
        }
    }
}

Problems as per brackets

1
Unexpected ‘(space)’. function writeCookie(name, value, hours)
2
Expected exactly one space between ‘)’ and ‘{‘. {}
2
Expected ‘{‘ at column 5, not column 1. {}
2
Missing ‘use strict’ statement. {}
4
Expected exactly one space between ‘)’ and ‘{‘. {}
4
Expected ‘{‘ at column 5, not column 1. {}
4
Missing ‘use strict’ statement. {}
6
Expected exactly one space between ‘)’ and ‘{‘. {}
6
Expected ‘{‘ at column 5, not column 1. {}
6
Missing ‘use strict’ statement. {}
9
Expected exactly one space between ‘)’ and ‘{‘. {
9
Expected ‘{‘ at column 5, not column 1. {
10
Missing ‘use strict’ statement. var expire = “”;
10
Expected ‘var’ at column 9, not column 5. var expire = “”;
10
Unexpected ‘(space)’. var expire = “”;
11
Expected ‘if’ at column 9, not column 5. if(hours != null)
11
Expected exactly one space between ‘if’ and ‘(‘. if(hours != null)
11
Expected ‘!==’ and instead saw ‘!=’. if(hours != null)
12
Expected exactly one space between ‘)’ and ‘{‘. {
12
Expected ‘{‘ at column 13, not column 5. {
13
Expected ‘expire’ at column 17, not column 9. expire = new Date((new Date()).getTime() + hours * 3600000);
14
Expected ‘expire’ at column 17, not column 9. expire = “; expires=” + expire.toGMTString();
15
Expected ‘}’ at column 13, not column 5. }
16
Expected ‘document’ at column 9, not column 5. document.cookie = name + “=” + escape(value) + expire;
16
‘escape’ was used before it was defined. document.cookie = name + “=” + escape(value) + expire;
17
Expected ‘}’ at column 5, not column 1. }
20
Expected exactly one space between ‘)’ and ‘{‘. {
20
Expected ‘{‘ at column 5, not column 1. {
21
Missing ‘use strict’ statement. var cookieValue,offset = “”;
21
Expected ‘var’ at column 9, not column 5. var cookieValue,offset = “”;
21
Missing space between ‘,’ and ‘offset’. var cookieValue,offset = “”;
21
Missing space between ‘,’ and ‘offset’. var cookieValue,offset = “”;
22
Expected ‘var’ at column 9, not column 5. var search = name + “=”;
22
Combine this with the previous ‘var’ statement. var search = name + “=”;
23
Expected ‘if’ at column 9, not column 5. if(document.cookie.length > 0)
23
Expected exactly one space between ‘if’ and ‘(‘. if(document.cookie.length > 0)
24
Expected exactly one space between ‘)’ and ‘{‘. {
24
Expected ‘{‘ at column 13, not column 5. {
24
Unexpected ‘(space)’. {
25
Expected ‘offset’ at column 17, not column 9. offset = document.cookie.indexOf(search);
26
Expected ‘if’ at column 17, not column 9. if (offset != -1)
26
Expected ‘!==’ and instead saw ‘!=’. if (offset != -1)
27
Expected exactly one space between ‘)’ and ‘{‘. {
27
Expected ‘{‘ at column 21, not column 9. {
28
Expected ‘offset’ at column 25, not column 13. offset += search.length;
29
Expected ‘end’ at column 25, not column 13. end = document.cookie.indexOf(“;”, offset);
29
‘end’ was used before it was defined. end = document.cookie.indexOf(“;”, offset);
30
Expected ‘if’ at column 25, not column 13. if (end == -1) end = document.cookie.length;
30
Expected ‘===’ and instead saw ‘==’. if (end == -1) end = document.cookie.length;
30
Expected ‘{‘ and instead saw ‘end’. if (end == -1) end = document.cookie.length;
30
Too many errors. (57% scanned). if (end == -1) end = document.cookie.length;

how to extend my web application using plugins that I can load dynamically

I was wondering how do websites have a plugin system where they can extend the functionality of their website. if I have a manifest file containing the entry points for the plugin such as the main.js and main.html and so forth, how can I inject the ui in my web app as well as how to communicate between the host and the plugin using events and states, essentially making the plugin context aware. it would be ideal if you could provide concrete examples on how to do it, preferably in react.js and node.js.

Deploying a react app using react router on GH pages

I’m trying to deploy a react made website on GH pages. I know GH pages doesnt natively support multiple pages websites but i wanted to do it anyway (silly me)

I tried multiple solutions but none of them seems to work. I tried using HashRouter, i tried tweaking the 404.html page following this guide. I believe i have tried everything but nothing works.

This is my code:

App.jsx

import { HashRouter as Router, Routes, Route } from 'react-router-dom';
...
...
...
return (
    <>
      <Router>
        { windowWidth > 768 ? null : <Header /> } {/* Render Navbar if window width is greater than 768 */ }
        <Navbar />
        <Routes>
          <Route path="/" element={ <Home /> } />
          <Route path="/about" element={ <About /> } />
          <Route path="/projects" element={ <Projects /> } />
          <Route path="/skills" element={ <Skills /> } />
          <Route path="/contact" element={ <Contact /> } />
          <Route path="/details/:id" element={ <Details /> } /> {/* Route for Details */ }
        </Routes>
        { windowWidth > 768 ? <Footer /> : null }
      </Router>
    </>
  );

main.jsx

import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'
import { HashRouter } from 'react-router-dom'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <HashRouter>
      <App />
    </HashRouter>
  </React.StrictMode>
)

package.json

{
  "homepage": "https://orlifera.github.io/port/#",
  "name": "portfolio",
  "private": true,
  "version": "0.0.0",
  "type": "module",
  "scripts": {
    "predeploy": "npm run build",
    "deploy": "gh-pages -d build",
    "dev": "vite",
    "build": "vite build --outDir=build",
    "lint": "eslint . --ext js,jsx --report-unused-disable-directives --max-warnings 0",
    "preview": "vite preview"
  },
  "dependencies": {
    "@emailjs/browser": "^4.3.3",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.22.3",
    "react-simple-typewriter": "^5.0.1"
  },
  "devDependencies": {
    "@types/react": "^18.2.64",
    "@types/react-dom": "^18.2.21",
    "@vitejs/plugin-react": "^4.2.1",
    "eslint": "^8.57.0",
    "eslint-plugin-react": "^7.34.0",
    "eslint-plugin-react-hooks": "^4.6.0",
    "eslint-plugin-react-refresh": "^0.4.5",
    "gh-pages": "^6.1.1",
    "querystring": "^0.2.1",
    "react-icons": "^5.0.1",
    "vite": "^5.1.6"
  }
}

automatic commenting for users on the home page of Twitter

this is my code for automatic commenting for users on the home page of Twitter. The code clicks on the comments, but does not leave the desired comment.I want to set up a code to send a message to users with a 20 second break.

// Function to click the reply button on a tweet
function clickReplyButton(tweet) {
    const replyButton = tweet.querySelector('div[data-testid="reply"]');
    if (replyButton) {
        replyButton.click();
    }
}

// Function to type a comment and submit
async function typeComment(commentText) {
    const commentBox = document.querySelector('div[data-testid="tweetTextArea_0"]');
    if (commentBox) {
        commentBox.focus();
        document.execCommand('insertText', false, commentText);

        // Wait for the comment to be typed
        await new Promise(resolve => setTimeout(resolve, 500));

        const tweetButton = document.querySelector('div[data-testid="tweetButton"]');
        if (tweetButton) {
            tweetButton.click();
        }
    }
}

// Function to comment on timeline tweets
async function commentOnTimeline() {
    const tweets = document.querySelectorAll('article[data-testid="tweet"]');

    for (const tweet of tweets) {
        clickReplyButton(tweet);

        // Wait for the reply box to appear
        await new Promise(resolve => setTimeout(resolve, 1000));

        typeComment('Hello');

        // Wait for the comment to be posted
        await new Promise(resolve => setTimeout(resolve, 2000));
    }
}

// Run the bot
commentOnTimeline()

How can I optimize creating an xlsx file?

I have created an API that reads a file we recieve and then gives me back the information I need. I now need to create a new .xlsx file with this new data I have recieved.

Currently it’s working, but it is really not optimized. Creating a file with 4000 lines pretty much instant, but we will need to create files with up to hundreds of thousands of lines. At the moment, creating a file with 140,000 lines took 14 minutes.

I am not very experienced in algoritm optimization so i’m not sure where look for optimizing.

This is a project written with a Django backend. Here is the views.py function

def vannmiljo(request):
    survey_id = request.GET.get('surveyID', None)
    if not survey_id:
        return JsonResponse({'error': 'SurveyID parameter is missing'}, status=400)
    
    instanceID = request.GET.get('m_instanceID', None)
    if not instanceID:
        error = "No datafile"
        return JsonResponse({'error': error}, status=400)
    
    instance = SurveyInstance.objects.get(id=instanceID)
    if not instance.survey_file:
        error = "No datafile"
        return JsonResponse({'error': error}, status=400)
    else:
        excel_file_url = instance.get_survey_file_url

    response = requests.get(excel_file_url) 
    if not response.status_code == 200:
        print(f'Failed to download Excel file: {response.status_code}')
    excel_data = BytesIO(response.content)

    try:
        dfs = pd.read_excel(excel_data, engine="openpyxl")

        start_row = dfs[dfs.eq('Sal.').any(axis=1)].index[0]
        dfs = dfs.iloc[start_row:]

        dfs.reset_index(drop=True, inplace=True)

        dfs.columns = dfs.iloc[0]
        dfs = dfs[1:]

        data_list = []
        columns_to_keep = [col for col in ["Sal.", "Cond.", "Temp", "Ox %", "mg/l", "T (FTU)", "Density", "S. vel.", "Depth(dp)", "Date", "Time"] if col in dfs.columns]

        # Create a new DataFrame with only the necessary columns
        filtered_dfs = dfs[columns_to_keep].copy()

        # Rename the columns to the desired names
        column_renames = {
            "Sal.": "sal", 
            "Cond.": "cond", 
            "Temp": "temp", 
            "Ox %": "ox", 
            "mg/l": "mg_l", 
            "T (FTU)": "t_ftu", 
            "Density": "density", 
            "S. vel.": "s_vel", 
            "Depth(dp)": "depth", 
            "Date": "date", 
            "Time": "time"
        }
        filtered_dfs.rename(columns=column_renames, inplace=True)

        # Convert DataFrame to a list of dictionaries (if needed)
        data_list = filtered_dfs.to_dict('records')

        survey_instance = get_object_or_404(Survey, SurveyID=survey_id)
        survey_details = survey_instance.addInfoID_fk
        approver = survey_details.get_approver
        approver_organization = approver.organisation
        approver_org_name = approver_organization.org_name if approver_organization else None 
        oppdragsgiver = approver_org_name
        oppdragstaker = approver_org_name
        data = {
            'oppdragsgiver': oppdragsgiver,
            'oppdragstaker': oppdragstaker,
            'surveyID': survey_id,
            'data_list': data_list,
        }
        print(data)
    except Exception as e:
        # Catch any exception and return a response indicating the issue
        return HttpResponse(f"Error: {str(e)}", status=500)



    def stream_data():
        yield '{'
        yield f'"oppdragsgiver": "{data["oppdragsgiver"]}",'
        yield f'"oppdragstaker": "{data["oppdragstaker"]}",'
        yield f'"surveyID": "{data["surveyID"]}",'
        yield '"data_list": ['
        first = True
        for item in data['data_list']:
            # Convert datetime and time objects to strings
            for key, value in item.items():
                if isinstance(value, (datetime.datetime, datetime.time)):
                    item[key] = value.isoformat()
            # Add a comma before each item except the first one
            if first:
                first = False
            else:
                yield ','
            yield json.dumps(item)
        yield ']}'


    response = StreamingHttpResponse(stream_data(), content_type='application/json')
    
    return response

Here is the frontend JS code

function createDataToSend(data, oppdragsgiver, oppdragstaker) {
    const parameter_mapping = {
        'cond': 'KOND',
        'density': 'DENS',
        's_vel': 'SOUNDVEL',
        'sal': 'SALIN',
        't_ftu': 'TURB',
        'temp': 'TEMP',
        'ox': 'O2',
        'mg_l': 'MGL'

    };

    const enhet_id_mapping = {
        'cond': 'ms/m',
        'density': 'density',
        's_vel': 'm/s',
        'sal': 'ppt',
        't_ftu': 'FNU',
        'temp': '°C',
        'ox': 'mg/l',
        'mg_l': 'mg/l'
    };

    const dataToSend = [];
    if(data !== undefined){
        data.forEach(item => {
            const parameters = ['cond', 'density', 's_vel', 'sal', 't_ftu', 'temp', 'ox', 'mg_l'];
            parameters.forEach(parameter => {
                if (item[parameter] !== undefined) {
                    const obj = {
                        "Vannlok_kode": "001",
                        "Aktivitet_id": "A123",
                        "Oppdragsgiver": oppdragsgiver,
                        "Oppdragstaker": oppdragstaker,
                        "Medium_id": "Saltvann",
                        "Parameter_id": parameter_mapping[parameter],
                        "Provetakingsmetode_id": "Method1",
                        "Filtrert_Prove": "False",
                        "UnntasKlassifisering" : "", 
                        "Analysemetode_id": "Analysis1",
                        "Operator": "=",
                        "Verdi": item[parameter].toString(),
                        "Enhet_id": enhet_id_mapping[parameter],
                        "Provenr": "",
                        "Tid_provetak": new Date(item.date).toISOString().split('T')[0] + ' ' + item.time,
                        "Ovre_dyp": item.depth.toString(),
                        "Nedre_dyp": item.depth.toString(),
                        "Dybdeenhet": "m",
                        "Ant_verdier": "",
                        "Kommentar": "",
                        "Deteksjonsgrense": "",
                        "Kvantifiseringsgrense": "",
                        "ID_lokal" : "",
                    };
                    dataToSend.push(obj);
                }
            });
        });
    }

    dataToSend.sort((a, b) => {
        if (a.Parameter_id < b.Parameter_id) {
            return -1;
        }
        if (a.Parameter_id > b.Parameter_id) {
            return 1;
        }
        return 0;
    });

    return dataToSend;
}


document.addEventListener('DOMContentLoaded', function() {
    document.querySelectorAll('.downloadBtn').forEach(button => {
        button.addEventListener('click', function() {
            const surveyID = this.getAttribute('data-survey-id');
            const instanceID = this.getAttribute('data-instance-id');
            console.log('Clicked surveyID:', surveyID, 'instanceID:', instanceID);

            fetch(`/surveys/survey/vannmiljo/?surveyID=${surveyID}&m_instanceID=${instanceID}`)
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.text();
            })
            .then(text => {
                const data = text.split('n').filter(line => line).map(JSON.parse);
                return data;  
            })
            .then(data => {
                const dataObject = data[0]; 
                const oppdragsgiver = dataObject.oppdragsgiver; 
                const oppdragstaker = dataObject.oppdragstaker; 
                console.log('Oppdragsgiver:', oppdragsgiver, 'Oppdragstaker:', oppdragstaker);
            
                if (!Array.isArray(dataObject.data_list)) { 
                    console.error('data.data_list is not an array');
                    return;
                }
            
                const dataToSend = createDataToSend(dataObject.data_list, oppdragsgiver, oppdragstaker); // Modify this line
                
                
                if (dataObject.data_list && dataObject.data_list.length > 0) {

                    if (Array.isArray(dataToSend) && dataToSend.length > 0) {
                        fetch('http://localhost:3000/api/generate-excel', {
                            method: 'POST',
                            headers: {
                                'Content-Type': 'application/json',
                            },
                            body: JSON.stringify({ data: dataToSend }),
                        })
                        .then(response => response.blob())
                        .then(blob => {
                            const url = window.URL.createObjectURL(blob);
                            const a = document.createElement('a');
                            a.href = url;
                            a.download = "survey_data.xlsx"; 
                            document.body.appendChild(a);
                            a.click();
                            window.URL.revokeObjectURL(url);
                        })
                    } else {
                        console.log('No data to send 1');
                    }
                } else {
                    console.log('No data to send 2');
                }
            });
        });
    });
});


As it seems this function’s runtime is performing badly, there must be something I can improve.

My server side is not working for mobile device why? [closed]

this is the rendered link : https://google-keeps-delta.vercel.app/
this is github link :https://github.com/Dhanushbd03/Google-Keeps

as my problem is while the list is added it is not sent to the db in mobile device only ,it works fine in laptop ,also checked in incognito mode

in mobile device on refresh all the todo’s vanish bcs it is not stored to the db
and while editted todo eill also not be sent to the db ,please help I am new to react and Backend to too ,please help

Please explain in basic terms

Apexcharts How to use different color on opposite bar chart begin on specified value (not zero)

How to use different color on opposite bar chart begin on specified value (not zero).

I already explore the Apexcharts docs example and can’t found any similar approach for my need, all example always use zero value as an axis.

enter image description here

The above example use 0 value as the axis to begin the different bar color.

What I want is to use 50 value as the axis in this y-axis

yaxis: {
          min: 0,
          max: 100,
       }

series: [
    {
        name: 'title1',
        data: [80]
    },
    {
        name: 'title2',
        data: [20]
    }
],

All codes

new Vue({
        el: '#app',
        components: {
          apexchart: VueApexCharts,
        },
        data: {
            series: [
                {
                    name: 'title1',
                    data: [80]
                },
                {
                    name: 'title2',
                    data: [20]
                }
            ],
            chartOptions: {
                chart: {
                  type: 'bar',
                  height: 350
                },
                xaxis: {
                  categories: ['South Korea'
                  ],
                },
                yaxis: {
                  min: 0,
                  max: 100,
                },
                plotOptions: {
                  bar: {
                    borderRadius: 4,
                    borderRadiusApplication: 'end',
                    horizontal: false,
                  }
                },
                dataLabels: {
                  enabled: false
                },
            },
        },
        
    })

Draw local image on canvas using react-native-canvas

everyone. I am going to draw image in expo react native project. Btw it is working on development stage with “yarn start”, but after building the apk, image isn’t displaying on canvas. Please check below codebase and let me know. If anyone has experience in this kind of issue, please let me know the solution for this. Thank you.

import {Asset} from ‘expo-asset’;


const context = canvas.getContext(`2d`);
let img = new CanvasImage(canvas);
img.src = Asset.fromModule(require(`../assets/images/gameIcons/game.png`)).uri;

img.addEventListener('load', function() {
    context.drawImage(image, 0, 0, 100, 100);
})

Ref defined in JSX div creation is not being set

I have a piano key component that can create “visuals” which are divs that float up from the keys. I have a visual_reference state included in the component’s return that also sets its ref so that I can animate it. I have this animate function inside of a useEffect that only runs after the div with the ref is defined, however the reference is always undefined.

I am pretty unexperienced with state and specifically dont understand useRef. I thought it was the same as useState except it doesnt rerender on change, and uses current value so things can access the new state.

PianoKey.js

  let curr_playback_anim = useRef([null, true])
  let [playback_visuals, set_playback_visuals] = useState([])
  let [pb_counter, set_pb_counter] = useState(0)
  let [curr_pb_anim, set_curr_pb_anim] = useState([null, true])
  let playback_visual_refs = useRef({})

  useEffect(() => {
    if (playback_visuals[pb_counter] && curr_pb_anim[1]) {
      playback_visual_refs.current[pb_counter] = playback_visuals[pb_counter].ref

      // ref should be readable here
      set_curr_pb_anim(prev_state => {
        let l = [...prev_state]
        l[0] = attribute_animation(playback_visual_refs.current[pb_counter], 'height', '100vh', '-300000px', 1000000)
        l[1] = false
        return l
      })
    }
    
  }, [playback_visuals])

useEffect(() => {
    if (pb_visual_mode === 'expand_down') {
      audio.play()
      set_playback_visuals(prev_state => {
        set_curr_pb_anim(in_prev_state => {
          let l = [...in_prev_state]
          l[1] = true
          return l
        })
        
        // ref should be set here
        return ({...prev_state,
          [pb_counter]: (
          <div key={`${pb_counter}`} ref={ref => playback_visual_refs.current[pb_counter] = ref} className='visualizer-instance'></div>
        )})
      })
    } 

return (
<div>
        {Object.keys(playback_visuals).map((key, index) => {
              return visuals[key]
            })}
      </div>
    )

I have tried changing around my usage of useRef and useState. Originally many of the defined states were refs but I just can not get them to set. I have set a useEffect with a dependency on the playback_visual_refs.current state but it never would run.

Rotating multiple objects around the origin (JavaScript Canvas)

I am currently building a canvas game. I currently have an issue with setting up players. What im trying to do is basically rotate them around an origin. I can place players, but i am not able to rotate them
My current code is

addEventListener("DOMContentLoaded",()=>{
    const canvas = document.getElementById("canvas")
    var h = window.innerHeight
    var w = window.innerWidth
    var playerCircleSize = 40
    canvas.height = h
    canvas.width = w
    console.log(h,w)
    function rad(degree){
        return degree * (Math.PI / 180)
    }
    function render(){
        const ctx = canvas.getContext("2d");
        ctx.fillStyle = "#6e955e";
        ctx.fillRect(0, 0, canvas.width, canvas.height);
        function player(position){
            function arc(tr1,tr2,size,fillst){
                this.draw = function(){
                    ctx.beginPath();
                    ctx.save()
                    ctx.translate(tr1,tr2)
                    ctx.rotate(rad(position.rot))
                    ctx.arc(0,0,size, 0, 2 * Math.PI);
                    ctx.fillStyle=fillst
                    ctx.fill()
                    ctx.restore()
                }
            }
            var body = new arc(position.x, position.y,playerCircleSize,"#ffc266")
            var hand1 = new arc(position.x-(playerCircleSize/1.5), position.y-(playerCircleSize/1.4),playerCircleSize/3,"#ffb84d")
            var hand2 = new arc(position.x-(playerCircleSize/-1.5), position.y-(playerCircleSize/1.4),playerCircleSize/3,"#ffb84d")

            hand1.draw()
            hand2.draw()
            body.draw()

        }
        player({
            x: w/2 - (playerCircleSize/2),
            y: h/2 - (playerCircleSize/2),
            rot: 90
        })
        player({
            x: 150,
            y: 300,
            rot: 45
        })
    }
    render()
    window.addEventListener("resize", ()=>{
        h = window.innerHeight
        w = window.innerWidth
        canvas.height = h
        canvas.width = w
        console.log(h,w)
        render()
    });
})

I tried to rotate every element individually, but that didnt work. I am expecting the result to look like this

Does Chromium pass URLs along with JS to V8?

I’ve added a print statement to v8/src/parsing/parsing.cc to output JS source code before compilation to deobfuscate code. I also want to print the URL associated with the JS if it exists.

There are objects, such as source_url, in parser.cc and scanner.cc that and would appreciate advice about extracting the URL from them if they actually contain that information.

If they don’t contain JS source URLs where should I look elsewhere in Chromium source code?

How do you change video format to mp4 in MediaRecorder()?

So I followed fireship’s tutorial on making a video recorder app using electronjs. When using the MediaRecorder function to record a video of the screen you pass in an option to specify the video format which is in this case video/webm. I want to change it to video/mp4 but I don’t know what to put there. At the moment it looks like this:

const options = { mimeType: "video/webm; codecs=vp9" };
const media = new MediaRecorder(stream, options);

I read the MDN documentation on this but I don’t know anything about video formats. https://developer.mozilla.org/en-US/docs/Web/Media/Formats/codecs_parameter.
I tried to pass in “video/mp4; codecs=avc1.4d002a” but it didn’t work.

Disable location.replace() in javascript

Is there a way to disable window.location.replace() in the javascript engine? A few websites including microsoft.com have been using it to load intermit analytics and login pages and then hide that they have been loaded by using the location.replace() function. I want to know if there’s a way to disable this javascript feature.