Unable to pass argument from outer scope in Node.js file system function?

I’ve noticed that arguments are not being recognized in Node.js filesystem when wrapped with (). Can anyone explain why this is happening please? My expectation was the even when wrapped in (), it will work just like forEach() function?

const fs = require('fs');
const path = require('path');
const root = path.resolve(__dirname);

fs.readdir(root, (error, filenames) => {
   filenames.forEach( filename => {
      const filePath = path.join(root, filename);
      fs.unlink( (filePath, err) => {
         // Throws error saying 'filePath' is not defined..?
      });
   });
});

Uncaught SyntaxError: Unexpected token ‘:’

I am having error when adding this code in my webpack.config.js Uncaught SyntaxError: Unexpected token ‘:’

const webpack = require('webpack');
const dotenv = require('dotenv');

dotenv.config();

module.exports = {
  //...
  plugins: [
    // ...
    new webpack.DefinePlugin({
       'process.env': JSON.stringify(process.env)
    })
    // ...
  ]
  //...
}

app.js

'use strict';
const dotenv = require('dotenv');
const config = dotenv.config();
const {API_KEYS} =config.parsed;

....

console.log("keys ",API_KEYS)

....

How to remove extra space in template literals?

When I create template literals, I would use the trim() to remove extra space. But I noticed when I do this inside a JS function, it still creates extra tabs or white space.

  function BottlesOfBeer()  {
    
        for (i = 99; i>=1; i--) {
    
            if (i === 1) {        
                var oneBottle = "1 bottle of beer on the wall, 1 bottle of beer.n" +
                                "Take one down and pass it around, no more bottles of beer on the wall.n" +
                                "No more bottles of beer on the wall, no more bottles of beer.n" +
                                "Go to the store and buy some more, 99 bottles of beer on the wall.";        
                
                console.log(oneBottle);
            } else {
                            
                var lineOne = `
                ${i} bottles of beer on the wall, ${i} bottles of beer.
                Take one down pass it around, ${i - 1} bottles of beer on the wall.
                `.trim();
    
                console.log(lineOne);        
            }
        }
    }
    
    BottlesOfBeer();
99 bottles of beer on the wall, 99 bottles of beer.
            Take one down pass it around, 98 bottles of beer on the wall.
98 bottles of beer on the wall, 98 bottles of beer.

You can see how the first line appears normally, but the second one has all the necessary tabs.

How can add my burger.price to my Item.price to create the Total?

I am looking to have my burger.price (if there is a custom burger in the cart) to be added to the total with the item.price. Any help would be great! I am new to using vue and vuex.

<template>
<div>
  <b-button v-b-modal.modal-1>Cart({{numInCart}})</b-button>
  <b-modal id="modal-1" size="xl" title="Shopping Cart" ok-title="Checkout" cancel-title="Continue Shopping">
    <table class="table">
      <tbody>
      <!-- replace in cart with custom burger -->
      <tr v-for="(item, index) in cart" :key="item.id">
        <td>{{ item.name }}</td>
        <td></td>
        <td></td>
        <td></td>
        <td></td>
        <td>{{ item.price | dollars }}</td>
        <td>
          <button class="btn btn-sm btn-danger" @click="removeFromCart(index)">&times;</button>
        </td>
      </tr>
        <tr>
        <th>Name</th>
        <th>Bun Type</th>
        <th>Cooked Style</th>
        <th>Cheese Type</th>
        <th>Toppings</th>
      </tr>
      <tr v-for="(burger) in customBurger" :key="burger">
        <td>{{burger.name = "Custom Burger"}}</td>
        <td>{{burger.bun}}</td>
        <td>{{burger.cookedStyle}}</td>
        <td>{{burger.cheese}}</td>
        <td>{{burger.toppings}}</td>
        <td>{{burger.price | dollars }}</td>
        <td>
          <button class="btn btn-sm btn-danger" @click="removeCustomBurger(customBurger)">&times;</button>
        </td>
      </tr>
      <tr>
        <th></th>
        <th>{{ total | dollars }}</th>
        <th></th>
      </tr>
      </tbody>
    </table>
  </b-modal>
