Snippets Collections
let value = 4
let negvalue = -value 
console.log(negvalue);

/*console.log(2+2);
console.log(2-2);
console.log(2*2);
console.log(2**2);
console.log(2/2);
console.log(2%2);*/

let str1 = "hello "
let str2 = "namastey"
let str3 = str1 + str2 
console.log(str1 + str2)

/* javascript basic tricks*/

console.log(2+"3") //23
console.log("2"+"3") //23
console.log("1"+2+2) //122
console.log(1+2+'2') //32 

/* bad performance*/
console.log(+true);//true
console.log(+"");//fales

let gamecounter = 100
gamecounter++; // post increment and pre increment gives a same answer 
console.log(gamecounter);

let score = true


console.log(score);
console.log(typeof (score));
let valueInNumber = Number(score)
console.log(typeof valueInNumber);
console.log( valueInNumber);
/* PRINTING OF
"33" = 33
"33annaa" = NaN(not a number )
true = 1
false = 0*/


let isLoggedIn = 1
/* empty will give false 
0 will give false*/
let booleanIsLoggedIn = Boolean(isLoggedIn)
console.log(booleanIsLoggedIn); //true


let somenumber = 33;
console.log(typeof somenumber);
let stringNumber = String(somenumber)
console.log(stringNumber);
console.log(typeof stringNumber);
#Boot in Safe Mode (via msconfig)
#Open Registry Editor
#Navigateto:
#HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Service
#The six keys in the registry to change the values of:
#Sense
#WdBoot
#WdFilter
#WdNisDrv
#WdNisSvc
#WinDefend

# To disable, set:
HKLM\SYSTEM\CurrentControlSet\Services\Sense\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdBoot\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdNisDrv\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WdNisSvc\Start	4
HKLM\SYSTEM\CurrentControlSet\Services\WinDefend\Start	4

#To re-enable, set:
HKLM\SYSTEM\CurrentControlSet\Services\Sense\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WdBoot\Start	0
HKLM\SYSTEM\CurrentControlSet\Services\WdFilter\Start	0
HKLM\SYSTEM\CurrentControlSet\Services\WdNisDrv\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WdNisSvc\Start	3
HKLM\SYSTEM\CurrentControlSet\Services\WinDefend\Start	2



Run actions/github-script@e69ef5462fd455e02edcaf4dd7708eda96b9eda0
2
  with:
3
    github-token: ***
4
    script: // Only perform this action with GitHub employees
5
  try {
6
    await github.rest.teams.getMembershipForUserInOrg({
7
      org: %27github%27,
8
      team_slug: %27employees%27,
9
      username: context.payload.sender.login,
10
    });
11
  } catch(err) {
12
    // An error will be thrown if the user is not a GitHub employee
13
    // If a user is not a GitHub employee, we should stop here and
14
    // Not send a notification
15
    return
16
  }
"use strict"; // treated as all new js code version 

// alert(3+3) we are using nodejs not brpwser 

console.log(3+3+3);
console.log("tansihq dhingra ");// code readibility is very important 

let name = "tanishq"
let age = 18 
let isLoggedIn = false 

/* primitive 
number = 2 ki power 53
bigint
string = " "
boolean = true/ false 
null = standalone value (value is null )
undefined = not defined 
symbbol = uniqueness in react */

// object 
console.log(typeof undefined );//undefined
console.log(typeof null);//object 
import java.util.*;

public class Graph {
    private int vertices;  // Number of vertices
    private LinkedList<Integer>[] adjList;  // Adjacency list representation
    private int time;  // Time counter for DFS

    // Constructor
    public Graph(int v) {
        vertices = v;
        adjList = new LinkedList[v];
        for (int i = 0; i < v; i++) {
            adjList[i] = new LinkedList<>();
        }
        time = 0;
    }

    // Add an edge to the graph
    public void addEdge(int v, int w) {
        adjList[v].add(w);
        adjList[w].add(v);  // Since the graph is undirected
    }

    // Articulation Point (Art) Algorithm
    public void findArticulationPoints() {
        boolean[] visited = new boolean[vertices];
        int[] dfn = new int[vertices];  // Discovery time of visited vertices
        int[] low = new int[vertices];  // Lowest discovery time reachable
        int[] parent = new int[vertices];  // Parent vertices in DFS
        Arrays.fill(parent, -1);  // Initialize all parents as -1

        // Start DFS from each unvisited node
        for (int i = 0; i < vertices; i++) {
            if (!visited[i]) {
                DFSArt(i, visited, dfn, low, parent);
            }
        }
    }

    private void DFSArt(int u, boolean[] visited, int[] dfn, int[] low, int[] parent) {
        visited[u] = true;  // Mark the current node as visited
        dfn[u] = low[u] = ++time;  // Initialize discovery time and low value
        int childCount = 0;  // Count of children in DFS tree
        boolean isArticulation = false;

        for (int v : adjList[u]) {
            if (!visited[v]) {
                childCount++;
                parent[v] = u;
                DFSArt(v, visited, dfn, low, parent);

                // Check if the subtree rooted at v has a connection back to one of u's ancestors
                low[u] = Math.min(low[u], low[v]);

                // u is an articulation point in two cases:
                // (1) u is not the root and low value of one of its child is more than discovery value of u
                if (parent[u] != -1 && low[v] >= dfn[u]) {
                    isArticulation = true;
                }

                // (2) u is the root of DFS tree and has two or more children
                if (parent[u] == -1 && childCount > 1) {
                    isArticulation = true;
                }
            } else if (v != parent[u]) {
                // Update low value of u for back edge
                low[u] = Math.min(low[u], dfn[v]);
            }
        }

        // If u is an articulation point, print it
        if (isArticulation) {
            System.out.println("Articulation Point: " + u);
        }
    }

    // Construct graph from adjacency matrix
    public static Graph createGraphFromAdjMatrix(int[][] adjMatrix) {
        int n = adjMatrix.length;
        Graph g = new Graph(n);
        for (int i = 0; i < n; i++) {
            for (int j = i + 1; j < n; j++) {  // Undirected graph, so only check i < j
                if (adjMatrix[i][j] == 1) {
                    g.addEdge(i, j);
                }
            }
        }
        return g;
    }

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

        // Input the number of vertices
        System.out.print("Enter the number of vertices: ");
        int v = scanner.nextInt();

        // Input the adjacency matrix
        System.out.println("Enter the adjacency matrix:");
        int[][] adjMatrix = new int[v][v];
        for (int i = 0; i < v; i++) {
            for (int j = 0; j < v; j++) {
                adjMatrix[i][j] = scanner.nextInt();
            }
        }

        // Create the graph from adjacency matrix
        Graph g = Graph.createGraphFromAdjMatrix(adjMatrix);

        // Find and print the articulation points
        System.out.println("Articulation Points:");
        g.findArticulationPoints();
    }
}

output1:
Enter the number of vertices: 5
Enter the adjacency matrix:
0 1 1 0 0
1 0 1 1 0
1 1 0 0 0
0 1 0 0 1
0 0 0 1 0
Articulation Points:
Articulation Point: 1
Articulation Point: 3

output2:
Enter the number of vertices: 6
Enter the adjacency matrix:
0 1 1 0 0 0
1 0 1 1 0 0
1 1 0 0 1 0
0 1 0 0 1 1
0 0 1 1 0 1
0 0 0 1 1 0
Articulation Points:
Articulation Point: 2
Articulation Point: 3
const accountID = 145242;//constant value 
let accountEmail = "dhingra@gmail.com";// variable we will use it the most 
var accountPassword = "123433";// variable we dont use var generally
accountCity = "jaipur";

accountEmail = "dhbscbbcd@g.com";
accountPassword = "132322";
accountCity = "bengaluru";
let accountState;

console.log(accountID);
console.table({ accountID, accountEmail, accountPassword, accountCity ,accountState });
import base64

sample_string = "GeeksForGeeks is the best"
sample_string_bytes = sample_string.encode("ascii")

base64_bytes = base64.b64encode(sample_string_bytes)
base64_string = base64_bytes.decode("ascii")

print(f"Encoded string: {base64_string}")
tar -xf node-v20.18.0-linux-x64.tar.xz

2. Mover Node.js a un directorio adecuado
Para que Node.js esté disponible globalmente, es recomendable moverlo a /usr/local. Puedes hacerlo con el siguiente comando:

sudo mv node-v20.18.0-linux-x64 /usr/local/nodejs

3. Configurar las variables de entorno
Para que el sistema reconozca los comandos de Node.js y npm, necesitas agregar el directorio de Node.js a tu variable de entorno PATH. Abre el archivo de configuración de tu shell. Si usas bash, puedes editar el archivo .bashrc:

nano ~/.bashrc

Agrega la siguiente línea al final del archivo:

4. Aplicar los cambios
Para aplicar los cambios realizados en el archivo .bashrc, ejecuta:

source ~/.bashrc

5. Verificar la instalación
Finalmente, verifica que Node.js y npm se hayan instalado correctamente ejecutando los siguientes comandos:

node -v
npm -v

pattrens = [
    '123456',
    '6665522',
    '887799',
    '123456',
    '6665522',
    '1111222',
    '123456',
    '6665522',
    '887799',
    '123456',
    '111111'
]


def classify_pattrens(pattrens_list):
    labels = {k : [] for k in pattrens_list}
    for pattren in pattrens_list:
        labels[pattren].append(pattren)

    return labels

print(classify_pattrens(pattrens))
ejemplo de exportar modulo
// archivo: miModulo.mjs
export function saludar(nombre) {
    return `Hola, ${nombre}!`;
}

