How to call a function from another component using click event

I want to call a function of another component which has no relation on the click

servive File

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

@Injectable()
export class ShareDetailsService {
  clicked : boolean = false;
  constructor() { }

}

component 2

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

  constructor(shareDetailsService : ShareDetailsService) { }

  ngOnInit() {
    if(shareDetailsService.clicked){
      console.log("clicked");
    }
  }

Component 1

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

  constructor(shareDetailsService : ShareDetailsService) { }

  ngOnInit() {
    if(shareDetailsService.clicked){
      console.log("clicked");
    }
  }
  someFunction(){
  }
  

Component 1 Html

<div (click)="someFunction()"></div>

When I call the function using the click event it should call the function of the another component , I created a service file and where I am able to change the boolean variable.

I Want to call the function when there is a change in the boolean Variable rather than calling the function on ngOnit()

Why the variable value will be change even though doesn’t reassign or update

I write following function to return the width and height of a text:

function size_calculation(word,fontSize) {
  const div = document.body.appendChild(document.createElement('div'));
  div.textContent = word;
  div.style.cssText = `
  font-size:${fontSize}px;
  width:auto;
  position:absolute;
  visibility:hidden;
  `
  const computed_styles = window.getComputedStyle(div);
//return the expected height
console.log(computed_styles.getPropertyValue('height'))
 
  div.remove();
 
//return nothing 
console.log(computed_styles,computed_styles.getPropertyValue('height'))
 
  return ({
    height: computed_styles["height"],
    width:computed_styles["width"]
  })
}
console.log(size_calculation("hi",15))

I am quite confused why after I remove the div, all styles’ property in the computed_styles will become "" nothing, but before I remove the div, all styles’ property in the computed_styles has something different than "".

In my understanding, the value for variable will not be changed and is static unless we write any update or reassign statement once declared (AM I Wrong?)

Why the computed_styles will be automatically update?

Thank you!

P.S: not asking for solution (solution quite easy), but curious why.

Cross Site Scripting to make an Prompt box pop up

XSS is the second most prevalent issue in the OWASP Top 10, and is found in around two thirds of all applications. Automated tools can find some XSS problems automatically, particularly in mature technologies such as PHP, J2EE / JSP, and ASP.NET.

Want to make an Prompt box pop up with Your Name in it and bypass xss Filter

....
....
Dim search4 As String = Request.Form["search4"]
//Replace JavaScript events

