How can a static method be called dynamically from an instance method?

I have several classes, each of which should be able to retrieve an existing instance of itself (using an ID) when possible, rather than creating a new instance. For encapsulation and convenience, I want to store each class’s library as a static property of the class, and abstract the whole pattern for quick reuse. But I can’t find a clean way to dynamically access a static method from an instance scope in JS.

class HasLibrary
{
    static library = new Map();
    static get(id) { return new this(id); }

    constructor(id) {
        let existing = HasLibrary.library.get(id);
        if (existing) return existing;

        this.id = id;
        HasLibrary.set(id, this);

        return false; // for inheritance
    }
}

class Tag extends HasLibrary
{
    constructor(name, options) {
        let existing = super(name);
        if (existing) return existing;
        
        // do Tag-specific stuff

        return this;
    }
}

class Product extends HasLibrary
{
    constructor(name, options) {
        let existing = super(name);
        if (existing) return existing;
        
        // do Product-specific stuff

        return this;
    }
}    

The static get() function inherits correctly, so I can call Tag.get("spruce") and it returns a Tag instance. (In OOP terms, I can access instance methods dynamically from static methods.) But of course, when Tag calls super(), the library property is hard-coded to the base class.

If this were (modern) PHP, I could call the static keyword to get the current class’s property.

abstract class HasLibrary
{
    ...