</div>
</template>

<script>
import { dollars } from '../models/filters'

export default {
  name: 'ShoppingCart',
  computed: {
    customBurger() {
      return this.$store.getters.customBurger;
    },
    inCart() { return this.$store.getters.inCart; },
    numInCart() { return this.inCart.length; },
    cart() {
      return this.$store.getters.inCart.map((cartItem) => {
        return this.$store.getters.forSale.find((forSaleItem) => {
          return cartItem === forSaleItem.invId;
        });
      });
    },
    total() {
      return this.cart.reduce((acc, cur) => acc + cur.price, 0);
    },
  },
  filters: {
    dollars,
  },
  methods: {
    removeFromCart(index) { this.$store.dispatch('removeFromCart', index); },
    removeCustomBurger(){this.$store.dispatch('removeCustomBurger');},
  },
};
</script>

I’ve been meaning to learn C# and wanted sto write something like this Javascript code. How would i go about doing it

An example of what I’m trying to do:
Adding the first and last numbers until only two digits remain:

num = 1234567:

1+7 = 8

2+6 = 8

3+5 = 8

4 remains

So the first result is: 8884. Now everything is added again:

8+8 = 16

8+4 = 12

The result is 1612. Again everything is summed up:

1+2 = 3

6+1 = 7

The result is 37 – which is also the final result.

The Javascript code:

function sum(num) {
    var numString = num.toString();
    var newString = "";
    while (numString.length > 1) {
        newString += (parseInt(numString[0]) + parseInt(numString[numString.length - 1])).toString();
        numString = numString.substring(1, numString.length - 1);
    }
    newString += numString;

    if (newString.length > 2) {
        console.log(newString)
        return sum(newString);
    }  else {
         return newString;
      }
}

How to correctly apply global scripts with Nextjs

I’m trying to apply a global fade-in animation to all components in my application. I’ve added the classname fadeIn to all the elements and set the opacity to 0 by default. I then use js to change that to 1 when the element comes into view.

Below is how I am applying this so far. It does work but there is a major issue and I’m sure it’s not the best method and firstly would love to know any better methods.

The major issue is that it only works on the first render. But if I navigate to another page and then come back, all elements are hidden with the opacity 0 and the script does not execute.

Appreciate any advice on how to either solve the current issue, or a better way to execute it.

_app.js

function MyApp({ Component, pageProps }) {

  return <Provider store={store}>
    <Layout>
      <PersistGate persistor={persistor}>
        <Component {...pageProps} />
      </PersistGate>
      <FadeIn />
    </Layout>
  </Provider>
}

export default MyApp

FadeIn component

import React, { useEffect, useState } from 'react'
import Script from 'next/script'
import ReactDOM from 'react-dom';

export default function FadeIn() {

  const myScript = (
    <Script src='/utils/scripts/appearOnScroll.js' strategy="afterInteractive" />
  )

  return ReactDOM.createPortal(myScript, document.getElementById('doc-root'));

}

appearOnScroll.js

(function () {
  const faders = document.querySelectorAll('.fade-in');
  const faderOptions = {
    threshold: 1
  };
  const appearOnScroll = new IntersectionObserver(function (
    entries,
    appearOnScroll
  ) {
    entries.forEach(entry => {
      if (!entry.isIntersecting) {
        return;
      } else {
        entry.target.classList.add('appear');
        appearOnScroll.unobserve(entry.target);
      }
    })
  }, faderOptions);

  faders.forEach(fader => {
    appearOnScroll.observer(fader);
  });
})();

how to show a Blog detail link in Angular

I want to show the Detail of a Blog in a different link in Angular. I already have a Blog file (blog.component.ts) and an Angular service where I can get all the blogs data from an API backend made with Strapi. There is one button in every single blog, which allows you to view the detail or complete Blog in a different link calling the unique ID, that is named ‘pagina.component.ts’.
For that purpose, I think I must call the ID of every single Blog.

