Change Object value after web page is loaded

I am learning about eventListeners and was given a task to update an object value after the page is loaded. Should I use form or is there any other way to do it?

const backpack = new Backpack(      
      100,
      200,
      300,
      30
)

function changeValue(){
      const input_value = document.querySelector(".data");
      backpack['width'] = input_value.value;
}

var button = document.querySelector(".button_click");
button.addEventListener("click", changeValue);

The block is not deleted after saving ckeditor 5

I am writing my plugin, and there was a problem when saving, the block is added and deleted when inserting, but if you save it, it is not deleted.

It seems to me that the block after saving is not detected by ckeditor 5, so it is not active for deletion, but I do not understand what this is related to

The whole code:

import Plugin from '@ckeditor/ckeditor5-core/src/plugin';
import { toWidget, toWidgetEditable } from '@ckeditor/ckeditor5-widget/src/utils';
import Widget from '@ckeditor/ckeditor5-widget/src/widget';

class GalleryImport extends Plugin {
     static get requires() {          
        return [ Widget ];
    }
    
     init() {
        const editor = this.editor;
         
        this._defineSchema();  
        this._defineConverters();

        editor.ui.componentFactory.add( 'galleryimport', () => {
            // The button will be an instance of ButtonView.
            const button = new ButtonView();

            button.set( {
                label: 'Insert gallery',
                icon: '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path d="M13.75 9v2.25H16v1.5h-2.25V15h-1.5v-2.25H10v-1.5h2.25V9h1.5ZM0 9.661l7.005 2.71L9 11.598v1.687l-1.71.662a.791.791 0 0 1-.456.033l-.111-.033L0 11.348V9.662Zm0-3.48L7.005 8.89 14 6.186v1.687l-6.71 2.595a.781.781 0 0 1-.456.034l-.111-.034L0 7.869V6.181ZM7.135.015l.083.026L14 2.77v1.689L7.29 7.053a.791.791 0 0 1-.456.034l-.111-.034L0 4.455V2.767l.011.003L6.794.04a.566.566 0 0 1 .34-.026Zm-.13 1.257L1.717 3.431l5.288 2.044 5.312-2.055-5.312-2.148Z"/></svg>',
                tooltip: true
            } );
            
             button.on( 'execute', () => {
                editor.model.change( writer => {
                    editor.model.insertObject( creategalleryImport( writer, 'Gallery 2' , '151', 'background-image: url(https://catherineasquithgallery.com/uploads/posts/2021-02/1614385475_77-p-svetlo-zelenii-fon-abstraktsiya-80.jpg)') );
                } );
            } );

            return button;
        } );
        
      
    }
    
    _defineSchema() {                                                          
        const schema = this.editor.model.schema;

        schema.register( 'galleryImport', {
             inheritAllFrom: '$blockObject',
             allowContentOf: '$block',
             allowAttributes: [ 'id', 'title', 'style', 'class' ]
        } );
        
    }

    
   _defineConverters() {                                                      
        const conversion = this.editor.conversion;

        conversion.for( 'upcast' ).elementToElement( {
            view: {
                name: 'section',
                classes: 'gallery-box',
                attributes: [ 'id', 'title', 'style', 'class' ]
            },
            model: ( viewElement, { writer: viewWriter } ) => {
            
          const section = viewWriter.createElement( 'galleryImport', { id: viewElement.getAttribute( 'id' ), title: viewElement.getAttribute( 'title' ), style: viewElement.getAttribute( 'style' ),  class: 'gallery-box' } );
         
         return toWidget( section, viewWriter, { label: 'gallery box widget' } );
           
        }
        } );
        
        
        conversion.for( 'downcast' ).elementToElement( {
             model: {
            name: 'galleryImport',
            classes: 'gallery-box',
            attributes: [ 'id', 'title', 'style', 'class' ]
        },
            view: ( modelElement, { writer: viewWriter } ) => {
                const section = viewWriter.createContainerElement('section', { id: modelElement.getAttribute( 'id' ), title: modelElement.getAttribute( 'title' ), style: modelElement.getAttribute( 'style' ),  class: 'gallery-box' } );
                return toWidget( section, viewWriter, { label: 'simple box widget' } );
            }
        } );
        
    }
}



function creategalleryImport( writer , name, galleryid, imageUrl) {
    const galleryImport = writer.createElement( 'galleryImport', {id: galleryid, title: name, style: imageUrl});
    return galleryImport;
}

enter image description here

data that saves:

enter image description here

how to make it deleted and when saving?
there is probably an error in the code

How to improve slow redirects between pages in production of NextJS websites with custom server?

I have deployed my nextjs app in shared hosting in AWS EC2 with command

pm2 start npm –name “app_name” — start

But the production build is very slow. Redirection between the pages are very slow, like if I click on any button it takes forever to go to that page.

I am using custom server since I need to run the app in https which is not possible without custom server (as far as I know, feel free to guide on this).

My custom server.js look like:

// const { createServer } = require("https");
const http = require("http");
const https = require("https");
const { parse } = require("url");
const next = require("next");
const fs = require("fs");

