Snippets Collections
import java.io.*;

class Test {
    public static void main(String args[]) {
        String path = "sample.txt";
        try {
            BufferedReader br = new BufferedReader(new FileReader(path));
            int charCount = 0;
            int lineCount = 0;
            int wordCount = 0;
            String line;

            while ((line = br.readLine()) != null) {
                charCount += line.length();
                lineCount++;
                String[] words = line.split("\\s+");
                wordCount += words.length;
            }

            br.close();

            System.out.println("Number of characters: " + charCount);
            System.out.println("Number of words: " + wordCount);
            System.out.println("Number of lines: " + lineCount);
        } catch (IOException e) {
            System.out.println(e);
        }
    }
}
import java.io.*;

public class FileCopyExample {

    public static void main(String[] args) {
        try {
            FileReader fr1 = new FileReader("source.txt");
            FileWriter fw2 = new FileWriter("destination.txt");

            int i;
            while ((i = fr1.read()) != -1) {
                fw2.write((char) i);
            }

            System.out.println("File copied");

            fr1.close();
            fw2.close();
        } catch (IOException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
import java.io.*;

public class FileExample {
    static FileInputStream fis;

    public static void main(String[] args) {
        try {
            fis = new FileInputStream("example.txt");

            int data;
            while ((data = fis.read()) != -1) {
                System.out.print((char) data);
            }

            fis.close();
        } catch (IOException io) {
            System.out.println("Caught IOException: " + io.getMessage());
        }
    }
}
// Custom exception class
class NegativeNumberException extends Exception {
    public NegativeNumberException(String message) {
        super(message);
    }
}

// Class using the custom exception
public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            int result = calculateSquare(5);
            System.out.println("Square: " + result);

            result = calculateSquare(-3); // This will throw NegativeNumberException
            System.out.println("Square: " + result); // This line won't be executed
        } catch (NegativeNumberException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }

    // Method that may throw the custom exception
    private static int calculateSquare(int number) throws NegativeNumberException {
        if (number < 0) {
            // Throw the custom exception if the number is negative
            throw new NegativeNumberException("Negative numbers are not allowed.");
        }
        return number * number;
    }
}
public class ExceptionExample {
    public static void main(String[] args) {
        int n = 26;
        try {
            int m = n / 0;
        } catch (ArithmeticException e) {
            System.out.println("Exception caught: " + e);
        } finally {
            System.out.println("Any number cannot be divided by zero");
        }
    }
}
public class StringBufferStringBuilderExample{
public static void main(String args[]){
StringBuffer stringBuffer=new StringBuffer("hello");
stringBuffer.append(" ").append("world");
System.out.println("StringBuffer result:" + stringBuffer);
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append("is").append("awesome");
System.out.println("StringBuilder result:" + stringBuilder);
}
}
public class StringExample {
    public static void main(String[] args) {
        String s = "Hello World!";
        System.out.println("Original string: " + s);
        System.out.println("Length: " + s.length());
        System.out.println("Uppercase: " + s.toUpperCase());
        System.out.println("Lowercase: " + s.toLowerCase());
        System.out.println("Substring from index 7: " + s.substring(7));
        System.out.println("Replace 'o' with 'x': " + s.replace('o', 'x'));
        System.out.println("Contains 'world': " + s.contains("world"));
        System.out.println("Starts with 'Hello': " + s.startsWith("Hello"));
        System.out.println("Index of 'o': " + s.indexOf('o'));
        System.out.println("Last index of 'o': " + s.lastIndexOf('o'));
        System.out.println("Ends with 'ld!': " + s.endsWith("ld!"));
        System.out.println("Character at index 4: " + s.charAt(4));
        System.out.println("Trimmed: " + s.trim());
    }
}
// Interface
interface Printable {
    void print();
}

// Class implementing the interface
class Printer implements Printable {
    @Override
    public void print() {
        System.out.println("Printing...");
    }
}

public class InterfaceExample {
    public static void main(String[] args) {
        // Creating an instance of the class implementing the interface
        Printable printer = new Printer();

        // Using the interface method
        printer.print();
    }
}
// Abstract class: Person
abstract class Person {
    private String name;
    private int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public abstract void displayDetails();

    public void greet() {
        System.out.println("Hello, I am " + name + ".");
    }
}

// Subclass: Student
class Student extends Person {
    private int studentId;

    public Student(String name, int age, int studentId) {
        super(name, age);
        this.studentId = studentId;
    }

    @Override
    public void displayDetails() {
        System.out.println("Student - Name: " + super.getName() + ", Age: " + super.getAge() +
                ", Student ID: " + studentId);
    }

    public void study() {
        System.out.println("Student is studying.");
    }
}

// Subclass: Faculty
class Faculty extends Person {
    private String department;

    public Faculty(String name, int age, String department) {
        super(name, age);
        this.department = department;
    }

    @Override
    public void displayDetails() {
        System.out.println("Faculty - Name: " + super.getName() + ", Age: " + super.getAge() +
                ", Department: " + department);
    }

    public void teach() {
        System.out.println("Faculty is teaching.");
    }
}

public class PersonExample {
    public static void main(String[] args) {
        Student student = new Student("John", 20, 123);
        Faculty faculty = new Faculty("Dr. Smith", 35, "Computer Science");

        student.displayDetails();
        student.greet();
        student.study();

        System.out.println();

        faculty.displayDetails();
        faculty.greet();
        faculty.teach();
    }
}
// Account class (Base class)
class Account {
 private int accountNumber;
 private double balance;
 public Account(int accountNumber) {
 this.accountNumber = accountNumber;
 this.balance = 0.0;
 }
 public int getAccountNumber() {
 return accountNumber;
 }
 public double getBalance() {
 return balance;
 }
 public void deposit(double amount) {
 balance += amount;
 System.out.println("Deposited: $" + amount);
 }
 public void withdraw(double amount) {
 if (amount <= balance) {
 balance -= amount;
 System.out.println("Withdrawn: $" + amount);
 } else {
 System.out.println("Insufficient balance");
 }
 }
}
// Subclasses of Account
class SavingsAccount extends Account {
 // Additional features specific to savings account
 public SavingsAccount(int accountNumber) {
 super(accountNumber);
 }
}
class CheckingAccount extends Account {
 // Additional features specific to checking account
 public CheckingAccount(int accountNumber) {
 super(accountNumber);
 }
}
// Customer class
class Customer {
 private String name;
 private Account account;
 public Customer(String name, Account account) {
 this.name = name;
 this.account = account;
 }
 public void deposit(double amount) {
 account.deposit(amount);
 }
 public void withdraw(double amount) {
 account.withdraw(amount);
 }
 public double checkBalance() {
 return account.getBalance();
 }
}
// Employee class
class Employee {
 private String name;
 public Employee(String name) {
 this.name = name;
 }
 public void processTransaction(Customer customer, double amount,
String type) {
 if (type.equalsIgnoreCase("Deposit")) {
 customer.deposit(amount);
 } else if (type.equalsIgnoreCase("Withdraw")) {
 customer.withdraw(amount);
 } else {
 System.out.println("Invalid transaction type");
 }
 }
}
// Main class for testing
public class BankingApplication {
 public static void main(String[] args) {
 // Create accounts for customers
 SavingsAccount savingsAccount = new SavingsAccount(1001);
 CheckingAccount checkingAccount = new CheckingAccount(2001);
 // Create customers and link accounts
 Customer customer1 = new Customer("Alice", savingsAccount);
 Customer customer2 = new Customer("Bob", checkingAccount);
 // Create bank employees
 Employee employee1 = new Employee("Eve");
 // Employee processing transactions for customers
 employee1.processTransaction(customer1, 1000, "Deposit");
 employee1.processTransaction(customer2, 500, "Withdraw");
 // Checking customer balances after transactions
 System.out.println("Customer 1 Balance: $" +
customer1.checkBalance());
 System.out.println("Customer 2 Balance: $" +
customer2.checkBalance());
 }
}
class Employee {
    private String name;
    private double baseSalary;