Here is my blog.component.html, where I already have the list of my blogs:

<section class="articles">

  <article class="blue-article" *ngFor="let data of datas; index as i">
    <div class="articles-header">
      <time>{{ data.fecha }}</time>
      <span class="articles-header-tag-blue">{{ data.relevante }}</span>
      <span class="articles-header-category">
        <a href="#" class="blue" title="">{{ data.category.name }}</a>
      </span>
    </div>
    <div class="articles-content">
      <h1><a title="">{{ data.title }}</a></h1>
      <!--<img *ngIf="!data.image" class="foto" [src]="data.image.name" alt="foto">-->
      <div *ngIf="data.image">
        <img
          src="http://localhost:1337{{ data.image.url }}"
          alt="foto"
          width="100%"
        />
      </div>
      <p>
        {{ data.content }}
      </p>
      <h3>{{ data.description }}</h3>
    </div>
    <div class="articles-footer">
      <ul class="articles-footer-info">
        <li><a href="#" class="light-link" title=""><i class="pe-7s-comment"></i> 7 Respuestas</a>
        </li>
        <li><a href="#" class="light-link" title=""><i class="pe-7s-like"></i> 1221</a></li>
      </ul>

      <a [routerLink]="['./pagina',i]" class="btn">Leer más</a>

    </div>
  </article>
</section>

Here is my blog.component.ts file


import { Component, OnInit } from '@angular/core';
import { Meta, Title } from '@angular/platform-browser';
import { StrapiService } from '../../../services/strapi.service';

import { Router } from '@angular/router';

@Component({
  selector: 'app-blog',
  templateUrl: './blog.component.html',
  styleUrls: ['./blog.component.scss']
})
export class BlogComponent implements OnInit {

  datas:any=[];
  errores:string="";

  constructor(
    public strapiserv:StrapiService,
    private router: Router
  ) { }

  ngOnInit(): void {

    this.title.setTitle('Blog');

    this.strapiserv.getData().subscribe(res=>{

        this.datas= res as string[];

    }, error =>{
      console.log(error);
        if(error.status == 0){
            this.errores="Código del error: "+error.status+" n Ha ocurrido un error del lado del cliente o un error de red.";
        }else{
            this.errores="Código del error: "+error.status+"nn"+error.statusText;
        }
    })

  }


}

Here is my Angular service named ‘strapi.service.ts’


import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';
@Injectable({
  providedIn: 'root'
})
export class StrapiService {

  REST_API: string ='http://localhost:1337/articles';
  //https://strapi-dot-gmal-api-313723.uc.r.appspot.com/
  httpHeaders = new HttpHeaders().set('Content-Type', 'application/json');
  constructor(private httpClient: HttpClient) { }


  getData():Observable<any>{
    console.log();
    let API=this.REST_API;
    return this.httpClient.get(API,{headers:this.httpHeaders}) .pipe(
      map((data:any) => { 
      
        return data;
      }), catchError( error => {
        return throwError(error);
      })
    )
    
  }

  /*getItem( idx:number ){
    return this.data[idx];
  }*/
 
 
}

And Here is my pagina.component.ts file where I want to show the complete detailed Blog


import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Router } from '@angular/router';

import { StrapiService } from '../../../../services/strapi.service';

@Component({
  selector: 'app-pagina',
  templateUrl: './pagina.component.html',
  styleUrls: ['./pagina.component.scss']
})
export class PaginaComponent implements OnInit {

  data:any = {};


  constructor( private activatedRoute: ActivatedRoute,
           private router: Router,
           public strapiserv:StrapiService
    ){ 

    this.activatedRoute.params.subscribe( params => {
      this.data = this.strapiserv.getData( params['id'] );
    });

  }

  ngOnInit(): void {
  }

}
 

My routes are:

const routes: Routes = [
    { path: 'blog', component: BlogComponent },
    { path: 'pagina/:id', component: PaginaComponent },
];

Is there an another way to get date instead of getting it from user’s device

