How to fix the issue with some post functions not working during autopagination?

I need help solving a problem with automatic pagination. When automatic pagination occurs from the home_list.html template to the home.html template, all functions of the template stop working, even though the template itself is paginated correctly. The functionality stops working after pagination, namely: “edit” and “delete” the published post, “Add comment”, “Edit comment”, “Save edited comment”, “Delete comment”.
In the home.html template, these functions work in the {% for post in post_lists %} loop, but after automatic pagination from the home_list.html template in the {% for post in posts %} loop, these functions do not work. How can I fix this?

home.html

<div id="post_contenter">
{% for post in post_lists %}

<div class="post_content" id="post_content"> <!-- Add identifier post_content -->
    <div class="post_header">
        <div class="post_user_avatar">
            {% if post.author.avatar %}
                <img style="width:50px; height: 50px;" src="{{ post.author.avatar.url }}" class="user-picture-small">
            {% else %}
                <img style="width:50px; height: 50px;" src="{% static 'twippie/img/avatar.png' %}" class="card_user_picture_small">
            {% endif %}
        </div>
        <div class="post_user_info">
            <div class="post_user_fullname"><a href="{% url 'user:profile_username' post.author.username %}" class="post_user_fullname_style">{{ post.author.first_name }} {{ post.author.last_name }}</a></div>
            <div class="post_user_username"><a href="{{ user_profile.username }}" class="post_user_nickname_style">@{{ post.author }}</a>

                 {% if post.author.verification %}
    <span class="verified_user_small"></span>
                {% endif %}

            </div>
            <div class="post_user_date"><a href="{{ post.get_absolute_url }}" class="post_user_date_style">{{ post.time_create }} {{ post.time_create|naturaltime }}</a></div>
        </div>
    </div>
    <div class="post_user_more">
        <div class="dropdown dropbtn" style="float:right;">
            <div class="dropdown-content">
                {% if request.user == post.author %}
                    <span><a href="{% url 'edit_post' post_slug=post.slug %}" class="post_user_edit">Edit</a></span>
                {% endif %}
                {% if user.is_authenticated and user == post.author %}
                    <span><a href="{% url 'delete_post' post_slug=post.slug %}" class="post_user_delete">Delete post</a></span>
                {% endif %}

                <span><a href="" class="post_user_complain">Report</a></span>
            </div>
        </div>
    </div>
    <div class="post_user_content">
        {{ post.content }}
    </div>
    <div class="post_user_action">



<div class="post_user_liked_post">


{% if liked_by_current_user %}
    <div class="unlike-button" id="unlike-button-{{ post.id }}" data-post-id="{{ post.id }}"></div>
{% else %}
    <div class="like-button" id="like-button-{{ post.id }}" data-post-id="{{ post.id }}"></div>
{% endif %}
    <div class="count_likevalue">
        <span class="like-count-value like_count_style" id="like-count-{{ post.id }}" data-post-id="{{ post.id }}">{{ like_count }}</span>
    </div>


</div>

        <div class="containercomment_post">
            <!-- Unique identifier for each post -->
    <div class="post_user_comment_post" data-post-id="{{ post.id }}">
        <span class="count_comment">{{ post.comments.count }}</span>
    </div>

        </div>
        <div class="post_user_share_post"></div>
        <div class="post_user_views_post">
            <div class="post_user_views_post_count"><span class="post_user_views_post_count_style">125025</span></div>
        </div>

    </div>



            <!-- Unique identifier for each comment form -->
    <div class="comment-form hidden" data-post-id="{{ post.id }}">
        <hr>
        <form action="{% url 'add_comment' post_id=post.id %}" method="post">
            {% csrf_token %}
            <textarea name="content" class="user_comment_style" placeholder="Write a comment..." required></textarea>
            <button type="submit" class="img_sbmt"></button>
        </form>
    </div>

<!-- Display all comments -->
{% for comment in post.comments.all %}
    <div class="comment-container">
        <div class="comment_post">
            {% if comment.author.avatar %}
                <img src="{{ comment.author.avatar.url }}" class="comment_author_img_style">
            {% else %}
                <img src="{% static 'twippie/img/avatar.png' %}" class="comment_author_img_style">
            {% endif %}
            <div class="comment_author"><a href="{% url 'user:profile_username' username=comment.author.username %}">{{ comment.author.first_name }}</a></div>
            <div class="comment_content" id="comment-content-{{ comment.id }}">{{ comment.content }}</div>
            <div class="comment_time">{{ comment.created_at }}
                <!--<span class="answer_comment_user"><a>Reply</a></span>-->
{% if comment.author == request.user %}
    <span id="edit-actions-{{ comment.id }}" class="edit_comment_user">
        <a href="#" onclick="editComment({{ comment.id }})" class="edit_comment_link">edit</a>
        <a href="#" onclick="saveComment(event, {{ comment.id }})" class="save_comment_link" style="display: none;">Save changes</a>
    </span>
    <span class="delete_comment_user"><a href="{% url 'delete_comment' comment_id=comment.id %}">delete</a></span>
{% endif %}
            </div>
        </div>
        {% if not forloop.last %}
            <!-- If the current comment is not the last one, add a separator -->
            <hr class="solid_bottom">
        {% endif %}
        <span class="massage_save_comment_error"></span> <!-- Error message -->
        <span id="save-message-{{ comment.id }}" class="massage_save_comment"></span> <!-- Save message -->
    </div>
{% endfor %}
    <br>
