Appending questions and answers into an array

i am new to javascript and i have 2 strings
lets say

const questions = "1.What is love? 2.1+1 = ? 3. 2+2 = ?"
const answers = "1.Yes 2.2 3.4"

i want to append it into sth like :

const package = [{question1: answer1},{question2: answer2}]

I tried to split and append it through regex and split but it didnt work
Is there a way to individually append into a {} and then into the array of the package?

Use switchMap operator in a resolver

I want to only navigate to the product detail page if the product exists so I created this productResolver function

export const productResolver: ResolveFn<Product | undefined> = (
  route: ActivatedRouteSnapshot,
) => {
  if (isNaN(Number(route.paramMap.get('productId')))) return EMPTY;

  return inject(ProductService)
    .getById(Number(route.paramMap.get('productId')))
    .pipe(filter((product) => !!product));
};

And used it in my products/:id route

RouterModule.forChild([
  {
    path: '',
    component: ProductComponent,
    resolve: {
      product: productResolver,
    },
  },
])

Problem with this implementation is if it takes a while to fetch a product by id. I can still click multiple products in the products list page before the product detail page is rendered and cause issuing multiple HTTP get requests when I only care about the last product that has been clicked

I tried wrapping the productId in an observable as follows but it didn’t seem to work as expected

export const productResolver: ResolveFn<Product | undefined> = (
  route: ActivatedRouteSnapshot,
) => {
  const productService = inject(ProductService);
  return of(Number(route.paramMap.get('productId'))).pipe(
    filter((productId) => !!productId),
    switchMap((productId) => productService.getById(productId)),
  );
};

useCallback not getting the new state from useState (react-hook-form)

I’m having issues with useCallback and react-hook-form.
Basically, I have to trigger a function when the user listens to a QR Code.

 const [result, setResult] = useState([])
 const [user, setUser] = useState(undefined)

What the issue is: the loadColab function triggers and sets the result state and the user state if isQrCode is true. But when handleVerifyColab is called, the user is undefined/null

This is without react-hook-form:

 const handleQrCode = async (cpf: string) => {
    setValue('search', cpf)
    setShowCameraModal(false)

    await loadColab({
      obra: getValues('obra'),
      search: cpf,
      isQrCode: true,
    })
    console.log(user) // This trigger undefined
    await handleVerifyColab({ obra: getValues('obra'), search: '' })
  }

This is with react-hook-form:

 const handleQrCode = async (cpf: string) => {
    setValue('search', cpf)
    setShowCameraModal(false)

    handleSubmit(loadColab)()
    console.log(user) // This trigger undefined
    handleSubmit(handleVerifyColab)()
  }

At first I though it was something with react-hook-form. That’s why I posted 2 types of calls.

The loadColab useCallback():

  const getColabDb = async (obra: any, search: any) => {
    const params = {
      term: search || '',
      obra
    }

    const { content } = await getColab(
      params,
    )

    return content
  }

const loadColab= useCallback(
    async ({ obra, search, isQrCode }: SchemaProps) => {
      try {
        console.log(obra, search, isQrCode)
        const content = await getColabDb(obra, search)

        if (content?.length === 0) {         
          return
        }

        setResult(content)

        if (isQrCode && content?.length) {
          setUser(content[0])
        }
      } catch (err) {
        console.log('erro', err)
      }
    },
    [],
  )

Verify function (This does comes with a undefined user, if the state was not even set for the user):

const handleVerifyColab = useCallback(
    async ({ obra }: SchemaProps) => {
      try {
        if (!user?.pessoa.pessoaFisica.cpf && !obra?.value) return

        const params: VerificarColaboradorRequestProps = {          
          obra: obra?.value as string,
        }

        const { content } = await verifyPerm(
          params,
        )

        setSelectedColab(content)
        setVerificadoModal(true)
      } catch (err) {
        console.log('erro verify', err)
      }
    },
    [catraca, user],
  )

Width of Canvas Square not being Constant

So this is my first time using the canvas in js, and I am trying to move the square, when it does move, the left side of the square just stays the same and it just gets wider. For example, if I press the ‘d’ key, the right side of the square keeps expanding and the left side does not move. Thanks!

let canvas = document.getElementById("canvas");
let width = window.innerWidth;
let height = window.innerHeight;
let context = canvas.getContext("2d");
let px = 0;
let directx = {"right": false, "left": false};
let speed = 6;

canvas.style.backgroundColor = "red";
canvas.width = width;
canvas.height = height;

document.addEventListener("keydown", startmove);