ejemplo de importar modulo
// archivo: app.mjs
import { saludar } from './miModulo.mjs';

console.log(saludar('Mundo')); // Salida: Hola, Mundo!
/mi-proyecto
├── backend
│   ├── composer.json
│   ├── index.php
│   └── miModulo.mjs
└── frontend
    ├── package.json
    └── app.mjs

codigo:

1. Archivo composer.json (Backend)
Este archivo se encuentra en la carpeta backend y define las dependencias de PHP que necesitas. Aquí hay un ejemplo básico:

{
  "require": {
    "monolog/monolog": "^2.0"
  }
}

2. Archivo index.php (Backend)
Este archivo es el punto de entrada de tu aplicación PHP. Aquí puedes manejar las solicitudes y enviar respuestas. Un ejemplo simple podría ser:

<?php
// backend/index.php

require 'vendor/autoload.php'; // Asegúrate de que el autoload de Composer esté incluido

use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Crear un logger
$log = new Logger('mi_proyecto');
$log->pushHandler(new StreamHandler('app.log', Logger::WARNING));

// Registrar un mensaje
$log->warning('Esto es un mensaje de advertencia');

// Enviar una respuesta simple
header('Content-Type: application/json');
echo json_encode(['message' => 'Hola desde el backend!']);

3. Archivo miModulo.mjs (Backend)
Este archivo contiene un módulo que puedes importar en otros archivos. Aquí hay un ejemplo de cómo podría verse:

// backend/miModulo.mjs

export function saludar(nombre) {
    return `Hola, ${nombre}!`;
}

4. Archivo package.json (Frontend)
Este archivo se encuentra en la carpeta frontend y define las dependencias de JavaScript que necesitas. Aquí hay un ejemplo básico:

{
  "name": "mi-proyecto-frontend",
  "version": "1.0.0",
  "dependencies": {
    "axios": "^0.21.1"
  },
  "scripts": {
    "start": "node app.mjs"
  }
}

5. Archivo app.mjs (Frontend)
Este archivo contiene el código JavaScript que se ejecutará en el lado del cliente. Aquí hay un ejemplo que utiliza axios para hacer una solicitud al backend y también importa la función saludar del módulo:

// frontend/app.mjs

import { saludar } from '../backend/miModulo.mjs'; // Importar la función del módulo

const nombre = 'Mundo';
console.log(saludar(nombre)); // Salida: Hola, Mundo!

// Hacer una solicitud al backend
axios.get('http://localhost/backend/index.php')
  .then(response => {
    console.log('Respuesta del backend:', response.data);
  })
  .catch(error => {
    console.error('Error al hacer la solicitud:', error);
  });


Conclusión
Este ejemplo proporciona una base para un proyecto que combina un backend en PHP y un frontend en JavaScript utilizando módulos ES. Puedes expandirlo según tus necesidades, añadiendo más funcionalidades y dependencias según sea necesario. Asegúrate de tener configurado un servidor para el backend y de ejecutar el script del frontend para ver la interacción entre ambos.
<script>
document.addEventListener('click', function (event) {
    if (event.target.closest('a[href*="#"]:not([aria-haspopup="true"])') && event.target.closest('.e-off-canvas[aria-hidden="false"]')) {
        const canvasTrigger = document.querySelector('[href*="off_canvas%3A"]:not([href*="%3Aopen"]');
        if (canvasTrigger) canvasTrigger.click();
    }
});
</script>
selector .menu-item .elementor-item-active {
    font-weight: 600;
}


selector .sub-menu {
    padding: 15px 20px 15px 15px;
}

selector .sub-menu li {
    padding: 5px 0;
}

selector .elementor-nav-menu--dropdown.elementor-nav-menu__container {
    padding: 20px;
}

@media only screen and (max-width: 1024px) {
selector .sub-menu.elementor-nav-menu--dropdown {
    padding: 0; 
}
selector .sub-menu.elementor-nav-menu--dropdown a {
    margin-left: -8px; 
}
selector .elementor-nav-menu--dropdown .menu-item  {
    padding: 10px 0;
}
selector .menu-item.menu-item-has-children .sub-menu .menu-item {
    padding: 0;
    padding-top: 15px;
    color: red !important;
}
selector .menu-item.menu-item-has-children .sub-menu .menu-item a {
    font-weight: 400
}
}
let phi = (1 + sqrt(5)) / 2; // Gouden ratio
<?php if ($result && $result->num_rows > 0): ?>
                    <?php while ($user = $result->fetch_assoc()): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($user['id']); ?></td>
                            <td class="<?php echo ($user['is_admin'] ? 'admin-user' : 'normal-user'); ?>">
                                <?php echo htmlspecialchars($user['username']); ?>
                            </td>
                            <td><?php echo htmlspecialchars(date('Y-m-d', strtotime($user['register_date']))); ?></td>
                            <td><?php echo ($user['is_admin'] ? 'Yes' : 'No'); ?></td>
                        </tr>
                    <?php endwhile; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="4">No users!</td>
                    </tr>
                <?php endif; ?>
#include <iostream>
using namespace std;

// Function to merge two sorted halves of the array into a single sorted array.
void merge(int arr[], int left, int mid, int right) 
{
    int n1 = mid - left + 1;
    int n2 = right - mid;

    //temporary arrays
    int leftArr[n1], rightArr[n2];

    //copy data to temporary arrays
    for (int i = 0; i < n1; i++)
        leftArr[i] = arr[left + i];
    for (int j = 0; j < n2; j++)
        rightArr[j] = arr[mid + 1 + j];

    //merge temporary arrays back into arr[left..right]
    int i = 0, j = 0, k = left;
    while (i < n1 && j < n2) 
    {
        if (leftArr[i] <= rightArr[j]) 
        {
            arr[k] = leftArr[i];
            i++;
        } else {
            arr[k] = rightArr[j];
            j++;
        }
        k++;
    }

    //copy the remaining elements of leftArr[], if any
    while (i < n1) 
    {
        arr[k] = leftArr[i];
        i++;
        k++;
    }

    //copy the remaining elements of rightArr[], if any
    while (j < n2) 
    {
        arr[k] = rightArr[j];
        j++;
        k++;
    }
}

// Function to recursively divide the array and merge the sorted halves.
void mergeSort(int arr[], int left, int right) 
{
    if (left < right) 
    {
        int mid = left + (right - left) / 2;

        //sort first and second halves
        mergeSort(arr, left, mid);
        mergeSort(arr, mid + 1, right);

        //merge the sorted halves
        merge(arr, left, mid, right);
    }
}

// Function to initiate the merge sort process.
void processMergeSort(int arr[], int n) 
{
    if (n > 1) 
    {
        mergeSort(arr, 0, n - 1);
    }
}

void displayArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "Unsorted array: ";
    displayArray(arr, n);
    processMergeSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
#include <iostream>
#include <cstdlib> // for rand() and srand()
#include <ctime> // for time()

using namespace std;

// Function to merge two sorted sub-arrays in place.
void inPlaceMerge(int arr[], int left, int mid, int right) 
{
    int start2 = mid + 1;

    //if the direct merge is already sorted
    if (arr[mid] <= arr[start2]) 
    {
        return;
    }

    //two pointers to maintain start of both arrays to merge
    while (left <= mid && start2 <= right) 
    {
        //if element 1 is in right place
        if (arr[left] <= arr[start2]) 
        {
            left++;
        } 
        else 
        {
            int value = arr[start2];
            int index = start2;

            //shifting all elements between element 1 and element 2 right by 1.
            while (index != left) 
            {
                arr[index] = arr[index - 1];
                index--;
            }
            arr[left] = value;

            //update all pointers
            left++;
            mid++;
            start2++;
        }
    }
}

// Function to recursively sort the array using Merge Sort.
void inPlaceMergeSort(int arr[], int left, int right) 
{
    if (left < right) 
    {
        int mid = left + (right - left) / 2;

        //sort first and second halves
        inPlaceMergeSort(arr, left, mid);
        inPlaceMergeSort(arr, mid + 1, right);

        //merge the sorted halves
        inPlaceMerge(arr, left, mid, right);
    }
}

// Function to initiate the Merge Sort process.
void processInPlaceMergeSort(int arr[], int n) 
{
    if (n > 1) 
    {
        inPlaceMergeSort(arr, 0, n - 1);
    }
}

void displayArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        cout << arr[i] << " ";
    }
    cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "Unsorted array: ";
    displayArray(arr, n);
    processInPlaceMergeSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
mpl.rcParams.update({'font.size': 14})

# Indices to step through colormap.
x = np.linspace(0.0, 1.0, 100)

gradient = np.linspace(0, 1, 256)
gradient = np.vstack((gradient, gradient))


def plot_color_gradients(cmap_category, cmap_list):
    fig, axs = plt.subplots(nrows=len(cmap_list), ncols=2)
    fig.subplots_adjust(top=0.95, bottom=0.01, left=0.2, right=0.99,
                        wspace=0.05)
    fig.suptitle(cmap_category + ' colormaps', fontsize=14, y=1.0, x=0.6)

    for ax, name in zip(axs, cmap_list):

        # Get RGB values for colormap.
        rgb = mpl.colormaps[name](x)[np.newaxis, :, :3]

        # Get colormap in CAM02-UCS colorspace. We want the lightness.
        lab = cspace_converter("sRGB1", "CAM02-UCS")(rgb)
        L = lab[0, :, 0]
        L = np.float32(np.vstack((L, L, L)))

        ax[0].imshow(gradient, aspect='auto', cmap=mpl.colormaps[name])
        ax[1].imshow(L, aspect='auto', cmap='binary_r', vmin=0., vmax=100.)
        pos = list(ax[0].get_position().bounds)
        x_text = pos[0] - 0.01
        y_text = pos[1] + pos[3]/2.
        fig.text(x_text, y_text, name, va='center', ha='right', fontsize=10)

    # Turn off *all* ticks & spines, not just the ones with colormaps.
    for ax in axs.flat:
        ax.set_axis_off()

    plt.show()


