Snippets Collections
parse_git_branch() {
    git branch 2> /dev/null | sed -n -e 's/^\* \(.*\)/[\1]/p'
}
COLOR_DEF='%f'
COLOR_USR='%F{15}'
COLOR_DIR='%F{120}'
COLOR_GIT='%F{39}'
NEWLINE=$'\n'
setopt PROMPT_SUBST
export PROMPT='${COLOR_USR}%n@%M ${COLOR_DIR}%d ${COLOR_GIT}$(parse_git_branch)$

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This load$


# Load Angular CLI autocompletion.
source <(ng completion script)
define('DISALLOW_FILE_EDIT', true);
define('DISALLOW_FILE_MODS', true);
/-----------remove dashboard menu globaly-------------------/

add_action('admin_menu', 'plt_hide_woocommerce_menus', 71);
function plt_hide_woocommerce_menus() {
    global $submenu , $menu;
    remove_menu_page( 'index.php' );
        remove_menu_page( 'edit-comments.php' );
        remove_menu_page( 'options-general.php' );
        remove_menu_page( 'themes.php' );
        remove_menu_page( 'plugins.php' );
        remove_menu_page( 'users.php' );
        remove_menu_page( 'tools.php' );
        remove_menu_page( 'edit.php?post_type=woodmart_sidebar' );
        remove_menu_page( 'edit.php?post_type=portfolio' );
        remove_menu_page( 'edit.php?post_type=woodmart_layout' );
        remove_menu_page( 'vc-general' );
        remove_menu_page( 'getwooplugins' );
        remove_menu_page( 'xts_theme_settings' );
        remove_menu_page( 'xts_dashboard' );
        remove_action('admin_footer', 'wp_admin_footer');
        remove_action('wp_footer', 'wp_generator');
        remove_filter('update_footer', 'core_update_footer');
        add_filter('admin_footer_text', '__return_empty_string');
}
//STRING TO ARRAY
function split(S) {
    let i = 0;
    let result = [];
    
    while(char_at(S, i) !== undefined){
        result[i] = char_at(S,i);
        i = i + 1;
    }
    
    return result;
}

//String to stream:
// your helper functions go here
function split(s) {
    let i = 0;
    let result = [];
    
    while(char_at(s, i) !== undefined){
        result[i] = char_at(s,i);
        i = i + 1;
    }
    
    return result;
}

//Alternatively:
//ARRAYS TO LIST AND LISTS TO ARRAYS
function array_to_list(arr){
    let res = null;
    const len = array_length(arr);
    for (let i = 1; i <= len; i = i + 1){
        res = pair(arr[len - i], res);
    }
    return res;
}

function string_to_list (s){
        const new_list = array_to_list(split(s));
        return new_list;
    }
function list_to_stream(lst){
        return is_null(lst)
               ? null 
               : pair(head(lst), ()=> list_to_stream(tail(lst)));
    }
function char_stream(s) {
    return list_to_stream(string_to_list(s));
}

//Searching 2 arrays for matching elements
function contains(B, A_i) {
    const len = array_length(B);
    
    for (let j = 0; j < len; j = j + 1){
    if (B[j] === A_i){
        return true;
      }
    }
    return false;
}

function num_characters_from(A, B) {
    let result = 0;
    for (let i = 0; i < array_length(A); i = i + 1){
        if (contains(B, A[i])){
            result = result + 1;
        }
    }
    return result;
}

//ARRAYS TO LIST AND LISTS TO ARRAYS
function runlength_decode(R) {
    const RA = list_to_array(R);
    const res = [];
    for (let i = 0; i < array_length(RA); i = i + 1){
    if (is_number(RA[i])){
        res[array_length(res)] = RA[i];
    } else {
        //RA[i] is a pair
        const item = head(RA[i]);
        const quantity = tail(RA[i]);
        for (let j = 0; j < quantity; j = j + 1){
            res[array_length(res)] = item;
        }
      }
    }
    return array_to_list(res);
}

function list_to_array(xs){
    const res = [];
    let current_pair = xs;
    while (!is_null(current_pair)){
        res[array_length(res)] = head(current_pair);
        current_pair = tail(current_pair);
    }
    return res;
}

function array_to_list(arr){
    let res = null;
    const len = array_length(arr);
    for (let i = 1; i <= len; i = i + 1){
        res = pair(arr[len - i], res);
    }
    return res;
}






//SEARCHING
//1. Generalised Search
function search_cond(A, cond) {
    const len = array_length(A);
    
    for (let i = 0; i < len; i = i + 1){
        if (cond(A[i])){
            return i;
        } 
    }
    return -1;
}
/*
Approach:
1. Loop through each element of array
2. Check is predicate condition returns true
3. If true, return i of A[i]
4. If no element in loop returns true, then return -1 instead.

Other case: empty array --> -1
*/


//2. INSERTION
function insert(A, pos, x){
    let len = array_length(A);
    len = len + 1;
    for (let i = len - 2; i >= pos; i = i-1){
        A[i + 1] = A[i];
    }
    A[pos] = x;
}

/*
inputs: Array, position and element

Input validity: 
- Position needs to be within array length

output: function should return inserted array, with array length modified

code structure:
1. Expand array: increase length by 1 to make space
2. Shifting: Start from last element, shift each element one spot to the right 
   until you reach position, leaving an empty space at position
3. Insert x into empty space

Loop condition: i > = pos
*/

//3. Insertion Sort
function insertion_sort(A) {
    let sorted_array = [];
    let len = array_length(A);
    
    for ( let i = 0; i < len; i=i+1){
        let x = A[i];
        let pos = search_cond(sorted_array, y => y > x);
        
        if (pos === -1) {
            pos = array_length(sorted_array);
        }
        
        insert(sorted_array, pos, x);
    }
    
    return sorted_array;
}

/*
1. Create a new array: sorted_array
2. Iterate over elements of original array
3. Use search_cond to find validity to insert into sorterd_array
*/
:target::before {
  content: "";
  display: block;
  height: 60px; /* fixed header height*/
  margin: -60px 0 0; /* negative fixed header height */
}
Or:
html {
  scroll-padding-top: 70px; /* height of sticky header */
}

Or use jquery:
var offset = $(':target').offset();
var scrollto = offset.top - 60; // minus fixed header height
$('html, body').animate({scrollTop:scrollto}, 0);
lb config noauto \
--mode "debian" \
--distribution "stretch" \
--archive-areas "main" \
\
--GNU Plus Linux-package "GNU Plus Linux-image GNU Plus Linux-headers" \
--bootloader "syslinux,grub-efi" \
--system "live" \
--binary-filesystem "fat32" \
--binary-images "iso-hybrid" \
\
--security "true" \
--updates "true" \
--backports "false" \
--apt-recommends "true" \
--apt-secure "true" \
--apt-indices "true" \
--apt-source-archives "false" \
\
--debian-installer "live" \
--debian-installer-gui "true" \
--debian-installer-distribution "stretch" \
\
--firmware-binary "true" \
--firmware-chroot "true" \
--iso-application "debian9" \
--iso-volume "debian9" \
--win32-loader "false" \
--clean \
--debug \
--verbose \
--source "false" \
"${@}"
///////////////************* HEAPS ***************/////////////////


//// WHAT IS HEAP ?
// complete binary tree comes with a complete binary tree properies as well as heap order property ...

// what is complete binary tree? 
// every level is full filled (fully filled means every parent node have 2 children and always filled from left side only  )  except the last level  nodes always added on left.. 

//// HEAPS PROPERTY
// MAX HEAP = parent ka child humesha use CHOTA honga 
// MIN HEAP = parent ka child humesha use BADA honga 

// suppose node index is i
// so, its left child will be at (2*i)th index.
// so, its right child will be at ((2*i)+1th) index.
// so, its parent will be at (i/2)


///MAP HEAP INSERTION
//STEP1 - INSERT AT THE END 
//STEP2 - COMAPRE IT WITH ITS PARENT NODE IF IT IST BIGGER THAN IT SHIFT IT TO THE TOP (FORMULA WE WILL USE PARENT = INDEX OF CHILD / 2)

// DELETION IN AN HEAP 
//STEP1 - REPALCE THE ROOT NODE WITH LAST NODE (SWAPPED)
//STEP2 - DELETE THE ROOT NODE NOW 
//STEP3 - COMPARE IT WITH ITS ALL CHILDREN AND REPLACE IT WITH MAX HEAP PROPERTY

///////////*** insertion in max heap ************///////////////
#include <iostream>
using namespace std;

class heap
{
    public:
    int arr[100];
    int size;
    
    heap()
    {
        arr[0] = -1;
        size = 0;
    }
    
    void insert(int val){
        
        size = size + 1 ;
        int index = size;
        arr[index] = val ;
        while(index > 1){
            int parent = index/2;
            
            if(arr[parent] < arr[index]){
                swap(arr[parent],arr[index]);
                index = parent;
            }
            else{
                return;
            }
        }
    }
    
    void print(){
        for(int i = 1 ; i<=size; i++){
            cout << arr[i] << " ";
        }cout<< endl;
    }

    void deletefromHeap()
    {
        if(size == 0){
            cout << "nothing to delete "<< endl;
            return;
        }
        
        // Step 1: Replace root with last element
        arr[1] = arr[size];
        size--;
        
        // Step 2: Take root to its correct position
        int i = 1;
        while(i <= size) // Fix: changed condition to `<= size` to avoid out of bounds
        {
            int leftIndex = 2 * i;
            int rightIndex = 2 * i + 1;
            int largest = i;
        
            // Check if left child exists and is greater
            if(leftIndex <= size && arr[largest] < arr[leftIndex])
            {
                largest = leftIndex;
            }

            // Check if right child exists and is greater
            if(rightIndex <= size && arr[largest] < arr[rightIndex])
            {
                largest = rightIndex;
            }

            // If largest is still the parent node, break the loop
            if(largest == i) {
                break;
            }

            // Swap with the largest child and continue down the heap
            swap(arr[i], arr[largest]);
            i = largest;
        }
    }
};

int main()
{
    heap h;
    h.insert(6);
    h.insert(54);
    h.insert(57);
    h.insert(59);
    h.insert(58);
    h.print();
    
    // Delete the root of the heap
    h.deletefromHeap();
    cout << "After deleting root: ";
    h.print();
    
    return 0;
}
/////////////////*************DELETION IN BST ***********/////////////////

///////// 3 CASES ////////////

/////// 0 CHILD = delete that node and  directlty return null


/////// 1 CHILD 
/// store the child one in temp and than delete the node and add temp one in bst 

////////2 children 
///  replace the favourable node with highest value in left child and than delete the favourable node frm tree.....
#include <iostream>
#include <queue>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int d) {
        this->data = d;
        this->left = NULL;
        this->right = NULL;
    }
};

Node* insertIntoBST(Node* root, int d) {
    // base case 
    if (root == NULL) {
        root = new Node(d); // Create a new node
        return root; // Return the newly created node
    }
    if (d > root->data) {
        // Insert in the right subtree
        root->right = insertIntoBST(root->right, d);
    } else {
        // Insert in the left subtree
        root->left = insertIntoBST(root->left, d);
    }
    return root; // Return the root of the subtree
}

void levelOrderTraversal(Node* root) {
    if (root == NULL) 
        return; // If the tree is empty, return

    queue<Node*> q;
    q.push(root);

    while (!q.empty()) {
        Node* temp = q.front();
        q.pop();
        cout << temp->data << " "; // Print the current node's data

        // Push left and right children into the queue
        if (temp->left) {
            q.push(temp->left);
        }
        if (temp->right) {
            q.push(temp->right);
        }
    }
    cout << endl; // Print a new line after level order traversal
}

void takeInput(Node*& root) {
    int data;
    cin >> data;

    while (data != -1) {
        root = insertIntoBST(root, data); // Update the root pointer
        
        // Print the current state of the BST after each insertion
        cout << "Current state of the BST after inserting " << data << ": ";
        levelOrderTraversal(root);
        
        cin >> data;
    }
}

void inorder(Node* root) {
    // base case
    if (root == NULL) {
        return;
    }
    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}

void preorder(Node* root) {
    // base case
    if (root == NULL) {
        return;
    }
    cout << root->data << " ";
    preorder(root->left);
    preorder(root->right);
}

void postorder(Node* root) {
    // base case
    if (root == NULL) {
        return;
    }
    postorder(root->left);
    postorder(root->right);
    cout << root->data << " ";
}

Node* minVal(Node* root) {
    Node* temp = root;
    
    while (temp->left != NULL) {
        temp = temp->left;
    }
    return temp;
}

Node* maxVal(Node* root) {
    Node* temp = root;
    
    while (temp->right != NULL) {
        temp = temp->right;
    }
    return temp;
}
Node* deleteFromBST(Node* root ,int val){
    // base case
    if(root == NULL){
        return root;
    }
    if(root->data == val){
        // 0 child
        if(root->left == NULL && root->right == NULL){
            delete root;
            return NULL;
            // here we directly deleting the root we want 
        }
        // 1 child
        if(root->left != NULL && root->right == NULL){
            Node* temp = root->left;
            delete root;
            return temp;
            // here we delete that root and save the children keyt into temp variable 
        }
        if(root->left == NULL && root->right != NULL){
            Node* temp = root->right;
            delete root;
            return temp;
        }
        // 2 children
        if(root->left != NULL && root->right != NULL ){
            int mini = minVal(root->right) -> data;
            root-> data = mini;
            root-> right = deleteFromBST(root->right,mini);
            return root;
            // here we take minimum from the rightleftsubtree or maximum from the leftsubtree  and copy the value of that value we taken above(MIN) and now delete that MIN value and than delete the root one which one we want tor delete  
        }
    }
    else if (root-> data > val){
        //left part me ajaio
        root->left = deleteFromBST(root->left,val);
        return root;
    }
    else{
        //right part me ajaio
        root->right = deleteFromBST(root->right,val);
        return root;
    }
}

