I have some problem in the get number of whishlist and show this?

In the following this error…
I have problems getting the number of likes for products and removing likes from the list of favorites.
like correctly in the database (add to favorite) but I don’t know how to get their number and make it dynamic in JavaScript codes by Ajax.

Can you look at my codes and give me the necessary guidance, what should I add or remove? thank you!

favorite.py

from apps.comment_scoring_favorites.models import Favorite
class favoriteProduct:
    def __init__(self,request) -> None:
        self.session=request.session
        favorite_product=self.session.get('favorite_product')
        if not favorite_product:
            favorite_product=self.session['favorite_product']=[]
        self.favorite_product=favorite_product
        self.count=Favorite.count_favorites_by_session()


    def __iter__(self):
        favorite_product=self.favorite_product.copy()
        for item in favorite_product:
            yield item

    def add_to_favorite_product(self,productId):
        productId=int(productId)
        if productId  not in self.favorite_product:
            self.favorite_product.append(productId)
        self.count=Favorite.count_favorites_by_session()
        self.session.modified=True

    def delete_from_favorite_product(self, productId):
        productId=int(productId)
        self.favorite_product.remove(productId)
        self.count=Favorite.count_favorites_by_session()
        self.session.modified=True

middleware.py

import threading
class RequestMiddleware:
    def __init__(self,get_response,thread_local=threading.local()):
        self.get_response=get_response
        self.thread_local=thread_local

    def __call__(self,request):
        self.thread_local.current_request=request
        response=self.get_response(request)
        return response

models.py

from middlewares.middleware import RequestMiddleware
class Favorite(models.Model):
    product=models.ForeignKey(Product,on_delete=models.CASCADE,related_name='favorite_product',verbose_name='کالا')
    favorite_user=models.ForeignKey(CustomUser, on_delete=models.CASCADE,related_name='favorite_user1',verbose_name='کاربر علاقه مند')
    register_date=models.DateTimeField(auto_now_add=True,verbose_name='تاریخ درج')

    def __str__(self) -> str:
        return f"{self.product} - {self.favorite_user}"
    
    
    class Meta:
        verbose_name='علاقه'
        verbose_name_plural='علایق'

    
    def count_favorites_by_session(self):
        request=RequestMiddleware(get_response=None)
        request=request.thread_local.current_reques
        session=request.session
        favorite_product_ids =session.get('favorite_product')
        return self.objects.filter(product__id__in=favorite_product_ids).count()

views.py

class ShowFavoriteListView(View):
    def get(self,request,*args,**kwargs):
        favorite_list=favoriteProduct(request)
        context={
            'favorite_list':favorite_list,
        }
        return render(request,'csf_app/partials/create_favorites.html',context)
    

def statuse_of_favorite_list(request):
    favoriteList=favoriteProduct(request)
    return HttpResponse(favoriteList.count)

def add_to_favorite(request):
    productId=request.GET.get('productId')
    product=Product.objects.get(id=productId)
    flag=Favorite.objects.filter(
        Q(favorite_user_id=request.user.id) &
        Q(product_id=productId)).exists()
    if(not flag):
        Favorite.objects.create(
            product=product,
            favorite_user=request.user,
        )
        return HttpResponse('added to favorite lists')
    return HttpResponse('it was in favorite')

def delete_from_favorite(request):
    productId=request.GET.get('productId')
    favoriteList=favoriteProduct(request)
    favoriteList.delete_from_favorite_product(productId)
    return redirect('csf:user_favorite_list')

class UserFavoriteView(View):
    def get(self,request,*args,**kwargs):
        user_favorite_products=Favorite.objects.filter(Q(favorite_user_id=request.user.id))
        return render(request,'csf_app/user_favorite.html',{'user_favorite_products':user_favorite_products})

urls.py

from django.urls import path
from . import views
app_name='csf'
urlpatterns = [
    path('create_comment/<slug:slug>/',views.CommentView.as_view(),name='create_comment'),  
    path('add_score/',views.add_score,name='add_score'),  
    path('add_to_favorite/',views.add_to_favorite,name='add_to_favorite'),
    path('user_favorite_list/',views.UserFavoriteView.as_view(),name='user_favorite_list'),  
    path('delete_from_favorite/',views.delete_from_favorite,name='delete_from_favorite'),  
    path('statuse_of_favorite_list/',views.statuse_of_favorite_list,name='statuse_of_favorite_list'),     
]

myscript.js