</div>

{% endfor %}

<div id="pagination-loader" class="pagination_pages" data-page="1"></div>
</div>
<script>
$(document).ready(function(){
    var loadedPage = 1; // Variable to store the loaded page number

    // Function to load the next batch of posts
    function loadNextPage() {
        // Perform an AJAX request to the server
        var nextPageUrl = '/load-posts/?page=' + (loadedPage + 1);
        console.log("Next page URL:", nextPageUrl);

        $.ajax({
            url: nextPageUrl,
            type: 'GET',
            dataType: 'json',
            success: function(response) {
                console.log("Response from server:", response);

                // Check if there is data about posts in the JSON response
                if (response.posts) {
                    // Add HTML with posts to the end of the container
                    $('#post_contenter').append(response.html_posts);

                    // Check if there are more posts on the next page
                    if (response.next_page_url) {
                        // Increase the value of the loadedPage variable
                        loadedPage++;
                    } else {
                        // If there is no next page, hide the loading indicator
                        $('#pagination-loader').hide();
                    }
                } else {
                    // If there is no data about posts, display an error message
                    console.error('Error loading posts: data about posts is missing in the JSON response');
                }
            },
            error: function(jqXHR, textStatus, errorThrown) {
                // Handle the error if it occurred during the request
                console.error('Error loading posts:', textStatus, errorThrown);
            }
        });
    }

    // Event handler for scrolling the page
    $(window).on('scroll', function() {
        // Get the current scroll position
        var scrollPosition = $(window).scrollTop();
        // Get the height of the browser window
        var windowHeight = $(window).height();
        // Get the height of the entire document
        var documentHeight = $(document).height();
        
        // If the user has scrolled to the end of the page
        if (scrollPosition + windowHeight >= documentHeight) {
            // Check if the loading indicator is visible
            if ($('#pagination-loader').is(':visible')) {
                // Load the next batch of posts
                loadNextPage();
            }
        }
    });

    // Check if the first page of posts needs to be loaded when the page is loaded
    if($(window).scrollTop() + $(window).height() == $(document).height()) {
        loadNextPage();
    }
});
</script>
<style>
    .hidden {
        display: none;
    }
</style>

home_list.html:

{% load humanize %}
{% load static %}
{% block content %}
{% if posts %}
    <div class="post-list">
        {% for post in posts %}
            {% if not forloop.first and post.author != request.user %}
           <div class="post_content" id="post_content"> <!-- Add identifier post_content -->
    <div class="post_header">
        <div class="post_user_avatar">
            {% if post.author.avatar %}
                <img style="width:50px; height: 50px;" src="{{ post.author.avatar.url }}" class="user-picture-small">
            {% else %}
                <img style="width:50px; height: 50px;" src="{% static 'twippie/img/avatar.png' %}" class="card_user_picture_small">
            {% endif %}
        </div>
        <div class="post_user_info">
            <div class="post_user_fullname"><a href="{% url 'user:profile_username' post.author.username %}" class="post_user_fullname_style">{{ post.author.first_name }} {{ post.author.last_name }}</a></div>
            <div class="post_user_username"><a href="{{ user_profile.username }}" class="post_user_nickname_style">@{{ post.author }}</a>

                 {% if post.author.verification %}
    <span class="verified_user_small"></span>
                {% endif %}

            </div>
            <div class="post_user_date"><a href="{{ post.get_absolute_url }}" class="post_user_date_style">{{ post.time_create }} {{ post.time_create|naturaltime }}</a></div>
        </div>
    </div>
    <div class="post_user_more">
        <div class="dropdown dropbtn" style="float:right;">
            <div class="dropdown-content">
                {% if request.user == post.author %}
                    <span><a href="{% url 'edit_post' post_slug=post.slug %}" class="post_user_edit">Edit</a></span>
                {% endif %}
                {% if user.is_authenticated and user == post.author %}
                    <span><a href="{% url 'delete_post' post_slug=post.slug %}" class="post_user_delete">Delete post</a></span>
                {% endif %}

                <span><a href="" class="post_user_complain">Report</a></span>
            </div>
        </div>
    </div>
    <div class="post_user_content">
        {{ post.content }}
    </div>
    <div class="post_user_action">



<div class="post_user_liked_post">