int main() {
    Node* root = NULL;
    cout << "Enter the data for BST (end with -1): ";
    takeInput(root);
    
    cout << "printing inorder" << endl;
    inorder(root);
    
    cout << endl << "printing preorder" << endl;
    preorder(root);
    
    cout << endl << "printing postorder" << endl;
    postorder(root);
    
    cout << endl << "min value is " << minVal(root)->data << endl;
    cout << "max value is " << maxVal(root)->data << endl;
    
    cout << endl << "before deletion" << endl;
    inorder(root);
    // Corrected deletion part
    root = deleteFromBST(root, 30); // Update the root with the new tree structure after deletion
    
    cout << endl << "after deletion" << endl;
    inorder(root); // Print inorder traversal to confirm deletion
   
    
    return 0;
}
internal final class NW_NumToTxtHelper
{
    static TempStr numeralsToTxt_AR(real _num)
    {
        real    numOfPennies = decround(frac(_num), 2);
        real    test         = _num - frac(_num);
        str     zero;
        str     comma;
        str     and;
        str     cent;
        int     numOfTenths;
        str 20  ones[19], tenths[9], hundreds, thousands, millions, billions, trillions;

        int64   temp;
        str 200  returntxt;

        real modOperator(real a1, real a2)
        {
            int     tmpi;
            real    tmp1, tmp2;
            tmp1 = a1 / a2;
            tmpi = real2int(tmp1);
            tmp2 = tmpi;
            return (tmp1 - tmp2)*a2;
        }

        str doubleDigit2ARTxt(real doubledigit,boolean _pennies = false)
        {
            str     txt;
            int     firstDigit;
            real    tempdigit;

            if(_pennies)
            {
                firstDigit = doubledigit * 10;
                doubledigit = doubledigit * 100;
                if(!firstDigit)
                {
                    doubledigit = doubledigit mod 10;
                    //txt = zero + " " + ones[doubledigit];
                    txt = ones[doubledigit];
                    return txt;
                }
            }
            tempdigit = doubledigit;
            if (tempdigit >= 20)
            {
                tempdigit = tempdigit div 10;
                txt = tenths[tempdigit];
                doubledigit = doubledigit mod 10;
            }
            if (doubledigit >= 1)
            {
                txt = txt ?  (ones[doubledigit] + and + txt) : ones[doubledigit];
            }

            return txt;
        }

        real checkPower(real  _test,int64 _power)
        {
            int64   numOfPower;

            if (_test >= _power)
            {
                numOfPower = _test div _power;
                if (numOfPower >= 100)
                {
                    temp = numOfPower div 100;

                    if(temp > 9)// The validation was previously on 2
                    {
                        returntxt = returntxt ? (returntxt + and + ones[temp] + ' ' + hundreds) :(returntxt + ' ' + ones[temp] + ' ' + hundreds);
                    }

                    else
                    {
                        switch(temp)
                        {

                            Case 1:
                                returntxt = returntxt ? (returntxt + and + hundreds) : (returntxt + ' ' + hundreds);
                                break;
                            Case 2:
                                // TO DO need to insert a label for two hundred in Arabic
                                returntxt = returntxt ? (returntxt + and + "مائتين") :   returntxt + ' ' + "مائتين";
                                break;
                            Case 3:
                                // TO DO need to insert a label for three hundred in Arabic
                                returntxt = returntxt ? (returntxt + and + "ثلاثمائة") :   returntxt + ' ' + 'ثلاثمائة';
                                break;
                            Case 4:
                                // TO DO need to insert a label for four hundred in Arabic
                                returntxt = returntxt ? (returntxt + and + "اربعمائة") :   returntxt + ' ' + "اربعمائة";
                                break;
                            Case 5:
                                // TO DO need to insert a label for five hundred in Arabic
                                returntxt = returntxt ? (returntxt + and + "خمسمائة") :   returntxt + ' ' + "خمسمائة";
                                break;
                            Case 6:
                                // TO DO need to insert a label for six hundred in Arabic
                                returntxt = returntxt ? (returntxt + and + "ستمائة") :   returntxt + ' ' + "ستمائة";
                                break;
                            Case 7:
                                // TO DO need to insert a label for seven hundred in Arabic
                                returntxt = returntxt ? (returntxt + and + "سبعمائة") :   returntxt + ' ' + "سبعمائة";
                                break;
                            Case 8:
                                // TO DO need to insert a label for eight hundred in Arabic
                                returntxt = returntxt ? (returntxt + and + "ثمانمائة") :   returntxt + ' ' + "ثمانمائة";
                                break;
                            Case 9:
                                // TO DO need to insert a label for nine hundred in Arabic
                                returntxt = returntxt ? (returntxt + and + "تسعمائة") :   returntxt + ' ' + "تسعمائة";
                                break;

                        }
                    }
                    numOfPower = numOfPower mod 100;
                }
                if(numOfPower > 2 && _power > 100)
                {
                    returntxt = returntxt ?  (returntxt + and + doubleDigit2ARTxt(real2int(numOfPower))) : (returntxt  + ' ' + doubleDigit2ARTxt(real2int(numOfPower)));
                }
                else
                {
                    if(returntxt && numOfPower)
                    {
                        returntxt = returntxt + and + ' ';
                    }
                }
                switch(_power)
                {
                    case 1000000000000 :
                        {
                            if( numOfPower == 2)
                            {
                                // TO DO need to insert a label for two trillions in Arabic
                                returntxt = returntxt + "تريليونين ";
                            }
                            else
                            {
                                returntxt = numOfPower > 10 ||  numOfPower == 1 || numOfPower == 0 ? (returntxt + ' ' + trillions) : (returntxt + ' ' + "تريليونات");
                            }
                            _test = modOperator(_test, 1000000000000.00);
                            break;
                        }
                    case 1000000000 :
                        {
                            if( numOfPower == 2)
                            {
                                // TO DO need to insert a label for two billions in Arabic
                                returntxt = returntxt + "مليارين";
                            }
                            else
                            {
                                returntxt = numOfPower > 10 ||  numOfPower == 1 || numOfPower == 0 ? (returntxt + ' ' + billions) : (returntxt + ' ' + "مليارات");
                            }
                            _test = modOperator(_test, 1000000000);
                            break;
                        }
                    case 1000000 :
                        {
                            if( numOfPower == 2)
                            {
                                // TO DO need to insert a label for two Millions in Arabic
                                returntxt = returntxt + "مليونين";
                            }
                            else
                            {

                                returntxt = numOfPower > 10 || numOfPower == 1 || numOfPower == 0 ? (returntxt + ' ' + millions) : (returntxt + ' ' + "ملايين");

                            }
                            _test = modOperator(_test, 1000000);
                            break;
                        }
                    case 1000 :
                        {
                            if( numOfPower == 2)
                            {
                                // TO DO need to insert a label for two Thousands' in Arabic
                                returntxt = returntxt + "ألفين";
                            }
                            else
                            {
                                returntxt = numOfPower > 10 ||  numOfPower == 1 || numOfPower == 0  ? (returntxt + ' ' + thousands) : (returntxt + ' ' + "الاف");
                            }
                            _test = modOperator(_test, 1000);
                            break;
                        }
                    case 100 :
                        {
                            switch (numOfPower)
                            {
                                case 2:
                                    returntxt = returntxt + "مائتين";
                                    break;

                                case 3:
                                    returntxt = returntxt +"ثلاثمائة";
                                    break;

                                case 4:
                                    returntxt = returntxt + "اربعمائة";
                                    break;

                                case 5:
                                    returntxt = returntxt + "خمسمائة";
                                    break;

                                case 6:
                                    returntxt = returntxt + "ستمائة";
                                    break;

                                case 7:
                                    returntxt = returntxt + "سبعمائة";
                                    break;

                                case 8:
                                    returntxt = returntxt + "ثمانمائة";
                                    break;

                                case 9:
                                    returntxt = returntxt + "تسعمائة";
                                    break;

                                default:
                                    returntxt = returntxt + ' ' + hundreds;
                            }

                            _test = modOperator(_test, 100);
                            break;
                        }
                }

            }
            return _test;

        }

        //infolog.language("AR");

        and     = ' ' + "@SYS5534" + ' ';
        //and     = ' ' + "و" + ' ';
        comma   = "ريـال";
        //comma = "@SYS80142";
        zero    = "@SYS2068";
        cent    = "هللــه";

        ones[1] = "@SYS26620";
        ones[2] = "@SYS26621";
        ones[3] = "@SYS26622";
        ones[4] = "@SYS26626";
        ones[5] = "@SYS26627";
        ones[6] = "@SYS26628";
        ones[7] = "@SYS26629";
        ones[8] = "@SYS26630";
        ones[9] = "@SYS26631";
        ones[10] = "@SYS26632";
        ones[11] = "@SYS26633";
        ones[12] = "@SYS26634";
        ones[13] = "@SYS26635";
        ones[14] = "@SYS26636";
        ones[15] = "@SYS26637";
        ones[16] = "@SYS26638";
        ones[17] = "@SYS26639";
        ones[18] = "@SYS26640";
        ones[19] = "@SYS26641";

        tenths[1] = 'Not used';
        tenths[2] = "@SYS26643";
        tenths[3] = "@SYS26644";
        tenths[4] = "@SYS26645";
        tenths[5] = "@SYS26646";
        tenths[6] = "@SYS26647";
        tenths[7] = "@SYS26648";
        tenths[8] = "@SYS26649";
        tenths[9] = "@SYS26650";

        hundreds    = "@SYS26651";
        thousands   = "@SYS26652";
        millions    = "@SYS26653";
        billions    = "@SYS26654";
        trillions   = "@SYS101697";

        if(test == 0)
        {
            returntxt = zero;
        }
        else
        {
            test = checkPower(test, 1000000000000);
            test = checkPower(test, 1000000000);
            test = checkPower(test, 1000000);
            test = checkPower(test, 1000);
            test = checkPower(test, 100);
        }
        if(returntxt && test)
        {
            returntxt = returntxt + and + doubleDigit2ARTxt(real2int(test));
        }
        else
        {
            returntxt = returntxt + ' ' + doubleDigit2ARTxt(real2int(test));
        }
        if(numOfPennies)
        {
            //Removing the stars and addin the pound and cent wording to fullfil the Egyptian requierment
            returntxt = ' فقط ' + returntxt + ' ' + comma + ' ' + and + doubleDigit2ARTxt(numOfPennies,true) + ' ' + cent + ' لاغير ';
            //returntxt = '***' + returntxt + ' ' + comma + ' ' + doubleDigit2ARTxt(numOfPennies,true);
        }
        else
        {
            //Removing the stars and the zeros if no cents to fullfil the Egyptian requierment
            returntxt = ' فقط ' + returntxt + ' ' + comma + ' لاغير ';
            //returntxt = '***' + returntxt + ' ' + comma + ' ' + zero + ' ' + zero;
        }
        return returntxt;
    }
}
await UPDATE`MY_VARIANT`.set`DEFAULT = false`.where`APP_NAME=${item.APP_NAME}`
<script>
// Sélectionner tous les éléments avec la classe "member"
const members = document.querySelectorAll('.member');

// Ajouter un événement de clic à chaque "member"
members.forEach(member => {
    member.addEventListener('click', () => {
        // Sélectionner l'élément "card" à l'intérieur de "member"
        const card = member.querySelector('.card');
        
        // Basculer la classe "flip" uniquement sur "card" dans l'élément cliqué
        card.classList.toggle('flip');
    });
});
</script>
<div class="swiper-wrapper">
<div class="member">
<div class="card">
<section class="front" id="open"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>

<section class="back" id="close"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>
</div>
</div>

<div class="member">
<div class="card">
<section class="front" id="open"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>

<section class="back" id="close"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>
</div>
</div>

<div class="member">
<div class="card">
<section class="front" id="open"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>

<section class="back" id="close"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>
</div>
</div>

<div class="member">
<div class="card">
<section class="front" id="open"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>

<section class="back" id="close"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>
</div>
</div>

<div class="member">
<div class="card">
<section class="front" id="open"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>

<section class="back" id="close"><img alt="" src="https://files.qualifio.com/library/anais_brison__onboarding_0/images/2024/studio%20page/stromae-blur.png" /></section>
</div>
</div>
</div>
.swiper-wrapper{
	display: flex;
}

.card {
    display: grid;
    transform-style: preserve-3d;
    transition: transform 0.8s;
}

.card .front, .card .back {
    grid-area: 1 / 1;
    backface-visibility: hidden;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.5rem;
}

.card .back {
    transform: rotateY(180deg);
}

.hide {
    display: none;
}

.flip {
    transform: rotateY(180deg);
}
TASK 1A
function make_k_list(k, d) {
    if (d === 0){
        return 0;
    } else { 
        const wish = make_k_list(k, d - 1); //each time an inner element is accessed, number of lists(degree) decreases by 1, while no. of elem kk is the same.
        return build_list(x=> wish, k);
    }
}

TASK 1B
function sum_k_list(klist) {
    
    if (!is_list(klist)){ //BC: if not list, return number
        return klist;
    } else {              //if list, apply recursion to get sum of internal list, continue addition.
        return accumulate ((x, acc) => sum_k_list(x) + acc, 0, klist);
    }
}
TASK 1C
function map_k_list(f, klist) {
    if (!is_list(klist)){
        return f(klist);
    } else {
        return map(x => map_k_list(f,x), klist);
    }
}
TASK 2A
function has_no_consecutive_pairs(list){
    for ( let i = 0; i < length(list) - 1; i = i + 1){
        if (list_ref(list, i) === list_ref(list, i + 1)){
            return false;
        } else {
            return true;
        }
    }
}


function route_distance(mat, route) {
    let total_distance = 0;
    if (length(route) < 2){
        return false;
    } else if (!has_no_consecutive_pairs(route)){
        return false;
    } else {
        for ( let i = 0; i < length(route) - 1; i = i + 1){
            const from = list_ref(route, i);
            const to = list_ref(route, i + 1);
            total_distance = total_distance + mat[from][to];
        }
        return total_distance;
    }

}

// Route: length of at least 2
// no repeating of houses back to back
TASK 2B
// The route_distance function for the preceding task has been
// pre-declared here for you to use in this task.
// Do not declare your own route_distance function.
/*
function route_distance(mat, route) {
    // Pre-declared
}
*/