I want to make an application that will only open at a specific date. I use new date() to do that, but new date() get time from the user’s device and the the user can open it by changing the time on its own device.

Example:

  let setdate = new Date('2021-12-10')
   let currentdate = new Date()
   console.log(setdate)
   if(setdate.getDate() == currentdate.getDate()){
    document.getElementById("result").style.display = 'revert'
   }
<div id=result style="display:none">Open now!!!</div>

If I don’t do anything with the time of my device, it won’t do anything. But if I change the date on my device to the specific date, then the area could open.

Could anyone suggests me a better way that could prevent this situation or is there an another way to get date instead of getting it from user’s device

Thanks for any responds!!!

Colores :root dinamicos desde sass al cargar pagina

Necesito de su ayuda para resolver la siguiente inquietud
quisiera cambiar los colores del :root del css desde los datos cargados de mi servidor (DB).Tengo una sass con los estilos `
$color-primary: #56b4d8;

$theme-colors: (
primary: $color-primary,
secondary: #56b4d8,
success: #0ebd65,
info: #198ae3,
warning: #fed713,
danger: #e64b4b,
light: #f8f9fa,
dark: #1a1a1a);`

mi requerimiento es necesito cambiar estos colores desde el servidor al cargar la imagen, quizas exista alguna manera de pasarle datos a las varibales de sass $

الجمال واللياقة البدنية

الجمال واللياقة البدنية

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

يقدم موقعنا اسرار الجمال واللياقة البدنية والرشاقة والعناية بصحتك للبنات والرجال حصريا تمارين – كمال اجسام – العناية بالوجه – العناية بالجسم – العناية بالبشرة – العناية بالشعر

Javascript Object Structure Without Key

I am trying to generate an object structure like so:

{nums: {500: 0, 600: 0}}

I have a function that loops and returns numbers as shown in object: 500 & 600. However,

No matter what I try to create an object structure like the above, it does not work.

This is what I have an array of object as follows :

 const scores = [ {score: 500}, {variant_id: 600} ]

How can I loop through the scores array of object and get a structure like:
Number 0 in this example as a value that will be applicable to all scores.

 {nums: {500: 0, 600: 0}}

What I have done is:

  let filteredScores = [];
  for (let i = 0; i < scores.length; i++) {
            const element = scores[i];
            filteredScores.push(element);
  }

However, this does not lead to the desired results.

Any insights or input is much appreciated!

Adding Chart.JS time cartesian (time.unit: second ) xAxes only shows 1 second difference in C#