const dev = process.env.NEXT_PUBLIC_ENVIRO !== "production";
const app = next({ dev });
const handle = app.getRequestHandler();

console.log(process.env.NEXT_PUBLIC_ENVIRO, "env variable");

let pKeyPath = "/etc/letsencrypt/live/appsinvo.co.uk/privkey.pem";
let cPath = "/etc/letsencrypt/live/appsinvo.co.uk/fullchain.pem";

const httpsOptions = {
  key: fs.readFileSync(pKeyPath),
  cert: fs.readFileSync(cPath),
};

app.prepare().then(() => {
  https
    .createServer(httpsOptions, async (req, res) => {
      await handle(req, res);
    })
    .listen(7000, (err) => {
      if (err) throw err;
      console.log("> Ready on https://localhost:443");
    });

  http
    .createServer((req, res) => {
      res.writeHead(301, {
        Location: `https://${req.headers.host}${req.url}`,
      });
      res.end();
  })
    .listen(7000, (err) => {
      if (err) throw err;
      console.log("> Ready on http://localhost:8080");
    });
});

My package.json file is as below:

"scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "node server.js",
    "lint": "next lint",
    "analyze": "cross-env ANALYZE=true next build",
    "analyze:server": "cross-env BUNDLE_ANALYZE=server next build",
    "analyze:browser": "cross-env BUNDLE_ANALYZE=browser next build"
},

The first render of the site is very slow. Below is what I am getting in the network tab.

enter image description here

If I check the first thing in the network tab which is basically the root path (“/”) of the website, it shows the below error:

enter image description here

Also the Javascript is loading before everything else like the main.ts, _app.ts which are heavy JS.

The first load of the app is also very high among the pages.

enter image description here

I googled and came across various articles and did all the package removal of unused dependencies and dynamic import of the component where necessary but still the first load of the components are very high. I also removed the prefect={false} from the Link imported from next/link.

So my questions are:

  1. How to make the first load of the page faster ?
  2. How to config the custom server for the production build ?
  3. How to reduce the first load js of all the components ?

Kindly help as I have been doing this for a week now and I am nowhere near a good user experience.

Switch between databases and perform operations with schema

Main objective is to create multi-database system. Here in index.js i’ve initialized a mongodb connection with test(db). In this orglist collection is present and it holds orgDomain and its database name.
task is to create a object in orglist collection and then automatically create new database from that orglist and switch to that database and use organization schema to insert organization info to the new organization db.

But the problem is orglist is created new database is not showing unless i create any collection in there. and then the organization info should have inserted into newly created db using the schema but it stores in the test(db). I did switch the db but it is not storing it in newdb

this is orglist schema

const mongoose = require('mongoose');

const orglistSchema = mongoose.Schema({
    orgDomain:{type:String, trim:true},
    dbName:{type:String, trim: true}
},{timestamps:true})

const orglist = mongoose.model('Orgs', orglistSchema);

module.exports = orglist;

This is organization schema:

const mongoose = require('mongoose');

const organizationSchema = new mongoose.Schema({
  organizationName: {
    type: String,
    required: true
  },
  orgDomain: {
    type: String,
    required: true,
    unique: true
  },
  userTyre: {
    type: Number,
    default: null,
  }
},{timestamps: true});


module.exports = mongoose.model('Organization', organizationSchema);

And this is the controller function:

const orglist = require('../models/adminEnd/niam')
const Organization = require('../models/adminEnd/organization')
const mongoose = require('mongoose')

function niamAdminController(){
    return{
        //add organization and its db from niam admin
        async addOrganization(req, res) {
            try {
              // Save org list details in main database
              const org = new orglist(req.body);
              const saveOrg = await org.save();
              //here it is saving properly in testdb

              // create newdb string
              const dbString = process.env.Mongoose_New_Db + '/' + org.dbName;
              console.log(dbString);
              
              //create new db
              const orgConnection = await mongoose.createConnection(dbString, {
                useNewUrlParser: true,
                useUnifiedTopology: true,
              });
              orgConnection.on('open', () => {
                console.log(`Connection  successful!`);
              });

              const db = orgConnection.useDb(org.dbName); // switch to the new database

              const orgDoc = new Organization({
                organizationName: org.dbName,
                orgDomain: org.orgDomain,
                userTyre: 10000,
              });
              await orgDoc.save();
              //but this save() is done in test db not into the switched db.
              console.log('Org info created');
              
              res.status(201).json({
                success: true,
                message: "New organization created.",
                data: saveOrg
              });
            } catch (err) {
              console.log(err);
              res.status(500).json({
                success: false,
                message: err.message
              });
            }
          }
          
    }
}

module.exports = adminController

For what my organization details in second part of controller is also inserted into initial test(db)

If the server doesn’t change the settings, can’t I stop CORS ERROR?

