Prerender vue application issue with prerender-spa-plugin

I am trying to get prerender-spa-plugin to work. At the initial setup I was getting some errors, which turned out to be due to prerender-spa-plugin being incompatible with webpack 5. I then found a forked version of the plugin which works with webpack 5 (@dreysolano/prerender-spa-plugin).

The problem now is when I run npm run build, the folders are correctly created for each route, but the html just returns instead of the HTML for the specific route. (I have script tag in the index.html also, and all the css etc for that is prerendered, its just the content under #app that isn’t)

This is my vue.config.js at the moment

const PrerenderSPAPlugin = require('./node_modules/@dreysolano/prerender-spa-plugin');
const {join} = require('path');
const Renderer = PrerenderSPAPlugin.PuppeteerRenderer

module.exports = {
runtimeCompiler: true,

publicPath: process.env.NODE_ENV === 'production'
    ? '/app/'
    : '/',

css: {
    loaderOptions: {
        sass: {
            additionalData: '@import "~@/styles/custom.scss";'
        }
    }
},
configureWebpack: {
    plugins :[
        new PrerenderSPAPlugin({
        staticDir: join(__dirname, 'dist'),
        routes: ['/'],
        postProcess(context) {
        context.html = context.html.replace('id="app"', 'id="app" data-server-rendered="true"');
        return context;
        },
        renderer: new Renderer({
        inject: 'head',
        renderAfterDocumentEvent: 'render-event'
        }),
        headless: true
        })
        ]
},
chainWebpack: config => {
    config.module
        .rule('vue')
        .use('vue-loader')
        .loader('vue-loader')
        .tap(options => {
            return {
                transformAssetUrls: {
                    video: ['src', 'poster'],
                    source: 'src',
                    img: 'src',
                    image: 'xlink:href',
                    'b-avatar': 'src',
                    'b-img': 'src',
                    'v-img': 'src',
                    'b-img-lazy': ['src', 'blank-src'],
                    'b-card': 'img-src',
                    'b-card-img': 'src',
                    'b-card-img-lazy': ['src', 'blank-src'],
                    'b-carousel-slide': 'img-src',
                    'b-embed': 'src'
                }
            }
        });
    const path = require('path')
    config.resolve.alias
      .set('AutoNumeric', path.resolve(__dirname,
        'node_modules/autonumeric/dist/autoNumeric.min'));
},

devServer: {
    proxy: {
        '^/api': {
            // target: `http://${process.env.BACKEND_HOST || 'localhost'}:5000/`,
            target: process.env.BACKEND_URL || 'http://localhost:5000/',
            ws: true,
            changeOrigin: true,
            pathRewrite: {
                '^/api': '/'
            }
        }
    }
},

pluginOptions: {
  i18n: {
    locale: 'en',
    fallbackLocale: 'en',
    localeDir: 'locales',
    enableInSFC: false
  }
}

}

I’ve tried renderAfterTime (not recommended) and no results.
When I add:

renderAfterDocumentEvent: 'render-event'

the npm run build just runs forever, which is probably because no event is ever dispatched for some reason, even though I have added this:

new Vue({
router,
store,
axios,
i18n,
render: function(h) {
 return h(App);
},
mounted() {
// You'll need this for renderAfterDocumentEvent.
setTimeout(() => {
  document.dispatchEvent(new Event('render-event'));
}, 5000);
},
 }).$mount("#app");

making countdown timer with date input

I am just beginning to learn html and tried to make an html page with a date input with a submit button and a clock that shows the remaining time when time is selected and submit button is clicked but code is simply not working and I don’t know where to fix it.

here is html:

<body class="body">
    <ul class="header">
        <p id="header_name">
            Countdown
        </p>
    </ul>
    <div class="menu">
        <form class="form">
            <div>
                <p class="date">choose a date</p>
            </div>
            <div>
                <input autocomplete="off" autofocus class="input__time" id="input__time" type="date">
            </div>
            <div>
                <button class="submit" type="submit">start countdown</button>
            </div>
        </form>
        <div class="until" id="myCountdown">
            <div class="until__component">
                <div class="until__numeric until__numeric--days">00</div>
                <div class="until__unit ">Days</div>
            </div>
            <div class="until__component">
                <div class="until__numeric until__numeric--hours">00</div>
                <div class="until__unit ">Hours</div>
            </div>
            <div class="until__component">
                <div class="until__numeric until__numeric--minutes">00</div>
                <div class="until__unit ">minutes</div>
            </div>
            <div class="until__component">
                <div class="until__numeric until__numeric--seconds">00</div>
                <div class="until__unit ">seconds</div>
            </div>
            <div class="until__event">Until DD MM YYYY</div>            
        </div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.1/dayjs.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.1/plugin/duration.min.js"></script>
    <script src="main.js"></script>
</body>

and js:

dayjs.extend(dayjs_plugin_duration);

function activateCountdown(date) {
    const targetDate = dayjs(date);

    document.getElementById("myCountdown").querySelector(".until__event").textContent = `Counting down until ${ targetDate.format("YYYY MM DD")}`;

    setInterval(() => {
        const now = dayjs();
        const duration = dayjs.duration(targetDate.diff(now)); 

        if (duration.asMilliseconds() <= 0) return;

        document.getElementById("myCountdown").querySelector(".until__numeric--seconds").textContent = duration.seconds().toString().padStart(2, "0");
        document.getElementById("myCountdown").querySelector(".until__numeric--minutes").textContent = duration.minutes().toString().padStart(2, "0");
        document.getElementById("myCountdown").querySelector(".until__numeric--hours").textContent = duration.hours().toString().padStart(2, "0");
        document.getElementById("myCountdown").querySelector(".until__numeric--days").textContent = duration.asDays().toFixed(0).toString().padStart(2, "0");
    }, 250);
}

document.querySelector("form").addEventListener('submit', activateCountdown(document.getElementById("input__time")))```


AutoPlay Sliders

so I’m trying to create an auto slider, and the issue that I’m having is the loop.

What I want is a loop between the right and left arrows, so it moves foward until the right arrow is disabled, and moves back until the left arrow is disabled, and so on.

The problem that I’m having is that when it goes all the way back until the left arrow is disabled, the setInterval keeps triggering the left arrow instead of the right arrow. I’ve tried to add a click eventListener but that didn’t go so well.

Here’s my JS code:

function Auto(){
  let $arrowRight = $('.arrow-right'); 
  let $arrowLeft = $('.arrow-left'); 
  let $disableArrowAttribute = $arrowRight.attr('disabled');
    
  $arrowRight.click(function(){
    $disableArrowAttribute = $arrowRight.attr('disabled');
  });

  setInterval(function (){  
  if ($disableArrowAttribute) {
      $arrowLeft.click();
    } 

  else {
      $arrowRight.click();
    }
  }, 100)
  }

How to disable past days and weekends in Jquery

Does anybody know why this Script not working? I am trying to disable weekends and previous dates? I have tried searching all over the web but I am struggling.

<input type="date" id="date" class="form-control">


<script type="text/javascript">
     $(function() {
     $( "#date" ).datepicker({
     beforeShowDay: $.datepicker.noWeekends,
     minDate : 'now'
  });
 });
</script>

DatePicker

Steamroller javascript code how to happen

pleases describe me recursion function how to happen flatten array in the final result. Mainly please describe in the if section

function steamrollArray(arr) {
  let answer = [].concat(...arr);
  console.log(answer)
  if(answer.some(Array.isArray)){
    return steamrollArray(answer);
  }
  return answer
}

let result = steamrollArray([1, [2], [3, [[4]]]]);
// console.log(result)

How to create OneToMany references between documents already inserted in MongoDB

It is the first time I am using MongoDB and I don’t know how to create references (relationships in SQL) between documents which are already inserted in my database.

I have two collections: the first one is called Films, and its documents have information about films (title, a unique URL, description…). Here is an example of a document:

{
  "_id": {
    "$oid": "6272aa886441c51b18de7b23"
  },
  "type": "Film",
  "title": "Les 2 papas et la maman",
  "genres": "Comedia",
  "description": "Jérôme and Delphine want a child but Jerome is sterile. They then ask the best friend of Jerome, Salim, to be the donor for artificial insemination of the mother...",
  "platform": "Netflix"
  "film_url": "exampleurl.com"
}

Also, there is another collection called “Actors”. Every document in the “Actors” collection has specific information about a certain Actor, the film in which he/she participates (title and a unique URL) and the character that he/she represents. A document of this collection could be the next one:

{
  "_id": {
    "$oid": "6272ac5b6441c51b18de9ee4"
  },
  "name": "Sophie Rundle",
  "film_title": "Peaky Blinders",
  "film_url": "exampleurl.com",
  "character": "Ada Shelby",
  "num_episodes": "36"
}

I want to create a OneToMany reference between the Collection Films and the collection Actors (a film has many actors, and one actor represents a character in a film), creating an array inside each Film document, which contains the ids of those actors who participate in a certain film. To do that, I have the unique field “film_url” in both collections and I have two CSV files with the data, so I could read and iterate over them to create the references, but it isn’t a good idea in terms of efficiency, since each file has more than 10,000 lines.

Is there a simpler and more efficient way to create these references in MongoDB?

Component changes not being shown in local host

I am currently learning Angular with a class from Ultimate Courses, currently I am following the on screen instructions, but for some reason I’m not seeing anything but a white screen in the local host. I’m suppose to be seeing “Hello!” after unzipping the downloadable zip folder from github, but nothing appears. The folder did not come with a app.component.html either. I have installed the correct dependencies and the package json already.

app.component.ts file

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  styleUrls: ['app.component.scss'],
  template: `
    <div class="app">
      Hello!
    </div>
  `
})
export class AppComponent {

}

app.module.ts file

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { AppComponent } from './app.component';

@NgModule({
  imports: [
    BrowserModule,
    CommonModule
  ],
  bootstrap: [
    AppComponent
  ],
  declarations: [
    AppComponent
  ]
})
export class AppModule {}

index.html

<!doctype html>
<html>
<head>
  <base href="/">
  <title>Ultimate Angular</title>
  <link rel="stylesheet" href="/css/app.css">
</head>
<body>
  <app-root></app-root>

  <script src="/vendor/vendor.js"></script>
  <script src="/build/app.js"></script>
</body>
</html>

The Javascript Profile Lookup challenge

Hi i’ve been stucked here for a while, and i checked on other solutions which matched mine perfectly. But i can’t seem to find the error in my code as it keeps saying..

// running tests
lookUpProfile("Kristian", "lastName") should return the string Vos
lookUpProfile("Sherlock", "likes") should return ["Intriguing Cases", "Violin"]
lookUpProfile("Harry", "likes") should return an array
// tests completed

This is the challenge…

        const contacts = [
      {
        firstName: "Akira",
        lastName: "Laine",
        number: "0543236543",
        likes: ["Pizza", "Coding", "Brownie Points"],
      },
      {
        firstName: "Harry",
        lastName: "Potter",
        number: "0994372684",
        likes: ["Hogwarts", "Magic", "Hagrid"],
      },
      {
        firstName: "Sherlock",
        lastName: "Holmes",
        number: "0487345643",
        likes: ["Intriguing Cases", "Violin"],
      },
      {
        firstName: "Kristian",
        lastName: "Vos",
        number: "unknown",
        likes: ["JavaScript", "Gaming", "Foxes"],
      },
    ];

My code…


function lookUpProfile(name,prop){

  for (let i = 0; i < contacts.length; i++){
    if (contacts[i].firstName === name && contacts[i].hasOwnProperty(prop)){
      return contacts[i][prop];
    } else if (contacts[i].firstName === name && !contacts[i].hasOwnProperty(prop)){
      return "No such property";
    }
    return "No such contact";

  }
  // Only change code above this line
}

lookUpProfile("Akira", "likes");

The test parameters

lookUpProfile("Kristian", "lastName") should return the string Vos

lookUpProfile("Sherlock", "likes") should return ["Intriguing Cases", "Violin"]

lookUpProfile("Harry", "likes") should return an array

lookUpProfile("Bob", "number") should return the string No such contact

lookUpProfile("Bob", "potato") should return the string No such contact

lookUpProfile("Akira", "address") should return the string No such property

Please i’d be so glad if anyone can help open my eyes.

NodeJS re-run a command in a row

My question is like, i have a command in 5th line and i am trying to rerun it in 16th line. How can i do this? The detail of rerun command is in the code.

Javascript;

import * as readline from 'node:readline/promises';
import { stdin as input, stdout as output } from 'node:process';
import * as fs from 'node:fs';
import moment from 'moment';
import * as process from 'node:process';

moment.locale("tr")
const saat = moment().format("DD MMMM dddd YYYY, HH:mm:ss");
const NotSaat = "["+saat+"]: "
const girdi = readline.createInterface({ input, output });

var GirisSorusu = await girdi.question("")

if(GirisSorusu.toLowerCase() == "hey therria" ||  "hey therria." || "hey therria!") {
 const heyterya = await girdi.question("Terya: Buyrun efendim?n")
  if(heyterya.toLowerCase() == "not al" ||  "not al." || "not al!") {
   const nots = await girdi.question("Therria: Ne almamı istersiniz?n")
   const NotRewrite = NotSaat + nots + "n";
    fs.open("notlar/notlar.txt", "a", (err, fd)=>{
    if(err){
        console.log("Dosyaya erimeye çalışırken bir hata oluştu: " + err);
    }else{
        fs.write(fd, NotRewrite, async(err, bytes)=>{
            if(err){
                console.log("Dosyaya yazmaya çalışırken bir hata oluştu: ");
            }else{
                const notaldim = await girdi.question("Therria: Notunuzu aldım, başka bir isteğiniz var mı?n") 
                 if(notaldim.toLowerCase == "yok" || "yok." || "yok!") {
                    await process.exit()
                 } else if (notaldim.toLowerCase == "evet" || "evet." || "evet!"); {
                    // Here is mine rerun command line, i want to rerun "heyterya" command
               } 
            }
        })        
    }
})
 }
}

How to use aggregation in the above code?

How to convert this code using aggregation, I tried using for loop but it's taking so much time (4.56 seconds) to get the data from the database so it's too time-consuming so now I'm trying using the aggregation function in the MongoDB.Is there any other way to resolve this issue? Do I need to use if condition or project method in aggregation?
 let filter = {
        _id: {
          $in: _.map(videoIds, id => mongoose.Types.ObjectId(id)) || []
        }
      }
    if (!req.isLocationWhitelisted) {
      if (req._countryCode) {
        filter['languages.country'] = {
          $in: req._countryCode
        }
        cataloguePopulateFilter.match['languages.country'] = {
          $in: req._countryCode
        }
      } else {
        filter['languages.country.141'] = { $exists: true }
        cataloguePopulateFilter.match['languages.country.141'] = { $exists: true }
      }
    }
   let videoList = await Video.find(filter).populate(cataloguePopulateFilter);

How to convert this code using aggregation, I tried using for loop but it’s taking so much time (4.56 seconds) to get the data from the database so it’s too time-consuming so now I’m trying using the aggregation function in the MongoDB.Is there any other way to resolve this issue? Do I need to use if condition or project method in aggregation?

Append a link when text overflowing parent

I’m using Ajax to get comments. Comment text is treated as max-height:90px by default. When importing comments, I want to attach a link if the text length is longer than the parent element.
The code below doesn’t work well.
It works imperfectly.
All comments have a link or only the first one.
Is there any right way?
enter image description here

$( document ).on('click' , '.view_comments' , function(){
        let id = $(this).attr("id");
        let content = $("#comment-post-"+id).val();
         let last_cmt = $("ul#canvas-comments-"+id+" li:last").val();
    $.ajax({
         type:"GET",
         url: "http://192.168.10.21/v1/server1/comment/view_comment.php",
         data:{ enclosure: content, cmt: last_cmt },
         success:function(html){
             const result = JSON.parse(html);
             if( result.length > 0 ){
                 let comment = '';
                 for( const item of result ){
                     const comment_list = comment_object( item );
                     comment += comment_list.get_html();                 
                 }           
                 $("ul#canvas-comments-"+id).append(comment);
                  /************************************************
                  * @ if comment overflown div.wts-comment-text   *
                  ************************************************/
                  const hasElement = $('*').is($(".wts-comment-text"));
                  if( hasElement === true ){
                      const parent = document.querySelector('.wts-comment-text');
                      if( isOverflown( parent ) ){
                          const sub_id = $(parent).attr("data-value");
                          $("#comment-option"+sub_id).html("<a href='#' data-value='"+sub_id+"' class='view-comment-details'><span>More...<span></a>");
                       }
                  }
                 $(this).html('More Comments');
             }else if( result.length === 0 ){
                 console.log("zero");
                 $(this).html('Comments 0');
             } 
         },
         error: function( xhr ){                
            console.log(xhr.status+' '+xhr.statusText);
         }
    });
    return false;       
});       

function isOverflown(e){
return e.scrollHeight > e.clientHeight;
}

var comment_object = function(data){
const id = data['comment_id'];
const user_id = data['user_id'];
const username = data['username'];
const date = data['date'];
const comment = data['comment'];

return {
    get_html: function(){
    return "<li value='"+id+"' class='wts-comment'><div class='wts-comment-left'><span class='wts-comment-author'>"+username+"</span><span class='wts-comment-date'>"+date+"</span></div><div class='wts-comment-text-wrapper'><input type='hidden' name='comment_id' value='"+id+"' /><div class='wts-comment-wrapper'><div class='wts-comment-rating-container'><div class='wts-rating-inner-wrapper'><div class='wts-comment-rating'><div class='wts-comment-rating-value'></div></div></div><div id='commentTextBox"+id+"' class='wts-comment-text'><p>"+comment+"</p></div><div class='wts-comment-action-icons'><div id='comment-option"+id+"' class='wts-comment-action-renderer'><a href='#' data-value='"+id+"' data-action='n-ack' class='cwt-link-cr view-comment-details'><span class='n-ack'>펼쳐보기<span></a></div></div></div></li>";
    }
};
};

Simple onclick event not triggering on Android devices

I have some simple HTML displaying a calendar as below. Once rendered the calendar has either 5 or 6 rows relative to the number of days in the month and which day of the week the 1st of the month is. Each day cell is clickable to execute some javascript. This all works fine on all desktop browsers and on iOS. However, with all versions of Android tested the bottom row of cells do not trigger the onclick event when clicked. Any ideas?

<div id="cal">
<div id="cal-caption">
    <span id="cal-last"><img src="/assets/images/arrow-left.png"></span>
    <span id="cal-month">May 2021</span>
    <span id="cal-next"><img src="/assets/images/arrow-right.png"></span>
</div>
<div id="cal-header">
<div class="cal-head">MON</div>
<div class="cal-head">TUE</div>
<div class="cal-head">WED</div>
<div class="cal-head">THU</div>
<div class="cal-head">FRI</div>
<div class="cal-head">SAT</div>
<div class="cal-head">SUN</div>
</div>
<div id="cal-body">
<div class="cal-row">
<div id="cl00" onclick="cal.click('cl00')"></div>
<div id="cl01" onclick="cal.click('cl01')"></div>
<div id="cl02" onclick="cal.click('cl02')"></div>
<div id="cl03" onclick="cal.click('cl03')"></div>
<div id="cl04" onclick="cal.click('cl04')"></div>
<div id="cl05" onclick="cal.click('cl05')"></div>
<div id="cl06" onclick="cal.click('cl06')"></div>
</div>
<div class="cal-row">
<div id="cl10" onclick="cal.click('cl10')"></div>
<div id="cl11" onclick="cal.click('cl11')"></div>
<div id="cl12" onclick="cal.click('cl12')"></div>
<div id="cl13" onclick="cal.click('cl13')"></div>
<div id="cl14" onclick="cal.click('cl14')"></div>
<div id="cl15" onclick="cal.click('cl15')"></div>
<div id="cl16" onclick="cal.click('cl16')"></div>
</div>
<div class="cal-row">
<div id="cl20" onclick="cal.click('cl20')"></div>
<div id="cl21" onclick="cal.click('cl21')"></div>
<div id="cl22" onclick="cal.click('cl22')"></div>
<div id="cl23" onclick="cal.click('cl23')"></div>
<div id="cl24" onclick="cal.click('cl24')"></div>
<div id="cl25" onclick="cal.click('cl25')"></div>
<div id="cl26" onclick="cal.click('cl26')"></div>
</div>
<div class="cal-row">
<div id="cl30" onclick="cal.click('cl30')"></div>
<div id="cl31" onclick="cal.click('cl31')"></div>
<div id="cl32" onclick="cal.click('cl32')"></div>
<div id="cl33" onclick="cal.click('cl33')"></div>
<div id="cl34" onclick="cal.click('cl34')"></div>
<div id="cl35" onclick="cal.click('cl35')"></div>
<div id="cl36" onclick="cal.click('cl36')"></div>
</div>
<div class="cal-row">
<div id="cl40" onclick="cal.click('cl40')"></div>
<div id="cl41" onclick="cal.click('cl41')"></div>
<div id="cl42" onclick="cal.click('cl42')"></div>
<div id="cl43" onclick="cal.click('cl43')"></div>
<div id="cl44" onclick="cal.click('cl44')"></div>
<div id="cl45" onclick="cal.click('cl45')"></div>
<div id="cl46" onclick="cal.click('cl46')"></div>
</div>
<div id="cal-extra" class="cal-row">
<div id="cl50" onclick="cal.click('cl50')"></div>
<div id="cl51" onclick="cal.click('cl51')"></div>
<div id="cl52" onclick="cal.click('cl52')"></div>
<div id="cl53" onclick="cal.click('cl53')"></div>
<div id="cl54" onclick="cal.click('cl54')"></div>
<div id="cl55" onclick="cal.click('cl55')"></div>
<div id="cl56" onclick="cal.click('cl56')"></div>
</div>
</div>
<div id="cal-footer">
<div class="cal-foot"></div>
<div class="cal-foot"></div>
<div class="cal-foot"></div>
<div class="cal-foot"></div>
<div class="cal-foot"></div>
<div class="cal-foot"></div>
<div class="cal-foot"></div>
</div>

How can I Neatly format a recursed console-logged Json Object in JavaScript?

I recursively listed a nested json object. When i console log, I get my data in a way that makes it difficult to know where a set of object begins or ends.

How can I format the response?

      fullName: 'Ram Kumar',
      age: 31,
      gender: male
      }
   },
      fullName: 'Ranbir Singh',
         age: 22,
         gender: male
      }
   },

function printAllVals(obj) {
  for (let prop in obj) {
    if (typeof obj[prop] === "object") {
      printAllVals(obj[prop])
    } else {   
      console.log(prop + ':' + obj[prop]);
    }
  }
}

I am getting:


fullName:Ram Kumar
age: 31
gender: male
fullName:Ranbir Singh
age: 22
gender: male

What I want is something like this. Anything to format or separate the objects for clarity or easy understanding :

fullName:Ram Kumar
age: 31
gender: male 
---
fullName:Ranbir Singh
age: 22
gender: male