I have 3 sets of data that have a timestamp (x) and value (y). I have tried to use guides and documentation to try to use the options scale xAxes type: “time” unit seconds. The graph shows nothing but y values on the y axes, labels and a 1 second difference on the x axes.
My code.
Basically, when i add the option to set the unit to seconds my chart breaks. I have no idea why.
Any suggestions would be helpful.

   <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
   <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>

    <div class="chartBox">
        <canvas id="myChart"></canvas>
    </div>
    <script>
        const ctx = document.getElementById('myChart').getContext('2d');
        const myChart = new Chart(ctx, {
            type: 'line',
            data: {

                datasets: [{
                    label: 'Melt Gas',
                    data: [{x: '2021-12-6 T 4:42:51' , y:43.450000},
{x: '2021-12-6 T 4:47:51' , y:44.440000},
{x: '2021-12-6 T 4:52:51' , y:45.280000},
{x: '2021-12-6 T 4:57:51' , y:45.940000},
{x: '2021-12-6 T 5:2:51' , y:46.710000},
{x: '2021-12-6 T 5:7:51' , y:47.480000},
{x: '2021-12-6 T 5:12:51' , y:48.140000},
{x: '2021-12-6 T 5:17:51' , y:48.910000},
{x: '2021-12-6 T 5:22:51' , y:49.690000},
{x: '2021-12-6 T 5:27:51' , y:50.350000},
{x: '2021-12-6 T 5:32:51' , y:51.130000},
],
                    backgroundColor: [
                      'rgba(54, 162, 235, 0.2)'
                    ],
                    borderColor: [
                        'rgba(54, 162, 235, 1)'
                    ],
                    tension: .4
                }, {label: 'Spin Gas',
                    data: [{x:'2021-12-6T4:44:5' , y:7.470000},
{x:'2021-12-6T4:49:5' , y:7.680000},
{x:'2021-12-6T4:54:5' , y:7.820000},
{x:'2021-12-6T4:59:5' , y:7.960000},
{x:'2021-12-6T5:4:5' , y:8.100000},
{x:'2021-12-6T5:9:5' , y:8.240000},
{x:'2021-12-6T5:14:5' , y:8.360000},
{x:'2021-12-6T5:19:5' , y:8.490000},
{x:'2021-12-6T5:24:5' , y:8.630000},
],
                    backgroundColor: [
                        'rgba(255, 206, 86, 0.2)'
                    ],
                    borderColor: [
                        'rgba(255, 206, 86, 1)'
                    ],
                    tension: .4
                }, {label: 'T5 OVEN Gas',
                    data: [{x:'2021-12-6T4:44:11' , y:23.140000},
{x:'2021-12-6T4:49:11' , y:23.520000},
{x:'2021-12-6T4:54:11' , y:24.000000},
{x:'2021-12-6T4:59:11' , y:24.390000},
{x:'2021-12-6T5:4:11' , y:24.770000},
{x:'2021-12-6T5:9:11' , y:25.130000},
{x:'2021-12-6T5:14:11' , y:25.550000},
{x:'2021-12-6T5:19:11' , y:26.030000},
{x:'2021-12-6T5:24:11' , y:26.440000},
{x:'2021-12-6T5:29:11' , y:26.730000},
{x:'2021-12-6T5:34:11' , y:27.000000},
{x:'2021-12-6T5:39:11' , y:27.310000},
{x:'2021-12-6T5:44:11' , y:27.590000},
{x:'2021-12-6T5:49:11' , y:27.970000},
{x:'2021-12-6T5:54:11' , y:28.430000},
],
                    backgroundColor: [

                        'rgba(153, 102, 255, 0.2)'
                    ],
                    borderColor: [
                       'rgba(153, 102, 255, 1)'
                    ],
                    tension: .4
                }],
            },
            options: {
                scales: {
                    xAxes: @*[ added/removed*@{
                        type: "time",
                        time: {
                            unit: "second", //when i this section the graphs breaks.
                        },
                        parser: true,//also have removed this/added
                    }@*] added/removed*@,
                    y: {
                        beginAtZero: false
                    }
                }
            }
        });
    </script>

Convert this JavaScript to Jquery [closed]

Here is what I need to convert. Any help would be greatly appreciated! TIA!

document.getElementById("color1").addEventListener("click",
            function() {
                document.getElementById("JS1").style.backgroundColor = 
                    document.getElementById("color1").value;
            });

Here is what I’ve tried so far.

$('#color1').on('click',function(){
            $('#JS1').css('background-color',$('#color1').val());
                });
            

Cant enable button java script [closed]

I want to make an input bar and search button where the search button is only enabled if there is any character in the input bar. So the button is disabled but when I type in the input, it doesn’t get enabled as it should.

    <!DOCTYPE html>
        <html lang="en">
        <head>
           <meta charset="UTF-8">
           <meta http-equiv="X-UA-Compatible" content="IE=edge">
           <meta name="viewport" content="width=device-width, initial-scale=1.0">
           <title>Document</title>
           <script>
              document.addEventListener('DOMContentLoaded', function(){
                 // by default search button is disabbled
                 document.querySelector('#search-button').disabled=true;
                 
                 documnet.querySelector('#search-bar').onkeyup = () => {
                    document.querySelector('#search-button').disabled = false;
                 }
              })
           </script>
        </head>
        <body>
           <form>
              <input id='search-bar'>
              <button id='search-button'>submit</button>
           </form>
        
        </body>
        </html>