{% if liked_by_current_user %}
    <div class="unlike-button" id="unlike-button-{{ post.id }}" data-post-id="{{ post.id }}"></div>
{% else %}
    <div class="like-button" id="like-button-{{ post.id }}" data-post-id="{{ post.id }}"></div>
{% endif %}
    <div class="count_likevalue">
        <span class="like-count-value like_count_style" id="like-count-{{ post.id }}" data-post-id="{{ post.id }}">{{ like_count }}</span>
    </div>


</div>

        <div class="containercomment_post">
            <!-- Unique identifier for each post -->
    <div class="post_user_comment_post" data-post-id="{{ post.id }}">
        <span class="count_comment">{{ post.comments.count }}</span>
    </div>

        </div>
        <div class="post_user_share_post"></div>
        <div class="post_user_views_post">
            <div class="post_user_views_post_count"><span class="post_user_views_post_count_style">125025</span></div>
        </div>

    </div>



            <!-- Unique identifier for each comment form -->
    <div class="comment-form hidden" data-post-id="{{ post.id }}">
        <hr>
        <form action="{% url 'add_comment' post_id=post.id %}" method="post">
            {% csrf_token %}
            <textarea name="content" class="user_comment_style" placeholder="Write a comment..." required></textarea>
            <button type="submit" class="img_sbmt"></button>
        </form>
    </div>

<!-- Display all comments -->
{% for comment in post.comments.all %}
    <div class="comment-container">
        <div class="comment_post">
            {% if comment.author.avatar %}
                <img src="{{ comment.author.avatar.url }}" class="comment_author_img_style">
            {% else %}
                <img src="{% static 'twippie/img/avatar.png' %}" class="comment_author_img_style">
            {% endif %}
            <div class="comment_author"><a href="{% url 'user:profile_username' username=comment.author.username %}">{{ comment.author.first_name }}</a></div>
            <div class="comment_content" id="comment-content-{{ comment.id }}">{{ comment.content }}</div>
            <div class="comment_time">{{ comment.created_at }}
                <!--<span class="answer_comment_user"><a>Reply</a></span>-->
{% if comment.author == request.user %}
    <span id="edit-actions-{{ comment.id }}" class="edit_comment_user">
        <a href="#" onclick="editComment({{ comment.id }})" class="edit_comment_link">edit</a>
        <a href="#" onclick="saveComment(event, {{ comment.id }})" class="save_comment_link" style="display: none;">Save changes</a>
    </span>
    <span class="delete_comment_user"><a href="{% url 'delete_comment' comment_id=comment.id %}">delete</a></span>
{% endif %}
            </div>
        </div>
        {% if not forloop.last %}
            <!-- If the current comment is not the last one, add a separator -->
            <hr class="solid_bottom">
        {% endif %}
        <span class="massage_save_comment_error"></span> <!-- Error message -->
        <span id="save-message-{{ comment.id }}" class="massage_save_comment"></span> <!-- Save message -->
    </div>
{% endfor %}
    <br>
</div>
            {% endif %}
        {% endfor %}
    </div>
{% else %}
    <p>No posts to display yet.</p>
{% endif %}




<style>
    .hidden {
        display: none;
    }
</style>

{% endblock %}

views.py:

from django.shortcuts import render, redirect
from usercreatepost.forms import PostForm
from publication.models import Userpublication
from user.models import ProfileMyapp, Subscription
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.urls import reverse
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.db.models import Q

@login_required
def create_post(request):
    form = PostForm(request.POST or None)

    if request.method == 'POST':
        if form.is_valid():
            post = form.save(commit=False)
            post.author = request.user
            post.save()
            return redirect('home')

    # Get IDs of users subscribed by the current user
    subscribed_user_ids = Subscription.objects.filter(subscriber=request.user).values_list('target_user', flat=True)

    # Get all posts by authors subscribed by the current user
    subscribed_posts = Userpublication.objects.filter(author__in=subscribed_user_ids)

    # Get all posts by the current user
    own_posts = Userpublication.objects.filter(author=request.user)

    # Merge post lists
    all_posts = (subscribed_posts | own_posts).order_by('-time_create')

    # Get page object of posts to display
    page_number = request.GET.get('page', 1)
    paginator = Paginator(all_posts, 5)  # 5 posts per page

    try:
        page_posts = paginator.page(page_number)
    except PageNotAnInteger:
        page_posts = paginator.page(1)
    except EmptyPage:
        page_posts = paginator.page(paginator.num_pages)

    context = {'form': form, 'post_lists': page_posts, 'title': 'Myapp | News', 'page_number': page_number}
    return render(request, 'myapp/home.html', context)

