Angular Lifecycle hooks?

Just wanted to know if I don’t implement any lifecycle hooks explicitly does Angular framework call it implicitly?

For Eg: If I am not using @input in component does ngOnChanges will get triggered implicitly by angular as it gets executed before ngOnInit? and if I am usling @input but don’t write ngOnChanges then will it get called implicitly ? Same question for other Hooks?

Thanks in advance.

Material Icons font family initially renders as text

I’m working in javascript and am applying the Material Icons fontFamily to my component. On the initial render, the child component is being rendered as normal text using what I would assume is the browser’s default fallback font. Once the font has loaded, then it re-renders as an icon. I want to set this up so that nothing is displayed at all until the font has been loaded. I have normal text to the right of the icon that makes leaving the text present for accessibility an invalid argument.

Here are a couple of screenshot for reference:

Here is the code as it is now, where iconName is the text being used to render my icon:

                        <div
                          className="text-left d-flex align-items-center"
                          style={{
                            fontFamily: "Material Icons",
                            fontSize: "24px",
                            opacity: parentActive || parentExpanded ? 1 : 0.8,
                            padding: "0 9px",
                            maxWidth: "45px",
                            overflow: "hidden",
                            height: "2.5rem",
                            color:
                              parentActive || parentExpanded
                                ? color.primary
                                : undefined,
                          }}
                        >
                          <span aria-hidden>{iconName}</span>
                        </div>

I have tried a few different solutions but only one them has sort of worked and am looking for a better alternative if possible. One solution that I tried was to use a ternary operation to render a blank space when the font is not yet loaded:

                        {document.fonts.check('1em "Material Icons"') ? 
                        <div
                          className="text-left d-flex align-items-center"
                          style={{
                            fontFamily: "Material Icons",
                            fontSize: "24px",
                            opacity: parentActive || parentExpanded ? 1 : 0.8,
                            padding: "0 9px",
                            maxWidth: "45px",
                            overflow: "hidden",
                            height: "2.5rem",
                            color:
                              parentActive || parentExpanded
                                ? color.primary
                                : undefined,
                          }}
                        >
                          <span aria-hidden>{iconName}</span>
                        </div>
                        : <div style={{ width: "42px", height: "40px", color: "transparent" }}/>
                      }

This solution does work, but there is an issue with that I would like to avoid. With my original code, once the font has been loaded and you reload the page manually, the icon is loaded initially since the font has already loaded. With this new code snippet, it does avoid rendering the text when the font family has not yet been loaded at the initial render. The issue now is that it always initializes to false for some amount of time before seeing that the font is there. Running this code next to the original code at the same time shows that the icon can sometimes be rendered right away whereas this conditional statement doesn’t allow that to happen.
Another idea that I am aware of is using the font-display property and setting it to block. I think this would work, but I can’t figure out how to apply it to my code. It seems that webpack in my project is not configured to be able to read @font-face from a css file and I haven’t seen any other way to do this. I also am not sure what to put for the font-family src since I didn’t need to specify the src in the div styles before. I put questions marks in here but when I tried it I just removed the line entirely.

   @font-face {       
        font-family: 'Material Icons';
        src: ??;
        font-display: block;   
    }      
   .material-icons {       
        font-family: 'Material Icons', sans-serif;     
   } 

