Authentication for NPM publish registry along with registry for dependencies

I am not a JS developer, but I have to create pipeline thats build and publish NodeJS package. We have JFROG repository for our npm packages. So first in our pipeline we create .npmrc file for authentication during dependency download.

registry=https://my-registry.com/artifactory/api/npm/dependencies
always-auth=true
//my-registry.com/artifactory/api/npm/dependencies/:_auth=**base64token**

then we are using

npm ci
npm run build

and at this point everything works fine. In packages.json we have also:

"publishConfig": {
  "registry": "https://my-registry.com/artifactory/api/npm/published-packages"
}

and now we want to publish our package to this registry from above. But when we do npm publish it shows us authentication error and tells us that we need to use npm adduser to be able to publish. The problem is that we are running this in pipeline so it can’t be interactive.

I tried to change .npmrc (via changing registry and _auth) before running npm publish but the error is still the same.

So there are two questions:

  1. Is there any possibility to log in to certain registry for publishing pourpose without prompt?
  2. Can we have somehow defined multiple authentication for different registries in one .npmrc?

I am facing issue in filtering JavaScript nested array of objects

I have a javasctpt array as mentioned below const mainCategories = [

{
id: 1,
name: “Men”,
categories: [
name:”Tshirt”,
image:”/img/shirt1.png”

]

},
{
id: 2,
name: “Women”,
categories: [
name:”Tshirt”,
image:”/img/shirt2.png”

]

},

{
id: 3,
name: “Men”,
categories: [
name:”Hat”,
image:”/img/hat1.png”

]

},

{
id: 4,
name: “women”,
categories: [
name:”Hat”,
image:”/img/hat1.png”

]

},

] I want to display categories array in jsx but only one image against same field. For example:- category name “Hat” should have only one image rest of one should be discarded. Eventually in resultant array I should have only objects i.e Tshirt and Hat and each of them should have only one image. Could anyone tell me how to achieve above objective.

I tried with JavaScript map method also filter method, but I could not be able to discard another image.

Cookie not show in browser

Cookie not show in browser : i try again and again but cookie send from backend but not store in browser, i also try another browser like chrome and microsoft bing
this is node js code and html, javascript

**backend code :

**

const express = require('express')
const cookieParser = require('cookie-parser')
const cors = require('cors')
const app = express();
app.listen(8080,()=>{
    console.log("express")
})
app.use(cookieParser())
app.use(cors())

app.get('/login',(req,res)=>{
    res.cookie('cookies','myid',{
        httpOnly:true
    }).json({msg:"cookies sended ! "})
})

**front end code :

**

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <button onclick="myfunction()">Fetch</button>

    <script>
        const myfunction = async ()=>{
        let res = await fetch('http://localhost:8080/login',{ method:"GET"})
        res = await res.json()
        console.log(res)
        }
    </script>
</body>
</html>

output in consol :

{ msg: 'cookies sended ! '}

i am expecting :
cookies store in browser

Can’ t implement Firebase authentification via thymeleaf template

I have version of similar Firebase authentification and it’s work just fine. but the second (below) doesn’t work at all.
Tamplete “login” uses spring security whith login page configured to (.loginPage(“/login”)) so i think it’s because of spring security. i’ve tryed to delete first part of html template but it has no effect.

    @GetMapping("/login")
    public String showLoginPage(Model model) {
        return "login"; // Возвращает имя представления login.html или login.jsp
    }

    @GetMapping("/get-token")
    @ResponseBody
    public String getToken1() {
        try {
        serviceAccount = new FileInputStream("./my-aws-6e0f8-firebase-adminsdk-q06q0-78540b7e56.json");
        } catch (Exception e) {     
        System.out.println("no key");
        }
        try {
        options = new FirebaseOptions.Builder()
                .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                .build();
        } catch (Exception e) {
        System.out.println("options error");    
        }
        FirebaseApp.initializeApp(options);
        try {
        customToken = FirebaseAuth.getInstance().createCustomTokenAsync(UID).get();
        } catch (Exception e) {
            System.out.println("get token error");
        }
        System.out.println(customToken);

        return customToken;
    }



<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Login</title>
    <div style="text-align: right;">
  <a href="/">На главную страницу</a>
</div>
  <script type="module" src="https://www.gstatic.com/firebasejs/10.3.0/firebase-app.js"></script>
  <script type="module" src="https://www.gstatic.com/firebasejs/10.3.0/firebase-analytics.js"></script>
  <script type="module" src="https://www.gstatic.com/firebasejs/10.3.0/firebase-auth.js"></script>
</head>
<body>
<h1>Login Page</h1>
    <p th:if="${param.resetSuccess}">Your password has been reset successfully!</p>
    <p th:if="${param.passwordReset}">Your password has been changed successfully!</p>
    <!-- Остальной код страницы логина -->
