Snippets Collections
package passedfailedgrades;
import java.util.Scanner;
public class PassedFailedGrades {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        int passedCount = 0, failedCount = 0;

        for (int i = 1; i <= 10; i++) {
            System.out.print("Enter grade " + i + ": ");
            int grade = input.nextInt();

            if (grade >= 75) {
                passedCount++;
            } else {
                failedCount++;
            }
        }

        System.out.println("Passed: " + passedCount);
        System.out.println("Failed: " + failedCount);
    }
}
package positivenegativecount;
import java.util.Scanner;
public class PositiveNegativeCount {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
                Scanner input = new Scanner(System.in);
        int positiveCount = 0, negativeCount = 0;

        for (int i = 1; i <= 5; i++) {
            System.out.print("Enter number " + i + ": ");
            int num = input.nextInt();

            if (num > 0) {
                positiveCount++;
            } else if (num < 0) {
                negativeCount++;
            }
        }

        System.out.println("Positive: " + positiveCount);
        System.out.println("Negative: " + negativeCount);
    }
}
        Scanner input = new Scanner(System.in);
        int positiveCount = 0, negativeCount = 0;

        for (int i = 1; i <= 5; i++) {
            System.out.print("Enter number " + i + ": ");
            int num = input.nextInt();

            if (num > 0) {
                positiveCount++;
            } else if (num < 0) {
                negativeCount++;
            }
        }

        System.out.println("Positive: " + positiveCount);
        System.out.println("Negative: " + negativeCount);
    }
}
package sumofsquares;

import java.util.Scanner;
public class SumOfSquares {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = input.nextInt();

        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i * i;
        }

        System.out.println("Sum of squares: " + sum);
    }
}
package rangecounter;

import java.util.Scanner;
public class RangeCounter {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
               Scanner input = new Scanner(System.in);
        int count1 = 0, count2 = 0, count3 = 0, count4 = 0;

        for (int i = 1; i <= 20; i++) {
            System.out.print("Enter number " + i + ": ");
            int num = input.nextInt();

            if (num >= 1 && num <= 50) {
                count1++;
            } else if (num >= 51 && num <= 100) {
                count2++;
            } else if (num >= 101 && num <= 150) {
                count3++;
            } else if (num >= 151 && num <= 200) {
                count4++;
            }
        }

        System.out.println("Number of values in range 1-50: " + count1);
        System.out.println("Number of values in range 51-100: " + count2);
        System.out.println("Number of values in range 101-150: " + count3);
        System.out.println("Number of values in range 151-200: " + count4);
    }
}

package sumsandaverage;
import java.util.Scanner;

public class SumsAndAverage {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
             Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = input.nextInt();

        int sum = 0;
        for (int i = 1; i <= n; i++) {
            System.out.print(i + " ");
            sum += i;
        }

        double average = (double) sum / n;

        System.out.println("\nSum: " + sum);
        System.out.println("Average: " + average);
    }
}
package displaynumbers;

import java.util.Scanner;
public class DisplayNumbers {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
         Scanner input = new Scanner(System.in);
        System.out.print("Enter a number: ");
        int n = input.nextInt();

        // Using a for loop
        for (int i = 1; i <= n; i++) {
            System.out.print(i + " ");
        }

        // Using a while loop
        int i = 1;
        while (i <= n) {
            System.out.print(i + " ");
            i++;
        }

        // Using a do-while loop
        i = 1;
        do {
            System.out.print(i + " ");
            i++;
        } while (i <= n);

        System.out.println();
    }
}
package circlearea;

/**
 *
 * @author Almer
 */
public class CircleArea {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        double pi = Math.PI;
        for (int r = 1; r <= 5; r++) {
            double area = pi * r * r;
            System.out.println("Radius: " + r + ", Area: " + area);
        }
    }
}
package countstoten;

/**
 *
 * @author Almer
 */
public class CountsToTen {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
               for (int i = 1; i <= 10; i++) {
            System.out.println(i);
        }
    }
}
package employeessalary;
import java.util.Scanner;
public class EmployeesSalary {

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

        System.out.print("Enter the employee category (c/p/r): ");
        char category = input.next().charAt(0);

        System.out.print("Enter number of days worked: ");
        int daysWorked = input.nextInt();

        double dailyRate;
        String categoryName;

        switch (category) {
            case 'c':
                dailyRate = 350;
                categoryName = "Contractual";
                break;
            case 'p':
                dailyRate = 400;
                categoryName = "Probationary";
                break;
            case 'r':
                dailyRate = 450;
                categoryName = "Regular";
                break;
            default:
                dailyRate = 0;
                categoryName = "Invalid Input";
        }

        double basicPay = dailyRate * daysWorked;

        System.out.println("Category: " + categoryName);
        System.out.println("Daily Rate: " + dailyRate);
        System.out.println("Basic Pay: " + basicPay);
    }
}
package studentgrade;

import java.util.Scanner;
public class StudentGrade {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
            Scanner input = new Scanner(System.in);

        System.out.print("Enter Prelim Grade: ");
        double prelim = input.nextDouble();

        System.out.print("Enter Midterm Grade: ");
        double midterm = input.nextDouble();

        System.out.print("Enter Final Grade: ");
        double finalGrade = input.nextDouble();

        double subjectGrade = (prelim + midterm + (finalGrade * 2)) / 4;

        String gradeEquivalent;
        if (subjectGrade >= 96) {
            gradeEquivalent = "1.00";
        } else if (subjectGrade >= 94) {
            gradeEquivalent = "1.25";
        } else if (subjectGrade >= 92) {
            gradeEquivalent = "1.50";
        } else if (subjectGrade >= 89) {
            gradeEquivalent = "1.75";
        } else if (subjectGrade >= 87) {
            gradeEquivalent = "2.00";
        } else if (subjectGrade >= 84) {
            gradeEquivalent = "2.25";
        } else if (subjectGrade >= 80) {
            gradeEquivalent = "2.50";
        } else if (subjectGrade >= 78) {
            gradeEquivalent = "2.75";
        } else if (subjectGrade >= 75) {
            gradeEquivalent = "3.00";
        } else {
            gradeEquivalent = "5.00";
        }

        System.out.println("Subject Grade: " + subjectGrade);
        System.out.println("Grade Equivalent: " + gradeEquivalent);
    }
}
package gendergreeting;
import java.util.Scanner;
public class GenderGreeting {

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

        System.out.print("Enter your gender (m/f): ");
        char gender = input.next().charAt(0);

        if (gender == 'm' || gender == 'M') {
            System.out.println("Hello Sir");
        } else if (gender == 'f' || gender == 'F') {
            System.out.println("Hello Madam");
        } else {
            System.out.println("Invalid input");
        }
    }
}
package yearendbonus;

import java.util.Scanner;
public class YearEndBonus {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
         Scanner input = new Scanner(System.in);

        System.out.print("Enter the employee's name: ");
        String name = input.nextLine();

        System.out.print("Enter the employee's monthly salary: ");
        double salary = input.nextDouble();

        double bonus;
        if (salary < 2000) {
            bonus = salary * 0.5;
        } else {
            bonus = 1500;
        }

        System.out.println(name + "'s bonus is: " + bonus);
    }
}
package employeesalary;
import java.util.Scanner;
public class EmployeeSalary {

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

        System.out.print("Enter the number of hours worked: ");
        int hoursWorked = input.nextInt();

        double salary = 0;
        if (hoursWorked <= 40) {
            salary = hoursWorked * 50;
        } else {
            salary = 40 * 50 + (hoursWorked - 40) * 30;
        }

        System.out.println("The salary is: " + salary);
    }
}
  
package gradeincrease;

import java.util.Scanner;
public class GradeIncrease {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);

        System.out.print("Enter the original grade: ");
        double originalGrade = input.nextDouble();

        double newGrade = originalGrade;
        if (originalGrade < 90) {
            newGrade += 5;
        }

        System.out.println("The new grade is: " + newGrade);
    }
}
//Increase the Modal Height

.uiModal flowruntime-flow {
    max-height: 100% !important;
}
 
//Set the Modal Width

.uiModal--medium .modal-container {
    max-width: 400px !important;
}
 

//Hide the Close Button

button.slds-modal__close.closeIcon {
    display: none;
}
 
//Increase the Text Area Fields' Height

textarea {
    min-height: 300px !important;
}
 

//
//Change the Color of Text Area Fields

textarea {
    color: green !important;
    font-weight: 800;
    min-height: 200px !important;
}

//Change the Navigation Bar's Color

.uiModal flowruntime-navigation-bar {
    background-color: lightblue !important;
    border-width: 0 !important;
}

//Add a Background Image

.uiModal flowruntime-flow {
    background-image: url("https://salesforcetime.com/wp-content/uploads/2021/04/sfba3.jpg") !important;
    background-repeat: no-repeat !important;
    background-position: center;
    background-size: cover;
}

.slds-modal__header {
    margin-bottom: 0 !important;
}

//Remove the Borders of the Flow