It accesses localhost:5500 and only images and videos are called to different sources (https://sitename.com, tentatively named). It’s not working properly. The error message is the same as the console window message below. I added 'console.log ('loadedImage: ${loadedImage}');' code to the image.js file. However, only undefined is output.

Is it because of the CORS error? Is there a way to change it from localhost without changing the settings on the https://sitename.com (tentative) server? In this case, I can install the “Allow CORS: Access-Control-Allow-Origin” plug-in of the Chrome browser, but if you look at the screenshot below, the GET command can be ALLOW, but it can be DENY. Or I can do it as a proxy server, but can I get the image without a CORS error without changing the settings on the https://sitename.com (tentative name) server?

./assets/script/utils/image.js

const LAZY_LOADED_IMAGES = []
const LOADED_IMAGES = []

export function loadImage(url, options = {}) {
    return new Promise((resolve, reject) => {

        let loadedImage = LOADED_IMAGES.find(image => image.url === url)
        console.log(`loadedImage : ${loadedImage}`);

        {...}
}

console windows

loadedImage : undefined
localhost/:1 Access to image at 'https://sitename.com/test.png' from origin
'http://localhost:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin'
header is present on the requested resource.
app.js:4694          GET https://sitename.com/test.png net::ERR_FAILED 200

Test CORS

TypeError: Cannot read property ‘model_config’ of undefined

Been trying to load this model in my expressjs app for sentiment analysis but have been seeing a few issues with it but have been stuck on this one with no progress. I’m fairly curtain my path is correct as well but just in case here’s my full path to model.json

C:/dev/AI-GroupProject/ExpressApiProject/model.json

This is my code for creating the model and saving it in case it helps

import tensorflow as tf
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import Dense, Embedding, GlobalAveragePooling1D
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.preprocessing.sequence import pad_sequences
import os
import json

# Load the dataset
data = pd.read_csv(os.getcwd() + "/datasets/sentiment labelled sentences/amazon_cells_labelled.txt", delimiter="t", header=None)
sentences = data[0].tolist()
labels = np.array(data[1].tolist())

# Split the data into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(sentences, labels, test_size=0.2, random_state=42)

# Tokenize the data
tokenizer = Tokenizer(num_words=10000, oov_token="<OOV>")
tokenizer.fit_on_texts(X_train)

# Save the tokenizer object as a JSON file
tokenizer_json = tokenizer.to_json()
with open('tokenizer.json', 'w', encoding='utf-8') as f:
    f.write(json.dumps(tokenizer_json, ensure_ascii=False))

# Convert the text to sequences
train_sequences = tokenizer.texts_to_sequences(X_train)
test_sequences = tokenizer.texts_to_sequences(X_test)

# Pad the sequences to the same length
train_padded = pad_sequences(train_sequences, maxlen=100, padding='post', truncating='post')
test_padded = pad_sequences(test_sequences, maxlen=100, padding='post', truncating='post')

# Define the model
model = Sequential([
    Embedding(input_dim=10000, output_dim=16, input_length=100),
    GlobalAveragePooling1D(),
    Dense(1, activation='sigmoid')
])

# Compile the model
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])

# Train the model
model.fit(train_padded, y_train, epochs=10, batch_size=32, validation_data=(test_padded, y_test))

# Save the model
model_json = model.to_json()
with open('sentiment_model.json', 'w') as f:
    f.write(model_json)

# Load the model
with open('sentiment_model.json', 'r') as f:
    model_json = f.read()
    loaded_model = tf.keras.models.model_from_json(model_json)

# Load the tokenizer object from the JSON file
with open('tokenizer.json', 'r', encoding='utf-8') as f:
    tokenizer_json = json.load(f)
    tokenizer = tf.keras.preprocessing.text.tokenizer_from_json(tokenizer_json)

# Example usage of the loaded model
example_text = ["This movie was terrible"]
example_sequence = tokenizer.texts_to_sequences(example_text)
example_padded = pad_sequences(example_sequence, maxlen=100, padding='post', truncating='post')
prediction = loaded_model.predict(example_padded)
print(prediction)

And this is the code in the express app and it fails when loading the model
const loadedModel = await tf.loadLayersModel(MODEL_PATH);

const express = require('express');
const bodyParser = require('body-parser');
const tf = require('@tensorflow/tfjs');
const fs = require('fs');
require('@tensorflow/tfjs-node');

async function loadModel() {
    // Load the saved model
    const MODEL_PATH = 'file:///dev/AI-GroupProject/ExpressApiProject/model.json';
    console.log("Loading Model")
    const loadedModel = await tf.loadLayersModel(MODEL_PATH);
    console.log("Model loaded");
    return loadedModel;
  }


// Initialize the Express app
const app = express();

// Use the body-parser middleware to parse request bodies as JSON
app.use(bodyParser.json());

// Define a route to handle sentiment analysis requests
app.post('/', async (req, res) => {
    try {
      // Load the model
      const loadedModel = await loadModel();
  
      // Get the text to analyze from the request body
      const { sentence } = req.body;
      const text = sentence.text;
  
      // Tokenize and pad the text
      const tokenizerJson = fs.readFileSync(__dirname + '/tokenizer.json', 'utf-8');
      const tokenizer = tf.keras.preprocessing.text.tokenizer_from_json(tokenizerJson);
      const textSequences = tokenizer.textsToSequences([text]);
      const paddedSequences = tf.keras.preprocessing.sequence.padSequences(
          [textSequences],
          { maxlen: 100, padding: 'post', truncating: 'post' }
        );
  
      // Make a prediction with the loaded model
      const prediction = loadedModel.predict(paddedSequences);
  
      // Extract the prediction score
      const score = prediction.dataSync()[0];
  
      // Return the sentiment prediction as a JSON response
      res.json({
        sentiment: score >= 0.5 ? 'positive' : 'negative',
        score
      });
    } catch (error) {
      // Handle errors by returning a 500 Internal Server Error response
      console.error(error);
      res.status(500).json({ error: error.message });
    }
  });

// Start the server
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});
[nodemon] 2.0.22
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node server.js`
Debugger attached.
2023-04-09 05:53:24.918929: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neural Network Library (oneDNN) to use the following CPU instructions in performance-critical operations:  AVX2
To enable them in other operations, rebuild TensorFlow with the appropriate compiler flags.
Server listening on port 3000
Loading Model
TypeError: Cannot read property 'model_config' of undefined
    at C:devAI-GroupProjectExpressApiProjectnode_modules@tensorflowtfjs-layersdisttf-layers.node.js:25405:38
    at step (C:devAI-GroupProjectExpressApiProjectnode_modules@tensorflowtfjs-layersdisttf-layers.node.js:162:27)
    at Object.next (C:devAI-GroupProjectExpressApiProjectnode_modules@tensorflowtfjs-layersdisttf-layers.node.js:111:53)
    at fulfilled (C:devAI-GroupProjectExpressApiProjectnode_modules@tensorflowtfjs-layersdisttf-layers.node.js:92:28)

Iven been working to try and find a solution for a while and I’m stumped, though I’m kind of new to working with tensorflow and js so if you notice anything else I’ve done wrong please let me know.

Firebase Analytics ReferenceError

I just try to use Firebase Cloud Firestore with analytic service here is my index.js:

// Import the functions you need from the SDKs you need
import { initializeApp } from "firebase/app";
import { getAnalytics } from "firebase/analytics";
import { getFirestore, collection, getDocs } from 'firebase/firestore/lite';
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries

// Your web app's Firebase configuration
// For Firebase JS SDK v7.20.0 and later, measurementId is optional
const firebaseConfig = {
  //someConfigAreAlreadyHere
};

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const analytics = getAnalytics(app);
const db = getFirestore(app);

async function getAccount(db) {
    const Account = collection(db, 'Account');
    const accountSnapshot = await getDocs(citiesCol);
    const accountList = accountSnapshot.docs.map(doc => doc.data());
    return accountList;
  }

console.log(getAccount(db))

index.esm2017.js are all is default (It too long I can’t show it in this post)

and I got this error:

ReferenceError: window is not defined
    at getOrCreateDataLayer (file:///D:/website/node_modules/@firebase/analytics/dist/esm/index.esm2017.js:176:23)
    at factory (file:///D:/website/node_modules/@firebase/analytics/dist/esm/index.esm2017.js:1010:9)
    at Component.instanceFactory (file:///D:/website/node_modules/@firebase/analytics/dist/esm/index.esm2017.js:1205:16)
    at Provider.getOrInitializeService (file:///D:/website/node_modules/@firebase/component/dist/esm/index.esm2017.js:290:39)
    at Provider.initialize (file:///D:/website/node_modules/@firebase/component/dist/esm/index.esm2017.js:234:31)
    at initializeAnalytics (file:///D:/website/node_modules/@firebase/analytics/dist/esm/index.esm2017.js:1059:49)
    at getAnalytics (file:///D:/website/node_modules/@firebase/analytics/dist/esm/index.esm2017.js:1038:12)
    at file:///D:/website/index.js:22:19
    at ModuleJob.run (node:internal/modules/esm/module_job:194:25)

problem with typer in javascript for RTL language

I want to use typer animation for Persian language. so I use below codes:

HTML:

`<h1 class="cd-headline letters rotate-3">محصولات دیجیتالی برای <span class="cd-words-wrapper">                             <b class="is-visible">فروش آنلاین</b>                             <b>تبلیغات و ارتقای وب‌سایت</b>                             <b>افزایش فروش</b>                         </span> </h1>`

CSS:

`@keyframes cd-rotate-3-in {   0% {     transform: rotateY(180deg);   }   100% {     transform: rotateY(0deg);   } } @keyframes cd-rotate-3-out {   0% {     transform: rotateY(0);   }   100% {     transform: rotateY(-180deg);   } } .appseo-banner-section .cd-headline.rotate-3 i.in {   animation: cd-rotate-3-in 0.6s forwards; }  .appseo-banner-section .cd-headline.rotate-3 i.out {   animation: cd-rotate-3-out 0.6s forwards; }`

JS:

`jQuery(document).ready(function($){    //set animation timing  var animationDelay = 2500,      //loading bar effect        barAnimationDelay = 3800,       barWaiting = barAnimationDelay - 3000, //3000 is the duration of the transition on the loading bar - set in the scss/css file       //letters effect        lettersDelay = 50,      //type effect       typeLettersDelay = 150,         selectionDuration = 500,        typeAnimationDelay = selectionDuration + 800,       //clip effect       revealDuration = 600,       revealAnimationDelay = 1500;        initHeadline();         function initHeadline() {       //insert <i> element for each letter of a changing word         singleLetters($('.cd-headline.letters').find('b'));         //initialise headline animation         animateHeadline($('.cd-headline'));     }   function singleLetters($words) {        $words.each(function(){             var word = $(this),                 letters = word.text().split(''),                selected = word.hasClass('is-visible');             for (i in letters) {                if(word.parents('.rotate-2').length > 0) letters[i] = '<em>' + letters[i] + '</em>';                letters[i] = (selected) ? '<i class="in">' + letters[i] + '</i>': '<i>' + letters[i] + '</i>';          }           var newLetters = letters.join('');          word.html(newLetters).css('opacity', 1);        });     }   function animateHeadline($headlines) {      var duration = animationDelay;      $headlines.each(function(){             var headline = $(this);                         if(headline.hasClass('loading-bar')) {              duration = barAnimationDelay;               setTimeout(function(){ headline.find('.cd-words-wrapper').addClass('is-loading') }, barWaiting);            } else if (headline.hasClass('clip')){              var spanWrapper = headline.find('.cd-words-wrapper'),                   newWidth = spanWrapper.width() + 10                 spanWrapper.css('width', newWidth);             } else if (!headline.hasClass('type') ) {               //assign to .cd-words-wrapper the width of its longest word                 var words = headline.find('.cd-words-wrapper b'),                   width = 0;              words.each(function(){                  var wordWidth = $(this).width();                    if (wordWidth > width) width = wordWidth;               });                 headline.find('.cd-words-wrapper').css('width', width);             };              //trigger animation             setTimeout(function(){ hideWord( headline.find('.is-visible').eq(0) ) }, duration);         });     }   function hideWord($word) {      var nextWord = takeNext($word);                 if($word.parents('.cd-headline').hasClass('type')) {            var parentSpan = $word.parent('.cd-words-wrapper');             parentSpan.addClass('selected').removeClass('waiting');             setTimeout(function(){                  parentSpan.removeClass('selected');                 $word.removeClass('is-visible').addClass('is-hidden').children('i').removeClass('in').addClass('out');          }, selectionDuration);          setTimeout(function(){ showWord(nextWord, typeLettersDelay) }, typeAnimationDelay);                 } else if($word.parents('.cd-headline').hasClass('letters')) {          var bool = ($word.children('i').length >= nextWord.children('i').length) ? true : false;            hideLetter($word.find('i').eq(0), $word, bool, lettersDelay);           showLetter(nextWord.find('i').eq(0), nextWord, bool, lettersDelay);         }  else if($word.parents('.cd-headline').hasClass('clip')) {            $word.parents('.cd-words-wrapper').animate({ width : '2px' }, revealDuration, function(){               switchWord($word, nextWord);                showWord(nextWord);             });         } else if ($word.parents('.cd-headline').hasClass('loading-bar')){          $word.parents('.cd-words-wrapper').removeClass('is-loading');           switchWord($word, nextWord);            setTimeout(function(){ hideWord(nextWord) }, barAnimationDelay);            setTimeout(function(){ $word.parents('.cd-words-wrapper').addClass('is-loading') }, barWaiting);        } else {            switchWord($word, nextWord);            setTimeout(function(){ hideWord(nextWord) }, animationDelay);       }   }   function showWord($word, $duration) {       if($word.parents('.cd-headline').hasClass('type')) {            showLetter($word.find('i').eq(0), $word, false, $duration);             $word.addClass('is-visible').removeClass('is-hidden');          }  else if($word.parents('.cd-headline').hasClass('clip')) {            $word.parents('.cd-words-wrapper').animate({ 'width' : $word.width() + 10 }, revealDuration, function(){                setTimeout(function(){ hideWord($word) }, revealAnimationDelay);            });         }   }   function hideLetter($letter, $word, $bool, $duration) {         $letter.removeClass('in').addClass('out');              if(!$letter.is(':last-child')) {            setTimeout(function(){ hideLetter($letter.next(), $word, $bool, $duration); }, $duration);          } else if($bool) {              setTimeout(function(){ hideWord(takeNext($word)) }, animationDelay);        }       if($letter.is(':last-child') && $('html').hasClass('no-csstransitions')) {          var nextWord = takeNext($word);             switchWord($word, nextWord);        }   }   function showLetter($letter, $word, $bool, $duration) {         $letter.addClass('in').removeClass('out');              if(!$letter.is(':last-child')) {            setTimeout(function(){ showLetter($letter.next(), $word, $bool, $duration); }, $duration);          } else {            if($word.parents('.cd-headline').hasClass('type')) { setTimeout(function(){ $word.parents('.cd-words-wrapper').addClass('waiting'); }, 200);}           if(!$bool) { setTimeout(function(){ hideWord($word) }, animationDelay) }        }   }   function takeNext($word) {      return (!$word.is(':last-child')) ? $word.next() : $word.parent().children().eq(0);     }   function takePrev($word) {      return (!$word.is(':first-child')) ? $word.prev() : $word.parent().children().last();   }   function switchWord($oldWord, $newWord) {       $oldWord.removeClass('is-visible').addClass('is-hidden');       $newWord.removeClass('is-hidden').addClass('is-visible');   } });`

Add text when Touch Screen in new changed background

I want to ask about this.

<script>
    let currentText = 1;
    const textElement1 = document.getElementById("text1");
    const textElement2 = document.getElementById("text2");
    const textElement3 = document.getElementById("text3");
    const textElement4 = document.getElementById("text4");
    const textElement5 = document.getElementById("text5");
    const textElement6 = document.getElementById("text6");
    const textElement7 = document.getElementById("text7");
    const textElement8 = document.getElementById("text8");
    const textElement9 = document.getElementById("text9");
    const textElement10 = document.getElementById("kata1");
    const imageArrow = document.getElementById("panah");
    const malam = document.getElementById("malam");
    const bg = document.getElementById("bg");
    const pet1 = document.getElementById("petasan1");
    const pet2 = document.getElementById("petasan2");
    

    function showText() {
        if (currentText === 1) {
        textElement1.style.display = "none";
        textElement2.style.display = "block";
        currentText = 2;
        } else if (currentText === 2) {
        textElement2.style.display = "none";
        textElement3.style.display = "block";
        currentText = 3;
        } else if (currentText === 3) {
        textElement3.style.display = "none";
        textElement4.style.display = "block";
        currentText = 4;
        } else if (currentText === 4){
        textElement4.style.display = "none";
        textElement5.style.display = "block";
        currentText = 5;
        } else if(currentText === 5){
        textElement5.style.display = "none";
        textElement6.style.display = "block";
        currentText = 6;
        } else if(currentText === 6){
        textElement6.style.display = "none";
        textElement7.style.display = "block";
        currentText = 7;
        } else if(currentText === 7){
        textElement7.style.display = "none";
        textElement8.style.display = "block";
        currentText = 8;
        } else if(currentText === 8){
        textElement8.style.display = "none";
        textElement9.style.display = "block";
        currentText = 9;
        } else if(currentText === 9){
        textElement9.style.display = "none";
        imageArrow.style.display = "block";
        } else {
        textElement9.style.display = "none";
        imageArrow.style.display = "none";
        malam.style.display = "block";
        }
    }
    
    document.body.ontouchstart = showText;
    imageArrow.addEventListener("click", function() {
    imageArrow.style.display = "none";
    pet1.style.display = "none";
    pet2.style.display = "none";
    bg.style.backgroundImage = "url(https://i.pinimg.com/originals/10/09/5a/10095a7903ca4102466641bd76e41b0f.gif)";
    textElement10.style.display = "block";
}

);

This is my code, in this code when I clik imageArrow the background changed and textElement10 showing in that new background image. What i want is, after that textElement10 is showing, and I touch the screen again, another new text will show, like showText() before. Please help me, I’ve tried various ways, but still can’t find a way

Import module in javascript

I am currently trying to use a function to export a html table to an excel file. The problem is whenever i try to call the modules needed it returns an error

Here’s the code:

import XLSX from 'xlsx'

function CalculateMedia(){

    const wb = XLSX.readFile('C:/Users/pedro/Downloads/WebsiteFinal/assets/ExcelTemplate.xlsx');
    const ws = wb.Sheets['Folha1'];

    ws['B1'] = { t: 'n', v: pt10 };
    ws['C2'] = { t: 'n', v: pt11 };
    ws['D3'] = { t: 'n', v: pt12 };

    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });

    const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' });

    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'result.xlsx';
    document.body.appendChild(link);
    link.click();

    setTimeout(function () {
        window.URL.revokeObjectURL(url);
        document.body.removeChild(link);
    }, 0);

}