    public Employee(String name, double baseSalary) {
        this.name = name;
        this.baseSalary = baseSalary;
    }

    public String getName() {
        return name;
    }

    // Base implementation of computeSalary method
    public double computeSalary() {
        return baseSalary;
    }
}
class Manager extends Employee {
    private double bonus;

    public Manager(String name, double baseSalary, double bonus) {
        super(name, baseSalary);
        this.bonus = bonus;
    }

    // Override computeSalary method to include bonus
    @Override
    public double computeSalary() {
        // Calling the base class method using super
        double baseSalary = super.computeSalary();
        return baseSalary + bonus;
    }
}
public class PolymorphicInvocationExample {
    public static void main(String[] args) {
        // Polymorphic invocation using base class reference
        Employee emp1 = new Employee("John Doe", 50000.0);
        System.out.println("Employee Salary: $" + emp1.computeSalary());

        // Polymorphic invocation using subclass reference
        Employee emp2 = new Manager("Jane Smith", 60000.0, 10000.0);
        System.out.println("Manager Salary: $" + emp2.computeSalary());
    }
}
// Employee class (base class)
class Employee {
    private String name;
    private int employeeId;

    public Employee(String name, int employeeId) {
        this.name = name;
        this.employeeId = employeeId;
    }

    public String getName() {
        return name;
    }

    public int getEmployeeId() {
        return employeeId;
    }

    public void displayDetails() {
        System.out.println("Employee ID: " + employeeId);
        System.out.println("Name: " + name);
    }
}

// Faculty class (inherits from Employee)
class Faculty extends Employee {
    private String department;
    private String designation;

    public Faculty(String name, int employeeId, String department, String designation) {
        super(name, employeeId);
        this.department = department;
        this.designation = designation;
    }

    public String getDepartment() {
        return department;
    }

    public String getDesignation() {
        return designation;
    }

    @Override
    public void displayDetails() {
        super.displayDetails();
        System.out.println("Department: " + department);
        System.out.println("Designation: " + designation);
    }
}

// Staff class (inherits from Employee)
class Staff extends Employee {
    private String role;

    public Staff(String name, int employeeId, String role) {
        super(name, employeeId);
        this.role = role;
    }

    public String getRole() {
        return role;
    }

    @Override
    public void displayDetails() {
        super.displayDetails();
        System.out.println("Role: " + role);
    }
}

// UniversityProgram class (main program)
public class UniversityProgram {
    public static void main(String[] args) {
        // Creating instances of Faculty and Staff
        Faculty facultyMember = new Faculty("John Doe", 101, "Computer Science", "Professor");
        Staff staffMember = new Staff("Jane Smith", 201, "Administrative Assistant");

        // Displaying details of Faculty and Staff
        System.out.println("Faculty Details:");
        facultyMember.displayDetails();
        System.out.println();

        System.out.println("Staff Details:");
        staffMember.displayDetails();
    }
}
public classgc
{
public static void main(String args[])
{
System.gc();
System.out.println("garbage collection is required using system.gc()");
runtime.getruntime().gc();
System.out.println("garbage collection is required using system.gc()");
Sytsem.out.println("free menory:"+runtime.getruntime() freememory()+"bytes");
System.out.println("total memory:"+runtime.getruntime().totalmemory()+"bytes");
System.out.println("available processors"+runtime.getruntime()available processors());
runtime.getruntime().exit(0);
System.out.println("this linewill not be executed");
}
}
package com.example.custom;
import java.util.ArrayList; // Import ArrayList from java.util package
class CustomClass {
void display() {
System.out.println("Custom class in the custom package.");
}
}
public class Main {
public static void main(String args[]) {
ArrayList list = new ArrayList<>(); // Fix the typo in ArrayList declaration
list.add("hello");
list.add("world");
System.out.println("ArrayList from java.util package: " + list);
CustomClass customObj = new CustomClass();
customObj.display();
AccessModifiersDemo demo = new AccessModifiersDemo();
demo.publicMethod();
demo.defaultMethod();
}
}
class AccessModifiersDemo {
public void publicMethod() {
System.out.println("Public method can be accessed from anywhere.");
}
void defaultMethod() {
System.out.println("Default method can be accessed within the same package.");
}
}
public class ArrayOperations {
    public static void main(String[] args) {
        // Initializing an array
        int[] numbers = { 5, 12, 8, 3, 15 };

        // Accessing elements
        System.out.println("Element at index 2: " + numbers[2]);

        // Finding the length of the array
        System.out.println("Length of the array: " + numbers.length);

        // Modifying an element
        numbers[1] = 20;

        // Printing the array
        System.out.print("Modified array: ");
        for (int i = 0; i < numbers.length; i++) {
            System.out.print(numbers[i] + " ");
        }
        System.out.println();

        // Finding the maximum element
        int maxElement = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] > maxElement) {
                maxElement = numbers[i];
            }
        }
        System.out.println("Maximum element: " + maxElement);

        // Finding the minimum element
        int minElement = numbers[0];
        for (int i = 1; i < numbers.length; i++) {
            if (numbers[i] < minElement) {
                minElement = numbers[i];
            }
        }
        System.out.println("Minimum element: " + minElement);

        // Iterating through the array to calculate the sum
        int sum = 0;
        for (int num : numbers) {
            sum += num;
        }
        System.out.println("Sum of elements: " + sum);
    }
}
public class ArraySumAverage {
    public static void main(String[] args) {
        // Predefined array of integers
        int[] array = { 10, 20, 30, 40, 50 };

        // Calculate sum and average
        int sum = 0;
        for (int i = 0; i < array.length; i++) {
            sum += array[i];
        }
        double average = (double) sum / array.length;

        // Output: Sum and Average
        System.out.println("Sum of the elements: " + sum);
        System.out.println("Average of the elements: " + average);
    }
}
class Explicit
{
    public static void main(String[] args)
    {
        long l=99;
        int i=(int)l;
        System.out.println("long value ="+l);
        System.out.println("int value ="+i);
    }
}
##Constructor overloading##

class T
{
    T()
    {
        System.out.println("0-args");
    }
    T(int i)
    {
        System.out.println("1-args");
    }
    T(int i,int j)
    {
        System.out.println("2-args");
    }
    public static void main(String[] args)
    {
        System.out.println("constructor overloading");
        T t1=new T();
        T t2=new T(10);
        T t3=new T(20,30);
    }
}





##Method overloading##

class MO {
    static int add(int a, int b) {
        return a + b;
    }

    static int add(int a, int b, int c) {
        return a + b + c;
    }

    public static void main(String[] args) {
        System.out.println(add(11, 11));
    }
}
class Comdargs{
public static void main(String[] args){
System.out.println(args[0]+" "+args[1]);
System.out.println(args[0]+args[1]);
}
}


###IN THE COMMAND PROMPT AFTER JAVA COMDARGS GIVE YOUR COMMAND LINE ARRGUMENTS###
import java.util.Scanner;

public class GradeCheckerSwitch {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the student's score: ");
        int score = scanner.nextInt();

        char grade = getGradeSwitch(score);

        System.out.println("Grade: " + grade);
    }

    public static char getGradeSwitch(int score) {
        int range = score / 10;

        switch (range) {
            case 10:
            case 9:
                return 'A';
            case 8:
                return 'B';
            case 7:
                return 'C';
            case 6:
                return 'D';
            default:
                return 'F';
        }
    }
}



USING IF -ELSE

import java.util.Scanner;

public class GradeCheckerIfElse {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter the student's score: ");
        int score = scanner.nextInt();

        char grade = getGradeIfElse(score);