article.flowRuntimeForFlexipage {
 border: none;
}

//Change the Height of a Data Table

flowruntime-datatable .restrict-scroll {
    max-height: 200px !important;
}
// Previous Way
function getListData(data) {
  const items = [];
  if (!data) return [];
  for (const [index, item] of Object.entries(data)) {
    const name = item.name;
    const category = item.category;
    const web = item.website;

    const obj = {
      name,
      category,
      web,
    };

    items.push(obj);
  }
  return items;
}





// Cleaner Solution - new way

  function getListData(data) {
    if (!data) return [];
    return Object.entries(data).map(([index, item]) => ({
      name: item.name,
      category: item.category,
      web: item.website,
    }));
  }


const getData = getListData(dummyData)
// Author : Khadiza Sultana
#include<iostream>
#include<vector>
using namespace std;
int LinearSearch(vector<int> &vec, int target){
    int i = 0;
    for(int val : vec){
        if(val == target)
           return i;
        i++;
    }
    return -1;
}
int main(){
    vector<int> vec = {1, 2, 5, 8, 5, 7, 8};
    int target = 7;
    cout << LinearSearch(vec, target) << endl;
    return 0;
}
import mongoose from "mongoose";

const userSchema = new mongoose.Schema(
  {},
  { timestamps: true }
);

export const User = mongoose.model("User", userSchema);
const mongoose = require('mongoose');

const userSchema = new mongoose.Schema(
  {
    name: { type: String, required: true },
    email: { type: String, required: true, unique: true },
    password: { type: String, required: true },
    age: { type: Number, min: 18 },
  },
  { timestamps: true } 
);

const User = mongoose.model('User', userSchema);

module.exports = User;
package prisontest;

/**
 *
 * @author Almer
 */
public class Prisontest {
    
        public static void main(String[] args){
        cell cellA1 = new cell("A1", false, 1234);
        prisoner bubba = new prisoner("Bubba", 2.08, 4, cellA1);
        
        bubba.display();
        cellA1.setIsOpen(1111);
        cellA1.setIsOpen(1234);
        cellA1.setIsOpen(1234);
    }
}
package prisontest;

/**
 *
 * @author Almer
 */
public class prisoner {
    
    private String name;
    private double height;
    private int sentence;
    private cell cell;
    
    //Constructor
    public prisoner(String name, double height, int sentence, cell cell){
 	this.name = name;
 	this.height = height;
 	this.sentence = sentence;
        this.cell = cell;
    }
    
    //Methods
    public void think(){
        System.out.println("I'll have my revenge.");
    }
    public void display(){
        System.out.println("Name: " +getName());
        System.out.println("Height: " +getHeight());
        System.out.println("Sentence: " +getSentence());
        System.out.println("Cell: " +getCell().getName());
    }

    public String getName() {
        return name;
    }
    public double getHeight() {
        return height;
    }
    public int getSentence() {
        return sentence;
    }
    public cell getCell() {
        return cell;
    }
    //Setters
    public void setName(String name) {
        this.name = name;
    }
    public void setHeight(double height) {
        this.height = height;
    }
    public void setSentence(int sentence) {
        this.sentence = sentence;
    }
    public void setCell(cell cell) {
        this.cell = cell;
    }
}

package prisontest;


public class cell {
    private String name;
    private boolean isOpen;
    private int securityCode;
    
    public cell(String name, boolean isOpen, int securityCode){
        this.name = name;
        this.isOpen = isOpen;
        this.securityCode = securityCode;
    }
    
    public String getName(){
        return name;
    }
    public boolean getIsOpen(){
        return isOpen;
    }
    
    public void setIsOpen(int code){
        if(code != securityCode){
            System.out.println("Incorrect code");
        }
        else{
            if(isOpen == true){
                isOpen = false;
                System.out.println("Cell " +name +" Closed");
            }
            else{
                isOpen = true;
                System.out.println("Cell " +name +" Open");
            }
        }
    }
}

#include <iostream>
#include <fstream>
#include <string>
#include <memory>

struct Node {
    std::string line;
    int number;
    std::shared_ptr<Node> next;
    
    Node(std::string l = "", int n = 0) : line(l), number(n), next(nullptr) {}
};

void read(std::shared_ptr<Node>& root) {
    std::ifstream reader("read.txt");  // cin
    if (reader.is_open() && !reader.eof()) {
        root = std::make_shared<Node>();
        reader >> root->line >> root->number;  
        auto tmp = root;
        
        while(!reader.eof()) {
            tmp->next = std::make_shared<Node>();
            tmp = tmp->next;
            reader >> tmp->line >> tmp->number;
        }
    }
}

void type(std::shared_ptr<Node> root) {
    auto tmp = root;
    while (tmp) {
        std::cout << tmp->line << " " << tmp->number << std::endl;
        tmp = tmp->next;
    }
}

void remove(std::shared_ptr<Node>& root, int const number) {
    
    // for first root
    if (root->number == number) {
        root = root->next;
        return;
    }

    auto tmp = root;
    while (tmp->next && tmp->next->number != number) {
        tmp = tmp->next;
    }

    if (tmp->next) {
        tmp->next = tmp->next->next;
    } else {
        std::cout << "we didn' find this element" << std::endl;
    }
}

void insert(std::shared_ptr<Node>& root, int pos, const std::string& str, int val) {
    if (pos == 0) {
        std::shared_ptr<Node> new_root = std::make_shared<Node>(str, val);
        new_root->next = root;
        root = new_root;
        return;
    }

    auto tmp = root;
    for (int i = 1; tmp && i < pos; ++i) {
        tmp = tmp->next;
    }

    if (tmp) {
        std::shared_ptr<Node> new_node = std::make_shared<Node>(str, val);
        new_node->next = tmp->next;
        tmp->next = new_node;
    } 
}

int main() {
    std::shared_ptr<Node> root;
    
    read(root);
    
    std::cout << "list:" << std::endl;
    type(root);
    
    insert(root, 0, "New first line", 10);
    std::cout << "\nuse insert to put new element to the first root:" << std::endl;
    type(root);

    insert(root, 2, "newline", 20);
    std::cout << "\njust use void insert:" << std::endl;
    type(root);
    
    remove(root, 10);
    std::cout << "\n delete root with value = 10:" << std::endl;
    type(root);


    return 0;
}
1. Purga la instalación de Docker:
sudo apk del docker

2. Instalar o reinstalar Docker:
sudo apk add docker

3. Solucionar problemas:
Para desmascarar los servicios de Docker:

sudo rc-update add docker default
sudo service docker start

4. Iniciar Docker:

sudo service docker start

5. Probar la instalación de Docker:
sudo docker run hello-world

6. Reiniciar Docker:

sudo service docker restart

7. Parar Docker:
sudo service docker stop

7.1 ver el estado de docker:
sudo service docker status

8. Comprobar el estado de Docker:
sudo service docker status

9. Ver imágenes de Docker:
docker images

10. Agregar usuario al grupo "docker":
Esto te permite ejecutar comandos de Docker sin sudo:
sudo addgroup $USER docker && newgrp docker

Otros Comandos Útiles
Listar contextos de Docker:
docker context ls 

Usar el contexto por defecto:
docker context use default 

Establecer el host de Docker:
export DOCKER_HOST="tcp://0.0.0.0:2375"

Detener todos los recursos pendientes (imágenes, contenedores, volúmenes y redes):
docker system prune

detener un contenedor de docker
docker stop <container_ID>
  
luego de detenerlo ejecuta este para eliminarlo
docker rm <container_ID>

Eliminar contenedores detenidos y todas las imágenes no utilizadas:
docker system prune -a

Eliminar imágenes por nombre (asegúrate de tener permisos adecuados):
sudo docker rmi <image_name>

sudo docker rmi -f <image_name:latest>
  
  Enumerar imágenes pendientes es decir que esten siendo usadas por otro contenedor:
docker images -f dangling=true

Eliminar imágenes pendientes:
docker rmi $(docker images -f "dangling=true" -q)
 Get-Process | Where-Object {$_.ProcessName -like '*ollama*'} | Stop-Process