function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i < s.length; i++) {
        view[i] = s.charCodeAt(i) & 0xff;
    }
    return buf;
}

Error:
error

Also tried to use const XLSX = require('xlsx'); but is says require is not defined

Why are cllient components not working – NextJS 13.3.0 experimental features

As I understand the beta docs, I need to use "use client" at top of my client component to be defined as one, and I can use it inside server components, leaves or layouts.

With that so, here’s my code.

ClientComponent.js

"use client";

export default function ClientComponent() {
  return (
    <div>
        <h1>This is a client component!</h1>
    </div>
  )
}

ServerComponent.js

import ClientComponent from "./ClientComponent"

export default function ServerComponent() 
{

    return (
        <div>
            <h1>This is a server component!</h1>
            <ClientComponent/>
        </div>
    )
}

Page.js (Leaf)

import { Inter } from 'next/font/google'

import ServerComponent from './ServerComponent';

const inter = Inter({ subsets: ['latin'] })

export default function Home() {
  return (
    <main styles={inter.className}>
      <ServerComponent/>
    </main>
  )
}

But I get this error:

Unhandled Runtime Error

SyntaxError: “undefined” is not valid JSON

Call Stack JSON.parse

React

parseModel

node_modulesnextdistcompiledreact-server-dom-webpackcjsreact-server-dom-webpack-client.browser.development.js
(33:0)