for cmap_category, cmap_list in cmaps.items():

    plot_color_gradients(cmap_category, cmap_list)
sync && echo 3 > /proc/sys/vm/drop_caches
public boolean equals(Object obj) {
    return (this == obj);
}
import React, { useState, useEffect } from "react";
import { FaMedal } from "react-icons/fa";
import axios from "axios";
import Apis from "../../APIs";
import { useAuth } from "../Auth/AuthContext";
import { useNavigate } from "react-router-dom"; // To navigate to the dashboard

const Assessment = () => {
  const { user, setUser } = useAuth(); // Assuming setUser is available to update user data
  const navigate = useNavigate(); // To handle navigation
  const [questions, setQuestions] = useState([]);
  const [answers, setAnswers] = useState([]);
  const [score, setScore] = useState(0);
  const [result, setResult] = useState(false);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);
  const [assessmentRecordId, setAssessmentRecordId] = useState(null); // To store the assessment record ID
  const [redirectPage, setRedirectPage] = useState(null); // Store the page to redirect after clicking "Ok"

  const optionLabels = ["A", "B", "C", "D"];

  // Fetch questions from the API
  useEffect(() => {
    const fetchQuestions = async () => {
      try {
        const response = await axios.get(Apis.QUESTION_API);
        const fetchedQuestions = response.data;
        setQuestions(fetchedQuestions);
        setAnswers(fetchedQuestions.map(() => Array(4).fill(null)));
        setLoading(false);
      } catch (err) {
        console.error("Error fetching questions:", err);
        setError("Failed to load questions. Please try again later.");
        setLoading(false);
      }
    };

    fetchQuestions();
  }, []);

  const handleRatingSelect = (qIndex, oIndex, rating) => {
    const newAnswers = [...answers];
    newAnswers[qIndex][oIndex] = rating;
    setAnswers(newAnswers);
  };

  const handleSubmit = async () => {
    setResult(true);

    // Create the payload in the required JSON format for the POST request
    const formattedResponses = questions.map((question, qIndex) => ({
      questionId: question._id,
      ratings: answers[qIndex].map((rating) => ({ rating })),
    }));

    const userId = user._id;

    const payload = {
      userId: userId,
      responses: formattedResponses,
    };

    try {
      const response = await axios.post(Apis.ASSESSMENT_API, payload);
      console.log("Assessment submitted successfully:", response.data);
      setAssessmentRecordId(response.data._id); // Store the assessment record ID
      fetchAssessmentRecord(response.data._id); // Fetch the assessment record
    } catch (error) {
      console.error("Error submitting assessment:", error);
    }
  };

  const fetchAssessmentRecord = async (recordId) => {
    try {
      const response = await axios.get(
        `${Apis.ASSESSMENT_API}/getAssessmentRecord/${recordId}`
      );
      const optionStats = response.data.optionStats;
      determineRedirect(optionStats); // Call function to determine redirect
    } catch (error) {
      console.error("Error fetching assessment record:", error);
    }
  };

  const determineRedirect = (optionStats) => {
    const maxOption = Object.entries(optionStats).reduce(
      (acc, [key, value]) => {
        if (value[1] > acc.count) {
          return { key, count: value[1] }; // Find option with the highest count of "1"
        }
        return acc;
      },
      { key: null, count: 0 }
    );

    switch (maxOption.key) {
      case "option1":
        setRedirectPage("/PdfC"); // Set the redirect page
        break;
      case "option2":
        setRedirectPage("/PdfC");
        break;
      case "option3":
        setRedirectPage("/PdfC");
        break;
      case "option4":
        setRedirectPage("/PdfC");
        break;
      default:
        setRedirectPage("/dashboard"); // Default fallback
    }
  };

  const handleOkClick = async () => {
    // Fetch the updated user data
    const fetchUserData = async () => {
      try {
        const response = await axios.get(`${Apis.USER_API}/${user._id}`, {
          headers: {
            Authorization: `Bearer ${localStorage.getItem("token")}`,
          },
        });
        const updatedUserData = response.data;
        setUser(updatedUserData); // Update the user data in the context
        console.log("User data refreshed:", updatedUserData);
      } catch (error) {
        console.error("Error refreshing user data:", error);
      }
    };

    await fetchUserData();
    // window.location.reload();

    navigate(redirectPage); // Navigate to the determined PDF page
  };

  if (loading) {
    return (
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center">
        <div className="text-white text-2xl">Loading questions...</div>
      </section>
    );
  }

  if (error) {
    return (
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center">
        <div className="text-white text-2xl">{error}</div>
      </section>
    );
  }

  return (
    <>
      <section className="min-h-screen w-full bg-slate-900 flex items-center justify-center p-5">
        {result ? (
          <div className="min-h-[400px] w-80 md:w-[400px] rounded-lg bg-white p-5 flex items-center justify-center flex-col gap-5">
            <h2 className="text-3xl text-center">
              Thank you for giving the assessment
            </h2>
            <h2 className="text-3xl text-center">
              To See Your Result Click Ok
            </h2>
            <FaMedal className="text-4xl text-yellow-400" />
            {/* <h3 className="font-semibold text-4xl">{score}</h3> */}
            <button
              onClick={handleOkClick} // Handle Ok click and navigate
              className="h-10 w-full rounded-lg bg-green-500 text-white hover:bg-green-700"
            >
              Ok
            </button>
          </div>
        ) : (
          <div className="min-h-[400px] w-full max-w-screen-md rounded-lg bg-white p-5">
            <h2 className="font-bold text-xl mb-5">
              Know Your Competency (KYC) - Assessment on DGCS Leadership Style :
              -{" "}
            </h2>
            <h2 className="font-semibold text-sm mb-5">
              Please choose your rating based on your preference. Rank 1 - Most
              Agreed; 2 - Agreed; 3 - Lesser agreed; 4 - Least Agreed. -{" "}
            </h2>
            <h2 className="font-semibold text-sm mb-5">
              only one option should be given for each rank for each questions.
              For the question one - if you give rank 4 for 1st option, the same
              rank 4 cannot be given for the other 3 options. -{" "}
            </h2>
            
            {questions.map((q, qIndex) => (
              <div key={q._id} className="mb-6">
                <h3 className="font-semibold text-lg mb-3">
                  {qIndex + 1}. {q.mainQuestion}
                </h3>
                <div className="flex flex-col gap-3">
                  {q.options.map((option, oIndex) => (
                    <div
                      key={option._id}
                      className="flex items-center justify-between"
                    >
                      <span>{`(${optionLabels[oIndex]}) ${option.option}`}</span>
                      <div className="flex gap-7">
                        {[1, 2, 3, 4].map((rating) => (
                          <button
                            key={rating}
                            onClick={() =>
                              handleRatingSelect(qIndex, oIndex, rating)
                            }
                            className={`w-8 h-8 rounded-full border-2 flex items-center justify-center ${
                              answers[qIndex][oIndex] === rating
                                ? "bg-green-500 text-white"
                                : "border-gray-300"
                            }`}
                          >
                            {rating}
                          </button>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            ))}
            <div className="mt-5 flex justify-end">
              <button
                onClick={handleSubmit}
                className="h-10 w-32 rounded-lg bg-green-500 text-white hover:bg-green-700"
              >
                Submit
              </button>
            </div>
          </div>
        )}
      </section>
    </>
  );
};

export default Assessment;
#include <iostream>
using namespace std;

// Function to sort the array using insertion sort algorithm.
void processSelectionSort(int arr[], int n) 
{
    for (int i = 0; i < n - 1; i++) 
    {
        int min_index = i;
        for (int j = i + 1; j < n; j++) 
        {
            if (arr[j] < arr[min_index]) 
            {
                min_index = j;
            }
        }
        
        if (min_index != i) 
        {
            swap(arr[min_index], arr[i]);
        }
    }
}

void displayArray(int arr[], int n) {
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "\nUnsorted array: ";
    displayArray(arr, n);
    processSelectionSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
In today's digital era, a strong online presence is essential for business success. VFIX Technology, based in Delhi, is recognized as the best website designing company in Delhi and a leading provider of cutting-edge solutions, including app development, e-commerce websites, and website customization. Our goal is to empower businesses with tailored technology solutions that drive growth and customer satisfaction.
Expert App Development for Seamless User Experiences
At VFIX Technology, we specialize in creating intuitive and high-performance mobile apps. Whether you're looking for an app for Android or iOS, we ensure that your users have a seamless experience. From idea conceptualization to final deployment, our app development services cover all stages, offering:

    Custom app solutions for businesses of all sizes
    User-friendly interfaces designed to enhance engagement
    Robust, scalable, and secure apps

By leveraging the latest technologies, our team delivers apps that not only meet your requirements but also exceed your expectations. Whether you need a dynamic mobile presence or a customized app tailored to your industry, we’re here to help you take your mobile strategy to the next level.
#include <iostream>
using namespace std;

// Function to sort the array using insertion sort algorithm.
void processInsertionSort(int arr[], int n) 
{
  for (int i = 1; i < n; i++) 
    {
        int key = arr[i];
        int j = i - 1;
        
        while (j >= 0 && arr[j] > key) 
        {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}

void displayArray(int arr[], int n) {
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "Unsorted array: ";
    displayArray(arr, n);
    processInsertionSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Boost Days: What's on in Melbourne this week!"
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n Hey Melbourne, happy Monday! Please see below for what's on this week. "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Xero Café :halloween-coffee:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n :new-thing: *This week we are offering:* \n\n Halloween Themed Cookies and Caramel & Macadamia Slice (Gluten Free) :jack_o_lantern: \n\n *Weekly Café Special:* _ *Superfreak Halloween Blend* - expect notes of Candy Apple, Citrus, Orange Marmalade and Praline! _"
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": " Wednesday, 30th October :calendar-date-30:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n* :cartoon-cannoli:* Afternoon Tea From *2pm* in the L3 kitchen \n\n:lotus: *Wellbeing - Yoga Flow*: Confirm your spot <https://docs.google.com/spreadsheets/d/1iKMQtSaawEdJluOmhdi_r_dAifeIg0JGCu7ZSPuwRbo/edit?gid=0#gid=0/|*here*>. Please note we have a maximum of 15 participants per class, a minimum notice period of 2 hours is required if you can no longer attend."
			}
		},
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": "Thursday, 31st October :halloween-date:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":halloween-breakfast: *Breakfast*: Provided by *Kartel Catering* from *8:30am - 10:30am* in the Wominjeka Breakout Space.\n\n :meow-scary: *Haunted Hackathon Social+* A combination of Hackathon + Halloween themed! Dress up in your scariest outfit and come along for a range of activities, drinks and delicious food! "
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "\n\n *🎟 RSVP to our EOY Event Now:*\nPlease click <https://xero-wx.jomablue.com/reg/store/eoy_mel|here> to RSVP! \nMake sure you RSVP by *_14th November 2024_* :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "header",
			"text": {
				"type": "plain_text",
				"text": ":xero-unicorn: Reminder: End of Year Celebration – Registrations :xero-unicorn:",
				"emoji": true
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*Hi Melbourne!* \n We hope you're getting excited for a night of magic! This is your friendly reminder to make sure you register to our end of year event by the 14th of November 2024! \n\n In today's post we've added in some answers to the commonly asked questions! Please read below."
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"fields": [
				{
					"type": "mrkdwn",
					"text": "*📅 When:*\nThursday 28th November"
				},
				{
					"type": "mrkdwn",
					"text": "*📍 Where:*\n<https://www.google.com/maps/place/The+Timber+Yard/@-37.8331021,144.918894,17z/data=!3m1!4b1!4m6!3m5!1s0x6ad667735e56fcab:0x966480f06c58c00c!8m2!3d-37.8331021!4d144.9214743!16s/g/11gyy7sy4c?entry=ttu&g_ep=EgoyMDI0MDkxOC4xIKXMDSoASAFQAw==/|*The Timber Yard*> \n351 Plummer Street, Port Melbourne"
				},
				{
					"type": "mrkdwn",
					"text": "*⏰ Time:*\n4PM - 10PM"
				}
			]
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*:question: FAQs Fast Answers:*\n *Can I register on behalf of a colleague if they're on leave?* Yes absolutely! Just make sure you fill in their registration form with their Xero email address + personal details. \n\n *Smoking at the party?* No smoking/vaping will be permitted onsite, we will have a dedicated area outside of the venue for you to do your business! \n\n *How do we get into the event?* Simply show the security guards your email confirmation from JomaBlue for quick and easy access into the venue! "
			}
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": "*🎟 RSVP Now:*\nPlease click <https://xero-wx.jomablue.com/reg/store/eoy_mel|here> to RSVP! \nMake sure you RSVP by *_14th November 2024_*"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "mrkdwn",
				"text": ":question:Got more questions? See the <https://docs.google.com/document/d/1iygJFHgLBRSdAffNsg3PudZCA45w6Wit7xsFxNc_wKM/edit|FAQs> doc or ask away in this thread!\n\n We can’t wait to celebrate with you! :partying_face: :xero-love:"
			}
		}
	]
}
{
  "type[currency]": "Hello, world!",
  "type[periodicity]": "Hello, world!",
  "type[price]": 1,
  "type[external_id]": "Hello, world!",
  "type[name]": "Hello, world!",
  "type[description]": "Hello, world!",
  "type[active]": true,
  "type[restriction_enabled]": true,
  "type[discharged]": true,
  "type[recurring_payment_enabled]": true,
  "type[until_year_end]": true,
  "type[enable_expire_month]": true,
  "type[expire_month]": 1,
  "type[recurring_mode]": "Hello, world!",
  "type[payment_account_id]": 1
}
for each  item in input.Items
{
	barcode = item.Barcode;
	query = Map();
	query.put("cf_barcode",barcode);
	fetch_item = invokeurl
	[
		url :"https://www.zohoapis.eu/books/v3/items?organization_id=" + organization_id
		type :GET
		parameters:query
		connection:"zoho_oauth_connection"
	];
	// 		info fetch_item;
	search_items = fetch_item.get("items");
	if(search_items.size() > 0)
	{
		////// Item found with barcode ////
		inventory_item_id = search_items.get(0).get("item_id");
		get_by_id = zoho.books.getRecordsByID("Items",organization_id,inventory_item_id,"zoho_oauth_connection");
// 		info get_by_id;
		item_details = get_by_id.get("item");
		custom_fields = item_details.get("custom_fields");
		rate = item_details.get("rate");
		for each field in custom_fields
        {
			if(field.get("label") == "Make")
			{
				make = field.get("value");
			}
			if(field.get("label") == "Model")
			{
				model = field.get("value");
			}
			if(field.get("label") == "Machine Type")
			{
				machine_type = field.get("value");
			}
			if(field.get("label") == "Shipping Class")
			{
				shipping_class = field.get("value");
			}
        } 
		item.Make = make;
		item.Model = model;
		item.Machine_Type = machine_type;
		item.Shipping_Class = shipping_class;
		item.Sales_Pric = rate;
		
	}
}
from yattag import Doc

import webbrowser

doc, tag, text = Doc().tagtext()

doc.asis('<!DOCTYPE html>')

with tag('html') as html:
    with tag('head') as head:
        with tag('title') as title:
            text('This is test web page')
    with tag('body') as body:
        with tag('h2') as h2:
            text('This is h2')

page = doc.getvalue()

f = open('page.html', 'w')
f.write(page)
f.close()

webbrowser.open('page.html')
<div class="col-xs-4" style="display: none;" id='id_estado'>
                                                    <?= $form->field($model, 'id_estado')->dropDownList(ArrayHelper::map(Estados::find()/*->where(['id_municipio'=> 2])*/->orderBy('desc_estado')->all(), 'id_estado', 'desc_estado'), ['prompt' => 'Seleccione ', 'id' => 'id-estado']); ?>
                                                </div>

                                                <div class="col-xs-4" style="display: none;" id='id_municipio'>

                                                    <?= $form->field($model, 'id_municipio')->widget(DepDrop::classname(), [
                                                        'options' => ['id' => 'id-ubicacion'],
                                                        'data' => $model->isNewRecord ? [] : ArrayHelper::map(Municipios::find()->where([ 'id_estado'=>$model->id_estado])->orderBy('desc_municipio')->asArray()->all(), 'id_municipio', 'desc_municipio'),
                                        
                                                        // ensure at least the preselected value is available
                                                        'pluginOptions' => [
                                                            'depends' => ['id-estado'],
                                                            // the id for cat attribute
                                                            'placeholder' => 'Seleccione un municipio...',
                                                            'url' => Url::to(['municipios/listar'])
                                                        ]
                                                    ]);
                                                    ?>
                                                </div>

                                                <div class="col-xs-4" style="display: none;" id='id_parroquia'>
                                                    <?= $form->field($model, 'id_parroquia')->widget(DepDrop::classname(), [
                                                        //'options'=>['id'=>'co_art_'.$regla->cod_linea.''],

                                                        'data' => $model->isNewRecord ? [] : ArrayHelper::map(Parroquias::find()->where(['id_municipio'=>$model->id_municipio])->orderBy('desc_parroquia')->asArray()->all(), 'id_parroquia', 'desc_parroquia'),
                                                        // ensure at least the preselected value is available
                                                        'pluginOptions' => [
                                                            'depends' => ['id-ubicacion'],
                                                            // the id for cat attribute
                                                            'placeholder' => 'Seleccione una parroquia...',
                                                            'url' => Url::to(['parroquias/listar'])
                                                        ]
                                                    ]);
                                                    ?>
                                                </div>

controlador municipio

public function actionListar() {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
            if ($parents != null) {
                $dep_id = $parents[0];
                //$hoy = date('Y-m-d');
                //$out = self::getSubCatList($cat_id);
                $out = \yii\helpers\ArrayHelper::toArray(Municipios::find()->where([ 'id_estado'=>$dep_id])->orderBy('desc_municipio')->all(), 'id_municipio', 'desc_municipio');
               
                $response = array();
                foreach ($out as $row) {
                  $arr['id'] = trim($row['id_municipio']);
                  $arr['name'] = trim($row['desc_municipio']);
                  array_push($response, $arr);
                }
                echo \yii\helpers\Json::encode(['output'=>$response, 'selected'=>'']);
                return;
            }
        }
        echo Json::encode(['output'=>'', 'selected'=>'']);
    }

controlador parroquia
public function actionListar() {
        $out = [];
        if (isset($_POST['depdrop_parents'])) {
            $parents = $_POST['depdrop_parents'];
    //var_dump($parents); die();
            if ($parents != null) {
                $dep_id = $parents[0];

                //para que se pueda cargar la parroquia en blanco, mientras no sea seleccionado un municipio
                if($dep_id == ""){
                          echo \yii\helpers\Json::encode(['output'=>'', 'selected'=>'']);
                          return;

                }
                //$hoy = date('Y-m-d');
                $out = yii\helpers\ArrayHelper::toArray(Parroquias::find()->where(['id_municipio'=>$dep_id])->orderBy('desc_parroquia')->all(), 'id_parroquia', 'desc_parroquia');

                $response = array();
                foreach ($out as $row) {
                  $arr['id'] = trim($row['id_parroquia']);
                  $arr['name'] = trim($row['desc_parroquia']);
                  array_push($response, $arr);
                }
                echo \yii\helpers\Json::encode(['output'=>$response, 'selected'=>'']);
                return;
            }
        }
        echo \yii\helpers\Json::encode(['output'=>'', 'selected'=>'']);
    }    

___________________otro ejemplo usando el modelo del mismo archivo este ejemplo es mas sencillo por que no hay que ponerle la condicion en data como en el ejemplo anterior
<div class="row">
        <div class="col-xs-1"></div>
        <div class="col-xs-3">
            <?= $form->field($model, 'id_estado')->dropDownList(ArrayHelper::map(Estados::find()->orderBy('desc_estado')->all(), 'id_estado', 'desc_estado'), ['prompt' => 'Seleccione un estado', 'id' => 'id-estado']); ?>
        </div>

        <div class="col-xs-3">
            <?= $form->field($model, 'id_municipio')->widget(DepDrop::classname(), [
                'options' => ['id' => 'id-municipio'],
                'data' => [$model->id_municipio => $model->municipio],
                // ensure at least the preselected value is available
                'pluginOptions' => [
                    'depends' => ['id-estado'],
                    // the id for cat attribute
                    'placeholder' => 'Seleccione un municipio...',
                    'url' => Url::to(['municipios/listar'])
                ]
            ]);
            ?>
        </div>
        <div class="col-xs-3">
            <?= $form->field($model, 'id_parroquia')->widget(DepDrop::classname(), [
                //'options'=>['id'=>'co_art_'.$regla->cod_linea.''],
            
                'data' => [$model->id_parroquia => $model->Parroquia],
                // ensure at least the preselected value is available
                'pluginOptions' => [
                    'depends' => ['id-municipio'],
                    // the id for cat attribute
                    'placeholder' => 'Seleccione una parroquia...',
                    'url' => Url::to(['parroquias/listar'])
                ]
            ]);
            ?>
        </div>
    </div>

depues colocar esto en el modelo solamente este ejemplo es mas sencillo que el anterior

public function getMunicipio(){
        if($this->id_municipio):
          $p = Municipios::findOne(['id_municipio'=>$this->id_municipio]);
          if ($p):
            $p = $p->desc_municipio;
          endif;
        else:
          $p = "";
        endif;
  
        return $p;
      }
  
       public function getParroquia(){
        if($this->id_parroquia):
          $p = Parroquias::findOne(['id_parroquia'=>$this->id_parroquia]);
          if ($p):
            $p = $p->desc_parroquia;
          endif;
        else:
          $p = "";
        endif;
  
        return $p;
      }
[acf field="field_name" post_id="123"]
add_action( 'acf/init', 'set_acf_settings' );
function set_acf_settings() {
    acf_update_setting( 'enable_shortcode', true );
}
// ==UserScript==
// @name         Chess.com Имена на Русском Языке
// @namespace    http://tampermonkey.net/
// @version      1.5
// @description  Автозамена английских имён на русские на chess.com с постоянным отслеживанием изменений интерфейса
// @author       Anton Kim
// @match        https://www.chess.com/*
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // Массив для замены текстов
    const replacements = {
        "Magnus Carlsen": "Магнус Карлсен",
        "Alireza Firouzja": "Алиреза Фирузджа",
        "Maxime Vachier-Lagrave": "Максим Вашье-Лаграв",
        "": "",
        "": "",
        "": "",
        // Добавьте другие имена здесь
    };

    // Кэширование обработанных узлов для предотвращения повторной обработки
    const processedNodes = new WeakSet();

    // Функция для замены текста на странице
    function replaceText(node) {
        if (node.nodeType === 3 && !processedNodes.has(node)) { // Проверяем, текст ли это и был ли он уже обработан
            let originalText = node.textContent;
            let newText = originalText;

            for (let [enName, ruName] of Object.entries(replacements)) {
                if (originalText.includes(enName)) { // Оптимизация: выполняем замену только если строка содержит имя
                    newText = newText.replace(new RegExp(enName, 'g'), ruName);
                }
            }

            // Заменяем текст только если были изменения
            if (newText !== originalText) {
                node.textContent = newText;
                processedNodes.add(node); // Кэшируем этот узел
            }
        }
    }

    // Функция для обхода всех узлов страницы
    function walk(node) {
        let child, next;

        switch (node.nodeType) {
            case 1:  // Элемент
            case 9:  // Документ
            case 11: // Фрагмент
                child = node.firstChild;
                while (child) {
                    next = child.nextSibling;
                    walk(child);
                    child = next;
                }
                break;

            case 3: // Текстовый узел
                replaceText(node);
                break;
        }
    }

    // Постоянный MutationObserver для слежения за изменениями интерфейса
    function observeMutations() {
        const observer = new MutationObserver(function(mutations) {
            mutations.forEach(function(mutation) {
                mutation.addedNodes.forEach(node => {
                    if (node.nodeType === 1) { // Только элементы
                        walk(node); // Проверяем новые узлы
                    }
                });

                // Также проверяем изменения текста в существующих узлах
                mutation.target.childNodes.forEach(node => {
                    if (node.nodeType === 3) { // Текстовые узлы
                        replaceText(node); // Обновляем текст при его изменении
                    }
                });
            });
        });

        // Наблюдаем за изменениями в body и всём поддереве
        observer.observe(document.body, { childList: true, subtree: true, characterData: true });
    }

    // Запуск функции сразу на загрузке страницы и отслеживание изменений
    walk(document.body);
    observeMutations();

})();
import math
import numpy as np
import pandas as pd
from typing import Tuple

def find_baseline_carti(mask: np.ndarray) -> Tuple[Tuple[int, int], Tuple[int, int]]:
    """
    Funkcja znajdująca baseline, który ma najwięcej punktów pokrywających się
    z górnym obrysem bony roof. Algorytm iteruje po pikselach wysuniętych
    najbardziej na prawo punktów bony roof, które są oddalone o 30 pikseli
    w górę i 10 pikseli w dół w celu zmniejszenia ilości obliczeń.

    Funkcja przyjmuje:
    - maskę w formacie png z zaznaczonymi strukturami
    Funkcja zwraca:
    - współrzędne prawego i lewego punktu baseline
    """
    height, width = mask.shape

    label_upper_contour_bony = 5
    label_upper_contour_carti = 4
    binary_mask_bony = (mask == label_upper_contour_bony).astype(np.uint8)
    binary_mask_carti = (mask == label_upper_contour_carti).astype(np.uint8)
    upper_contour_bony = []

    # Znalezienie punktów górnego obrysu bony roof
    for x in range(width):
        column_bony = binary_mask_bony[:, x]
        if np.any(column_bony):
            y_bony = np.where(column_bony)[0][0]
            upper_contour_bony.append((x, y_bony))

    # Znalezienie najbardziej na prawo wysuniętego punktu carti roof
    x_max_carti = -1
    for x in range(width):
        column_carti = binary_mask_carti[:, x]
        if np.any(column_carti):
            x_max_carti = x  # Ustalamy x_max_carti na najbardziej wysunięty na prawo punkt
            y_max_carti = np.where(column_carti)[0][0]  # Używamy tylko y, ale nie potrzebujemy

    # Ustalanie prawego punktu bony roof (+1 piksel w prawo)
    rightmost_point_x = x_max_carti + 1 if x_max_carti != -1 else None

    # Znalezienie punktu bony roof dla współrzędnej x = x_max_carti + 1
    bony_point_y = None
    if rightmost_point_x is not None and rightmost_point_x < width:
        column_bony = binary_mask_bony[:, rightmost_point_x]
        if np.any(column_bony):
            bony_point_y = np.where(column_bony)[0][0]  # Znajdź punkt na bony roof w kolumnie x_max_carti + 1

    # Definiowanie punktów startowych (iteracja 30 pikseli w górę i 10 w dół od punktu bony roof)
    start_points = []
    if bony_point_y is not None:
        start_points = [(rightmost_point_x, y) for y in range(max(0, bony_point_y - 5),
                                                              min(height, bony_point_y + 5))]

    best_line = []
    max_overlap = 0
    rightmost_point = (rightmost_point_x, bony_point_y) if rightmost_point_x is not None else (None, None)

    for x0, y0 in start_points:
        for angle in range(360):
            line_points = []

            angle_rad = math.radians(angle)
            sin_angle = math.sin(angle_rad)
            cos_angle = math.cos(angle_rad)

            # Definiujemy maksymalną liczbę kroków
            n_max = 2 * (width + height)
            n = np.arange(n_max)

            x = x0 + n * cos_angle
            y = y0 - n * sin_angle

            x_rounded = np.round(x).astype(int)
            y_rounded = np.round(y).astype(int)

            # Filtrujemy punkty znajdujące się w granicach obrazu
            valid_mask = (x_rounded >= 0) & (x_rounded < width) & \
                         (y_rounded >= 0) & (y_rounded < height)

            x_valid = x_rounded[valid_mask]
            y_valid = y_rounded[valid_mask]

            line_points = list(zip(x_valid, y_valid))

            # Obliczenie overlapu między linią a konturem
            overlap = len(set(line_points) & set((p for p in upper_contour_bony if p[0] <= rightmost_point_x)))
            if overlap > max_overlap:
                max_overlap = overlap
                best_line = line_points

    # Znalezienie najbardziej na lewo wysuniętego punktu linii
    leftmost_point = None
    if best_line:
        for point in best_line:
            x, y = point
            if mask[y, x] == label_upper_contour_bony:
                if leftmost_point is None or x < leftmost_point[0]:
                    leftmost_point = (x, y)

    if leftmost_point is None:
        leftmost_point = (None, None)

    return rightmost_point, leftmost_point


def find_baseline(mask: np.ndarray) -> Tuple[Tuple[int, int], Tuple[int, int]]:
    """
    Funkcja znajdująca baseline, który ma najwięcej punktów pokrywających się
    z górnym obrysem bony roof. Algorytm iteruje po pikselach wysuniętych
    najbardziej na prawo punktów bony roof, które są oddalone o 10 pikseli
    w górę i w dół w celu zmniejszenia ilości obliczeń.

    Funkcja przyjmuje:
    - maskę w formacie png z zaznaczonymi strukturami
    Funkcja zwraca:
    - współrzędne prawego i lewego punktu baseline
    """
    height, width = mask.shape

    label_upper_contour = 5
    binary_mask = (mask == label_upper_contour).astype(np.uint8)
    upper_contour = []

    # Znalezienie punktów górnego obrysu (konturu)
    for x in range(width):
        column = binary_mask[:, x]
        if np.any(column):
            y = np.where(column)[0][0]
            upper_contour.append((x, y))

    # Znalezienie najbardziej na prawo wysuniętego punktu
    x_max = max(p[0] for p in upper_contour)
    y_max = max(p[1] for p in upper_contour if p[0] == x_max)

    # Iterowanie po pikselach znajdujących się 30 pikseli ponad i 10
    # pikseli podnajbardziej wysuniętymi na prawo punktami bony roof

    start_points = [(x, y) for x, y in upper_contour if x == x_max] +\
        [(x_max, y) for y in range(max(0, y_max - 30),
                                   min(height, y_max + 10))]

    best_line = []
    max_overlap = 0
    rightmost_point = None

    for x0, y0 in start_points:
        for angle in range(360):
            line_points = []

            angle_rad = math.radians(angle)
            sin_angle = math.sin(angle_rad)
            cos_angle = math.cos(angle_rad)

            # Definiujemy maksymalną liczbę kroków
            n_max = 2 * (width + height)
            n = np.arange(n_max)

            x = x0 + n * cos_angle
            y = y0 - n * sin_angle

            x_rounded = np.round(x).astype(int)
            y_rounded = np.round(y).astype(int)

            # Filtrujemy punkty znajdujące się w granicach obrazu
            valid_mask = (x_rounded >= 0) & (x_rounded < width) & \
                (y_rounded >= 0) & (y_rounded < height)

            x_valid = x_rounded[valid_mask]
            y_valid = y_rounded[valid_mask]

            line_points = list(zip(x_valid, y_valid))

            # Obliczenie overlapu między linią a konturem
            overlap = len(set(line_points) & set(upper_contour))
            if overlap > max_overlap:
                max_overlap = overlap
                best_line = line_points
                rightmost_point = (x0, y0)

    # Znalezienie najbardziej na lewo wysuniętego punktu linii
    leftmost_point = None
    if best_line:
        for point in best_line:
            x, y = point
            if mask[y, x] == label_upper_contour:
                if leftmost_point is None or x < leftmost_point[0]:
                    leftmost_point = (x, y)

    if leftmost_point is None:
        leftmost_point = (None, None)

    return rightmost_point, leftmost_point


def old_find_baseline(class_mask: np.ndarray) -> Tuple[
        Tuple[int, int] | None, Tuple[int, int] | None]:
    """Bazując na położeniu bony i carti roof określa punkt początkowy
    oraz końcowy baseline dla maksymalnej odległości do 5 pikseli.
    Algorytm przeszukuje obszar jednego piksela dookoła (czyli 3x3),
    a jeżeli nie znajdzie punktów, to zwiększa obszar poszukiwań aż
    do progu jakim jest 5 pikseli. Dodatkowo na początku algorytm
    zawęża obszar poszukiwań tylko do obszarów bony roof i carti
    roof oraz pikselom im sąsiadującym

    Args:
        class_mask (np.ndarray): Maska wygenerowana z txt

    Returns:
        Współrzędne punktów baseline
    """
    mask_4_indices = np.argwhere(class_mask == 4)
    mask_5_indices = np.argwhere(class_mask == 5)
    if mask_4_indices.size == 0 or mask_5_indices.size == 0:
        return None, None

    min_y = max(0, min(np.min(mask_4_indices[:, 0]), np.min(mask_5_indices[
        :, 0])))
    max_y = min(class_mask.shape[0], max(np.max(mask_4_indices[:, 0]), np.max(
        mask_5_indices[:, 0])))
    min_x = max(0, min(np.min(mask_4_indices[:, 1]), np.min(
        mask_5_indices[:, 1])))
    max_x = min(class_mask.shape[1], max(np.max(mask_4_indices[:, 1]), np.max(
        mask_5_indices[:, 1])))

    for distance in range(1, 6):
        right_point = None
        left_point = None

        for y in range(min_y, max_y + 1):
            for x in range(min_x, max_x + 1):
                surroundings = class_mask[max(0, y - distance):min(
                    class_mask.shape[0], y + distance + 1),
                                          max(0, x - distance):min(
                                        class_mask.shape[1], x + distance + 1)]
                if (surroundings == 5).any() and (surroundings == 4).any():
                    if right_point is None or (x > right_point[0] or (
                            x == right_point[0] and y > right_point[1])):
                        right_point = (x, y)
                    if left_point is None or (x < left_point[0] or (
                            x == left_point[0] and y > left_point[1])):
                        left_point = (x, y)

        if right_point is not None and left_point is not None:
            if distance == 5 and right_point == left_point:
                left_point = (left_point[0] - 1, left_point[1])

            if right_point == left_point:
                continue

            return right_point, left_point

    return None, None


import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image

# Słownik kolorów dla poszczególnych klas
CLASS_COLORS = {
    0: {'color_rgb': (0, 0, 0), 'label': 'background'},
    1: {'color_rgb': (255, 0, 0), 'label': 'chondroosseous border'},
    2: {'color_rgb': (0, 255, 0), 'label': 'femoral head'},
    3: {'color_rgb': (0, 0, 255), 'label': 'labrum'},
    4: {'color_rgb': (255, 255, 0), 'label': 'cartilagineous roof'},
    5: {'color_rgb': (0, 255, 255), 'label': 'bony roof'},
    6: {'color_rgb': (159, 2, 250), 'label': 'bony rim'},
    7: {'color_rgb': (255, 132, 0), 'label': 'lower limb'},
    8: {'color_rgb': (255, 0, 255), 'label': 'baseline'},
    9: {'color_rgb': (66, 135, 245), 'label': 'lower limb template'},
    10: {'color_rgb': (255, 69, 0), 'label': 'lower limb - alg. v3'}
}

def visualize_masks_with_baseline(masks_dir: str, output_directory: str):
    # Upewnij się, że katalog wyjściowy istnieje
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    # Iterowanie po katalogu z maskami
    for mask_filename in os.listdir(masks_dir):
        if mask_filename.endswith('.png'):
            mask_path = os.path.join(masks_dir, mask_filename)
            mask = cv2.imread(mask_path, cv2.IMREAD_GRAYSCALE)  # Wczytaj maskę w skali szarości

            # Znajdź punkty baseline za pomocą nowego algorytmu
            rightmost_point, leftmost_point = find_baseline_carti(mask)

            # Debug: Sprawdzenie punktów
            print(f"Maska: {mask_filename}, Punkt prawy: {rightmost_point}, Punkt lewy: {leftmost_point}")

            # Stwórz obraz RGB, na który będziemy rysować
            mask_rgb = np.zeros((mask.shape[0], mask.shape[1], 3), dtype=np.uint8)

            # Iteracja po klasach w masce i kolorowanie
            for class_value, class_info in CLASS_COLORS.items():
                mask_rgb[mask == class_value] = class_info['color_rgb']

            # Rysowanie białej linii między punktami zwróconymi przez find_baseline
            if rightmost_point and leftmost_point and rightmost_point != (None, None) and leftmost_point != (None, None):
                cv2.line(mask_rgb, rightmost_point, leftmost_point, (255, 255, 255), 1)  # Biała linia
                cv2.circle(mask_rgb, rightmost_point, 1, (255, 255, 255), -1)  # Prawy punkt
                cv2.circle(mask_rgb, leftmost_point, 1, (255, 255, 255), -1)  # Lewy punkt

            # Zapisz wizualizację do katalogu
            output_path = os.path.join(output_directory, f'visualization_{mask_filename}')
            cv2.imwrite(output_path, mask_rgb)

            # Wyświetlenie obrazu
            plt.figure(figsize=(10, 10))
            plt.imshow(cv2.cvtColor(mask_rgb, cv2.COLOR_BGR2RGB))  # Zamiana na RGB dla wyświetlenia
            plt.title(f'Visualization for {mask_filename}')
            plt.axis('off')

# Przykładowe wywołanie funkcji
masks_directory = './Angles/dane/masks_baseline'
output_directory = './Angles/dane/visualizations_carti'
#visualize_masks_with_baseline(masks_directory, output_directory)


import os
import numpy as np
import matplotlib.pyplot as plt
from typing import Tuple, List
import math

def slope(x1: int, y1: int, x2: int, y2: int) -> float:
    """Calculates the slope of the line through two points."""
    # Sprawdzanie czy punkty są None
    if None in (x1, y1, x2, y2):
        print(f"Invalid slope points: ({x1}, {y1}), ({x2}, {y2}). Skipping.")
        return None  # Zwracamy None, aby pominąć obliczenia

    if x2 - x1 == 0:  # Unikamy dzielenia przez 0
        return float('inf')  # Linia pionowa
    return (y2 - y1) / (x2 - x1)

def find_angle(line1_point1: Tuple[int, int],
               line1_point2: Tuple[int, int],
               line2_point1: Tuple[int, int],
               line2_point2: Tuple[int, int],
               return_absolute_value: bool = True) -> float:
    """Finds the angle between two lines."""
    if len(line1_point1) != 2 or len(line1_point2) != 2 or \
            len(line2_point1) != 2 or len(line2_point2) != 2:
        print('Point with wrong number of coordinates')
        return np.NaN  # Zwracamy NaN zamiast zgłaszać wyjątek
        
    M1 = slope(line1_point1[0], line1_point1[1], line1_point2[0], line1_point2[1])
    M2 = slope(line2_point1[0], line2_point1[1], line2_point2[0], line2_point2[1])

    PI = 3.14159265

    # Sprawdzamy, czy M1 i M2 nie są None
    if M1 is None or M2 is None:
        print(f"Invalid slopes: M1={M1}, M2={M2}. Skipping angle calculation.")
        return None

    if M2 != float('inf') and M1 * M2 != -1:
        if return_absolute_value:
            angle = abs((M2 - M1) / (1 + M1 * M2))
        else:
            angle = (M2 - M1) / (1 + M1 * M2)

        ret = math.atan(angle)
        val = (ret * 180) / PI
        return round(val, 1)

    elif M1 * M2 == -1:
        return 90.0
    else:
        return np.NaN

def read_doctor_coordinates(file_path: str) -> Tuple[Tuple[int, int], Tuple[int, int]]:
    """Reads doctor coordinates from a text file."""
    with open(file_path, 'r') as file:
        lines = file.readlines()
        
        if len(lines) < 2:
            return None, None
        
        try:
            point1 = tuple(map(int, lines[-2].strip().split()))
            point2 = lines[-1].strip()
            
            if point2 == "0":
                return None, None
            
            point2 = tuple(map(int, point2.split()))
        except ValueError as e:
            print(f"Error reading coordinates from {file_path}: {e}")
            return None, None
        
        return point1, point2

def calculate_angle(pt1: Tuple[int, int], pt2: Tuple[int, int], baseline: Tuple[Tuple[int, int], Tuple[int, int]]) -> float:
    """Calculates the angle between the line formed by pt1 and pt2 and the baseline."""
    # Check if points are None
    if pt1 is None or pt2 is None or baseline[0] is None or baseline[1] is None:
        print(f"Invalid points: pt1={pt1}, pt2={pt2}, baseline={baseline}. Skipping.")
        return None  # Return None to skip the calculation

    angle_doctor = find_angle(pt1, pt2, baseline[0], baseline[1], return_absolute_value=False)
    
    if angle_doctor is None:
        return None
    
    angle_baseline = find_angle(baseline[0], baseline[1], baseline[0], baseline[1], return_absolute_value=True)

    angle_diff = angle_baseline - angle_doctor
    return angle_diff

def compare_baselines_to_doctor(masks_dir: str, coords_dir: str, method: int) -> np.ndarray:
    """Compares baseline methods with doctor's coordinates and generates a histogram."""
    angle_diffs = []

    for filename in os.listdir(masks_dir):
        if not filename.endswith('.png'):
            continue
        
        mask_path = os.path.join(masks_dir, filename)
        coords_path = os.path.join(coords_dir, filename.replace('.png', '.txt'))
        
        doctor_coords = read_doctor_coordinates(coords_path)
        if doctor_coords == (None, None):
            print(f"Skipping file {coords_path}, invalid doctor coordinates.")
            continue
        
        mask = np.array(Image.open(mask_path))
        
        if method == 1:
            rightmost, leftmost = find_baseline_carti(mask)
        elif method == 2:
            rightmost, leftmost = find_baseline(mask)
        elif method == 3:
            rightmost, leftmost = old_find_baseline(mask)
        else:
            raise ValueError("Invalid method specified.")
        
        if rightmost is None or leftmost is None:
            print(f"Skipping file {mask_path}, invalid baseline points.")
            continue

        baseline = (leftmost, rightmost)
        
        angle_diff = calculate_angle(doctor_coords[0], doctor_coords[1], baseline)
        if angle_diff is not None:
            angle_diffs.append(angle_diff)

    return np.array(angle_diffs)

def plot_histogram(angle_diffs: np.ndarray):
    """Plots histogram of angle differences."""
    plt.figure(figsize=(10, 6))
    
    if angle_diffs.size == 0:
        print("No angle differences to plot.")
        return

    mean_angle = np.mean(angle_diffs)
    std_angle = np.std(angle_diffs)
    
    plt.hist(angle_diffs, bins=np.linspace(-15, 15, 30), edgecolor='black')
    
    plt.title(f'Histogram of Angle Differences - Wersja najstarsza\nMean: {mean_angle:.2f}°, Std: {std_angle:.2f}°')
    plt.xlabel('Angle Difference (degrees)')
    plt.ylabel('Frequency')
    plt.xlim(-15, 15)
    plt.grid(axis='y')
    plt.axvline(0, color='red', linestyle='dashed', linewidth=1)
    plt.show()

# Example usage:
masks_directory = './Angles/dane/masks_baseline'
coords_directory = './Angles/dane/templates_baseline'
method_type = 3  # Choose the method (1, 2, or 3)
angle_differences = compare_baselines_to_doctor(masks_directory, coords_directory, method_type)
plot_histogram(angle_differences)
import WithHeaderFooter from "hocs/withHeaderFooter";
import { AppProps } from "next/app";
import Head from "next/head";
import { useRouter } from "next/router";
import Script from "next/script";
import { metaData } from "public/js/metaData.constants";
import "react-datepicker/dist/react-datepicker.css";
import { Toaster } from "react-hot-toast";
import "styles/base.scss";
import "../styles/globals.modules.scss";

function MyApp({ Component, pageProps }: AppProps) {


  const router = useRouter();
  const currentPath = router.asPath;
  const currentMeta = metaData.find((meta) => meta.route == currentPath);
  let is404;
  const test = ["/careers/job-apply-form?jobId=", "/careers/job-apply?jobId="];
  if (!test.includes(router.asPath)) {
    is404 = Component.name === "Custom404";
  }

  return (
    <>
      <Script
        src="https://www.googletagmanager.com/gtag/js?id=G-WK6PVRZXQ8"
        strategy="afterInteractive"
      />
      <Script id="google-analytics" strategy="afterInteractive">
        {`
            window.dataLayer = window.dataLayer || [];
            function gtag(){window.dataLayer.push(arguments);}
            gtag('js', new Date());
  
            gtag('config', 'G-WK6PVRZXQ8');
          `}
      </Script>
      <Head>
        <meta charSet="UTF-8" />
        <link rel="canonical" href="http://www.coditas.com/" />
        <link rel="icon" type="image/svg+xml" href="/favicon.ico" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta
          property="og:image"
          content={
            currentMeta?.image
              ? currentMeta?.image
              : "https://events-cover.s3.ap-south-1.amazonaws.com/Coditas.png"
          }
        />
        <meta
          name="google-site-verification"
          content="SCDCX0bd5CKrf4fnq6kdCSmuiFAJMzJX5eVXBUfwHXA"
        />
        <meta
          property="og:description"
          content={
            currentMeta?.description ||
            "Transform your business with Generative AI-powered Product Engineering, Legacy Modernization, and Design to thrive in the digital age."
          }
        />
        <meta
          property="title"
          content={
            currentMeta?.title ||
            "Coditas | Building Exceptional Software Solutions with Clean Code Practices"
          }
        />
        <meta
          property="og:title"
          content={
            currentMeta?.title ||
            "Coditas | Building Exceptional Software Solutions with Clean Code Practices"
          }
        />
        <meta property="og:type" content="website" />
        <meta property="og:url" content="https://www.coditas.com" />
        <meta
          name="description"
          content={
            currentMeta?.description ||
            "Transform your business with Generative AI-powered Product Engineering, Legacy Modernization, and Design to thrive in the digital age."
          }
        />
        <meta
          name="keywords"
          content={
            currentMeta?.keywords ||
            "Software development services, Product engineering, Legacy modernization, Digital transformation solutions, UIUX design, DevOps Services, Generative AI solutions, AI-powered product engineering, Mobile app development, Cloud solutions, Coditas"
          }
        />
        <meta
          name="image"
          content={
            currentMeta?.image
              ? currentMeta?.image
              : "https://events-cover.s3.ap-south-1.amazonaws.com/Coditas.png"
          }
        />
        <title>
          {currentMeta?.title ||
            "Coditas | Building Exceptional Software Solutions with Clean Code Practices"}
        </title>
      </Head>
      {is404 ? (
        <Component {...pageProps} />
      ) : (

        <WithHeaderFooter headerData={pageProps?.headerData} footerData={pageProps?.footerData}>
          <Component {...pageProps} />
          <Toaster />
        </WithHeaderFooter>
      )}
    </>
  );
}