def load_posts(request):
    # Get page number from the request
    page_number = request.GET.get('page', 1)  # Set default value to 1

    # Get IDs of users subscribed by the current user
    subscribed_user_ids = Subscription.objects.filter(subscriber=request.user).values_list('target_user', flat=True)

    # Get all posts subscribed by the current user or authored by them
    all_posts = Userpublication.objects.filter(Q(author__in=subscribed_user_ids) | Q(author=request.user)).order_by('-time_create')

    # Create a Paginator object
    paginator = Paginator(all_posts, 5)  # 5 posts per page

    try:
        # Get objects for the current page
        current_page_posts = paginator.page(page_number)
    except PageNotAnInteger:
        # If page number is not an integer, show the first page
        current_page_posts = paginator.page(1)
    except EmptyPage:
        # If page number is out of range, return an empty response
        return JsonResponse({'posts': [], 'next_page_url': None})

    # Rendering HTML markup of posts
    html_posts = render_to_string('myapp/home_list.html', {'posts': current_page_posts})

    # Forming a list of posts to pass to JSON
    posts_list = [{'id': post.id, 'content': post.content} for post in current_page_posts]

    # Get URL for the next page if it exists
    next_page_url = None
    if current_page_posts.has_next():
        next_page_url = reverse('load_posts') + f'?page={current_page_posts.next_page_number()}'

    # Return JSON response with data about the posts, HTML markup, and URL of the next page
    return JsonResponse({'posts': posts_list, 'html_posts': html_posts, 'next_page_url': next_page_url})

Webpack hot module replacement fully reloads page in response to css style changes, fully resetting application state

What is wrong with my config? Why doesn’t HMR work as specified?

I want web-dev-server to hot module replacement, in response to project changes not fully refresh i.e liveReload. This is disruptive to my workflow as, when my application state resets while i’m working on styling, I have to go through an entire e2e flow just to see the effects of my change.

The webpack-dev-server does not function along with its API specifications. Despite my config being set to devServer.hot, webpack liveReloads to every file change, be it css, js or html.

According to the Webpack-dev-servers documentation, for liveReload to take effect, devServer.hot must be disabled.

By default, the dev-server will reload/refresh the page when file changes are detected. devServer.hot option must be disabled or devServer.watchFiles option must be enabled in order for liveReload to take effect. Disable devServer.liveReload by setting it to false:

source

So liveReload shouldn’t even be working yet somehow it supercedes HMR.

This is my webpack config

webpack.dev.js

const { merge } = require('webpack-merge');
const common = require('./webpack.common');

module.exports = merge(common, {
  mode: 'development',
  devtool: 'inline-source-map',
  devServer: {
    static: './src',
    port: 8080,
    hot: 'only',

    // watchFiles: ['src/*.html'],
  },
});

webpack.common.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const dotEnv = require('dotenv-webpack');

module.exports = {
  entry: {
    index: './src/index.ts',
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js'],
  },

  output: {
    filename: '[name].bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },

  module: {
    rules: [
      {
        test: /.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      },
      {
        test: /.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /.(png|svg|jpg|jpeg|gif)$/i,
        type: 'asset/resource',
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: path.resolve(__dirname, './src/app.html'),
    }),
    new dotEnv(),
  ],
};

The only thing that has worked, is setting liveReload to false. However, that makes it so that I have to manually reload html changes as HMR does not seem to function for html.

How to filter an array to a set number of responses

I am creating a social media app that allows users to follow one another. I have realized that it is now returning thousands of posts from people that are being followed. I am looking to just return the last ten posts. I assume there is some kind of filter method that allows just the last 10 posts to be rendered (without slicing).

 useEffect(() => {
    if (props.following.length !== 0) {
      const feed = [...props.feed]
        .filter(({ user }) => props.following?.includes(user?.uid))
        .sort((x, y) => y.creation - x.creation);

      
      setPosts(feed);
    }
  }, [JSON.stringify(props.following), JSON.stringify(props.feed)]);

Using Puppeteer to scrape a public API ONLY ON CHANGE

My code uses puppeteer to scrape a public API (cant get axios to work).

Takes product´s prices and saves the data into a Sqlite3 DB.

API has a view limit in every query, so it scrapes

 www.apiexample.com/api/query=shoes/start=0      
 www.apiexample.com/api/query=shoes/start=48      
 www.apiexample.com/api/query=shoes/start=96  ... there are 5200 products

It does this every hour and it compares the DB data with the new scaped data to look for differences. (prices DO change every now an then- not very frecuent).

Is there a way to scrape the URL items ONLY if there are changes in the data?

I´m looking into caching concept but I cant figure out how to do it. Is there another logic to tackle this proyect? thanks.

async function fetchData(browser, queryItem, start) {
if (!browser) {
    console.error('Browser instance is not initialized');
    return;
}
const page = await browser.newPage();

try {
    const url = `${baseURL}?query=${queryItem}&start=${start}`;
    await page.goto(url, { waitUntil: 'networkidle0' });

    const data = await page.evaluate(() => JSON.parse(document.body.innerText));
    let filteredItems = {};
    if(data.raw.itemList.items){
        filteredItems = data.raw.itemList.items.map(item => ({
            link: item.link,
            displayName: item.displayName,
            productId: item.productId,
            price: item.price,
            salePrice: item.salePrice,
            salePercentage: item.salePercentage,
            imageUrl: item.image.src
        }));
    }     

    await saveToDatabase(filteredItems);

    return {
        totalCount: data.raw.itemList.count,
        items: filteredItems
    };
} catch (error) {
    console.error('Error fetching data:', error);
} finally {
    await page.close();
}

}

Replace function using Chrome Extension

I am creating a Chrome extension to modify functions in real time using a code editor. The idea behind this extension was to update the original script with a new updated one, but since that seems impossible due to the CSP policies, I need to bypass this policy or use a different approach.

Currently, when I click on the extension on the website, it opens a popup. In the popup I click on “Open editor” and it opens a new tab with the editor adn the functions. When the new tab is loaded, the script on the original tab (the one it opened the popup) should be replaced with the modified one.

I have tried different approaches but this seems to be the one is not throwing any errors in the console, but still the functions are not replaced (changes are not reflected).

I am using a content.js to listen for messages:

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.action === 'executeFunction') {
        if (request.name && request.group) {
            const fn = new Function(request.args, request.code);

            switch (request.group) {
                case 'form':
                    window[request.name] = fn;
                    break;
                case 'template':
                    window.templateFunctions[request.name] = fn;
                    break;
                case 'global':
                    window.globalFunctions[request.name] = fn;
                    break;
            }
        }
    }
}