        System.out.println("Grade: " + grade);
    }

    public static char getGradeIfElse(int score) {
        if (score >= 90 && score <= 100) {
            return 'A';
        } else if (score >= 80 && score < 90) {
            return 'B';
        } else if (score >= 70 && score < 80) {
            return 'C';
        } else if (score >= 60 && score < 70) {
            return 'D';
        } else if (score >= 0 && score < 60) {
            return 'F';
        } else {
            // Handle invalid score (outside the range 0-100)
            System.out.println("Invalid score. Please enter a score between 0 and 100.");
            return '\0'; // '\0' is used to represent an undefined character
        }
    }
}
public class OperatorDemo {
    public static void main(String[] args) {
        // Comparison operators
        int a = 5, b = 10;

        System.out.println("Comparison Operators:");
        System.out.println("a == b: " + (a == b));
        System.out.println("a != b: " + (a != b));
        System.out.println("a < b: " + (a < b));
        System.out.println("a > b: " + (a > b));
        System.out.println("a <= b: " + (a <= b));
        System.out.println("a >= b: " + (a >= b));

        // Arithmetic operators
        int x = 15, y = 4;

        System.out.println("\nArithmetic Operators:");
        System.out.println("x + y: " + (x + y));
        System.out.println("x - y: " + (x - y));
        System.out.println("x * y: " + (x * y));
        System.out.println("x / y: " + (x / y));
        System.out.println("x % y: " + (x % y));

        // Bitwise operators
        int num1 = 5, num2 = 3;

        System.out.println("\nBitwise Operators:");
        System.out.println("num1 & num2: " + (num1 & num2)); // Bitwise AND
        System.out.println("num1 | num2: " + (num1 | num2)); // Bitwise OR
        System.out.println("num1 ^ num2: " + (num1 ^ num2)); // Bitwise XOR
        System.out.println("~num1: " + (~num1));             // Bitwise NOT
        System.out.println("num1 << 1: " + (num1 << 1));     // Left shift
        System.out.println("num1 >> 1: " + (num1 >> 1));     // Right shift
    }
}
Interview Preparation Prompt:

I need to prepare a short, one-page interview featuring a mix of personal and professional questions for a successful individual. Below is an example of the interview style I am aiming for [attach example image if available]. I will provide you with the details of the person to be interviewed, which may include a LinkedIn profile or a resume/CV. Based on the provided information, please create a set of interview questions that cover their background, achievements, current role, personal interests, and advice for others.

Steps:

Describe yourself and your motivation:
Ask about their background, education, and what inspired their career path.
Career milestones and achievements:
Inquire about significant milestones and noteworthy accomplishments in their career.
Current role and impact:
Focus on their current position, goals, and the impact of their work.
Challenges and solutions:
Discuss the challenges they've faced and how they overcame them.
Personal interests and work-life balance:
Explore their hobbies, interests, and how they balance professional and personal life.
Advice and future vision:
Request advice for aspiring professionals and insights into their future goals.
Please generate questions based on the details I provide. For example, if I share a LinkedIn profile or CV, use that information to tailor the questions accordingly.

/**
 * function to add two numbers together
 * @param {number} a this is the first number param
 * @param {number} b this is the second number param
 * @returns {number}
 */
function addNum(a = 0, b = 0) {
  return a + b;
}

addNum(4, 6);
//Type Host Value TTL
CNAME Record www parkingpage.namecheap.com. 30 min
URL Redirect Record @ http://www.avsfitness.com/ unmasked
e69857f152e0c2f5384cc603586c3dff2c30c93e674263346a702863e7277c1a  Transmission-4.0.6.dmg
29417282f2a5405018a211aa94e60d324657cf347e7a496ca7a51798ede0f6c1  transmission-4.0.6-x64.msi
b7bdac970c686cfcdc249dc96fabb83fe85057e7d53f4c9aa55dc71891ba8c26  transmission-4.0.6-x86.msi
8fe99234539da38be335fc3d999d1364c0c203d5dbc53109519b1df634e0462d  transmission-4.0.6-qt5-x64.msi
2f58c166e3163ad4fbe7c14a2a1fdf4c36fd7376891be2922091ffed1aa3c702  transmission-4.0.6-qt5-x86.msi
2a38fe6d8a23991680b691c277a335f8875bdeca2b97c6b26b598bc9c7b0c45f  transmission-4.0.6.tar.xz
f9984b6ba51a02bb8f880c538b28e2c7d6a3b7a22257a166cc3e1d55a133ab34  Transmission-3.00.dmg
c34828a6d2c50c7c590d05ca50249b511d46e9a2a7223323fb3d1421e3f6b9d1  transmission-3.00-x64.msi
eeab85327fa8a1299bb133d5f60f6674ca9e76522297202bbe39aae92dad4f32  transmission-3.00-x86.msi
9144652fe742f7f7dd6657716e378da60b751aaeda8bef8344b3eefc4db255f2  transmission-3.00.tar.xz
helm install my-release oci://registry-1.docker.io/bitnamicharts/wordpress
# Read more about the installation in the 
Bitnami package for WordPress Chart Github repository

  helm repo add bitnami https://charts.bitnami.com/bitnami

    
//Models
public class Reward_Type
{
    [Key]
    public int Reward_Type_ID { get; set; }

    [Required]
    public string Reward_Type_Name { get; set; }

    [Required]
    public string Reward_Criteria { get; set; }

    public int Inventory_ID { get; set; } // Link to Inventory
    [ForeignKey(nameof(Inventory_ID))]
    public Inventory Inventory { get; set; } // Reference to Inventory item
}

//Viewmodels
public class RewardTypeViewModel
{
    public string Reward_Type_Name { get; set; }
    public string Reward_Criteria { get; set; }
    public int Inventory_ID { get; set; }
}

/controller
[HttpGet]
    [Route("getAllRewardTypes")]
    public async Task<IActionResult> GetAllRewardTypes()
    {
        try
        {
            var rewardTypes = await _appDbContext.Reward_Types
                .Include(rt => rt.Inventory) // Include Inventory details
                .ToListAsync();
            return Ok(rewardTypes);
        }
        catch (Exception)
        {
            return BadRequest();
        }
    }

    [HttpPost]
    [Route("createRewardType")]
    public async Task<IActionResult> CreateRewardType(RewardTypeViewModel rt)
    {
        try
        {
            var rewardType = new Reward_Type
            {
                Reward_Type_Name = rt.Reward_Type_Name,
                Reward_Criteria = rt.Reward_Criteria,
                Inventory_ID = rt.Inventory_ID
            };
            _appDbContext.Reward_Types.Add(rewardType);
            await _appDbContext.SaveChangesAsync();

            return CreatedAtAction(nameof(GetRewardTypeById), new { id = rewardType.Reward_Type_ID }, rewardType);
        }
        catch (Exception)
        {
            return BadRequest();
        }
    }

[HttpPost]
    [Route("setReward")]
    public async Task<IActionResult> SetReward(RewardSetViewModel r)
    {
        try
        {
            var reward = new Reward
            {
                Reward_Issue_Date = r.Reward_Issue_Date,
                Reward_Type_ID = r.Reward_Type_ID,
                IsPosted = r.IsPosted
            };
            _appDbContext.Rewards.Add(reward);
            await _appDbContext.SaveChangesAsync();

            // Automatically populate Reward_Member based on criteria
            var members = await _appDbContext.Members // Assuming members criteria is stored in members
                .Where(m => /* apply criteria based on reward type */ true)
                .ToListAsync();

            foreach (var member in members)
            {
                var rewardMember = new Reward_Member
                {
                    Member_ID = member.Member_ID,
                    Reward_ID = reward.Reward_ID,
                    IsRedeemed = false
                };
                _appDbContext.Reward_Members.Add(rewardMember);
            }
            await _appDbContext.SaveChangesAsync();

            return CreatedAtAction(nameof(GetRewardById), new { id = reward.Reward_ID }, reward);
        }
        catch (Exception)
        {
            return BadRequest();
        }
    }