function startmove(event){
    if(event.key == "d"){
        directx.right = true;
        directx.left = false;
    }
    else if(event.key == "a"){
        directx.right = false;
        directx.left = true;
    }
}
function move(){
    context.fillRect(px, 0, 100, 100);
    if(directx.right == true){
        px = px + speed;
    }
    else if(directx.left == true){
        px = px - speed;
    }
    requestAnimationFrame(move);
}
move();

I tried finding a way to constantly set the width of the square, but that didnt work 🙁

Error: ‘At-rule or selector expected’ in SCSS when using Vue.js – How to Fix?

I’m working on a Vue.js project and using SCSS for styling. I have the following code in my App.vue component:

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <HelloWorld msg="Welcome to Your Vue.js App" />
  <p>weqt</p>
</template>

<script>
import HelloWorld from './components/HelloWorld.vue';

export default {
  name: 'App',
  components: {
    HelloWorld,
  },
};
</script>

<style lang="scss">
$color: red; // shown error here
body {
  background-color: $color;
  p {
    color: white;
  }
}
</style>

enter image description here

However, I’m encountering the following error: ‘At-rule or selector expectedcss(css-ruleorselectorexpected). But,The Scss syntax applies to web pages correctly, Can someone please explain why I’m getting this error and how I can fix it?

What’s puzzling is that other team members who are using the same codebase do not encounter this error.

Your assistance in resolving this issue would be greatly appreciated!

Order save multiple times in Django online store

as I stated in the title, I have a problem where an order is saved multiple times in my online store, the more I go into the problem, the more I mess it up.
I am pretty new at this and I need some assistance, thank you for taking the time to look at this hot mess.

models.py:

from django.db import models
from django.contrib.auth.models import User


class Customer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True)
    first_name = models.CharField(max_length=200, null=True)
    last_name = models.CharField(max_length=200, null=True)
    email = models.EmailField(max_length=200, null=True)
    phone = models.IntegerField(null=True)

    def __str__(self):
        return str(self.first_name) + ' ' + str(self.last_name)


class Product(models.Model):
    name = models.CharField(max_length=200)
    category = models.CharField(max_length=200, null=True, blank=True)
    price = models.IntegerField(default=1000, null=True, blank=True)
    image = models.ImageField(null=True, blank=True)

    def __str__(self):
        return str(self.id) + '.' + str(self.name)

    def display_in_euro(self):
        cents = str(self.price)
        return round(int(cents) / 100)

    @property
    def imageURL(self):
        try:
            url = self.image.url
        except:
            url = ''
        return url


class Order(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    date_ordered = models.DateTimeField(auto_now_add=True)
    complete = models.BooleanField(default=False)
    transaction_id = models.CharField(max_length=100, null=True)

    def __str__(self):
        return str(self.id) + '. ' + str(self.customer)

    @property
    def get_cart_total(self):
        order_items = self.orderitem_set.all()
        total = sum([item.get_total for item in order_items]) / 100
        return total

    @property
    def get_cart_items(self):
        order_items = self.orderitem_set.all()
        quantity = sum([item.quantity for item in order_items])
        return quantity


class OrderItem(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, blank=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True)
    quantity = models.IntegerField(default=0, null=True, blank=True)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.customer) + ' - ' + str(self.product) + '*' + str(self.quantity)

    @property
    def get_total(self):
        total = self.quantity * self.product.price
        return total

    @property
    def get_stripe_total(self):
        total = round(self.quantity * self.product.price)
        return total


class ShippingAddress(models.Model):
    customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, null=True, blank=True)
    order = models.ForeignKey(Order, on_delete=models.SET_NULL, null=True, blank=True)
    country = models.CharField(max_length=200)
    county = models.CharField(max_length=200)
    city = models.CharField(max_length=200)
    address = models.CharField(max_length=200)
    zipcode = models.CharField(max_length=200)
    date_added = models.DateTimeField(auto_now_add=True)

    def __str__(self):
        return str(self.id) + ' | ' + str(self.customer) + ' | ' + str(self.city) + ' | ' + str(self.address)

utils.py:

import json
import os
import ssl
import smtplib
from os.path import basename
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from .models import *
from fpdf import FPDF