Then I have an editor.js to handle general scripting stuff like the evaluation of the code:

    function executeScriptInFormTab(functionName, args, code, group) {
        chrome.storage.local.get(['tabId'], function(result) {
            if (result.tabId) {
                chrome.tabs.sendMessage(result.tabId, {
                    action: 'executeFunction',
                    name: functionName,
                    args,
                    code,
                    group,
                });
            } else {
                console.error('No tabId found in storage');
            }
        });
    }

This is the manifest.json (the parts that matters, I guess):

{
    "manifest_version": 3,
    "permissions": [
        "tabs",
        "activeTab",
        "scripting",
        "storage"
    ],
    "content_scripts": [
        {
            "matches": ["<all_urls>"],
            "js": ["content.js"]
        }
    ]
}

I know the content.js is being loaded correctly because it has other actions that are working as expected. Any ideas?

Can I use Javascript IIFE to assign type scpecific value

below is my current code,

const createArtistsData = [];
    createSongPayload.artists.map((id: number) => {
      const artistsData: Prisma.ArtistsSongsCreateWithoutSongInput = {
        artist: {
          connect: {
            userId: id,
          },
        },
      };
      createArtistsData.push(artistsData);
    });

createArtistsData currently have any type. createArtistsData should have Prisma.ArtistsSongsCreateWithoutSongInput[] type, but if I specify its typePrisma.ArtistsSongsCreateWithoutSongInput[] , I have to assing value to it while declaring. I want to syse its type as constant.

How do I return Prisma.ArtistsSongsCreateWithoutSongInput[] using IIFE in the same line which can be assigned to createArtistsData

inline SVG text (js)

I want to show text within an SVG which is wholly defined in js. The SVG picture shows as expected, but the text does not.
I have tried the actual SVG definition in an online SVG viewer and it has the same result: picture is good, but no text showing.

I create the following string in js and then use it as the content in an AdvancedMarkerElementmarker in Google Maps.

SVGstring = '<svg xmlns="http://www.w3.org/2000/svg" width="26" height="26" viewBox="-3 -49 52 52" > <style>svg { margin-top: 3px margin-bottom: 3px margin-right: 3px margin-left: 3px}</style> <path  stroke="black" stroke-width="3" d="m 0,0 l 0,-25 l 23,0 l 7,-20 l 7,20 l 3,0 l 0,25 z" fill="#9494ff"  /><text x="20" y="35" font = "20px sans-serif" fill="black" >999</text></svg>'

The google maps marker then has its content set by:

        pinSvg = document.createElement('pinSvg');
        pinSvg.innerHTML = SVGstring; 
        marker.content = pinSvg;

An array of images and a for loop display the buttons. How to assign each button to open its own block by name?

I’m making my first game in Twine. I’m trying to figure out JS. I immediately apologize for the code in my examples, because… Twine has slightly modified HTML, but I don’t know how to write it correctly in pure HTML, so I copied it directly from the project. Everything in it is correct and works, but in an excerpt and in pure HTML form as here, most likely it will not work. But I threw it off so that I could follow the logic to write the correct JS. Sorry about that!
Now to the question…
I’m making a gaming phone. There is an array of icons. Using a for loop, I display the universal buttons in the grid. Only the icons in them change relative to the iteration of the loop and the array. The names of the icons correspond to the Ids of the blocks, for example foto.svg – fotoApp.
This is implemented in such a way that by adding the next application icon to the array and creating the corresponding block, the JS logic works regardless of the number of applications (images in the array).
I was able to implement the function of opening itself (opening the application occurs as in a real phone, overlapping the desktop with an open application) and opening each button, but they all open as before the first test block – “messengerApp” and so far without reference to names.
I perform the discovery by adding the class “active” and “activeNow”, replacing them and deleting them, I was able to implement the “return” button.
Actually, the task is to ensure that each button opens only its own application foto – fotoApp, phone – phoneApp, etc. I thought that somehow it was necessary to take the name of the icon and substitute it in a button in which Id = “App”, so that the total would be foto.svg -> foto+App=fotoApp and the block with this ID would receive the class “activeNow” thereby opening up. Preferably without changing the existing structure too much. Help me please!