<div style="text-align: right;">
    <span th:if="${#httpServletRequest.userPrincipal != null}">
        Пользователь: <span th:text="${#httpServletRequest.userPrincipal.name}"></span>
        <form th:action="@{/logout}" method="post">
            <input type="submit" value="Выйти"/>
        </form>
    </span>
</div>
<form th:action="@{/login}" method="POST">
    <label for="username">Username:</label>
    <input type="text" id="username" name="username" required><br><br>

    <label for="password">Password:</label>
    <input type="password" id="password" name="password" required><br><br>

   <button type="submit">Login</button>
</form>

<br>

<a href="/register"><button>Register</button></a> <br> <br>
<a href="/forgot-password"><button>Забыли пароль?</button></a> <br> <br>
<!-- Сообщение об ошибке -->
<div th:if="${param.error}">
    <p style="color: red;">Пользователь не найден</p>
</div>


<script type="module">
      import { initializeApp } from 'https://www.gstatic.com/firebasejs/10.3.0/firebase-app.js';
      import { getAnalytics } from 'https://www.gstatic.com/firebasejs/10.3.0/firebase-analytics.js';
      import { getAuth, signInWithCustomToken} from 'https://www.gstatic.com/firebasejs/10.3.0/firebase-auth.js';

const firebaseConfig = {
  apiKey: "AIzaSyCC7XORgSSdu4gq4OGZQ4G0XKAgy7K5STM",
  authDomain: "my-aws-6e0f8.firebaseapp.com",
  projectId: "my-aws-6e0f8",
  storageBucket: "my-aws-6e0f8.appspot.com",
  messagingSenderId: "567282066781",
  appId: "1:567282066781:web:52a68db33898707420b4b4",
  measurementId: "G-8VML47T1BF"
};

  // Initialize Firebase
  const app = initializeApp(firebaseConfig);
  const analytics = getAnalytics(app);
    // Получение токена с помощью Fetch API
    fetch('/get-token')
      .then(response => response.text())
      .then(tokenFromServer => {
        document.getElementById('token').textContent = tokenFromServer;

        const auth = getAuth(app);
        signInWithCustomToken(auth, tokenFromServer)
          .then((userCredential) => {
            // Пользователь успешно вошел
            const user = userCredential.user;
            // ...
          })
          .catch((error) => {
            // Обработка ошибки при входе пользователя
            const errorCode = error.code;
            const errorMessage = error.message;
            // ...
          });
      })
      .catch(error => console.log(error));
  </script>
</body>
</html>

Specific media queries extract and store in a variable

I’m using gulp in an email generator. This generator is using Juice to manipulate a CSS file linked to the HTML file and will inline, clean, keep media queries in head, etc. to have a final HTML file without CSS file linked to it.

The issue I have is with dark mode. In email we are using the “normal” dark mode media query (@media (prefers-color-scheme: dark)) but also other declaration for specific mailing platform such as Outlook.

This specific declaration is in a <style> tag:

[data-ogsc] body { background-color: #2a2c2e !important; }
[data-ogsb] body { background-color: #2a2c2e !important; }

But, even though those are in my CSS file, Juice is stripping it.

Here is my task that does most of the job:

// tasks/juice.js
"use strict";


module.exports = function(gulp, $, fromRoot) {

    var juice = require('gulp-juice-concat');
    var removeUnused = require("gulp-email-remove-unused-css");

    gulp.task("juice", function(done) {
        gulp
            .src(fromRoot("dist") + "/*.html")
            .pipe(
                juice({
                    applyStyleTags: true,
                    applyLinkTags: true,
                    removeStyleTags: true,
                    preservePseudos: true,
                    preserveMediaQueries: true,
                    applyAttributesTableElements: true,
                    preserveImportant: true,
                    preserveFontFaces: true,
                    applyWidthAttributes: true
                })
            )
            .pipe(
                removeUnused({
                    whitelist: [
                        ".External*",
                        ".ReadMsgBody",
                        ".yshortcuts",
                        ".Mso*",
                        "#outlook",
                        "#preheader",
                        "#MessageViewBody",
                        "#body",
                        "u",
                        "[data-ogsc]",
                        "[data-ogsb]"
                    ],
                })
            )
    .pipe(gulp.dest(fromRoot("dist")));
    done();
    });

};

The idea I have in mind is to add a supplemental task to my npm run dist (after the juice that will extract the content of @media (prefers-color-scheme: dark), add relevant value and reinject that in the HTML file.

But I have not found any solution so far to do that.

My gulpfile.js look like this at the moment:

// gulpfile.js
'use strict';

const
    gulp = require('gulp'),
      fromRoot = require('../utils/from-root'),

      $ = require('gulp-load-plugins')({
        pattern: '*',
        config: '../../package.json',
        scope: ['dependencies', 'devDependencies', 'peerDependencies'],
        rename: {
          'lodash.assign': 'assign'
        }
      });


$.loadSubtasks('./tasks/**/*.js', $, fromRoot);

gulp.task('dist', gulp.series('clean:dist', 'sass:dist', 'src:dist', 'juice'));


I’m trying to use setTimeout in my tester file and connect it to my HTML file

<!-- app.component.html -->

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div *ngIf="title">
    <h1>This is a {{title}}</h1>
    <p>Lorem ipsum dolor sit, amet consectetur adipisicing elit. Corrupti eum quam consectetur
       corporis excepturi, velit delectus inventore tenetur sapiente dolor dignissimos numquam
       consequatur at? Excepturi voluptate accusantium, ut voluptatibus culpa recusandae ratione
       harum rerum!
    </p>
  </div>
</body>
</html>
// app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'cwh-todo-list';

  constructor(private ngZone: NgZone) {
    console.log("Constructor called");

    // Use NgZone to run code outside Angular's zone
    this.ngZone.runOutsideAngular(() => {
      setTimeout(() => {
        // This code will run outside Angular's zone
        console.log("Timeout callback called");
        this.ngZone.run(() => {
          // Inside this callback, Angular's change detection is enabled
          this.title = "Changed Title";
        });
      }, 2000);
    });
  }  
}

I expected the setTimeout to get executed but the web page shows ” This is a {{title}} ” instead of changing from ” This is a cwh-todo-list ” to ” This is a Changed Title “.`

How to check if a HTML document is empty via JavaScript without causing layout/reflow?

Need to check if an HTML div is empty and contains no text and no child elements as such inside it – a black page only.

e.g

function isPageEmpty(page) {
    const paragraphNodes = page.querySelectorAll(".paragraph");
    if ((paragraphNodes[0].children[0]).innerText !== "") {
      return false;
    }

    return true;
}

What would be the best way to do it, current code causing re calculation of styles?

Open for suggestion and new ideas.

what The best and shortest way to send email using the PHP language

I have a problem sending an email message from the server to a gmail email. I have tried all the methods (phpmailer, mail function),I also changed the settings of php.ini and sendmail.ini more than once… and despite that, errors appeared. I tried to find solutions, but to no avail. I have a project and I am supposed to send it at the specified time, but I have no help… Is there anyone of you who has solved what I mean to help me, because for 3 months I have been trying, but there is no solution for this, so I hope for your help… Thank you.

The language used in the system is php

Get the keys of a generic type object

I need to get the names of the keys of the object that comes as generic type T

I tried to do this through an

function getGnericTypeKeys<T>(): string[] {
  return Object.keys({} as T);
}

and

function getGnericTypeKeys<T>(): string[] {
  return Object.getOwnProperties({} as T);
}

and

function getGnericTypeKeys<T>(): string[] {
  return Reflect.ownKeys({} as T);
}

how to get window.{some_variable} from current active tab, in chrome extension

So,i am injecting a convert.js file into the current active tab.
inside the convert.js file, i have to fetch some window.{some_var}, which i have set when the page will load on the browser, i append those windows var, from server side rendering.

how to acces those window.{some_variable{ from my convert.js file.

structure

-popup.html
-popup.js
-convert.js
......
.....

based on a condition, the convert.js file injected into current tab.

I tried with sendMessage and listener, but giving me undefined.

but if the do window.{some_var} in browser console, its printing properly.

need help….

How do I show the current GMT (time) using Javascript on my website

I have a script that I use to display the data/time on a website. This works ok but just works off the users/browser time.

On something new I’m working on, I’d like it to display the time in a specific timezone (GMT) always – is that possible?

I don’t need the month in this version, so you can see that commented out.

As an aside, even on the original version. The time ‘jumps’ into view as it takes a while to load – is there away to fix this?

Might be worth noting this is a simple static website, so no database or much else to play with to get the time.

Cheers!

function showDateTime() {
    var currentDate = document.getElementById("date");
    var currentTime = document.getElementById("time");
    
    var date = new Date();
    var dayList = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
    /* var monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; */
    var dayName = dayList[date.getDay()];
    /* var monthName = monthNames[date.getMonth()]; */
    /* var today = `${dayName} ${date.getDate()} ${monthName}`; */
    var today = `${dayName}`;
    
    var hour = ('0' + date.getHours()).substr(-2);
    var min = ('0' + date.getMinutes()).substr(-2);
    var sec = ('0' + date.getSeconds()).substr(-2);
    
    
    var time = hour + ":" + min + ":" + sec;
    currentDate.innerText = `${today}`;
    currentTime.innerText = `${time}`;
}
setInterval(showDateTime, 1000);
<p><span id="date" class="os-menu__item"></span> <span id="time"></span> GMT</p>