statuse_of_favorite_list();
function statuse_of_favorite_list(){
    $.ajax({
        type:"GET",
        url:"/csf/statuse_of_favorite_list/",
        success: function(res){
            $('#favorite_count_icon').show();
            $('#favorite_count').text(res);
        }
    });
}

function addToFavorite(productId){
    $.ajax({
        type:"GET",
        url:"/csf/add_to_favorite/",
        data:{
            productId: productId,
        },
        success: function(res){
            alert(res)
            statuse_of_favorite_list();

        }
    });
}

function deleteFromFavorite(product_id){
    $.ajax({
        type:"GET",
        url:"/csf/delete_from_favorite/",
        data:{
            product_id:product_id,
        },
        success:function(res){
            alert('deleted!');    
            $("#favorite_list").html(res);
            statuse_of_favorite_list();           

        }
    });
}

createfavorites.html

{% load render_partial %}
{% load humanize %}
{% block titile %}
 
{% endblock titile %}
{% block content %}
    <div id="favorite_list">
        {% render_partial 'csf:user_favorite_list' %}
    </div>
{% endblock %}

usre_favorite.html

{% extends 'main_template.html' %}
{% load render_partial %}
{% load humanize %}
{% block titile %}
    WishList...
{% endblock titile %}
{% block content %}
<div class="site__body">
    <div class="page-header">
        <div class="page-header__container container">
            <div class="page-header__breadcrumb">
                <nav aria-label="breadcrumb">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="{% url 'main:index' %}">Home</a>
                            /
                        </li>
                        <li class="breadcrumb-item active" aria-current="page">Favorites</li>
                    </ol>
                </nav>
            </div>
            <div class="page-header__title">
                <h1>Favorites</h1></div>
        </div>
    </div>
    <div class="block">
        <div class="container">
            <table class="wishlist">
                <thead class="wishlist__head">
                    <tr class="wishlist__row">
                        <th class="wishlist__column wishlist__column--image">image</th>
                        <th class="wishlist__column wishlist__column--product">product</th>
                        <th class="wishlist__column wishlist__column--stock">stock</th>
                        <th class="wishlist__column wishlist__column--price">price</th>
                        <th class="wishlist__column wishlist__column--tocart">buy or not buy</th>
                        <th class="wishlist__column wishlist__column--remove">delete</th>
                    </tr>
                </thead>
                <tbody class="wishlist__body">
                    {% for favorite in user_favorite_products %}
                        <tr class="wishlist__row">
                            <td class="wishlist__column wishlist__column--image">
                                <a href=""><img src="{{media_url}}{{favorite.product.image_name}}" alt=""></a>
                            </td>
                            <td class="wishlist__column wishlist__column--product">
                                <a href="" class="wishlist__product-name">
                                    {{favorite.product.product_name}}
                                </a>
                            </td>
                            <td class="wishlist__column wishlist__column--stock">
                                {% if favorite.product.get_number_in_warehouse > 0 %}
                                    <div class="badge badge-success">موجود در انبار</div>
                                {% else %}
                                    <div class="badge badge-danger">موجود نمی باشد </div>
                                {% endif %}
                            </td>
                            <td class="wishlist__column wishlist__column--price"> {{favorite.product.price}} تومان</td>
                            <td class="wishlist__column wishlist__column--tocart">
                            {% if favorite.product.get_number_in_warehouse > 0 %}
                                <button type="button" class="btn btn-primary btn-sm" onclick="add_to_shop_cart({{favorite.product.id}},1)">افزودن به سبد</button>
                            </td>
                            {% else %}
                            <button type="button" class="btn btn-info disable btn-sm">افزودن به سبد</button>
                            {% endif %}
                        
                            <td class="cart-table__column cart-table__column--remove">
                                <a type="button" class="btn btn-light btn-sm btn-svg-icon" onclick="deleteFromFavorite({{favorite.product.id}})">
                                    <i class="fa fa-trash"></i>
                                </a>
                            </td>
                            
                        </tr>
                    {% endfor %}
                </tbody>
            </table>
        </div>
    </div>
</div>
{% endblock content %}

slick carousel align blocks to center slide

I’m using slick carousel. Each slide has a description, but I made it so that the description is shown only for the central block.

But because of this, my slides are uneven. How can I align my slides so they are all evenly lined up at the bottom? Regardless of the text that may be in the description.

And another question, now my description disappears and appears after the slide scrolls to the end. Is it possible to make the description disappear and appear instantly, that is, not at the end of the scroll, but at the very beginning?