<div class = "phone">
  <div class = "appBtns">
      for (let i = 0; i < setup.appButtonsList.length; i++) {                                                                                           
            <span id="gridItem">
                  <button id="App" class="appButton open__app">[img[setup.appButtonsList[_i]]]
                  </button>
            </span>
      }
  </div>

<div class = "messengerApp content__app"> 
</div>
<div class = "phoneApp content__app"> 
</div>
<div class = "fotoApp content__app"> 
</div>
<div class = "browserApp content__app"> 
</div>


<div class = "phoneBtns"> 
    <span  id='appLast' class="phone-button" ><<button [img[assets/img/phone/phoneBtns/lastApp.svg]]>><</button>></span>
    <span  id='appHome' class="phone-button close__app" ><<button [img[assets/img/phone/phoneBtns/homeApp.svg]]>><</button>></span>
    <span  id='appReturn' class="phone-button return__app" ><<button [img[assets/img/phone/phoneBtns/returnApp.svg]]>><</button>></span>
</div>

  </div>
.content__app {
  display: none;
}
.content__appChat {
  display: none;
}

.content__app.active {
  display: flex;
}
.content__app.activeNow {
  display: flex;
}

.content__appChat.active {
  display: flex;
}
.content__appChat.activeNow {
  display: flex;
}

.phone {
    display:flex;
    position: relative;
    flex-direction:column;
    justify-content: flex-start;
    width: 232px;
    z-index:1;
    border-radius: 30px;
    overflow: hidden;
    height: 514px;
    z-index: 1;
    background-color: blue;
}


#appButtons{
    display: grid;
    grid-template-columns: 1fr 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr 1fr 1fr 0.3fr 1fr;
    grid-template-areas:
        "6 6 6 6"
        "5 5 5 5"
        "4 4 4 4"
        "3 3 3 image"
        "upArrow upArrow upArrow upArrow"
        "phone internet sms foto";
    flex-grow: 1;
    flex-wrap: wrap;
    justify-content: center;
    justify-items: center;
    align-items: center;
    padding: 40px 10px 0px 10px;
    z-index: 2;
}
#appButtons img {
    width: 40px;
}
#gridItem {
    width: 40px;
    height:40px;
}

.messengerApp{
    position: relative;
    flex-direction:column;
    justify-content: flex-start;
    width: 232px;
    z-index:1;
    border-radius: 30px;
    overflow: hidden;
    height: 514px;
    z-index: 1;
    background-color: green;
}

.fotoApp{
    position: relative;
    flex-direction:column;
    justify-content: flex-start;
    width: 232px;
    z-index:1;
    border-radius: 30px;
    overflow: hidden;
    height: 514px;
    z-index: 1;
    background-color: red;
}

.browserApp{
    position: relative;
    flex-direction:column;
    justify-content: flex-start;
    width: 232px;
    z-index:1;
    border-radius: 30px;
    overflow: hidden;
    height: 514px;
    z-index: 1;
    background-color: black;
}

.phoneApp{
    position: relative;
    flex-direction:column;
    justify-content: flex-start;
    width: 232px;
    z-index:1;
    border-radius: 30px;
    overflow: hidden;
    height: 514px;
    z-index: 1;
    background-color: yellow;
}
let setup.appButtonsList = ['assets/img/phone/appBtns/foto.svg', 'assets/img/phone/appBtns/messenger.svg', 'assets/img/phone/appBtns/browser.svg', 'assets/img/phone/appBtns/phone.svg'];

let openApp = document.querySelectorAll('.open__app');
let openAppChat = document.querySelectorAll('.open__appChat');
let contentApp = document.querySelector('.content__app');
let contentAppChat = document.querySelector('.content__appChat');
let closeApp = document.querySelector('.close__app');
let returnApp = document.querySelector('.return__app');
let returnAppChat = document.querySelector('.messengerReturn');
const active = document.querySelector('.active');
const activeNow = document.querySelector('.activeNow');


openApp.forEach(open__app => {open__app.addEventListener('click', () => contentApp.classList.toggle('activeNow'));
});

openAppChat.forEach(open__appChat => {open__appChat.addEventListener('click', () => {contentApp.classList.replace('activeNow', 'active'); contentAppChat.classList.add('activeNow');
})
});

closeApp.addEventListener('click', () => {contentApp.classList.remove('active'); contentAppChat.classList.remove('activeNow');
});