export default MyApp;
#include <iostream>
using namespace std;

// Function to sort the array using bubble sort algorithm.
void processBubbleSort(int arr[], int n) 
{
  while(n != 0)
  {
      for(int i = 0; i < n-1; i++)
      {
          if(arr[i] > arr[i+1])
          {
              int temp = arr[i];
              arr[i] = arr[i+1];
              arr[i+1] = temp;
          }
      }
      --n;
  }
}

void displayArray(int arr[], int n) {
  for (int i = 0; i < n; i++) {
    cout << arr[i] << " ";
  }
  cout << endl;
}

// Function to dynamically allocate an array and fill it with random values.
void fillDynamicArrayWithRandomValues(int** arr, int* n) {
    cout << "Enter the size of the array: ";
    cin >> *n;
    *arr = new int[*n];
    srand(time(0)); // Seed for random number generation
    for (int i = 0; i < *n; i++) {
        (*arr)[i] = rand() % 1000; // Fill with random numbers between 0 and 999
    }
}

int main() {
    int* arr;
    int n;
    fillDynamicArrayWithRandomValues(&arr, &n);
    cout << "Unsorted array: ";
    displayArray(arr, n);
    processBubbleSort(arr, n);
    cout << "Sorted array: ";
    displayArray(arr, n);
    delete[] arr; // Deallocate dynamically allocated memory
    return 0;
}
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>children - DOM</title>
  </head>
  <body>
    <ul id="result">
        <li>Apple</li>
        <li>Orange</li>
        <li>Banana</li>
        <li>Pear</li>
        <li>Tamato</li>
    </ul>

    <div id="parent">
      <p>
        Lorem ipsum dolor, sit amet consectetur adipisicing elit. Non laboriosam
        quas fuga libero vero autem vel maiores animi rerum! Ab quod quo sunt
        beatae et veniam suscipit praesentium fuga maxime?
      </p>
      <span
        >Lorem ipsum dolor sit amet consectetur adipisicing elit. Hic facere
        ipsa at adipisci dolorem iure qui nostrum odio, vero ducimus debitis
        sapiente quis iste aperiam odit fugiat velit aut necessitatibus?
      </span>
      <p>
        Lorem ipsum dolor sit amet consectetur adipisicing elit. Alias eum
        excepturi reprehenderit quisquam dignissimos cum temporibus non omnis
        sequi quasi obcaecati consequatur cupiditate possimus eius, beatae,
        dolores accusantium maiores ipsum.
      </p>
    </div>

    <script src="children.js"></script>
  </body>
</html>



const result = document.getElementById("parent");

//---------- All Children with white spaceas ---------- //
const allChildren = result.childNodes;
console.log(allChildren);

//---------- Only Tags Nodes without White space ---------- //
const chilDren = result.children;
console.log(chilDren);

//---------- First child (text) ---------- //
const first_Child = result.firstChild;
console.log(first_Child);

//---------- First child (Node) ---------- //
const first_Child = result.firstElementChild;
console.log(first_Child);


//---------- Last child (text)---------- //
const last_Child = result.lastChild;
console.log(last_Child);

//---------- Last child (Node)---------- //
const last_Child = result.lastElementChild;
console.log(last_Child);
int age = 35;

if(age >= 30)
{
    if(age < 40)
    {
        Debug.Log("Age is in the thirties!");


    }
}
int age = 35;

if(age >= 30 && age < 40)
{
    Debug.Log("Age is in the thirties!");
}
star

Sat Oct 26 2024 11:48:33 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 10:03:40 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 09:35:20 GMT+0000 (Coordinated Universal Time) https://lazyadmin.nl/win-11/turn-off-windows-defender-windows-11-permanently/

@Curable1600 #windows

star

Sat Oct 26 2024 09:31:43 GMT+0000 (Coordinated Universal Time) https://github.com/orgs/community/discussions/139005

@Ashsebahay0323_

star

Sat Oct 26 2024 09:28:15 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 09:01:51 GMT+0000 (Coordinated Universal Time)

@signup #html #javascript

star

Sat Oct 26 2024 08:26:18 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Sat Oct 26 2024 06:34:03 GMT+0000 (Coordinated Universal Time) https://maticz.com/p2p-cryptocurrency-exchange-development

@jamielucas #nodejs

star

Sat Oct 26 2024 03:23:34 GMT+0000 (Coordinated Universal Time) https://developer.chrome.com/blog/new-in-devtools-130/?utm_source

@Ashsebahay0323_

star

Sat Oct 26 2024 01:44:49 GMT+0000 (Coordinated Universal Time) https://www.geeksforgeeks.org/encoding-and-decoding-base64-strings-in-python/

@jrb9000 #python

star

Fri Oct 25 2024 20:59:03 GMT+0000 (Coordinated Universal Time) https://www.go2bank.com/?utm_medium

@Ashsebahay0323_

star

Fri Oct 25 2024 19:12:59 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Fri Oct 25 2024 18:31:19 GMT+0000 (Coordinated Universal Time) https://element.how/elementor-close-off-canvas-on-anchor-link-click/

@webisko #javascript

star

Fri Oct 25 2024 13:30:04 GMT+0000 (Coordinated Universal Time)

@banch3v

star

Fri Oct 25 2024 12:21:57 GMT+0000 (Coordinated Universal Time) https://editor.p5js.org/

@seb_prjcts_be

star

Fri Oct 25 2024 09:17:55 GMT+0000 (Coordinated Universal Time)

@SVELTRON #php

star

Fri Oct 25 2024 07:44:53 GMT+0000 (Coordinated Universal Time) https://myaccount.google.com/apppasswords?pli

@jwhitlow5

star

Fri Oct 25 2024 06:57:58 GMT+0000 (Coordinated Universal Time) https://innosoft-group.com/sports-betting-software-development/

@johnstone #sportsbetting app developers #bettingapp development company #sportsbetting app development

star

Fri Oct 25 2024 05:50:03 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Fri Oct 25 2024 05:20:41 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Fri Oct 25 2024 02:11:21 GMT+0000 (Coordinated Universal Time) https://matplotlib.org/stable/users/explain/colors/colormaps.html

@theshyxin

star

Fri Oct 25 2024 00:33:07 GMT+0000 (Coordinated Universal Time) https://eda-ai-lab.tistory.com/580

@wheedo

star

Thu Oct 24 2024 16:10:33 GMT+0000 (Coordinated Universal Time) undefined

@kirexmak

star

Thu Oct 24 2024 13:38:52 GMT+0000 (Coordinated Universal Time) https://www.dabapps.com/insights/api-performance-profiling-django-rest-framework/

@fearless

star

Thu Oct 24 2024 10:11:01 GMT+0000 (Coordinated Universal Time)

@sarathkishore

star

Thu Oct 24 2024 08:18:16 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Oct 24 2024 07:16:08 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Thu Oct 24 2024 07:10:49 GMT+0000 (Coordinated Universal Time) https://www.bestwebsite.com

@Webvfix #laravel

star

Thu Oct 24 2024 06:12:32 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Thu Oct 24 2024 05:26:18 GMT+0000 (Coordinated Universal Time)

@WXAPAC

star

Thu Oct 24 2024 04:21:20 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Thu Oct 24 2024 02:19:44 GMT+0000 (Coordinated Universal Time) https://hivebrite.com/documentation/api/admin

@acassell

star

Wed Oct 23 2024 21:55:14 GMT+0000 (Coordinated Universal Time)

@RehmatAli2024 #deluge

star

Wed Oct 23 2024 19:52:13 GMT+0000 (Coordinated Universal Time)

@freepythoncode ##python #coding #python #programming

star

Wed Oct 23 2024 14:23:07 GMT+0000 (Coordinated Universal Time)

@jrg_300i #undefined

star

Wed Oct 23 2024 13:09:45 GMT+0000 (Coordinated Universal Time)

@webisko

star

Wed Oct 23 2024 12:55:49 GMT+0000 (Coordinated Universal Time)

@webisko #php

star

Wed Oct 23 2024 12:48:55 GMT+0000 (Coordinated Universal Time) https://antonkim.ru/chess/all/auto-replace-english-names-to-russian-names-on-chess-com/

@Artemsikin

star

Wed Oct 23 2024 12:47:42 GMT+0000 (Coordinated Universal Time)

@dphillips #typoscript #typo3 #ckeditor

star

Wed Oct 23 2024 10:41:18 GMT+0000 (Coordinated Universal Time)

@mateusz021202

star

Wed Oct 23 2024 07:34:03 GMT+0000 (Coordinated Universal Time)

@2late

star

Wed Oct 23 2024 07:21:17 GMT+0000 (Coordinated Universal Time) https://medium.com/cryptocurrency-scripts/key-considerations-to-develop-nft-marketplace-ab3fccd61fad

@LilianAnderson #nftmarketplacedevelopment #nftplatformcreation #nftbusinesssuccess #nftdevelopmentcost #nftentrepreneurs

star

Wed Oct 23 2024 06:59:33 GMT+0000 (Coordinated Universal Time)

@akanksha #react.js #typescript

star

Wed Oct 23 2024 06:43:53 GMT+0000 (Coordinated Universal Time)

@Rohan@99

star

Wed Oct 23 2024 02:33:19 GMT+0000 (Coordinated Universal Time) https://memo.cash/protocol

@Tanawat90 #go #nodejs #actionscript3 #javascript

star

Wed Oct 23 2024 00:14:23 GMT+0000 (Coordinated Universal Time) https://academy.zenva.com/lesson/conditional-operators-2/?zva_less_compl

@r2ks

Save snippets that work with our extensions

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