// Khadiza Sultana
#include<iostream>
#include <climits>
using namespace std;
int sum(int arr[], int size){
    int sum = 0;
    for(int i = 0; i < size; i++){
        sum += arr[i];
    }
    return sum;
}
int product(int arr[], int size){
    int product = 1;
    for(int i = 0; i < size; i++){
        product *= arr[i];
    }
    return product;
}
void swap(int &a, int &b){
    a = a + b;
    b = a - b;
    a = a - b;
}
void uniqueElement(int arr[], int size){
    for(int i = 0; i < size; i++){
        bool isUnique = true;
        for(int j = 0; j < size; j++){
            if(i != j && arr[i] == arr[j]){
                isUnique = false;
                break;
            }
        }
        if(isUnique) cout << arr[i] << " ";
    }
    cout << endl;
} 
void reverseMinAndMax(int arr[], int size){
    int largest = INT_MIN, smallest = INT_MAX, largest_index = -1, smallest_index = -1;
    for(int i = 0; i < size; i++){
        if(arr[i] > largest){
            largest = arr[i];
            largest_index = i;
        }
        if(arr[i] < smallest){
            smallest = arr[i];
            smallest_index = i;
        }
    }
    swap(arr[largest_index], arr[smallest_index]);
    for(int i = 0; i < size; i++){
        cout << arr[i] << " ";
    }
    cout << endl;
}
void intersection(int arr1[], int size1, int arr2[], int size2){
    for(int i = 0; i < size1; i++){
        bool repeated = false;
        for(int j = 0; j < size1; j++){
            if(i != j && arr1[i] == arr1[j]){
               repeated = true;
               break;
            }
        }
        if(repeated) arr1[i] = INT_MAX;
        for(int j = 0; j < size2; j++){
            if(arr1[i] == arr2[j]){
               cout << arr1[i] << " ";
               break;
            }
        }

    }
    cout << endl;
}
int main(){
    int arr1[] = {1, 2, 4, 6, 4, 6, 2, 5, 9};
    int size1 = sizeof(arr1) / sizeof(int);
    int arr2[] = {2, 4, 3, 5, 8, 6, 3};
    int size2 = sizeof(arr2) / sizeof(int);
    cout << "Sum of elements : " << sum(arr1, size1) << endl;
    cout << "Product of elements : " << product(arr1, size1) << endl;
    cout << "The elements of the first array after the maximum element and minimum element are reversed : ";
    reverseMinAndMax(arr1, size1);
    cout << "The unique elements in the first array : ";
    uniqueElement(arr1, size1);
    cout << "The intersecting elements between the first and second array : ";
    intersection(arr1, size1, arr2, size2);
    return 0;
}
document.addEventListener("DOMContentLoaded", function () {
  gsap.registerPlugin(ScrollTrigger);

  const cards = document.querySelectorAll(".stacking-cards .card");
  const cardWidth = cards[0].offsetWidth;
  const gap = 20;
  const totalOffset = (cardWidth + gap) * (cards.length - 1);

  const scrollTrigger = ScrollTrigger.create({
    trigger: ".stacking-cards",
    pin: true,
    start: "top top",
    end: "+=" + totalOffset + "px",
    scrub: true,
    markers: true,
    onUpdate: (self) => {
      const progress = self.progress; // Global progress [0 - 1]

      cards.forEach((card, index) => {
        const cardStart = index / cards.length; // Start point for this card
        const cardEnd = (index + 1) / cards.length; // End point for this card
        const cardProgress = (progress - cardStart) / (cardEnd - cardStart); // Normalize progress for this card

        if (progress >= cardStart && progress < cardEnd) {
          // Active card during its scroll range
          gsap.to(card, {
            x: -(index * (cardWidth + gap)), // Move to active position
            duration: 0.3,
            ease: "power1.out",
          });
          card.classList.add("active");
          card.classList.remove("stacked");
          card.classList.remove("vertical-text");
        } else if (progress >= cardEnd) {
          // Cards before the active one
          gsap.set(card, {
            x: -(index * (cardWidth + gap)), // Stack position
          });
          card.classList.add("stacked");
          card.classList.remove("active");
        } else {
          // Cards after the active one
          gsap.set(card, {
            x: 0, // Keep in starting position until their turn
          });
          card.classList.remove("active", "stacked", "vertical-text");
        }
      });
    },
    onLeave: () => {
      // At the end of the scroll, remove the 'stacked' class from all cards
      cards.forEach((card) => {
        card.classList.remove("stacked");
      });
    },
  });
});
color-mix(in color-space, color1 percentage1, color2 percentage2)
.element {
  color: #3498db; /* Blue text */
  border: 2px solid currentColor; /* Border matches text color */
}
// import React, { useRef, useState, useEffect } from 'react'
// import { HotTable } from '@handsontable/react'
// import 'handsontable/dist/handsontable.full.min.css'
// import Handsontable from 'handsontable'
// import {
//   registerControl,
//   RegisterControlProps,
//   RegisteredControlProperties,
// } from '../hoc/registerControl'
// import { CustomContentRenderer } from './utils/customButtonRenderer'
// import { hyperformulaInstance, sheetId } from './utils/hyperformulaConfig'
// import { reformatDate, reformatCurrency } from './utils/formatters'
// import { SpreadsheetProperties } from '@components/features/FormBuilder/FormBuilderFieldProperties/Spreadsheet/types'
// import { registerAllCellTypes } from 'handsontable/cellTypes'
// import { registerAllPlugins } from 'handsontable/plugins'
// import { useFormBuilderWorksheetGrid } from '../../hooks/useFormBuilderWorksheetGrid'
// import { createSpreadsheetDefaultValue } from '../../FormBuilderFieldProperties/Spreadsheet/constants'
// import { useFormBuilder } from '../../hooks/useFormBuilder'
// import { useFormService } from '../../hooks/useFormService'

// registerAllCellTypes()
// registerAllPlugins()

// type Properties = RegisteredControlProperties &
//   SpreadsheetProperties & {
//     externalVariables?: {
//       [key: string]: {
//         propertyName?: string
//         defaultValue?: number
//       }
//     }
//   }

// const SpreadsheetControl: React.FC<RegisterControlProps<Properties>> = (
//   props
// ) => {
//   const hotTableRef = useRef<any>(null)
//   const containerRef = useRef<HTMLDivElement>(null)

//   const { rows = 1, columns = 1 } = props.properties || {}

//   const DEFAULT_COLUMN_WIDTH = 100
//   const DEFAULT_ROW_HEIGHT = 25

//   const defaultMeta = {
//     data: createSpreadsheetDefaultValue(rows, columns),
//     cellFormats: {} as { [key: string]: 'date' | 'currency' | undefined },
//     mergeCellsConfig: [],
//     formulas: [],
//   }

//   const meta = props.properties?.meta || defaultMeta
//   const { actions: formBuilderWorksheetActions } = useFormBuilderWorksheetGrid()
//   const { actions, data: formBuilderData } = useFormBuilder()
//   const { watch } = useFormService()
//   const formData = watch()

//   if (!actions || !actions.getAllFields) {
//   }

//   const [data, setData] = useState(
//     () => props?.value ?? JSON.parse(JSON.stringify(meta.data))
//   )
//   const [cellFormats, setCellFormats] = useState(meta.cellFormats)
//   const [mergeCellsConfig, setMergeCellsConfig] = useState(
//     meta.mergeCellsConfig
//   )

//   const [formulas, setFormulas] = useState<
//     { row: number; col: number; formula: string }[]
//   >(meta.formulas || [])

//   useEffect(() => {
//     if (props.properties?.meta) {
//       const {
//         data: metaData,
//         formulas: metaFormulas = [],
//         mergeCellsConfig: metaMergeCells,
//       } = props.properties.meta

//       setData(props.value ?? metaData)
//       setFormulas(metaFormulas)
//       setMergeCellsConfig(metaMergeCells)

//       metaFormulas.forEach(({ row, col, formula }) => {
//         try {
//           hyperformulaInstance.setCellContents({ sheet: sheetId, row, col }, [
//             [formula],
//           ])
//         } catch (error) {
//           // Handle error if necessary
//         }
//       })

//       hyperformulaInstance.rebuildAndRecalculate()
//     }
//   }, [props.properties?.meta, props.value])

//   // useEffect(() => {
//   //   if (formBuilderData) {
//   //     const existingExpressions = hyperformulaInstance.listNamedExpressions()

//   //     Object.entries(formBuilderData).forEach(([key, value]) => {
//   //       const numericValue = Number(value) || 0

//   //       if (!existingExpressions.includes(key)) {
//   //         hyperformulaInstance.addNamedExpression(key, numericValue)
//   //       } else {
//   //         hyperformulaInstance.changeNamedExpression(key, numericValue)
//   //       }
//   //     })

//   //     try {
//   //       hyperformulaInstance.rebuildAndRecalculate()

//   //       if (sheetId !== undefined) {
//   //         const recalculatedData = hyperformulaInstance.getSheetValues(sheetId)

//   //         const adjustedData = adjustDataDimensions(
//   //           recalculatedData,
//   //           rows,
//   //           columns
//   //         )
//   //         setData(adjustedData)
//   //         updateFieldProperties({ data: adjustedData })
//   //       }
//   //     } catch (error) {}
//   //   }
//   // }, [formBuilderData])

//   // useEffect(() => {
//   //   if (formBuilderData && Object.keys(formBuilderData).length > 0) {
//   //     const existingExpressions = hyperformulaInstance.listNamedExpressions()

//   //     Object.entries(formBuilderData).forEach(([key, value]) => {
//   //       if (!existingExpressions.includes(`${key}`)) {
//   //         hyperformulaInstance.addNamedExpression(`${key}`, Number(value) || 0)
//   //       } else {
//   //         hyperformulaInstance.changeNamedExpression(
//   //           `${key}`,
//   //           Number(value) || 0
//   //         )
//   //       }
//   //     })