returnApp.addEventListener('click', () => {contentAppChat.classList.remove('activeNow'); contentApp.classList.remove('activeNow'); contentApp.classList.replace('active', 'activeNow');
});

returnAppChat.addEventListener('click', () => {contentAppChat.classList.remove('activeNow');
});

I read a lot of examples on the Internet, where they open and close with one button, hide through “hidden”, through “template”, through a lister on buttons. But what I didn’t try didn’t fit mine, or I don’t know how to apply it all correctly.

Codeigniter update complex database value frontend user input

Basicaly i want to update database table image size value if a user would input custom width and height:
enter image description here

Size has a split -> widthxheight

Posting my code below
View:

    <input type="hidden" value="<?php echo html_escape($template[0]['template_id']); ?>" id="template_id">
                            <input type="text" value="" placholder="width" id="widthInput" name="widthInput">
                            <input type="text" value="" placholder="height" id="heightInput" name="heightInput">
<button id="resizecustomboth" class="btn btn-secondary">
Resize Custom
</button>

Javascript:


function updateCanvasSize() {
  const width = parseInt(widthInput.value);
  const height = parseInt(heightInput.value);


  // Calculate the ratio of width to height
  const ratio = width / height;

  // Determine the maximum physical size (in pixels)
  const maxSize = Math.max(width, height);

  // Calculate the scaled width and height based on the maximum size
  let scaledWidth, scaledHeight;
  if (width > height) {
    scaledWidth = maxSize;
    scaledHeight = maxSize / ratio;
  } else {
    scaledWidth = maxSize * ratio;
    scaledHeight = maxSize;
  }

  // Set the canvas width and height attributes
  canvas.width = scaledWidth;
  canvas.height = scaledHeight;


};

$('#resizecustomboth').click(function(){
    var newWidth = parseInt($('#widthInput').val(), 10); 
    var newHeight = parseInt($('#heightInput').val(), 10); 
    updateCanvasSize();

  
    canvas_width = canvas.getWidth();
    canvas_height = canvas.getHeight(); 

    var data = {
        'thumb': canvas.toDataURL({format: "jpg"}),
        'template_data': JSON.stringify(canvas.toJSON(properties_to_save)),
        'width': canvas_width,
        'height': canvas_height
    };

    $.ajax({
        url: ajaxurl + 'editor/save_template',
        type: "POST",
        data: data,
        success: function(data){

            var result = jQuery.parseJSON(data);
                    if(result.status){
                        var size = result.size;
                        var size_arr = size.split('x');
                        canvas_width = size_arr[0];
                        canvas_height = size_arr[1];
                        canvas.setWidth(canvas_width).setHeight(canvas_height);
                        set_canvas_size(canvas_width, canvas_height);
                        $.toaster(result.msg, 'Success', 'success');
                        Unsaved = false;
                    }else{
                        $.toaster(result.msg, 'Error', 'error');
                    }
                    $('.pg-preloader-wrap').hide();

        }
    });
});

Controller:

    public function resizecustomboth(){
        if(isset($_POST['template_size']) && $_POST['template_id']){
            $where = array( 'template_id' => $_POST['template_id'] );
            $image = $this->Common_DML->set_data( 'user_templates', $where );
            $size = '';
            if(!empty($image[0]['template_size'])){
                $size = $image[0]['template_size'];
            }
            
            $what = array(
                'template_size' => $_POST['template_size']
            );

            $this->Common_DML->set_data( 'user_templates', $what, $where );

            echo json_encode( array( 'status' => 1, 'msg' =>html_escape($this->lang->line('resize_msg')), 'size' => $size ) );
        }



        }

Model:

    public function set_data( $table_name, $what = array() , $where = array()){
        $this->db->where($where);
        $this->db->update($table_name,$what);
    }
  public function get_data( $table_name, $where = array(), $field = '*', $order = array() ){
        $this->db->select( $field );
        $this->db->from( $table_name );
        if( !empty($where) ){
             $this->db->where( $where );
        }
        if(!empty($order)){
            foreach($order as $k=>$v){
                $this->db->order_by($k, $v);
            }
        }
        $query = $this->db->get();
        return $query->result_array();
    }

Am not the best coder, but still trying to learn it step by step…
The more i look, the more it frustrates me and i guess the more mistakes i do in the code.

Some help would be very much appreciated.

Authenticate Flask rest API

I have a use case:
I have a static website without server side code and I want to send an email whenever someone submits a form on website.
To send an email i am using flask rest api. I have deployed the api seperately and then i am calling the api from the website using javascript.
Now I am wondering how can i protect my api?
I am new to authentication and authorization.
The website is open to all which means its a non user website and any one can submit their queries.
How can i secure my API And call the api using javascript with the required credentials or token.

How to request administrator rights?

How do I ask for admin rights when executing the code for this code?
For example, I have a program that creates a shortcut to a directory and it will be compiled via pkg into an .exe file:

const fs = require("fs");
const path = require("path");

fs.symlink(path.resolve("path/to/directory"), path.resolve("path/to/shortcut"), console.log);

Maybe there is some library or something else to request these rights directly from the code, or something else?

mp4 embedded videos within github pages website not loading

It’s my first time deploying a website via github pages and I’ve noticed a problem with embedding videos (mp4 in my case). Everything else is working and loading fine (including images) however whenever I try to view any of the embedded videos on my website, I get the following black screen with the controls greyed out:

Video not loading
(for reference the video in this screen shot is only 2.89 MB)

I found this weird, because while building the website and testing things on local host, everything was working fine and all embedded videos were working perfectly with full audio and video. I’ve researched a bit on what the issue is but can’t seem to get a clear solution as some people recommend hosting the videos externally like on youtube and then embedding that link but I really want the videos to work embedded within the website without having to host the videos anywhere else which is a last resort.

For reference, following are the snippets of my code relating to how I’m displaying these videos and cannot seem to find any errors so far:

index.html:

<video class="responsive-video" id="knowPros_vid" controls>
    <source src="./assets/knowPros_Demo.mp4" type="video/mp4">
    Your browser does not support the video tag.
</video>

style.css:

/* Applying CSS limits for videos used in the carousel to avoid distortion */
.responsive-video {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
}

Out of the 3 videos I have on this webpage, only one is a large video file (143 MB) but the other two are both small video files (2.89 MB & 4.39 MB), however this issue is being had with all of them which is why I think it’s safe to rule out a git-lfs problem since that’s only used for the largest video file.

I also don’t have a gitattributes file for this repository, idk if I should cause everything has been working fine without one. (don’t know if it’s important but just thought I should mention it just incase)

Getting no console errors and the page is still loading up just fine. No 404 errors or network issues.

Please let me know if anyone has faced a similar issue and if so how it can be tackled. Also if any methodologies have expired as of currently, plese let me know. Thanks 🙂

In Datatables, start value resets to 0, when column sorting

I’m using Datatables.js version 1.9, and doing server-side implementation. Pagination is working fine but, the start param is resets to 0 value if do sorting on any column.

For example If a go to 3rd or 4th page, the value of start should be persistent but here Datatables sending every time 0 value on subsequent http requests. I Checked length (no.of records per page) param, it’s good when doing sorting but start param is resets to 0. Any please suggest me on this.

enter image description here

How do I link two models in mongoose?

There are two models, ProductModel and CategoryModel.

Purpose: When creating a product (ProductModel), assign a category to it, respectively, an array of products should be filled in the category collection, but the connection between them does not work. When creating a product (ProductModel), I output the response via json, it contains all fields except the category field, I need this field to be filled in too.

Product Model

import { Schema, model } from 'mongoose'

const ProductModel = new Schema({
    productName: { type: String, required: true },
    price: { type: Number, required: true },
    preview: { type: String },
    color: { type: String, required: true },
    specs: {
        images: [{ type: String }],
        memory: { type: Number },
        ram: { type: Number },
        diagonal: { type: String },
    },
    category: {
        name: String,
        type: Schema.Types.ObjectId,
        ref: 'Category',
    },
})

export default new model('Product', ProductModel)

CategoryModel

import { Schema, model } from 'mongoose'

const CategoryModel = new Schema({
    name: {
        type: String,
        required: true,
    },
    products: [
        {
            type: Schema.Types.ObjectId,
            ref: 'Product',
        },
    ],
})

export default new model('Category', CategoryModel)

The logic of the product creation route

  async post(req, res, next) {
        try {
            // Get fields from client
            let { productName, price, preview, color, specs, category } = req.body

            // Looking for a category transferred from a client
            const productCategory = await CategoryModel.find({ name: category })
            console.log(productCategory)

            // Creating product
            const doc = new ProductModel({
                productName,
                price,
                preview,
                color,
                specs,
                category: productCategory._id,
            })

            // Save product
            const product = await doc.save()

            // Returning a response from the server to the client
            return res.json(product)
        } catch (error) {
            console.log(error.message)
        }
    }

Here is what I send to the server and receive from it

Request:
{
    "productName": "Air pods pro",
    "price": 123,
    "preview": "preview",
    "color": "red",
    "specs": {
        "images": ["image1, image2, image3"],
        "memory": 64,
        "ram": 16,
        "diagonal": "diagonal"
    },
    "category": "AirPods"
}

Response:
{
    "productName": "Air pods pro",
    "price": 123,
    "preview": "preview",
    "color": "red",
    "specs": {
        "images": [
            "image1, image2, image3"
        ],
        "memory": 64,
        "ram": 16,
        "diagonal": "diagonal"
    },
    "_id": "6609ad76341da85122e029d0",
    "__v": 0
}

As you can see, there is no category field in the response, just like in the database, this field is missing in each product. And the Category collection, which has an array of products, is also not filled

I will attach screenshots below

Mongo
Mongo