search4 = search4.Replace("onafterprint|onbeforeprint|onbeforeunload|onerror|onhashchange|
onload|onmessage|onoffline|ononline|onpagehide|onpageshow|onpopstate|onresize|onstorage|
onunload|onblur|onchange|oncontextmenu|onfocus|oninput|oninvalid|onreset|onsearch|onselect|
onsubmit|onclick|ondblclick|onmousedown|onmousemove|onmouseout|
onmouseover|onmouseup|onmousewheel|onwheel| alert|confirm","")
//Repace New HTML Tags 
search4 = search4.Replace("<.*>","")
//replace '/' to '//'
search4 = search4.Replace("/","//")
//count number of occurrence of single and double quotes
Dim count1 As Integer = search4.count("'")
Dim count2 As Integer = search4.count('"')
if ( count1 > 1 || count2 > 1 )
{
   search4 = ""; 
}
....
....

Change background color of an element when hover on other element (slowly)

I need to change .main linear gradient top color when hovering over .child elements to the .child element color but slowly (like Spotify)

I created a Spotify clone (https://spotify.dinujaya.me/) but I can’t figure out how to change top color when hovering over other elements.

enter image description here

<!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>
    <style>
        :root{
            --red: #ff5656f8;
            --blue: #00ffea;
            --green: #6cff7f;
            --black: #353535;
            --pink: #ff2fff;
            --brown: #8b0000;
        }
        body{
            display: flex;
            justify-content: center;
            align-items: center;
            margin: 0;
            height: 100vh;
        }
        .main{
            display: flex;
            background-image: linear-gradient(to bottom, var(--blue), blue);
            padding: 50px;
            border-radius: 10px;
        }
        .child{
            width: 100px;
            height: 100px;
            margin: 20px;
            background-color: green;
        }
    </style>
</head>
<body>
    <div class="main">
        <div class="child" style="background-color: var(--red);"></div>
        <div class="child" style="background-color: var(--blue);"></div>
        <div class="child" style="background-color: var(--green);"></div>
        <div class="child" style="background-color: var(--black);"></div>
        <div class="child" style="background-color: var(--pink);"></div>
        <div class="child" style="background-color: var(--brown);"></div>
    </div>
</body>
</html>

How to implement a distributed countdown timer with Firebase

So basically I’m running an online game site whereby each “match” would be a certain duration, after said duration the “match” would change in name and details. How do I implement a live countdown which synchronizes with all users, which continues running on the server side even when a user closes the window?

Visual Studio how to stop indentation formatting on select javascript code?

I’m keen to know whether there is a way to stop Visual Studio Cntl + K + D hot function from resetting the indentation of my code for certain code sections?

Example is when I write html in javascript code, to make it more readable i like to apply my own indentations, as shown below:

let html =
    '<div class="d-flex flex-column" style="height: 100%">' +
        '<div class="d-flex">' +
            '<div class="icon-heading">' +
                '<i class="fa-solid fa-clipboard-list fa-1x"></i>' +
                '<h6 class="ms-2 mt-2">User Ack Notes</h6>' +
                '<!-- spinner = see layout.cshtml file -->' +
            '</div>' +
        '</div>' +
    '</div>;

But as soon as i hiy Cntrl + K + D then VS will automatically remove these indentations, as shown below:

enter image description here

This is very annoying and would be great if some kind of a js tag could be added to stop VS from applying the removal of indentations. I often use Cntrl + K + D to tidy up all other code blocks so I couldnt afford to simply remove the code tidy up feature.

some Facebook URLs not working in react player

const App = () => {
return (

<ReactPlayer
className=”react-player”
url=”https://www.facebook.com/cricketworldcup/videos/1426396294457890/”
width=”50%”
height=”50%”
playing
muted
loop
onEnded={() => console.log(“yes is ended”)}
/>

);
};

video play as well as but events not working

Refresh site after closing popup

I’m trying to make refresh script, at this point everything works perfect untill I close popup window then script stops. I tried to use multiple functions and i think this background.js is the closest

browser.runtime.onMessage.addListener(monitor);

function monitor() {
    if (localStorage.getItem("refresh")) {
        startref()
    }
    }

The content scripts looks like this:

function startref() {
   
        let intervalId = setInterval(function () {
                chrome.tabs.query({ active: true, currentWindow: true }, function (arrayOfTabs) {
                 var code = 'window.location.reload();';
                 chrome.tabs.executeScript(arrayOfTabs[0].id, { code: code });


            });
        
        }, 2000);
        localStorage.setItem('refresh', intervalId );
    }
window.onload = function () {
    if (localStorage.getItem("refresh")) {
        startref()  

});
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById("startbtn").addEventListener('click', startref);

And manifest includes "background": {"scripts": [ "background.js" ]}

Could you guys help me with it ?

Deploy to Vercel error (Error: Command “npm run build” exited with 127)

I’m using parcel-bundler for sass on my projects, I’ve always used npm start instead of npm run build and it has always worked for me. But this time, when I try to deploy my project on vercel, it failed and it says “Error: Command “npm run build” exited with 127″?

[19:25:23.101] Cloning github.com/sn-tin/odin-etch-a-sketch (Branch: main, Commit: e5ff000)
[19:25:23.584] Cloning completed: 482.734ms
[19:25:23.676] Installing build runtime...
[19:25:25.452] Build runtime installed: 1.775s
[19:25:26.373] No Build Cache available
[19:25:26.541] Installing dependencies...
[19:25:27.829] 
[19:25:27.830] added 17 packages in 1s
[19:25:27.830] 
[19:25:27.830] 2 packages are looking for funding
[19:25:27.830]   run `npm fund` for details
[19:25:28.030] Detected `package-lock.json` generated by npm 7...
[19:25:28.031] Running "npm run build"
[19:25:28.305] 
[19:25:28.306] > [email protected] build
[19:25:28.306] > parcel build src/index.html
[19:25:28.306] 
[19:25:28.322] Error: Command "npm run build" exited with 127

My package.json

{
 "name": "odin-eas",
 "version": "1.0.0",
 "description": "",
 "main": "index.js",
 "target": {
   "main": false
 },
 "scripts": {
   "start": "parcel src/index.html",
   "build": "parcel build src/index.html"
 },
 "keywords": [],
 "author": "",
 "license": "ISC",
 "devDependencies": {
   "@parcel/transformer-sass": "^2.5.0",
   "bundler": "^0.8.0",
   "parcel": "^2.5.0",
   "sass": "^1.51.0"
 }
}

getting Uncaught TypeError: Cannot read properties of null (reading ‘style’) error

I know this question has been asked before but I went through them and still couldn’t find out what is wrong. I want to show/hide a div using a javascript function and i used an external script with an onclick function. Please explain why this error is happening.

This is my html:

<div class="payment">
            <fieldset style="background-image:linear-gradient(rgba(0, 0, 0, 0.527),rgba(0, 0, 0, 0.5)),url(img/orangekat.jpg);">

                <h2>Payment</h2><br>
                <p>Choose Payment Method</p>

                <input type="button" name="paycod" class="cod" value="Cash on Delivery" onclick="callForm1()" >

                <div  id="when" style="display: none;">
                    <form method="post" action="" >
                        <label>What would be the most convinient time for you to recieve the package?</label>
                        <br>
                        <input type="radio" name="when" id="" value="Weekdays">
                        <label>Weekdays</label>
                        <input type="radio" name="when" id="" value="Weekends">
                        <label>Weekends</label>
                        <br>
                        <input type="checkbox" id="morn" name="morn" value="Morning">
                        <label > Morning</label><br>
                        <input type="checkbox" id="after" name="after" value="Afternoon">
                        <label > Afternoon</label><br>
                        <input type="checkbox" id="eve" name="eve" value="Evening">
                        <label > Evening</label><br>
                        <input type="submit" name="subcod" value="Submit">
                    </form>
                </div>

                <input type="button" name="paycard" class="card" value="Credit/Debit Card" onclick="callForm2()">

                <div id="paycard" style="display: none;">
                    <form method="post" action="">
                    <label>Name On Card*</label>
                    <input type="text" name="cardname" placeholder="Eg:- Kavishki Perera" required><br>
                    <label>Card Number*</label>
                    <input type="" name="cardnum" placeholder="1111-1111-1111-1111" required><br>
                    <label>Expire Month & Year*</label>
                    <input type="date" name="exp" id="" required><br>
                    <label>CVC*</label>
                    <input type="text" name="cvc" placeholder="123" required><br>
                    <input type="checkbox" id="savepay" name="savepay" value="Save My Details">
                    <label >Save My Payment Details</label><br>
                    <input type="submit" name="btnsub" value="Pay">
                    <input type="reset" name="btnres" value="Clear">
                </form>

                </div>
            </fieldset>
        </div>

this is the javascript:

var form1=document.getElementById('when');
var form2=document.getElementById('paycard');

console.log(form1);
console.log(form2);

var formVisibility1=form1.style.display;
var formVisibility2=form2.style.display;

function callForm1() {
  if (formVisibility1==='block') 
  {
    formVisibility1='none';
  }
  else 
  {
    formVisibility1='block';
  }
}

function callForm2() {
  if (formVisibility2==='block') 
  {
    formVisibility2='none';
  }
  else
  {
    formVisibility2='block';
  }
}

Function only on click of the exact class and data-id

I have two elements both with the same class .one. Click this button and show class .A.
One of those elements also has a data-id of two. Click this button and show class .B.

But, as the second “button” also has the class .one it’s showing both .A and .B.

How can I say perform this function/ show .B only if button has .one and .two?

https://jsfiddle.net/tdo6cz7p/

$('.one').on('click', function() {
  $('.A').show();
});
$("[data-id='two'].one").on('click', function() {
  $('.B').show();
});
.one {
  width: 50px;
  margin: 10px;
  padding: 10px 0;
  text-align: center;
  outline: 1px solid black
}

.A,
.B {
  display: none;
  background: yellow;
  width: 50px;
  margin: 10px;
  padding: 10px 0;
  text-align: center;
  outline: 1px solid black
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">one</div>
<div data-id="two" class="one">two one</div>


<div class="A">A</div>
<div class="B">B</div>

TypeScript: Index node_modules namespace types using template literal

I’m working with Prisma to make a generic repository object. Here’s my current interface (which the base repository implements) which works:

import { Log as LogSchema, Prisma, User as UserSchema } from "@prisma/client";
import type { CamelCase } from "type-fest";


type PrismaSchema = UserSchema | LogSchema; // I currently have to define all schemas schema.prisma here
type NonWriteable = "updatedAt" | "createdAt"; // I also have to explicitly define fields which should never be writeable
type WriteableSchemaWithId<Schema> = Omit<Schema, NonWriteable>;
type WriteableSchema<Schema> = Omit<WriteableSchemaWithId<Schema>, "id">;

interface IBaseRepository<
  Key extends CamelCase<Prisma.ModelName>,
  Schema extends PrismaSchema
> {
  create: (parameters: { [key in Key]: WriteableSchema<Schema> }) => Promise<{
    id: number;
  }>;

  // ... Other methods
}

However, in the type of argument to the create method are slightly incorrect. I’d really be like to using the Prisma-generated types instead of the type of the schema. For example, the Prisma client exports UserCreateArgs which defines what can be passed to prisma.user.create({ data: ... }).

Then I’d have to do this for all actions, for all schemas. Now, this isn’t a problem currently because there are only two models with no relations to each other. However, I’m expecting this implementation to become brittle (and cumbersome) with a more complex database schema.

Instead, I was looking for something like:

import { Prisma } from "@prisma/client";
import type { PascalCase } from "type-fest";

type NamespaceKey<
  Model extends Prisma.ModelName,
  Action extends Prisma.PrismaAction
> = `${Capitalize<Model>}${PascalCase<Action>}Args`;

type ActionArgs<
  Model extends Prisma.ModelName,
  Action extends Prisma.PrismaAction
> = typeof Prisma[NamespaceKey<Model, Action>];

Where NamespaceKey turns User into e.g., UserCreateArgs which should be imported from the Prisma namespace.

But I get an error saying NamespaceKey cannot be used to index typeof Prisma.

Is there a way to get what I’m looking for.

React Quiz App: How to show if a question is a correct/incorrect after a user selects an answer?

Hi I am new to React and I am trying to create a React quiz app. I wanted to add an extra feature to show the user if the answer they selected is correct/incorrect after they have clicked one of the answer options. I also then want to be able to display a ‘next question’ button after this so that the user can have time to see whether or not they answer correctly and only then move onto the next question when they are ready.

I am not sure how I would include this in the return section of my function. I would appreciate if anyone could show me where I could implement this and how in my code snippet below. Thank you!

Here is my code so far:

import React, { useState } from 'react';
import '../quiz.css';


const Quiz = () => {
    const questions = [
        {
            question: 'This is Question 1?',
            answer: [
                { text: 'Answer 1', isCorrect: tue },
                { text: 'Answer 2', isCorrect: false },
                { text: 'Answer 3', isCorrect: false },
                { text: 'Answer 4', isCorrect: false },
            ],
        },
        {
            question: 'This is Question 2?',
            answer: [
                { text: 'Option 1', isCorrect: false },
                { text: 'Option 2', isCorrect: false },
                { text: 'Option 3', isCorrect: false },
                { text: 'Option 4', isCorrect: true },
            ],
        },
        
    ];

    const [currentQuestion, setCurrentQuestion] = useState(0);

    const [showScore, setShowScore] = useState(false);

    const [score, setScore] = useState(0)

    const [answer, setAnswer] = useState(0)

    const userSelection = (isCorrect) => {
        if(isCorrect===true){
            setScore(score + 1);
        } 

        const nextQuestion = currentQuestion + 1;
        if(nextQuestion < questions.length){
            setCurrentQuestion(nextQuestion);
        } else{
            setShowScore(true) 
        }
    }


    return (
        <div className='quiz-app'>
            {showScore ? (
                <div className='score'>You scored <br></br> {score} / {questions.length}
        </div>
            ) : (
                <>
                    <div className='question'>
                        <div className='question-count'>
                            <span>Question {currentQuestion+1} </span>/{questions.length}
                        </div>
                        <div className='q-text'>{questions[currentQuestion].question}</div>
                    </div>
                    <div className='answer'>
                        {questions[currentQuestion].answer.map((answer) => 
                            <button className='option-button' onClick = {() => userSelection(answer.isCorrect)} 
                            className = {`answer-output ${questions[currentQuestion].answer.isCorrect ? true : false}`}
                            >{answer.text}
                            </button>)}
                            
                            <button>
                            Next Question
                            </button>
                             
                    </div>
                </>
            )}
        </div>
    );
}

export default Quiz;

My code prevents 2 integers from sorting themselves

I have a quite complex algorithm here, and probably I am close to the final solution. The goal of this algorithm is to sort elephantsOrder to be the same as proposedOrder. But every integer of elephantsOrderGiven has his own weight. it works like 1: 197, 2: 170, 3:124 4:180, 5:128 6:163 7:188 8:140. I spent days figuring out how to do it most efficiently and It is nearly done. the expected output is 1534, now I get 1236 but if we sort 2 (170 weight) and 5 (128 weight) we get the expected output which is 1534. But I can not figure out where the logical mistake prevents 2 and 5 from sorting themselves. It is about sorting elephantsOrderGiven to be proposedOrder array in the most efficient way to use the least ‘mass’. If you do not understand I can try to clarify the problem

let numberOfElephants = 8;
let massOfElephants = [197, 170, 124, 180, 128, 163, 188, 140];

let elephantsOrderGiven = [2, 5, 7, 8, 1, 3, 6, 4];
let proposedOrder = [5, 6, 1, 8, 2, 4, 7, 3]; 

const sortElephants = (
  numberOfElephants,
  massOfElephants,
  elephantsOrder,
  directorsOrder
) => {
  const elephantObject = [];
  let mass = 0;
  elephantsOrder.forEach((val, i) => {
    elephantObject.push({
      mass: massOfElephants[val - 1],
      numberOfEl: val,
      indexOfEl: i,
      isCorrect: false,
    });
  });

  for (let i = 0; i < numberOfElephants; i++) {
    const corrected = elephantObject.map((elephantObj) => {
      return {
        ...elephantObj,
        isCorrect:
          elephantsOrder.indexOf(elephantObj.numberOfEl) ===
          directorsOrder.indexOf(elephantObj.numberOfEl),
      };
    });
    const correctIndex = directorsOrder.indexOf(elephantObject[i].numberOfEl);
    const currentIndex = elephantsOrder.indexOf(elephantObject[i].numberOfEl);
    const elephantAtCorrectIndex = corrected.find(
      (elph) => elph.numberOfEl === elephantsOrder[correctIndex]
    );
    const elephantAtCurrentIndex = corrected.find(
      (elph) => elph.numberOfEl === elephantsOrder[currentIndex]
    );

    const isInCorrectPosition =
      proposedOrder.indexOf(elephantAtCorrectIndex.numberOfEl) ===
        elephantsOrder.indexOf(elephantAtCurrentIndex.numberOfEl) &&
      proposedOrder.indexOf(elephantAtCurrentIndex.numberOfEl) ===
        elephantsOrder.indexOf(elephantAtCorrectIndex.numberOfEl);

    if (correctIndex === currentIndex) continue;
    if (isInCorrectPosition) {
      const elephantOne = elephantObject.find(
        (elephant) => elephant.numberOfEl === elephantsOrder[correctIndex]
      );
      const secondElephant = elephantObject.find(
        (elephant) => elephant.numberOfEl === elephantsOrder[currentIndex]
      );

      temp = elephantsOrder[currentIndex];
      elephantsOrder[currentIndex] = elephantsOrder[correctIndex];
      elephantsOrder[correctIndex] = temp;
      console.log(elephantsOrder);

      mass += elephantOne.mass + secondElephant.mass;
    }

    if (!isInCorrectPosition) {
      const notSortedElephants = corrected.filter((elph) => !elph.isCorrect);

      const getHeaviest = (initial, current) => {
        return initial.mass > current.mass ? initial : current;
      };
      const getLightest = (initial, current) => {
        return initial.mass < current.mass ? initial : current;
      };
      const lightest = notSortedElephants.reduce(getLightest);
      const heaviest = notSortedElephants.reduce(getHeaviest);

      const lightestHasPlaceOfTheHeaviest =
        elephantsOrder.indexOf(lightest.numberOfEl) ===
        proposedOrder.indexOf(heaviest.numberOfEl);

      if (!lightestHasPlaceOfTheHeaviest) {
        const currentIndexOfLightest = elephantsOrder.indexOf(
          lightest.numberOfEl
        );

        const elephantAtCorrectIndexOfLightest = notSortedElephants.find(
          (elph) => elph.numberOfEl === proposedOrder[currentIndexOfLightest]
        );

        const currentIndexOfMassyElephant = elephantsOrder.indexOf(
          elephantAtCorrectIndexOfLightest.numberOfEl
        );

        temp = elephantsOrder[currentIndexOfLightest];
        elephantsOrder[currentIndexOfLightest] =
          elephantsOrder[currentIndexOfMassyElephant];
        elephantsOrder[currentIndexOfMassyElephant] = temp;

        mass += lightest.mass + elephantAtCorrectIndexOfLightest.mass;
      }

      if (
        elephantsOrder.indexOf(lightest.numberOfEl) ===
        proposedOrder.indexOf(heaviest.numberOfEl)
      ) {
        const currentIndexOfHeaviest = elephantsOrder.indexOf(
          heaviest.numberOfEl
        );
        const correctIndexOfHeaviest = proposedOrder.indexOf(
          heaviest.numberOfEl
        );

        temp = elephantsOrder[currentIndexOfHeaviest];
        elephantsOrder[currentIndexOfHeaviest] =
          elephantsOrder[correctIndexOfHeaviest];
        elephantsOrder[correctIndexOfHeaviest] = temp;

        mass += lightest.mass + heaviest.mass;
      }
    }
  }
  console.log(elephantsOrder);

  return mass;
};

console.log(
  sortElephants(
    numberOfElephants,
    massOfElephants,
    elephantsOrderGiven,
    proposedOrder
  )
);

.