function shortest_paper_route(n, mat, start) {

        // You can keep, modify or remove the permutations function.
    function permutations(ys) { //Ultimately generates a list of lists of all different permutations as lists
        return is_null(ys)
            ? list(null)
            : accumulate(append, null,
                map(x => map(p => pair(x, p), 
                             permutations(remove(x, ys))),
                    ys));
                    
            //permutations(remove(x, ys)): removes x, generates permutations for all other elements
            //Outer map: loops through each x in ys
                //Inner map: pairs x with every new permutation p genrated
    }       //accumulate: accumulates all different permutations(lists) in one list (becomes a list of lists)


// n is the total number of houses
// peter's house can be any
// One simple possible permutations is list(1,2, 3 ... , n)

    const route_without_start = remove(start, build_list(x => x, n));
    const all_routes_without_start = permutations(route_without_start);
    const all_routes = map ( x => append(pair(start, x), list(start)), all_routes_without_start);
    
    function filter_shortest(lst){
        let smallest_distance = Infinity;
        let smallest_permutation = null;

        for ( let i = 0; i < length(lst); i = i + 1){
            const current_distance = route_distance(mat, list_ref(lst, i));
            const current_permutation = list_ref(lst, i);
            
            if ( current_distance < smallest_distance){
                smallest_distance = current_distance;
                smallest_permutation = current_permutation;
            }
        }
        return pair(smallest_permutation, smallest_distance);
    }
    return filter_shortest(all_routes);
}

//generate list of permutations 
//Define function to return smallest distance and list using route distance
//Options:
  //1. Apply sort list, get head.
  
  
/*
Mistakes:
1. build_list : list required includes from 0 to n not 1 to n)
2. all_routes --->place pair after append to avoid a nested pair structure
3. smallest_distance variable: initialise it to infinity instead of 0
4. for loop: place return statement outside of if and for loop to not besl loop
5. for loop: starting varible should be i = 0 not 1
6. for loop: termination condition to be i < length(lst) instead of i < length(lst) - 1
    i < length(lst) - 1 : used to compare between 2 consecutive elements for sorting
    i < length(lst): used to go through the while list
7. current_distance and current_permutation should be defined as constants instead of variables
   as they shouldn't be changed within each iteration of loop
*/
TASK 3A
function make_postfix_exp(bae) {
    if (is_number(bae)){   //base case: if number, return number in array
       return [bae];
    } else {
       const left = make_postfix_exp(bae[0]);
       const right = make_postfix_exp(bae[2]);
       const op = bae[1]; //Why doesn't op require make_postfix_exp command?
       
       const result = [];
       for ( let i = 0; i < array_length(left); i = i + 1){ 
           result[array_length(result)] = left[i]; //next element of result is symbolised by array_length(result)
       } 
       
       for ( let i = 0; i < array_length(right); i = i + 1){
           result[array_length(result)] = right[i];
       }
       result[array_length(result)] = op; //no loop required, since will only have 1 element
       return result;
   }
}
    
/*
Key concepts:
1. "appending" different arrays by using a loop.
2. Rearranging elements of an array
*/
TASK 3B
let stack = []; // ionitialize stack

function eval_postfix_exp(pfe) { //evaluates through array pfe
    stack = [];
    for (let i = 0; i < array_length(pfe); i = i + 1){ //look at each element
        if(is_number(pfe[i])){ //check if current element is a number
            push(pfe[i]); //to add current elem named in pfe into stack
        } else {
            const operands = take_two(); //side effect of shortening stack, but calls the 2 most recent numbers from stack, returning in pair format
            const result = evaluate(head(operands), tail(operands), pfe[i]);  
            push(result); //add result to stack
        }
    }
    const final_result = stack[0]; //assigns value to final computed value of stack
    stack = [];       //good practice to clear stack
    return final_result;
}

function push(elem){
    stack[array_length(stack)] = elem;
}

function take_two(){
    const len = array_length(stack);
    const right = stack[len - 1]; //last elem of stack
    const left = stack[len - 2];  //2nd to last elem of stack
    const new_stack = [];         //new array to 
    for (let i = 0; i < len - 2; i = i + 1){ // for loop removes the last 2 elements, by copying every element except last 2 to new_stack
        new_stack[i]=stack[i];    //stack is then assigned to new_stack
    }
    stack = new_stack;
    return pair(left, right); 
}


//Purpose:
//1. retrieve last 2 elem from stack
//2. remove these elem ofrom stack
//3. return these 2 numbers s a pair, so they can be used in a operation

function evaluate(left, right, op){
    if (op === '+'){
        return left + right;
    }
    if (op === '-'){
        return left - right;
    }
    if (op === '*'){
        return left * right;
    }
    if (op === '/'){
        return left / right;
    }
}
///If number, add it to stack 
{
	"blocks": [
		{
			"type": "section",
			"block_id": "heading",
			"text": {
				"type": "mrkdwn",
				"text": "*🌟 Boost Days Extended 🌟*"
			}
		},
		{
			"type": "section",
			"block_id": "intro",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Singapore!\n\nThanks to your incredible feedback, we’re thrilled to announce that our Boost Days program is extended through March 2025! With your input, we’ve refined Boost Days to focus on the experiences that bring our Xeros the most enjoyment. To maximise what you love, we’re saying farewell to Afternoon Tea and Wellbeing activities. But don't worry - our awesome Wellbeing team and Wellbeing Champions in each region will continue to offer and promote these initiatives.\n\n*From the week of the 25th of November, here’s what’s changing—and what’s here to stay:*"
			}
		},
		{
			"type": "section",
			"block_id": "meals",
			"text": {
				"type": "mrkdwn",
				"text": "*🍽️ More Meals, More Connections*\nWe’re adding more deliciousness to the menu!\nGet ready for both a breakfast and a light lunch each week.\nNow you'll have two opportunities to come together and refuel with your fellow Xeros."
			}
		},
		{
			"type": "section",
			"block_id": "social-events",
			"text": {
				"type": "mrkdwn",
				"text": "*🎉 Social Happy Hour*\nHappening every two weeks with a rebranded style. Enjoy drinks and tasty nibbles - this regular schedule makes it easier than ever to connect and have some fun!"
			}
		},
		{
			"type": "section",
			"block_id": "cafe-partnership",
			"text": {
				"type": "mrkdwn",
				"text": "*☕ Café Partnership*\nContinue to enjoy your favourite café-style beverages from _Group Therapy Coffee_. Whether it's a latte, tea or a hot chocolate, it's the perfect pick-me-up through your Boost day!"
			}
		},
		{
			"type": "section",
			"block_id": "closing",
			"text": {
				"type": "mrkdwn",
				"text": "Boost Days have always been about giving you time to recharge and reconnect, and we’re so excited to bring you an even better experience with these updates.\n\nSee you at the next Boost Day! 🌟\n\nWith love,\nThe WX Team :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "section",
			"block_id": "heading",
			"text": {
				"type": "mrkdwn",
				"text": "*🌟 Boost Days Extended 🌟*"
			}
		},
		{
			"type": "section",
			"block_id": "intro",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Melbourne!\n\nThanks to your incredible feedback, we’re thrilled to announce that our Boost Days Program is extended through March 2025! \nWith your input, we’ve fine-tuned Boost Days to focus on the experiences that our Xeros enjoy most. To maximise what you love, we’re saying farewell to Afternoon Tea, Fitness Programs and Wellbeing activities.  But don't worry - our awesome Wellbeing team and the Wellbeing Champions in each region will continue to offer and promote these initiatives. \n\n* From the week of the 25th of November, here’s what’s changing—and what’s here to stay:*"
			}
		},
		{
			"type": "section",
			"block_id": "meals",
			"text": {
				"type": "mrkdwn",
				"text": "*🍽️ More Meals, More Connections*\nWe’re adding more deliciousness to the menu!\nGet ready for both a breakfast and a light lunch each week.\nNow you’ll have two opportunities to come together and refuel with your fellow Xeros."
			}
		},
		{
			"type": "section",
			"block_id": "social-events",
			"text": {
				"type": "mrkdwn",
				"text": "*🎉 Social Happy Hour*\nHappening every two weeks with a rebranded style.  Enjoy drinks and tasty nibbles - this regular schedule makes it easier than ever to connect and have some fun!"
			}
		},
		{
			"type": "section",
			"block_id": "xero-cafe",
			"text": {
				"type": "mrkdwn",
				"text": "*☕ Xero Café *\nOur skilled baristas will continue serving up your beloved café-style beverages. Sip on a latte, tea, or enjoy a sweet treat to keep you energised!"
			}
		},
		{
			"type": "section",
			"block_id": "closing",
			"text": {
				"type": "mrkdwn",
				"text": "Boost Days have always been about giving you time to recharge and reconnect, and we’re so excited to bring you an even better experience with these updates. \n\nSee you at the next Boost Day! 🌟\n\nWith love,\nThe WX Team :party-wx:"
			}
		}
	]
}
#include <stdio.h>
#include <unistd.h>   // For sleep function

#define BUCKET_CAPACITY 10  // Maximum capacity of the bucket
#define LEAK_RATE 1         // Amount of water that leaks per second

// Struct to represent the bucket
typedef struct {
    int currentWater;   // Current amount of water in the bucket
} LeakyBucket;

// Initialize the bucket by setting its water level to zero
void initBucket(LeakyBucket *bucket) {
    bucket->currentWater = 0;
}

// Function to add water to the bucket
void addWater(LeakyBucket *bucket, int water) {
    // Check if adding water would exceed the bucket's capacity
    if (bucket->currentWater + water > BUCKET_CAPACITY) {
        printf("Bucket overflow! Discarding excess water.\n");
    } else {
        bucket->currentWater += water;
        printf("Added %d units of water. Current level: %d\n", water, bucket->currentWater);
    }
}

// Function to leak water from the bucket
void leakWater(LeakyBucket *bucket) {
    // Only leak if there is water in the bucket
    if (bucket->currentWater > 0) {
        bucket->currentWater -= LEAK_RATE;
        if (bucket->currentWater < 0) {
            bucket->currentWater = 0;   // Make sure water level doesn’t go negative
        }
        printf("Leaked 1 unit of water. Current level: %d\n", bucket->currentWater);
    } else {
        printf("Bucket is empty. No water to leak.\n");
    }
}