def cookie_cart(request):
    try:
        cart_lc = json.loads(request.COOKIES['cart'])
    except:
        cart_lc = {}
    items = []
    order = {'get_cart_total': 0, 'get_cart_items': 0}
    cart_items = order['get_cart_items']
    for i in cart_lc:
        try:
            cart_items += cart_lc[i]['quantity']
            product = Product.objects.get(id=i)
            total = (product.price * cart_lc[i]['quantity'])
            order['get_cart_total'] += total
            order['get_cart_items'] += cart_lc[i]['quantity']
            item = {
                'product': {
                    'id': product.id,
                    'name': product.name,
                    'price': product.price,
                    'imageURL': product.imageURL,
                },
                'quantity': cart_lc[i]['quantity'],
                'get_total': total,
            }
            items.append(item)
        except:
            pass
    return {'items': items, 'order': order, 'cart_items': cart_items}


def cart_data(request):
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
        items = order.orderitem_set.all()
        cart_items = order.get_cart_items
    else:
        cookie_data = cookie_cart(request)
        cart_items = cookie_data['cart_items']
        items = cookie_data['items']
        order = cookie_data['order']
    return {'order': order, 'items': items, 'cart_items': cart_items}


def guest_order(request, data):
    cookie_data = cookie_cart(request)
    form = data['form']
    first_name = form['first_name']
    last_name = form['last_name']
    email = form['email']
    phone = form['phone']
    items = cookie_data['items']

    customer, created = Customer.objects.get_or_create(email=email)
    customer.first_name = first_name
    customer.last_name = last_name
    customer.phone = phone
    customer.save()

    order = Order.objects.create(customer=customer, complete=False)

    for item in items:
        product = Product.objects.get(id=item['product']['id'])
        order_item = OrderItem.objects.create(
            product=product,
            order=order,
            customer=customer,
            quantity=item['quantity'],
        )
    return {'customer': customer, 'order': order}


class GetUserData:
    def __init__(self):
        self.first_name = None
        self.last_name = None
        self.email = None
        self.phone = None
        self.cart_items = {
            'item_id': [],
            'item_name': [],
            'item_price': [],
            'item_quantity': [],
            'item_total': []
        }

    @staticmethod
    def get_shipping_info(data):
        shipping = data.get('shipping', {})
        return {
            'country': shipping.get('country', ''),
            'county': shipping.get('county', ''),
            'city': shipping.get('city', ''),
            'address': shipping.get('address', ''),
            'zipcode': shipping.get('zipcode', ''),
        }

    def get_user_details(self, data, request):
        if request.user.is_anonymous:
            self.first_name = data['form']['first_name']
            self.last_name = data['form']['last_name']
            self.email = data['form']['email']
            self.phone = data['form']['phone']
        else:
            customer_lc = request.user.customer
            self.first_name = customer_lc.first_name
            self.last_name = customer_lc.last_name
            self.email = customer_lc.email
            self.phone = customer_lc.phone
        return {
            'first_name': self.first_name,
            "last_name": self.last_name,
            'email': self.email,
            'phone': self.phone,
        }

    def get_user_order(self, request):
        user = request.user
        if user.is_anonymous:
            cart = cookie_cart(request)['items']
        else:
            customer = user.customer
            order = Order.objects.filter(customer=customer, complete=False).first()

            if not order:
                order = Order.objects.create(customer=customer, complete=False)

            cart = OrderItem.objects.filter(order=order)

        for item in cart:
            if request.user.is_anonymous:
                item_id = item['product']['id']
                item_name = item['product']['name']
                item_price = item['product']['price']
                item_quantity = item['quantity']
            else:
                item_id = item.product.id
                item_name = item.product.name
                item_price = item.product.price
                item_quantity = item.quantity
            item_total = item_price * item_quantity
            self.cart_items['item_id'].append(item_id)
            self.cart_items['item_name'].append(item_name)
            self.cart_items['item_price'].append(item_price)
            self.cart_items['item_quantity'].append(item_quantity)
            self.cart_items['item_total'].append(item_total)
        return self.cart_items


class PDF(FPDF):
    def header(self):
        self.set_font('helvetica', 'B', 25)
        title = 'Magic Home Decors'
        title_w = self.get_string_width(title) + 6
        doc_w = self.w
        self.set_x((doc_w - title_w) / 2)
        # Title Background Color
        self.set_fill_color(230, 230, 0)
        # Text Color
        # self.set_text_color(255, 255, 255)
        # Border Width
        self.set_line_width(1)
        self.cell(title_w, 10, title, border='B', align='C', ln=True)
        self.ln(10)

    def footer(self):
        self.set_y(-15)
        self.set_font('helvetica', 'I', 15)
        self.set_text_color(169, 169, 169)
        self.cell(0, 10, f'Page {self.page_no()}/{{nb}}', align='C')


def make_invoice(data, request, user_order):
    user_data = GetUserData()
    user_address = user_data.get_shipping_info(data=data)
    user_info = user_data.get_user_details(data=data, request=request)
    user_data.get_user_order(request=request)
    user_cart_items = user_order

    pdf = PDF(orientation='P', unit='mm', format='A4')
    pdf.alias_nb_pages()
    pdf.set_auto_page_break(auto=True, margin=15)
    pdf.add_page()
    pdf.set_font('helvetica', 'B', 20)

    # Content
    pdf.cell(0, 15, 'User Address:', align='L', ln=False)
    pdf.cell(0, 15, 'User Info:', align='R', ln=True)
    pdf.set_font('helvetica', '', 15)
    start_y = pdf.get_y()  # Get the starting Y position before the first multi_cell

    pdf.multi_cell(0, 15, txt=f"""
    Country: {user_address['country']},
    County: {user_address['county']},
    City: {user_address['city']},
    Address: {user_address['address']},
    ZipCode: {user_address['zipcode']},
    """, align='L', ln=False)

    pdf.set_y(start_y)  # Reset the Y position for the second multi_cell
    pdf.set_x(105)  # Adjust the X position for the second multi_cell

    pdf.multi_cell(0, 15, txt=f"""
    First Name: {user_info['first_name']},
    Last Name: {user_info['last_name']},
    Email Address: {user_info['email']},
    Phone Number: {user_info['phone']},
    """, align='R', ln=True)

    # Draw border
    pdf.cell(0, 10, '', border='B', ln=True, align='C')

    # Items:
    pdf.set_draw_color(169, 169, 169)
    pdf.set_font('helvetica', 'I', 12)
    pdf.cell(0, 10, 'Ordered Items: ', border='B', ln=True, align='C')
    item_name = user_cart_items['item_name']
    item_price = user_cart_items['item_price']
    item_quantity = user_cart_items['item_quantity']
    item_total = user_cart_items['item_total']
    for i in user_cart_items['item_id']:
        i -= 1
        pdf.cell(0, 10, f"""
        {i + 1}. {item_name[i]}: {int(item_price[i]) / 100} * {item_quantity[i]} = {int(item_total[i]) / 100}
        """, border='B', ln=True, align='C')
    pdf.cell(0, 10, f"Invoice Total: {sum(user_cart_items['item_total']) / 100}", align='C', border='B')

    return pdf.output(f"static/invoices/InvoiceFor{user_info['first_name']}{user_info['last_name']}.pdf")


class SendEmail:
    def __init__(self):
        self.user_data = GetUserData()
        self.sender = '[email protected]'
        self.password = os.getenv('PASS')
        self.seller = '[email protected]'
        self.subject = 'Magic Home Decors'
        self.context = ssl.create_default_context()
        self.server = smtplib.SMTP_SSL(host='smtp.gmail.com', port=465, context=self.context)
        self.server.login(self.sender, self.password)

    def send_email(self, data, request, receiver):
        msg = MIMEMultipart()
        msg['From'] = self.sender
        msg['Subject'] = self.subject

        user_details = self.user_data.get_user_details(data=data, request=request)
        fname = user_details['first_name']
        lname = user_details['last_name']

        filename = f"static/invoices/InvoiceFor{fname}{lname}.pdf"

        with open(filename, 'rb') as f:
            attachment = MIMEApplication(f.read(), Name=basename(filename))
            attachment['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename))

        msg.attach(attachment)

        customer_body = f"""
        Thank you {fname} for choosing Magic Home Decors! n
        You have successfully placed an order! n
        Below you can find an invoice with your details and your order:
        """

        body = MIMEText(customer_body, 'plain')

        msg['To'] = receiver
        msg.attach(body)

        return self.server.send_message(msg, from_addr=self.sender, to_addrs=[receiver])

    def send_seller_email(self, data, request):
        msg = MIMEMultipart()
        msg['From'] = self.sender
        msg['Subject'] = self.subject

        user_details = self.user_data.get_user_details(data=data, request=request)
        fname = user_details['first_name']
        lname = user_details['last_name']

        filename = f"static/invoices/InvoiceFor{fname}{lname}.pdf"

        with open(filename, 'rb') as f:
            attachment = MIMEApplication(f.read(), Name=basename(filename))
            attachment['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename))

        msg.attach(attachment)

        seller_body = f"""
        An order has been placed by {fname} {lname} n
        You can find the invoice with {fname}'s data attached below!
        """

        body = MIMEText(seller_body, 'plain')

        msg.add_header('To', self.seller)
        msg.attach(body)  # Attach the seller's email body here

        return self.server.send_message(msg, from_addr=self.sender, to_addrs=[self.seller])

views.py:

import os
import time

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings
from .utils import cart_data, guest_order, SendEmail, make_invoice, GetUserData
from .models import *
import json
import datetime
import stripe
import pickle

stripe.api_key = settings.STRIPE_SECRET_KEY


def store(request):
    products = Product.objects.all()
    cart_items = cart_data(request)['cart_items']
    context = {'products': products, 'cartItems': cart_items}
    return render(request, 'store/store.html', context)


def cart(request):
    data = cart_data(request)
    items = data['items']
    order = data['order']
    cart_items = data['cart_items']
    if request.user.is_anonymous:
        order['get_cart_total'] = order['get_cart_total'] / 100
        for item in items:
            item['product']['price'] = item['product']['price'] / 100
            item['get_total'] = item['get_total'] / 100
    else:
        for item in items:
            item.product.price = item.product.display_in_euro()
    context = {'basket': items,
               'order': order,
               'cartItems': cart_items,
               'logged': request.user.is_authenticated}
    return render(request, 'store/cart.html', context)


def checkout(request):
    data = cart_data(request)
    items = data['items']
    order = data['order']
    cart_items = data['cart_items']
    item_id = None
    user_order = []
    if request.user.is_anonymous:
        order['get_cart_total'] = order['get_cart_total'] / 100
    for item in items:
        if request.user.is_anonymous:
            item['product']['price'] = item['product']['price'] / 100
            item['get_total'] = item['get_total'] / 100
        else:
            item.product.price = item.product.display_in_euro()
        try:
            item_id = item.product.id
        except Exception as e:
            item_id = item['product']['id']
    user_data = GetUserData()
    user_order = user_data.get_user_order(request)
    pickle_out = open("user_order.pickle", "wb")
    pickle.dump(obj=user_order, file=pickle_out)
    pickle_out.close()
    product = Product.objects.get(id=item_id)
    context = {'basket': items,
               'order': order,
               'cartItems': cart_items,
               'STRIPE_PUBLIC_KEY': settings.STRIPE_PUBLIC_KEY,
               'product': product}
    return render(request, 'store/checkout.html', context)


def update_item(request):
    data = json.loads(request.body)
    product_id = data['productId']
    action = data['action']

    customer = request.user.customer
    product = Product.objects.get(id=product_id)
    order, created = Order.objects.get_or_create(customer=customer, complete=False)
    order_item, created = OrderItem.objects.get_or_create(order=order, product=product, customer=customer)

    if action == 'add':
        order_item.quantity = (order_item.quantity + 1)
    elif action == 'remove':
        order_item.quantity = (order_item.quantity - 1)

    if order_item.quantity <= 0:
        order_item.quantity = 0
        order_item.delete()
    else:
        order_item.save()
    return JsonResponse('item Was Added!', safe=False)


def success(request):
    return render(request, 'store/success.html')


def cancel(request):
    return render(request, 'store/cancel.html')


def process_order(request):
    transaction_id = datetime.datetime.now().timestamp()
    data = json.loads(request.body)
    pickle_out = open("user_data.pickle", "wb")
    pickle.dump(obj=data, file=pickle_out)
    pickle_out.close()
    if request.user.is_authenticated:
        customer = request.user.customer
        order, created = Order.objects.get_or_create(customer=customer, complete=False)
    else:
        customer = guest_order(request=request, data=data)['customer']
        order = guest_order(request=request, data=data)['order']
    total = float(data['form']['total'])
    order.transaction_id = transaction_id
    if total == order.get_cart_total:
        order.complete = True

    order.save()

    ShippingAddress.objects.create(
        customer=customer,
        order=order,
        country=data['shipping']['country'],
        county=data['shipping']['county'],
        city=data['shipping']['city'],
        address=data['shipping']['address'],
        zipcode=data['shipping']['zipcode'],
    )

    return JsonResponse('Payment Complete', safe=False)


class CreateCheckoutSessionView(View):
    def post(self, request, *args, **kwargs):
        data = cart_data(request)
        items = data['items']
        line_items = []
        prod_id_list = ''
        for item in items:
            try:
                quantity = item.quantity
                item_price = item.product.price
                item_name = item.product.name
                prod_id_list += str(item.product.id)
            except Exception as e:
                quantity = item['quantity']
                item_price = item['product']['price']
                item_name = item['product']['name']
                prod_id_list += str(item['product']['id'])

            line_items.append(
                {
                    'price_data': {
                        'currency': 'eur',
                        'unit_amount': item_price,
                        'product_data': {
                            'name': item_name,
                        },
                    },
                    'quantity': quantity
                },
            )

        YOUR_DOMAIN = 'http://127.0.0.1:8000'
        product_id = self.kwargs["pk"]
        product = Product.objects.get(id=product_id)

        checkout_session = stripe.checkout.Session.create(
            payment_method_types=['card'],
            line_items=line_items,
            metadata={
                "product_id": prod_id_list
            },
            mode='payment',
            success_url=YOUR_DOMAIN + '/success/',
            cancel_url=YOUR_DOMAIN + '/cancel/',
        )
        return JsonResponse({
            'id': checkout_session.id
        })


@csrf_exempt
def stripe_web_hook(request):
    payload = request.body
    sig_header = request.META['HTTP_STRIPE_SIGNATURE']
    event = None
    try:
        event = stripe.Webhook.construct_event(
            payload, sig_header, settings.STRIPE_WEBHOOK_SECRET
        )
    except ValueError as e:
        return HttpResponse(status=400)
    except stripe.error.SignatureVerificationError as e:
        return HttpResponse(status=400)

    if event['type'] == 'checkout.session.completed':
        session = event['data']['object']
        pickle_in = open("user_data.pickle", "rb")
        pickle_in_order = open("user_order.pickle", "rb")
        user_data = pickle.load(pickle_in)
        user_order = pickle.load(pickle_in_order)
        print("USER_DATA: ", user_data)
        make_invoice(data=user_data, request=request, user_order=user_order)
        mail = SendEmail()
        receiver = session["customer_details"]["email"]
        print("RECEIVER: ", receiver)
        mail.send_email(data=user_data, request=request, receiver=receiver)
        mail.send_seller_email(data=user_data, request=request)
    return HttpResponse(status=200)

I tried everything I could possibly think of

Javascrip Click Button Using ClassName

I have TWO buttons on webpage with the following classes (below).

Only 1 of the 2 buttons work, not sure why the other is not working.

Button 1 (OK):

<button _ngcontent-vil-c68="" 
class="btn btn-success bet ng-star-inserted"><span _ngcontent-vil-c68="" 
 //Button 1 Click (Working)
 document.getElementsByClassName('btn btn-success bet ng-star-inserted')[0].click();

Button 2 (Not OK):

<div _ngcontent-vil-c66="" 
class="buttons"><button _ngcontent-vil-c66="" type="button" 
class="plus ng-star-inserted">

//Button 2 (Tried the following but not working)
document.getElementsByClassName('buttons')[0].click();
document.getElementsByClassName('plus ng-star-inserted')[0].click();
document.querySelector('.plus .ng-star-inserted').click();

Both buttons are from the same webpage.

Image not aligning to left

My image is not aligning to the left in css

please help

This is my website screenshot

my image is not aligned to left

html code

<div class="poster">
           

 <img src="ac51af11-090c-49e8-9296-472de72fc5cb (1).webp" alt="poster">

        </div>

**css code **

.poster {
    padding: 0px;
    background-position: center;
    background-size: cover;
    margin-left: 0px;
    margin-block-start: 0em;
    margin-block-end: 0em;
    margin-inline-start: 0px;
    margin-inline-end: 0px;
    object-fit: cover;
    margin-bottom: 0px;
    vertical-align: middle;
    margin-top: 15px;
    margin-right: 150px;
}

I tried many codes and saw tutorials but i cant understand

Is it possible to determine which links on the site have been clicked by the user and which have not yet been placed by the user?

There is a list of links, I need to track which of them have already been clicked, and which have not been clicked yet.

For example:
There are no links that have been clicked, I should start with the first one.
The first and second links have been placed, you should start with the third.

How can this be implemented?

Was looking to find a solution using querySelector and a:visited, but the browser won’t let me access that information.

Tensorflow learns poorly if the output data form is tf.tensor2d(outputArr, [100,2]);

The neural network learns poorly if the output data form is tf.tensor2d(outputArr, [100,2]);
but when tf.tensor2d(inputArr, [100, 1]); then everything is fine, or tf.tensor2d(inputArr, [1, 1]);

I need to predict two multipliers, but when there are 2 output elements, the Loss does not go below 0.035. I copied all the code here. For example, when I predict 1 element, for example the result of division, then everything is fine.

import {reactive} from "vue";

const tf = require('@tensorflow/tfjs')

const stateTf = reactive({
    result: 0,

});


let model = null
function initTf(){
    model = tf.sequential();
    model.add(tf.layers.dense({ inputShape: [1], units: 2, activation: 'linear', useBias: true }));
    
    model.add(tf.layers.dense({inputShape: [2], units: 2, activation: 'linear', useBias: true }));
    model.compile({loss: tf.losses.meanSquaredError, optimizer: tf.train.sgd(0.01)});

    enterFrame()
}


async function doTraining(model, inputArr, outputArr, epochs = 1, batchSize=32) {

    let inputTensor = tf.tensor2d(inputArr, [100, 1]);
    let outputTensor = tf.tensor2d(outputArr, [100,2]);

    await model.fit(inputTensor, outputTensor, {
        batchSize,
        epochs: epochs, shuffle: true, callbacks: {
            onEpochEnd: async (epoch, logs) => {
                console.log("epoch:"
                    + epoch
                    + " result:"
                    + JSON.stringify(logs));

            }
        }
    });
}

let requestId
let inputArr = []
let outputArr
let randomNumber
let randomNumber2
let maximum



function enterFrame()
{
    requestId = undefined;
    inputArr = []
    outputArr = []
    randomNumber = 0
    randomNumber2 = 0
    maximum = 100
    for(let i=0; i<100; i++){
        randomNumber = getRandomInt(1, maximum);
        randomNumber2 = getRandomInt(1, randomNumber);
        inputArr.push((randomNumber)/maximum)
        outputArr.push([(randomNumber/randomNumber2)/maximum, randomNumber2/maximum])
    }

    doTraining(model, inputArr, outputArr, 100).then(() => {
        const inputValue = [12/maximum];
        const prediction = model.predict(tf.tensor2d(inputValue,[1,1]));
        console.log(inputArr, outputArr)
        console.log("prediction:", prediction.arraySync()[0][0]*maximum);
        console.log("prediction:", prediction.arraySync()[0][1]*maximum);

        requestId = requestAnimationFrame(enterFrame);
    });



}

function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

“menu icon is getting displaced when i toggle my menu icon” how can i fix it?

I’m trying to make a menu toggle bar in my web for mobile devices but getting an error. The toggle icon gets displaced when I open it. Here is an example:

when menu is off:

when menu is on: See the menu icon change the position and gets displaced to left side, How can I fix it ?

Here is the source code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css">

    <style>
    *{
        background-color: #000;
    }

    #menu {
    display: none;
    }
  
    #menu > i {
    
    transition: 0.4s;
    text-align: right;
    color: #f0f8ff;
    font-size: 25px;  
    }

    #navbar{
    display: block;
    float: right;
    position: sticky;
    top: 0;
    z-index: 100;
    padding-top: 15px;
    padding-right: 50px;

}


