Issue bringing a p5.js project from Visual Studio Code over to the Web Editor (TypeError: e.set is not a function)

When migrating a p5.js project I have been working on from Visual Studio Code to the p5.js Web Editor, I encountered an issue where whenever I attempted to run the project it would give me the error:

TypeError: e.set is not a function
at undefined:2:64726

My current version of the p5.min.js file is 1.6.0 and I have tried using Edge, Chrome, and Firefox to the same results. The project runs fine whenever it is launched from Visual Studio Code.
The project itself is a simple JRPG coded from the ground up, and there is already an older version of it running fine on the Web Editor, though this is from quite a long time ago and I have made a lot of changes and additions since then.

I think the error is referring to a portion of the p5.min.js file, but I don’t want to edit anything in that for fear of breaking it even more. After trying different versions of the file and different browsers, I have no idea what could be causing this, and as the program runs fine whenever I launch it from Visual Studio Code, and as the error the Web Editor throws doesn’t provide me with any information about where in my sketch.js file (which is over 12000 lines long) there could be an issue, I have no idea how to go about fixing this.

The portion of the p5.min.js file being pointed to by the error is this (the specific character is the first ‘f’ character):

87:[ function(e,t,r){var o=e(“../internals/is-regexp”);t.exports=function(e){if(o(e))throw TypeError(“The method doesn’t accept regular expressions”);return e}},

I tried switching my p5.min.js file with an older version (1.3.1) that was in an older version of my project that does still run fine on the Web Editor (though I later realized that the older version of the project seems to be pulling from version 1.4.0, which is being stored elsewhere). I also tried opening the Web Editor in Edge, Chrome, and Firefox. No matter what I did I either got the TypError error thrown six times, or worse got it constantly thrown with my laptop being slowed down to a crawl. I’m beginning to worry that I simply won’t be able to share my project, as the only way I know how to put it up on my Google site like I plan to is by first saving it on the p5.js Web Editor and then embedding the project from the Web Editor into the site.

What should I do? Is there a way to fix this issue? If not, is there another way that I could embed my game?

Why do I keep getting an Unhandled Promise Rejection Error? [duplicate]

I am using Firebase Auth and Firebase Firestore to log a user in and test if a user has admin perms. This is tested in the function isAdmin right when the users logs in. If they are an admin, the addAdminButton function is called, spending a test admin button. However, I keep getting an “Unhandled Promise Rejection: TypeError: null is not an object (evaluating ‘document.getElementById(“navBarRight”).appendChild’)” error. I tried eliminating the addAdminButton function, and putting the code under the if statement, but I kept getting the error. This code runs inside a script tag at the bottom of the body tag, and the div I am trying to append to runs before the script tag.

Code:

auth.onAuthStateChanged((user) => {
  if (user) {
    // User is signed in, see docs for a list of available properties
    // https://firebase.google.com/docs/reference/js/firebase.User
    
    var uid = user.uid;
    console.log(user);
    isAdmin(uid);
    // ...
  } else {
    // User is signed out
    // ...
    window.location.href = "/index.html";
  }
  
});

async function isAdmin (uid) {
  const usersRef = collection(db, "Users");
  const q = query(usersRef, where("UserId", "==", uid));
  const querySnapshot = await getDocs(q);
  querySnapshot.forEach((doc) => {
    if(doc.data().accessLevel == "admin"){
      addAdminButton();
    }
  });
}

function addAdminButton() {
  var item = document.createElement("a");
      item.setAttribute("href", "google.com");
      var textnode = document.createTextNode("Admin");
      item.appendChild(textnode);
      document.getElementById("navBarRight").appendChild(item);
      console.log("clear");
}

How to access properties on a dynamically created component in Svelte

How can I access a component’s properties when that component was created dynamically at runtime? When creating a component in markup I can simply bind:someProperty={someVariable}, but I don’t know of any way to do this when the component is instantiated using new Component() at runtime? How can I get access to this new component’s properties?

App.svelte:

<script>
    import { onMount } from "svelte";
    
    import Component2 from "./Component2.svelte";
    
    let taken;
    
    let container;
    
    onMount(() => {
        new Component2({
            target: container
        });
        
        // How do I access this new component's `someValue` property?
    });
    
</script>

<div bind:this={container}>
    
</div>

<Component2 bind:someValue={taken}></Component2>

Component2.svelte:

<script>
    export const someValue = Math.floor(Math.random() * 8999 + 1000);
</script>

<p>
    {someValue}
</p>

I know that I can pass in a props: {} object to the constructor to assign values to the properties, but what I want is to have the component assign its own values to the properties and just be able to access them from outside the component.

Is this considered bad practice and a “not Svelte-like” approach? Should I be using a store instead? If so, what should that look like?

google chrome extension manifest v3 context menu create and console command

This is my first chrome extension.
I want to run a console command from the right-click menu, for example a plain hello world, but it doesn’t print. The menu appears, but the command is not executed

manifest.json

{
   "name": "Hello",
   "description": "Hello world",
   "version": "0.1.107",
   "permissions": ["contextMenus"],
   "host_permissions": ["<all_urls>"],
   "background": {
     "service_worker": "background.js"
   },
   "manifest_version": 3
 }

background.js

chrome.contextMenus.create({
    id: 'hello',
    title: 'Hello world',
    contexts: ['page']
  })
  
  function contextClick(info, tab) {
    const { menuItemId } = info
  
    if (menuItemId === 'hello') {
      console.log("Hello world");
    }
  }
  
  chrome.contextMenus.onClicked.addListener(contextClick);

Why the first element in the chart does not show when the background svg path is behind it?

I am working on a variable radius pie chart. The original code was from here: https://embed.plnkr.co/plunk/atGc2B. I have added a background of a doughnut shape which works fine. But when the background path is there, the first element in the chart does not show.

Here are images of what happens without and with the background.

Desired view of chart without background

Broken chart with background

Here is the code:

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8" />
     <title>D3.js Variable Radius Donut Chart</title>
     <link data-require="normalize@*" data-semver="3.0.1" rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.min.css" />

    <style>
        body {
          background-color: #282a35;
        }

        #bg svg {
          position: relative;
          z-index: 0; 
        }
    </style>
