Disable scrolling without jumpy behaviour, or without it stoping dead on it’s tracks

Hello and good evening.

I’m trying to make scrolling impossible upon reaching a certain div, and making it possible again after another. Problem is between those I want to move between divs through anchors.

Let’s say this is my html:

<div id="plano1" class="plano">
<div id="plano2" class="plano">
<div id="plano3" class="planoslide"><a href="#plano4"><button onclick="enableScroll()"><a>
<div id="plano4" class="planoslide"><a href="#plano5"><button onclick="enableScroll()"><a>
<div id="plano5" class="plano">

I want to make scrolling disabled upon entering the class .planoslide. I have two functions which add or remove the class .stop-scrolling which has the usual height:100% and overflow:hidden. The funcion disableScroll is activated upon entering the planoslide class but it stops dead in its tracks either mid heigh, or if I scroll to much even after it. So I had to animate it almost upon entering the div so that offsets to the right place. Right now this is my code:

function disableScroll() {
$('body').addClass('stop-scrolling');
$('body').bind('touchmove', function(e){e.preventDefault()})
}

function enableScroll() {
$('body').removeClass('stop-scrolling');
$('body').unbind('touchmove');
}

$(window).bind('scroll', function() {
  if($(window).scrollTop() >= ($('.planoslide').offset().top + $('.planoslide').outerHeight() - window.innerHeight)*0.1) {
    disableScroll();
    $('html,body').animate({
      scrollTop: $(".planoslide").offset().top},
      2000);
  }
}); 

Problem is when i use the button with onclick to enable the scroll again nothing happens.
I wished it would not only enable the scroll back again but navigate to the supposed ID I send it to.

Also the first enableScroll should enable it and disable again upon entering the new .planoslide, but that one I haven’t gotten to yet.

Help would be much aprecciated.

Best regards.

Creating a server like pusher using websocket nodejs

I have a big question regarding Websocket.

Well, let’s go..
What am I needing? I need to add in my application a way to notify my user in real time about things that happen in the backend, for example, let’s say that some administrator has updated the user’s data, then that same user needs to receive a notification saying that the data has changed.

Challenges in this process.
1st – I need to save a unique ID of the user connected to the websocket, for that I’m using the “getUniqueID” function that I’ve seen in other posts, the question in this case would be, could I save the id that was generated in the database referring to the logged in user? is it a good alternative?

2nd I need that when the registry is updating send the message to the user, in case I need to trigger the notification coming from the Controller, the question is, how do I access the WSS variable once it was instantiated when the server was turned on?

Below I’m putting my 2 files that I’m using to turn on the server.

appSocket.js

import WebSocket from "ws";
import { Server } from "socket.io";

function onError(ws, err) {
    console.error(`onError: ${err.message}`);
}

function onMessage(ws, data) {
    console.log(`onMessage: ${data}`);
    ws.send(`recebido!`);
}

function onConnection(ws, request) {     
    ws.on('message', data => onMessage(ws, data));
    ws.on('error', error => onError(ws, error));
    ws.id = request.headers['sec-websocket-key']; 
    console.log("WS ID = "+ws.id)
}

export default (server) => {
    // const wss = new Server(server);
    const wss = new WebSocket.Server({
        server
    });

    wss.getUniqueID = function () {
        function s4() {
            return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
        }
        return s4() + s4() + '-' + s4();
    };
    
    wss.on('connection', onConnection);

    console.log(`App Web Socket Server is running!`);
    return wss;
}

My App.js

// import app from './app';
import appWs from './app-socket';
import express from 'express';
import cors from 'cors';
import helmet from 'helmet';
import morgan from 'morgan';
import dotenv from 'dotenv';
import {i18n} from './i18n';
import routes from './routes';
import bodyParser from 'body-parser';

var multer = require('multer');
var upload = multer();
const path = require('path');
dotenv.config();

class App {
    constructor() {
      this.express = express();
  
      this.database();
      this.middlewares();
      this.routes();
    
      const server = this.express.listen(process.env.PORT || 3000, () => {
        console.log(`Welcome to  => PORT ${process.env.PORT || 3000}`);
      });

      appWs(server);
    }
  
    database() {
      //      
    }
  
    middlewares() {
      this.express.use(cors({ origin: process.env.CORS_ORIGIN || '*' }));
      this.express.use(helmet());      
      this.express.use(morgan('dev'));
      this.express.use(express.json());      
      this.express.use(express.static(path.join(__dirname,'public')));
      // for parsing application/json
      this.express.use(bodyParser.json()); 
      // for parsing application/xwww-
      this.express.use(bodyParser.urlencoded({ extended: true })); 
      //form-urlencoded
      // for parsing multipart/form-data
      this.express.use(upload.array()); 

      let appExpress = this.express;
      i18n.init({ appExpress });     
    }
  
    routes() {
      this.express.use(routes);
    }
  }
  export default new App().express;

POST Request from JS to FastAPI geting “422 Unprocessable Entity”

I’m starting to work on a project with React and FastAPI.

On the server side:

from fastapi import APIRouter, Request, Depends, Response, encoders
import typing
import datetime

from app.db.session import get_db
from app.db.crud import (
    create_lead,
)
from app.db.schemas import LeadCreate


leads_router = r = APIRouter()


@r.post("/leads", response_model=LeadCreate)
async def lead_create(
    # request: Request,
    lead: LeadCreate,
    db=Depends(get_db),
):
    lead.datetime_insert = datetime.datetime.now()
    return create_lead(db, lead)
from pydantic import BaseModel
import datetime


class LeadCreate(BaseModel):
    email: str
    source: str
    datetime_insert: datetime.datetime

    class Config:
        orm_mode = True
from sqlalchemy import Boolean, Column, Integer, String, DateTime

from .session import Base


class Lead(Base):
    __tablename__ = "lead"

    id = Column(Integer, primary_key=True, index=True)
    email = Column(String)
    source = Column(String)
    datetime_insert = Column(DateTime)

In frontend side:

export const create_lead = async (email: string, source: string) => {
    if (!(email.length > 0)) {
        throw new Error('Email was not provided');
    }

    const d = {"email": email,
               "source": source,
               "datetime_insert": "",}

    const request = new Request('/api/v1/leads', {
        method: 'POST',
        body: JSON.stringify(d),
    });

    const response = await fetch(request);

    if (response.status === 500) {
        throw new Error('Internal server error');
    }

    const data = await response.json();

    if (response.status > 400 && response.status < 500) {
        if (data.detail) {
          throw data.detail;
        }
        throw data;
    }

    return data;
};

However, I’m getting the following error in the backend log:
"POST /api/v1/leads HTTP/1.0" 422 Unprocessable Entity

I have already tried to use FormData. I think it is related to the data structure, where the frontend side is sending something different than the expected by server-side.

Poblem with embed message discord js

Hello everyone I have a problem with embed messages in discord js.
I have a variable which is storing text “.addField(“text”, “text”, false)” and I want to use this stored text in the embed message

Example

var fields = ".addField("text", "text", false).addField("text", "text", false);
const embedmessage = new Discord.MessageEmbed()
.setTitle("title")
.setDescription("description")
.setColor("#f2320c")

and I want to add this variable named fields to the end of this embed message. How can i do it?

Sorry for my english but I hope it isn’t a problem ;/

Trying to make a function that prints an array range. I’m given the start, stop and step values. I keep getting an infinite loop

I am trying to write a function that returns a list of integers from a ‘start’ value (inclusive) to a ‘stop’ value (exclusive) and am given the ‘step’ (or number to increment by…).

The function is supposed to be able to handle different amount of arguments passed in. I believe I have the function most of the way completed but I seem to be getting an infinite loop and am unsure why or how to proceed.

Here is the code I have written so far…

function range(start, stop, step) {
    if (arguments.length===1) {
        start = 0;
        stop = arguments[0];
        step = 1;
    } else if (arguments.length===2) {
        start = arguments[0];
        stop = arguments[1];
        step = 1;
    } else if (arguments.length===3) {
        start = arguments[0];
        stop = arguments[1];
        step = arguments[2];
    }
    // define result array
    let result = [];
    // create a for-loop
    for (start; start < stop; start + step) {
        result.push(start);
    }
    return result;
}

And here are some example calls and their expected outputs…

range(10); -> [0,1,2,3,4,5,6,7,8,9]
range(1,11); -> [1,2,3,4,5,6,7,8,9,10]
range(0,30,5); -> [0,5,10,15,20,25]
range(0,-10,-1); -> [0,-1,-2,-3,-4,-5,-6,-7,-8,-9]

The function is also supposed to be able to do negative ranges with negative ‘step’ values as well.

Could someone explain to me why I seem to be getting an infinite loop?

How to fill an empty nested object with existed one [closed]

The question maybe simple, but i’m stuck with this for half a day,
I have an object like this:

{
    "loginStatus": false,
    "data": {}
}

Now i recieve some data like this

{
    "id": 1,
    "firstname": "Le",
    "Last name": " Quoc Khanh",
    "username": "[email protected]",
    "password": 12345678
}

How can i put this data to above object , the result be like

{
     "loginStatus": false,
     "data": 
      {
        "id": 1,
        "firstname": "Le",
        "Last name": " Quoc Khanh",
        "username": "[email protected]",
        "password": 12345678
      }
 }

How remove specific text from option

i need remove text “+ 0 Kč” from this options via Jquery, can you help me? Thx

 <option value="177" data-surcharge-final-price="0" data-surcharge-additional-price="0">Ginger +0 Kč</option>
 <option value="180" data-surcharge-final-price="0" data-surcharge-additional-price="0">Taupe +0 Kč</option>
 <option value="183" data-surcharge-final-price="0" data-surcharge-additional-price="0">Mocca +0 Kč</option>

Show Object in Object in React

Hello I have a data like this in json

data =   {
    "1": {
        "success": true,
        "cache_last_updated": 1638898857253,
        "win_rate": 0,
        "mmr": 1303,
        "last_claim": 1638245364,
        "name": "test 1",
        "next_claim": 1639454964
      },
      "2": {
        "success": true,
        "cache_last_updated": 1638899627451,
        "win_rate": 0,
        "mmr": 1922,
        "last_claim": 1638077836,
        "name": "test 2",
        "next_claim": 1639287436
      },
      "3": {
        "success": true,
        "cache_last_updated": 1638899627442,
        "win_rate": 0,
        "mmr": 1214,
        "last_claim": 1638078027,
        "name": "test 3",
        "next_claim": 1639287627
      }
    }

May I ask for your help on how I fetch the data on 1, 2 ,3 separately? I’m having a problem on fetching then separately.

My implementation

const App = () => {
    const [test, setTest] = useState([]);
    return (
        <div>
            <h1 style={{ textAlign: "center" }}>Test Data</h1>

            <div style={{ textAlign: "center" }}>
                <div>{JSON.stringify(data)}</div>
            </div>
        </div>
    );
};

export default App;

When I’m trying this it shows all the data, but I can’t fetch them one by one.

Dynamically create OBJECTS NAME in javascript/jquery, NOT it’s keys or values

How can you create an object with a dynamically created NAME?
NOT dynamically created keys or values.
I’d like to learn this in both jQuery and javascript

var com = "thing_"
var bined = "one"
var [com+bined] = {}

//so I can populate as such:
thing_one.key = value

I’ve googled my eyes out and tried a thousand things. Thanks in advance and apologies if I overlooked the obvious.

How to maximize amount of NestJS/NodeJS requests to another server?

I want to make a service (for training purposes) for throwing a resource of some kind with a large number of requests, like this: GET example.com/someResource

I tried this:

for (let i = 0; i < 10000; i++) {
  this.http.get('example.com/someResource').toPromise();
  // that's a NestJS so it's a HttpService of HttpModule (Obvservable, so we need to transform it to Promise using 'toPromise()')
} 

But this does not seem to work, because the requests take too long and a small ratio of time/number of requests is obtained (in 4 seconds only 500 requests, at the same time on python about 1200 requests per second can be squeezed out) How can we improve this and send more requests? Help, please, the course is on))

Unable to declare multiple custom named properties TypeScript MUI v5 Palette

I am trying to setup many custom attributes to keep things semantically easy to update in the future. However I am having issues with having more than just one custom property in MUI v5

Ts Error

TS2717: Subsequent property declarations must have the same type. Property 'background' must be of type 'TypeBackground', but here has type 'PaletteColor'.

palette.ts

export const palette = {
  primary: {
    light: '#6D6B8C',
    main: '#6514DD',
    dark: '#6D6B8C',
  },
  secondary: {
    main: '#6D6B8C',
  },
  error: {
    main: '#bd4646',
  },
  background: {
    main: '#fff',
    paper: '#F5F5F5',
  },
  border: {
    main: '#DADAE1',
    primary: '#DADAE1',
  },
  text: {
    primary: '#6D6B8C',
    secondary: '#000',
  },
}