@media (max-width: 480px){
    #menu {
        display: block;
        cursor: pointer;
        /* text-align: right; */
        float: right;
        /* margin-right: -174px; */
        margin-top: 35px;
        margin-right: 35px;
      }
    
      #navbar {
        display: none;
        flex-direction: column;
        text-align: center;
      }
    
      #navbar.open {
        display: flex;
        margin-top: 38px;
        padding-right: 5px;
        height: fit-content;
        position: sticky;
        z-index: 100;

      }
    
      #navbar.open a {
        margin: 10px;
        font-size: 22px;
        padding: 10px;
        
      }

      #nav_container{
        position: sticky;
        top: 0;

      }

      #left-heading{
        font-size: 30px;
        padding-top: 23px;
        padding-left: 15px;
      }
 
      #background1 > h1{
        font-size: 40px;
        margin-top: 245px;
        padding-top: 0px;
      }
    }
    </style>
</head>
<body>
    <div id="nav_container" >
        <nav id="navbar">
          <a href="projects.html"><i class="fas fa-laptop-code"></i> Projects</a>
          <a href="about.html"><i class="fas fa-rocket"></i> About me</a>
          <a href=""><i class="fas fa-wrench"></i> Services</a>
          <a href=""><i class="fas fa-envelope"></i> Contact me</a>
        </nav>

        <div id="menu">
           <i class="fa fa-bars" aria-hidden="true"></i>
        </div>
                 <a href="1st_webpage.html" id="left-heading"> company</a>
                </div>

          <script>
            const Menu = document.querySelector('#menu');
            const navbar = document.querySelector('#navbar');

            Menu.addEventListener('click', () => {
            navbar.classList.toggle('open');
        });

        </script>      