</head>
<body>
  <div id="chart"></div>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.6/d3.min.js" data-semver="3.4.6" data-require="d3@*"></script>
  <script>
            (function(d3) {
                'use strict';

                var dataset = [
            //    { count: 0, size: 0, label: '', colour: '' },
                  { count: 3, size: 30, label: 'Use', colour: 'slateblue' }, 
                  { count: 1, size: 10, label: 'Production', colour: 'yellow' },
                  { count: 15, size: 100, label: 'Distribution', colour: 'orange' },
                ];

                var width = 500;
                var height = 500;
                var donutWidth = 50;
                var innerRadius = (Math.min(width, height) / 4.5) - donutWidth;
                
                var svg = d3.select('#chart')
                  .append('svg')
                  .attr('width', width)
                  .attr('height', height)
                  .style('position', 'relative')
                  .style('z-index', 1)
                  .append('g')
                  .attr('transform', 'translate(' + (width / 2) + 
                    ',' + (height / 2) + ')');
                
                var arc = d3.svg.arc()
                  .innerRadius(innerRadius)
                  .outerRadius(function (d) { 
                    return innerRadius + d.data.size; 
                  });
                

                var pie = d3.layout.pie()
                  .value(function(d) { return d.count; })
                  .sort(null);
                
                var data = pie(dataset);
                
                //I don't know why this background doughnut is not working.
                var bg = svg.append('path')
                  .attr('d', d3.svg.arc()
                    .innerRadius(innerRadius-10)
                    .outerRadius(innerRadius + donutWidth + 80)
                    .startAngle(0)
                    .endAngle(2 * Math.PI))
                  .attr('fill', '#18a34a');

                var path = svg.selectAll('path')
                  .data(data)
                  .enter()
                  .append('path')
                  .attr('d', arc)
                  .attr('fill', function(d){return d.data.colour});

                var text = svg.selectAll('text')
                  .data(data)
                  .enter()
                  .append('text')
                  .text(function(d) { 
                    return d.data.label + ": " + d.data.count; 
                  })
                  .attr('transform', function(d) {
                    var c = arc.centroid(d),
                      x = c[0],
                      y = c[1],
                      h = Math.sqrt(x*x + y*y);
                  return 'translate(' + (x/h * (innerRadius+donutWidth/2)) + ',' +
                     (y/h * (innerRadius+donutWidth/2)) +  ')';
                })
                  .attr('dy', '.35em')
                  .attr('fill', 'black')
                  .attr('text-anchor', function(d) {
            return (d.endAngle + d.startAngle)/2 > Math.PI ?
                'end' : 'start';
                  });
                
              })(window.d3);

    </script>