$(document).ready(function(){
    $('.carousel').slick({
        centerMode: true,
        centerPadding: '0px',
        slidesToShow: 3,
        autoplay: true,
        autoplaySpeed: 3000,
        responsive: [
            {
                breakpoint: 768,
                settings: {
                    arrows: false,
                    centerMode: true,
                    centerPadding: '40px',
                    slidesToShow: 1
                }
            },
            {
                breakpoint: 480,
                settings: {
                    arrows: false,
                    centerMode: true,
                    centerPadding: '40px',
                    slidesToShow: 1
                }
            }
        ]
    });
    
    $('.carousel .slick-center').addClass('center');
  
    $('.carousel').on('afterChange', function(event, slick, currentSlide){
        var centerIndex = Math.floor(slick.slideCount / 2);
        $('.slide').removeClass('center');
        $('.slick-center').addClass('center');
    });

    
});
html, body {
    background-color: #e74c3c;
}
.wrapper {
    width: 100%;
    padding-top: 20px;
    text-align: center;
}
.carousel {
    width: 90%;
    margin: 0px auto;
}
.slick-slide {
    margin: 10px;
}
.slick-slide img {
    width: 100%;
    border-radius: 10px;
}
.slide .description {
    display: none;
}
.slide .info {
    padding: 10px;
}
.slide.center .info {
    border-radius: 10px 10px 0 0;
    border: 2px solid #fff;
    border-bottom: none;
}
.slide.center .description {
    display: block;
}
.slide.center.slick-slide img{
    border-radius: 0 0 10px 10px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css" rel="stylesheet"/>


<div class="wrapper">
      <div class="carousel">
        <div class="slide">
            <div class="info">
              <div class="title">TITLE 1</div>
              <div class="description">Description for the first slide</div>
            </div>
            <img src="https://picsum.photos/300/200?random=1" alt="Slide 1">
        </div>
        <div class="slide">
            <div class="info">
                <div class="title">TITLE 2</div>
                <div class="description">Description for the second slide</div>
             </div>
            <img src="https://picsum.photos/300/200?random=2" alt="Slide 2">
        </div>
        <div class="slide">
            <div class="info">
                <div class="title">TITLE 3</div>
                <div class="description">Description for the third slide</div>
            </div>
            <img src="https://picsum.photos/300/200?random=3" alt="Slide 3">
        </div>
        <div class="slide">
            <div class="info">
                <div class="title">TITLE 4</div>
                <div class="description">Description for the fourth slide</div>
            </div>
            <img src="https://picsum.photos/300/200?random=4" alt="Slide 4">
        </div>
        <div class="slide">
            <div class="info">
                <div class="title">TITLE 5</div>
                <div class="description">Description for the fifth slide</div>
            </div>
            <img src="https://picsum.photos/300/200?random=5" alt="Slide 5">
        </div>
        <div class="slide">
            <div class="info">
                <div class="title">TITLE 6</div>
                <div class="description">Description for the sixth slide</div>
            </div>
            <img src="https://picsum.photos/300/200?random=6" alt="Slide 6">
        </div>
      </div>
</div>

The carousel is not working in my code, I used Bootstrap

<div id="carouselExampleControls" class="carousel slide" data-ride="carousel">
                <div class="carousel-inner">
                    <% campground.images.forEach((img,i)=> { %>
                        <div class="carousel-item <%= i===0?'active':'' %>">
                            <img class="d-block w-100" src="<%=img.url%>" alt="Image <%= i %>">
                        </div>
                        <% }); %>
                </div>
                <a class="carousel-control-prev" href="#carouselExampleControls" role="button" data-slide="prev">
                    <span class="carousel-control-prev-icon" aria-hidden="true"></span>
                    <span class="sr-only"></span>
                </a>
                <a class="carousel-control-next" href="#carouselExampleControls" role="button" data-slide="next">
                    <span class="carousel-control-next-icon" aria-hidden="true"></span>
                    <span class="sr-only"></span>
                </a>
            </div>

This is my code, one image is being displayed but the carousel is not sliding to view further images I added. Can somebody help me find the error here…

I did console.log(images) and it is an array of objects having img as a property in them with it’s url being the value.
I want the carousel to work.

“(void 0) is not a constructor” when trying to access esbuild minified class

I’ve got a class defined in an npm package:

export default class SomeClass{
    constructor({ testA, testB }) {
        this.testA = testA;
        this.testB = testB;
    }

    log() {
        console.log(this.testA + this.testB);
    }
}

That then gets aggregated with another file in the source file:

import SomeClass from './some-class';
import anotherFunction from './another-function';

export { SomeClass, anotherFunction };

And then built with the esbuild config as below:

const esbuild = require('esbuild');

async function bundle() {
    await esbuild.build({
      logLevel: 'info',
      entryPoints: ['src/js/package.js'],
      bundle: true,
      minify: true,
      sourcemap: true,
      outfile: 'dist/js/package.min.js'
    })
      .catch(() => process.exit(1));
  }

bundle();

But when I try import that into my app’s app.js as such:

import { SomeClass } from '../package.min.js';
const newClass = new SomeClass(constructorObject);

I get the aforementioned void 0 message.

If I open the minified js file I do see a message about the class not being referenced anywhere else, is there something I can do to make it export the file?

Unexpected Delays in HTTP Requests Using Fetch in Google Cloud Functions

Body:

I’m experiencing unexpected delays when making HTTP requests using fetch in Google Cloud Functions. Despite not awaiting any of the requests, they are not being executed concurrently as expected. Here are some details and a relevant snippet of my code:

Problem Description:

In my Google Cloud Function, I am attempting to make multiple HTTP requests in parallel using fetch. However, I’ve noticed significant delays between these requests, even though I am not awaiting any of them. The delays seem to occur randomly, and the requests are not being sent out simultaneously as intended.

Observed Behavior:

Here’s a sample of the log output showing the delays between the requests:

2024-07-29T15:04:44.371230Z Triggering fetch for document
yQv8lQBVZ9OdyXrPHtB8 – 7/29/2024, 3:04:44 PM
2024-07-29T15:04:43.770616Z Triggering fetch for document
mkjpBSwcSXu4l1p9F7pt – 7/29/2024, 3:04:43 PM
2024-07-29T15:04:43.370684Z Triggering fetch for document
mGYfOXQOtWeztx9DJjAD – 7/29/2024, 3:04:43 PM
2024-07-29T15:04:42.971156Z Triggering fetch for document
kaSfSXvFLQauBdQECTo4 – 7/29/2024, 3:04:42 PM
2024-07-29T15:04:42.770962Z Triggering fetch for document
Z4ZtCxvEQk0UXuRliQgN – 7/29/2024, 3:04:42 PM
2024-07-29T15:04:42.572475Z Triggering fetch for document
V2FZf8NcAwO5pfA7xBMS – 7/29/2024, 3:04:42 PM
2024-07-29T15:04:42.171896Z Triggering fetch for document
OD9vHJeQ5Y1ZsN1wPxP4 – 7/29/2024, 3:04:42 PM
2024-07-29T15:04:41.172708Z Triggering fetch for document
DcCRo2XjRUQ28aPeW4DT – 7/29/2024, 3:04:41 PM
2024-07-29T15:04:41.171919Z Triggering fetch for document
AKi0zSkcDU4lq9F5jerH – 7/29/2024, 3:04:41 PM
2024-07-29T15:04:40.572401Z Triggering fetch for document
1qCtthUVfHZmjEQccSzi – 7/29/2024, 3:04:40 PM
2024-07-29T15:04:40.277409Z Triggering fetch for document
1FaZXjM3rQoySvw3RBFJ – 7/29/2024, 3:04:40 PM

Relevant Code:

Here’s the code snippet where I am making the fetch requests:

const fetch = require('node-fetch');
const functions = require('@google-cloud/functions-framework');
const admin = require('firebase-admin');

admin.initializeApp();

async function triggerFunctionForAllDocuments() {
  const db = admin.firestore();
  const oneMindCollectionRef = db.collection("OneMind");
  const oneMindDocsSnapshot = await oneMindCollectionRef.get();

  const functionUrl =
    "https://us-central1-onemind-95fb2.cloudfunctions.net/processDocument";

  oneMindDocsSnapshot.docs.forEach((doc) => {
    const startTime = new Date();
    console.log(
      `Triggering fetch for document ${doc.id} - ${startTime.toLocaleString()}`
    );

    const agent = functionUrl.startsWith("https") ? httpsAgent : httpAgent;

    fetch(functionUrl, {
      method: "POST",
      body: JSON.stringify({ documentId: doc.id, documentData: doc.data() }),
      headers: { "Content-Type": "application/json" },
    })
      .then((data) => {
        const endTime = new Date();
        console.log(
          `Successfully triggered function for document ${
            doc.id
          } - ${endTime.toLocaleString()} - Duration: ${endTime - startTime}ms`
        );
      })
      .catch((err) => {
        console.error(`Error triggering function for document ${doc.id}:`, err);
      });
  });

  console.log("Triggered Cloud Function for all OneMind documents.");
}

Question:

Why are my fetch requests experiencing delays even though I am not awaiting them and how can I ensure that they are executed concurrently to avoid these delays?

Any insights or suggestions on how to resolve this issue would be greatly appreciated!

Adaptation of the interface when the on-screen keyboard is switched on

When you activate the inputtextarea, the height changes, so that certain elements are no longer available, and others overlap. I’m using react js, is there any way to adapt the interface when the keyboard is enabled?

I tried to solve the problem myself via useRef, but I encountered two problems

  1. After closing the keyboard, the inputtextarea was still active and the elements were inactive
  2. Scrolling to the desired element did not work correctly and I had to make several clicks, not automatically

How to best support merge tags/tokens in a JSON Formatter / Viewer control

I am looking for a way to support merge tags/tokens inside JSON that will either pass validation and retain the primitive data types or ideally it would work with our the popular standard JSON formatter control for validation.

However I realise there will need to be a custom approach here as our merge tags utilize the same structure characters as JSON.

enter image description here

In the above example, we need to map this key to a merge tag/token that contains a number. However the JSON does not validate because the merge tag/token’s name itself is a string.

Any suggestions are welcomed. Looking for a creative approach that will be user friendly and easy to understand what is going on with the JSON. Also open to using other controls.

Background: The frontend is React.js with a ASP.Net backend. The purpose of this part of the BPM/IPaaS application is to configure a payload to be sent to an API based on data in the system. It must be flexible enough to generate objects, arrays, and other keys based on mapped data points while allowing us to replace merge tags/tokens.

Thanks in advance.

Prisma Migration Issue: “Migration history doesn’t match” Error on Production Database

I’m encountering an issue with Prisma migrations in my NestJS application. My backend setup includes Prisma and PostgreSQL, and I’m using a remote database for my production environment. Every time I try to migrate any database schema changes on the production server, I get the following error:

Error: Migration history doesn't match

It suggests resetting the whole database, which unfortunately clears all the data in my production database. Here is a summary of my current workflow:

  1. Backup Production Database: I take a backup of the production database before making any schema changes.
  2. Migrate Schema Changes: I run the migration commands, which leads to the above error and ends up clearing the data.
  3. Restore Data:I manually import the data back into the production database.

Steps I’ve Taken to Resolve the Issue:

  1. Shadow Database Configuration: I’ve specified a different shadow database in my schema.prisma file:
datasource db {
  provider          = "postgresql"
  url               = env("DATABASE_URL")
  shadowDatabaseUrl = env("SHADOW_DATABASE_URL")
}
  1. Synchronize Migration History:
    I’ve tried to ensure that the migration history in my local environment matches the one in production by copying migration files from production to local.

  2. Deploying Migrations:
    I’ve attempted to use the npx prisma migrate deploy command to apply the migrations without resetting the database, but the issue persists.

how i can fix this error?! : Uncaught ReferenceError: THREE is not defined

I created a subdomain inside the host and inside this subdomain I created a folder and created an index file to call the threejs code, which is my code:

    <script>  
        // صحنه، دوربین و رندرکننده را ایجاد کنید  
        const scene = new THREE.Scene();  
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);  
        const renderer = new THREE.WebGLRenderer();  
        renderer.setSize(window.innerWidth, window.innerHeight);  
        document.body.appendChild(renderer.domElement);  

        // نور به صحنه اضافه کنید  
        const light = new THREE.AmbientLight(0xffffff);  
        scene.add(light);  

        // دراکو بارگذار و GLTFLoader را تنظیم کنید  
        const dracoLoader = new THREE.DRACOLoader();  
        dracoLoader.setDecoderPath('/examples/jsm/libs/draco/');  
        const loader = new THREE.GLTFLoader();  
        loader.setDRACOLoader(dracoLoader);  

        // بارگذاری مدل GLTF  
        loader.load(  
            'https://demo.arendlighting.com/arsalan/object/scene.gltf',  
            function (gltf) {  
                scene.add(gltf.scene);  
                gltf.scene.position.set(0, 0, 0); // موقعیت مدل  
            },  
            function (xhr) {  
                console.log((xhr.loaded / xhr.total * 100) + '% loaded');  
            },  
            function (error) {  
                console.log('An error happened:', error);  
            }  
        );  

        // تنظیم دوربین  
        camera.position.z = 5;  

        // حلقه رندر  
        function animate() {  
            requestAnimationFrame(animate);  
            renderer.render(scene, camera);  
        }  
        animate();  

        // تنظیم اندازه‌گیری صفحه  
        window.addEventListener('resize', function() {  
            camera.aspect = window.innerWidth / window.innerHeight;  
            camera.updateProjectionMatrix();  
            renderer.setSize(window.innerWidth, window.innerHeight);  
        });  
    </script>  
</body>  
</html>`

But when I run the browser page, I encounter a white screen and it shows me this error in the console: Uncaught ReferenceError: THREE is not defined.
What is wrong?!

i try in this link : https://demo.arendlighting.com/arsalan/
PlZz heeeeelppp me…

How to prevent from auto reloading in html page?

I am making a chatting application using spring boot 3 and i use web socket to make connection. I’ve created a web page with 2 buttons “Start Chat” and “Close Chat”. When i click the “Start Chat” button it adds html codes into an html element(id=”chat”). This html code is from “https://spring.io/guides/gs/messaging-stomp-websocket”. And when i click the “Close Chat” button it removes the html codes from the element. My issue:

When i click the Start Chat button and Connect it works well. After closing, if i open the chat again and click Connect the page is reloaded. I don’t want this reloading when i try to connect chat again.
(Note: After clearing the chat elements from page i also call disconnect() function from webSocket.js )

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@stomp/[email protected]/bundles/stomp.umd.min.js"></script>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script src="/js/app.js"></script>
</head>
<body>
<div th:insert="components/header :: header"></div>
<div class="container-fluid">
    <div class="col-md-3">
        <div class="row">
            <button onclick="openChat()" class="btn btn-primary m-3">Start Chatting</button>
            <button onclick="closeChat()" class="btn btn-primary m-3">Close Chat</button>
        </div>
    </div>
    <div class="col-md-9">
        <div class="row m-3" id="chat"></div>
    </div>
</div>

<script>
    function closeChat() {
        const chatElement = document.getElementById("main-content");
        chatElement.remove();
        disconnect();
        const scriptElement = document.getElementById("webSocketJs");
        if (scriptElement) {
            scriptElement.remove();
        }
    }

    function openChat() {
        event.preventDefault();
        const chatElement = document.getElementById("chat");
        const content =
            `<div id="main-content" className="container">
                <div className="row">
                    <div className="col-md-6">
                        <form className="form-inline">
                            <div className="form-group">
                                <label htmlFor="connect">WebSocket connection:</label>
                                <button id="connect" className="btn btn-default" type="submit" >Connect</button>
                                <button id="disconnect" className="btn btn-default" type="submit"
                                        disabled="disabled">Disconnect
                                </button>
                            </div>
                        </form>
                    </div>
                    <div className="col-md-6">
                        <form className="form-inline">
                            <div className="form-group">
                                <label htmlFor="name">What is your name?</label>
                                <input type="text" id="name" className="form-control" placeholder="Your name here..."/>
                            </div>
                            <button id="send" className="btn btn-default" type="submit">Send</button>
                        </form>
                    </div>
                </div>
                <div className="row">
                    <div className="col-md-12">
                        <table id="conversation" className="table table-striped">
                            <thead>
                            <tr>
                                <th>Greetings</th>
                            </tr>
                            </thead>
                            <tbody id="greetings">
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>`;
        chatElement.innerHTML = content;

        const scriptElement = document.getElementById("webSocketJs");
        if (!scriptElement) {
            let webSocketScript = document.createElement('script');
            webSocketScript.setAttribute('src', '/js/webSocket.js');
            webSocketScript.setAttribute('id', 'webSocketJs');
            document.body.appendChild(webSocketScript);
        }
    }
</script>
</body>
</html>
const stompClient = new StompJs.Client({
    brokerURL: 'ws://localhost:8080/gs-guide-websocket'
});

stompClient.onConnect = (frame) => {
    setConnected(true);
    console.log('Connected: ' + frame);
    stompClient.subscribe('/topic/greetings', (greeting) => {
        showGreeting(JSON.parse(greeting.body).content);
    });
};

stompClient.onWebSocketError = (error) => {
    console.error('Error with websocket', error);
};

stompClient.onStompError = (frame) => {
    console.error('Broker reported error: ' + frame.headers['message']);
    console.error('Additional details: ' + frame.body);
};

function setConnected(connected) {
    $("#connect").prop("disabled", connected);
    $("#disconnect").prop("disabled", !connected);
    if (connected) {
        $("#conversation").show();
    }
    else {
        $("#conversation").hide();
    }
    $("#greetings").html("");
}

function connect() {
    stompClient.activate();
}

function disconnect() {
    stompClient.deactivate();
    setConnected(false);
    console.log("Disconnected");
}

function sendName() {
    stompClient.publish({
        destination: "/app/hello",
        body: JSON.stringify({'name': $("#name").val()})
    });
}

function showGreeting(message) {
    $("#greetings").append("<tr><td>" + message + "</td></tr>");
}

$(function () {
    $("form").on('submit', (e) => e.preventDefault());
    $( "#connect" ).click(() => connect());
    $( "#disconnect" ).click(() => disconnect());
    $( "#send" ).click(() => sendName());
});

First one is my html page, and second one is webSocket.js file.

Re-adjusting image (and container) to accordeon variable height (in elementor)

I am trying to “copy” the effect of the accortdeon in the following link (https://the-healer-template.squarespace.com/work-with-me). The think that I want is to enlarge the image and the container of the image to fit the height of the accordeon container due to his variable height dependint on the lengh of the text from each accordeon elements.

Since I am working with elementor, the aproach that I am woking with is a two column container one with the image and the other with the container. Also I set the elementor accordion to only one accordeon element unfolded at a time, so when te user click to one of them, automaticaly closes the one that was active or if the click is on the same element, it desactivates it.

The main issue I am having now is that I am new to javascript and programing logic and I don’t know how to make it work. Here is the code that I am using so far, It does what I need but it is not taking in consideration the click on the other element while an other one is active. I activated the “Nested elements” on elementor to be able to assign an ID to each section of the accordeon

The link to my section example: https://www.balanceyoga.beinframe.com/example

<script>

document.addEventListener("DOMContentLoaded", function() {
    
    .responsive-image01 {
    max-width: 100% !important;
    height: auto !important;

    float:right !important;
   /* object-fit: cover;*/
    

    transition: width 300ms linear; 


    }
         
    var yogaCont01 = document.querySelector('.yoga-cont01'); // contenedor 01
    
    var yogaCont02 = document.querySelector('.yoga-cont02'); // contenedor 02
    
    var responsiveImage01 = document.querySelector('.responsive-image01'); 
    
        
    var originalWidth = responsiveImage01.offsetWidth; 

    var responsiveImageWidth01 = responsiveImage01.offsetWidth; 

    var originalHeight = yogaCont02.offsetHeight; 

    var yogaCont02Height = yogaCont02.offsetHeight; 

            
    responsiveImage01.style.width= (responsiveImageWidth01*0.65)+'px'; 

        
            
    function contHeight() {
        if (originalHeight==yogaCont02Height) {
                    
            yogaCont02Height = yogaCont02.offsetHeight;
        
            yogaCont01.style.height = yogaCont02Height + 'px';
            
            responsiveImage01.style.height = yogaCont02Height + 'px';
            
            var calculatedWidth = (originalWidth * yogaCont02Height)/originalHeight;
                
            responsiveImage01.style.width = calculatedWidth + 'px';
                    
        }else {
            

            responsiveImage01.style.height = originalHeight + 'px';
                
            responsiveImage01.style.width = (originalWidth*0.65) + 'px';
            
            yogaCont01.style.height = originalHeight + 'px';
            
            yogaCont02.style.height = originalHeight + 'px';
                
            yogaCont02Height = originalHeight;
            

        }
    }
        
    document.querySelector("#yoga-included").addEventListener("click", function() {
        setTimeout(contHeight, 360);
    
        });
        
    document.querySelector("#yoga-timeline").addEventListener("click", function() {
        setTimeout(contHeight, 360);
    
        });
        
   document.querySelector("#yoga-payment").addEventListener("click", function() {
        setTimeout(contHeight, 360);
    
        });
        
                
    }
        
);

</script>

How is the scope of variables used in Event Handlers determined? (when do I have to assign variables to fetch via event.currentTarget and when not???)

Working on my card game project I noticed at some point that I needed to append values I want to use inside an addEventListener’s function, to the tag that becomes available inside the function as event.currentTarget… but that in seemingly exactly similar coding situations, just calling variables declared outside the Event Handler’s function works.

Here is some code where calling a variable declared outside works :

document.querySelectorAll('.HexKeyControl').forEach(function(Tag) {
  Tag.IdSplitAtUnderScore = Tag.id.split('_');
  Tag.addEventListener('mousedown', function() {
    PlayNote(Tag.IdSplitAtUnderScore[1], Tag.IdSplitAtUnderScore[2]);
    SlideModeOn = true;
  });
  Tag.addEventListener('mouseup', function() {
    SlideModeOn = false;
  });
  Tag.addEventListener('mouseenter', function() {
    if (SlideModeOn) {
      PlayNote(Tag.IdSplitAtUnderScore[1], Tag.IdSplitAtUnderScore[2]);
    }
  });
  Tag.addEventListener('mouseleave', function() {
    EvidenceOut(document.getElementById('HexKeyImage_' + Tag.IdSplitAtUnderScore[1] + '_' + Tag.IdSplitAtUnderScore[2]));
  });
});

Maybe because the addEventListeners are themselves part of the forEach’s function, and the Tag variable was declared into this function, the addEventListener’s functions become child functions of the forEach’s function and for some quirky design reason it results into the variable being available… Maybe because Tag contains a DOM Element’s reference instead of a common value, it is treated differently becaue of its type…

Here is some code where I had to use event.currentTarget :

function display_board_card(spot, player, figure, instant_only = false) {
  // Variables preparation
  [...some out - of -context code...]


  /* Here comse the 1st case, in which the event handler's code is put into a variable
  for later use with eval() (which is bad I know but I don't remotely care, all cases of eval being
  replacable with other code are dumb situations that never happened to me).
  That said I understand that eval may steal the scope and force me to use event.currentTarget
  (and don't worry, the drop_target variable IS appended to the currentTarget before the eval(onClick) is
  called) */
  var onClick = "if (targeting_a_credo){
  evaluate_credo_target(drag_memory, evt.currentTarget.drop_target);
}
";


[...lots of out - of -context code...]


// Event handlers
// Here is the 2nd case in which I had to append the value to the DOM element
card_bg_div.drop_target = player + '***' + figure;
card_bg_div.addEventListener('drop', function(evt) {
  check_drop(event, evt.currentTarget.drop_target);
});
card_bg_div.addEventListener('dragover', function() {
  allowDrop(event);
});

In the 2nd case, we’re still inside a main function which has for parameters player and figure, which for some reason are made unavailable inside addEventListeners functions, which as you will admit, are located inside the parent function, just like in the first snipet, but won’t trail the parent function’s parameters inside their own function…

JavaScript is a total mess compared to PHP… I could ramble for long on this.

How can i read and write to cells in the same function?

I am creating a discord bot and I have 2 issues.

Issue One:

In my script i am trying to get the users response to :

interaction.options.get('steamid').value;

and store it in the variable userInput.

Once stored i want to write the stored response to my google sheet in sheet BOTDATA!H1.

The code works when i set const userInput = interaction.options.get('steamid').value; inside the function. Only when i use the ‘/checkbl’ command. If i use any other command i receive an error.

Issue Two: Any command that i use, regardless if it is the ‘/checkbl’ command or not will write `sample value` to the sheet BOTDATA!H1.

This is my current script:

async function blackList() { 
    const sheets = google.sheets({ version: "v4", auth });
    const spreadsheetId = "1lEB9fEqZUNtR0Tq-gzHVVaQ2eQvxsuiwXSTW3VGC2xw";
  
    const sheetName = "BOTDATA";
    const cells = ["H1"];
    const valueInputOption = "USER_ENTERED";
    const userInput = "sample value";
    const result = await sheets.spreadsheets.values.update({
      spreadsheetId,
      range: `'${sheetName}'!${cells[0]}`,
      resource: { values: [[userInput]] },
      valueInputOption,
    });
    console.log(result.data);
    
  }
  
  blackList();

  (async()=>{

if (interaction.commandName === 'checkbl') {
    const userInput = interaction.options.get('steamid').value;
    const bl = new EmbedBuilder()
    .setTitle('Blacklist Checker')
    .setDescription(`${userInput} is`)
    .setColor('Red')
    .setThumbnail('https://i.imgur.com/9GKhYQf.png')
    .setFooter({text: 'DroneOS', iconURL: 'https://i.imgur.com/9GKhYQf.png'})
    .setTimestamp()

    interaction.reply({ embeds: [bl]});

}

})()

I would like to solve both my issues stated above. Along side this i would like ‘userInput’ to write to cell H1 and i want to read cell H2 in the same function. This way i can set the response to:

.setDescription(`${userInput} is ${H2}`)

on my discord bot. Thanks for any help.

Keycloak: how to log in a user through the API

I managed to log in as admin through the /protocol/openid-connect/token url.

Now I have an admin that can list users, realms + create/delete them etc.

What I would like is to check if the credentials I receive from my user are the good ones or not.

When I use the same call than for the admin /protocol/openid-connect/token I get “bad credentials” but I know they are correct.

I am using nextjs + @keycloak/keycloak-admin-client but looks like the keycloak-admin-client cannot handle user authentication