</body>
</html>

Vuelidate – validating login and signup forms, combined in a single form

I’m using Vuelidate for Vue3 and I’ve created a single form in a modal that serves as both login and registration form.

When you click the Register button, the form displays 4 fields – username, email, password and repeat password. Clicking the Login button only displays the email and password fields from the same form.

How can I validate the Register form separately from the Login form when we have 2 overlapping fields used in both forms – email and password.

How to Change #logo and .mobile_menu_bar_toggle:before elements colour dynamically depending on any other colour behind on a pixel level

SO… I tried, everything, I am not seemingly knowledgeable enough about this particular Plain JS solution as I thought I was.

I turned to many blogs, sites, AI’s and logic, and console logs and tests, to no avail to get what I need.

” How to Change #logo and .mobile_menu_bar_toggle:before elements colour dynamically depending on any other colour behind on a pixel level. “

Whether I skipped best practice, particular methodology or something obscure I haven’t learnt yet, I am at a loss 🙂

1 – This is a wordpress / divi theme site
2 – Its not modified in any way, base implementation.
3 – I can’t add changes to it as the deployment needs to stay as low maintenance as possible thus, the attempt in Plain JS OG JS. The only JS that has never screwed me due to Libraries

My “solution” thus far below, there are no console errors to report, but also, nothing is happening.