[HttpPost]
    [Route("redeemReward")]
    public async Task<IActionResult> RedeemReward([FromBody] RewardRedeemViewModel request)
    {
        try
        {
            var rewardMember = await _appDbContext.Reward_Members
                .Include(rm => rm.Reward)
                .ThenInclude(r => r.Reward_Type)
                .FirstOrDefaultAsync(r => r.Reward_ID == request.RewardId && r.Member_ID == request.MemberId);

            if (rewardMember == null)
            {
                return NotFound("Reward not found or not eligible for the member.");
            }

            if (rewardMember.IsRedeemed)
            {
                return BadRequest("Reward is already redeemed.");
            }

            // Reduce inventory quantity
            var inventory = await _appDbContext.Inventories.FindAsync(rewardMember.Reward.Reward_Type.Inventory_ID);
            if (inventory == null || inventory.Inventory_Item_Quantity <= 0)
            {
                return BadRequest("Inventory item is not available.");
            }
            inventory.Inventory_Item_Quantity -= 1;
            _appDbContext.Entry(inventory).State = EntityState.Modified;

            // Mark reward as redeemed
            rewardMember.IsRedeemed = true;
            _appDbContext.Entry(rewardMember).State = EntityState.Modified;

            await _appDbContext.SaveChangesAsync();

            return Ok(new { Status = "Success", Message = "Reward redeemed successfully!" });
        }
        catch (Exception)
        {
            return BadRequest("An error occurred while redeeming the reward.");
        }
    }

public async Task<List<Inventory>> GetAvailableInventoryItems()
{
    return await _appDbContext.Inventories
        .Where(i => i.Inventory_Item_Quantity > 0)
        .ToListAsync();
}

public async Task<bool> ValidateRewardTypeCreation(RewardTypeViewModel rt)
{
    var inventory = await _appDbContext.Inventories.FindAsync(rt.Inventory_ID);
    return inventory != null && inventory.Inventory_Item_Quantity > 0;
}
IN(LOOKUP(USEREMAIL(),User Manager, Email, Role),LIST("Admin","Employee"))
//Suggested changes
1. Create Separate ViewModels: Define different ViewModels for each user type (Member, Employee, Owner) with the specific fields required for each.

2. Determine User Type First: Create a step in your registration process to first capture the user type.

3. Use Specific ViewModel Based on User Type: Use the captured user type to select and validate the appropriate ViewModel.

//Viewmodels
public class UserViewModel
{
    public string Email { get; set; }
    public string Password { get; set; }
    public int User_Type_ID { get; set; }
    // Common fields...
}

public class MemberViewModel : UserViewModel
{
    public int Contract_ID { get; set; }
    public bool Is_Active { get; set; }
    // Other member-specific fields...
}

public class EmployeeViewModel : UserViewModel
{
    public int Employee_Type_ID { get; set; }
    public int Shift_ID { get; set; }
    public int Hours_Worked { get; set; }
    // Other employee-specific fields...
}

public class OwnerViewModel : UserViewModel
{
    // Owner-specific fields...
}

//UserTypeVM
public class UserTypeVM
{
    public int User_Type_ID { get; set; }
}


//Controller
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Identity;
using System.Text.RegularExpressions;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;

[Route("api/[controller]")]
[ApiController]
public class UserController : ControllerBase
{
    private readonly UserManager<User> _userManager;
    private readonly AppDbContext _appDbContext;
    private readonly ILogger<UserController> _logger;

    public UserController(UserManager<User> userManager, AppDbContext appDbContext, ILogger<UserController> logger)
    {
        _userManager = userManager;
        _appDbContext = appDbContext;
        _logger = logger;
    }

    [HttpPost]
    [Route("DetermineUserType")]
    public async Task<IActionResult> DetermineUserType([FromForm] UserTypeViewModel userTypeViewModel)
    {
        if (userTypeViewModel == null || userTypeViewModel.User_Type_ID <= 0)
        {
            return BadRequest("Invalid user type.");
        }

        // Determine user type based on the provided information
        int userTypeID = userTypeViewModel.User_Type_ID;

        // Redirect to the appropriate registration method
        switch (userTypeID)
        {
            case 1:
                return await RegisterMember(userTypeViewModel);
            case 2:
                return await RegisterEmployee(userTypeViewModel);
            case 3:
                return await RegisterOwner(userTypeViewModel);
            default:
                return BadRequest("Invalid user type.");
        }
    }

    private async Task<IActionResult> RegisterMember(UserTypeViewModel userTypeViewModel)
    {
        // Map UserTypeViewModel to MemberViewModel
        var memberViewModel = new MemberViewModel
        {
            Email = userTypeViewModel.Email,
            Password = userTypeViewModel.Password,
            User_Type_ID = userTypeViewModel.User_Type_ID,
            // Initialize other member-specific fields
        };

        return await Register(memberViewModel);
    }

    private async Task<IActionResult> RegisterEmployee(UserTypeViewModel userTypeViewModel)
    {
        // Map UserTypeViewModel to EmployeeViewModel
        var employeeViewModel = new EmployeeViewModel
        {
            Email = userTypeViewModel.Email,
            Password = userTypeViewModel.Password,
            User_Type_ID = userTypeViewModel.User_Type_ID,
            // Initialize other employee-specific fields
        };

        return await Register(employeeViewModel);
    }

    private async Task<IActionResult> RegisterOwner(UserTypeViewModel userTypeViewModel)
    {
        // Map UserTypeViewModel to OwnerViewModel
        var ownerViewModel = new OwnerViewModel
        {
            Email = userTypeViewModel.Email,
            Password = userTypeViewModel.Password,
            User_Type_ID = userTypeViewModel.User_Type_ID,
            // Initialize other owner-specific fields
        };

        return await Register(ownerViewModel);
    }