declare module '@mui/material/styles' {
  interface Palette {
    border: Palette['primary']
    background: Palette['primary']
  }

  // allow configuration using `createTheme`
  interface PaletteOptions {
    border?: PaletteOptions['primary']
    background?: PaletteOptions['primary']
  }
}

enter image description here

How to get the final state from an array of objects representing changes

I have an array of changes (objects) and would like to get the final state after all the changes have been made.

For example, having this array of changes:

const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const tomorrow = new Date(today);
tomorrow.setDate(tomorrow.getDate() + 1);

const item1 = {
  id: 'id1',
  timestamp: yesterday,
};
const item2 = {
  id: 'id2',
  timestamp: today,
};
const item3 = {
  id: 'id3',
  timestamp: tomorrow,
};

const changes = [
  {
    action: 'swap',
    item1,
    item2,
  },
  {
    action: 'swap',
    item1,
    item2: item3,
  },
]

I am expecting this array with the final state of each item:

const finalState = [
  {
    id: item1.id,
    timestamp: item3.timestamp,
  },
  {
    id: item2.id,
    timestamp: item1.timestamp,
  },
  {
    id: item3.id,
    timestamp: item2.timestamp,
  },
]

currently, the logic I am using is this one. However it is not working properly.

export const convertChangesToFinalState = ({
  changes,
}): FinalChanges => {
  const finalState: {
    [id: string]: FinalChange;
  } = {};

  for (const { item1, item2 } of changes) {
    finalState[item1.id] = {
      id: item1.id,
      timestamp: new Date(finalState[item2.id]?.timestamp ?? item2.timestamp),
    };

    finalState[item2.id] = {
      id: item2.id,
      timestamp: new Date(finalState[item1.id]?.timestamp ?? item1.timestamp),
      // timestamp: new Date(new Date(item2.timestamp).getTime() !== new Date(finalState[item1.id]?.timestamp).getTime()? finalState[item1.id]?.timestamp : item1.timestamp),
    };
  }

  return Object.values(finalState);
};

Could you please help me solve this?

Thank you in advance!

Select2 User Select Add a new Company Popup Window

I have this Company control that list all the company from the database. I also added this Add a New Company... -1 which I would like the user to select if it is a new company that a pop up window will display and the user can enter the information. Any help would be great

enter image description here

    html += "<h3 class='form-section'>Submission Information</h3><div class='row'>";
    html += "<div class='col-md-6'><div class='form-group'><label class='control-label'>Company</label>";
    
   html += "<select id='txtCompany' name='txtCompany' class='form-control select2-multiple' multiple='multiple'>";
    
    html += "<option value=''></option> <option value='-1'>Add a New Company...</option>";
    html += "<optgroup label = 'Existing Company' >";
    $.each(data.listOfRequesters, function (index, r) {
    if (requesterList.includes(r.SubmissionRequesterId)) {
       html += "<option value='" + r.SubmissionRequesterId + "' selected='selected'>" + r.Company + "</option>"
     } else {
    html += "<option value='" + r.SubmissionRequesterId + "'>" + r.Company + "</option>"
    }
    });
    
   html += "</optgroup></select>";

Access Javascript file in Kotlin/JS

I have a bunch of Javascript files I need to access from Kotlin Code.

I created a js-files directory in my root project with the needed .js files and a package.json which looks like this:

{
  "name": "js-files",
  "version": "1.0.0",
  "dependencies": {
  }
}

My build.gradle looks like this:

plugins {
    kotlin("js")
}

version = "unspecified"

repositories {
    mavenCentral()
}

kotlin {
    js {
        useCommonJs()

        nodejs()
        browser {
            webpackTask {
                output.libraryTarget = "commonjs2"
            }
        }

        binaries.executable()
    }
}

dependencies {
    val path = rootProject.projectDir.resolve("js-files").canonicalPath
    implementation(npm("js-protos", "file:$path"))
}

The idea for this I got from this post.

For debugging, i have the following js file in js-files:

export function func() {
    console.log("This is my test function.")
}

and my kotlin main looks like this:

@JsModule("js-files")
external fun func()

fun main() {
    func()
}

However, when i run the project using vrowserDevelopmentRun i receive this error:

Module not found: Error: Can't resolve 'js-files' in 'path-to-my-project/build/js/packages/project-name-js/kotlin-dce-dev'

Maybe there is an easier way of binding my js files but after hours of research i found nothing. I’m thankful for any help.