// Function to calculate contrast color based on a given RGB color
function calculateContrastColor(rgb) {
  var colors = rgb.match(/^rgb((d+),s*(d+),s*(d+))$/);
  if (!colors) {
    return 'black'; // Default to black if parsing fails
  }
  var r = parseInt(colors[1]);
  var g = parseInt(colors[2]);
  var b = parseInt(colors[3]);
  var luminance = 0.299 * r + 0.587 * g + 0.114 * b;
  return luminance > 128 ? 'black' : 'white';
}

// Function to update logo/icon colors based on sampled pixel colors
function updateColors() {
  var logo = document.getElementById('logo');
  var menuIcon = document.querySelector('.mobile_menu_bar_toggle');
  
  // Create hidden canvas elements to sample pixel colors
  var logoCanvas = document.createElement('canvas');
  var menuIconCanvas = document.createElement('canvas');
  logoCanvas.style.display = 'none';
  menuIconCanvas.style.display = 'none';
  
  // Set canvas dimensions to match the logo and menu icon elements
  logoCanvas.width = logo.clientWidth;
  logoCanvas.height = logo.clientHeight;
  menuIconCanvas.width = menuIcon.clientWidth;
  menuIconCanvas.height = menuIcon.clientHeight;
  
  // Append canvases to the DOM
  document.body.appendChild(logoCanvas);
  document.body.appendChild(menuIconCanvas);
  
  // Function to sample pixel color at a specific position on the canvas
  function getPixelColor(canvas, x, y) {
    var context = canvas.getContext('2d');
    var pixel = context.getImageData(x, y, 1, 1).data;
    return 'rgb(' + pixel[0] + ', ' + pixel[1] + ', ' + pixel[2] + ')';
  }
  
  // Sample pixel colors below the logo and menu icon
  var logoBelowColor = getPixelColor(logoCanvas, 0, logoCanvas.height - 1);
  var menuIconBelowColor = getPixelColor(menuIconCanvas, 0, menuIconCanvas.height - 1);
  
  // Calculate contrast colors
  var logoContrastColor = calculateContrastColor(logoBelowColor);
  var menuIconContrastColor = calculateContrastColor(menuIconBelowColor);
  
  // Apply the contrast colors
  logo.style.color = logoContrastColor;
  menuIcon.style.color = menuIconContrastColor;
  
  // Remove the canvases from the DOM
  document.body.removeChild(logoCanvas);
  document.body.removeChild(menuIconCanvas);
}

// Function to handle scroll event and update colors using requestAnimationFrame
function handleScroll() {
  requestAnimationFrame(updateColors);
}

// Initialize colors
updateColors();

// Attach the scroll event listener
window.addEventListener('scroll', handleScroll);

How to detect touch screen devices and prevent both click and touchstart events from being triggered?

The code below is for a drum machine project.

It’s working perfectly on desktop click events are working perfectly, however on touch screen devices (testing on my Iphone) I am getting no sound.
When I go to the chrome dev tools, mobile view. “is touch device” is being logged to the console so it is detecting a touch device but am getting no sound out when using my phone.

    const isTouchDevice = 'ontouchstart' in window || 
navigator.maxTouchpoints > 0;
    
    if(!isTouchDevice) {
    console.log("No Touch Device");
        kick.addEventListener("mousedown", () => {
            kicksample.currentTime = 0;
            kicksample.play();
        });
    }
    
    if(isTouchDevice) {
    console.log("Is touch device");
        kick.addEventListener("touchstart", (e) => {
            kicksample.currentTime = 0;
            kicksample.play();
            e.preventDefault();
        });
    }