    private async Task<IActionResult> Register(UserViewModel uvm)
    {
        try
        {
            var formCollection = await Request.ReadFormAsync();
            var photo = formCollection.Files.FirstOrDefault();

            // Validate Phone Number Pattern
            var phoneNumberPattern = @"^\d{10}$";
            bool isValidPhoneNumber = Regex.IsMatch(uvm.PhoneNumber, phoneNumberPattern);

            if (!isValidPhoneNumber) return BadRequest("Enter valid 10-digit phone number.");

            // Validate South African ID number
            if (!IsValidSouthAfricanIDNumber(uvm.Id_Number, uvm.Date_of_Birth))
            {
                return BadRequest("Enter a valid South African ID number.");
            }

            var user = await _userManager.FindByEmailAsync(uvm.Email);
            int lastUserID = _appDbContext.Users
                                .OrderByDescending(u => u.User_ID)
                                .Select(u => u.User_ID)
                                .FirstOrDefault();

            if (user == null)
            {
                if (photo != null && photo.Length > 0)
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        await photo.CopyToAsync(memoryStream);
                        var fileBytes = memoryStream.ToArray();
                        string base64Image = Convert.ToBase64String(fileBytes);

                        user = new User
                        {
                            User_ID = lastUserID + 1,
                            Name = uvm.Name,
                            Surname = uvm.Surname,
                            UserName = uvm.Email,
                            Email = uvm.Email,
                            PasswordHash = _userManager.PasswordHasher.HashPassword(null, uvm.Password),
                            User_Status_ID = uvm.User_Status_ID,
                            User_Type_ID = uvm.User_Type_ID,
                            PhoneNumber = uvm.PhoneNumber,
                            Date_of_Birth = uvm.Date_of_Birth,
                            ID_Number = uvm.Id_Number,
                            Physical_Address = uvm.Physical_Address,
                            Photo = base64Image // Store the base64 string of the photo
                        };

                        IdentityResult result = await _userManager.CreateAsync(user);

                        if (result.Succeeded)
                        {
                            // Assign role based on User_Type_ID
                            string roleName = GetRoleNameByUserType(uvm.User_Type_ID);
                            if (!string.IsNullOrEmpty(roleName))
                            {
                                var roleResult = await _userManager.AddToRoleAsync(user, roleName);
                                if (!roleResult.Succeeded)
                                {
                                    return BadRequest(new { Status = "Error", Errors = roleResult.Errors });
                                }
                            }

                            if (uvm.User_Type_ID == 1) // Member
                            {
                                var memberViewModel = uvm as MemberViewModel;
                                int lastMemberID = _appDbContext.Members
                                    .OrderByDescending(m => m.Member_ID)
                                    .Select(m => m.Member_ID)
                                    .FirstOrDefault();

                                var newMember = new Member
                                {
                                    Member_ID = lastMemberID + 1,
                                    User_ID = user.User_ID,
                                    Contract_ID = memberViewModel.Contract_ID,
                                    Is_Active = memberViewModel.Is_Active // Use the value from the view model
                                };

                                _appDbContext.Members.Add(newMember);
                                _logger.LogInformation("Adding new member with User_ID: {User_ID}, Member_ID: {Member_ID}", user.User_ID, newMember.Member_ID);
                                await _appDbContext.SaveChangesAsync();
                                _logger.LogInformation("Member added successfully with User_ID: {User_ID}, Member_ID: {Member_ID}", user.User_ID, newMember.Member_ID);
                            }
                            else if (uvm.User_Type_ID == 2) // Employee
                            {
                                var employeeViewModel = uvm as EmployeeViewModel;
                                int lastEmployeeID = _appDbContext.Employees
                                    .OrderByDescending(e => e.Employee_ID)
                                    .Select(e => e.Employee_ID)
                                    .FirstOrDefault();

                                var newEmployee = new Employee
                                {
                                    Employee_ID = lastEmployeeID == 0 ? 1 : lastEmployeeID + 1,
                                    User_ID = user.User_ID,
                                    Employment_Date = DateTime.UtcNow,
                                    Hours_Worked = employeeViewModel.Hours_Worked, // Use the value from the view model (initialized to zero)
                                    Employee_Type_ID = employeeViewModel.Employee_Type_ID,
                                    Shift_ID = employeeViewModel.Shift_ID
                                };

                                _appDbContext.Employees.Add(newEmployee);
                                _logger.LogInformation("Adding new employee with User_ID: {User_ID}, Employee_ID: {Employee_ID}", user.User_ID, newEmployee.Employee_ID);
                                await _appDbContext.SaveChangesAsync();
                                _logger.LogInformation("Employee added successfully with User_ID: {User_ID}, Employee_ID: {Employee_ID}", user.User_ID, newEmployee.Employee_ID);
                            }
                            else if (uvm.User_Type_ID == 3) // Owner
                            {
                                var ownerViewModel = uvm as OwnerViewModel;
                                int lastOwnerID = _appDbContext.Owners
                                    .OrderByDescending(o => o.Owner_ID)
                                    .Select(o => o.Owner_ID)
                                    .FirstOrDefault();

                                var newOwner = new Owner
                                {
                                    Owner_ID = lastOwnerID == 0 ? 1 : lastOwnerID + 1,
                                    User_ID = user.User_ID
                                };

                                _appDbContext.Owners.Add(newOwner);
                                _logger.LogInformation("Adding new owner with User_ID: {User_ID}, Owner_ID: {Owner_ID}", user.User_ID, newOwner.Owner_ID);
                                await _appDbContext.SaveChangesAsync();
                                _logger.LogInformation("Owner added successfully with User_ID: {User_ID}, Owner_ID: {Owner_ID}", user.User_ID, newOwner.Owner_ID);
                            }

                            return Ok(new { Status = "Success", Message = "Your profile has been created successfully!" });
                        }
                        else
                        {
                            return StatusCode(StatusCodes.Status500InternalServerError, result.Errors.FirstOrDefault()?.Description);
                        }
                    }
                }
                else
                {
                    return BadRequest("Photo is required.");
                }
            }
            else
            {
                return Forbid("User already exists.");
            }
        }
        catch (DbUpdateException dbEx)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, dbEx.InnerException?.Message ?? "An error occurred while processing your request.");
        }
        catch (Exception ex)
        {
            return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while processing your request.");
        }
    }

    private bool IsValidSouthAfricanIDNumber(string idNumber, DateTime dateOfBirth)
    {
        // Implement South African ID number validation logic here
        return true;
    }

    private string GetRoleNameByUserType(int userTypeID)
    {
        // Implement logic to get role name by user type ID
        return "RoleName";
    }
}
Functions are ideal for reusable logic. When a function itself needs to reuse logic, you can declare a nested function to handle that logic. Here is an example of a nested function:

Example Code
const outer = () => {
  const inner = () => {

  };
};

Object properties consist of key/value pairs. You can use shorthand property names when declaring an object literal. When using the shorthand property name syntax, the name of the variable becomes the property key and its value the property value.

The following example declares a user object with the properties userId, firstName, and loggedIn.

Example Code
const userId = 1;
const firstName = "John";
const loggedIn = true;

const user = {
  userId,
  firstName,
  loggedIn,
};

console.log(user); // { userId: 1, firstName: 'John', loggedIn: true }

The concept of returning a function within a function is called currying. This approach allows you to create a variable that holds a function to be called later, but with a reference to the parameters of the outer function call.

For example:

Example Code
const innerOne = elemValue(1);
const final = innerOne("A");
innerOne would be your inner function, with num set to 1, and final would have the value of the cell with the id of A1. This is possible because functions have access to all variables declared at their creation. This is called closure.

In your elemValue function, you explicitly declared a function called inner and returned it. However, because you are using arrow syntax, you can implicitly return a function. For example:

Example Code
const curry = soup => veggies => {};
curry is a function which takes a soup parameter and returns a function which takes a veggies parameter.

You can pass a function reference as a callback parameter. A function reference is a function name without the parentheses. For example:

Example Code
const myFunc = (val) => `value: ${val}`;
const array = [1, 2, 3];
const newArray = array.map(myFunc);
The .map() method here will call the myFunc function, passing the same arguments that a .map() callback takes. The first argument is the value of the array at the current iteration, so newArray would be [value: 1, value: 2, value: 3].

Arrays have a .some() method. Like the .filter() method, .some() accepts a callback function which should take an element of the array as the argument. The .some() method will return true if the callback function returns true for at least one element in the array.

Here is an example of a .some() method call to check if any element in the array is an uppercase letter.

Example Code
const arr = ["A", "b", "C"];
arr.some(letter => letter === letter.toUpperCase());

Arrays have an .every() method. Like the .some() method, .every() accepts a callback function which should take an element of the array as the argument. The .every() method will return true if the callback function returns true for all elements in the array.

Here is an example of a .every() method call to check if all elements in the array are uppercase letters.

Example Code
const arr = ["A", "b", "C"];
arr.every(letter => letter === letter.toUpperCase());
LOOKUP([_Thisrow].[Email],"Employee","Email","Name")

---------------------
  
LOOKUP([_THISROW].[Product ID],"Room DATA","Room ID","Room Photo")

----------

LOOKUP([_Thisrow].[hotel name],"hotel","hotel id","location")

-----------
  
LOOKUP([_Thisrow].[room],"room_type","room id","calendarId")
The .split() method takes a string and splits it into an array of strings. You can pass it a string of characters or a RegEx to use as a separator. For example, string.split(",") would split the string at each comma and return an array of strings.