    function __construct($id) {
        $result = static::$library[$id];
        ...

I’ve resorted to setting an instance property that each of the child classes must override, but there’s still more copy-paste action required than I would prefer. (In addition, the static library property does not create new Maps when inherited, so that Tag.library and Product.library point to the same Map.)

class HasLibrary
{
    static get(id) { return new this(id); }

    id = '';

    constructor(id) {
        let result = this.self.library.get(id);
        if (result) return result;
        this.id = id;
        this.self.library.set(id, this);
        return false; // for inheritance
    }
}

class Tag extends HasLibrary
{
    static library = new Map();
    get self() { return Tag; }

    constructor(name, options) {
        let existing = super(name);
        if (existing) return existing;
        
        // do Tag-specific stuff

        return this;
    }
}

class Product extends HasLibrary
{
    static library = new Map();
    get self() { return Product; }

    constructor(name, options) {
        let existing = super(name);
        if (existing) return existing;
        
        // do Product-specific stuff

        return this;
    }
}

A module failed and `AppRegistry.registerComponent` wasn’t called

New to react-native, and I got this error:

    * A module failed to load due to an error and `AppRegistry.registerComponent` wasn't called., js engine: hermes

here is my index.js:

import { AppRegistry } from 'react-native';
import App from './App';
import { name as appName } from './app.json';

AppRegistry.registerComponent(appName, () => App);

and I have put the codes below in my app.json,

{
  "name": "EatNGo",
  "displayName": "EatNGo"
}

Any suggestions?

How to retrieve user roles using @auth0/nextjs-auth0

I’m using Auth0 to integrate an authentication and user system with Next.js and the @auth0/nextjs-auth0 lib. I’ve created two roles in the Auth0 dashboard but I’m struggling to find documentation or a place that gives me some updated information on how do this.

Initially, I was creating an endpoint in the next api called me, where I basically made this request:

import { NextApiRequest, NextApiResponse } from "next";

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  const userId = req.query.userId as string
  const mgmtApiAccessToken = process.env.MGMT_API_ACCESS_TOKEN

  if (!userId || !mgmtApiAccessToken) return res.status(400).json({
    error: 'Missing required params'
  })

  try {
    const response = await fetch(`${process.env.AUTH0_DOMAIN_URL}/api/v2/users/${userId}/roles`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${mgmtApiAccessToken}`
      }
    })

    if (!response.ok) throw new Error('Failed to fetch user roles')

    const data = await response.json()
    res.status(200).json(data)
  } catch (err) {
    res.status(500).json({ error: err });
  }
}

However, I’m having difficulty finding the mgmtApiAccessToken. Is this really the best approach? Please give me some good tips.

NPM no funciona [closed]

al querer instalar un paquete npm o al crear un proyecto en next.js, vite, etc. Me da el siguiente error

npm create vite@latest proyecto
npm ERR! code ECONNRESET
npm ERR! syscall read
npm ERR! errno ECONNRESET
npm ERR! network request to https://registry.npmjs.org/create-vite failed, reason: read ECONNRESET
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settings.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network ‘proxy’ config is set properly. See: ‘npm help config’

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersRowanAppDataLocalnpm-cache_logs2023-11-29T21_33_49_477Z-debug-0.log

Me esta pasando hace varios dias y no se que hacer. Si alguien me puede ayudar por favor

Comprobe mi conexion a internet, no uso ningun proxy, tengo la version 9.5.1 de npm y la 18.16.0 de node y antes funcionaba.

Onclick Random Redirect from List

I’m trying to create a button on my website that opens a random page from a list in a new tab.

I think I’m pretty close, but when a new tab opens it is an “about:blank” page.

I’m not sure where I’m going wrong.

What I’ve tried is below

`<html lang="en">
  <head>
    <title>Redirect From List</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
  <body>
      <div style="text-align:center;padding:15px;">
     
    <button style="text-align:center;" onclick="window.open()" type="button" name="" id="" class="btn btn-primary" btn-lg btn-block target="_blank">Random Website</button>    
    </div>
    <script>
        var links = [
        "http://www.google.com",
        "http://www.yahoo.com",
        "http://www.bing.com",
        "http://www.duckduckgo.com"
    ]

    function openLink() {
        var i = parseInt(Math.random() * links.length);
            location.href = links[i];
    }
</script>
</body>
</html>`

I’m using google, yahoo, bing, duckduckgo as placeholder websites, and I want it so that when I click the button, a random webpage from my Var Links list will open, so that I can update the URL’s as I add content.

However, right now, a new tab opens, but it doesn’t open any of the webpages from the list. Is there an error that I’m missing?

Can I use a client component (nav bar) in the root layout of my Next.js app?

I’m using Next.js and I have a root layout file in my app router. However, i’m encountering an error in my <Nav/> component because it’s using state to keep track of whether the mobile nav is open or not.

the error says:

You’re importing a component that needs useState. It only works in a Client Component but none of its parents are marked with “use client”, so they’re Server Components by default.

in my root layout.js file:

import Footer from './components/footer';
import Hero from './components/hero';
import Nav from './components/nav';
import "../styles/globals.css"

export default function Layout({ children }) {

  return (
    <html lang="en">
      <Nav />
      <Hero />
      <main className='bg-white'> 
          {children}
      </main>
      <Footer />    
    </html>

  )
}

I’ve tried adding “use client” to the top of my <Nav/> component, but it disables all of my event handlers and state in the component, rendering it useless on mobile. I’m not clear on the relationship between client and server components works, or how event handlers should work in this case.

Is there a way to get around this error while maintaining the nav’s position in the root layout and also keep its interactivity?

Unable to write in TextInput (JavaScript)

For reasons unknown my text input wont let me update or even type into the text box. I swear I was able to write into it earlier but now clicking on it does nothing except producing the black border. The specific bit of code I’m using is:

        <SafeAreaView>
            <TextInput
                style={styles.input}
                placeholder="Enter cohort code"
                value={cohortInput}
                onChangeText={(text) => { cohortInput = text }}
            />
        </SafeAreaView>

meanwhile the whole code is:

import * as React from ‘react’;
import { Button, SafeAreaView, StyleSheet, Text, View, TextInput } from ‘react-native’;

function WelcomeScreen({ navigation }) {

var cohortInput = '';
var instructorInput = '';
const [empty, setEmpty] = React.useState(false);
const [error, setError] = React.useState(false);


return (
    <View style={styles.container}>
        
        <Text style={styles.text}>
            {'Join cohort: n'}
        </Text>

        <SafeAreaView>
            <TextInput
                style={styles.input}
                placeholder="Enter cohort code"
                value={cohortInput}
                onChangeText={(text) => { cohortInput = text }}
            />
        </SafeAreaView>

        {/*
        <Text style={style.error}>
            {empty? <Text>  Please enter a code!</Text>: null }
        </Text>
        */}
        

        <Text style={styles.text}>{'n Join as Instructor:'}</Text>
        
        <SafeAreaView>
            <TextInput
                style={styles.input}
                placeholder="Enter facilitator code"
                value={instructorInput}
                onChangeText={(text) => { instructorInput = text }}
            />
        </SafeAreaView>

        
        <view style={styles.buttonContainer }>
            <Button
                title='Join'
                onPress={() => {
                if (cohortInput === '')
                    setEmpty(!empty);
            }}>
            </Button>
        </view> 
        
    </View>

);

}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: ‘#ffff’,
alignItems: ‘center’,
fontSize: 20,
},
input: {
height: 40,
fontSize: 20,
borderBlockColor: ‘black’,
borderColor: ‘black’,
borderRadius: 5,
},
text: {
fontSize: 20,
},
error: {
fontSize: 15,
color: ‘red’,
},
buttonContainer: {
width: 70,
height: 30,
color: ‘#0000cd’,
justifyContent: ‘center’,
alignItems: ‘center’,
borderRadius: 30,
}
});

export default WelcomeScreen;

If you have any advice on how to resolve this I would greatly appreciate it.

Undoing untill the textbox worked again but that was unfruitful

ScrollMagic glitch on Chrome

Hello community,

I’ve implemented an effect on my website using Scroll Magic to make a video play as the user scrolls down the page. This effect works perfectly in other browsers, but I’m experiencing significant performance issues in Google Chrome.

Issue Description:

The video stutters noticeably on Chrome, while it plays smoothly in other browsers.
I’ve checked and haven’t encountered any other notable performance issues on my website.
The problem seems specific to Chrome, as I don’t observe this stuttering in other browsers.

This is my JS code:

const intro = document.querySelector('.intro');
const video = intro.querySelector('video');
const text = intro.querySelector('h1');
//END SECTION
const section = document.querySelector('section');
const end = section.querySelector('h1');

//SCROLL MAGIC

const controller = new ScrollMagic.Controller();

//SCENES
let scene = new ScrollMagic.Scene({

    duration: 9000,
    triggerElement: intro,
    triggerHook: 0
})
.addIndicators()
.setPin(intro)
.addTo(controller);


//TEXT ANIMATION
const textAnim = TweenMax.fromTo(text, 3, {opacity: 1}, {opacity: 0});

let scene2 = new ScrollMagic.Scene({
    duration: 3000,
    triggerElement: intro,
    triggerHook: 0
})

.setTween(textAnim)
.addTo(controller);

//VIDEO ANIMATION

let accelAmount = 0.1;
let scrollPos = 0;
let delay = 0;

scene.on("update", e => {
    scrollPos = e.scrollPos / 1000;
});

setInterval(() =>{
    delay += (scrollPos - delay) * accelAmount;

    video.currentTime = delay;
}, 10);

My HTML code :

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AxB|Home</title>
    <link rel="stylesheet" href="./style.css">
</head>

<body>

    <div class="intro">
        <h1>Make it floating</h1>
        <video src="Images/Floating2.mp4"></video>
    </div>

    <section>
        <h1>REVOLUTIONARRY</h1>
    </section>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/latest/TweenMax.min.js"
        integrity="sha512-8Wy4KH0O+AuzjMm1w5QfZ5j5/y8Q/kcUktK9mPUVaUoBvh3QPUZB822W/vy7ULqri3yR8daH3F58+Y8Z08qzeg=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/ScrollMagic.min.js"
        integrity="sha512-8E3KZoPoZCD+1dgfqhPbejQBnQfBXe8FuwL4z/c8sTrgeDMFEnoyTlH3obB4/fV+6Sg0a0XF+L/6xS4Xx1fUEg=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/ScrollMagic.js"
        integrity="sha512-UgS0SVyy/0fZ0i48Rr7gKpnP+Jio3oC7M4XaKP3BJUB/guN6Zr4BjU0Hsle0ey2HJvPLHE5YQCXTDrx27Lhe7A=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script
        src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/plugins/animation.gsap.js"
        integrity="sha512-judXDFLnOTJsUwd55lhbrX3uSoSQSOZR6vNrsll+4ViUFv+XOIr/xaIK96soMj6s5jVszd7I97a0H+WhgFwTEg=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script type="text/javascript"
        src="https://cdnjs.cloudflare.com/ajax/libs/ScrollMagic/2.0.8/plugins/debug.addIndicators.js"
        integrity="sha512-mq6TSOBEH8eoYFBvyDQOQf63xgTeAk7ps+MHGLWZ6Byz0BqQzrP+3GIgYL+KvLaWgpL8XgDVbIRYQeLa3Vqu6A=="
        crossorigin="anonymous" referrerpolicy="no-referrer"></script>

   
    <script src="script.js"></script>
</body>

</html>

And my CSS code :

*{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body{
    font-family: sans-serif;
}

.intro{
    height: 100vh;
}

.intro video{
    height: 100%;
    width: 100%;
    object-fit: cover;

}

.intro h1{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%);
    font-size: 80px;
    color: white;
}

section{
    height: 100vh;
    color: black;
}

section h1{
    padding-top: 300px;
    text-align: center;
    font-size: 80px;
}

What I’ve Tried So Far:

I’ve reduced the dimensions of the video to improve performance, but the issue persists.
I’ve looked for Chrome-specific video performance issue solutions without success so far.

Converting Standard Web IFrame JS, HTML, CSS Functions and Code into Angular Typescript and Using Them

I am trying to convert Clovers Ecommerce Iframe code from basic web app (JS, HTMl, CSS) into code that works in my angular component. I am running into a couple of issues. This is the code I want to convert into angular and although I have successfully got the clover object and elements object to initialize and the form to display, I am having trouble getting the behavior to work. It seems that the form is not sending with the request. Also if I convert the old promise to subscribe, it doesn’t work. Is there something I am missing. I replicated my code into a basic angular project here. I manage to get into the then part but it is showing that the card details are null. Can someone help me connect the form values to the request and understand what is causing this error and how to link the form to get rid of it and get the code working exactly as the javascript example?

My guess is the issue lies when setting or mounting the card object and successfully populating it might resolve part of the issue:

const cardNumber = this.elements.create('CARD_NUMBER', styles);
    const cardDate = this.elements.create('CARD_DATE', styles);
    const cardCvv = this.elements.create('CARD_CVV', styles);
    const cardPostalCode = this.elements.create('CARD_POSTAL_CODE', styles);

    cardNumber.mount('#card-number');
    cardDate.mount('#card-date');
    cardCvv.mount('#card-cvv');
    cardPostalCode.mount('#card-postal-code');

The error I get

Comparing two arrays by its element [closed]

This is a code that my teacher gave me on javascript course. I didnt understand why we have to use let same=true; in the top od the function.

let a = [1, 2, 3];
let b = [1, 2, 3];
document.write(f(a, b));

function f(a, b) {
    let same = true;
    if (a.length != b.length) return false;
    for (i in a) {
        if (a[i] !== b[i]) {
            return false;
        }
    }
    return true;
}

Scrollify, automatic scrolling of long sections

Today I’m trying to implement an animation that, when a button is clicked, begins to smoothly transition from section to section. For work, I chose Scrollify.
I wrote a simple example code to move from section to section after a certain period of time. And everything works, if not for one thing.

In my project there are sections that are much higher in height than the height of the user screen. And when using this animation, half of the content is simply skipped. If there is a way to fix this? Smooth scrolling within a section? There is a possibility of writing a separate function that will scroll through the content inside the section.

My code:

function toNextWin(){
    var counterValue = 0;
    if (counterValue < 10) {
        counterValue++;
        $.scrollify.next();
        setTimeout(toNextWin, 2000);
    }
}

File sometimes being deleted before download is complete

I have a page where a user clicks on a button to download a file. It is supposed to decrypt the file, download the file, and then delete the decrypted file. What is intermittently happening is that the deletion is happening before the download is complete. Sometimes the file is partially downloaded, sometimes not at all.

I would normally download the files server side, but since this is an AJAX page the method I use for that does not appear to work. So instead I am doing some back and forth from server and client side.

Here is the VB.NET server side sub fired after button click:

Sub DownloadFile()
    output = MapPath + _hdnFilePath.Value
    input = output.Replace("_dec", "_enc")
    crptFile.Decrypt(input, output)
    Dim encodedFileName As String = _hdnFilePath.Value.Replace("'", "@@@")
    RadAjaxManager1.ResponseScripts.Add("downloadURI('" & encodedFileName & "');")
    ''OLD  DOWNLOAD METHOD BELOW - does not work with ajax
    'Response.Clear()
    'Response.ContentType = "application/pdf"
    'Response.AppendHeader("Content-Disposition", "attachment; filename=" + 
    'Path.GetFileName(output))
    'Response.WriteFile(output)
    'Response.Flush()

    'Delete the decrypted (output) file.
    'File.Delete(output)
End Sub

Here is the javascript fired by this function:

function downloadURI(encodedFileName) {
    encodedFileName = encodedFileName.replace(/@@@/g, "'");
    var encodedURI = encodeURIComponent(encodedFileName)
    encodedFileName = encodedFileName.replace("###", "%").replace("$$$", "&")
    fetch('<%= ResolveUrl("/CUTracking/CUFiles/") %>' + encodedURI)
        .then(resp => resp.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.style.display = 'none';
            a.href = url;
            a.download = encodedFileName;
            document.body.appendChild(a);
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove();
        })
        .catch(() => alert('There was an error'));
    $find("<%= RadAjaxManager1.ClientID %>").ajaxRequest("Delete")
}

And here is the delete VB.NET sub fired by the javascript download function:

Protected Sub RadAjaxManager1_AjaxRequest(sender As Object, e As 
    AjaxRequestEventArgs)
    If e.Argument = "Delete" Then
        File.Delete(MapPath + _hdnFilePath.Value)
    End If
End Sub

Is there any way I can prevent the file from getting deleted too early, or is there a less roundabout way of going about this? I am only using a blob in an attempt to fix this issue, and only using javascript for downloading the file because my server side method is not working with AJAX.

Can´t get the html selectors right using Puppetter

I started to learn puppetter recently following a tutorial. The tutorial code that I followed worked but I tried to write and similar code that didn´t.

TUTORIAL CODE:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: false, 
    defaultViewport: false,
    userDataDir: "./tmp"
  
  });
  const page = await browser.newPage();
  await page.goto('https://www.amazon.com/s?rh=n%3A16225007011&fs=true&ref=1p_16225007011_sar');

  const productsHandles = await page.$$( "div.s-main-slot.s-result-list.s-search-results.sg-row > .s-result-item");

  for(const producthandle of productsHandles){
    try {
      
      const title = await page.evaluate(el => el.querySelector('h2 > a > span').textContent, producthandle)
  
      console.log(title)
    } catch (error) {
      
    }

  }




  //await browser.close()
})();

MY CODE:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch({
    headless: false, 
    defaultViewport: false,
    userDataDir: "./tmp"
  
  });
  const page = await browser.newPage();
  await page.goto('https://www.superanimes.biz/lista-de-animes');

  const productsHandles = await page.$$("#containerVideos > section > section > div.post_cat.notranslate");

  for(const producthandle of productsHandles){
    try {
      
      const title = await page.evaluate(el => el.querySelector('div.title_cat > span').textContent, producthandle)
  // #video_ > a > div.title_cat > span
      console.log(title)
    } catch (error) {
      
    }

  }




  //await browser.close()
})();

It was supposed to loop to the elements and return the title of each one

It was supposed to loop through each one of the elements but my code just printed the first

Cannot pass props after adding vuetify to a vue web component

Im in the process of developing a web component in vue. A lot of it has been made using vuetify component library and I’m currently in process of trying to export to to a web component. I’ve followed the steps described in this thread: How can Add libraries like Vuetify inside of a web component created by Vue 3?, which consist of overriding the standard ‘defineCustomElement’ method, however after following all the steps Im now unable to pass props to the exported component in the index.html file.

Some code snippets to give you an idea:

  1. Very Simplified version of my component using vuetify

  2. Binding vuetify files to the web-component (as described in the thread above)
    I’ve also declared the props separately within the method because otherwise I get an error followed by a whitescreen. However, even after the declaration, they are not passed onto the actual component.

Binding vuetify files to the web-component
 

  1. Adding props to the custom component within the index.html file
    <custom-vuetify-element checkProp = "foo"></custom-vuetify-element>

What could be the reason for this issue? Is there anything within the override defineCustomElement method, that could be changed to make passing a props possible?

Any help would be greatly appreciated!
Thanks in advance

Tried various methods. Unfortunately this specific issue isn’t really mentioned anywhere else.