//   //     try {
//   //       hyperformulaInstance.rebuildAndRecalculate()

//   //       if (hotTableRef.current?.hotInstance && typeof sheetId === 'number') {
//   //         const updatedData = hyperformulaInstance.getSheetSerialized(sheetId)
//   //         const adjustedData = adjustDataDimensions(updatedData, rows, columns)

//   //         hotTableRef.current.hotInstance.loadData(adjustedData)
//   //         setData(adjustedData)
//   //       }
//   //     } catch (error) {}
//   //   }
//   // }, [formBuilderData])

//   // useEffect(() => {
//   //   if (formData && Object.keys(formData).length > 0) {
//   //     const existingExpressions = hyperformulaInstance.listNamedExpressions()

//   //     Object.entries(formData).forEach(([key, value]) => {
//   //       if (!existingExpressions.includes(`${key}`)) {
//   //         hyperformulaInstance.addNamedExpression(`${key}`, Number(value) || 0)
//   //       } else {
//   //         hyperformulaInstance.changeNamedExpression(
//   //           `${key}`,
//   //           Number(value) || 0
//   //         )
//   //       }
//   //     })

//   //     try {
//   //       hyperformulaInstance.rebuildAndRecalculate()

//   //       if (hotTableRef.current?.hotInstance && typeof sheetId === 'number') {
//   //         const updatedData = hyperformulaInstance.getSheetSerialized(sheetId)
//   //         const adjustedData = adjustDataDimensions(updatedData, rows, columns)

//   //         hotTableRef.current.hotInstance.loadData(adjustedData)
//   //         setData(adjustedData)
//   //       }
//   //     } catch (error) {}
//   //   }
//   // }, [formData])

//   useEffect(() => {
//     const syncFormBuilderData = (data) => {
//       if (data && Object.keys(data).length > 0) {
//         const existingExpressions = hyperformulaInstance.listNamedExpressions()

//         Object.entries(data).forEach(([key, value]) => {
//           if (!existingExpressions.includes(`${key}`)) {
//             hyperformulaInstance.addNamedExpression(
//               `${key}`,
//               Number(value) || 0
//             )
//           } else {
//             hyperformulaInstance.changeNamedExpression(
//               `${key}`,
//               Number(value) || 0
//             )
//           }
//         })

//         try {
//           hyperformulaInstance.rebuildAndRecalculate()

//           if (hotTableRef.current?.hotInstance && typeof sheetId === 'number') {
//             const updatedData = hyperformulaInstance.getSheetSerialized(sheetId)
//             const adjustedData = adjustDataDimensions(
//               updatedData,
//               rows,
//               columns
//             )

//             hotTableRef.current.hotInstance.loadData(adjustedData)
//             setData(adjustedData)
//           }
//         } catch (error) {
//           console.error('Error syncing form builder data:', error)
//         }
//       }
//     }

//     // Sync formBuilderData
//     syncFormBuilderData(formBuilderData)

//     // Sync formData if applicable
//     syncFormBuilderData(formData)
//   }, [formBuilderData, formData])

//   useEffect(() => {
//     const adjustedData = adjustDataDimensions(data, rows, columns)
//     if (JSON.stringify(data) !== JSON.stringify(adjustedData)) {
//       setData(adjustedData)
//     }
//   }, [rows, columns])

//   const adjustDataDimensions = (
//     currentData: any[][],
//     rows: number,
//     columns: number
//   ) => {
//     const adjustedData = currentData.map((row) => [...row])

//     while (adjustedData.length < rows) {
//       adjustedData.push(Array(columns).fill(null))
//     }
//     adjustedData.length = rows

//     adjustedData.forEach((row) => {
//       while (row.length < columns) {
//         row.push(null)
//       }
//       row.length = columns
//     })

//     return adjustedData
//   }

//   useEffect(() => {
//     if (hotTableRef.current?.hotInstance) {
//       hotTableRef.current.hotInstance.render()
//     }
//   }, [data])

//   const handleAfterChange = (changes: any, source: string) => {
//     if (!changes || source === 'loadData') return

//     const validSheetId = sheetId ?? 0
//     let updatedFormulas = [...formulas] // Copy the current formulas array

//     changes.forEach(([row, col, oldValue, newValue]: any) => {
//       const formulaIndex = updatedFormulas.findIndex(
//         (formula) => formula.row === row && formula.col === col
//       )

//       if (
//         newValue &&
//         typeof newValue === 'string' &&
//         newValue.startsWith('=')
//       ) {
//         if (props.runtime) {
//           // Do not process formulas in runtime mode
//           // The cell value is already set to '#ERROR!' in beforeChange
//         } else {
//           try {
//             if (formulaIndex !== -1) {
//               // Update existing formula
//               updatedFormulas[formulaIndex].formula = newValue
//             } else {
//               // Add new formula
//               updatedFormulas.push({ row, col, formula: newValue })
//             }
//             setFormulas(updatedFormulas)

//             // Set cell contents in HyperFormula
//             hyperformulaInstance.setCellContents(
//               { sheet: validSheetId, row, col },
//               [[newValue]]
//             )
//           } catch (error) {
//             // Handle error if necessary
//           }
//         }
//       } else {
//         if (formulaIndex !== -1) {
//           // Remove formula from formulas array
//           updatedFormulas.splice(formulaIndex, 1)
//           setFormulas(updatedFormulas)
//         }

//         try {
//           // Set cell contents for regular values
//           hyperformulaInstance.setCellContents(
//             { sheet: validSheetId, row, col },
//             [[newValue]]
//           )
//         } catch (error) {
//           // Handle error if necessary
//         }
//       }
//     })

//     try {
//       // Recalculate HyperFormula
//       hyperformulaInstance.rebuildAndRecalculate()

//       // Get updated data from HyperFormula
//       const updatedData = hyperformulaInstance.getSheetSerialized(validSheetId)

//       // Adjust data dimensions if necessary
//       const adjustedData = adjustDataDimensions(updatedData, rows, columns)
//       setData(adjustedData)

//       if (props.onChange) {
//         console.log('onChange triggered with data:', adjustedData)
//         props.onChange(adjustedData)
//       }

//       // Update field properties
//       updateFieldProperties({ data: adjustedData })
//     } catch (error) {
//       // Handle error if necessary
//     }
//   }

//   const handleBeforeChange = (changes: any, source: string) => {
//     if (!changes || source === 'loadData') return

//     changes.forEach(([row, col, oldValue, newValue]: any, index: number) => {
//       if (
//         props.runtime &&
//         newValue &&
//         typeof newValue === 'string' &&
//         newValue.startsWith('=')
//       ) {
//         // Replace formula input with '#ERROR!' in runtime mode
//         changes[index][3] = '#ERROR!'
//       }
//     })
//   }

//   const updateFieldProperties = (updatedMeta: any) => {
//     if (!props.runtime) {
//       formBuilderWorksheetActions?.setFieldConfigProperty(props.config?.id!, {
//         meta: {
//           data,
//           formulas,
//           mergeCellsConfig,
//           ...updatedMeta,
//         },
//       })
//     }
//   }

//   const cellsHandler = (row: any, col: any) => {
//     const cellProperties = {} as Handsontable.CellProperties
//     cellProperties.width = DEFAULT_COLUMN_WIDTH
//     cellProperties.height = DEFAULT_ROW_HEIGHT

//     // Determine if the cell is a formula cell
//     const isFormulaCell = formulas.some(
//       (formula) => formula.row === row && formula.col === col
//     )

//     // In runtime mode, prevent editing formula cells
//     if (props.runtime && isFormulaCell) {
//       cellProperties.readOnly = true
//     } else {
//       cellProperties.readOnly = false
//     }

//     cellProperties.renderer = function (
//       instance,
//       td,
//       row,
//       col,
//       prop,
//       value,
//       cellProperties
//     ) {
//       td.style.border = ''
//       td.style.color = ''
//       td.style.backgroundColor = ''

//       let cellValue = instance.getDataAtCell(row, col)

//       if (
//         typeof cellValue === 'string' &&
//         (cellValue.startsWith('#ERROR!') ||
//           cellValue.startsWith('#NAME?') ||
//           cellValue.startsWith('#DIV/0'))
//       ) {
//         td.style.border = '1px solid red'
//         td.style.color = 'red'
//       }

//       Handsontable.renderers.TextRenderer.call(
//         this,
//         instance,
//         td,
//         row,
//         col,
//         prop,
//         value,
//         cellProperties
//       )
//     }

//     return cellProperties
//   }

//   const handleMergeCells = () => {
//     const hotInstance = hotTableRef.current?.hotInstance
//     const selected = hotInstance?.getSelected()
//     if (selected) {
//       const [startRow, startCol, endRow, endCol] = selected[0]
//       const newMerge = {
//         row: startRow,
//         col: startCol,
//         rowspan: endRow - startRow + 1,
//         colspan: endCol - startCol + 1,
//       }

//       const updatedMergeCellsConfig = [...mergeCellsConfig, newMerge]
//       hotInstance.updateSettings({ mergeCells: updatedMergeCellsConfig })
//       setMergeCellsConfig(updatedMergeCellsConfig)

//       updateFieldProperties({
//         data,
//         cellFormats,
//         mergeCellsConfig: updatedMergeCellsConfig,
//       })
//     }
//   }

//   const handleUnmergeCells = () => {
//     const hotInstance = hotTableRef.current?.hotInstance
//     const selected = hotInstance?.getSelected()
//     if (selected) {
//       const [startRow, startCol] = selected[0]
//       const mergeCellsPlugin = hotInstance.getPlugin('mergeCells')
//       mergeCellsPlugin.unmerge(startRow, startCol)

//       const updatedMergeCellsConfig = mergeCellsConfig.filter(
//         (cell) => cell.row !== startRow || cell.col !== startCol
//       )
//       hotInstance.updateSettings({ mergeCells: updatedMergeCellsConfig })
//       setMergeCellsConfig(updatedMergeCellsConfig)

//       updateFieldProperties({
//         data,
//         cellFormats,
//         mergeCellsConfig: updatedMergeCellsConfig,
//       })
//     }
//   }

//   const handleSetAsDate = () => {
//     const selected = hotTableRef.current?.hotInstance.getSelected()
//     if (selected) {
//       const [row, col] = selected[0]
//       const newFormats = { ...cellFormats, [`${row}-${col}`]: 'date' as const }
//       setCellFormats(newFormats)
//       updateFieldProperties({ data, cellFormats: newFormats, mergeCellsConfig })
//     }
//   }

//   const handleSetAsCurrency = () => {
//     const selected = hotTableRef.current?.hotInstance.getSelected()
//     if (selected) {
//       const [row, col] = selected[0]
//       const newFormats = {
//         ...cellFormats,
//         [`${row}-${col}`]: 'currency' as const,
//       }
//       setCellFormats(newFormats)
//       updateFieldProperties({ data, cellFormats: newFormats, mergeCellsConfig })
//     }
//   }

//   return (
//     <div
//       ref={containerRef}
//       className="h-[400px] w-1/2 resize-x overflow-auto border md:w-full"
//       style={{ minWidth: '50%', maxWidth: '100%', resize: 'horizontal' }}
//       onMouseDown={(e) => e.stopPropagation()}
//     >
//       <HotTable
//         id="mySpreadsheet"
//         data={data}
//         colHeaders={true}
//         rowHeaders={true}
//         width="100%"
//         height="100%"
//         selectionMode="multiple"
//         copyPaste={true}
//         contextMenu={{
//           items: {
//             row_above: {},
//             row_below: {},
//             col_left: {},
//             col_right: {},
//             remove_row: {},
//             remove_col: {},
//             clear_column: {},
//             mergeCells: { name: 'Merge Cells', callback: handleMergeCells },
//             unmergeCells: {
//               name: 'Unmerge Cells',
//               callback: handleUnmergeCells,
//             },
//             set_as_date: { name: 'Set as Date', callback: handleSetAsDate },
//             set_as_currency: {
//               name: 'Set as Currency',
//               callback: handleSetAsCurrency,
//             },
//           },
//         }}
//         ref={hotTableRef}
//         afterChange={handleAfterChange}
//         beforeChange={handleBeforeChange}
//         persistentState={true}
//         licenseKey="non-commercial-and-evaluation"
//         manualColumnResize={false}
//         manualRowResize={false}
//         autoColumnSize={false}
//         autoRowSize={false}
//         stretchH="all"
//         mergeCells={mergeCellsConfig}
//         formulas={{ engine: hyperformulaInstance }}
//         cells={cellsHandler}
//         colWidths={DEFAULT_COLUMN_WIDTH}
//         rowHeights={DEFAULT_ROW_HEIGHT}
//       />
//     </div>
//   )
// }

// export default registerControl<Properties>(SpreadsheetControl, {
//   noDisplayLabel: true,
// })

import React, { useRef, useState, useEffect } from 'react'
import { HotTable } from '@handsontable/react'
import 'handsontable/dist/handsontable.full.min.css'
import Handsontable from 'handsontable'
import {
  registerControl,
  RegisterControlProps,
  RegisteredControlProperties,
} from '../hoc/registerControl'
import { hyperformulaInstance, sheetId } from './utils/hyperformulaConfig'
import { createSpreadsheetDefaultValue } from '../../FormBuilderFieldProperties/Spreadsheet/constants'
import { SpreadsheetProperties } from '@components/features/FormBuilder/FormBuilderFieldProperties/Spreadsheet/types'
import { registerAllCellTypes } from 'handsontable/cellTypes'
import { registerAllPlugins } from 'handsontable/plugins'
import { useFormBuilderWorksheetGrid } from '../../hooks/useFormBuilderWorksheetGrid'
import { useFormBuilder } from '../../hooks/useFormBuilder'
import { useFormService } from '../../hooks/useFormService'

registerAllCellTypes()
registerAllPlugins()

type Properties = RegisteredControlProperties &
  SpreadsheetProperties & {
    externalVariables?: {
      [key: string]: {
        propertyName?: string
        defaultValue?: number
      }
    }
  }

const SpreadsheetControl: React.FC<RegisterControlProps<Properties>> = (
  props
) => {
  const hotTableRef = useRef<any>(null)
  const containerRef = useRef<HTMLDivElement>(null)

  const { rows = 1, columns = 1 } = props.properties || {}

  const DEFAULT_COLUMN_WIDTH = 100
  const DEFAULT_ROW_HEIGHT = 25

  const defaultMeta = {
    data: createSpreadsheetDefaultValue(rows, columns),
    cellFormats: {} as { [key: string]: 'date' | 'currency' | undefined },
    mergeCellsConfig: [],
    formulas: [],
  }

  const meta = props.properties?.meta || defaultMeta
  const { actions: formBuilderWorksheetActions } = useFormBuilderWorksheetGrid()
  const { actions, data: formBuilderData } = useFormBuilder()
  const { watch } = useFormService()
  const formData = watch()

  const [data, setData] = useState(
    () => props?.value ?? JSON.parse(JSON.stringify(meta.data))
  )
  const [cellFormats, setCellFormats] = useState(meta.cellFormats)
  const [mergeCellsConfig, setMergeCellsConfig] = useState(
    meta.mergeCellsConfig
  )
  const [formulas, setFormulas] = useState<
    { row: number; col: number; formula: string }[]
  >(meta.formulas || [])

  useEffect(() => {
    if (props.properties?.meta) {
      const {
        data: metaData,
        formulas: metaFormulas = [],
        mergeCellsConfig: metaMergeCells,
      } = props.properties.meta

      const initialData = props.value ?? metaData
      const isDataDifferent =
        JSON.stringify(initialData) !== JSON.stringify(data)
      const isFormulasDifferent =
        JSON.stringify(metaFormulas) !== JSON.stringify(formulas)
      const isMergeDifferent =
        JSON.stringify(metaMergeCells) !== JSON.stringify(mergeCellsConfig)

      if (isDataDifferent || isFormulasDifferent || isMergeDifferent) {
        setData(initialData)
        setFormulas(metaFormulas)
        setMergeCellsConfig(metaMergeCells)
      }

      metaFormulas.forEach(({ row, col, formula }) => {
        try {
          hyperformulaInstance.setCellContents({ sheet: sheetId, row, col }, [
            [formula],
          ])
        } catch (error) {
          // Handle error if necessary
        }
      })

      hyperformulaInstance.rebuildAndRecalculate()
    }
  }, [props.properties?.meta, props.value]) // Only re-run if meta or value changes

  useEffect(() => {
    const syncFormBuilderData = (sourceData: any) => {
      if (sourceData && Object.keys(sourceData).length > 0) {
        const existingExpressions = hyperformulaInstance.listNamedExpressions()

        Object.entries(sourceData).forEach(([key, value]) => {
          if (!existingExpressions.includes(key)) {
            hyperformulaInstance.addNamedExpression(
              `${key}`,
              Number(value) || 0
            )
          } else {
            hyperformulaInstance.changeNamedExpression(
              `${key}`,
              Number(value) || 0
            )
          }
        })

        try {
          hyperformulaInstance.rebuildAndRecalculate()

          if (hotTableRef.current?.hotInstance && typeof sheetId === 'number') {
            const updatedData = hyperformulaInstance.getSheetSerialized(sheetId)
            const adjustedData = adjustDataDimensions(
              updatedData,
              rows,
              columns
            )

            // Only update if data actually changed
            if (JSON.stringify(adjustedData) !== JSON.stringify(data)) {
              hotTableRef.current.hotInstance.loadData(adjustedData)
              setData(adjustedData)
            }
          }
        } catch (error) {
          console.error('Error syncing form builder data:', error)
        }
      }
    }

    syncFormBuilderData(formBuilderData)
    syncFormBuilderData(formData)
  }, [formBuilderData, formData, data, rows, columns])

  useEffect(() => {
    const adjustedData = adjustDataDimensions(data, rows, columns)
    if (JSON.stringify(data) !== JSON.stringify(adjustedData)) {
      setData(adjustedData)
    }
  }, [rows, columns, data])

  const adjustDataDimensions = (
    currentData: any[][],
    rows: number,
    columns: number
  ) => {
    const adjustedData = currentData.map((row) => [...row])

    while (adjustedData.length < rows) {
      adjustedData.push(Array(columns).fill(null))
    }
    adjustedData.length = rows

    adjustedData.forEach((row) => {
      while (row.length < columns) {
        row.push(null)
      }
      row.length = columns
    })

    return adjustedData
  }

  useEffect(() => {
    if (hotTableRef.current?.hotInstance) {
      hotTableRef.current.hotInstance.render()
    }
  }, [data])

  const handleAfterChange = (changes: any, source: string) => {
    if (!changes || source === 'loadData') return

    const validSheetId = sheetId ?? 0
    let updatedFormulas = [...formulas]

    changes.forEach(([row, col, oldValue, newValue]: any) => {
      const formulaIndex = updatedFormulas.findIndex(
        (formula) => formula.row === row && formula.col === col
      )

      if (
        newValue &&
        typeof newValue === 'string' &&
        newValue.startsWith('=')
      ) {
        if (props.runtime) {
          // Runtime mode - do not process formulas
        } else {
          try {
            if (formulaIndex !== -1) {
              updatedFormulas[formulaIndex].formula = newValue
            } else {
              updatedFormulas.push({ row, col, formula: newValue })
            }
            setFormulas(updatedFormulas)
            hyperformulaInstance.setCellContents(
              { sheet: validSheetId, row, col },
              [[newValue]]
            )
          } catch (error) {}
        }
      } else {
        // Not a formula cell
        if (formulaIndex !== -1) {
          updatedFormulas.splice(formulaIndex, 1)
          setFormulas(updatedFormulas)
        }

        try {
          hyperformulaInstance.setCellContents(
            { sheet: validSheetId, row, col },
            [[newValue]]
          )
        } catch (error) {}
      }
    })

    try {
      hyperformulaInstance.rebuildAndRecalculate()
      const updatedData = hyperformulaInstance.getSheetSerialized(validSheetId)
      const adjustedData = adjustDataDimensions(updatedData, rows, columns)

      if (JSON.stringify(adjustedData) !== JSON.stringify(data)) {
        setData(adjustedData)
        if (props.onChange) {
          props.onChange(adjustedData)
        }
        updateFieldProperties({ data: adjustedData })
      }
    } catch (error) {}
  }

  const handleBeforeChange = (changes: any, source: string) => {
    if (!changes || source === 'loadData') return

    changes.forEach(([row, col, oldValue, newValue]: any, index: number) => {
      if (
        props.runtime &&
        newValue &&
        typeof newValue === 'string' &&
        newValue.startsWith('=')
      ) {
        changes[index][3] = '#ERROR!'
      }
    })
  }

  const updateFieldProperties = (updatedMeta: any) => {
    if (!props.runtime) {
      // Check if the updated meta actually differs
      const newMeta = {
        meta: {
          data,
          formulas,
          mergeCellsConfig,
          ...updatedMeta,
        },
      }

      // Only update if something changed
      if (
        JSON.stringify(props.properties?.meta?.data) !==
          JSON.stringify(newMeta.meta.data) ||
        JSON.stringify(props.properties?.meta?.formulas) !==
          JSON.stringify(newMeta.meta.formulas) ||
        JSON.stringify(props.properties?.meta?.mergeCellsConfig) !==
          JSON.stringify(newMeta.meta.mergeCellsConfig)
      ) {
        formBuilderWorksheetActions?.setFieldConfigProperty(
          props.config?.id!,
          newMeta
        )
      }
    }
  }

  const cellsHandler = (row: any, col: any) => {
    const cellProperties = {} as Handsontable.CellProperties
    cellProperties.width = DEFAULT_COLUMN_WIDTH
    cellProperties.height = DEFAULT_ROW_HEIGHT

    const isFormulaCell = formulas.some(
      (formula) => formula.row === row && formula.col === col
    )

    cellProperties.readOnly = props.runtime && isFormulaCell

    cellProperties.renderer = function (
      instance,
      td,
      row,
      col,
      prop,
      value,
      cellProperties
    ) {
      td.style.border = ''
      td.style.color = ''
      td.style.backgroundColor = ''

      let cellValue = instance.getDataAtCell(row, col)
      if (
        typeof cellValue === 'string' &&
        (cellValue.startsWith('#ERROR!') ||
          cellValue.startsWith('#NAME?') ||
          cellValue.startsWith('#DIV/0'))
      ) {
        td.style.border = '1px solid red'
        td.style.color = 'red'
      }

      Handsontable.renderers.TextRenderer.call(
        this,
        instance,
        td,
        row,
        col,
        prop,
        value,
        cellProperties
      )
    }

    return cellProperties
  }

  const handleMergeCells = () => {
    const hotInstance = hotTableRef.current?.hotInstance
    const selected = hotInstance?.getSelected()
    if (selected) {
      const [startRow, startCol, endRow, endCol] = selected[0]
      const newMerge = {
        row: startRow,
        col: startCol,
        rowspan: endRow - startRow + 1,
        colspan: endCol - startCol + 1,
      }

      const updatedMergeCellsConfig = [...mergeCellsConfig, newMerge]
      hotInstance.updateSettings({ mergeCells: updatedMergeCellsConfig })
      setMergeCellsConfig(updatedMergeCellsConfig)

      updateFieldProperties({
        data,
        cellFormats,
        mergeCellsConfig: updatedMergeCellsConfig,
      })
    }
  }

  const handleUnmergeCells = () => {
    const hotInstance = hotTableRef.current?.hotInstance
    const selected = hotInstance?.getSelected()
    if (selected) {
      const [startRow, startCol] = selected[0]
      const mergeCellsPlugin = hotInstance.getPlugin('mergeCells')
      mergeCellsPlugin.unmerge(startRow, startCol)

      const updatedMergeCellsConfig = mergeCellsConfig.filter(
        (cell) => cell.row !== startRow || cell.col !== startCol
      )
      hotInstance.updateSettings({ mergeCells: updatedMergeCellsConfig })
      setMergeCellsConfig(updatedMergeCellsConfig)

      updateFieldProperties({
        data,
        cellFormats,
        mergeCellsConfig: updatedMergeCellsConfig,
      })
    }
  }

  const handleSetAsDate = () => {
    const selected = hotTableRef.current?.hotInstance.getSelected()
    if (selected) {
      const [row, col] = selected[0]
      const newFormats = { ...cellFormats, [`${row}-${col}`]: 'date' as const }
      setCellFormats(newFormats)
      updateFieldProperties({ data, cellFormats: newFormats, mergeCellsConfig })
    }
  }

  const handleSetAsCurrency = () => {
    const selected = hotTableRef.current?.hotInstance.getSelected()
    if (selected) {
      const [row, col] = selected[0]
      const newFormats = {
        ...cellFormats,
        [`${row}-${col}`]: 'currency' as const,
      }
      setCellFormats(newFormats)
      updateFieldProperties({ data, cellFormats: newFormats, mergeCellsConfig })
    }
  }

  return (
    <div
      ref={containerRef}
      className="h-[400px] w-1/2 resize-x overflow-auto border md:w-full"
      style={{ minWidth: '50%', maxWidth: '100%', resize: 'horizontal' }}
      onMouseDown={(e) => e.stopPropagation()}
    >
      <HotTable
        id="mySpreadsheet"
        data={data}
        colHeaders={true}
        rowHeaders={true}
        width="100%"
        height="100%"
        selectionMode="multiple"
        copyPaste={true}
        contextMenu={{
          items: {
            row_above: {},
            row_below: {},
            col_left: {},
            col_right: {},
            remove_row: {},
            remove_col: {},
            clear_column: {},
            mergeCells: { name: 'Merge Cells', callback: handleMergeCells },
            unmergeCells: {
              name: 'Unmerge Cells',
              callback: handleUnmergeCells,
            },
            set_as_date: { name: 'Set as Date', callback: handleSetAsDate },
            set_as_currency: {
              name: 'Set as Currency',
              callback: handleSetAsCurrency,
            },
          },
        }}
        ref={hotTableRef}
        afterChange={handleAfterChange}
        beforeChange={handleBeforeChange}
        persistentState={true}
        licenseKey="non-commercial-and-evaluation"
        manualColumnResize={false}
        manualRowResize={false}
        autoColumnSize={false}
        autoRowSize={false}
        stretchH="all"
        mergeCells={mergeCellsConfig}
        formulas={{ engine: hyperformulaInstance }}
        cells={cellsHandler}
        colWidths={DEFAULT_COLUMN_WIDTH}
        rowHeights={DEFAULT_ROW_HEIGHT}
      />
    </div>
  )
}

export default registerControl<Properties>(SpreadsheetControl, {
  noDisplayLabel: true,
})
add_filter( 'woocommerce_loop_add_to_cart_link', 'custom_add_to_cart_button_text_archives', 10, 2 );

function custom_add_to_cart_button_text_archives( $link, $product ) {
    if ( $product->is_type( 'variable' ) ) {
        // Zmiana tekstu przycisku dla produktów zmiennych
        $link = str_replace( 'ADD TO CART', 'SELECT', $link );
    }
    return $link;
}
<?php
class Elementor_Sliderreview extends \Elementor\Widget_Base {

	public function get_name() {
		return 'smo_sliderreview';
	}

	public function get_title() {
		return esc_html__( 'Smo Slider review', 'elementor-addon' );
	}

	public function get_icon() {
		return 'eicon-featured-image';
	}

	public function get_categories() {
		return [ 'basic' ];
	}

	public function get_keywords() {
		return [ 'Sliderreview' ];
	}
	protected function register_controls() {
	
		$this->start_controls_section(
			'content_section',
			[
				'label' => esc_html__( 'Content', 'smo' ),
				'tab' => \Elementor\Controls_Manager::TAB_CONTENT,
			]
		);

		$this->add_control(
			'list',
			[
				'label' => esc_html__( 'Repeater List', 'smo' ),
				'type' => \Elementor\Controls_Manager::REPEATER,
				'fields' => [
                    [
						'name' => 'quantity_star',
						'label' => esc_html__( 'Quantity Star (max 5)', 'smo' ),
						'type' => \Elementor\Controls_Manager::NUMBER,
                        'min' => 1,
                        'max' => 5,
                        'step' => 1,
                        'default' => 5,
						'label_block' => true,
					],
                    [
						'name' => 'reviews_desc',
						'label' => esc_html__( 'Description reviews', 'smo' ),
						'type' => \Elementor\Controls_Manager::TEXTAREA,
                        'rows' => 10,
                        'default' => esc_html__( 'Default description', 'smo' ),
                        'placeholder' => esc_html__( 'Type your description here', 'smo' ),
						'label_block' => true,
					],
					[
						'name' => 'image_slider',
						'label' => esc_html__( 'Image Slider', 'smo' ),
						'type' => \Elementor\Controls_Manager::MEDIA,
						'default' => [
							'width' => '',
							'height' => '',
						],
						'label_block' => true,
					],
                    [
						'name' => 'list_name',
						'label' => esc_html__( 'Name', 'smo' ),
						'type' => \Elementor\Controls_Manager::TEXT,
                        'default' => esc_html__( 'Default title', 'smo' ),
                        'placeholder' => esc_html__( 'Type your title here', 'smo' ),
						'label_block' => true,
					],
                ],
				'default' => [
				],
			]
		);
	
		
		$this->end_controls_section();

		// Content Tab End


	}

	protected function render() {
		$settings = $this->get_settings_for_display();
		if ( is_array($settings['list']) && !empty($settings['list']) ) {
		?>
		<div class="slider-review">
            <?php
            foreach (  $settings['list'] as $item ) {
            ?>
            <div class="detail-revews">
                <a href="<?php echo esc_url($item['list_link']['url']); ?>"></a>
                <div class="start">
                    <?php
                    for ($i = 0; $i < $item['quantity_star']; $i++) {
                        echo '<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                        <path d="M8 0L10.3511 4.76393L15.6085 5.52786L11.8042 9.23607L12.7023 14.4721L8 12L3.29772 14.4721L4.19577 9.23607L0.391548 5.52786L5.64886 4.76393L8 0Z" fill="#D4AE75"/>
                        </svg>
                        ';
                    }
                    ?>
                </div>
                <p class="review-desc"><?php echo $item['reviews_desc']; ?></p>
<!--                 <h4><a href="<?php echo esc_url($item['list_link']['url']); ?>"></a></h4> -->
                <span><img src="<?php echo $item['image_slider']['url'] ?>" alt=""/><?php echo $item['list_name']; ?>
                </span>
            </div>
            <?php
            }
            ?>
        </div>
		<?php
		}
	}
}
const [inputs, setInputs] = useState({});

const handleChange = (event) => {
  const name = event.target.name;
  const value = event.target.value;
  setInputs(values => ({...values, [name]: value}))
}
import os
import cv2
import numpy as np
import prediction_utils  # Zależności od twojej struktury projektu

# Funkcja przetwarzająca obrazy i maski
def process_images_and_masks(images_directory: str, masks_directory: str, output_directory: str):
    """
    Przetwarza obrazy i maski przez kolejne funkcje, zapisując wyniki do plików
    oraz wyświetlając tylko kąty.
    """
    os.makedirs(output_directory, exist_ok=True)
    images_output_dir = os.path.join(output_directory, 'images')
    masks_output_dir = os.path.join(output_directory, 'masks')
    masks_with_lines_output_dir = os.path.join(output_directory, 'masks_with_lines')

    os.makedirs(images_output_dir, exist_ok=True)
    os.makedirs(masks_output_dir, exist_ok=True)
    os.makedirs(masks_with_lines_output_dir, exist_ok=True)
    images = [cv2.imread(os.path.join(images_directory, f)) for f in os.listdir(images_directory) if f.endswith('.png')]
    masks = [cv2.imread(os.path.join(masks_directory, f), 0) for f in os.listdir(masks_directory) if f.endswith('.png')]

    images = images[700:800]
    masks = masks[700:800]

    data = {
        "images": images,
        "masks": masks
    }

    print(f"Initial number of images: {len(data['images'])}")
    print(f"Initial number of masks: {len(data['masks'])}")

    print("1. Przepuszczanie danych przez `choose_frame_1`...")
    data = prediction_utils.choose_frame_1(data)
    print(f"After `choose_frame_1`, remaining images: {len(data['images'])}")
    print(f"After `choose_frame_1`, remaining masks: {len(data['masks'])}")

    print("2. Wyznaczanie punktów i bazowych linii...")
    data = prediction_utils.calculate_points_and_baseline_8class(data)
    print(f"After `calculate_points_and_baseline`, remaining images: {len(data['images'])}")
    print(f"After `calculate_points_and_baseline`, remaining masks: {len(data['masks'])}")

    print("3. Przepuszczanie danych przez `choose_frame_2`...")
    data = prediction_utils.choose_frame_2(data)
    print(f"After `choose_frame_2`, remaining images: {len(data['images'])}")
    print(f"After `choose_frame_2`, remaining masks: {len(data['masks'])}")

    print("4. Obliczanie kąta alpha...")
    try:
        result = prediction_utils.identify_alpha_beta_angle_new(data)

        print("Wynik z `identify_alpha_beta_angle_new`:")
        print(result)

        image_filename = "image_with_max_angle.png"
        image_path = os.path.join(images_output_dir, image_filename)
        cv2.imwrite(image_path, result["image"])

        mask_filename = "mask_with_max_angle.png"
        mask_path = os.path.join(masks_output_dir, mask_filename)
        cv2.imwrite(mask_path, result["mask"])

        mask_with_lines_filename = "mask_with_lines.png"
        mask_with_lines_path = os.path.join(masks_with_lines_output_dir, mask_with_lines_filename)
        cv2.imwrite(mask_with_lines_path, result["angle_lines_mask"])

    except ValueError as e:
        print(f"Błąd: {e}")

images_directory = './app/angle_utils_5class/images'
masks_directory = './app/angle_utils_5class/masks'
output_directory = './app/angle_utils_5class/output'

process_images_and_masks(images_directory, masks_directory, output_directory)
<ul class="menu-hover-fill flex flex-col items-start leading-none text-xl uppercase space-y-">
2
  <li><a href="#" data-text="home">home</a></li>

  <li><a href="#" data-text="archives">archives</a></li>
4
  <li><a href="#" data-text="tags">tags</a></li>

  <li><a href="#" data-text="categories">categories</a></li>

  <li><a href="#" data-text="about">about</a></li>

</ul>
body {

  display: flex;

  justify-content: center;

  align-items: center;

  min-height: 0vh;

  background: black;

}

​

:root {
10
  --grey-color: #7f8c8d;

}

​

ul {

  padding: 0;

  margin: 0;

  list-style-type: none;

}

​

a {

  text-decoration: none;

}

​

$menu-link-active-colors: var(--primary-color), var(--info-color),

  var(--success-color), var(--warning-color), var(--danger-color);
<style>
  .copy-btn {
      font-weight: normal; /* פונט רגיל עבור הכפתור */
      display: inline-flex;
      align-items: center;
  }
  .elementor-button-content-wrapper p {
      margin: 0;
  }
  .copy-prefix, .success-message {
      color: #0A2556; /* צבע הטקסט של ההעתקה וההודעה */
      margin-right: 5px; /* רווח של 5 פיקסל */
      margin-left: 5px;
      font-weight: normal; /* פונט רגיל */
  }
</style>

<script>
  document.addEventListener("DOMContentLoaded", function() {
    var buttons = document.querySelectorAll(".copy-btn");
    var userLang = document.documentElement.lang || 'en';

    buttons.forEach(function(button) {
      // קביעת הטקסט לפי השפה
      var prefixText = '';
      if (userLang.startsWith("he")) {
        prefixText = "לחץ להעתקה ";
      } else if (userLang.startsWith("en")) {
        prefixText = "Click to copy&nbsp;";
      } else if (userLang.startsWith("de")) {
        prefixText = "Klicken zum Kopieren&nbsp;";
      } else {
        prefixText = "Click to copy&nbsp;";
      }

      // הוספת הטקסט לתחילת הכפתור
      button.innerHTML = `<span class="copy-prefix">${prefixText}</span> ` + button.innerHTML;

      // שמירת העיצוב המקורי של הכפתור
      var originalHTML = button.innerHTML;

      // מאזין ללחיצה
      button.addEventListener("click", function() {
        copyButtonText(button, prefixText, originalHTML);
      });
    });
  });

  function copyButtonText(button, prefixText, originalHTML) {
    // לוקחים את הקופון מהכפתור
    var couponElement = button.querySelector('.elementor-button-text');
    var couponCode = couponElement ? couponElement.innerText.trim() : ''; // לוקח את הטקסט של הקופון

    // יצירת שדה קלט זמני להעתקה
    var tempInput = document.createElement("input");
    tempInput.value = couponCode; // שמירת הקוד של הקופון בלבד
    document.body.appendChild(tempInput);

    tempInput.select();
    document.execCommand("copy");
    document.body.removeChild(tempInput);

    // הצגת הודעת העתקה
    var userLang = document.documentElement.lang || 'en';
    var successMessage = "";
    if (userLang.startsWith("he")) {
      successMessage = "הועתק ללוח!";
    } else if (userLang.startsWith("en")) {
      successMessage = "Copied to clipboard!";
    } else if (userLang.startsWith("de")) {
      successMessage = "In die Zwischenablage kopiert!";
    } else {
      successMessage = "Copied!";
    }

    // הוספת ההודעה לכפתור
    button.innerHTML = <span class="success-message">${successMessage}</span>;

    // החזרת הטקסט המקורי לאחר 4 שניות
    setTimeout(function() {
      // טוענים את הכפתור מחדש עם העיצוב המקורי
      button.innerHTML = originalHTML; // מחזירים את התוכן המקורי של הכפתור
    }, 4000);
  }
</script>

const downloadVideo = (urls: string) => {
  axios({
    url,
    method: 'GET',
    responseType: 'blob',
  }).then((response) => {
    const urlObject = window.URL.createObjectURL(new Blob([response.data]));
    const link = document.createElement('a');
    link.href = urlObject;
    link.setAttribute('download', 'recording.mp4');
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  });
};
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Data bindings</title>
</head>

<body>
    <div id="root">
        <input type="text" v-model="name">
        <h1>Your name is {{name}} </h1>
    </div>

    <script type="text/javascript" src="vue.js"></script>
    <script type="text/javascript">
        var app = new Vue({
            el: '#root',
            data: { name: "Moana" }
        });
    </script>
</body>

</html>
star

Sun Dec 08 2024 11:13:01 GMT+0000 (Coordinated Universal Time)

@John_Almer

star

Sun Dec 08 2024 11:10:57 GMT+0000 (Coordinated Universal Time)

@John_Almer

star

Sun Dec 08 2024 10:33:11 GMT+0000 (Coordinated Universal Time)

@John_Almer

star

Sun Dec 08 2024 10:32:36 GMT+0000 (Coordinated Universal Time)

@John_Almer

star

Sat Dec 07 2024 21:20:19 GMT+0000 (Coordinated Universal Time) https://salesforcetime.com/2023/11/15/how-to-control-the-css-of-screen-flows/

@dannygelf #flow #salesforce #ui

star

Sat Dec 07 2024 19:46:13 GMT+0000 (Coordinated Universal Time)

@davidmchale

star

Sat Dec 07 2024 11:45:20 GMT+0000 (Coordinated Universal Time)

@khadizasultana #loop #c++ #vector

star

Sat Dec 07 2024 11:27:32 GMT+0000 (Coordinated Universal Time)

@hitsabhishek

star

Sat Dec 07 2024 11:01:50 GMT+0000 (Coordinated Universal Time)

@hitsabhishek

star

Sat Dec 07 2024 10:31:58 GMT+0000 (Coordinated Universal Time) https://developer.chrome.com/docs/extensions/reference/api/types#ChromeSetting

@Misotek25 #ts

star

Sat Dec 07 2024 10:16:46 GMT+0000 (Coordinated Universal Time) https://www.onlinegdb.com/online_c_compiler

@Narendra

star

Sat Dec 07 2024 10:15:42 GMT+0000 (Coordinated Universal Time) https://www.onlinegdb.com/online_c_compiler

@Narendra

star

Sat Dec 07 2024 08:58:43 GMT+0000 (Coordinated Universal Time) https://www.onlinegdb.com/online_c_compiler

@Narendra

star

Sat Dec 07 2024 07:00:07 GMT+0000 (Coordinated Universal Time) https://angelx-speedo.com/fast-liquidation-sell-usdt-to-inr-with-angelx-speedo/

@diagorass #angelxspeedo #sell #usdt #inr

star

Sat Dec 07 2024 06:53:28 GMT+0000 (Coordinated Universal Time) https://blockchainjunction.online

@diagorass #blockchain #blockchainjunction #web3 #india

star

Sat Dec 07 2024 06:49:54 GMT+0000 (Coordinated Universal Time) https://angelx-super.com/how-it-works/

@diagorass ##angelxsuper ##usdt #inr

star

Sat Dec 07 2024 02:39:57 GMT+0000 (Coordinated Universal Time)

@John_Almer

star

Fri Dec 06 2024 20:50:23 GMT+0000 (Coordinated Universal Time)

@okkpurple

star

Fri Dec 06 2024 18:01:21 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Fri Dec 06 2024 17:04:19 GMT+0000 (Coordinated Universal Time)

@RobertoSilvaZ #server #ollama #windows #llama

star

Fri Dec 06 2024 12:13:48 GMT+0000 (Coordinated Universal Time)

@khadizasultana #loop #array #c++

star

Fri Dec 06 2024 11:28:44 GMT+0000 (Coordinated Universal Time) https://appticz.com/cash-app-clone

@davidscott

star

Fri Dec 06 2024 09:07:10 GMT+0000 (Coordinated Universal Time)

@shri

star

Fri Dec 06 2024 08:02:53 GMT+0000 (Coordinated Universal Time) https://www.mageplaza.com/devdocs/custom-shipping-address-template-magento-2.html

@zaki

star

Fri Dec 06 2024 06:52:45 GMT+0000 (Coordinated Universal Time) https://webdeveloper.beehiiv.com/p/css-color-properties-you-might-not-know-about?ref

@Sourav010

star

Fri Dec 06 2024 06:52:37 GMT+0000 (Coordinated Universal Time) https://webdeveloper.beehiiv.com/p/css-color-properties-you-might-not-know-about?ref

@Sourav010

star

Fri Dec 06 2024 06:35:48 GMT+0000 (Coordinated Universal Time)

@anamarie

star

Fri Dec 06 2024 06:31:26 GMT+0000 (Coordinated Universal Time) https://blog.qaisarsatti.com/magento_2/magento-2-shopping-cart-items-subtotal-grand-total-billing-and-shipping-address/

@zaki

star

Fri Dec 06 2024 06:27:59 GMT+0000 (Coordinated Universal Time) https://www.mageplaza.com/devdocs/how-get-data-shopping-cart-items-subtotal-grand-total-billing-shipping-address-magento-2.html

@zaki

star

Fri Dec 06 2024 03:03:33 GMT+0000 (Coordinated Universal Time)

@webisko #javascript

star

Fri Dec 06 2024 02:28:52 GMT+0000 (Coordinated Universal Time)

@mamba

star

Thu Dec 05 2024 22:25:57 GMT+0000 (Coordinated Universal Time)

@kanatov

star

Thu Dec 05 2024 18:01:39 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Thu Dec 05 2024 16:24:26 GMT+0000 (Coordinated Universal Time) https://codepen.io/alphardex/pen/OJNLyOv

@Dc #html

star

Thu Dec 05 2024 16:24:03 GMT+0000 (Coordinated Universal Time) https://codepen.io/alphardex/pen/OJNLyOv

@Dc #css

star

Thu Dec 05 2024 12:28:52 GMT+0000 (Coordinated Universal Time) https://appticz.com/turo-clone

@davidscott ##appticz #turo_clone_app

star

Thu Dec 05 2024 07:13:11 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/71829361/how-to-download-mp4-video-in-js-react

@rtrmukesh

star

Thu Dec 05 2024 05:59:09 GMT+0000 (Coordinated Universal Time)

@truthfinder #vue.js

Save snippets that work with our extensions

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