The .map() method takes a callback function as its first argument. This callback function takes a few arguments, but the first one is the current element being processed. Here is an example:

Example Code
array.map(el => {

})

Much like the .map() method, the .filter() method takes a callback function. The callback function takes the current element as its first argument.

Example Code
array.filter(el => {

})

Array methods can often be chained together to perform multiple operations at once. As an example:

Example Code
array.map().filter();
The .map() method is called on the array, and then the .filter() method is called on the result of the .map() method. This is called method chaining.

The .reduce() method takes an array and applies a callback function to condense the array into a single value.

Like the other methods, .reduce() takes a callback. This callback, however, takes at least two parameters. The first is the accumulator, and the second is the current element in the array. The return value for the callback becomes the value of the accumulator on the next iteration.

Example Code
array.reduce((acc, el) => {

});

The .reduce() method takes a second argument that is used as the initial value of the accumulator. Without a second argument, the .reduce() method uses the first element of the array as the accumulator, which can lead to unexpected results.

To be safe, it's best to set an initial value. Here is an example of setting the initial value to an empty string:

Example Code
array.reduce((acc, el) => acc + el.toLowerCase(), "");

By default, the .sort() method converts the elements of an array into strings, then sorts them alphabetically. This works well for strings, but not so well for numbers. For example, 10 comes before 2 when sorted as strings, but 2 comes before 10 when sorted as numbers.

To fix this, you can pass in a callback function to the .sort() method. This function takes two arguments, which represent the two elements being compared. The function should return a value less than 0 if the first element should come before the second element, a value greater than 0 if the first element should come after the second element, and 0 if the two elements should remain in their current positions.

You previously learned about the global Math object. Math has a .min() method to get the smallest number from a series of numbers, and the .max() method to get the largest number. Here's an example that gets the smallest number from an array:

Example Code
const numbersArr = [2, 3, 1];

console.log(Math.min(...numbersArr));
// Expected output: 1

To calculate a root exponent, such as x−−√n
, you can use an inverted exponent x1/n
. JavaScript has a built-in Math.pow() function that can be used to calculate exponents.

Here is the basic syntax for the Math.pow() function:

Example Code
Math.pow(base, exponent);
Here is an example of how to calculate the square root of 4:

Example Code
const base = 4;
const exponent = 0.5;
// returns 2
Math.pow(base, exponent);
{% if item.product.metafields.custom.message %}
{{ item.product.metafields.custom.message }}
{% endif %}
  
window.pixelmatch = (() => {
  var __getOwnPropNames = Object.getOwnPropertyNames;
  var __commonJS = (cb, mod) => function __require() {
    return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
  };

  // entry.js
  var require_entry = __commonJS({
    "entry.js"(exports, module) {
      module.exports = pixelmatch;
      var defaultOptions = {
        threshold: 0.1,
        // matching threshold (0 to 1); smaller is more sensitive
        includeAA: false,
        // whether to skip anti-aliasing detection
        alpha: 0.1,
        // opacity of original image in diff output
        aaColor: [255, 255, 0],
        // color of anti-aliased pixels in diff output
        diffColor: [255, 0, 0],
        // color of different pixels in diff output
        diffColorAlt: null,
        // whether to detect dark on light differences between img1 and img2 and set an alternative color to differentiate between the two
        diffMask: false
        // draw the diff over a transparent background (a mask)
      };
      function pixelmatch(img1, img2, output, width, height, options) {
        if (!isPixelData(img1) || !isPixelData(img2) || output && !isPixelData(output))
          throw new Error("Image data: Uint8Array, Uint8ClampedArray or Buffer expected.");
        if (img1.length !== img2.length || output && output.length !== img1.length)
          throw new Error("Image sizes do not match.");
        if (img1.length !== width * height * 4) throw new Error("Image data size does not match width/height.");
        options = Object.assign({}, defaultOptions, options);
        const len = width * height;
        const a32 = new Uint32Array(img1.buffer, img1.byteOffset, len);
        const b32 = new Uint32Array(img2.buffer, img2.byteOffset, len);
        let identical = true;
        for (let i = 0; i < len; i++) {
          if (a32[i] !== b32[i]) {
            identical = false;
            break;
          }
        }
        if (identical) {
          if (output && !options.diffMask) {
            for (let i = 0; i < len; i++) drawGrayPixel(img1, 4 * i, options.alpha, output);
          }
          return 0;
        }
        const maxDelta = 35215 * options.threshold * options.threshold;
        let diff = 0;
        for (let y = 0; y < height; y++) {
          for (let x = 0; x < width; x++) {
            const pos = (y * width + x) * 4;
            const delta = colorDelta(img1, img2, pos, pos);
            if (Math.abs(delta) > maxDelta) {
              if (!options.includeAA && (antialiased(img1, x, y, width, height, img2) || antialiased(img2, x, y, width, height, img1))) {
                if (output && !options.diffMask) drawPixel(output, pos, ...options.aaColor);
              } else {
                if (output) {
                  drawPixel(output, pos, ...delta < 0 && options.diffColorAlt || options.diffColor);
                }
                diff++;
              }
            } else if (output) {
              if (!options.diffMask) drawGrayPixel(img1, pos, options.alpha, output);
            }
          }
        }
        return diff;
      }
      function isPixelData(arr) {
        return ArrayBuffer.isView(arr) && arr.constructor.BYTES_PER_ELEMENT === 1;
      }
      function antialiased(img, x1, y1, width, height, img2) {
        const x0 = Math.max(x1 - 1, 0);
        const y0 = Math.max(y1 - 1, 0);
        const x2 = Math.min(x1 + 1, width - 1);
        const y2 = Math.min(y1 + 1, height - 1);
        const pos = (y1 * width + x1) * 4;
        let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
        let min = 0;
        let max = 0;
        let minX, minY, maxX, maxY;
        for (let x = x0; x <= x2; x++) {
          for (let y = y0; y <= y2; y++) {
            if (x === x1 && y === y1) continue;
            const delta = colorDelta(img, img, pos, (y * width + x) * 4, true);
            if (delta === 0) {
              zeroes++;
              if (zeroes > 2) return false;
            } else if (delta < min) {
              min = delta;
              minX = x;
              minY = y;
            } else if (delta > max) {
              max = delta;
              maxX = x;
              maxY = y;
            }
          }
        }
        if (min === 0 || max === 0) return false;
        return hasManySiblings(img, minX, minY, width, height) && hasManySiblings(img2, minX, minY, width, height) || hasManySiblings(img, maxX, maxY, width, height) && hasManySiblings(img2, maxX, maxY, width, height);
      }
      function hasManySiblings(img, x1, y1, width, height) {
        const x0 = Math.max(x1 - 1, 0);
        const y0 = Math.max(y1 - 1, 0);
        const x2 = Math.min(x1 + 1, width - 1);
        const y2 = Math.min(y1 + 1, height - 1);
        const pos = (y1 * width + x1) * 4;
        let zeroes = x1 === x0 || x1 === x2 || y1 === y0 || y1 === y2 ? 1 : 0;
        for (let x = x0; x <= x2; x++) {
          for (let y = y0; y <= y2; y++) {
            if (x === x1 && y === y1) continue;
            const pos2 = (y * width + x) * 4;
            if (img[pos] === img[pos2] && img[pos + 1] === img[pos2 + 1] && img[pos + 2] === img[pos2 + 2] && img[pos + 3] === img[pos2 + 3]) zeroes++;
            if (zeroes > 2) return true;
          }
        }
        return false;
      }
      function colorDelta(img1, img2, k, m, yOnly) {
        let r1 = img1[k + 0];
        let g1 = img1[k + 1];
        let b1 = img1[k + 2];
        let a1 = img1[k + 3];
        let r2 = img2[m + 0];
        let g2 = img2[m + 1];
        let b2 = img2[m + 2];
        let a2 = img2[m + 3];
        if (a1 === a2 && r1 === r2 && g1 === g2 && b1 === b2) return 0;
        if (a1 < 255) {
          a1 /= 255;
          r1 = blend(r1, a1);
          g1 = blend(g1, a1);
          b1 = blend(b1, a1);
        }
        if (a2 < 255) {
          a2 /= 255;
          r2 = blend(r2, a2);
          g2 = blend(g2, a2);
          b2 = blend(b2, a2);
        }
        const y1 = rgb2y(r1, g1, b1);
        const y2 = rgb2y(r2, g2, b2);
        const y = y1 - y2;
        if (yOnly) return y;
        const i = rgb2i(r1, g1, b1) - rgb2i(r2, g2, b2);
        const q = rgb2q(r1, g1, b1) - rgb2q(r2, g2, b2);
        const delta = 0.5053 * y * y + 0.299 * i * i + 0.1957 * q * q;
        return y1 > y2 ? -delta : delta;
      }
      function rgb2y(r, g, b) {
        return r * 0.29889531 + g * 0.58662247 + b * 0.11448223;
      }
      function rgb2i(r, g, b) {
        return r * 0.59597799 - g * 0.2741761 - b * 0.32180189;
      }
      function rgb2q(r, g, b) {
        return r * 0.21147017 - g * 0.52261711 + b * 0.31114694;
      }
      function blend(c, a) {
        return 255 + (c - 255) * a;
      }
      function drawPixel(output, pos, r, g, b) {
        output[pos + 0] = r;
        output[pos + 1] = g;
        output[pos + 2] = b;
        output[pos + 3] = 255;
      }
      function drawGrayPixel(img, i, alpha, output) {
        const r = img[i + 0];
        const g = img[i + 1];
        const b = img[i + 2];
        const val = blend(rgb2y(r, g, b), alpha * img[i + 3] / 255);
        drawPixel(output, i, val, val, val);
      }
    }
  });
  return require_entry();
})();
// ==UserScript==
// @name         spys.one proxy parser
// @namespace    iquaridys:hideme-parser-proxy
// @version      0.1
// @description  parse proxy from site page
// @author       iquaridys
// @match        http://spys.one/*/
// @grant        GM_registerMenuCommand
// ==/UserScript==