</body>

</html>

How to write an ASP.NET ef core sql query in javascript?

Im using javascript to draw my UI and implement a map from the Google Maps API, however, I have an MSSQL database connected to an ASP.NET program that contains the map which is run in a cshtml page, I managed to get a SQL query working in c# however it would make my life so much easier if I could generate SQL queries in my javascript code instead, is there any way I could translate this (or equivalent) code:

    string fishName;
    SqlConnection conn = new SqlConnection("sqlConnection");
    conn.Open();
    SqlCommand cmd = new SqlCommand();
    cmd.CommandTimeout = 60;
    cmd.Connection = conn;
    cmd.CommandType = System.Data.CommandType.Text;
    cmd.CommandText = "SELECT minLength FROM Fish";
    fishName = cmd.ExecuteScalar().ToString();
    conn.Close();

into javascript?

I know I could use Html.DisplayFor(modelItem => item.Name) and it makes it much easier, however, the amount of marks I lose out on if I use this solution is far too large.

I cant even remember what I have tried it has taken so long, I am quite new to ASP and JavaScript and have been scouring the internet for actual days trying any solution I could find.

Unable to get a reference for an array index

I am trying to delete the list item from the array Tasks[] when the delete button is clicked but I am unable to generate a reference for the specific index of Tasks[]. I am a newbie to react, infact I recently started learning react.

Here’s my code
App.js

type hereimport React, { Component } from "react";
import Overview from "./OverView";
import uniqid from "uniqid";

class App extends Component {
  constructor() {
    super();
    this.deleteTask = this.deleteTask.bind(this);
    this.state = {
      task: {
        text: '', 
        taskno: 0,
        id: uniqid()
      },
      tasks: [],
    };
  }

  handleChange = (e) => {
    this.setState({
      task: {
        text: e.target.value,
        taskno: this.state.task.taskno,
        id: this.state.task.id,
      },
    });
  };
  deleteTask = (e) => {
    console.log(this.state.task.taskno)
    // this.setState({
    //   // tasks: this.state.tasks.filter(this.state.tasks[task.id])
    // })
    
  };

  onSubmitTask = (e) => {
    e.preventDefault();
    this.setState({
      tasks: this.state.tasks.concat(this.state.task),
      
      task: {
        text: '',
        taskno: this.state.task.taskno + 1, 
        id: uniqid()
      },
    });
  };

  render() {
    const { task, tasks} = this.state;
    // const {deleteTask} = this.props;
    return (
      <div>
        <form onSubmit={this.onSubmitTask}>
          <label htmlFor="taskInput">Enter task</label>
          <input
            onChange={this.handleChange}
            value={task.text}
            type="text"
            id="taskInput"
          />
          <button type="submit">Add Task</button>
        </form>
        <Overview tasks={tasks} deleteTask={this.deleteTask} />
        
      </div>
    );
  }
}

export default App;

and here’s Overview.js

import React from "react";

const Overview = (props) => {
  
  const { tasks,deleteTask} = props;

  return (
     
    <ul>
      {tasks.map((task) => {
        return(
        <div>
       <li key={task.id}>{task.taskno} : {task.text}   <button onClick={deleteTask}> Delete</button>  </li>
       
        </div>)
      })}
     
      
    </ul>
  
  );
};

export default Overview;

So far I have been able to add the delete button and register a click on the delete button but I am struck there now.

Filter returns an empty array when trying to check the length of numbers

I should create a function that given an array of numbers and a specific value, returns another array filled with those numbers in which the number of digits matches the specified value.