resolveModule

node_modulesnextdistcompiledreact-server-dom-webpackcjsreact-server-dom-webpack-client.browser.development.js
(749:0)

processFullRow

node_modulesnextdistcompiledreact-server-dom-webpackcjsreact-server-dom-webpack-client.browser.development.js
(825:0)

processBinaryChunk

node_modulesnextdistcompiledreact-server-dom-webpackcjsreact-server-dom-webpack-client.browser.development.js
(869:0)

progress

node_modulesnextdistcompiledreact-server-dom-webpackcjsreact-server-dom-webpack-client.browser.development.js
(1476:0)

Even if I put directly the client component inside <main> in the leaf, it appears the same error. I do not understand what’s happening as I’d followed the docs. Can someone help?

EDIT: This only happen when client components are added anywhere to the code.

Toogle individual classes with JavaScript

I am learning to code by myself and started with html, css and javascript. I am trying to code two boxes that expand and hide/shoe text but individually. The problem is that both boxes expand when clicking on one button even if only one makes the text visible. I tried assingning individual classes to all css elements, but this did not help. Could it be related to the js .active class? is it possible to define .active further to apply it only to one element?

A) Both boxes collapsed, visibility hidden, that is ok

B) Left box expanded, text of the left box visible, but the right box should not expand

C) Righ box expanded, text of right box visible, but the left box should not expand and remain like in pic A. It is possible to hide and show text too but it should stay collapsed