(function() {
    'use strict';
    GM_registerMenuCommand('Parse', function() {
        var resultText = "";
        var a = document.getElementsByClassName('spy14');
            for(var i=0;i<a.length;i++){
                if(a[i].innerText.includes(':')){
                    resultText += a[i].innerText+"<br>";
                }
            }
        var win = window.open("about:blank", "proxy", "width=500,height=400");
        win.document.write(resultText);
    });
})();
<?php 
  function my_scripts_method() {
  wp_enqueue_script(
      'custom-script',
      get_stylesheet_directory_uri() . '/js/unused-javascript.js',
      array( 'jquery' )
   );
  }

  add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
?>
{
  "DFIntTaskSchedulerTargetFps": 5588562,
  "FFlagDebugSkyGray": true,
  "FFlagDebugDisplayFPS": false,
  "DFFlagDebugRenderForceTechnologyVoxel": true,
  "DFFlagDebugPauseVoxelizer": true,
  "FFlagNewLightAttenuation": true,
  "FIntRenderShadowIntensity": 0,
  "FFlagDisablePostFx": true,
  "DFFlagTextureQualityOverrideEnabled": true,
  "DFIntTextureQualityOverride": 0,
  "FIntRenderShadowmapBias": 0,
  "FFlagLuaAppSystemBar": false,
  "FIntFontSizePadding": 3,
  "FFlagAdServiceEnabled": false,
  "FIntScrollWheelDeltaAmount": 25,
  "FFlagDebugDisableTelemetryEphemeralCounter": true,
  "FFlagDebugDisableTelemetryEphemeralStat": true,
  "FFlagDebugDisableTelemetryEventIngest": true,
  "FFlagDebugDisableTelemetryPoint": true,
  "FFlagMSRefactor5": false,
  "FFlagDebugDisableTelemetryV2Counter": true,
  "FFlagDebugDisableTelemetryV2Event": true,
  "FFlagDebugDisableTelemetryV2Stat": true,
  "DFIntCSGLevelOfDetailSwitchingDistance": 1
}
cd gatsby-sydney-ecommerce-theme/
npm start or yarn start
git clone https://github.com/netlify-templates/gatsby-ecommerce-theme/
<script type="text/javascript" async>
    ////add Attrs alt to images	
	function addAltAttrs() {
			
    //get the images
    let images = document.querySelectorAll("img"); 
     
    //loop through all images
    for (let i = 0; i < images.length; i++) {
		
       //check if alt missing
       if  ( !images[i].alt || images[i].alt == "" || images[i].alt === "") {
		//add file name to alt
         images[i].alt = images[i].src.match(/.*\/([^/]+)\.([^?]+)/i)[1];
       }
    } 
    // end loop
}
</script>
<!-- in css: -->
<style>
  #p-bar-wrapper {
   	display:none;
   	position: fixed;
   	bottom: 0;
   	right: 0;
   	width: 100vw;
   	height: 8px;
   	background-color:#d1d6d8;
   	z-index: 18;
  }
  #progress-bar {
   	background-color:#295b71;
   	width: 0;
   	height: 8px;
   	transition: .3s;
  }
  #progress-bar span {
   	position: absolute;
   	color: #42616c;
   	top: -18px;
   	font-size: 0.8em;
   	font-weight: 600;
   	margin-right:0;
  }
  #run-bar.right-fix {
   	margin-right: -80px;
  }
  #run-bar.right-fix-2one {
   	margin-right: -77px;
  }
</style>

<!-- in html: -->
<div id="p-bar-wrapper">
    <div id="progress-bar"><span id="run-bar"></span></div>
</div>

<!-- in js: -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js" crossorigin="anonymous"></script>
<script type="text/javascript" async>
    document.addEventListener("DOMContentLoaded", function() {
    	  document.addEventListener("scroll", function() {
    	    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    	    var scrollHeight = document.documentElement.scrollHeight || document.body.scrollHeight;
    		var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
    		var windowWidth = window.innerWidth;
    		var p_bar =	document.getElementById("progress-bar");
    		var scrolled = (scrollTop / (scrollHeight - clientHeight)) * 100;
     
     	//Check if Tablet or smaller than hide all progress bar
    		if( windowWidth < 767 ){
    			return;
    		}
    		else {
    			jQuery("#p-bar-wrapper").css('display','block').show('slow');
    			p_bar.style.width = scrolled + "%";
    			var scrolled_num = parseInt(scrolled, 10);
    			var span_run = document.getElementById("run-bar");
    			jQuery(span_run).text(scrolled_num + '%').css('right',scrolled + '%');
    				if (scrolled == 100){
    					jQuery(span_run).addClass('right-fix-2one').css('color','#21f1af');
    				}
    				else {
    					jQuery(span_run).removeClass('right-fix-2one').css('color','#42616c');
    					if (scrolled > 15){
    						jQuery(span_run).addClass('right-fix');
    					}
    					else {
    						jQuery(span_run).removeClass('right-fix');
    					}
    				}
    			}
    		});
    	});	
</script>
<!-- in css: -->
<style>
	#up-btn {
      position: fixed;
      bottom: 20px;
      right: 20px;
  	  z-index: 15;
	  cursor: pointer;
      transition: all .3s;
  	}
 	img[src$=".svg"]{
		width:48px
    }
</style>

<!-- in html: -->
<div class="btn-hide" data-id="" data-element_type="widget" id="up-btn" data-settings="" alt="scroll to top">
	<img width="40" height="55" src="https://aspx.co.il/wp-content/uploads/2023/04/arrowup.svg" class="" alt="arrowup" /> 