function filtrarPorQuantidadeDeDigitos (array, nDigitos) {
  let solucao = array.filter(elemento => {
    elemento.toString().length === nDigitos
    console.log(elemento.toString().length == nDigitos)
  })
  return solucao
}

console.log(filtrarPorQuantidadeDeDigitos([123, 11, 158, 0], 3))

Thus I created an arrow function associated with the .filter method that converts each number in a string (.toString()) and then, counts its length to check if it’s the same as what we are expecting. Naturally, if the condition was fulfilled, that element would be copied to the resulting array. However, even checking with a console.log that the boolean values for each loop are correct, I still get an empty array as output.

Why isn’t it working? What should I do to solve this problem? Is it possible to do it in any similar way?

Video Tag in Chrome Browser requesting incorrect range when seeking progress bar to random location. Firefox is working flawlessly

I have FASTAPI server which can server partial content, Response status 206.

@video_router.get("/video/file/{folder}/{name}")
async def video_endpoint(folder: str, name: str, range: str = Header(None)):
    CHUNK_SIZE = 2048*2048
    video_path = Path(f"./media/{folder}/{name}")
    video_size = video_path.stat().st_size
    start, end = range.replace("bytes=", "").split("-")
    start = int(start)
    if start + CHUNK_SIZE > video_size:
        end = video_size
    else:
        end = start + CHUNK_SIZE

    with open(video_path, "rb") as video:
        video.seek(start)
        data = video.read(end - start)
        headers = {
            'Content-Range': f'bytes {start}-{end}/{video_size}',
            'Accept-Ranges': 'bytes'
        }
        return Response(data, status_code=206, headers=headers, media_type="video/mp4")

From react frontend I am requesting this URL to give partial content.

<video
          controlsList="nodownload"
          key="abc"
          width="100%"
          height="100%"
          poster={poster_url}
          controls
          src={video_url}
          type="video/mp4"
          preload="metadata"
        />

This is working flawlessly in firefox browser, but in Google Chrome when I am seeking the progress bar to any location either backward or forwards. The video player gets hung/stuck. Post playing the Pause/Play button, video starts to play from starting i.e. bytes=0-.

When debugging this range parameter which is passed in header I notice that the chrome browser is requesting the incorrect bytes i.e. bytes=INCORRECT_NUMBER-. Additionally that INCORRECT_NUMBER is same for any position in progress bar. Please check the below images.

IMAGE1: Time was equal to 15 seconds but bytes requested was the ending bytes

IMAGE2: Time was equal to 2:54 minutes but bytes requested was the ending bytes identical to previous image

After this operation as you can see the video tag is no longer requesting any data from the FASTAPI server.

I tried changing headers, other react-video players and iframe tag.

I am expecting to stream videos through fastapi server serving partial content. Suggestion for alternative or workaround of video tag is much appreciated.

The gdpr what cookies allow without permissions?

For security when loading the main page with setcookie() I want to put a user id in a cookie and save it in your browser, for example when loading the general data protection regulation page for the first time it puts 3 cookies in my browser without there being accepted cookies, it is also seen in other web pages, so according to the rules of the general data protection regulation, if it is for security, can a cookie be created with a name, expiration time and the user’s id without their permission?

GeneralDataProtectionRegulation web page

What is the most performant way to merge down a matrix of numbers?

Let’s say I have a matrix that looks like the following.

const m = [[0,1,6,7,2,2],
           [2,3,4,5,3,3],
           [6,7,0,0,4,5]]

Given a matcher block, I want to traverse the array, jumping by the length of the matcher block(two at a time in this example), from last row to first row and choose the matcher block or the one beneath it if there’s no match.

So given a matcher block of [6,7], the result should be a 1D array of [6,7,6,7,2,2]

In this naive example it’s pretty easy to just do loops(loop the rows last first, increment columns by the block size, then compare the current slice of the row to the matcher), but this matrix could have millions of numbers and so will get slow very quickly.

What is the most efficient way to accomplish this?

Hooking javascript object literal constructors to modify objects created in inaccessible contexts

I’m attempting to modify an object present in code that I do not control and cannot directly alter. Ideally, I’d like to do this from a bookmarklet, but the extra permissions of a userscript are also a usable context.

The code I’m attempting to hook looks like this:

(() => {
  var target = { nestedsubobject: { foo: 'value' } };
  // does some stuff with target
})();

I’d like to intercept the object literal assigned to target and modify the value of foo, before the IIFE uses it further.

So far everything I’ve tried that doesn’t work:

  • Prototypes appear unrelated to this problem. While I can override the global object prototype, this gives me no way to actually listen for objects created using that prototype.
  • Constructors are bypassed with object literals. While I can override the global object constructor (as in Override JavaScript global native Object() constructor), the literal syntax doesn’t appear to use that constructor.

Additionally, I can’t alter the code directly (e.g. intercepting and rewriting the network request for it) because I expect that it may be obfuscated in the future. I’d like to directly hook object creation to make my userscript much more durable.

How to mark exported function as used somewhere in typescript

I have something like that:

  • modules with exported functions
  • a resolver function that would require via an alias like module-name/function-name
  • a json file in other repo that maps pages and functions to be called to load page data via these async functions.

The module-name is just a directory name from which the index.js would be require -ed.

resolver function works like that:

export function resolveModuleFunction(moduleName, functionName) {
    if (moduleName.indexOf('~/modules') === 0) {
        moduleName = moduleName.replace('~/','../');
    } else if (moduleName.indexOf('~modules/') === 0) {
        moduleName = moduleName.replace('~modules/','../modules/');
    } else if (moduleName.indexOf('~/') === 0) {
        moduleName = moduleName.replace('~/','../');
    }
    return function(...params) {
        let moduleInstance = require(moduleName);
        if (moduleInstance.default) {
            moduleInstance = moduleInstance.default;
        }
        return moduleInstance[functionName].apply(moduleInstance, params);
    };
}

It works, and all I want to get for now is to explain to IDE that functions to be used via these dynamic references – e. g. with these aliases in other repos with markup, are “used somewhere else”, and avoid these “exported function X of module Y is unused”.

I don’t want right now to re-factor that part of system to typescript file(s) that would register the pages in code.

I just looking for a way (with a JSDoc may be?) to mark an exported function to be used somewhere?

I thought about making some exported-functions.md file where these modules and their functions would be listed in a JS markdown blocks, both for documentation purposes and for getting that effect of exported functions considered to be “used somewhere”.

Is there other way to achieve it, with some keyword at per-function JSDoc?

Can’t change the color of digits in toast

Simple task but i cant handle it dunno why , hope someone can help with it

var frame = document.getElementsByClassName("notifications_frame")[0];
var frame_b = document.getElementsByClassName("notifications_frame_block")[0];

function add_notify(time, format_text, type) {
    let div = document.createElement('div');
    div.className = "notify_bock";
    div.id = "notify_bock";
    frame_b.append(div);
    let text = document.createElement('div');
    text.className = "notify_bock_text";
    text.innerHTML = format_text
    if (type == 0) text.style.borderBottom = "0.31vh solid #668C65"; 
    else if (type == 1) text.style.borderBottom = "0.31vh solid #897E35";
    else if (type == 2) text.style.borderBottom = "0.31vh solid #F8463B";
    div.append(text);
    var animation = div.animate([{opacity: '0',}, {opacity: '1',}], 2000);
    animation.addEventListener('finish', () => {setTimeout(elem_remove, parseInt(time), div);});
    frame.scrollTop = frame.scrollHeight;
}
function elem_remove(elem) {var animation=elem.animate([{opacity:'1',}, {opacity:'0',}],2000);animation.addEventListener('finish',()=>{elem.remove();});}


<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://cdn.rawgit.com/mfd/09b70eb47474836f25a21660282ce0fd/raw/e06a670afcb2b861ed2ac4a1ef752d062ef6b46b/Gilroy.css">
    <link href="./css/main.css" rel="stylesheet" />
    <title>Notify</title>
</head>
<body>
    <div class="notifications_frame">
        <div class="notifications_frame_block"></div>
    </div>
    <script src="./js/main.js"></script>
    <script>Vue.filter('formatThousands', (x) => {return x.toString().replace(/B(?=(d{3})+(?!d))/g, ",");})</script> 
</body>
</html>

Please help , lost already week

I need to make all digits in text green color, but when i try to add it in browser im not seen it