// Main function to demonstrate adding and leaking water
int main() {
    LeakyBucket bucket;           // Create a bucket
    initBucket(&bucket);           // Initialize the bucket

    // Simulate adding and leaking water in a simple loop
    for (int i = 0; i < 5; i++) {  // Run 5 cycles
        printf("\nCycle %d:\n", i + 1);

        addWater(&bucket, 3);      // Add 3 units of water each cycle
        leakWater(&bucket);        // Leak 1 unit of water each cycle

        sleep(1);                  // Wait for 1 second to simulate time passing
    }

    return 0;
}
{
	"blocks": [
		{
			"type": "section",
			"block_id": "heading",
			"text": {
				"type": "mrkdwn",
				"text": "*🌟 Boost Days Extended 🌟*"
			}
		},
		{
			"type": "section",
			"block_id": "intro",
			"text": {
				"type": "mrkdwn",
				"text": "Hey London!\n\nThanks to your incredible feedback, we’re thrilled to announce that our Boost Days program is extended through March 2025! With your input, we’ve refined Boost Days to focus on the experiences that bring our Xeros the most enjoyment. To maximise what you love, we’re saying farewell to Afternoon Tea and Wellbeing activities. But don't worry - our awesome Wellbeing team and Wellbeing Champions in each region will continue to offer and promote these initiatives.\n\n*From the week of the 25th of November, here’s what’s changing—and what’s here to stay:*"
			}
		},
		{
			"type": "section",
			"block_id": "meals",
			"text": {
				"type": "mrkdwn",
				"text": "*🍽️ Same Delicious Meals, Same Great Connections*\nOur Boost Days will continue to offer two meals each week, giving you two opportunities to come together and refuel with your fellow Xeros."
			}
		},
		{
			"type": "section",
			"block_id": "social-events",
			"text": {
				"type": "mrkdwn",
				"text": "*🎉 Social Happy Hour*\nHappening every two weeks with a rebranded style. Enjoy drinks and tasty nibbles - this regular schedule makes it easier than ever to connect and have some fun!"
			}
		},
		{
			"type": "section",
			"block_id": "cafe-partnership",
			"text": {
				"type": "mrkdwn",
				"text": "*☕ Café Partnership*\nContinue to enjoy your favourite café-style beverages from _Vinyl Coffee_, located at 6a Tileyard Rd, London N7 9AH. Simply bring your Xero ID to claim your free beverage. Whether it's a latte, tea, or a hot chocolate, it's the perfect pick-me-up to power through your Boost day!"
			}
		},
		{
			"type": "section",
			"block_id": "closing",
			"text": {
				"type": "mrkdwn",
				"text": "Boost Days have always been about giving you time to recharge and reconnect, and we’re so excited to bring you an even better experience with these updates.\n\nSee you at the next Boost Day! 🌟\n\nWith love,\nThe WX Team :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "section",
			"block_id": "heading",
			"text": {
				"type": "mrkdwn",
				"text": "*🌟 Boost Days Extended 🌟*"
			}
		},
		{
			"type": "section",
			"block_id": "intro",
			"text": {
				"type": "mrkdwn",
				"text": "Hey San Mateo!\n\nThanks to your incredible feedback, we’re thrilled to announce that our Boost Days program is extended through March 2025! With your input, we’ve refined Boost Days to focus on the experiences that bring our Xeros the most enjoyment. To maximize what you love, we’re saying farewell to Afternoon Tea and Wellbeing activities. But don't worry - our awesome Wellbeing team and Wellbeing Champions in each region will continue to offer and promote these initiatives.\n\n*From the week of the 25th of November, here’s what’s changing:*"
			}
		},
		{
			"type": "section",
			"block_id": "meals",
			"text": {
				"type": "mrkdwn",
				"text": "*🍽️ More Meals, More Connections*\nWe’re adding more deliciousness to the menu!\nGet ready for both a breakfast and a light lunch each week.\nNow you'll have two opportunities to come together and refuel with your fellow Xeros."
			}
		},
		{
			"type": "section",
			"block_id": "social-events",
			"text": {
				"type": "mrkdwn",
				"text": "*🎉 Social Happy Hour*\nHappening every two weeks with a rebranded style. Enjoy drinks and tasty nibbles - this regular schedule makes it easier than ever to connect and have some fun!"
			}
		},
		{
			"type": "section",
			"block_id": "cafe-partnership",
			"text": {
				"type": "mrkdwn",
				"text": "*☕ Café Partnership*\nEnjoy Café-style beverages with _The Vineyard Café_ located on the first floor of the 1825 S Grant Building. Grab a latte, tea, or even a hot chocolate to power through your day!"
			}
		},
		{
			"type": "section",
			"block_id": "closing",
			"text": {
				"type": "mrkdwn",
				"text": "Boost Days have always been about giving you time to recharge and reconnect, and we’re so excited to bring you an even better experience with these updates.\n\nSee you at the next Boost Day! 🌟\n\nWith love,\nThe WX Team :party-wx:"
			}
		}
	]
}
{
	"blocks": [
		{
			"type": "section",
			"block_id": "boost_days_heading",
			"text": {
				"type": "mrkdwn",
				"text": "*🌟 Boost Days Extended 🌟*"
			}
		},
		{
			"type": "section",
			"block_id": "boost_days_intro",
			"text": {
				"type": "mrkdwn",
				"text": "Hey Canberra! \n\nWe’re thrilled to share that Boost Days are here to stay through March 2025! \nThanks to your feedback, we’ll be continuing the Boost Day experience that you’ve enjoyed so far, giving you time to recharge and connect with your fellow Xeros."
			}
		},
		{
			"type": "section",
			"block_id": "whats_staying",
			"text": {
				"type": "mrkdwn",
				"text": "*You'll Still Enjoy:*\n\n🍽️ *Weekly Meals*: Your Boost Day Lunch will continue as usual, giving you the opportunity to come together for delicious food and great company."
			}
		},
		{
			"type": "section",
			"block_id": "boost_days_impact",
			"text": {
				"type": "mrkdwn",
				"text": "Boost Days are all about creating moments to recharge and reconnect, and we’re excited to keep bringing you this experience."
			}
		},
		{
			"type": "section",
			"block_id": "closing_message",
			"text": {
				"type": "mrkdwn",
				"text": "See you at the next Boost Day! 🌟\n\nWith love,\nThe WX Team :party-wx:"
			}
		}
	]
}
function slick_cdn_enqueue_scripts(){
    wp_enqueue_style( 'slick-style', '//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.css' );
    wp_enqueue_script( 'slick-script', '//cdn.jsdelivr.net/npm/slick-carousel@1.8.1/slick/slick.min.js', array(), null, true );
}
add_action( 'wp_enqueue_scripts', 'slick_cdn_enqueue_scripts' );
<div class="short-desc"><?php the_excerpt(); ?></div>
{
	"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 This is your friendly reminder that today is the last day to RSVP for our End of Year event that's only *2 WEEKS AWAY!* If you need a little motivation to RSVP, here's some things we have to look forward to :eyes:"
			}
		},
		{
			"type": "divider"
		},
		{
			"type": "section",
			"text": {
				"type": "plain_text",
				"text": ":saxophone: Entertainment Line Up: We have locked in the INCREDIBLE Ashley James on Saxophone and DJ Jodilly \n\n :cocktail: Enjoy our super shimmery Unicorn Cocktail/Mocktail on entry! \n\n :golf: We'll have LED Mini Golf set up at the venue for some friendly competition \n\n :blinky_stars: Get into the theme and bedazzle yourself with our Self Service Glitter Station! As apart of our sustainablility goals, we've made sure all of the body glitter is biodegradable :sustainability-at-xero:\n\n :pretzel: Help yourselves to the pretzel station set up at the bar! \n\n :icecream: Enjoy a delicious dessert from one of our favourite Xero Customers - 7 Apples Gelato! \n\n :homer_drool: We will have a delectable menu on offer throughout the entire night to keep you fuelled for the dancefloor. \n\n + Soooo much more, we won't spoil the rest :wink:",
				"emoji": true
			}
		},
		{
			"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": "*🎟 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:"
			}
		}
	]
}
#include <stdio.h> 
#include <unistd.h> // For sleep function 
#include <stdlib.h> 
#define BUCKET_CAPACITY 10 // Maximum capacity of the bucket 
#define LEAK_RATE 1         
second) 
typedef struct { 
// Rate at which the bucket leaks (units per 
int currentWater; // Current amount of water in the bucket 
} LeakyBucket; 
// Initialize the leaky bucket 
void initBucket(LeakyBucket *bucket) { 
bucket->currentWater = 0; 
} 
// Add data to the bucket 
int addWater(LeakyBucket *bucket, int water) { 
if (bucket->currentWater + water > BUCKET_CAPACITY) { 
printf("Bucket overflow! Excess water discarded.\n"); 
return 0; // Overflow occurred 
} 
bucket->currentWater += water; 
printf("Added %d units of water. Current level: %d\n", water, bucket
>currentWater); 
return 1; // Successfully added water 
} 
// Leak water from the bucket 
void leakWater(LeakyBucket *bucket) { 
if (bucket->currentWater > 0) { 
bucket->currentWater -= LEAK_RATE; 
if (bucket->currentWater < 0) { 
bucket->currentWater = 0; // Prevent negative water level 
} 
printf("Leaked 1 unit of water. Current level: %d\n", bucket
>currentWater); 
} 
} 
int main() { 
LeakyBucket bucket; 
initBucket(&bucket); 
// Simulate adding water and leaking over time 
for (int i = 0; i < 15; i++) { 
printf("\nCycle %d:\n", i + 1); 
// Add a random amount of water (1-5 units) 
int waterToAdd = rand() % 5 + 1; 
addWater(&bucket, waterToAdd); 
// Leak water 
leakWater(&bucket); 
// Sleep for 1 second to simulate time passing 
sleep(1); 
} 
return 0; 
} 
Output: 
Cycle 1: 
Added 3 units of water. Current level: 3 
Leaked 1 unit of water. Current level: 2 
Cycle 2: 
Added 1 units of water. Current level: 3 
Leaked 1 unit of water. Current level: 2 
Cycle 3: 
Added 4 units of water. Current level: 6 
Leaked 1 unit of water. Current level: 5 
... 
Cycle 15: 
Added 2 units of water. Current level: 9 
Leaked 1 unit of water. Current level: 8 
#include <stdio.h> #include<stdlib.h> #include<string.h> 
//Functiontoconvertdecimalnumberto8-bitbinarystring 
voiddecimalToBinary(unsignedintdecimal,char*binaryResult){ int i; 
for(i= 7;i>= 0;--i) { 
binaryResult[i]=(decimal%2)+'0'; decimal /= 2; 
} 
binaryResult[8]='\0'; //Null-terminatethebinarystring 
} 
//FunctiontoconvertIPv4addresstobinary void ipToBinary(char *ipAddress) { 
char*token; int octet; 
charbinaryResult[33]; //Buffertostore fullbinaryIP address 
charbinaryOctet[9];//Buffer 
printf("Binary IP address: "); 
tostoreeachoctet's 
binaryrepresentation 
//TokenizetheIPaddressusingstrtok token = strtok(ipAddress, "."); 
while(token!=NULL){ 
octet=atoi(token);//Converttokentointeger if (octet < 0 || octet > 255) { 
printf("InvalidIPaddressformat.\n"); return; 
} 
decimalToBinary(octet, 
binaryOctet); 
// 
Convert 
octet 
strcat(binaryResult,binaryOctet);//Appendbinaryoctettoresult 
strcat(binaryResult, ""); // Add space for readability 
token=strtok(NULL,"."); 
} 
binaryResult[strlen(binaryResult)-1]='\0';//Removelastspace 
binaryResult); // Print the binary IP address 
} 
intmain(){ 
charipAddress[20];//Buffer forIPv4addressinput 
//InputIPv4addressfromuser 
to 
binary 
printf("%s\n", 
printf("EnteranIPv4address(e.g.,300.522.1.203):"); scanf("%19s", ipAddress); 
//CallfunctiontoconvertIPv4 addresstobinary ipToBinary(ipAddress); 
return0; 
} 
Output: 
EnteranIPv4address:300.522.1.203 
BinaryIPaddress:100101100.100001010.00000001.11001011
#include<stdio.h> 
#include<string.h> 
int main() 
{ 
int a[20],b[30],i,j,k,count,n; 
printf("Enter frame size (Example: 8):"); 
scanf("%d",&n); 
printf("Enter the frame in the form of 0 and 1 :"); 
    for(i=0; i<n; i++) 
        scanf("%d",&a[i]); 
    i=0; 
    count=1; 
    j=0; 
    while(i<n) 
    { 
        if(a[i]==1) 
        { 
            b[j]=a[i]; 
            for(k=i+1; a[k]==1 && k<n && count<5; k++) 
            { 
                j++; 
                b[j]=a[k]; 
                count++; 
                if(count==5) 
                { 
                    j++; 
                    b[j]=0; 
                } 
                i=k; 
            } 
        } 
        else 
        { 
            b[j]=a[i]; 
        } 
i++; 
j++; 
} 
printf("After Bit Stuffing :"); 
for(i=0; i<j; i++) 
printf("%d",b[i]); 
return 0; 
} 
Output: Enter frame size (Example: 8):12 
Enter the frame in the form of 0 and 1 :0 1 0 1 1 1 1 1 1 0 0 1 
After Bit Stuffing :0101111101001 
#include<stdio.h> 
int main () 
{ 
char str[100]; 
int n,i,j,c=0,count=0; 
printf ("Enter the String:"); 
scanf ("$s",str); 
printf ("Enter the number of frames:"); 
scanf ("gd",&n); 
int frames [n]; 
printf ("Enter the frames size of the frames:in"); 
for (i=0;i<n;itt) 
{ 
printf ("Frame d:"i); 
scanf ("&d" &frames [i]): 
} 
printf("Frame sd:",i); 
scanf ("&d",&frames[i]); 
} 
printf ("InThe number of frames sd\n",n); 
for (i=0;i<n;itt) 
{ 
printf ("The content of the frame $d:",i); 
j=0; 
while(c<strlen(str) && j<frames[i]) 
{ 
printf("sc",str[c]); 
if(str[c]!="I0") 
{ 
Count ++; 
} 
c=c+1; 
j=j+1; 
} 
printf("InSize of frame &d : &d\n\n",i,count); 
count=0; 
} 
} 
OUTPUT 
Enter the frames size of the frames : 
Frame 0:5 
Frame 1:5 
Frame 2:5 
The number of frames : 
3 
The content of the frame 0:10010 
Size of frame 0 
5 
The content of the frame 1:10101 
Size of frame 1 
5 
The content of the frame 2:01 
Size of frame 2 2    
#include<stdio.h> 
#include<stdlib.h> 
#include<string.h> 
//Functiontoconvertbinarytooctalfor 
a 
binaryToOctalForOctet(int binaryNumber) { 
int octalNumber=0,decimalNumber=0,i=0; 
single 
//Convertbinarytodecimal while(binaryNumber!=0){ 
decimalNumber+=(binaryNumber%10)*(1<<i); 
++i; 
binaryNumber/= 10; 
} 
i= 1; 
// Convert decimal to octal while(decimalNumber!=0){ 
octet(8bits) 
octalNumber+=(decimalNumber%8)*i; decimalNumber /= 8; 
i*=10; 
} 
returnoctalNumber; 
} 
//FunctiontoconvertbinaryIPaddresstooctal 
void 
int 
binaryIPToOctal(char 
binaryIP[]) { 
inti,octet,octal; char *ptr; 
//SplitbinaryIP intooctetsandconverteachoctet printf("Octal IP address: "); 
for(i= 0;i<32;i+= 8) { 
octet = strtol(binaryIP + i, &ptr, 2); octal=binaryToOctalForOctet(octet); 
printf("%d", octal); 
if (i < 24) { printf("."); 
} 
} 
printf("\n"); 
} 
intmain(){ 
charbinaryIP[33];//Assuming IPv4addressinbinaryform 
// Input binary IP address from user printf("EnterabinaryIPv4address(32bits):"); 
scanf("%32s", binaryIP); 
//CallfunctiontoconvertbinaryIPtooctal binaryIPToOctal(binaryIP); 
return0; 
} 
Output: 
EnterabinaryIPv4address(32bits):11000000101010000000000100000011   
Octal IP address: 300.522.1.203
{
"key": "run",
"url": "https://manager.qualifio.com/library/stefano_0/images/2023/runner-adidas2.png",
"type": "image",
"width": 1140,
"config": {
"yoyo": false,
"repeat": -1,
"frameRate": 10
},
"height": 382,
"frameNumber": 4,
"percentPropHeightCompareToBG": 0.27,
"percentPropWidthCompareToGameWidth": 0.27
},
#update
sudo apt-get update || true && sudo apt-get upgrade -y || true

#dependencies 
sudo apt-get install gnupg1

#add webmin repo
echo "deb http://download.webmin.com/download/repository sarge contrib" | sudo tee /etc/apt/sources.list.d/webmin.list

#add pgp key
sudo mkdir -p /etc/apt/keyrings
wget -qO- http://www.webmin.com/jcameron-key.asc | gpg --dearmor | sudo tee /etc/apt/keyrings/webmin.gpg > /dev/null

echo "deb [signed-by=/etc/apt/keyrings/webmin.gpg] http://download.webmin.com/download/repository sarge contrib" | sudo tee /etc/apt/sources.list.d/webmin.list


#install Webmin
sudo apt-get update || true && sudo apt-get upgrade -y || true
sudo apt-get install webmin -y || true

#enable firewall
sudo ufw allow 10000

#to use webman navigate to https://your_server_ip:10000 in web browser 
#replace "your_server_ip" with servers ip. 
<!-- RANGESLIDER SCRIPT-->

<script>
/*! rangeslider.js - v0.3.7 | (c) 2014 @andreruffert | MIT license | https://github.com/andreruffert/rangeslider.js */ ! function(a) {
    "use strict";
    "function" == typeof define && define.amd ? define(["jquery"], a) : a("object" == typeof exports ? require("jquery") : jQuery)
}(function(a) {
    "use strict";

    function b() {
        var a = document.createElement("input");
        return a.setAttribute("type", "range"), "text" !== a.type
    }

    function c(a, b) {
        var c = Array.prototype.slice.call(arguments, 2);
        return setTimeout(function() {
            return a.apply(null, c)
        }, b)
    }

    function d(a, b) {
        return b = b || 100,
            function() {
                if (!a.debouncing) {
                    var c = Array.prototype.slice.apply(arguments);
                    a.lastReturnVal = a.apply(window, c), a.debouncing = !0
                }
                return clearTimeout(a.debounceTimeout), a.debounceTimeout = setTimeout(function() {
                    a.debouncing = !1
                }, b), a.lastReturnVal
            }
    }

    function e(a) {
        return 0 !== a.offsetWidth || 0 !== a.offsetHeight ? !1 : !0
    }

    function f(a) {
        for (var b = [], c = a.parentNode; e(c);) b.push(c), c = c.parentNode;
        return b
    }

    function g(a, b) {
        var c = f(a),
            d = c.length,
            e = [],
            g = a[b];
        if (d) {
            for (var h = 0; d > h; h++) e[h] = c[h].style.display, c[h].style.display = "block", c[h].style.height = "0", c[h].style.overflow = "hidden", c[h].style.visibility = "hidden";
            g = a[b];
            for (var i = 0; d > i; i++) c[i].style.display = e[i], c[i].style.height = "", c[i].style.overflow = "", c[i].style.visibility = ""
        }
        return g
    }

    function h(b, e) {
        if (this.$window = a(window), this.$document = a(document), this.$element = a(b), this.options = a.extend({}, m, e), this._defaults = m, this._name = i, this.startEvent = this.options.startEvent.join("." + i + " ") + "." + i, this.moveEvent = this.options.moveEvent.join("." + i + " ") + "." + i, this.endEvent = this.options.endEvent.join("." + i + " ") + "." + i, this.polyfill = this.options.polyfill, this.onInit = this.options.onInit, this.onSlide = this.options.onSlide, this.onSlideEnd = this.options.onSlideEnd, this.polyfill && l) return !1;
        this.identifier = "js-" + i + "-" + k++, this.min = parseFloat(this.$element[0].getAttribute("min") || 0), this.max = parseFloat(this.$element[0].getAttribute("max") || 100), this.value = parseFloat(this.$element[0].value || this.min + (this.max - this.min) / 2), this.step = parseFloat(this.$element[0].getAttribute("step") || 1), this.toFixed = (this.step + "").replace(".", "").length - 1, this.$fill = a('<div class="' + this.options.fillClass + '" />'), this.$handle = a('<div class="' + this.options.handleClass + '" />'), this.$range = a('<div class="' + this.options.rangeClass + '" id="' + this.identifier + '" />').insertAfter(this.$element).prepend(this.$fill, this.$handle), this.$element.css({
            position: "absolute",
            width: "1px",
            height: "1px",
            overflow: "hidden",
            opacity: "0"
        }), this.handleDown = a.proxy(this.handleDown, this), this.handleMove = a.proxy(this.handleMove, this), this.handleEnd = a.proxy(this.handleEnd, this), this.init();
        var f = this;
        this.$window.on("resize." + i, d(function() {
            c(function() {
                f.update()
            }, 300)
        }, 20)), this.$document.on(this.startEvent, "#" + this.identifier + ":not(." + this.options.disabledClass + ")", this.handleDown), this.$element.on("change." + i, function(a, b) {
            if (!b || b.origin !== i) {
                var c = a.target.value,
                    d = f.getPositionFromValue(c);
                f.setPosition(d)
            }
        })
    }
    var i = "rangeslider",
        j = [],
        k = 0,
        l = b(),
        m = {
            polyfill: !0,
            rangeClass: "rangeslider",
            disabledClass: "rangeslider--disabled",
            fillClass: "rangeslider__fill",
            handleClass: "rangeslider__handle",
            startEvent: ["mousedown", "touchstart", "pointerdown"],
            moveEvent: ["mousemove", "touchmove", "pointermove"],
            endEvent: ["mouseup", "touchend", "pointerup"]
        };
    h.prototype.init = function() {
        this.onInit && "function" == typeof this.onInit && this.onInit(), this.update()
    }, h.prototype.update = function() {
        this.handleWidth = g(this.$handle[0], "offsetWidth"), this.rangeWidth = g(this.$range[0], "offsetWidth"), this.maxHandleX = this.rangeWidth - this.handleWidth, this.grabX = this.handleWidth / 2, this.position = this.getPositionFromValue(this.value), this.$element[0].disabled ? this.$range.addClass(this.options.disabledClass) : this.$range.removeClass(this.options.disabledClass), this.setPosition(this.position)
    }, h.prototype.handleDown = function(a) {
        if (a.preventDefault(), this.$document.on(this.moveEvent, this.handleMove), this.$document.on(this.endEvent, this.handleEnd), !((" " + a.target.className + " ").replace(/[\n\t]/g, " ").indexOf(this.options.handleClass) > -1)) {
            var b = this.getRelativePosition(a),
                c = this.$range[0].getBoundingClientRect().left,
                d = this.getPositionFromNode(this.$handle[0]) - c;
            this.setPosition(b - this.grabX), b >= d && b < d + this.handleWidth && (this.grabX = b - d)
        }
    }, h.prototype.handleMove = function(a) {
        a.preventDefault();
        var b = this.getRelativePosition(a);
        this.setPosition(b - this.grabX)
    }, h.prototype.handleEnd = function(a) {
        a.preventDefault(), this.$document.off(this.moveEvent, this.handleMove), this.$document.off(this.endEvent, this.handleEnd), this.onSlideEnd && "function" == typeof this.onSlideEnd && this.onSlideEnd(this.position, this.value)
    }, h.prototype.cap = function(a, b, c) {
        return b > a ? b : a > c ? c : a
    }, h.prototype.setPosition = function(a) {
        var b, c;
        b = this.getValueFromPosition(this.cap(a, 0, this.maxHandleX)), c = this.getPositionFromValue(b), this.$fill[0].style.width = c + this.grabX + "px", this.$handle[0].style.left = c + "px", this.setValue(b), this.position = c, this.value = b, this.onSlide && "function" == typeof this.onSlide && this.onSlide(c, b)
    }, h.prototype.getPositionFromNode = function(a) {
        for (var b = 0; null !== a;) b += a.offsetLeft, a = a.offsetParent;
        return b
    }, h.prototype.getRelativePosition = function(a) {
        var b = this.$range[0].getBoundingClientRect().left,
            c = 0;
        return "undefined" != typeof a.pageX ? c = a.pageX : "undefined" != typeof a.originalEvent.clientX ? c = a.originalEvent.clientX : a.originalEvent.touches && a.originalEvent.touches[0] && "undefined" != typeof a.originalEvent.touches[0].clientX ? c = a.originalEvent.touches[0].clientX : a.currentPoint && "undefined" != typeof a.currentPoint.x && (c = a.currentPoint.x), c - b
    }, h.prototype.getPositionFromValue = function(a) {
        var b, c;
        return b = (a - this.min) / (this.max - this.min), c = b * this.maxHandleX
    }, h.prototype.getValueFromPosition = function(a) {
        var b, c;
        return b = a / (this.maxHandleX || 1), c = this.step * Math.round(b * (this.max - this.min) / this.step) + this.min, Number(c.toFixed(this.toFixed))
    }, h.prototype.setValue = function(a) {
        a !== this.value && this.$element.val(a).trigger("change", {
            origin: i
        })
    }, h.prototype.destroy = function() {
        this.$document.off(this.startEvent, "#" + this.identifier, this.handleDown), this.$element.off("." + i).removeAttr("style").removeData("plugin_" + i), this.$range && this.$range.length && this.$range[0].parentNode.removeChild(this.$range[0]), j.splice(j.indexOf(this.$element[0]), 1), j.length || this.$window.off("." + i)
    }, a.fn[i] = function(b) {
        return this.each(function() {
            var c = a(this),
                d = c.data("plugin_" + i);
            d || (c.data("plugin_" + i, d = new h(this, b)), j.push(this)), "string" == typeof b && d[b]()
        })
    }
});
</script>

<!-- EDIT SLIDER PARAMETERS-->

<script>
    $('#ranger').change(function(){
        console.log($('#ranger').val());
        if($('#ranger').val() === '1'){
            $('.pricing-card').removeClass('active-1 active-2 active-3 display-hidden');
            $('.pricing-card').addClass('active-1');
        } else if($('#ranger').val() === '2'){
            $('.pricing-card').removeClass('active-1 active-2 active-3');
            $('.pricing-card').addClass('active-2 display-hidden');
        } else if($('#ranger').val() === '3'){
            $('.pricing-card').removeClass('active-1 active-2 active-3');
            $('.pricing-card').addClass('active-3 display-hidden');
        }
    })
    
    
  $( document ).ready(function() {
  // Handler for .ready() called.
    $('.slide').removeClass('active');
  });
  $('input[type="range"]').rangeslider({
      polyfill: false,
      rangeClass: 'rangeslider',
      fillClass: 'rangeslider__fill',
      handleClass: 'rangeslider__handle',
      onInit: function() {

      },
      onSlide: function(position, value) {
          $('.rangeslider__handle').attr('data-content', value);
          $('.done').removeClass('active');
          $('.slide').addClass('active');
      },
      onSlideEnd: function(position, value) {
        $('.done').addClass('active');
        $('.slide').removeClass('active');
      }
  });
  
  </script>
  
<!-- Set the initial value for the range input element -->
<input id="ranger" type="range" min="1" max="3" step="1" value="2">

<script>
  $(document).ready(function() {
    // Set the default slider position to 2nd point
    $('#ranger').val(2).change(); // This sets the handle to the value '2' on load
    
    // Initialize the rangeslider plugin
    $('input[type="range"]').rangeslider({
      polyfill: false,
      rangeClass: 'rangeslider',
      fillClass: 'rangeslider__fill',
      handleClass: 'rangeslider__handle',
      onInit: function() {
        // Sync initial handle position
        $('.rangeslider__handle').attr('data-content', $('#ranger').val());
      },
      onSlide: function(position, value) {
        $('.rangeslider__handle').attr('data-content', value);
        $('.done').removeClass('active');
        $('.slide').addClass('active');
      },
      onSlideEnd: function(position, value) {
        $('.done').addClass('active');
        $('.slide').removeClass('active');
      }
    });
  });
</script>
code --extensions-dir <dir>
    Set the root path for extensions.
code --list-extensions
    List the installed extensions.
code --show-versions
    Show versions of installed extensions, when using --list-extension.
code --install-extension (<extension-id> | <extension-vsix-path>)
    Installs an extension.
code --uninstall-extension (<extension-id> | <extension-vsix-path>)
    Uninstalls an extension.
code --enable-proposed-api (<extension-id>)
    Enables proposed API features for extensions. Can receive one or more extension IDs to enable individually.

Copy
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:rrispat_app/src/features/auth/domains/models/auth_model.dart';
import 'package:rrispat_app/src/shared/shared_views.dart';
import 'package:rrispat_app/src/shared/widgets/rr_header.dart';

import '../../controllers/auth_controller.dart';

class AddUserWidget extends ConsumerStatefulWidget {
  const AddUserWidget({super.key});
  @override
  ConsumerState<ConsumerStatefulWidget> createState() => _AddUserPageState();
}

class _AddUserPageState extends ConsumerState<AddUserWidget> {
  TextEditingController phoneNumberController = TextEditingController();
  TextEditingController fullNameController = TextEditingController();
  final _gKey = GlobalKey<FormState>();
  String code = "";

  AuthModel authModel = AuthModel(
    uid: "",
    fcmToken: "",
    phoneNumber: "",
    fullName: "",
    division: "",
    department: "",
    isActive: true,
    isDefaultPin: true,
    isSuperAdmin: false,
    devices: const [],
    deviceHistory: const [],
    apps: const [],
    createdAt: DateTime.now(),
    updatedAt: DateTime.now(),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: const RRHeader(),
      body: Padding(
        padding: const EdgeInsets.all(5.0),
        child: Form(
          key: _gKey,
          child: ListView(
            children: [
              const SizedBox(
                height: 10,
              ),
              fullNameWidget(),
              const SizedBox(
                height: 10,
              ),
              phoneWidget(),
              FilledButton(
                onPressed: () {
                  if (_gKey.currentState!.validate()) {
                    createUser(
                      context,
                      authModel.copyWith(
                        fullName: fullNameController.text,
                        phoneNumber: code + phoneNumberController.text,
                      ),
                    );
                  }
                },
                child: const Text("Submit"),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget fullNameWidget() {
    return TextFormField(
      controller: fullNameController,
      keyboardType: TextInputType.text,
      style: Theme.of(context).textTheme.titleMedium,
      textCapitalization: TextCapitalization.words,
      decoration: InputDecoration(
        hintText: "Enter Full Name",
        label: const Text("Full Name"),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return "Enter Full Name";
        }
        return null;
      },
    );
  }

  Widget phoneWidget() {
    return TextFormField(
      controller: phoneNumberController,
      keyboardType: TextInputType.phone,
      maxLength: 10,
      style: Theme.of(context).textTheme.titleMedium,
      decoration: InputDecoration(
        prefix: const Text("+91"),
        hintText: "Enter Phone Number",
        label: const Text("Phone Number"),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(10),
        ),
      ),
      validator: (value) {
        if (value == null || value.isEmpty) {
          return "Enter a valid PhoneNumber";
        } else if (value.length < 10) {
          return "Phone Number length must be 10";
        }
        return null;
      },
    );
  }

  Future<void> createUser(BuildContext context, AuthModel auth) async {
    return showDialog(
      context: context,
      builder: (context) {
        return AlertDialog(
          title: Text("Confirm User",
              style: Theme.of(context).textTheme.titleLarge),
          content: SizedBox(
            height: 100,
            child: Column(
              children: [
                const SizedBox(
                  height: 10,
                ),
                Table(
                  children: [
                    TableRow(children: [
                      TableCell(
                          child: Text("Full Name",
                              style: Theme.of(context).textTheme.labelLarge)),
                      TableCell(
                          child: Text(auth.fullName,
                              style: Theme.of(context).textTheme.bodyMedium)),
                    ]),
                    TableRow(children: [
                      TableCell(
                          child: Text("Phone Number",
                              style: Theme.of(context).textTheme.labelLarge)),
                      TableCell(
                          child: Text(auth.phoneNumber,
                              style: Theme.of(context).textTheme.bodyMedium)),
                    ]),
                  ],
                ),
                const SizedBox(
                  height: 30,
                ),
              ],
            ),
          ),
          actions: [
            OutlinedButton(
                onPressed: () {
                  context.pop(true);
                },
                child: Text("Cancel",
                    style: Theme.of(context).textTheme.titleMedium)),
            ElevatedButton(
                onPressed: () {
                  ref.read(authControllerProvider).createUser(ref, auth);
                  context.goNamed(HomeView.routeName);
                },
                child: Text("Confirm",
                    style: Theme.of(context).textTheme.titleMedium))
          ],
        );
      },
    );
  }
}
import { Injectable, HttpException, HttpStatus, Logger } from '@nestjs/common';
import { HttpService, } from '@nestjs/axios';
import * as dayjs from 'dayjs';
import { AxiosResponse } from 'axios';
import { log } from 'console';
import * as https from 'https'; 

@Injectable()
export class DailyEquityService {
  private readonly spotwareApiUrl: string;
  private readonly apiToken: string;
  private readonly xanoEquityUrl: string;
  private readonly logger = new Logger(DailyEquityService.name);
  private lastFetchedData: any[] = [];

  constructor(private readonly httpService: HttpService) {
    this.spotwareApiUrl = process.env.SPOTWARE_API_URL;
    this.apiToken = process.env.SPOTWARE_API_TOKEN;
    this.xanoEquityUrl = process.env.XANO_API_EQUITYURL;
  
  this.httpService.axiosRef.defaults.httpsAgent = new https.Agent({ rejectUnauthorized: false });
  }
  // Fetch daily equity data from external service
  async fetchDailyEquityData(fromDate: string, toDate: string) {
    this.logger.log(`Fetching daily equity data from Spotware for date range ${fromDate} to ${toDate}`);

    try {
      const response: AxiosResponse = await this.httpService
        .get(`${this.spotwareApiUrl}/v2/webserv/traders/`, {
          params: {
            from: fromDate,
            to: toDate,
            fields: 'login,balance,minEquityDaily,maxEquityDaily',
            token: this.apiToken,
          },
        })
        .toPromise();

      if (response.status !== 200) {
        throw new Error(`Unexpected status code: ${response.status}`);
      }

      const mappedData = response.data.trader.map((trader) => ({
        account: trader.login,
        starting_daily_equity: trader.balance.toString(),
        sde_date: dayjs().format('YYYY-MM-DD'),
        gmt_date: dayjs().toISOString(),
        created_at: dayjs().toISOString(),
        status: 'pending',
        trading_days: '0',
        challenge_begins: dayjs().subtract(30, 'days').format('YYYY-MM-DD'),
        new_status: 'pending',
      }));

      this.logger.log('Successfully fetched and mapped daily equity data');
      return mappedData;
    } catch (error) {
      this.logger.error(`Error fetching daily equity data: ${error.message}`);
      throw new HttpException(`Failed to fetch daily equity data: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  // Check if data exists in Xano, and then update or create as needed
  async checkAndUpdateDailyEquityInXano(equityData: any[]) {
    this.logger.log('Starting Xano data check and update process');

    // Log to check the equityData content
    this.logger.debug(`Received equityData: ${JSON.stringify(equityData)}`);
    
    const results = [];

    if (!equityData || equityData.length === 0) {
        this.logger.warn('No equity data to process. Exiting function.');
        return results; // Return early if there is no data
    }

    for (const data of equityData) {
      try {
        this.logger.debug(`Processing account: ${data.account}`);
        console.log(`${this.xanoEquityUrl}/${data.account}/`,"hyhy");
        const existingDataResponse = await this.httpService
          .get(`${this.xanoEquityUrl}/${data.account}/`, {
            headers: { 'Content-Type': 'application/json' },
          })
          .toPromise();
        
        this.logger.debug(`Received response for account ${data.account}: ${JSON.stringify(existingDataResponse.data)}`);

        if (existingDataResponse.status === 200) {
          this.logger.log(`Account ${data.account} exists in Xano, updating record`);

          const updateResponse = await this.httpService
            .patch(`${this.xanoEquityUrl}/${data.account}`, data, {
              headers: { 'Content-Type': 'application/json' },
            })
            .toPromise();

          this.logger.debug(`Update response for account ${data.account}: ${JSON.stringify(updateResponse.data)}`);
          results.push(updateResponse.data);
        } else {
          this.logger.log(`Account ${data.account} does not exist, creating new record`);

          const createResponse = await this.httpService
            .post(this.xanoEquityUrl, data, {
              headers: { 'Content-Type': 'application/json' },
            })
            .toPromise();

          this.logger.debug(`Create response for account ${data.account}: ${JSON.stringify(createResponse.data)}`);
          results.push(createResponse.data);
        }
      } catch (error) {
        if (error.response?.status === 404) {
          this.logger.log(`Account ${data.account} not found in Xano, creating new record`);

          const createResponse = await this.httpService
            .post(this.xanoEquityUrl, data, {
              headers: { 'Content-Type': 'application/json' },
            })
            .toPromise();

          this.logger.debug(`Create response for account ${data.account}: ${JSON.stringify(createResponse.data)}`);
          results.push(createResponse.data);
        } else {
          this.logger.error(`Failed to process account ${data.account}: ${error.message}`);
          throw new HttpException(`Failed to process account ${data.account}: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
        }
      }
    }

    this.logger.log('Completed Xano data check and update process');
    return results;
  }


  // Update the equity for traders daily
  async updateDailyEquityForTraders() {
    const fromDate = dayjs().subtract(1, 'day').startOf('day').format('YYYY-MM-DDTHH:mm:ss.SSS');
    const toDate = dayjs().startOf('day').format('YYYY-MM-DDTHH:mm:ss.SSS');

    this.logger.log(`Starting daily equity update for traders from ${fromDate} to ${toDate}`);

    try {
      const equityData = await this.fetchDailyEquityData(fromDate, toDate);

      if (this.hasDataChanged(equityData)) {
        this.logger.log('Data has changed; proceeding with update');
        const result = await this.checkAndUpdateDailyEquityInXano(equityData);
        this.lastFetchedData = equityData;  // Update the cache
        return result;
      } else {
        this.logger.log('No changes in data; skipping Xano update');
        return { message: 'No changes detected; update skipped.' };
      }
    } catch (error) {
      this.logger.error(`Failed to update daily equity for traders: ${error.message}`);
      throw new HttpException(`Failed to update daily equity for traders: ${error.message}`, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  private hasDataChanged(newData: any[]): boolean {
    return JSON.stringify(this.lastFetchedData) !== JSON.stringify(newData);
  }
}
#
# DO NOT EDIT THIS FILE
#
# It is automatically generated by grub-mkconfig using templates
# from /etc/grub.d and settings from /etc/default/grub
#

### BEGIN /etc/grub.d/00_header ###
insmod part_gpt
insmod part_msdos
if [ -s $prefix/grubenv ]; then
  load_env
fi
if [ "${next_entry}" ] ; then
   set default="${next_entry}"
   set next_entry=
   save_env next_entry
   set boot_once=true
else
   set default="0"
fi

if [ x"${feature_menuentry_id}" = xy ]; then
  menuentry_id_option="--id"
else
  menuentry_id_option=""
fi

export menuentry_id_option

if [ "${prev_saved_entry}" ]; then
  set saved_entry="${prev_saved_entry}"
  save_env saved_entry
  set prev_saved_entry=
  save_env prev_saved_entry
  set boot_once=true
fi

function savedefault {
  if [ -z "${boot_once}" ]; then
    saved_entry="${chosen}"
    save_env saved_entry
  fi
}

function load_video {
  if [ x$feature_all_video_module = xy ]; then
    insmod all_video
  else
    insmod efi_gop
    insmod efi_uga
    insmod ieee1275_fb
    insmod vbe
    insmod vga
    insmod video_bochs
    insmod video_cirrus
  fi
}

if [ x$feature_default_font_path = xy ] ; then
   font=unicode
else
insmod part_gpt
insmod ext2
search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
    font="/usr/share/grub/unicode.pf2"
fi

if loadfont $font ; then
  set gfxmode=3840x2160,auto
  load_video
  insmod gfxterm
  set locale_dir=$prefix/locale
  set lang=en_US
  insmod gettext
fi
terminal_input console
terminal_output gfxterm
insmod part_gpt
insmod ext2
search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
insmod gfxmenu
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_12.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_14.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_16.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_24.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_32.pf2
loadfont ($root)/usr/share/grub/themes/stylish/dejavu_sans_48.pf2
loadfont ($root)/usr/share/grub/themes/stylish/terminus-12.pf2
loadfont ($root)/usr/share/grub/themes/stylish/terminus-14.pf2
loadfont ($root)/usr/share/grub/themes/stylish/terminus-16.pf2
loadfont ($root)/usr/share/grub/themes/stylish/terminus-18.pf2
insmod jpeg
insmod png
set theme=($root)/usr/share/grub/themes/stylish/theme.txt
export theme
if [ x$feature_timeout_style = xy ] ; then
  set timeout_style=menu
  set timeout=5
# Fallback normal timeout code in case the timeout_style feature is
# unavailable.
else
  set timeout=5
fi
### END /etc/grub.d/00_header ###

### BEGIN /etc/grub.d/10_linux ###
menuentry 'Arch GNU Plus Linux' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-simple-b9549161-95f2-47de-a863-c97513774fe7' {
        load_video
        set gfxpayload=keep
        insmod gzio
        insmod part_gpt
        insmod ext2
        search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
        echo    'Loading GNU Plus Linux GNU Plus Linux-surface ...'
        GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux-surface root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
        echo    'Loading initial ramdisk ...'
        initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux-surface.img
}
submenu 'Advanced options for Arch GNU Plus Linux' $menuentry_id_option 'gnulinux-advanced-b9549161-95f2-47de-a863-c97513774fe7' {
        menuentry 'Arch GNU Plus Linux, with GNU Plus Linux GNU Plus Linux-surface' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-GNU Plus Linux-surface-advanced-b9549161-95f2-47de-a863-c97513774fe7' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
                echo    'Loading GNU Plus Linux GNU Plus Linux-surface ...'
                GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux-surface root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
                echo    'Loading initial ramdisk ...'
                initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux-surface.img
        }
        menuentry 'Arch GNU Plus Linux, with GNU Plus Linux GNU Plus Linux-surface (fallback initramfs)' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-GNU Plus Linux-surface-fallback-b9549161-95f2-47de-a863-c97513774fe7' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
                echo    'Loading GNU Plus Linux GNU Plus Linux-surface ...'
                GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux-surface root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
                echo    'Loading initial ramdisk ...'
                initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux-surface-fallback.img
        }
        menuentry 'Arch GNU Plus Linux, with GNU Plus Linux GNU Plus Linux' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-GNU Plus Linux-advanced-b9549161-95f2-47de-a863-c97513774fe7' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
                echo    'Loading GNU Plus Linux GNU Plus Linux ...'
                GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
                echo    'Loading initial ramdisk ...'
                initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux.img
        }
        menuentry 'Arch GNU Plus Linux, with GNU Plus Linux GNU Plus Linux (fallback initramfs)' --class arch --class gnu-GNU Plus Linux --class gnu --class os $menuentry_id_option 'gnulinux-GNU Plus Linux-fallback-b9549161-95f2-47de-a863-c97513774fe7' {
                load_video
                set gfxpayload=keep
                insmod gzio
                insmod part_gpt
                insmod ext2
                search --no-floppy --fs-uuid --set=root b9549161-95f2-47de-a863-c97513774fe7
                echo    'Loading GNU Plus Linux GNU Plus Linux ...'
                GNU Plus Linux   /boot/vmlinuz-GNU Plus Linux root=UUID=b9549161-95f2-47de-a863-c97513774fe7 rw  loglevel=3
                echo    'Loading initial ramdisk ...'
                initrd  /boot/intel-ucode.img /boot/initramfs-GNU Plus Linux-fallback.img
        }
}

### END /etc/grub.d/10_linux ###

### BEGIN /etc/grub.d/20_linux_xen ###
### END /etc/grub.d/20_linux_xen ###

### BEGIN /etc/grub.d/30_os-prober ###
### END /etc/grub.d/30_os-prober ###

### BEGIN /etc/grub.d/30_uefi-firmware ###
if [ "$grub_platform" = "efi" ]; then
        fwsetup --is-supported
        if [ "$?" = 0 ]; then
                menuentry 'UEFI Firmware Settings' $menuentry_id_option 'uefi-firmware' {
                        fwsetup
                }
        fi
fi
### END /etc/grub.d/30_uefi-firmware ###

### BEGIN /etc/grub.d/35_fwupd ###
### END /etc/grub.d/35_fwupd ###

### BEGIN /etc/grub.d/40_custom ###
# This file provides an easy way to add custom menu entries.  Simply type the
# menu entries you want to add after this comment.  Be careful not to change
# the 'exec tail' line above.
### END /etc/grub.d/40_custom ###

### BEGIN /etc/grub.d/41_custom ###
if [ -f  ${config_directory}/custom.cfg ]; then
  source ${config_directory}/custom.cfg
elif [ -z "${config_directory}" -a -f  $prefix/custom.cfg ]; then
  source $prefix/custom.cfg
fi
### END /etc/grub.d/41_custom ###

### BEGIN /etc/grub.d/60_memtest86+-efi ###
if [ "${grub_platform}" == "efi" ]; then
    menuentry "Memory Tester (memtest86+)" --class memtest86 --class gnu --class tool {
        if loadfont unicode ; then
            set gfxmode=1024x768,800x600,auto
            set gfxpayload=800x600,1024x768
            terminal_output gfxterm
        fi
        search --fs-uuid --no-floppy --set=root  b9549161-95f2-47de-a863-c97513774fe7
        GNU Plus Linux /boot/memtest86+/memtest.efi 
    }
fi
### END /etc/grub.d/60_memtest86+-efi ###
 public NW_GeneralResponse CreatePartialInvoice(PurchId PurchId, ProductReceiptId PackingSlipId, Num InvoiceNum, TransDate InvoiceDate)
 {
     VendPackingSlipJour vendPackingSlipJour;
     PurchFormLetter purchFormLetter;
     PurchTable  purchTable;
     PurchLine purchLine;
     VendPackingSlipTrans vendPackingSlipTrans;

     VendInvoiceInfoTable vendInvoiceInfoTable, vendInvoiceInfoTable2, vendInvoiceInfoTable3;
     VendInvoiceInfoLine vendInvoiceInfoLine;
     VendInvoiceInfoSubTable vendInvoiceInfoSubTable;
     VendInvoiceInfoSubLine vendInvoiceInfoSubLine;

     InvoiceId invoiceId;
     TransDate _invoiceDate;

     VendInvoiceJour vendInvoiceJour;
     InventTrans inventTransQty;
     str Log;
     boolean Result;
     List Errors;
     NW_GeneralResponse Response = new NW_GeneralResponse();

     ;
     changecompany('shc')
     {
        
         select vendPackingSlipJour 
             where vendPackingSlipJour.PurchId == PurchId
             && vendPackingSlipJour.PackingSlipId == PackingSlipId;

         while select vendInvoiceInfoTable2
             where vendInvoiceInfoTable2.InvoiceAccount == vendPackingSlipJour.InvoiceAccount
             && vendInvoiceInfoTable2.PurchId == PurchId
         {
             if(vendInvoiceInfoTable2.packingSlipId(vendInvoiceInfoTable2) == PackingSlipId)
             {
                 Result = false;
                 Response.ParmResult(Result);
                 Response.ParmMsg("You have already Invoice with this Product Receipt.");
                 Response.ParmErrors(Errors);
                 return Response;
             }
         }


         ttsBegin;
         if(vendPackingSlipJour.PackingSlipId)
         {
             invoiceId = InvoiceNum; //strFmt("INV-%1", vendPackingSlipJour.PackingSlipId);

             _invoiceDate = InvoiceDate;//DateTimeUtil::getSystemDate(DateTimeUtil::getUserPreferredTimeZone());

             purchTable = vendPackingSlipJour.purchTable();
             //Generate Pending Invoice Header
             vendInvoiceInfoTable.clear();
             vendInvoiceInfoTable.initValue();
             vendInvoiceInfoTable.initFromPurchTable(purchTable);

             vendInvoiceInfoTable.ParmId = FormletterParmData::getNewParmId();

             vendInvoiceInfoTable.DocumentOrigin = DocumentOrigin::Manual;
             vendInvoiceInfoTable.CurrencyCode = purchTable.CurrencyCode;
             vendInvoiceInfoTable.DeliveryName = purchTable.DeliveryName;
             vendInvoiceInfoTable.Num = invoiceId;
             vendInvoiceInfoTable.PurchName = purchTable.PurchName;
             vendInvoiceInfoTable.VendInvoiceSaveStatus = VendInvoiceSaveStatus::Pending;
             vendInvoiceInfoTable.TransDate = _invoiceDate;
             vendInvoiceInfoTable.DocumentDate = _invoiceDate;
             vendInvoiceInfoTable.LastMatchVariance = LastMatchVarianceOptions::OK;
             vendInvoiceInfoTable.ParmJobStatus = ParmJobStatus::Waiting;

             vendInvoiceInfoTable.DefaultDimension = vendInvoiceInfoTable.copyDimension(purchTable.DefaultDimension);
             vendInvoiceInfoTable.defaultRow(purchTable);
             vendInvoiceInfoTable.insert();

             //Generate Vend Invoice Info reference
             if(vendInvoiceInfoTable)
             {
                 vendInvoiceInfoSubTable.clear();
                 vendInvoiceInfoSubTable.initValue();
                 vendInvoiceInfoSubTable.defaultRow();

                 vendInvoiceInfoSubTable.ParmId = vendInvoiceInfoTable.ParmId;
                 vendInvoiceInfoSubTable.OrigPurchId = vendInvoiceInfoTable.PurchId;
                 vendInvoiceInfoSubTable.PurchName = vendInvoiceInfoTable.PurchName;
                 vendInvoiceInfoSubTable.TableRefId = vendInvoiceInfoTable.TableRefId;

                 vendInvoiceInfoSubTable.insert();
             }

             //select all packing slip line
             while select vendPackingSlipTrans
                 where vendPackingSlipTrans.PackingSlipId == vendPackingSlipJour.PackingSlipId
                 && vendPackingSlipTrans.VendPackingSlipJour == vendPackingSlipJour.RecId
             {
                 //Generate Pending Invoice Line
                 purchLine = vendPackingSlipTrans.purchLine();
                 vendInvoiceInfoLine.clear();
                 vendInvoiceInfoLine.initValue();
                 // vendInvoiceInfoLine.defaultRow(null,purchLine);
                 vendInvoiceInfoLine.initFromPurchLine(purchLine);

                 vendInvoiceInfoLine.DeliveryName = vendInvoiceInfoTable.DeliveryName;
                 vendInvoiceInfoLine.ParmId = vendInvoiceInfoTable.ParmId;
                 vendInvoiceInfoLine.TableRefId = vendInvoiceInfoTable.TableRefId;
                 vendInvoiceInfoLine.currencyCode = vendInvoiceInfoTable.CurrencyCode;
                 vendInvoiceInfoLine.LineNum = any2int(purchLine.LineNumber);

                 vendInvoiceInfoLine.InvoiceAccount = vendInvoiceInfoTable.InvoiceAccount;
                 vendInvoiceInfoLine.InventDimId = vendPackingSlipTrans.InventDimId;
                 vendInvoiceInfoLine.OrderAccount = vendInvoiceInfoTable.OrderAccount;
                 vendInvoiceInfoLine.ItemId = vendPackingSlipTrans.ItemId;
                 vendInvoiceInfoLine.InventTransId = vendPackingSlipTrans.InventTransId;

                 vendInvoiceInfoLine.DocumentOrigin = DocumentOrigin::Manual;
                 vendInvoiceInfoLine.ReceiveNow = vendPackingSlipTrans.Qty;

                 vendInvoiceInfoLine.modifiedReceiveNow();

                 vendInvoiceInfoLine.PurchPrice = purchLine.PurchPrice;
                 vendInvoiceInfoLine.InventNow = vendInvoiceInfoLine.ReceiveNow;
                 if(purchLine.PurchQty != 0)
                 {
                     vendInvoiceInfoLine.LineAmount = (purchLine.LineAmount / purchLine.PurchQty) * vendInvoiceInfoLine.ReceiveNow;
                 }

                 vendInvoiceInfoLine.DefaultDimension = purchLine.DefaultDimension;

                 vendInvoiceInfoLine.insert();

                 //Generate Vend Invoice Info reference from packing slip
                 if(vendInvoiceInfoLine.RecId)
                 {
                     vendInvoiceInfoSubLine.clear();
                     vendInvoiceInfoSubLine.initValue();
                     vendInvoiceInfoSubLine.defaultRow();
                     vendInvoiceInfoSubLine.ParmId = vendInvoiceInfoTable.ParmId;
                     vendInvoiceInfoSubLine.LineRefRecId = vendInvoiceInfoLine.RecId;
                     vendInvoiceInfoSubLine.ReceiveNow = vendInvoiceInfoLine.ReceiveNow;
                     vendInvoiceInfoSubLine.InventNow = vendInvoiceInfoLine.InventNow ;
                     vendInvoiceInfoSubLine.JournalRefRecId = vendPackingSlipTrans.RecId;
                     vendInvoiceInfoSubLine.JournalRefTableId = vendPackingSlipTrans.TableId;
                     vendInvoiceInfoSubLine.DocumentId = vendPackingSlipTrans.PackingSlipId;
                     vendInvoiceInfoSubLine.insert();
                 }
             }
             ttsCommit;
             Response.ParmResult(true);
             Response.ParmMsg(strFmt("Invoice %1 has been Created for Purchase order %2 with Product Receipt %3",invoiceId, purchTable.PurchId, PackingSlipId));
             //Posting pending invoice invoice
             //purchFormLetter = PurchFormLetter_Invoice::newFromSavedInvoice(vendInvoiceInfoTable);
             //purchFormLetter.update(vendInvoiceInfoTable.purchTable(),vendInvoiceInfoTable.Num);
         }
         else
         {
             Response.ParmResult(false);
             Response.ParmMsg(strFmt("Can't found Product Receipt %1", PackingSlipId));
         }

         
         return Response;
     }
 }
var GroupUtil = Class.create();
GroupUtil.prototype = Object.extendsObject(AbstractAjaxProcessor, {

    //To check unique name of group
    isGroupNameUnique: function() {
        var g_name = this.getParameter('sysparam_gname');
        var grname = new GlideRecord('sys_user_group');
        grname.addQuery('name', g_name);
        grname.query();

        if (grname.next())
            return true;
    },


    //Update Support Group auto populate details
    GroupAutoPopulateDetails: function() {

        var result = this.newItem("result");
        var group_name = this.getParameter('sysparm_group');
        var grname = group_name.toString();
        var gr_detail = new GlideRecord('sys_user_group');
        gr_detail.addQuery('sys_id', grname);
        gr_detail.query();
        if (gr_detail.next()) {
            return gr_detail.name + ';' + gr_detail.description + ';' + gr_detail.parent + ';' + gr_detail.manager + ';' + gr_detail.u_manager_backup + ';' + gr_detail.type + ';' + gr_detail.email + ';' + gr_detail.u_notifications_when_tickets_assigned + ';' + gr_detail.u_is_on_call + ';' + gr_detail.u_on_call_phone_no + ';' + gr_detail.u_hours_when_on_call + ';' + gr_detail.u_day_when_on_call + ';' + gr_detail.u_region + ';' + gr_detail.u_is_support_group + ';' + gr_detail.u_phone_number + ';' + gr_detail.u_phone_no_justification;
        }
    },

    //get members from group auto populate;
    GetMembersFromGroup: function(grp) {
        var group_id = this.getParameter('sysparm_grp');
        var member = [];
        var gp = grp;
        var grUser = new GlideRecord('sys_user_grmember');
        grUser.addQuery('group', group_id);
        grUser.query();
        while (grUser.next()) {
            member.push(grUser.getValue('user').toString());
        }
        return member.join(',');
    },

    //Update SG Supported CI Auto Populate
    ToGetSupportedCI: function() {

        var group_id = this.getParameter('sysparm_grp');
        var CI = [];
        var grUser = new GlideRecord('cmdb_ci');
        grUser.addQuery('managed_by_group', group_id);
        grUser.query();
        while (grUser.next()) {
            CI.push(grUser.getValue('sys_id').toString());
        }
        return CI.join(',');
    },

    //get row count
    GetRowCount: function() {
        var group_id = this.getParameter('sysparm_grp');
        var grtask = new GlideAggregate('task');
        grtask.addQuery('assignment_group', group_id);
        grtask.addQuery('active', true);
        grtask.addAggregate('COUNT');
        grtask.query();
        var task = 0;
        if (grtask.next()) {
            task = grtask.getAggregate('COUNT');
            gs.log('Active task count: ' + task);
        }
        return task;
    },

    //To Check user membership and Primary group
    checkprimarygroup: function() {

        var groupID = this.getParameter('sysparm_gp');
        var usrID = gs.getUserID(); //Get current user ID	
        var returnval = 0;


        var groupGr = new GlideRecord('sys_user_group');
        if (groupGr.get(groupID)) {
            var isSupportGroup = groupGr.u_is_support_group;
        }

        if (isSupportGroup) {
            var grmember = new GlideRecord('sys_user_grmember');
            grmember.addQuery('group', groupID);
            grmember.addQuery('user', usrID);
            grmember.query();
            gs.log('Test99 ' + grmember.getRowCount());
            if (grmember.getRowCount() > 0) {
                returnval = 6; //not mem not primary
            } else {
                gs.log('Test100');
                var user = GlideRecord('sys_user');
                user.addQuery('sys_id', usrID);
                user.query();
                if (user.next())
                    if (user.u_primary_group == groupID) {
                        returnval = 1; //meber and primary
                    } else {
                        returnval = 2; //member but not primary
                    }
            }

            return returnval;

        } else {
            var grm = new GlideRecord('sys_user_grmember');
            grm.addQuery('group', groupID);
            grm.addQuery('user', usrID);
            grm.query();
            gs.log('group12');
            if (grm.getRowCount() > 0) {
                returnval = 5; //not mem not primary
            } else {
                var usr = GlideRecord('sys_user');
                usr.addQuery('sys_id', usrID);
                usr.query();
                if (usr.next())
                    if (usr.u_primary_group == groupID) {
                        returnval = 3; //meber and primary
                    } else {
                        returnval = 4; //member but not primary
                    }
            }
            return returnval;

        }
    },

    //users Current Groups Auto Populate in variable set
    getusersGroup: function() {

        var uID = this.getParameter('sysparm_gp');
        var supportgroup = 0;

        var grmember = new GlideRecord('sys_user_grmember');
        grmember.addQuery('user', uID);
        grmember.addQuery('group.active', true);
        grmember.addQuery('group.u_is_support_group', true);

        grmember.query();

        var groupArray = [];
        var groupJSON = {};

        while (grmember.next()) {
            var primarygroup = grmember.user.u_primary_group.getDisplayValue();
            var isprimarygroup = false;
            if (primarygroup == grmember.getDisplayValue('group'))
                isprimarygroup = true;

            var groupGr = new GlideRecord('sys_user_group');
            groupGr.addQuery('sys_id', grmember.group.sys_id);
            groupGr.query();
            while (groupGr.next()) {
                if (groupGr.u_is_support_group == true) {
                    supportgroup = true;
                } else {
                    supportgroup = false;
                }

                groupJSON.relationship = {
                        issupport: supportgroup ? 'Yes' : 'No',
                        group: grmember.getDisplayValue('group'),
                        isprimary: isprimarygroup ? 'Yes' : 'No'
                    },
                    groupArray.push(groupJSON.relationship);
            }
        }
        return JSON.stringify(groupArray);
    },


    //Remove Normal groups that user is already member and Remove Primary Group from group list Manage my subscription catalog

    removenormalgroups: function() {
        var userId = gs.getUserID();
        var excludeIds = [];

        var userGr = new GlideRecord('sys_user');
        userGr.get(gs.getUserID());
        var primaryGroup = userGr.u_primary_group.toString();

        var grtype = new GlideRecord('sys_user_group');
        grtype.addEncodedQuery('u_is_support_group=false^ORactive=false');
        grtype.query();
        while (grtype.next()) {
            excludeIds.push(grtype.sys_id.toString());
        }

        var memberGr = new GlideRecord('sys_user_grmember');
        memberGr.addQuery('user', userId);
        memberGr.addQuery('group.u_is_support_group', false);
        memberGr.query();
        while (memberGr.next()) {
            excludeIds.push(memberGr.getValue('group'));
        }
        excludeIds.push(primaryGroup);

        return 'sys_id NOT IN' + excludeIds;

    },

    type: 'GroupUtil'
});



Client Script : Populate group members

function onChange(control, oldValue, newValue, isLoading) {
   if (isLoading || newValue == '') {
	
    g_form.clearValue('new_group_members');
    g_form.clearValue('old_group_members');
      return;
   }

		
var group_name = g_form.getValue('select_support_group');
	
	var grmember = new GlideAjax('GroupUtil');
	grmember.addParam('sysparm_name','GetMembersFromGroup');
	grmember.addParam('sysparm_grp',group_name);
	grmember.getXML(ajaxResponse);
	
	function ajaxResponse(response){
		var resp = (response.responseXML.documentElement.getAttribute('answer'));
    resp = resp.toString();
		
		
	g_form.setValue('new_group_members', resp);
    g_form.setValue('old_group_members', resp);
		
	}
	
}
mkdir backend
cd backend

mkdir config
New-Item -ItemType File -Path ./config/db.js

mkdir controllers
New-Item -ItemType File -Path ./controllers/authController.js

mkdir models
New-Item -ItemType File -Path ./models/User.js

mkdir routes
New-Item -ItemType File -Path ./routes/authRoutes.js

mkdir middleware
New-Item -ItemType File -Path ./middleware/authMiddleware.js

New-Item -ItemType File -Path ./server.js
New-Item -ItemType File -Path ./package.json
New-Item -ItemType File -Path ./.env







echo ".env" >> .gitignore
import type {NextApiRequest, NextApiResponse} from "next";
import * as XLSX from "xlsx";

// Handle file upload and parse Excel data
export const handleFileUpload = async (file: File) => {
  const reader = new FileReader();
  return new Promise<{
    managerRecords: { imo: string; manager: string }[];
  }>((resolve) => {
    reader.onload = (e) => {
      const data = e.target?.result;
      const workbook = XLSX.read(data, { type: "binary" });
      const managerWorksheet = workbook.Sheets["Recent Changes (EffControl)"];

      // Extract IMO and EffectiveControl columns dynamically by header name
      const managerData = XLSX.utils.sheet_to_json<any>(managerWorksheet, {
        header: 1,
      });
      const headers = managerData[0];
      const imoIndex = headers.findIndex(
        (header: string) => header === "IMONumber",
      );
      const managerIndex = headers.findIndex(
        (header: string) => header === "EffectiveControl",
      );

      const managerRecords = managerData
        .slice(1)
        .map((row: any) => ({
          imo: row[imoIndex],
          manager: row[managerIndex],
        }))
        .filter((record) => record.imo && record.manager); // Filter out empty rows

      resolve({ managerRecords });
    };
    reader.readAsBinaryString(file);
  });
};

// API handler for menteithUpdate
export default async function handler(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  switch (req.method) {
    case "POST":
      if (req.body.action === "previewData") {
        try {
          const file = req.body.file;
          const { managerRecords } = await handleFileUpload(file);
          return res.status(200).json({ success: true, managerRecords });
        } catch (error) {
          return res
            .status(500)
            .json({ success: false, error: (error as Error).message });
        }
      }
      return res.status(400).json({ success: false, error: "Invalid action" });

    default:
      res.setHeader("Allow", ["POST"]);
      return res
        .status(405)
        .send(`Method ${req.method ?? "Undefined"} Not Allowed`);
  }
}
import React, { useState } from "react";
import { useDropzone } from "react-dropzone";
import { UpdateManager } from "@/types/vessel";

interface ManagerAndCoatingFormProps {
  onManagerDataUpdate: (data: UpdateManager[]) => void;
}

const ManagerAndCoatingForm: React.FC<ManagerAndCoatingFormProps> = ({
  onManagerDataUpdate,
}) => {
  const [file, setFile] = useState<File | null>(null);
  const [managerData, setManagerData] = useState<UpdateManager[]>([]);

  const onDrop = async (acceptedFiles: File[]) => {
    const uploadedFile = acceptedFiles[0];
    setFile(uploadedFile);

    const formData = new FormData();
    formData.append("file", uploadedFile);

    try {
      const response = await fetch("/api/menteithUpdate?action=previewData", {
        method: "POST",
        body: formData,
      });

      const data = await response.json();
      if (data.success) {
        const filteredManagerRecords = data.managerRecords.filter(
          (record: any) => !/unknown/i.test(record.manager),
        );
        setManagerData(filteredManagerRecords);
        onManagerDataUpdate(filteredManagerRecords);
      }
    } catch (error) {
      console.error("Error previewing file: ", error);
    }
  };

  const handleUpdate = async () => {
    try {
      // Update manager records in DB
      await fetch("/api/menteithUpdate", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          action: "updateManagerRecords",
          records: managerData,
        }),
      });

      alert("Manager data updated successfully.");
    } catch (error) {
      console.error("Error updating manager data: ", error);
    }
  };

  const { getRootProps, getInputProps } = useDropzone({ onDrop });

  return (
    <div className="p-4">
      <div
        {...getRootProps({
          className:
            "dropzone border-2 border-dashed p-4 rounded-md text-center cursor-pointer text-white",
        })}
      >
        <input {...getInputProps()} />
        <p>
          Drag & drop a vessel manager update file here, or click to select one
        </p>
      </div>

      {file && (
        <div className="mt-4">
          <p className="text-white">File: {file.name}</p>
        </div>
      )}

      <button
        onClick={handleUpdate}
        className="mt-4 rounded-md bg-blue-500 px-4 py-2 text-white"
      >
        Update Data
      </button>

      {managerData.length > 0 && (
        <div className="mt-6">
          <h3 className="mb-2 bg-gray-800 p-2 text-lg text-white">
            Manager Changes
          </h3>
          <div className="max-h-96 overflow-auto">
            <table className="min-w-full border-collapse border border-gray-400">
              <thead className="sticky top-0 bg-gray-700">
                <tr>
                  <th className="border border-gray-300 px-4 py-2 text-white">
                    IMO Number
                  </th>
                  <th className="border border-gray-300 px-4 py-2 text-white">
                    Manager
                  </th>
                </tr>
              </thead>
              <tbody>
                {managerData.map((record, index) => (
                  <tr key={index}>
                    <td className="border border-gray-300 px-4 py-2 text-white">
                      {record.imo}
                    </td>
                    <td className="border border-gray-300 px-4 py-2 text-white">
                      {record.manager}
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      )}
    </div>
  );
};

export default ManagerAndCoatingForm;
import React, { useState } from "react";
import {
  BackHomeButton,
  CommandPalletteButton,
  MinimalPage,
  PageHeading,
} from "ui";
import { BugReportButton, CommandInterface, Navigation } from "@/components";
import ManagerAndCoatingForm from "@/components/forms/managerAndCoatingForm";
import { UpdateCoating, UpdateManager } from "@/types/vessel";

const MenteithUpdater: React.FC = () => {
  const [managerData, setManagerData] = useState<UpdateManager[]>([]);
  const [coatingData, setCoatingData] = useState<UpdateCoating[]>([]);

  return (
    <MinimalPage
      pageTitle={"Update Vessel Manager | Vessel Interface"}
      pageDescription={"Vessel Interface | Update Vessel Manager"}
    >
      <div className="flex w-full flex-row justify-between pl-1 pt-1">
        <div>
          <BackHomeButton />
        </div>
        <Navigation />
        <div className="flex flex-row gap-4">
          <BugReportButton />
          <CommandPalletteButton />
          <CommandInterface />
        </div>
      </div>

      <PageHeading text="Update Vessel Manager" />

      <ManagerAndCoatingForm
        onManagerDataUpdate={setManagerData}
        onCoatingDataUpdate={setCoatingData}
      />
    </MinimalPage>
  );
};

export default MenteithUpdater;
import java.util.*;

public class Knapsack {

    public static double greedyKnapSack(ItemValue[] items, int capacity) {
        Arrays.sort(items, (a, b) -> Double.compare((double) b.profit / b.weight, (double) a.profit / a.weight));

        double totalProfit = 0;
        for (ItemValue item : items) {
            if (capacity >= item.weight) {
                capacity -= item.weight;
                totalProfit += item.profit;
            } else {
                totalProfit += (double) capacity / item.weight * item.profit;
                break;
            }
        }
        return totalProfit;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of items: ");
        int n = sc.nextInt();
        ItemValue[] items = new ItemValue[n];
        
        System.out.println("Enter weight and profit of each item:");
        for (int i = 0; i < n; i++) {
            items[i] = new ItemValue(sc.nextInt(), sc.nextInt());
        }

        System.out.print("Enter capacity: ");
        int capacity = sc.nextInt();
        
        System.out.println("Maximum profit: " + greedyKnapSack(items, capacity));
        sc.close();
    }
}

class ItemValue {
    int weight, profit;
    ItemValue(int weight, int profit) {
        this.weight = weight;
        this.profit = profit;
    }
}




function greedyKnapSack(items, n, W):
    sort items in descending order of (profit/weight)

    totalProfit = 0
    remainingCapacity = W

    for each item in items:
        if remainingCapacity >= item's weight:
            totalProfit += item's profit
            remainingCapacity -= item's weight
        else:
            fraction = remainingCapacity / item's weight
            totalProfit += fraction * item's profit
            break

    return totalProfit





Procedure GREEDY_KNAPSACK (P, W, M, X, n):

 and  contain the profits and weights respectively of the  objects arranged so that .

 is the knapsack size, and  is the solution vector.


real P(1:n), W(1:n), X(1:n), M, cu;  
integer i, n;  

X ← 0  // Initialize solution to zero  
cu ← M  // cu = remaining knapsack capacity  

for i ← 1 to n do  
    if W(i) > cu then exit endif  
    X(i) ← 1  
    cu ← cu - W(i)  
repeat  

if i ≤ n then X(i) ← cu/W(i) endif  

end GREEDY_KNAPSACK



OUTPUT:

Enter the number of items: 
3
Enter weight, profit of each item: 
10 60
20 100
30 120
Enter capacity: 
50
Maximum profit: 240.0
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

data = pd.read_csv('Pune_rent.csv')

print(data.head())
print(data.info())

X = data.drop(columns=['rent'])
y = data['rent']

X = pd.get_dummies(X, drop_first=True)

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)

mae = mean_absolute_error(y_test, y_pred)
rmse = mean_squared_error(y_test, y_pred, squared=False)
r2 = r2_score(y_test, y_pred)

print("Model Performance:")
print(f"Mean Absolute Error (MAE): {mae:.2f}")
print(f"Root Mean Squared Error (RMSE): {rmse:.2f}")
print(f"R² Score: {r2:.2f}")
star

Sat Nov 09 2024 03:56:19 GMT+0000 (Coordinated Universal Time)

@lahi2010

star

Sat Nov 09 2024 00:58:58 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Sat Nov 09 2024 00:58:10 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Sat Nov 09 2024 00:07:57 GMT+0000 (Coordinated Universal Time)

@hkrishn4a #undefined

star

Fri Nov 08 2024 23:31:16 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/4086107/fixed-page-header-overlaps-in-page-anchors

@ASPX #css #html #jquery

star

Fri Nov 08 2024 21:26:42 GMT+0000 (Coordinated Universal Time) https://forums.debian.net/viewtopic.php?t

@Dewaldt

star

Fri Nov 08 2024 21:01:29 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Fri Nov 08 2024 18:48:34 GMT+0000 (Coordinated Universal Time)

@E23CSEU1151

star

Fri Nov 08 2024 14:35:51 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Fri Nov 08 2024 12:59:21 GMT+0000 (Coordinated Universal Time)

@SubhamSahoo

star

Fri Nov 08 2024 11:41:06 GMT+0000 (Coordinated Universal Time)

@maxwlrt

star

Fri Nov 08 2024 11:40:41 GMT+0000 (Coordinated Universal Time)

@maxwlrt

star

Fri Nov 08 2024 11:40:04 GMT+0000 (Coordinated Universal Time)

@maxwlrt

star

Fri Nov 08 2024 10:27:00 GMT+0000 (Coordinated Universal Time)

@hkrishn4a #undefined

star

Fri Nov 08 2024 05:41:52 GMT+0000 (Coordinated Universal Time) https://technoderivation.com/taxi-booking-app-development

@prbhakar #softwaredevelopment #webassembly #html #appdevelopment #usa #uk #technology #android #scheme #ios

star

Fri Nov 08 2024 05:21:04 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Fri Nov 08 2024 05:13:39 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Fri Nov 08 2024 03:12:43 GMT+0000 (Coordinated Universal Time)

@viinod07

star

Fri Nov 08 2024 01:46:22 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Fri Nov 08 2024 01:31:42 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Fri Nov 08 2024 01:27:48 GMT+0000 (Coordinated Universal Time)

@FOHWellington

star

Thu Nov 07 2024 23:57:34 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Thu Nov 07 2024 23:55:16 GMT+0000 (Coordinated Universal Time)

@shahmeeriqbal

star

Thu Nov 07 2024 23:14:28 GMT+0000 (Coordinated Universal Time)

@WXAPAC

star

Thu Nov 07 2024 17:40:24 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 17:36:29 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 17:29:07 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 17:27:12 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 17:24:48 GMT+0000 (Coordinated Universal Time)

@freefire

star

Thu Nov 07 2024 16:33:21 GMT+0000 (Coordinated Universal Time)

@maxwlrt

star

Thu Nov 07 2024 15:28:51 GMT+0000 (Coordinated Universal Time)

@jrray ##terminal

star

Thu Nov 07 2024 14:51:21 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Nov 07 2024 14:44:48 GMT+0000 (Coordinated Universal Time)

@zily

star

Thu Nov 07 2024 12:22:18 GMT+0000 (Coordinated Universal Time) https://code.visualstudio.com/docs/editor/extension-marketplace

@Dewaldt

star

Thu Nov 07 2024 11:48:17 GMT+0000 (Coordinated Universal Time)

@Rishi1808

star

Thu Nov 07 2024 11:39:01 GMT+0000 (Coordinated Universal Time)

@saurabhp643

star

Thu Nov 07 2024 10:46:32 GMT+0000 (Coordinated Universal Time) https://bbs.archlinux.org/viewtopic.php?id

@Dewaldt

star

Thu Nov 07 2024 09:36:52 GMT+0000 (Coordinated Universal Time)

@MinaTimo

star

Thu Nov 07 2024 09:32:18 GMT+0000 (Coordinated Universal Time)

@amrit_v

star

Thu Nov 07 2024 08:17:45 GMT+0000 (Coordinated Universal Time)

@codeing #javascript #react.js #nodejs

star

Thu Nov 07 2024 08:00:03 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Nov 07 2024 07:59:32 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Nov 07 2024 07:58:54 GMT+0000 (Coordinated Universal Time)

@rafal_rydz

star

Thu Nov 07 2024 01:11:46 GMT+0000 (Coordinated Universal Time)

@login123

star

Thu Nov 07 2024 01:04:39 GMT+0000 (Coordinated Universal Time)

@sagar123

Save snippets that work with our extensions

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