I am not sure where to look for the error. Thank you for your help 🙂

  • assigned individual classes to all css elements, but this did not work, how should I approach this?

I want to See code behind the application for learning purposes. But can’t open the exe file in VSC

I want to See code behind the application for learning purposes. But can’t open the exe file in VSC
This is the download link of the files,
This is a bot which help you trade very quickly in crypto currency on different exchanges this is a trading bot.

Official website of the bot https://pump-bot.com/
This bot has the leicence key also.

Response Time: I will try to response ASAP in few hours. Everyone’s help is appreciated

below is the example of the bot working:-

Note:- It runs on CMD type window popup



 ██████╗ ██╗   ██╗███╗   ███╗██████╗ ██████╗  ██████╗ ████████╗
 ██╔══██╗██║   ██║████╗ ████║██╔══██╗██╔══██╗██╔═══██╗╚══██╔══╝
 ██████╔╝██║   ██║██╔████╔██║██████╔╝██████╔╝██║   ██║   ██║
 ██╔═══╝ ██║   ██║██║╚██╔╝██║██╔═══╝ ██╔══██╗██║   ██║   ██║
 ██║     ╚██████╔╝██║ ╚═╝ ██║██║     ██████╔╝╚██████╔╝   ██║
 ╚═╝      ╚═════╝ ╚═╝     ╚═╝╚═╝     ╚═════╝  ╚═════╝    ╚═╝

 ██╗  ██╗ ██████╗ ████████╗██████╗ ██╗████████╗
 ██║  ██║██╔═══██╗╚══██╔══╝██╔══██╗██║╚══██╔══╝
 ███████║██║   ██║   ██║   ██████╔╝██║   ██║
 ██╔══██║██║   ██║   ██║   ██╔══██╗██║   ██║
 ██║  ██║╚██████╔╝   ██║   ██████╔╝██║   ██║
 ╚═╝  ╚═╝ ╚═════╝    ╚═╝   ╚═════╝ ╚═╝   ╚═╝

by PumpBot!

DISCORD: https://discord.gg/EbwQtV6RaE | WEBSITE: https://pump-bot.com/

=====================================================================================

Hello Shreyansh Singh,
Welcome to your PumpBot. Program is ready to use and will now start.

Checking Cookies: True

=================================== PumpBot Pro =====================================
-> License is correct
Hit 'Enter' to load all Prices.
2023-04-06 19:00:09.789: Success: Bot is ready to use!
=====================================================================================
2023-04-06 19:00:09.789: ===> Loaded all prices with Success
------------------------------ Enter the Coin Name manual ---------------------------
2023-04-06 19:00:09.789: Enter the Coin name and hit 'Enter': BTFA
2023-04-06 19:00:13.058: Entered Coin Name Manual BTFA
===================================== BUY ORDER =====================================
2023-04-06 19:00:13.068: Buy Order sent to Hotbit.
2023-04-06 19:00:13.762: Hotbit sent OrderId: {'Code': 1100, 'Msg': 'success', 'Content': {'id': 148259156010}}
2023-04-06 19:00:14.763: Cancel the Buy Order...
2023-04-06 19:00:14.996: Go checking the order
2023-04-06 19:00:14.996: ===> Open the Web Browser
2023-04-06 19:00:15.064: Get Buy Order Details

-------------------------------- Buy OrderDetails -----------------------------------
BuyTime:     Tue, 20 Jan 1970 16:23:27
Status:      0
Amount:      92463000
Price:       3.4990000000000003e-07
--------------------------------------------------------------------------------------

2023-04-06 19:00:15.787: ===> Selling Part
-------------------------------------------------------------------------------------
===================================== SELLING PART ==================================
!!! Clicking into this Screen will Stop the PumpBot !!!!
Start Stream - dont click into this Window or you stop the Bot.
Timestamp           | Price Change in % | Buy Price | Seconds since Buy
Start Stream
2023-04-06 19:00:16.583 | -0.0 % | 3.4990000000000003e-07 BTFA/USDT  | 0.8 seconds
2023-04-06 19:00:17.318 | -0.0 % | 3.4990000000000003e-07 BTFA/USDT  | 1.53 seconds
2023-04-06 19:00:18.058 | -0.0 % | 3.4990000000000003e-07 BTFA/USDT  | 2.27 seconds
2023-04-06 19:00:18.802 | -0.0 % | 3.4990000000000003e-07 BTFA/USDT  | 3.02 seconds
2023-04-06 19:00:19.825 | -0.0 % | 3.4990000000000003e-07 BTFA/USDT  | 4.04 seconds
2023-04-06 19:00:20.575 | -42.9 % | 3.4990000000000003e-07 BTFA/USDT  | 4.79 seconds
2023-04-06 19:00:21.318 | -42.9 % | 3.4990000000000003e-07 BTFA/USDT  | 5.53 seconds
2023-04-06 19:00:22.082 | -42.9 % | 3.4990000000000003e-07 BTFA/USDT  | 6.3 seconds
2023-04-06 19:00:22.828 | -0.0 % | 3.4990000000000003e-07 BTFA/USDT  | 7.04 seconds
2023-04-06 19:00:23.554 | -0.09 % | 3.4990000000000003e-07 BTFA/USDT  | 7.77 seconds
2023-04-06 19:00:24.261 | -0.09 % | 3.4990000000000003e-07 BTFA/USDT  | 8.48 seconds
2023-04-06 19:00:25.094 | -0.09 % | 3.4990000000000003e-07 BTFA/USDT  | 9.31 seconds
2023-04-06 19:00:25.792 | -0.09 % | 3.4990000000000003e-07 BTFA/USDT  | 10.01 seconds
2023-04-06 19:00:26.483 | -0.09 % | 3.4990000000000003e-07 BTFA/USDT  | 10.7 seconds
2023-04-06 19:00:27.241 | -0.09 % | 3.4990000000000003e-07 BTFA/USDT  | 11.45 seconds
2023-04-06 19:00:27.983 | -0.03 % | 3.4990000000000003e-07 BTFA/USDT  | 12.2 seconds
2023-04-06 19:00:28.728 | -0.03 % | 3.4990000000000003e-07 BTFA/USDT  | 12.94 seconds
2023-04-06 19:00:29.455 | -0.03 % | 3.4990000000000003e-07 BTFA/USDT  | 13.67 seconds
2023-04-06 19:00:30.145 | -0.03 % | 3.4990000000000003e-07 BTFA/USDT  | 14.36 seconds
2023-04-06 19:00:30.875 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 15.09 seconds
2023-04-06 19:00:31.573 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 15.79 seconds
2023-04-06 19:00:32.270 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 16.48 seconds
2023-04-06 19:00:32.990 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 17.2 seconds
2023-04-06 19:00:33.706 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 17.92 seconds
2023-04-06 19:00:34.441 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 18.65 seconds
2023-04-06 19:00:35.176 | 54.9 % | 3.4990000000000003e-07 BTFA/USDT  | 19.39 seconds
2023-04-06 19:00:35.873 | 54.9 % | 3.4990000000000003e-07 BTFA/USDT  | 20.09 seconds
2023-04-06 19:00:36.609 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 20.82 seconds
2023-04-06 19:00:37.368 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 21.58 seconds
2023-04-06 19:00:38.067 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 22.28 seconds
2023-04-06 19:00:38.773 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 22.99 seconds
2023-04-06 19:00:39.486 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 23.7 seconds
2023-04-06 19:00:40.194 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 24.41 seconds
2023-04-06 19:00:40.916 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 25.13 seconds
2023-04-06 19:00:41.621 | 54.9 % | 3.4990000000000003e-07 BTFA/USDT  | 25.83 seconds
2023-04-06 19:00:42.373 | 26.32 % | 3.4990000000000003e-07 BTFA/USDT  | 26.59 seconds

2023-04-06 19:00:42.970 | -0.0 % | 3.4990000000000003e-07 BTFA/USDT  | 27.18 seconds

2023-04-06 19:00:42.971: Sell Order sent
2023-04-06 19:00:43.216: Sell Order details returned: {"Code":1100,"Msg":"success","Content":{"id":148259223277}}
2023-04-06 19:00:43.216: CHECK THE EXCHANGE: Your Limit Sell Order was sent.
2023-04-06 19:00:43.217: PumBot Hotbit - Done. Cya the next time! ;-)
=====================================================================================
2023-04-06 19:00:43.217: Bot from: https://pump-bot.com/
Bye Shreyansh Singh.
Hit 'Enter' to exit the PumpBot.

I was trying to learn how this bot is trading so fast and easily with simple commands in CMD.
and I want to make such bot for learning purpose. I might make these bots for commercial purposes also. Depends on my mind 🙂