I get an error in the browser when I try to do this:
ERROR in ./src/navigation/components/iconFont.css 1:0 Module parse failed: Unexpected character ‘@’ (1:0) You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders > @font-face { | font-family: ‘Material Icons’;

I don’t want to have to update the project configurations to get that approach to work. Does anyone have any ideas that I could try out? Any help is much appreciated!

The text is encrypted [closed]

The writing must be deciphered. This text is encrypted.

The codes below are encrypted text..!

LyGNDYTdDWw5z2VN5eyruyA8S7rxYInQMQy6xvRSzbvwroH906ZkCl27ELecmSA

Wx9dvdpBQypiQyK44eHnyhwE8gYe7eZY7F27LVweI7FUq5GrN633qdBzQ3wNfiFt2ReKqU9UIlf4Y9MZXTNB2rqRh5gEhDvTIInQIyMHdhIFzh7MQhbTeLUuHZKrYgXT

How I should create metadata with Metaplex Token Data in ReactJS and the correctly use to createMetadataAccountV3?

Im trying to send metadata with Metaplex to one transaction in Solana, but this is not possible, always get one error:

error TypeError: context.programs.getPublicKey is not a function at Object.createMetadataAccountV3 (createMetadataAccountV3.ts:111:38)

Image Error

This is my code:

[....]
const contextMetaData = {
            eddsa: signTransaction,
            identity: publicKey,
            payer: publicKey,
            programs: {
              tokenMetadata: new PublicKey("AddressProgram"), 
            },
          };

const metadataAccount = await mpl.createMetadataAccountV3(contextMetaData, {
  metadata: undefined, // empty
  mint: mint.PublicKey, 
  mintAuthority: publicKey, 
  payer: publicKey,
  updateAuthority: 
  data: {
    name,
    symbol,
    uri: uri,
    sellerFeeBasisPoints: 0, 
    creators: null, 
  },
  isMutable: true, 
  collectionDetails: null, 
});

This is the instruction:

/**
 * This code was AUTOGENERATED using the kinobi library.
 * Please DO NOT EDIT THIS FILE, instead use visitors
 * to add features, then rerun kinobi to update it.
 *
 * @see https://github.com/metaplex-foundation/kinobi
 */
import { Context, Option, OptionOrNullable, Pda, PublicKey, Signer, TransactionBuilder } from '@metaplex-foundation/umi';
import { Serializer } from '@metaplex-foundation/umi/serializers';
import { CollectionDetails, CollectionDetailsArgs, DataV2, DataV2Args } from '../types';
export type CreateMetadataAccountV3InstructionAccounts = {
    /** Metadata key (pda of ['metadata', program id, mint id]) */
    metadata?: PublicKey | Pda;
    /** Mint of token asset */
    mint: PublicKey | Pda;
    /** Mint authority */
    mintAuthority: Signer;
    /** payer */
    payer?: Signer;
    /** update authority info */
    updateAuthority?: PublicKey | Pda | Signer;
    /** System program */
    systemProgram?: PublicKey | Pda;
    /** Rent info */
    rent?: PublicKey | Pda;
};
export type CreateMetadataAccountV3InstructionData = {
    discriminator: number;
    data: DataV2;
    isMutable: boolean;
    collectionDetails: Option<CollectionDetails>;
};
export type CreateMetadataAccountV3InstructionDataArgs = {
    data: DataV2Args;
    isMutable: boolean;
    collectionDetails: OptionOrNullable<CollectionDetailsArgs>;
};
export declare function getCreateMetadataAccountV3InstructionDataSerializer(): Serializer<CreateMetadataAccountV3InstructionDataArgs, CreateMetadataAccountV3InstructionData>;
export type CreateMetadataAccountV3InstructionArgs = CreateMetadataAccountV3InstructionDataArgs;
export declare function createMetadataAccountV3(context: Pick<Context, 'eddsa' | 'identity' | 'payer' | 'programs'>, input: CreateMetadataAccountV3InstructionAccounts & CreateMetadataAccountV3InstructionArgs): TransactionBuilder;

I already check the documentation, but im not expert in this area. How I should create the correctly instruction to error?

Regards !

I want find the problem or some guide to fix and use correctly createMetadataAccountV3

How to create a bar chart image on nodejs without a browser? [duplicate]

Have a single nodejs project using a PDF generator, and need paste a bar chart into it, but the project runs on a desktopless server.

Have any library or method to create a bar chart image on nodejs on the runtime without a web browser for paste it into a pdf file?

I use puppeteer for create the PDF but the Chart.js library can not render the canvas, by example:

await page.setContent(`<!DOCTYPE html>
<html><body>
<canvas id="chart"></canvas>
<script>
    const ctx = document.getElementById('chart');

    new Chart(ctx, {
        type: 'bar',
        data: {
            labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
            datasets: [{
                label: '# of Votes',
                data: [12, 19, 3, 5, 2, 3],
                borderWidth: 1
            }]
        },
        options: {
            scales: { y: { beginAtZero: true } }
        }
    });
</script>
</body></html>`,
{ waitUntil: 'domcontentloaded' });

await page.addScriptTag({ url: 'https://cdn.jsdelivr.net/npm/chart.js' })

The results is a blank page. That’s why I’m looking for a better option to generate a simple image and paste it directly.

Make Load More With Javascript Fetch in Laravel

Can u guys help me how to create load more with my javascript

and this is my javascript for fetch API resource

<script type="text/javascript">
  const filterProduct = document.getElementById("filterProducts");
  const domain = window.location.host
  if (filterProduct) {
    // Fetch JSON data and generate HTML
    fetch(`http://api.${domain}/v2/categories`)
      .then((response) => response.json())
      .then((data) => {
        const generateCTGameHTML = (games, targetElementId) => {
          const gameListHTML = games
            .map(
              (game) => `
                <a class="group relative transform overflow-hidden rounded-2xl bg-murky-700 duration-300 ease-in-out hover:shadow-2xl hover:ring-2 hover:ring-primary-500 hover:ring-offset-2 hover:ring-offset-murky-900" href="order/${game?.slug}" style="outline: none;">
                  <img alt="${game?.title}" width="192" height="288" class="aspect-[4/6] object-cover object-center" src="${game?.image}" style="color: transparent;">
                  <article class="absolute inset-x-0 -bottom-10 z-10 flex transform flex-col px-3 transition-all duration-300 ease-in-out group-hover:bottom-3 sm:px-4 group-hover:sm:bottom-4">
                    <h2 class="truncate text-sm font-semibold text-murky-200 sm:text-base">${game?.title}</h2>
                    <p class="truncate text-xxs text-murky-400 sm:text-xs">${game?.production}</p>
                  </article>
                  <div class="absolute inset-0 transform bg-gradient-to-t from-transparent transition-all duration-300 group-hover:from-murky-900"></div>
                </a>
              `
            )
            .join("");

          const gameListElement = document.getElementById(targetElementId);
          gameListElement.innerHTML = gameListHTML;
        };
        data.forEach(function(cat){
            generateCTGameHTML(cat.lists, cat.panel);
        });
      })
      .catch((error) => console.log("Error:", error));
  }
    // Drawer Menu
    function drawerMenu() {
      return {
          open: false,
          usedKeyboard: false,
          init() {
              this.$watch('open', value => {
                  value && this.$refs.closeButton.focus()
                  this.toggleOverlay()
              })
              this.toggleOverlay()
          },
          toggleOverlay() {
              document.body.classList[this.open ? 'add' : 'remove']('h-screen', 'overflow-hidden')
          }
      }
  }

</script>

this my html

 <div id="filterProducts">
            @foreach ($typecategories as $item)
                <div class="hidden" id="{{ preg_replace('/s+/', '', $item->name) }}panel" role="tabpanel" aria-labelledby="{{ preg_replace('/s+/', '', $item->name) }}panel-tab">
                <div id="{{ preg_replace('/s+/', '', $item->name) }}" class="grid grid-cols-3 gap-4 sm:grid-cols-4 sm:gap-x-6 sm:gap-y-8 lg:grid-cols-5 xl:grid-cols-6"></div>
                </div>
            @endforeach
          </div>

in my html code not add a button from load more because i dont know how to called in javascript system,
and i need load more form diferent panels like my json

Node js asynchron router

i have a question about Node js router, i want that the router send a answer for the webrequest directly without waiting for some code which is inside a promise block and i am not sure if i have understand asynchron working from nodejs good enough, if my following code would do that:

    let objektKunden=[];
app.get('/getuser', async function (req, res)
{
  try
  {
     new Promise((resolve) => {
      //console.log(getuser);
      
      const kundenData = [];
      const masterData = [];

        Kunden.forEach(item => {
          if (item.note !== "master") {
            kundenData.push(item);
          } else {
            masterData.push(item);
          }
        });
      objektKunden[0]=kundenData;
      objektKunden[1]=APIKeyInvalid;
      objektKunden[2]=Masteraccounts;
      objektKunden[3]=masterData;
      const responseJSON = JSON.stringify(objektKunden);     
  });
  res.status(200).json(objektKunden);
  }
  catch (error)
  {
    console.error("error getuser:", error);
    res.status(500).send("error");
  }
});

What i want is that the router send objektKunden directly as answer and dont wait that the code above which is inside the promise will be run first

How to create custom undo/redo buttons for GrapesJS template editor?

I’m working on a project using GrapesJS template editor, and I’m trying to implement undo/redo functionality with two buttons. Of course, the buttons I created do not have currently the undo and redo actions.

Please help me!

<div class="action">
    <a class="btn" id="undo-btn"><i class="fa fa-undo"></i></a>
    <a class="btn" id="redo-btn"><i class="fa fa-redo"></i></a>
</div>
const editor = grapesjs.init({
  // Indicate where to init the editor. You can also pass an HTMLElement
  container: '#gjs',
  // Get the content for the canvas directly from the element
  // As an alternative we could use: `components: '<h1>Hello World Component!</h1>'`,
  fromElement: true,
  // Size of the editor
  height: '300px',
  width: 'auto',
  // Disable the storage manager for the moment
  storageManager: false,
  // Avoid any default panel
  panels: { defaults: [...] },
  // ...
});
$('#undo-btn').click(function() {
    // undo action here
})
$('#redo-btn').click(function() {
    // redo action here
})

How to intergrate Jupiter terminal dexswap in WordPress?

This is the terminal, scrolling down gives the codes to put in header and body. It also provides the code snippet.

https://terminal.jup.ag/

So I’ve put

<script src='https://terminal.jup.ag/main-v2.js' /> in my website head

and

<div id="integrated-terminal"></div> in my website body

The code snippet is inserted like this in a html block:

<script 
    window.Jupiter.init({
  displayMode: "integrated",
  integratedTargetId: "integrated-terminal",
  endpoint: "https://api.mainnet-beta.solana.com",

});
</script

The Jupiter dex swap is not showing up.

My domain : top-autoservice.nl

How to test the downloaded file content using jest

I have the following code to download a file on button click:

const blob = new Blob([data], { type: 'text/csv;charset=utf-8;' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', 'fileName.csv');
link.click();

I wonder if there is a way to test the content of the downloaded file.

I tried to mock createObjectURL object and check the value of link’s attributes.

jest
 .spyOn(URL, 'createObjectURL')
 .mockReturnValue('test');

expect(link.download).toEqual('filename.csv');
expect(link.href).toEqual('test');

My Array Is Not Being Loaded By my useState Function

My JavaScript (ES6) creates a list of data, which I then use my useState function to set a state variable’s value. Console.log shows the state variable remains an empty array after setting the state. Why would useState not work?

import { useEffect, useState } from "react";
import { TableContainer } from '@chakra-ui/react';

function Leaderboard() {
    const [reportLeaders, setReportLeaders] = useState([]);

    const fetchData = async () => {
        const reporterResponse = await fetch("URL REDACTED");
        if (reporterResponse.ok) {
            // Data cleanup an compilation which is confirmed to be correct.
            console.log('***** Compiled Reports List: ' + JSON.stringify(reportsList));
            // Update the list of report leaders.
            setReportLeaders(reportsList);
            console.log("***** Updated Reports Leaders: " + JSON.stringify(reportLeaders));
        }
    };

    useEffect(() => {
        fetchData();
    }, []);

The final console.log shows reportLeaders = [] instead of showing it containing the values in the reportsList array.

How to get the user-input value from a HTML text field

I am learning JS and trying to make a simple calculator on my own with 1 weeks lessons to test myself but I got stuck at getting the user-input values from my HTML text fields,

below is my html:

    <div class="container">
        <input id="first-number" type="number" placeholder="first number">
        <input id="second-number" type="number" placeholder="second number">
        <br /><br />
        <button id="multiplication" onclick="multiply()">Mutliply</button>
        <button id="addition" onclick="addition()">Addition</button>
        <button id="subtraction" onclick="subtraction()">Subtraction</button>
        <button id="divison" onclick="division()">Divison</button>
        <br /><br />
        Your answer is <b><span id="final-answer"></span></b>
    </div>

and below is my JS code:

let firstNumber = document.getElementById("first-number").value;
let secondNumber = document.getElementById("second-number").value;

function multiply() {
    finalAnswser = firstNumber + secondNumber;
    document.getElementById("final-answer").innerHTML = finalAnswser;
    console.log(firstNumber);
};

I am only working on getting the first function correct, since as per my understanding the rest will follow teh same pattern except differnt operators..

PS: I haven’t learn the.value porperty as of yet but I Google and came to this solution but even this not working for me, any help is highly appreciate

EDIT: So now I know I was declaring the firstNumber and secondNumber outside of my function before the button actions, and I have also updated my JS code to the following:

function multiply() {
    let firstNumber = document.getElementById("first-number").value;
    let secondNumber = document.getElementById("second-number").value;
    finalAnswser = firstNumber * secondNumber;
    document.getElementById("final-answer").innerHTML = finalAnswser;
    console.log(firstNumber);
};

function addition() {
    let firstNumber = document.getElementById("first-number").value;
    let secondNumber = document.getElementById("second-number").value;
    finalAnswser = firstNumber + secondNumber;
    document.getElementById("final-answer").innerHTML = finalAnswser;
    console.log(firstNumber);
};

function subtraction() {
    let firstNumber = document.getElementById("first-number").value;
    let secondNumber = document.getElementById("second-number").value;
    finalAnswser = firstNumber - secondNumber;
    document.getElementById("final-answer").innerHTML = finalAnswser;
    console.log(firstNumber);
};

function division() {
    let firstNumber = document.getElementById("first-number").value;
    let secondNumber = document.getElementById("second-number").value;
    finalAnswser = firstNumber / secondNumber;
    document.getElementById("final-answer").innerHTML = finalAnswser;
    console.log(firstNumber);
};

and the multiply, division and subtraction are working perfectly but the addition function is adding 2 string instead of numbers.

File transfer between React/express server

I’m trying to transfer file between my react app and my express server, but the logs show ”
undefined
{}” on the server. I can see the files on react, so the problem must be in the transfer or with the reception, but i don’t see where.

React :

handleMultipleSubmit(event) {
    event.preventDefault();
    const formData = new FormData();
    this.state.files.forEach((file, index) => {
        formData.append(`file${index}`, file);
    }); 
    console.log(formData);
    uploadFile(formData,res=>{
        console.log("form uploaded");
        console.log(res);
    },()=>{});
}
render(){
    return (<form onSubmit={this.handleMultipleSubmit}>
                <input type="file" multiple onChange={this.handleMultipleChange} />
                <button type="submit">Upload</button>
            </form>);
}
function uploadFiles(info,Callback){
console.log("uploading");
console.log(info);
var option={
    method : "POST",
    mode: 'cors',
    headers : {'content-type': 'multipart/form-data',},
    body: info
}
fetch("http://localhost:8000/uploadFiles",option).then(
    function(response){ 
        return response.text();  
    }).then(function(result){
        Callback(result);
})

}

Express :

const fileupload = require("express-fileupload");
var router = require('express').Router();
router.use(fileupload());
router.post("/", function (req, res) {
    console.log(req.files);
    console.log(req.body);
})
module.exports=router;

accessing VariantProps defined with Eva

I’m trying to access VariantProps defined with class-variance-authority, the props are connected using an interface to the button:

import React, {ComponentPropsWithRef } from "react";
import { type VariantProps } from "class-variance-authority";
import { buttonStyles } from "./variants";

type ButtonElementProps = ComponentPropsWithRef<'button'>;


export interface ButtonProps
  extends Omit<ButtonElementProps, "color"> ,
    VariantProps<typeof buttonStyles> {
  leftIcon?: React.ReactNode;
  rightIcon?: React.ReactNode;
  label?: string;
  test?: string;
}

When I try to import the button in another project I can access to props like leftIcon, rightIcon and label but not the ones defined inside buttonStyles