</div>

<!-- in js: -->
<script src="https://code.jquery.com/jquery-3.7.1.min.js" crossorigin="anonymous"></script>
<script type="text/javascript" async>
	jQuery(document).ready(function($){
  
	//Check to see if the window is top if more then 500px from top display button
	$(window).scroll(function(){
		if ($(this).scrollTop() > 500) {
			$('#up-btn').fadeIn(300,'linear').removeClass('btn-hide');
		} else {
			$('#up-btn').fadeOut(200).hide('slow').addClass('btn-hide');
		}
	});

	//Click event to scroll to top
	$('#up-btn').click(function(){
		$('html, body').animate({scrollTop : 0},800);
		$(this).addClass('btn-hide');
			return false;
	});
</script>

Benefits of Developing Pancakeswap clone script?

Introduction:
PancakeSwap is a decenAtralized exchange (DEX) built on the Binance Smart Chain (BSC), It lets people exchange cryptocurrencies, add money to liquidity pools, and earn rewards by farming all while keeping fees low and processing transactions faster than many other blockchain platforms.
Objective:
PancakeSand effective DeFi options. The use of the CAKE token for governance and rewards enhances its attractiveness in the crypto community.wap is a decentralized platform on the Binance Smart Chain for trading tokens, providing liquidity, and participating in yield farming. It is popular among users seeking affordable 

How Does pancakeswap clone script works?
When creating a PancakeSwap clone, the first step is to define what sets your platform apart from PancakeSwap. Next, decide whether to use a pre-made clone script from a trusted provider or build one yourself. Before launching, thoroughly check the smart contracts for any security issues through audits. Test the platform extensively to fix any bugs and ensure everything works smoothly. Once everything is ready, deploy your platform on the Binance Smart Chain.
What is the importance of creating a PancakeSwap clone?
Developing a PancakeSwap clone is crucial because it provides a quick and cost-effective way for developers to enter the DeFi market. By using a clone script, they can take advantage of proven technology and attract users more easily. Moreover, it encourages innovation by allowing developers to add unique features while benefiting from PancakeSwap's established success on the Binance Smart Chain. Overall, cloning PancakeSwap enables faster, cheaper, and more secure development of decentralized exchange platforms, promoting growth and diversity in DeFi.
Features Of Pancakeswap Clone Script:
The PancakeSwap clone has essential features such as an Automated Market Maker (AMM) protocol, which allows token trading without order books, and Liquidity Pools that enable users to earn rewards by providing liquidity. It also supports Yield Farming, where users can stake tokens to earn additional rewards. Furthermore, it includes an NFT Marketplace for buying, selling, and trading non-fungible tokens, as well as a Prediction feature that allows users to forecast cryptocurrency price movements and earn rewards. Additionally, it offers Profit Sharing, distributing a portion of the platform's revenue among token holders.
Advantages of developing PancakeSwap clone:
Using a clone script speeds up DeFi platform deployment, enabling quick responses to capture market opportunities. It is cost-effective, saving money compared to starting from scratch, and offers a customizable framework. Cloning a proven model reduces risks such as security issues and guarantees platform stability. Users trust familiar platforms, making it easier to attract an initial user base."
Conclusion:
"Beleaf Technologies recognizes the value of PancakeSwap clone script development for swiftly entering the DeFi market with a proven, cost-effective solution. By leveraging this approach, they aim to innovate while building on PancakeSwap's established success on the Binance Smart Chain. This strategic move positions Beleaf Technologies to contribute meaningfully to the decentralized finance ecosystem, driving adoption and fostering community trust in their platform with a secure and user-friendly platform that meets the evolving needs of cryptocurrency enthusiasts



star

Mon Jul 08 2024 06:15:35 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 06:14:48 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 06:13:21 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 06:11:29 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 06:06:30 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 06:04:16 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 06:01:30 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 06:00:13 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 05:59:27 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 05:56:37 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 05:52:34 GMT+0000 (Coordinated Universal Time)

@varuntej #java

star

Mon Jul 08 2024 05:41:22 GMT+0000 (Coordinated Universal Time)

@miskat80

star

Mon Jul 08 2024 01:02:50 GMT+0000 (Coordinated Universal Time)

@davidmchale #jsdocs

star

Sun Jul 07 2024 21:49:40 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sun Jul 07 2024 20:45:27 GMT+0000 (Coordinated Universal Time) https://transmissionbt.com/download#unixdistros

@shookthacr3ator

star

Sun Jul 07 2024 16:32:26 GMT+0000 (Coordinated Universal Time) https://bitnami.com/stack/wordpress/helm

@shookthacr3ator

star

Sun Jul 07 2024 15:49:28 GMT+0000 (Coordinated Universal Time) https://kubeapps.dev/

@shookthacr3ator

star

Sun Jul 07 2024 14:53:19 GMT+0000 (Coordinated Universal Time) https://github.com/

@shookthacr3ator

star

Sun Jul 07 2024 12:59:05 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sun Jul 07 2024 11:52:41 GMT+0000 (Coordinated Universal Time)

@roamtravel

star

Sun Jul 07 2024 10:38:28 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Sun Jul 07 2024 09:52:49 GMT+0000 (Coordinated Universal Time)

@NoFox420 #javascript

star

Sun Jul 07 2024 06:08:28 GMT+0000 (Coordinated Universal Time)

@roamtravel

star

Sun Jul 07 2024 00:35:15 GMT+0000 (Coordinated Universal Time)

@caughlan

star

Sat Jul 06 2024 20:33:20 GMT+0000 (Coordinated Universal Time) https://greasyfork.org/en/scripts/498926-pixelmatch-5-3-0/code

@Shook87 #javascript

star

Sat Jul 06 2024 19:41:30 GMT+0000 (Coordinated Universal Time) https://greasyfork.org/en/scripts/391214-spys-one-proxy-parser/code

@Shook87 #javascript

star

Sat Jul 06 2024 19:16:25 GMT+0000 (Coordinated Universal Time)

@ASPX #php #functionphp #add_action

star

Sat Jul 06 2024 19:04:09 GMT+0000 (Coordinated Universal Time)

@enojiro7

star

Sat Jul 06 2024 12:09:24 GMT+0000 (Coordinated Universal Time) https://github.com/shookthacr3ator777/Brandbox-Marketplace

@Shook87

star

Sat Jul 06 2024 12:09:22 GMT+0000 (Coordinated Universal Time) https://github.com/shookthacr3ator777/Brandbox-Marketplace

@Shook87

star

Sat Jul 06 2024 12:09:18 GMT+0000 (Coordinated Universal Time) https://github.com/shookthacr3ator777/Brandbox-Marketplace

@Shook87

star

Sat Jul 06 2024 12:09:09 GMT+0000 (Coordinated Universal Time) undefined

@Shook87

star

Sat Jul 06 2024 10:59:08 GMT+0000 (Coordinated Universal Time) https://aspx.co.il/

@ASPX #javascript #alt #alttoimages #seo

star

Sat Jul 06 2024 10:56:37 GMT+0000 (Coordinated Universal Time) https://aspx.co.il/

@ASPX #html #css #javascript #topbutton #scrollup #upbutton #scrolltotop #jquery

star

Sat Jul 06 2024 10:33:28 GMT+0000 (Coordinated Universal Time) https://aspx.co.il/

@ASPX #html #css #javascript #topbutton #scrollup #upbutton #scrolltotop #jquery

star

Sat Jul 06 2024 09:31:32 GMT+0000 (Coordinated Universal Time) https://www.beleaftechnologies.com/own-blockchain-development-company

@sivaprasadm203 #blockchain #cryptocurrency #defi #web3

star

Sat Jul 06 2024 08:38:11 GMT+0000 (Coordinated Universal Time) https://app.netlify.com/drop

@Shook87

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension