Webpack over CDN import to vue js The requested module ‘url’ does not provide an export named ‘default’

Hope you’re doing well. I’m currently working on a JavaScript module that I plan to load via a Content Delivery Network (CDN) using the URL https://x.com/my-script.js. However, I’ve hit a snag despite trying various webpack configurations.

Environment :

  • VueJS 3.3.4
  • Webpack 5.88.1
  • Webpack-cli 5.1.4

To clarify, when I simplify my module without webpack, like so:

const randomGenerator = {
    generateRandomNumber: function(min, max) {
       return Math.floor(Math.random() * (max - min + 1)) + min;
    }
};

export default randomGenerator;

…the import works like a charm. Here’s how I import and use the module:

import  randomGenerator from 'https://x.com/my-script.js'; 

console.log(randomGenerator.generateRandomNumber(1, 100));

Responses in the following Stack Question tels you how to export default and import named-default-javascript

But when I throw webpack into the mix, I get this error:

requested module 'https://x.com/my-script.js' does not provide an export named 'default'

I suspected it’s a webpack configuration issue, so I consulted the Webpack documentation, which recommends configuring output like so for a Universal Module Definition which are capable of working everywhere, be it in the client, on the server or elsewhere as noted in github :

 output: {  
   filename: 'compactedModule.js',
   path: path.resolve(__dirname, 'dist'),  
   library:'randomGenerator',
   libraryTarget: 'umd'  
 }

I also checked out how Axios axios.min.js is built, and it’s similar

Finally here is my full webpack config file :

const path = require('path');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');


module.exports = {
  mode: 'development',
  entry: '../src/test.js',
  output: {  
       filename: 'compactedModule.js',
       path: path.resolve(__dirname, 'dist'),  
       library:'randomGenerator',
       libraryTarget: 'umd'  
  },
  plugins: [
    new CleanWebpackPlugin(),
  ],
};

Note that for every changement I make to the bundle module I clear browser cache

Any help would be greatly appreciated.

Thanks in advance!

I want to show my job posting platform name in google job search gallery

I am working on a job posting platform through which companies can post job’s on google. The jobs are getting indexing and shown inside the job search gallery of google. The issue i am facing is that it is taking the domain name as the platform name unlike a job posted from linkedin which show like via linkedin and apply on linkedin button as well on my end it is showing via app-test.meetovo.de and apply on app-test.meetovo.de as well. So, i want to fix this. How can fix this issue. Please guide me regarding this. Thanks.

This is the structured data (Just an example of how it is working on my end):
https://search.google.com/test/rich-results/result/r%2Fjobs?id=fCELJANj-KQsfphyZhDOlw

This the job which is getting shown inside job gallery:
https://www.google.com/search?q=tkturners&oq=jobs&gs_lcrp=EgZjaHJvbWUqEggAEEUYOxiDARixAxjJAxiABDISCAAQRRg7GIMBGLEDGMkDGIAEMgYIARBFGDwyDQgCEAAYkgMYgAQYigUyDQgDEAAYkgMYgAQYigUyDQgEEAAYgwEYsQMYgAQyBggFEEUYPDIGCAYQRRg8MgYIBxBFGEHSAQgxMTg1ajBqN6gCALACAA&sourceid=chrome&ie=UTF-8&ibp=htl;jobs&sa=X&ved=2ahUKEwjctpHwi8uFAxUwzAIHHT9TB_YQudcGKAF6BAgfECg#fpstate=tldetail&htivrt=jobs&htidocid=ZBx4a-n0JaJk2q82AAAAAA%3D%3D

The issue is:

  1. via of left side of the screen below address and company Name
  2. Apply on Button generated as well

I tried a lot of stuff but it is still not working. What i found out you can’t create this through job posting google creates it by itself.Please help me i can’t find anything else is their a way.
I wanted to show my app company name thier instead of domain name.

Drizzle one to many relation to the same table

I have a table of articles, an article can have a parent article. Meaning that a parent article references many child articles.
I can’t find a way to query for all articles and join their child articles.

Thanks for helping me out.

This is in my schema.ts file:

export const articles = pgTable('articles', {
    id: uuid('id').defaultRandom().primaryKey(),
    title: varchar('title', { length: 600 }).notNull(),
    description: varchar('description'),    
    parentArticleId: uuid('parent_article_id').references(() => articles.id)
});
export const childArticlesRelation = relations(articles, ({ many }) => ({
    childarticles: many(articles, { relationName: 'childarticles' })
}));

And now I want to query for articles and join their child articles:

db.Instance().query.articles
        .findMany({
                where: and(...filter),
                with: {
                        childarticles: true
                }
         });

That gives me:
There is not enough information to infer relation "articles.childarticles"
Which I understand, but I can’t find anything in the docs that gives me the correct syntax.

There are two listings and the footer one is correct

So my code has to show items from a database in grid view which it does but it shows one where i want to and the another on the footer, but the one above has wrong dimensions and i want to show the footer listing on the above one and that only and remove the footer code but i am very lost here so i need help

 <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>

    <div class="container mt-5">
    <div class="grid grid-cols-1 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4">
        <!-- Grid items start here -->
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script>
            $(document).ready(function () {
                getdata();
            });

            function getdata() {
                $.ajax({
                    type: "GET",
                    url: "fetch.php",
                    success: function (response) {
                        $.each(response, function (key, value) { 
                            $('.grid').append('<div class="grid-item">
                                <a href="booking.html" class="group">
                                    <div class="aspect-h-1 aspect-w-1 w-full overflow-hidden rounded-lg bg-gray-200 xl:aspect-h-8 xl:aspect-w-7">
                                        <img src="1.jpg" class="h-80 w-full object-cover object-center group-hover:opacity-75">
                                    </div>
                                    <h3 class="mt-4 text-sm text-gray-700">' + value.Name + '</h3>
                                    <p class="mt-1 text-lg font-medium text-gray-900">$' + value.PricePerKm + '</p>
                                    <button class="mt-2 text-sm text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg px-4 py-2">Book Now</button>
                                </a>
                            </div>');
                        });
                    }
                });
            }
        </script>
    </div>
</div>

  

  <!-- FOOTER -->
  
<footer class="bg-white dark:bg-gray-900">
    <div class="mx-auto w-full max-w-screen-xl p-4 py-6 lg:py-8">
        <div class="md:flex md:justify-between">
          <div class="mb-6 md:mb-0">
              <a href="#" class="flex items-center">
                  <span class="self-center text-2xl font-semibold whitespace-nowrap dark:text-white">Vroom</span>
              </a>
          </div>
          
          <div class="grid grid-cols-2 gap-8 sm:gap-6 sm:grid-cols-3">
              <div>
                  <h2 class="mb-6 text-sm font-semibold text-gray-900 uppercase dark:text-white">Pages</h2>
                  <ul class="text-gray-500 dark:text-gray-400 font-medium">
                      <li class="mb-4">
                          <a href="#" class="hover:underline">How it works</a>
                      </li>
                      <li>
                          <a href="#" class="hover:underline">Rides</a>
                      </li>
                  </ul>
              </div>
              <div>
                  <h2 class="mb-6 text-sm font-semibold text-gray-900 uppercase dark:text-white">Follow us</h2>
                  <ul class="text-gray-500 dark:text-gray-400 font-medium">
                      <li class="mb-4">
                          <a href="#" class="hover:underline ">instagram</a>
                      </li>
                      <li>
                          <a href="#" class="hover:underline">Facebook</a>
                      </li>
                  </ul>
              </div>
              <div>
                  <h2 class="mb-6 text-sm font-semibold text-gray-900 uppercase dark:text-white">Legal</h2>
                  <ul class="text-gray-500 dark:text-gray-400 font-medium">
                      <li class="mb-4">
                          <a href="#" class="hover:underline">Privacy Policy</a>
                      </li>
                      <li>
                          <a href="#" class="hover:underline">Terms &amp; Conditions</a>
                      </li>
                  </ul>
              </div>
          </div>
      </div>
      <hr class="my-6 border-gray-200 sm:mx-auto dark:border-gray-700 lg:my-8" />
      <div class="sm:flex sm:items-center sm:justify-between">
          <span class="text-sm text-gray-500 sm:text-center dark:text-gray-400">© 2023 <a href="#" class="hover:underline">Vroom™</a>. All Rights Reserved.
          </span>
          <div class="flex mt-4 sm:justify-center sm:mt-0">
              <a href="#" class="text-gray-500 hover:text-gray-900 dark:hover:text-white">
                  <svg class="w-4 h-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 8 19">
                        <path fill-rule="evenodd" d="M6.135 3H8V0H6.135a4.147 4.147 0 0 0-4.142 4.142V6H0v3h2v9.938h3V9h2.021l.592-3H5V3.591A.6.6 0 0 1 5.592 3h.543Z" clip-rule="evenodd"/>
                    </svg>
                  <span class="sr-only">Facebook page</span>
              </a>
              <a href="#" class="text-gray-500 hover:text-gray-900 dark:hover:text-white ms-5">
                  <svg class="w-4 h-4" aria-hidden="true" xmlns="http://www.w3.org/2000/svg" fill="currentColor" viewBox="0 0 20 17">
                    <path fill-rule="evenodd" d="M20 1.892a8.178 8.178 0 0 1-2.355.635 4.074 4.074 0 0 0 1.8-2.235 8.344 8.344 0 0 1-2.605.98A4.13 4.13 0 0 0 13.85 0a4.068 4.068 0 0 0-4.1 4.038 4 4 0 0 0 .105.919A11.705 11.705 0 0 1 1.4.734a4.006 4.006 0 0 0 1.268 5.392 4.165 4.165 0 0 1-1.859-.5v.05A4.057 4.057 0 0 0 4.1 9.635a4.19 4.19 0 0 1-1.856.07 4.108 4.108 0 0 0 3.831 2.807A8.36 8.36 0 0 1 0 14.184 11.732 11.732 0 0 0 6.291 16 11.502 11.502 0 0 0 17.964 4.5c0-.177 0-.35-.012-.523A8.143 8.143 0 0 0 20 1.892Z" clip-rule="evenodd"/>
                </svg>
                  <span class="sr-only">Twitter page</span>
              </a>
          </div>
      </div>
    </div>

    <!-- MAP -->
    <div class="mx-auto w-full max-w-screen-xl p-4 py-6 lg:py-8 flex flex-col lg:flex-row justify-between items-start lg:items-center">
        <div class="mb-6 lg:mb-0">
            <a href="#" class="flex items-center">
                <span class="self-center text-2xl font-semibold whitespace-nowrap dark:text-white"></span>
            </a>
        </div>
        <div>
            <iframe src="https://www.google.com/maps/embed?pb=!1m18!1m12!1m3!1d3532.8089279289666!2d85.33153554586143!3d27.692299814989383!2m3!1f0!2f0!3f0!3m2!1i1024!2i768!4f13.1!3m3!1m2!1s0x39eb19e908b36f51%3A0x6bdb7054ec60a79d!2sEyeplex%20Mall!5e0!3m2!1sen!2snp!4v1712698272190!5m2!1sen!2snp" width="300" height="200" style="border:0;" allowfullscreen="" loading="lazy"></iframe>
        </div>
    </div>
    
</footer>
</body>
</html>

<!-- The JavaScript for search functionality -->
<script>
        // Function to perform search
        function performSearch() {
            // Get the search query
            var searchQuery = document.getElementById('default-search').value.toLowerCase();
            // Get all the product cards
            var products = document.querySelectorAll('.grid .group');
            // Loop through each product card
            products.forEach(function(product) {
                // Get the product name
                var productName = product.querySelector('h3').textContent.toLowerCase();
                // Get the product price
                var productPrice = product.querySelector('p').textContent.toLowerCase();
                // If the product name or price contains the search query, show the product card, else hide it
                if (productName.indexOf(searchQuery) > -1 || productPrice.indexOf(searchQuery) > -1) {
                    product.style.display = 'block';
                } else {
                    product.style.display = 'none';
                }
            });
        }

        // Add event listener for input change
        document.getElementById('default-search').addEventListener('input', function() {
            performSearch();
        });
    </script>

Changes in html without refreshing(ajax problem)

I got problem or i kinda don’t understand how ajax works.

I want after clicking button to add user in likes column in datatable, and then pass variables in json again to ajax which one change elements in html file. All without refreshing. i’m stuck. Ajax works with adding, deleting user, but don’t know how to return json and change elements in html.

urls.py

urlpatterns = [
    path('',views.logout_view, name = 'logout'),
    path('like/<int:pk>', views.commLike, name="comm_like"),
]

views.py

@login_required
def commLike(request, pk):
    comm_id = request.POST.get('comm_id')
    comm = Comment.objects.get(comment_id=comm_id)
    user_name = request.POST.get('user')
    user_email = request.POST.get('email')
    profile = User.objects.get(email=user_email

)
    if not User.objects.get(email=user_email):
       User.objects.create(email=user_email,name=user_name)
    if profile in comm.likes.all():
        comm.likes.remove(profile)
        is_liked = False
    else:
        comm.likes.add(profile)
        is_liked = True
    response = {}
    response['is_liked'] = is_liked
    response['total_likes'] = comm.total_likes()
    # response_data[is_liked,comm.total_likes()]
    # return render(request, 'show_post.html', { 'is_liked': is_liked, 'total_likes': comm.total_likes()})
    return JsonResponse(response)

show.html

 <form action= "{% url 'comm_like' pk=cs.comment_id %}" id=like-butt class="like-button" method="post" >
                            {% csrf_token %}
                            <input type="hidden" name="user" value="{{user}}">
                            <input type="hidden" name="email" value="{{user.email}}">
                            <input type="hidden" name="comm_id" value="{{ cs.comment_id }}">
                            <button type="submit"  id='comm_like' value="{{ cs.comment_id }}" class="comment-rating">
                                 <img src="/static/img/thumb_up.png" style="height:2rem;width:2rem;">
                            </button>
                      </form>

script.js

$('#like-butt').on('submit',function(e){
        e.preventDefault();
        console.log("form submitted!")
        comm_like();
        });


function comm_like() {
       console.log("create post is working!");
       const email =  $('input[name="email"]').val();
       const user = $('input[name="user"]').val();
       const comm_id = $('input[name="comm_id"]').val();
       console.log(user);
       console.log(email);
       console.log(comm_id);
       $.ajax({
          url : '{% url "comm_like" %}',
          type:  "GET",
          data : {
             csrfmiddlewaretoken: $('input[name=csrfmiddlewaretoken]').val(),
             email : email,
             user : user,
             comm_id : comm_id
          },
          success: function(response) {
               var response = JSON.parse(response);

               if (response.is_liked === false) {
                  $('.like-btn').html('<button><i><img src="/static/img/thumb_up_fill.png" style="height:2rem;width:2rem;display: inline-block;"></i></button>');
               } else{
                 $('.like-btn').html('<button><i><img src="/static/img/thumb_up.png" style="height:2rem;width:2rem;display: inline-block;"></i></button>');
               }
                },

       })


       };

I tried with “GET” but still site just open json with values. I’m stuck and all info on youtube, or anywhere else don’t really works. Should i do two views and separate ajax with typ: ‘Get ‘ which change elements. I don’t know anymore…

Buliding a Test/simple Survey

I’m having some slight issues with my script, perhaps you could kindly advise?

  1. On the first page (once you open the script in e.g. Chrome) I have this question displayed “Is the name easy to spell: Select E for yes and I otherwise?”, the thing is I don’t want it to be displayed on the front page, all I simply need is the instruction: “Please remember that you will be using letters: ‘E’ (corresponding to Yes) and ‘I’ (Corresponding to No) on your keyboard.
    Press E or I to start the test.”

Then, once E or I is pressed the question appears on top and the exercise begins. FYI the exercise measures the time taken to select either E or I once the e.g. name appears on the screen.

  1. How do I change the colour of particular letters in the script, namely the E and I in instructions for each question e.g. E to green and I to red?

  2. My script registers the responses which I can then review in the console (and I want to keep it this way – unless you can advise something here with regards to efficiency or improvement).

Thank you

Here is my html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>IAT Test</title>
</head>
<body>
  <div id="question" style="font-size: 20px; margin-bottom: 10px;"></div>
  <div id="stimulus" style="font-size: 24px; font-weight: bold; margin: 20px;"></div>
  <div id="instructions" style="font-size: 18px; margin-bottom: 20px;"></div>
  <script src="iat.js"></script>
</body>
</html>

Here is my js:

document.addEventListener('DOMContentLoaded', function() {
    let currentQuestionIndex = 0;
    let startTime;
    const questions = [
        {
            prompt: "Is the name easy to spell: Select E for yes and I otherwise?",
            options: ["Johnson", "Madoff", "Kaufman", "Brown"],
            responses: [],
            instruction: "Press E if yes, I if not."
        },
        {
            prompt: "Is the name easy to remember: Select E for yes and I otherwise?",
            options: ["Franklin", "Madoff", "Kaufman", "Brown"],
            responses: [],
            instruction: "Press E if yes, I if not."
        },
        {
            prompt: "Select “E” if you consider person famous and “I” otherwise.",
            options: ["Madoff", "Robson", "Eckstein", "Smith", "Rosenthal", "Johnson"],
            responses: [],
            instruction: "Press E , I otherwise."
        }
    ];

    function displayInitialPrompt() {
        const question = questions[currentQuestionIndex];
        document.getElementById('question').textContent = question.prompt;
        document.getElementById('stimulus').textContent = "Please remember that you will be using letters: 'E' (corresponding to Yes) and 'I' (Corresponding to No) on your keyboard.";
        document.getElementById('instructions').textContent = "Press E or I to start the test.";
    }

    function displayQuestion() {
        const question = questions[currentQuestionIndex];
        document.getElementById('question').textContent = question.prompt;
        document.getElementById('instructions').textContent = question.instruction;
        question.currentOptionIndex = 0;
        displayStimulus();
    }

    function displayStimulus() {
        const question = questions[currentQuestionIndex];
        if (question.currentOptionIndex < question.options.length) {
            document.getElementById('stimulus').textContent = question.options[question.currentOptionIndex];
            startTime = new Date();
        } else {
            displayTransition();
        }
    }

    function displayTransition() {
        document.getElementById('question').textContent = "Get ready. To advance to the next question, press H. REMEMBER: that you will be using letters: 'E' (corresponding to Yes) and 'I' (Corresponding to No) on your keyboard.";
        document.getElementById('stimulus').textContent = "";
        document.getElementById('instructions').textContent = "";
    }

    function endTest() {
        document.getElementById('question').textContent = "Test completed. Thank you! Your pass phrase is";
        document.getElementById('stimulus').textContent = '';
        document.getElementById('instructions').textContent = '';
        console.log('All responses:', questions.map(q => q.responses));
    }

    document.addEventListener('keydown', function(event) {
        if (event.key.toLowerCase() === 'h' && document.getElementById('question').textContent === "Get ready. To advance to the next question, press H. REMEMBER: that you will be using letters: 'E' (corresponding to Yes) and 'I' (Corresponding to No) on your keyboard.") {
            if (currentQuestionIndex < questions.length - 1) {
                currentQuestionIndex++;
                displayQuestion();
            } else {
                endTest();
            }
        } else if (event.key.toLowerCase() === "e" || event.key.toLowerCase() === "i") {
            if (document.getElementById('instructions').textContent.includes("Press E or I to start")) {
                startTest();
            } else {
                const response = event.key.toUpperCase();
                recordResponse(response);
            }
        }
    });

    function startTest() {
        displayQuestion();
    }

    function recordResponse(response) {
        const endTime = new Date();
        const reactionTime = endTime - startTime;
        const question = questions[currentQuestionIndex];
        const option = question.options[question.currentOptionIndex];
        question.responses.push({ option, response, reactionTime });
        console.log(`Recorded: ${option} - ${response} - Reaction Time: ${reactionTime} ms`);
        question.currentOptionIndex++;
        displayStimulus();
    }

    displayInitialPrompt(); // Ensure initial prompt display
});

Error while calling openapi-typescript-codegen [closed]

我在项目中想要使用这个(I want to use this in my project)
https://github.com/ferdikoomen/openapi-typescript-codegen?tab=readme-ov-file#openapi-typescript-codegen

我已经使用如下命令配置好了axios(I have configured axios using the following command)

npm install axios --save-dev
npm install [email protected] --save-dev

我的接口文档地址为(My interface document address)http://localhost:8101/api/v2/api-docs%EF%BC%8C

在终端中调用了如下命令(The following command was called in the terminal):

openapi --input http://localhost:8101/api/v2/api-docs --output ./generated --client axios

而在运行之后返回结果如下(After running, the result returned is as follows)

{
  stack: 'JSONParserError: Error downloading http://localhost:8101/api/v2/api-docs n' +
    'fetch is not definedn' +
    '    at download (D:\CodeMaster_project\codemaster-frontend\node_modules\@apidevtools\json-schema-ref-parser\dist\lib\resolvers\http.js:113:15)',        
  code: 'ERESOLVER',
  name: 'ResolverError',
  message: 'Error downloading http://localhost:8101/api/v2/api-docs n' +
    'fetch is not defined',
  source: 'http://localhost:8101/api/v2/api-docs',
  path: null,
  toJSON: [Function: toJSON],
  footprint: 'null+http://localhost:8101/api/v2/api-docs+ERESOLVER+Error downloading http://localhost:8101/api/v2/api-docs n' +
    'fetch is not defined',
  toString: [Function: toString]
}

Is there any way to solve this problem?

DB design for user and tests case

I have a case where i have a lot of users, and every user does a test every 3 months.
Each test has 30 questions with number based answer from 1 to 5, or an irrelevant answer.
Also there are “jobs”, with the same 30 questions, but every number answer is a requirement.
Assuming every person has a new test every 3 months, i have over 50,000 people, and over 10,000 jobs. The prepose is to have analytics on all the people, and on single cases, and also do data science which require to access all the data at once. What is a way to design this DB and why?

Server Send Events, EventSource on the web, for each event all previous data are send again?

Using PostgreSQL, PHP, JavaScript

Background

When I’m on the webpage and something updates on the database I want to receive a notification so I can query some data and update the page accordingly or receive the result of a query immediately to avoid in one step, went with the second one.

At first I tried setting this up myself, I did make an AJAX request to a PHP script that was using LISTEN on the database and when a related NOTIFY occured else where, it listened to it, queried the data and AJAX received it.

I noticed that each time I received all the previous data and the latest ones in the response after a NOTIFY.

So it was hard to parse and get only the latest response + the bandwidth used with each response was getting bigger and bigger. The webpage may have to run for 4-5 hours without refreshing may less, in either I researched a bit more and found out EventSource. It does my job and it gives only the last response each time.

Question

So my question is, am I fine with the following PHP and JavaScript or EventSource has the same issue I had but it hides it? Do I have to do something like restarting the EventSource every now and then to avoid too much data being send with each new response? Is there something I am missing?

const event_source = new EventSource("/_update.php?for=secretary");

event_source.addEventListener("update", (e) => {
    update(JSON.parse(e.data));
});

event_source.addEventListener("uerror", (e) => {
    alert("Updating from EventSource does not work properly: " + e.data);
    event_source.close();
});
<?php

// script: _update.php

enum Event : string {
    case UPDATE = 'update';
    case ERROR  = 'uerror';
}

enum Parameter : string {
    case FOR = 'for';
}

// ---

ob_implicit_flush(false);

function produce(Event $event, string $data) : void {
    echo "event:{$event->value}ndata:{$data}nn";
    flush();
}

// ---

if (isset($_GET) === false || isset($_GET[Parameter::FOR->value]) === false) {
    produce(Event::ERROR, "use GET method and parameter '".Parameter::FOR->value."'n");
    exit(0);
}

require_once $_SERVER['DOCUMENT_ROOT'] . '/.private/database.php';

$db = database();

$request_data = [
    'secretary' => function () use ($db) : array  {
        return $db->retrieve("interviewee");
    }
];

$for = $_GET[Parameter::FOR->value];

if (in_array($for, array_keys($request_data)) === false) {
    produce(Event::ERROR, "unknown value of '" . Parameter::FOR->value . "' parameter: {$for}n");
    exit(0);
}

// ---

header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
header("X-Accel-Buffering: no");

try {
    $conf = (require $_SERVER['DOCUMENT_ROOT'] . '/.private/config.php')['dbms'];

    $listener = new PDO(
        "pgsql:host={$conf['host']};dbname={$conf['dbname']}", $conf['user'], $conf['password'],
        [
            PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
            PDO::ATTR_EMULATE_PREPARES   => false,
        ]
    );
    
    $listener->exec("LISTEN " . Postgres::$UPDATE_CHANNEL . ";");
    
    while (connection_aborted() === 0) {

        $notification = $listener->pgsqlGetNotify(PDO::FETCH_ASSOC, 25_000); // at 30_000 php timesout

        if ($notification === false) {
            continue;
        }

        produce(Event::UPDATE, json_encode($request_data[$for]()));
    }

    $listener = null;
} 
catch (PDOException $e) {
    produce(Event::ERROR, $e->getMessage());
}

How to implement multiple Requests in React/Gatsby

I am trying to implement multiple requests to database and then display the results in my gatsby app.

I have a working solution with one (!) request.

const ListRezept = (props) => {

const url_id = props.params.id;
const [data, setData] = useState(null);
const [isPending, setIsPending] = useState(true);
const [error, setError] = useState(null);

 useEffect(() => {
    const abortCont = new AbortController();

    setTimeout(() => {
    fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezept?$filter=RezeptId eq '+ url_id)
       .then(res => {
          if (!res.ok) { // error coming back from server
            console.log("error");
            throw Error('Could not fetch the data for that resource!');
          } 
          return res.json();
       })
       .then(data => {
        setIsPending(false);
        setData(data.value);
        setError(null);
       })
       .catch(err => {
        if (err.name === 'AbortError') {
          console.log('fetch aborted')
        } else {
          // auto catches network / connection error
          setIsPending(false);
          setError(err.message);
        }
       });
 }, []);

     // abort the fetch
     return () => abortCont.abort();
    }, []) 
    
 ...
   
 }

Now I want to integrate the Promise.all function for calling multiple requests.
How can I do that?
In many websites there is only an example how to call mutiple requests and log them in the console.
for e.g. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

In my approach I have to map each result of the single request to an variable.

Here you can see how I started, but failed… I don’t know how to handle the multiple answers in Promise.all

const rezeptreq = fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezept?$filter=RezeptId eq '+ url_id);
const rezeptartreq = fetch('https://abc.4.azurestaticapps.net/data-api/rest/Rezeptart');

Promise.all([rezeptreq, rezeptartreq])
       .then(([res1, res2 ]) => {
     
          if (!res1.ok) { // error coming back from server
            console.log("error");
            throw Error('Could not fetch the data for that resource!');
          } 
          return res.json(), res2.json();

...

Do I have to create an array?
How to access the single results of each request?

How to pass variable into Vue component using router?

I have a simple application with Vue.

Vue version: 3.x

Vue router: This one https://router.vuejs.org/

const routes = [
    {
        path:       '/',
        component:  welcomeComponent,
        name:       'welcome'
    }, {
        path:       '/item/edit/:itemId(\d+)?',
        component:  itemEditComponent,
        name:       'item_edit',
        props:      true
    }
    ];

const router = VueRouter.createRouter({
    history:    VueRouter.createWebHistory(),
    routes
    });

const main_vue_app = {
    ...
    data() {
        return {
            languages_list: [
                            { id : 1,
                              title: 'German'
                            },
                            { id : 2,
                              title: 'Italian'
                            },
                            ...
                            ]
            }
        },
    ...
    }

let root_vue_app = Vue.createApp(main_vue_app).use(router).mount('#vue_app');

HTML

...
<div id="#vue_app">
   ...
   <router-view />
   ...
</div>
...

I know how to pass parameters from URL path like props to RouterLink component (https://router.vuejs.org/guide/essentials/passing-props.html)

But how to pass reactive version of languages_list to component inside RouterLink i.e. itemEditComponent?

I know that from inside itemEditComponent I can use this.$root but this is bad solution, beside it I can’t add watcher to parent item… thou I can, but this is obvious bad code style.

Code example appriciated, may be information inside manual, but I read it twice and found nothing.

Unable to bypass rotate captcha using 2captcha API

I’m currently working on bypassing the rotate captcha on the 2captcha API’s demo page. The issue I’m encountering isn’t related to the integration aspect; I’ve already figured out how to integrate it with the 2captcha API. However, the challenge lies in correctly inserting the output, which in our case is ‘165 degrees,’ into the appropriate place using JavaScript.

Upon closer analysis, I’ve observed that each right-click on the captcha image rotates it by 15 degrees and updates the ‘style’ attribute of the ‘img’ HTML tag accordingly. Therefore, by clicking the right button 11 times, we reach the desired 165-degree rotation, which successfully solves the captcha.

While my script effectively adds the rotation, ensuring the image appears correctly rotated, encountering a failure when clicking the ‘check’ button. Below is the snippet of the HTML:

<div class="_3i4YsKXQ1sT9uqskDtNNuA"><img src="/dist/web/43.png" alt="rotatecaptcha example" width="118" height="118" style="transform: rotate(165deg);"></div>

I’ve tried a lot of searches and unable to find any blog or tutorial for this kind of captcha, there are some other related question on stack but those are for simple captcha, like this one.

Here is the reproducible code:

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from time import sleep
import requests

# Initialize Chrome webdriver
option = webdriver.ChromeOptions()
# option.add_argument("--headless")
option.add_argument("--start-maximized")
driver = webdriver.Chrome(ChromeDriverManager().install(), options=option)

# Load the webpage
driver.get('https://2captcha.com/demo/rotatecaptcha')



image_element = driver.find_element(By.XPATH, '//img[@alt="rotatecaptcha example"]')
new_style = f"transform: rotate(165deg);"
driver.execute_script(f"arguments[0].setAttribute('style', '{new_style}')", image_element)

sleep(3)

try:
    click_element = driver.find_element(By.XPATH, '//button[@type="submit"]').click(); sleep(15)
except:
    print('Not able to locate the click button')

how to use css variables inside javascript in rollup

I have a UI components repo setup with rollup where I want to use my css variables inside my javascript files. I have done this in another repo which was using webpack and it was quite easy:

import vars from '!css-variables-loader!./variables.css';

Is there any plugin like css-variables-loader for rollup that I can use?

code for randomly falling object from top [closed]

I supposed to make randomly falling squares but the squares are falling in the same repeated pattern after some seconds.I am developing a game so that there is man at the bottom who can move from left to right and viceversa.The game will end if the squares fall on the man.But here since the squares fall in same pattern.if the man stands on a particular point he won’t be hit by the squares and the game won’t end at any time.I want to modify this code to avoid this situation

Instead of setting their left position based on the container’s width, I created a random position within the viewport width and I expected the squares will fall randomly across the entire viewport but this also is not giving the results.

Get the title details of opened child window in parent window in Flutter Web using Javascript

I am opening the new tab from flutter by using

js.Method.call()

to call the js function and open the new tab.Below is the JS code

function openURLAndListen(url) {
  var openedWindow = window.open(url, '_self');

  // Check if we can access the new tab
  if (openedWindow && openedWindow.document) {
    // Function to periodically check the title
    var checkTitle = function() {
      console.log('New tab title: ' + openedWindow.document.title);
    };

    // Poll the new tab's title every 500 milliseconds
    var titlePollInterval = setInterval(checkTitle, 500);

    // Stop polling when the window is closed or navigated away
    openedWindow.addEventListener('beforeunload', function() {
      clearInterval(titlePollInterval);
    });
  } else {
    console.log('Cannot access new tab due to same-origin policy');
  }
} 

I am actually opening the payment gateway url and after payment done, the callBack url should called. In that the details of transaction Id and other parts is present in the title of the tab. So I want it to get the details from title.
In this code I just want it to display the result on the console.

I had tried lots of JS code to get the title details back but not succed. Let me know if this thing is possible or not.