Snippets Collections
#include<iostream>
using namespace std;

int main(){
  
  int n;
  cin>>n;
  for(int j=1;j<+n;i++){
  for( int i=1;j<=n+1-i;j++){
      cout<<j<<" ";
  }
    cout<<endl;
    
    return 0;
  }
using av_motion_api.Data;
using av_motion_api.Models;
using av_motion_api.ViewModels;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using System.Data;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using System.Text;
using System.Net;
using System.Net.Mail;
using Microsoft.AspNetCore.Cors;
using System.Text.RegularExpressions;
using SendGrid.Helpers.Mail;
using SendGrid;

namespace av_motion_api.Controllers
{
    [Route("api/[controller]")]
    [EnableCors("AllowAll")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly UserManager<User> _userManager;
        private readonly IUserClaimsPrincipalFactory<User> _claimsPrincipalFactory;
        private readonly IConfiguration _configuration;
        private readonly AppDbContext _appDbContext;
        private readonly RoleManager<Role> _roleManager;
        private readonly ILogger<UserController> _logger;

        public UserController(AppDbContext context, UserManager<User> userManager, IUserClaimsPrincipalFactory<User> claimsPrincipalFactory, IConfiguration configuration, RoleManager<Role> roleManager, ILogger<UserController> logger)
        {
            _appDbContext = context;
            _userManager = userManager;
            _claimsPrincipalFactory = claimsPrincipalFactory;
            _configuration = configuration;
            _roleManager = roleManager;
            _logger = logger;
        }

        ////addUser
        //[HttpPost]
        //[Route("Register")]
        //public async Task<IActionResult> Register(UserViewModel uvm)
        //{
        //    var user = await _userManager.FindByEmailAsync(uvm.Email);
        //    int lastUserID = _appDbContext.Users
        //                     .OrderByDescending(u => u.User_ID)
        //                     .Select(u => u.User_ID)
        //                     .FirstOrDefault();

        //    if (user == null)
        //    {
        //        user = new User
        //        {
        //            User_ID = lastUserID + 1,
        //            Name = uvm.Name,
        //            Surname = uvm.Surname,
        //            UserName = uvm.Email,
        //            Email = uvm.Email,
        //            PasswordHash = uvm.Password,
        //            User_Status_ID = uvm.User_Status_ID,
        //            User_Type_ID = uvm.User_Type_ID,
        //            PhoneNumber = uvm.PhoneNumber,
        //            Date_of_Birth = uvm.Date_of_Birth,
        //            ID_Number = uvm.Id_Number,
        //            Physical_Address = uvm.Physical_Address,
        //            Photo = uvm.Photo
        //        };

        //        IdentityResult result = await _userManager.CreateAsync(user, uvm.Password);

        //        if (result.Succeeded)
        //        {
        //            // Assign role based on User_Type_ID
        //            string roleName = GetRoleNameByUserType(uvm.User_Type_ID);
        //            if (!string.IsNullOrEmpty(roleName))
        //            {
        //                var roleResult = await _userManager.AddToRoleAsync(user, roleName);
        //                if (!roleResult.Succeeded)
        //                {
        //                    return BadRequest(roleResult.Errors);
        //                }
        //            }
        //        }
        //        else
        //        {
        //            return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
        //        }
        //    }
        //    else
        //    {
        //        return Forbid("Account already exists.");
        //    }

        //    return Ok();
        //}

        //private string GetRoleNameByUserType(int userTypeId)
        //{
        //    return userTypeId switch
        //    {
        //        1 => "Administrator",
        //        2 => "Employee",
        //        3 => "Member",
        //        _ => string.Empty,
        //    };
        //}

        //addUser
        [HttpPost]
        [DisableRequestSizeLimit]
        [Route("Register")]
        public async Task<IActionResult> Register([FromForm] UserViewModel uvm)
        {
            try
            {
                var formCollection = await Request.ReadFormAsync();
                var photo = formCollection.Files.FirstOrDefault();

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

                // Validate Phone Number Pattern
                var phoneNumberPattern = @"^\d{10}$";

                bool isValidPhoneNumber = Regex.IsMatch(uvm.PhoneNumber, phoneNumberPattern);

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

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

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

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

                            IdentityResult result = await _userManager.CreateAsync(user);

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


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

        // Method to validate South African ID number
        private bool IsValidSouthAfricanIDNumber(string idNumber, DateTime dateOfBirth)
        {
            // Check if the ID number is exactly 13 digits long
            if (idNumber.Length != 13 || !long.TryParse(idNumber, out _))
            {
                return false;
            }

            // Validate date of birth (first six digits)
            string dateOfBirthPart = idNumber.Substring(0, 6);
            if (!DateTime.TryParseExact(dateOfBirthPart, "yyMMdd", null, System.Globalization.DateTimeStyles.None, out DateTime parsedDate))
            {
                return false;
            }

            // Check if the last two digits of the ID number match the last two digits of the year of birth
            if (parsedDate.Year % 100 != dateOfBirth.Year % 100)
            {
                return false;
            }

            // If it passes the length, date of birth, and year checks, it is considered valid
            return true;
        }


        private string GetRoleNameByUserType(int userTypeId)
        {
            return userTypeId switch
            {
                1 => "Administrator",
                2 => "Employee",
                3 => "Member",
                _ => string.Empty,
            };
        }

        [HttpPost]
        [Route("Login")]
        public async Task<ActionResult> Login(LoginViewModel lv)
        {
            var user = await _userManager.FindByNameAsync(lv.Email);

            if (user != null && await _userManager.CheckPasswordAsync(user, lv.Password))
            {
                try
                {
                    var principal = await _claimsPrincipalFactory.CreateAsync(user);
                    return await GenerateJWTToken(user);
                }
                catch (Exception)
                {

                    return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                }
            }
            else
            {
                return NotFound("Incorrect email or password, Please Try Again");
            }
        }

        [HttpGet]
        private async Task<ActionResult> GenerateJWTToken(User user)
        {
            var role = await _userManager.GetRolesAsync(user);
            IdentityOptions _identityOptions = new IdentityOptions();
            // Create JWT Token
            var claims = new List<Claim>
            {
                new Claim(JwtRegisteredClaimNames.Sub, user.Email),
                new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
                new Claim(JwtRegisteredClaimNames.UniqueName, user.UserName),
                // Add user ID claim
                new Claim("userId", user.Id.ToString()),

                new Claim("User_Type_ID", user.User_Type_ID.ToString()),

            };

            if (role.Count() > 0)
            {
                claims.Add(new Claim(_identityOptions.ClaimsIdentity.RoleClaimType, role.FirstOrDefault()));
            }

            var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_configuration["Tokens:Key"]));
            var credentials = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

            var token = new JwtSecurityToken(
               issuer:  _configuration["Tokens:Issuer"],
               audience: _configuration["Tokens:Audience"],
               claims: claims,
               signingCredentials: credentials,
               expires: DateTime.UtcNow.AddHours(3)
            );

            return Created("", new
            {

                token = new JwtSecurityTokenHandler().WriteToken(token),
                user = user.UserName,

                userTypeId = user.User_Type_ID,
                // Include user ID in the response
                userId = user.Id
            });
        }

        [HttpPost]
        [Route("ChangePassword")]
        public async Task<IActionResult> ChangePassword(int id, ChangePasswordViewModel cpvm)
        {
            var user = await _userManager.FindByIdAsync(id.ToString());
            if (user == null)
            {
                return NotFound("User not found.");
            }

            var result = await _userManager.ChangePasswordAsync(user, cpvm.CurrentPassword, cpvm.NewPassword);
            if (result.Succeeded)
            {
                return Ok("Password changed successfully.");
            }
            else
            {
                return BadRequest(result.Errors);
            }
        }

        [HttpPut]
        [Route("editUser/{id}")]
        public async Task<IActionResult> EditUser(int id, [FromForm] UpdateUserViewModel uv)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return NotFound("User not found.");
                }

                // Read the form data to get the photo file
                var formCollection = await Request.ReadFormAsync();
                var photo = formCollection.Files.FirstOrDefault();

                user.Name = uv.Name;
                user.Surname = uv.Surname;
                user.Email = uv.Email;
                user.Physical_Address = uv.Physical_Address;
                user.PhoneNumber = uv.PhoneNumber;

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

                        user.Photo = base64Image; // Store the base64 string of the photo
                    }
                }

                // Update the user
                var result = await _userManager.UpdateAsync(user);

                if (result.Succeeded)
                {
                    return Ok("User updated successfully.");
                }
                else
                {
                    return BadRequest(result.Errors);
                }
            }
            catch (Exception)
            {
                return BadRequest("An Error Occurred, Please Try Again");
            }
        }


        [HttpDelete]
        [Route("deleteUser/{id}")]
        public async Task<IActionResult> DeleteUser(int id)
        {
            try
            {
                var user = await _userManager.FindByIdAsync(id.ToString());

                if (user == null)
                {
                    return NotFound("User not found.");
                }

                var result = await _userManager.DeleteAsync(user);

                if (result.Succeeded)
                {
                    return Ok();
                }
                else
                {
                    return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
                }
            }
            catch (Exception)
            {

                return BadRequest("An Error Occured, Please Try Again");
            }
        }

        [HttpGet]
        [Route("getAllUsers")]
        public IActionResult GetAllUsers()
        {
            try
            {
                var users = _userManager.Users.ToList();


                if (users == null || users.Count == 0)
                {
                    return NotFound("No users found.");
                }

                return Ok(users);
            }
            catch (Exception)
            {

                return BadRequest("An Error Occured, Please Try Again");
            }
        }

        [HttpGet]
        [Route("getUserById/{id}")]
        public async Task<IActionResult> GetUserById(int id)
        {
            try
            {
                var u = await _appDbContext.Users
                                .Include(u => u.User_Status)
                                .Include(u => u.User_Type)
                                .FirstOrDefaultAsync(u => u.Id == id);

                var user = new
                {
                    u.Id,
                    u.Name,
                    u.Surname,
                    u.Email,
                    u.Physical_Address,
                    u.PhoneNumber,
                    u.Date_of_Birth,
                    UserStatus = u.User_Status.User_Status_Description,
                    UserType = u.User_Type.User_Type_Name,
                    u.Photo,
                    u.ID_Number
                };

                return Ok(user);
            }
            catch (Exception ex)
            {
                // Log the exception for debugging
                Console.WriteLine(ex.Message);
                return BadRequest("An error occurred while fetching user details.");
            }
        }


        [HttpGet("GetMemberByUserId/{userId}")]
        public async Task<ActionResult<Member>> GetMemberByUserId(int userId)
        {
            var member = await _appDbContext.Members.FirstOrDefaultAsync(m => m.User_ID == userId);
            if (member == null)
            {
                return NotFound();
            }
            return Ok(member);
        }

        [HttpGet("employee")]
        public async Task<ActionResult<IEnumerable<EmployeeViewModel>>> GetEmployees()
        {
            var query = await( from e in _appDbContext.Employees
                        join u in _appDbContext.Users on e.User_ID equals u.User_ID
                        select new EmployeeViewModel
                        {
                            employee_ID = e.Employee_ID,
                            employee_name = u.Name
                        }).ToListAsync();

            return query;

        }
        //Roles

        [HttpPost]
        [Route("CreateRole")]
        public async Task<IActionResult> CreateRole(string roleName)
        {
            var role = await _roleManager.FindByNameAsync(roleName);
            if (role == null)
            {
                role = new Role
                {
                    Name = roleName,
                    NormalizedName = roleName.ToUpper(),
                    isEditable = true,
                };

                var result = await _roleManager.CreateAsync(role);
                if (!result.Succeeded) return BadRequest(result.Errors);
            }
            else
            {
                return Forbid("Role already exists.");
            }

            return Ok();
        }

        [HttpPost]
        [Route("AssignRole")]
        public async Task<IActionResult> AssignRole(string emailAddress, string roleName)
        {
            var user = await _userManager.FindByEmailAsync(emailAddress);
            if (user == null) return NotFound();

            var result = await _userManager.AddToRoleAsync(user, roleName);
            if (result.Succeeded) return Ok();

            return BadRequest(result.Errors);
        }


        [HttpPost("ForgotPassword")]
        public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model)
        {
            try
            {
                if (string.IsNullOrEmpty(model.Email))
                {
                    return BadRequest("Email is required.");
                }

                var user = await _userManager.FindByEmailAsync(model.Email);
                if (user == null)
                {
                    return Ok("User does not exist.");
                }

                var token = await _userManager.GeneratePasswordResetTokenAsync(user);
                var resetLink = Url.Action("ResetPassword", "User",
                                           new { token, email = user.Email },
                                           protocol: HttpContext.Request.Scheme);

                await SendResetPasswordEmail(model.Email, resetLink);

                return Ok("Please check your email for password reset instructions.");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending reset password email.");
                return StatusCode(StatusCodes.Status500InternalServerError, "Error sending reset password email.");
            }
        }

        [HttpPost("ResetPassword")]
        public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest("Invalid data.");
            }

            var user = await _userManager.FindByEmailAsync(model.Email);
            if (user == null)
            {
                return NotFound("User not found.");
            }

            var result = await _userManager.ResetPasswordAsync(user, model.Token, model.Password);
            if (result.Succeeded)
            {
                return Ok("Password has been reset successfully.");
            }

            return BadRequest("Error while resetting the password.");
        }

        private async Task SendResetPasswordEmail(string email, string resetLink)
        {
            try
            {
                var apiKey = _configuration["SendGrid:ApiKey"];
                var client = new SendGridClient(apiKey);
                var from = new EmailAddress(_configuration["SendGrid:FromEmail"], _configuration["SendGrid:FromName"]);
                var to = new EmailAddress(email);
                var subject = "Reset Password";
                var htmlContent = $"<h4>Reset your password by <a href='{resetLink}'>clicking here</a></h4>";
                var msg = MailHelper.CreateSingleEmail(from, to, subject, null, htmlContent);

                var response = await client.SendEmailAsync(msg);
                if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Accepted)
                {
                    throw new Exception($"Failed to send email. Status code: {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error sending reset password email.");
                throw;
            }
        }
    }
}
void deleteNode (node* &head, node* &tail, int position) {
  // delete first node
  if (position == 1) {
    node* temp = head;
    temp -> next -> prev = NULL;
    head = temp -> next;
    temp -> next = NULL;
    delete temp;
    return;
  }
  node* curr = head;
  node* back = NULL;
  int cnt = 1;
  while (cnt < position) {
    back = curr;
    curr = curr -> next;
    cnt++;
  }
  //delete last node 
  if (curr -> next == NULL) {
    tail = back;
    back -> next = NULL;
    curr -> prev = NULL;
    delete curr;
    return;
  }
  // delete in between node 
  back -> next = curr -> next;
  curr -> next -> prev = back;
  curr -> next = NULL;
  curr -> prev = NULL;
  delete curr;
}
void insertAtPosition(node *&head, node *&tail, int position, int d) {
  // insert at start
  if (position == 1) {
    insertAtHead(head, tail, d);
    return;
  }
  node *temp = new node(d);
  node *curr = head;
  int cnt = 1;
  while (cnt < position - 1) {
    curr = curr->next;
    cnt++;
  }
  // insert at last
  if (curr->next == NULL) {
    insertAtTail(tail, head, d);
    return;
  } else {
    temp->next = curr->next;
    curr->next = temp;
    temp->prev = curr;
    curr->next->prev = temp;
  }
}
void insertAtTail(node *&tail, node* &head, int d) {
  node *temp = new node(d);
  if (tail == NULL) {
    tail = head = temp;
  } else {
    tail->next = temp;
    temp->prev = tail;
    tail = temp;
  }
}
void insertAtHead(node *&head, node* & tail, int d) {
  node *temp = new node(d);
  if (head == NULL) {
    head = tail = temp;
  } else {
    head->prev = temp;
    temp->next = head;
    head = temp;
  }
}
int getLen(node *head) {
  int len = 0;
  node *temp = head;
  while (temp != NULL) {
    len++;
    temp = temp->next;
  }
  return len;
}
class node {
public:
  int data;
  node *next;
  node *prev;
  node(int d) {
    this->data = d;
    this->next = NULL;
    this->prev = NULL;
  }
  ~node() {
    int value = this -> data;
    if (next != NULL) {
      delete next;
      next = NULL;
    }
    cout << "memory free for node with data " << value << endl;
  }
};
using av_motion_api.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System.Net.NetworkInformation;
using System.Reflection.Emit;
using System.Security.Claims;
using System.Xml.Linq;

namespace av_motion_api.Data
{
    public class AppDbContext : IdentityDbContext<User, Role, int>

    {
        public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

        //set tables


        public DbSet<Attendance_List> Attendance_Lists { get; set; }
        public DbSet<Audit_Trail> Audit_Trails { get; set; }
        public DbSet<Booking> Bookings { get; set; }
        public DbSet<Booking_Time_Slot> Booking_Time_Slots { get; set; }
        public DbSet<Contract> Contracts { get; set; }
        public DbSet<Contract_History> Contract_History { get; set; }
        public DbSet<Contract_Type> Contract_Types { get; set; }
        public DbSet<Discount> Discounts { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Employee_Type> Employee_Types { get; set; }
        public DbSet<Equipment> Equipment { get; set; }
        public DbSet<Inspection> Inspection { get; set; }
        public DbSet<Inspection_Status> Inspection_Status { get; set; }
        public DbSet<Inspection_Type> Inspection_Type { get; set; }
        public DbSet<Inventory> Inventory { get; set; }
        public DbSet<Lesson_Plan> Lesson_Plans { get; set; }

        public DbSet<Lesson_Plan_Workout> lesson_Plan_Workout { get; set; }

        public DbSet<Member> Members { get; set; }
        public DbSet<Order> Orders { get; set; }
        public DbSet<Order_Line> Order_Lines { get; set; }
        public DbSet<Order_Status> Order_Status { get; set; }
        public DbSet<Outstanding_Payment> Outstanding_Payments { get; set; }
        public DbSet<Owner> Owners { get; set; }
        public DbSet<Payment> Payments { get; set; }
        public DbSet<Payment_Method> Payment_Methods { get; set; }
        public DbSet<Payment_Type> Payment_Types { get; set; }
        public DbSet<Price> Prices { get; set; }
        public DbSet<Product> Products { get; set; }
        public DbSet<Product_Category> Product_Categories { get; set; }
        public DbSet<Received_Supplier_Order> Received_Supplier_Orders { get; set; }
        public DbSet<Received_Supplier_Order_Line> Received_Supplier_Order_Lines { get; set; }
        public DbSet<Report> Reports { get; set; }
        public DbSet<Reward> Rewards { get; set; }

        public DbSet<Role> Roles { get; set; }
        public DbSet<Reward_Member> Reward_Members { get; set; }
        public DbSet<Reward_Type> Reward_Types { get; set; }
        public DbSet<Shift> Shifts { get; set; }
        public DbSet<Supplier> Suppliers { get; set; }
        public DbSet<Supplier_Order> Supplier_Orders { get; set; }
        public DbSet<Supplier_Order_Line> Supplier_Order_Lines { get; set; }
        public DbSet<Time_Slot> Time_Slots { get; set; }

        public DbSet<User> Users { get; set; }
        public DbSet<User_Status> Users_Status{ get; set; }

        public DbSet<User_Type> User_Types { get; set; }
        public DbSet<VAT> VAT { get; set; }

        public DbSet<Workout_Category> Workout_Category { get; set; }
        public DbSet<Workout> Workout { get; set; }
  
        public DbSet<Write_Off> Write_Offs { get; set; }



        protected override void OnModelCreating(ModelBuilder builder)
        {
            //Renaming of Default asp Tables
            builder.Entity<User>().ToTable("Users");
            builder.Entity<IdentityUserRole<int>>().ToTable("User_Roles");
            builder.Entity<IdentityUserLogin<int>>().ToTable("User_Logins");
            builder.Entity<Role>().ToTable("Roles");
            builder.Entity<IdentityRoleClaim<int>>().ToTable("Role_Claims");
            builder.Entity<IdentityUserClaim<int>>().ToTable("User_Claims");
            builder.Entity<IdentityUserToken<int>>().ToTable("Tokens");

            //Validation fix for database, specifying coulm types to be type decimal
            builder.Entity<Contract>()
           .Property(c => c.Initial_Fee)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<VAT>()
            .Property(v => v.VAT_Percentage)
            .HasColumnType("decimal(18, 2)");

            builder.Entity<Order>()
           .Property(o => o.Total_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Outstanding_Payment>()
           .Property(op => op.Amount_Due)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Outstanding_Payment>()
           .Property(op => op.Late_Fee)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Payment>()
           .Property(pay => pay.Amount)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Price>()
           .Property(pr => pr.Unit_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Supplier_Order>()
           .Property(so => so.Total_Price)
           .HasColumnType("decimal(18, 2)");

            builder.Entity<Discount>()
           .Property(d => d.Discount_Percentage)
           .HasColumnType("decimal(18, 2)");

            //Delete cascade error fix
            builder.Entity<Payment>()
            .HasOne(p => p.Payment_Type)
            .WithMany()
            .HasForeignKey(p => p.Payment_Type_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Supplier_Order_Line>()
             .HasOne(s => s.Product)
             .WithMany()
             .HasForeignKey(s => s.Product_ID)
             .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Supplier_Order_Line>()
            .HasOne(s => s.Supplier)
            .WithMany()
            .HasForeignKey(s => s.Supplier_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Received_Supplier_Order_Line>()
            .HasOne(r => r.Received_Supplier_Order)
            .WithMany()
            .HasForeignKey(r => r.Received_Supplier_Order_ID)
            .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Received_Supplier_Order_Line>()
            .HasOne(r => r.Supplier_Order)
            .WithMany()
            .HasForeignKey(r => r.Supplier_Order_ID)
            .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Received_Supplier_Order_Line>()
            .HasOne(r => r.Product)
            .WithMany()
            .HasForeignKey(r => r.Product_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Outstanding_Payment>()
            .HasOne(op => op.Member)
            .WithMany()
            .HasForeignKey(op => op.Member_ID)
            .OnDelete(DeleteBehavior.NoAction); 

            builder.Entity<Outstanding_Payment>()
            .HasOne(op => op.Payment)
            .WithMany()
            .HasForeignKey(op => op.Payment_ID)
            .OnDelete(DeleteBehavior.NoAction);


            builder.Entity<Booking>()
            .HasOne(b => b.Member)
            .WithMany()
            .HasForeignKey(b => b.Member_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Reward_Member>()
            .HasOne(rm => rm.Member)
            .WithMany()
            .HasForeignKey(rm => rm.Member_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Reward_Member>()
            .HasOne(rm => rm.Reward)
            .WithMany()
            .HasForeignKey(rm => rm.Reward_ID)
            .OnDelete(DeleteBehavior.NoAction);

           builder.Entity<Booking_Time_Slot>()
            .HasOne(bts => bts.Booking)
            .WithMany()
            .HasForeignKey(bts => bts.Booking_ID)
            .OnDelete(DeleteBehavior.NoAction);

           builder.Entity<Booking_Time_Slot>()
            .HasOne(bts => bts.Time_Slot)
            .WithMany()
            .HasForeignKey(bts => bts.Time_Slot_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Attendance_List>()
            .HasOne(b => b.Time_Slot)
            .WithMany()
            .HasForeignKey(b => b.Time_Slot_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Lesson_Plan_Workout>()
            .HasOne(lpw => lpw.Workout)
            .WithMany()
            .HasForeignKey(lpw => lpw.Workout_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Lesson_Plan_Workout>()
            .HasOne(lpw => lpw.Lesson_Plan)
            .WithMany()
            .HasForeignKey(lpw => lpw.Lesson_Plan_ID)
            .OnDelete(DeleteBehavior.NoAction);

            builder.Entity<Workout>()
           .HasOne(w => w.Workout_Category)
           .WithMany()
           .HasForeignKey(w => w.Workout_Category_ID)
           .IsRequired()
           .OnDelete(DeleteBehavior.Restrict);

            base.OnModelCreating(builder);



            var Contract_Types = new Contract_Type[]
            {
                new Contract_Type { Contract_Type_ID = 1, Contract_Type_Name = "3-Month Membership", Contract_Description = "Three-month gym membership contract" },              
            };
            builder.Entity<Contract_Type>().HasData(Contract_Types);



            var Discounts = new Discount[]
            {
                new Discount { Discount_ID = 1, Discount_Percentage = 10.00m, Discount_Date = new DateTime(2024, 4, 10) }

            };
            builder.Entity<Discount>().HasData(Discounts);


            var Employee_Types = new Employee_Type[]
            {
                new Employee_Type { Employee_Type_ID = 1, Job_Title = "Administrator", Job_Description = "Responsible for managing administrative tasks and operations" }
            };
            builder.Entity<Employee_Type>().HasData(Employee_Types);

            var Inspection_Statuses = new Inspection_Status[]
            {
                new Inspection_Status { Inspection_Status_ID = 1, Inspection_Status_Description= "Pending" }


            };
            builder.Entity<Inspection_Status>().HasData(Inspection_Statuses);

            var Inspection_Types = new Inspection_Type[]
            {
                new Inspection_Type { Inspection_Type_ID = 1, Inspection_Type_Name = "Safety Inspection", Inspection_Type_Criteria = "Ensure compliance with safety standards" }
    
            };
            builder.Entity<Inspection_Type>().HasData(Inspection_Types);

            var Membership_Statuses = new Membership_Status[]
            {
                new Membership_Status { Membership_Status_ID = 1, Membership_Status_Description = "Active" }

            };
            builder.Entity<Membership_Status>().HasData(Membership_Statuses);

            var Newsletters = new Newsletter[]
            {
                new Newsletter { Newsletter_ID = 1, Newsletter_Title = "Fitness Tips", Newsletter_Photo = "fitness_tips.jpg", Newsletter_Description = "Stay updated with our latest fitness tips!" }

            };
            builder.Entity<Newsletter>().HasData(Newsletters);

            var Payment_Methods = new Payment_Method[]
            {
                new Payment_Method { Payment_Method_ID = 1, Payment_Method_Name = "Card" },
                new Payment_Method { Payment_Method_ID = 2, Payment_Method_Name = "EFT" },

  
            };
            builder.Entity<Payment_Method>().HasData(Payment_Methods);

            var Payment_Types = new Payment_Type[]
            {
                new Payment_Type { Payment_Type_ID = 1, Payment_Type_Name = "Online Payment" },
                new Payment_Type { Payment_Type_ID = 2, Payment_Type_Name = "Cash Payment" },
             
            };
            builder.Entity<Payment_Type>().HasData(Payment_Types);

            var Product_Categories = new Product_Category[]
            {
                new Product_Category { Product_Category_ID = 1, Category_Name = "Clothing", Category_Description = "Fitness clothing for various activities" }
            };
            builder.Entity<Product_Category>().HasData(Product_Categories);

            var Reports = new Report[]
            {
                new Report { Report_ID = 1, Report_Name = "Monthly Sales Report", Report_Description = "Report summarizing monthly sales data", Generated_Date = new DateTime(2024, 4, 10) }
            };
            builder.Entity<Report>().HasData(Reports);

            var Reward_Types = new Reward_Type[]
            {
                new Reward_Type { Reward_Type_ID = 1, Reward_Type_Name = "Membership Renewal Discount", Reward_Criteria = "Receive a discount on membership renewal after completing a certain number of workouts" }

            };
            builder.Entity<Reward_Type>().HasData(Reward_Types);

            var Suppliers = new Supplier[]
            {
                new Supplier { Supplier_ID = 1, Name = "FitnessGear", Contact_Number = "1234567890", Email_Address = "info@fitnessgear.com", Physical_Address = "123 Fitness Street, Cityville, South Africa" }
            };
            builder.Entity<Supplier>().HasData(Suppliers);


            var userStatus = new User_Status[]
            {
                new User_Status { User_Status_ID = 1, User_Status_Description = "Actived" },
                new User_Status { User_Status_ID = 2, User_Status_Description = "Deactivated" },
                new User_Status { User_Status_ID = 3, User_Status_Description = "Idle" }
            };
            builder.Entity<User_Status>().HasData(userStatus);

            var userTypes = new User_Type[]
    {
                new User_Type { User_Type_ID = 1, User_Type_Name = "Owner" },
                new User_Type { User_Type_ID = 2, User_Type_Name = "Employee" },
                new User_Type { User_Type_ID = 3, User_Type_Name = "Member" }
    };
            builder.Entity<User_Type>().HasData(userTypes);

            var Users = new User[]                
            {
                new User 
                {
                    User_ID = 1,
                    Id = 1,
                    Name = "Don",
                    Surname = "Percival",
                    ID_Number = "0203057644931",
                    Email = "DonPercival@gmail.com",
                    Physical_Address = "456 Oak Avenue",
                    PhoneNumber = "0734457681",
                    Photo = "DonProfilePic.jpg",
                    PasswordHash = "AEWR54Q35H5T4HRGRGQ",
                    Date_of_Birth = new DateTime(1994,10,11),
                    User_Type_ID =1,
                    User_Status_ID =1
                },
                new User
                {
                    User_ID = 2,
                    Id = 2,
                    Name = "Barbra",
                    Surname = "Gordon",
                    ID_Number = "1220231231312",
                    Email = "barbragordon@gmail.com",
                    Physical_Address = "456 Oak Avenue",
                    PhoneNumber = "9876543210",
                    Photo = "barbra_photo.jpg",
                    PasswordHash = "HJDKL3948SJDF3JSHFD",
                    Date_of_Birth = new DateTime(1985, 5, 15),
                    User_Type_ID =2,
                    User_Status_ID =1
                },

                new User

                {
                User_ID = 3,
                Id = 3,
                Name = "Jane",
                Surname = "Smith",
                ID_Number = "1220231231312",
                Email = "JaneSmith@gmail.com",
                Physical_Address = "456 Oak Avenue",
                PhoneNumber = "9876543210",
                Photo = "jane_smith_photo.jpg",    
                PasswordHash = "JKLFSF34JKLRE983JFSD",
                Date_of_Birth = new DateTime(1985, 5, 15),
                User_Type_ID =3,
                User_Status_ID =1
                }


            };
        builder.Entity<User>().HasData(Users);








            var Contracts = new Contract[]
            {
               new Contract { Contract_ID = 1, Subscription_Date = new DateTime(2023, 1, 1), Expiry_Date = new DateTime(2023, 4, 1), Terms_Of_Agreement = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", Approval_Status = true, Approval_Date = new DateTime(2023, 1, 1), Initial_Fee = 100.00m, Contract_Type_ID = 1, Payment_Type_ID = 1 }
            };
            builder.Entity<Contract>().HasData(Contracts);


            var ContractHistories = new Contract_History[]
            {
                new Contract_History { Contract_History_ID = 1, Modification_Date = new DateTime(2023, 5, 15), Previous_Terms = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.", Updated_Terms = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut enim ad minim veniam.", Reasons_For_Changes = "To include additional benefits for members.", Contract_ID = 1 },

            };
            builder.Entity<Contract_History>().HasData(ContractHistories);


            var VAT = new VAT[]
            {
               new VAT { VAT_ID = 1, VAT_Percentage = 15.00m, VAT_Date = new DateTime(2024, 1, 1) }
            };
            builder.Entity<VAT>().HasData(VAT);


            var Audit_Trails = new Audit_Trail[]
            {
                new Audit_Trail { Audit_Trail_ID = 1, Action = "Action description", Timestamp = DateTime.Now }

            };
            builder.Entity<Audit_Trail>().HasData(Audit_Trails);

            var Shifts = new Shift[]
            {
              new Shift { Shift_ID = 1, Start_Time = new TimeSpan(8, 0, 0), End_Time = new TimeSpan(12, 0, 0) }

            };
            builder.Entity<Shift>().HasData(Shifts);


            var Employees = new Employee[]
            {
               new Employee { Employee_ID = 1, Employment_Date = new DateTime(2024, 4, 12), Employee_Type_ID = 1 , Shift_ID =1, User_ID = 2 }
            };
            builder.Entity<Employee>().HasData(Employees);


            var Members = new Member[]
            {
               new Member { Member_ID = 1, Contract_ID = 1,User_ID = 3 }
               
            };
            builder.Entity<Member>().HasData(Members);


            var AttendanceLists = new Attendance_List[]
            {

                new Attendance_List { Attendance_ID = 1, Number_Of_Bookings = 1, Members_Present = 10, Members_Absent = 5, Time_Slot_ID = 1}
            };
            builder.Entity<Attendance_List>().HasData(AttendanceLists);


            var Bookings = new Booking[]
            {
                new Booking { Booking_ID = 1,  Member_ID = 1}
            };
            builder.Entity<Booking>().HasData(Bookings);

            var workoutcategories = new Workout_Category[]
            {
                new Workout_Category { Workout_Category_ID = 1, Workout_Category_Name = "Cardio", Workout_Category_Description = "Cardio workouts to improve endurance and burn calories." },
                new Workout_Category { Workout_Category_ID = 2, Workout_Category_Name = "Strength", Workout_Category_Description = "Strength training workouts to build muscle and increase strength." },
                new Workout_Category { Workout_Category_ID = 3, Workout_Category_Name = "Flexibility", Workout_Category_Description = "Flexibility workouts to improve range of motion and reduce injury risk." }
            };
            builder.Entity<Workout_Category>().HasData(workoutcategories);


            var workouts = new Workout[]
            {
                    new Workout
                    {
                        Workout_ID = 1,
                        Workout_Name = "Cardio Blast",
                        Workout_Description = "High-intensity cardio workout to burn calories and improve endurance.",
                        Sets = 4,
                        Reps = 10,
                        Workout_Category_ID = 1
                    },
                    new Workout
                    {
                        Workout_ID = 2,
                        Workout_Name = "Strength Training",
                        Workout_Description = "Build muscle strength and endurance.",
                        Sets = 3,
                        Reps = 12,
                        Workout_Category_ID = 2
                    },
                    new Workout
                    {
                        Workout_ID = 3,
                        Workout_Name = "Flexibility Routine",
                        Workout_Description = "Improve your flexibility with this stretching routine.",
                        Sets = 2,
                        Reps = 15,
                        Workout_Category_ID = 3
                    }
            };
            builder.Entity<Workout>().HasData(workouts);


            var Lesson_Plans = new Lesson_Plan[]
            {
                new Lesson_Plan { Lesson_Plan_ID = 1, Program_Name = "Base", Program_Description = "Base program description", }

            };
            builder.Entity<Lesson_Plan>().HasData(Lesson_Plans);


            var orderStatuses = new Order_Status[]
            {
                new Order_Status { Order_Status_ID = 1, Order_Status_Description = "Pending" },
            };
            builder.Entity<Order_Status>().HasData(orderStatuses);


            var Orders = new Order[]
            {
               new Order { Order_ID = 1, Order_Date = new DateTime(2024, 4, 12), Order_Details = "Example order details", Total_Price = 100.00m, Member_ID = 1, Order_Status_ID = 1 }
            };
            builder.Entity<Order>().HasData(Orders);


            var Outstanding_Payments = new Outstanding_Payment[]
            {
               new Outstanding_Payment { Outstanding_Payment_ID = 1, Due_Date = new DateTime(2024, 4, 12), Amount_Due = 50.00m, Late_Fee = 0.00m, Member_ID = 1, Payment_ID = 1 }
            };
            builder.Entity<Outstanding_Payment>().HasData(Outstanding_Payments);


            var Owners = new Owner[]
            {
               new Owner { Owner_ID = 1, User_ID = 1 }
            };
            builder.Entity<Owner>().HasData(Owners);


            var Payments = new Payment[]
            {
              new Payment { Payment_ID = 1, Amount = 50.00m, Payment_Date = new DateTime(2024, 4, 12), Order_ID = 1, Payment_Type_ID = 1, Payment_Method_ID = 1 }
            };
            builder.Entity<Payment>().HasData(Payments);


            var Products = new Product[]
            {
               new Product { Product_ID = 1, Product_Name = "T-Shirt", Product_Description = "Cotton Shirt sleevless", Create_Date = new DateTime(2024, 4, 12), Last_Update_Date = new DateTime(2024, 4, 12), IsActive = true,Size = "XS" ,Product_Category_ID = 1, Supplier_ID = 1 }
            };
            builder.Entity<Product>().HasData(Products);


            var prices = new Price[]
            {
                new Price { Price_ID = 1, Unit_Price = 50.00m, Product_ID = 1 }
            };
            builder.Entity<Price>().HasData(prices);


            var OrderLines = new Order_Line[]
            {
                new Order_Line { Order_Line_ID = 1, Order_ID = 1, Product_ID = 1 }

            };
            builder.Entity<Order_Line>().HasData(OrderLines);


            var Received_Supplier_Orders = new Received_Supplier_Order[]
            {
                new Received_Supplier_Order { Received_Supplier_Order_ID = 1, Supplies_Received_Date = new DateTime(20, 04, 10) }
            };

            builder.Entity<Received_Supplier_Order>().HasData(Received_Supplier_Orders);



            var Received_Supplier_Order_Lines = new Received_Supplier_Order_Line[]
            {
                new Received_Supplier_Order_Line { Received_Supplier_Order_Line_ID = 1,Received_Supplier_Order_ID = 1,Supplier_Order_ID = 1,Product_ID = 1,Received_Supplies_Quantity = 10 }
            };

            builder.Entity<Received_Supplier_Order_Line>().HasData(Received_Supplier_Order_Lines);

            var Rewards = new Reward[]
            {
                new Reward { Reward_ID = 1, IsPosted = false, Reward_Issue_Date = new DateTime(2024, 4, 10), Reward_Type_ID = 1 }

            };
            builder.Entity<Reward>().HasData(Rewards);

            var Reward_Members = new Reward_Member[]
            {
                new Reward_Member{ Reward_Member_ID = 1, IsRedeemed = false, Member_ID = 1, Reward_ID = 1}
            };
            builder.Entity<Reward_Member>().HasData(Reward_Members);

            var Roles = new Role[]
            {
                new Role{ Id = 1, Name = "Owner", NormalizedName= "OWNER", isEditable = false},
                new Role{ Id = 2, Name = "Employee", NormalizedName= "EMPLOYEE", isEditable =true},
                new Role{ Id = 3, Name = "Member", NormalizedName= "MEMBER", isEditable =true}
            };
            builder.Entity<Role>().HasData(Roles);


            int claimId = 1;
            //Owner Claims
            //for each admin claim
            var ownerClaims = new Claim[]

            {
                new Claim("Booking Manager", "Create"),
                new Claim("Booking Manager", "Read"),
                new Claim("Booking Manager", "Update"),
                new Claim("Booking Manager", "Delete"),

                new Claim("Equipment Manager", "Create"),
                new Claim("Equipment Manager", "Read"),
                new Claim("Equipment Manager", "Update"),
                new Claim("Equipment Manager", "Delete"),

                new Claim("Employee Manager", "Create"),
                new Claim("Employee Manager", "Read"),
                new Claim("Employee Manager", "Update"),
                new Claim("Employee Manager", "Delete"),

                new Claim("Inventory Manager", "Create"),
                new Claim("Inventory Manager", "Read"),
                new Claim("Inventory  Manager", "Update"),
                new Claim("Inventory Manager", "Delete"),

                new Claim("Gym Manager", "Create"),
                new Claim("Gym Manager", "Read"),
                new Claim("Gym  Manager", "Update"),
                new Claim("Gym Manager", "Delete"),
            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in ownerClaims) 
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                { 
                   Id = claimId++,
                   RoleId = Roles[0].Id,
                   ClaimType = claim.Type,
                   ClaimValue = claim.Value
                });
            }

            //Employee Claims , they are admin too but just for separation        
            //for each employee claim
            var employeeClaims = new Claim[]
            {
                new Claim("Booking Manager", "Create"),
                new Claim("Booking Manager", "Read"),
                new Claim("Booking Manager", "Update"),
                new Claim("Booking Manager", "Delete"),

                new Claim("Equipment Manager", "Create"),
                new Claim("Equipment Manager", "Read"),
                new Claim("Equipment Manager", "Update"),
                new Claim("Equipment Manager", "Delete"),

                new Claim("Employee Manager", "Read"),
                new Claim("Employee Manager", "Update"),

                new Claim("Inventory Manager", "Create"),
                new Claim("Inventory Manager", "Read"),
                new Claim("Inventory Manager", "Update"),
                new Claim("Inventory Manager", "Delete"),
            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in employeeClaims)
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                {
                    Id = claimId++,
                    RoleId = Roles[1].Id,
                    ClaimType = claim.Type,
                    ClaimValue = claim.Value
                });
            }

            var memberClaims = new Claim[]
            {
                new Claim("Booking Interface", "Create"),
                new Claim("Booking Interface", "Read"),
                new Claim("Booking Interface", "Update"),
                new Claim("Booking Interface", "Delete"),

                new Claim("Profile", "Create"),
                new Claim("Profile", "Read"),
                new Claim("Profile", "Update"),

            };
            //create a refrence of it in the Role Claims table
            foreach (var claim in memberClaims)
            {
                builder.Entity<IdentityRoleClaim<int>>().HasData(new IdentityRoleClaim<int>
                {
                    Id = claimId++,
                    RoleId = Roles[2].Id,
                    ClaimType = claim.Type,
                    ClaimValue = claim.Value
                });
            }

            var Supplier_Orders = new Supplier_Order[]
            {
                new Supplier_Order { Supplier_Order_ID = 1, Date = new DateTime(2024, 4, 10), Supplier_Order_Details = "Ordered 50 units of dumbbells and 20 yoga mats", Total_Price = 1500.00m, Supplier_ID = 1, Owner_ID = 1 }

            };
            builder.Entity<Supplier_Order>().HasData(Supplier_Orders);

            var Supplier_Order_Lines = new Supplier_Order_Line[]
            {
                new Supplier_Order_Line { Supplier_Order_Line_ID = 1, Supplier_Qauntity = 12, Supplier_ID = 1, Product_ID = 1 }

            };
            builder.Entity<Supplier_Order_Line>().HasData(Supplier_Order_Lines);

            var Inventory = new Inventory[]
            {
                new Inventory { Inventory_ID = 1, Inventory_Item_Category = "Clothes", Inventory_Item_Name = "Men's Dry-fit Tops", Inventory_Item_Quantity = 20, Inventory_Item_Photo = "dry_fit_tops.jpg", Received_Supplier_Order_ID = 1, Supplier_ID = 1 }

            };
            builder.Entity<Inventory>().HasData(Inventory);

            var Equipments = new Equipment[]
            {
                
                 new Equipment{ Equipment_ID = 1, Equipment_Name = "Treadmill", Equipment_Description = "A motorized device used for running or walking while staying in one place." }
                
            };
            builder.Entity<Equipment>().HasData(Equipments);

            var Inspections = new Inspection[]
            {
                new Inspection { Inspection_ID = 1, Inspection_Date = new DateTime(2024, 4, 12),Inspection_Notes = "Holes in AVS pants" , Equipment_ID = 1,  Inspection_Type_ID = 1, Inspection_Status_ID = 1 }

            };
            builder.Entity<Inspection>().HasData(Inspections);

            var Booking_Time_Slots = new Booking_Time_Slot[]
            {
                new Booking_Time_Slot{Booking_Time_Slot_ID = 1, Booking_ID = 1,Time_Slot_ID = 1}
            };
            builder.Entity<Booking_Time_Slot>();


            var Time_Slots = new Time_Slot[]
            {

                new Time_Slot{Time_Slot_ID = 1,Slot_Date =  new DateTime(2024, 4, 12)  , Slot_Time = DateTime.Parse("11:00:00"), Availability = true, Lesson_Plan_ID= 1, Employee_ID=1}

            };
            builder.Entity<Time_Slot>().HasData(Time_Slots);


            var Write_Offs = new Write_Off[]
            {
                new Write_Off { Write_Off_ID = 1, Date = new DateTime(2024, 4, 12), Write_Off_Reason = "Expired items", Inventory_ID = 1 }

            };
            builder.Entity<Write_Off>().HasData(Write_Offs);


            var lessonPlanWorkOuts = new Lesson_Plan_Workout[]
            {
                new Lesson_Plan_Workout {Lesson_Plan_Workout_ID =1, Lesson_Plan_ID = 1, Workout_ID = 1}
            };
            builder.Entity<Lesson_Plan_Workout>().HasData(lessonPlanWorkOuts);

        }

    }
}

<?xml version='1.0' encoding='UTF-8'?>
<Products>
    <Product>
        <name>TTS Bee-Bot Programmable Floor Robot</name>
        <product_code>IT10077B</product_code>
        <price_wholesale>XX.XX</price_rrp>
        <price_rrp>XX.XX</price_rrp>
        <stock>349.0</stock>
        <brand_id>(35, 'TTS')</brand_id>
        <description>Along with a memory of 200 steps, Bee-Bot® can now detect another Bee-Bot® or Blue-Bot® and say hello.</description>
        <descriptione_long>They will play a default sound or the students can record their own...</description_long>
        <sale_argument>Bee-Bot® is a perfect starting point for teaching control, directional language and programming.</sale_argument>
        <Images>
            <Image>https://www.insplay.eu/web/image/product.product/3488/image_raw</Image>
            <Image>https://www.insplay.eu/web/image/product.image/38470/image_raw</Image>
            <Image>https://www.insplay.eu/web/image/product.image/38471/image_raw</Image>
        </Images>
        <age_from>3.0</age_from>
        <age_to>False</age_to>
        <under_3_forbidden>True</under_3_forbidden>
        <ean>False</ean>
        <origin_country>CN</origin_country>
        <weight>0.34</weight>
        <more_info_url>www.tts-international.com</more_info_url>
        <tariff_no>95030075</tariff_no>
        <date_create>2019-01-29</date_created>
        <date_updated>2019-11-26</date_updated>
    </Product>
</Products>
void insertInPosition(node *&head, node *&tail, int d, int position) {
  if (position == 1) {
    insertAtHead(head, d);
    return;
  }

  node *temp = head;
  int count = 1;
  while (count < position - 1) {
    temp = temp->next;
    count++;
  }
  if (temp->next == NULL) {
    insertAtTail(tail, d);
    return;
  }

  node *nodeToInsert = new node(d);
  nodeToInsert->next = temp->next;
  temp->next = nodeToInsert;
}
void print (node* &head) {
  node* temp = head;
  while (temp != NULL) {
    cout << temp -> data << " ";
    temp = temp -> next;
  }
}
void insertAtTail(node *&tail, int d) {
  node *temp = new node(d);
  tail->next = temp;
  tail = temp;
}
void insertAtHead(node *&head, int d) {
  node *temp = new node(d);
  temp->next = head;
  head = temp;
}
void deleteNode(node *&head, int position) {
  if (position == 1) {
    node *temp = head;
    head = head->next;
    temp->next = NULL;
    delete temp;
  }

  else {
    node *curr = head;
    node *prev = NULL;
    int cnt = 1;
    while (cnt < position) {
      prev = curr;
      curr = curr->next;
      cnt++;
    }
    prev->next = curr->next;
    curr->next = NULL;
    delete curr;
  }
}
const test = [3, 5, 6, 7, 8, 0, "", null, undefined, "testing"];


 test.forEach(listItem);

function listItem(item, number, total) {
    return `<li class="${number}">${item} ${number} of ${total}</li>`;
}


let htmlDOM = `<ul>${test.map((item, index, array) => listItem(item, `${index + 1}`, `${array.length}`)).join("")}</ul>`;
  

//console.log(htmlDOM);

/**

'<ul><li class="1">3 1 of 10</li><li class="2">5 2 of 10</li><li class="3">6 3 of 10</li><li class="4">7 4 of 10</li><li class="5">8 5 of 10</li><li class="6">0 6 of 10</li><li class="7"> 7 of 10</li><li class="8">null 8 of 10</li><li class="9">undefined 9 of 10</li><li class="10">testing 10 of 10</li></ul>'

*/


(function () {
  "use strict";

  const person = {
    name: "John Doe",
    age: 30,
    hobbies: ["reading", "traveling", "coding"],
  };

  const { hobbies, name, age } = person; // descructure

  hobbies.forEach((item, idx) => passInfo(item, idx, { name, age })); // pass function into the foreach

  function passInfo(item, idx, ...args) {
    console.log({ item, idx, args });
  }
})();



// another example

const test = [3, 5, 6, 7, 8, 0, "", null, undefined, "testing"];

test.forEach(listItem);


 function listItem(item, number, total) {
    return `<li class="${number}">${item} ${number} of ${total}</li>`;
  }
{
  "eventId": 168,
  "associationId": 72,
  "eventTypeId": 2,
  "title": "Tech Conference 2024",
  "description": "A conference for tech enthusiasts to share ideas and innovations.",
  "cityId": 148013,
  "stateId": 32,
  "countryId": 1,
  "eventModeId": 45,
  "registrationStartDate": "2024-07-17T06:32:21.324Z",
  "registrationEndDate": "2024-07-18T06:32:21.324Z",
  "eventStartDate": "2024-07-18T06:32:21.324Z",
  "eventEndDate": "2024-07-23T06:32:21.324Z",
  "broucherUrl": "",
  "address": "Madhapur",
  "videoUrl": "https://youtube.com/shorts/t6SLjTQbPh0?si=gJ9_eiYVqS3JFsGJ",
  "eventStatusId": 0,
  "phoneCode": "+91",
  "phoneCountryId": 1,
  "contactNumber": "7898561235",
  "contactEmail": "contact@sustainablefuture.com",
  "webSite": "https://sustainablefutureforum.com",
  "geolocation": {
    "x": 17.419791987251436,
    "y": 78.32488111758651
  },
  "isFreeEvent": true,
   "noOfSeats": 100,
   "categoryId": 6,
}
// Splide JS
function splide_js_script () {
    wp_enqueue_script( 'splide-js', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/js/splide.min.js', null, null, true );
    wp_enqueue_style('splide-css', 'https://cdn.jsdelivr.net/npm/@splidejs/splide@4.1.4/dist/css/splide.min.css');
}
add_action( 'wp_enqueue_scripts', 'splide_js_script' );
import React, { useCallback, useEffect, useState } from 'react';
import { NavLink, useParams } from 'react-router-dom';
import Loader from '../common/components/Loader';
import { IRouteParams } from '../common/interfaces/IRouteParams';
import Repository from '../common/repository/repository';
import { AssetType, IAsset } from './interfaces/IAsset';
import styled from 'styled-components';
import config from '../config.json';
import Title from '../common/components/LayoutComponents/Title';
// import { Button, Col, Input, Row, UncontrolledAlert } from 'reactstrap';
import { Button, Col, Form, FormGroup, Input, Label, Row, UncontrolledAlert } from 'reactstrap';
import Asset from '../composition_riv/components/Asset';
import { IApiPostResponse } from '../common/interfaces/IApiPostResponse';
import { formatDateString } from '../common/utils/Date';
import AppRoutes from '../AppRoutes';
import { useTranslations } from '../i18n/useTranslations';
import * as Constants from "../common/constants/library-constants";
import * as Global_Constants from "../common/constants/shared-constants";
import * as Dam_Constants from "../digital_assets_management/constants/dam-constants";

const AssetContainer = styled.div`
  overflow-y: auto;
  height:100%;
  
`;

const AssetDiv = styled.div`
  display: flex;
  flex-direction: column;
`;

const AssetIllustration = styled.div`
  width: 100%;
  max-height: 270px;
  height: 270px;
  display: flex;
  justify-content: center;

  .sdc-asset {
    &.sdc-playlist {
      height: 100%;
      width: 100%;
    }
  }
`;

const AssetPropertyTitle = styled.div`
  width: 100%;
  font-weight: bold;
  justify-content: top;
`;

const AssetTagsContainer = styled.div`
  width: 100%;
  display: flex;
  width: 9rem;
`;

const TagContainer = styled.div.attrs({
  'data-testid': 'new-asset-tag-container',
})`
  display: flex;
  align-items: center;
  width: 9rem;
  padding-bottom: 0.25rem;
`;
const ScrollableContainer = styled.div`
 	 max-height: 270px;
 		  overflow-y: auto;
 		  width: 100%;
 		`;
const TagsList = styled.div.attrs({
  className: 'col-sm-9',
})`
  display: flex;
  flex-wrap: wrap;
`;

const TagButton = styled.i`
  cursor: pointer;
  padding: 0.25rem 0.5rem;
  color: darkred;
`;

export const AssetDetails = () => {
  const i18n = useTranslations()
  const [changeNameErrorMessage, setChangeNameErrorMessage] = useState('');
  const [tagsErrorMessage, setTagsErrorMessage] = useState('');
  const [resultLoaded, setResultLoaded] = useState(false);
  const [assetVersions, setAssetVersions] = useState([] as IAsset[]);
  const [selectedAsset, setSelectedAsset] = useState(null as unknown as IAsset);
  const [selectedAssetIndex, setSelectedAssetIndex] = useState(0);
  const [selectedAssetRoute, setSelectedAssetRoute] = useState<
    string | undefined
  >('');
  const [showEditNameForm, setShowEditNameForm] = useState(false);
  const [newAssetName, setNewAssetName] = useState('');
  const [newTag, setNewTag] = useState('');
  const [sequencesForScene, setSequencesForScene] = useState<IAsset[]>([]);
  const { id } = useParams<IRouteParams>();

  const retrieveAssetVersions = useCallback(async () => {
    setResultLoaded(false);

    const assets = await Repository.getInstance().getAssetVersions(
      parseInt(id)
    );

    setAssetVersions(assets);
    if (
      assets !== null &&
      assets[selectedAssetIndex] !== undefined &&
      assets[selectedAssetIndex] !== null
    ) {
      setSelectedAsset(assets[selectedAssetIndex]);
      setSelectedAssetRoute(assetToRoute(assets[selectedAssetIndex]));
    } else {
      setSelectedAsset(null as unknown as IAsset);
    }
    setResultLoaded(true);
  }, [id, selectedAssetIndex]);

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

  useEffect(() => {
    if (!selectedAsset) return;
    if (selectedAsset.file_type !== AssetType.Scene) return;
    const retrieveSequences = async () => {
      const sequenceNames =
        await Repository.getInstance().getSequencesUsingScene(
          selectedAsset.name
        );
      setSequencesForScene(sequenceNames);
    };
    retrieveSequences();
  }, [selectedAsset]);

  function changeSelectedVersion(e: React.ChangeEvent<HTMLInputElement>) {
    const selectedId = e.target.value;
    const selectedIndex = assetVersions.findIndex((ast) => ast.id.toString() === selectedId);
    setSelectedAssetIndex(selectedIndex);
  }

  function toggleEditNameForm() {
    setShowEditNameForm(!showEditNameForm);
  }

  function changeNewAssetName(evt: React.ChangeEvent<HTMLInputElement>) {
    setNewAssetName(evt.target.value);
  }

  function changeNewTag(evt: React.ChangeEvent<HTMLInputElement>) {
    setNewTag(evt.target.value);
  }

  function validateNewNameForm() {
    return newAssetName !== '' && newAssetName !== selectedAsset?.name;
  }

  async function sendNewName() {
    setChangeNameErrorMessage('');
    setResultLoaded(false);

    const data = new FormData();
    data.append('newName', newAssetName);
    const apiResponse = new IApiPostResponse();
    await Repository.getInstance().editAssetName(
      selectedAsset?.id,
      data,
      apiResponse,
      i18n(Global_Constants.GLOBAL, Dam_Constants.CHECK_NETWORK_STATUS)
    );
    if (apiResponse.errorMessage != null) {
      setChangeNameErrorMessage(apiResponse.errorMessage);
    }
    await retrieveAssetVersions();
  }

  async function removeTag(tagId: number) {
    setResultLoaded(false);
    await Repository.getInstance().removeTagFromAsset(selectedAsset?.id, tagId);
    await retrieveAssetVersions();
  }

  async function addTag(tagName: string) {
    if (selectedAsset?.tags.findIndex((t) => t.name === tagName) !== -1) return;

    setTagsErrorMessage('');
    setResultLoaded(false);

    const data = new FormData();
    data.append('assetId', selectedAsset?.id.toString());
    data.append('tagName', tagName);

    const apiResponse = new IApiPostResponse();
    await Repository.getInstance().addTagToAsset(data, apiResponse);
    if (apiResponse.errorMessage != null) {
      setTagsErrorMessage(apiResponse.errorMessage);
    }
    setNewTag('');
    await retrieveAssetVersions();
  }

  const setAssetIsSubstitution = async (checked: boolean) => {
    setResultLoaded(false);
    if (checked)
      await Repository.getInstance().setIsSubstitutionAsset(selectedAsset.id);
    else
      await Repository.getInstance().UnsetIsSubstitutionAsset(selectedAsset.id);
    await retrieveAssetVersions();
  };

  const assetTypeToDescription = (assetType: AssetType) => {
    const types = new Map([
      [AssetType.Image, 'Image'],
      [AssetType.Scene, 'Scene'],
      [AssetType.Sound, 'Son'],
      [AssetType.Video, 'Vidéo'],
      [AssetType.Sequence, 'Séquence'],
      [AssetType.Text, 'Texte'],
      [AssetType.Font, 'Police'],
      [AssetType.Style, 'Style'],
      [AssetType.PredefMessage, 'Message'],
      [AssetType.Programmation, 'Programmation'],
    ]);
    return types.get(assetType);
  };

  const assetToRoute = (asset: IAsset) => {
    const types = new Map([
      [AssetType.Sequence, AppRoutes.sequence(asset.id.toString())],
      [AssetType.Scene, AppRoutes.editor(asset.id.toString())],
      [
        AssetType.PredefMessage,
        AppRoutes.predefinedMessage(asset.id.toString()),
      ],
      [AssetType.Playlist, AppRoutes.audioPlaylist(asset.id.toString())],
      [AssetType.Style, AppRoutes.style(asset.id.toString())],
      [AssetType.Programmation, AppRoutes.programmation(asset.id.toString())],
    ]);

    return types.get(asset.file_type);
  };

  return (
    <AssetContainer>
      {!resultLoaded && <Loader />}
      <Title>{i18n(Global_Constants.LIBRARY, Constants.RESOURCE_DETAILS)}: {selectedAsset?.name}</Title>
      <Form>
        <AssetDiv>
          <AssetIllustration>
            {selectedAsset && <Asset asset={selectedAsset} />}
          </AssetIllustration>

          <FormGroup row >
            <Label for="version" sm={3}><AssetPropertyTitle>Version</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input
                type="select"
                id="version"
                value={selectedAsset?.id}
                onChange={changeSelectedVersion}
                disabled={!assetVersions || !assetVersions.length || assetVersions.length === 1}
              >
                {assetVersions?.map((asset, index) => (
                  <option key={`${asset.version}-${index}`} value={asset.id}>
                    {asset.version}
                  </option>
                ))}
              </Input>
            </Col>
          </FormGroup>

          <FormGroup row>
            <Label for="assetName" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.GLOBAL, Global_Constants.NAME)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <div className="d-flex align-items-center">
                {selectedAsset?.name}
                <i
                  className={`ms-1 fa fa-lg fa-pencil-square${showEditNameForm ? '' : '-o'}`}
                  style={{ cursor: 'pointer' }}
                  onClick={toggleEditNameForm}
                />
              </div>
            </Col>
          </FormGroup>

          {showEditNameForm && (
            <FormGroup row>
              <Label for="newAssetName" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.NEW_NAME)}</AssetPropertyTitle></Label>
              <Col sm={3}>
                <Input
                  type="text"
                  id="newAssetName"
                  value={newAssetName}
                  onChange={changeNewAssetName}
                  placeholder={selectedAsset.name}
                />
                <Button
                  className="btn btn-danger mt-1"
                  disabled={!validateNewNameForm()}
                  onClick={sendNewName}
                >
                  {i18n(Global_Constants.LIBRARY, Global_Constants.CHANGE)}
                </Button>
              </Col>
              {changeNameErrorMessage && (
                <UncontrolledAlert color="danger">
                  Error: {changeNameErrorMessage}
                </UncontrolledAlert>
              )}
            </FormGroup>
          )}

          <FormGroup row>
            <Label for="creationDate" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.GLOBAL, Global_Constants.CREATION_DATE)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input type="text" id="creationDate" value={formatDateString(selectedAsset?.created_at)} readOnly />
            </Col>
          </FormGroup>

          <FormGroup row>
            <Label for="modificationDate" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.GLOBAL, Global_Constants.LAST_MODIFICATION_DATE)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input type="text" id="modificationDate" value={formatDateString(selectedAsset?.updated_at)} readOnly />
            </Col>
          </FormGroup>

          <FormGroup row>
            <Label for="resourceType" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.RESOURCE_TYPE)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input type="text" id="resourceType" value={assetTypeToDescription(selectedAsset?.file_type)} readOnly />
            </Col>
          </FormGroup>

          <FormGroup row>
            <Label for="dimension" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.SIZE)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <Input type="text" id="dimension" value={String(selectedAsset?.dimension)} readOnly />
            </Col>
          </FormGroup>

          {selectedAsset && (selectedAsset?.file_type === AssetType.Image || selectedAsset?.file_type === AssetType.Text || selectedAsset?.file_type === AssetType.Style) && (
            <FormGroup row>
              <Label for="substitute" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.SUBSTITUTE_MESSAGE)}</AssetPropertyTitle></Label>
              <Col sm={3}>
                <Input
                  id="isSubstitution"
                  type="checkbox"
                  className="form-check-input"
                  checked={selectedAsset?.isSubstitution ?? false}
                  onChange={(e) => setAssetIsSubstitution(e.target.checked)}
                />
              </Col>
            </FormGroup>
          )}

          <FormGroup row>
            <Label for="keywords" sm={3}><AssetPropertyTitle>{i18n(Global_Constants.LIBRARY, Constants.KEYWORDS)}</AssetPropertyTitle></Label>
            <Col sm={3}>
              <AssetTagsContainer>
                <TagsList>
                  {selectedAsset?.tags.map((tag, i) => (
                    <TagContainer key={`asset-tag-${selectedAsset.name}-${i}`}>
                      <Input type="text" value={tag.name} readOnly />
                      <TagButton className="fa fa-xs fa-close" onClick={() => removeTag(tag.id)} />
                    </TagContainer>
                  ))}
                  <TagContainer>
                    <Input
                      type="text"
                      id="new-asset-tag"
                      value={newTag}
                      placeholder={i18n(Global_Constants.LIBRARY, Constants.KEYWORD)}
                      onChange={changeNewTag}
                    />
                    <TagButton className={`fa fa-plus ${newTag === '' ? 'sdc-disabled' : ''}`} onClick={() => addTag(newTag)} />
                  </TagContainer>
                </TagsList>
              </AssetTagsContainer>
              {tagsErrorMessage && (
                <UncontrolledAlert color="danger">
                  Error: {tagsErrorMessage}
                </UncontrolledAlert>
              )}
            </Col>
          </FormGroup>

          {selectedAsset?.file_type === AssetType.Scene && sequencesForScene.length > 0 && (
            <FormGroup row>
              <Label for="sequences" sm={3}><AssetPropertyTitle>Utilized in sequences</AssetPropertyTitle></Label>
              <Col sm={3}>
                {sequencesForScene.map((s) => (
                  <div key={`seq-for-scene-${s.name}`}>
                    <NavLink to={AppRoutes.assetDetails(s.id.toString())}>
                      {s.name}
                    </NavLink>
                  </div>
                ))}
              </Col>
            </FormGroup>
          )}

          {selectedAssetRoute && (
            <div>
              <NavLink className="btn btn-secondary" to={selectedAssetRoute}>
                {i18n(Global_Constants.INFORMATION, Global_Constants.MODIFY_BUTTON)}
              </NavLink>
            </div>
          )}
        </AssetDiv>
      </Form>
    </AssetContainer>
  );
};

export default AssetDetails;
<div class="bottom-row">
    <div class="footer-nav">
        <small>
            <ul>
                <li>
                    <a href="/returnpolicy">Policy</a>
                </li>
                <li>
                    <a href="/privacypolicy">Privacy</a>
                </li>
                <li>
                    <a href="/termsandconditions">Terms</a>
                </li>
                <li>
                    <a href="/sitemap">Site Map</a>
                </li>
            </ul>
        </small>
    </div>
	<div class="footer-copyright">
        <a href="https://www.dealerspike.com/" target="_blank" title="Powered by Dealer Spike">
            <small>Copyright© <script>document.write(new Date().getFullYear())</script> Dealer Spike | All Rights Reserved</small>
        </a>
    </div>
	<div class="footer-ds-logo">
		<a href="https://www.dealerspike.com" title="Powered by Dealer Spike" target="_blank">
			<img src="//published-assets.ari-build.com/Content/Published/Site/{{Site.Id}}/images/ds-logo.png" alt="Powered by Dealer Spike" width="101" height="auto">
		</a>
	</div>
</div>
curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
chmod +x wp-cli.phar
# Download the latest available Chrome for Testing binary corresponding to the Stable channel.
npx @puppeteer/browsers install chrome@stable

# Download a specific Chrome for Testing version.
npx @puppeteer/browsers install chrome@116.0.5793.0

# Download the latest available ChromeDriver version corresponding to the Canary channel.
npx @puppeteer/browsers install chromedriver@canary

# Download a specific ChromeDriver version.
npx @puppeteer/browsers install chromedriver@116.0.5793.0
SELECT 
    CASE 
        WHEN column1 IS NULL OR column1 = 0 THEN column2
        ELSE column1
    END AS result_column
FROM example_table;


SELECT 
    COALESCE(NULLIF(column1, 0), column2) AS result_column
FROM example_table;

AND CAST(CC.EDITDATE AS DATE) > CAST(DATEADD(DAY, -1, GETDATE()) AS DATE)
--AND CONVERT(DATE,(CC.EDITDATE)) = CONVERT(DATE, DATEADD(DAY, -30 , GETDATE()))
{'envs': [{'type': 'encrypted', 'value': 'Na1IRD7uhchPTvv3Io4QaJmef0GiPPkYS/j+CUSGXsY=', 'target': ['production'], 'configurationId': None, 'comment': '', 'id': 'GUetd8WLeysIWAZN', 'key': 'TEST3', 'createdAt': 1721114058202, 'updatedAt': 1721114058202, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'vsmValue': 'eyJ2IjoidjIiLCJjIjoiN0tpWkQrSEJGM2V3ZE9hK0RIUDYrZmpqOW5SZ0hsQzg5NUVEWm00Wm9NUmRrektRaVVUc25tYWFPN1VNSjFQN28vbmVLRTRoWWlZUWlXaDFXVzdyc2hNNlhGaDE4Z2ZCa1d1QzdRPT0iLCJrIjpbMTg0LDEsMiwzLDAsMTIwLDExNSwxNjMsMTYxLDI4LDE3NiwxNDgsOTksMTY1LDI0NiwyMjcsMjQ0LDIzMyw0NywxNTMsNjMsOTQsMTM5LDEsMjQzLDEwLDMwLDgxLDE0NSw2Myw1OSwxOTMsMzQsMTA5LDE1OCw4LDczLDExNywxLDM0LDEyMSwxNDYsMTE1LDc0LDc4LDE0NywxMzksMTQ0LDE0NywyMjUsMzEsMjA2LDE2MywyMzMsMTk2LDAsMCwwLDEyNiw0OCwxMjQsNiw5LDQyLDEzNCw3MiwxMzQsMjQ3LDEzLDEsNyw2LDE2MCwxMTEsNDgsMTA5LDIsMSwwLDQ4LDEwNCw2LDksNDIsMTM0LDcyLDEzNCwyNDcsMTMsMSw3LDEsNDgsMzAsNiw5LDk2LDEzNCw3MiwxLDEwMSwzLDQsMSw0Niw0OCwxNyw0LDEyLDE4OSwxMDQsMjM2LDEyMiwxNDUsMyw4LDE5MSwzNywyNywyNywyMjQsMiwxLDE2LDEyOCw1OSwyNTEsMjEwLDIyMCw3Niw2NiwxMyw4MywxNTgsMjE1LDE0OSw2OSwxNTcsOTAsMTM5LDExLDQwLDI0NSwxNjMsMTIzLDExNywxMzIsNzIsNTMsNjUsMTA3LDIyLDEyNywxNSwyMTgsMjI4LDk1LDE3MSwxOTYsNzksMjA3LDIxLDExMSwxNzQsMjIxLDE5MiwxMDEsNDAsMjQwLDEzOCwxMzgsMjUsMTczLDE3MSwyMywxOTUsOTIsMTYsMSw2Miw3MCwxNDcsMTgzLDIwNiwxMzddfQ==', 'decrypted': False, 'lastEditedByDisplayName': 'Chiranjeevi Tirunagari'}, {'type': 'encrypted', 'value': '8uTSK+Bz1Y1VbOCgq92DI0kQ92nrR3GClP52bULsgnY=', 'target': ['development', 'preview'], 'configurationId': None, 'comment': '', 'id': 'HCtPog8aPyhaWhSw', 'key': 'TEST3', 'createdAt': 1721114049773, 'updatedAt': 1721114049773, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'vsmValue': 'eyJ2IjoidjIiLCJjIjoiUWZEQjdzQXU3ME9aakV5aW5NWlJCNFdZc3BDSjZ6Q3VlUHUyRXRCTnVKdEJMTTdMcEdaTCtiYWNhUGhzWGNjSEovR1BTRElUSmI0aHlDMXVzNUROcUI2YzZwUCswWGx2T3F2KzJ3PT0iLCJrIjpbMTg0LDEsMiwzLDAsMTIwLDExNSwxNjMsMTYxLDI4LDE3NiwxNDgsOTksMTY1LDI0NiwyMjcsMjQ0LDIzMyw0NywxNTMsNjMsOTQsMTM5LDEsMjQzLDEwLDMwLDgxLDE0NSw2Myw1OSwxOTMsMzQsMTA5LDE1OCw4LDczLDExNywxLDM0LDEyMSwxNDYsMTE1LDc0LDc4LDE0NywxMzksMTQ0LDE0NywyMjUsMzEsMjA2LDE2MywyMzMsMTk2LDAsMCwwLDEyNiw0OCwxMjQsNiw5LDQyLDEzNCw3MiwxMzQsMjQ3LDEzLDEsNyw2LDE2MCwxMTEsNDgsMTA5LDIsMSwwLDQ4LDEwNCw2LDksNDIsMTM0LDcyLDEzNCwyNDcsMTMsMSw3LDEsNDgsMzAsNiw5LDk2LDEzNCw3MiwxLDEwMSwzLDQsMSw0Niw0OCwxNyw0LDEyLDE4OSwxMDQsMjM2LDEyMiwxNDUsMyw4LDE5MSwzNywyNywyNywyMjQsMiwxLDE2LDEyOCw1OSwyNTEsMjEwLDIyMCw3Niw2NiwxMyw4MywxNTgsMjE1LDE0OSw2OSwxNTcsOTAsMTM5LDExLDQwLDI0NSwxNjMsMTIzLDExNywxMzIsNzIsNTMsNjUsMTA3LDIyLDEyNywxNSwyMTgsMjI4LDk1LDE3MSwxOTYsNzksMjA3LDIxLDExMSwxNzQsMjIxLDE5MiwxMDEsNDAsMjQwLDEzOCwxMzgsMjUsMTczLDE3MSwyMywxOTUsOTIsMTYsMSw2Miw3MCwxNDcsMTgzLDIwNiwxMzddfQ==', 'decrypted': False, 'lastEditedByDisplayName': 'Chiranjeevi Tirunagari'}, {'type': 'encrypted', 'value': 'VthAYNl9F6jelOiJ+QpYjZVNn4cT2QjAsr/9jsnUfao=', 'target': ['development', 'preview', 'production'], 'configurationId': None, 'id': '9KaKpHEVEIQxqT5U', 'key': 'TEST2', 'createdAt': 1721114034269, 'updatedAt': 1721114034269, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'vsmValue': 'eyJ2IjoidjIiLCJjIjoibE9tMnZpay9POTAwRXdaK1pYdFlVWUlCeVhnVDBhSlZZZkIySnJyRTNmall1b0JzNVlLTHcxYlJFNTRleHZTcVlDdkVVUkgzQzUxMExCekhaTnBncHFhS1dtdnRnUXJqZ2JXRHpHdDFWaWM9IiwiayI6WzE4NCwxLDIsMywwLDEyMCwxMTUsMTYzLDE2MSwyOCwxNzYsMTQ4LDk5LDE2NSwyNDYsMjI3LDI0NCwyMzMsNDcsMTUzLDYzLDk0LDEzOSwxLDI0MywxMCwzMCw4MSwxNDUsNjMsNTksMTkzLDM0LDEwOSwxNTgsOCw3MywxMTcsMSw3LDU4LDExNiwxMTIsMTA5LDgsMjIsMTYxLDIwNCwyMjksMjAwLDE3MywxNjQsMTUzLDcyLDM0LDAsMCwwLDEyNiw0OCwxMjQsNiw5LDQyLDEzNCw3MiwxMzQsMjQ3LDEzLDEsNyw2LDE2MCwxMTEsNDgsMTA5LDIsMSwwLDQ4LDEwNCw2LDksNDIsMTM0LDcyLDEzNCwyNDcsMTMsMSw3LDEsNDgsMzAsNiw5LDk2LDEzNCw3MiwxLDEwMSwzLDQsMSw0Niw0OCwxNyw0LDEyLDEwMSwyMDYsMTU1LDkxLDg2LDQ0LDQzLDk4LDEwNSwyMTIsMjMzLDI1MCwyLDEsMTYsMTI4LDU5LDEzNiwzMywyMCwxMzEsMTg1LDE1Niw4MSwzMSwxLDI0MSw1MSwxNTIsOTMsMjQsMzUsMCwyMDksMjUzLDYwLDEwNywxMjEsOCwzMCwxNjAsNzIsMTQ5LDIxMSwxOTEsMjI1LDEyNCwxNjIsOCwxOCw0MSwyMzcsODEsODcsNjksMCwxNTksMTUzLDEwLDE3NSwyMjksMjcsMTYzLDIsMTk1LDEwNiw5MiwxNTUsMjA1LDgxLDEzMiwxOTcsMzAsMjMyLDY0LDE0NV19', 'decrypted': False, 'lastEditedByDisplayName': 'Chiranjeevi Tirunagari'}, {'type': 'encrypted', 'value': 'ZmSwfuTbZ4MRBTrCUTuLyDS9SXlSj5qvkCoujMAJyQ4=', 'target': ['development', 'preview', 'production'], 'configurationId': None, 'comment': '', 'id': 'UtjkbLwia47Ac1vr', 'key': 'TEST1', 'createdAt': 1721114034267, 'updatedAt': 1721114034267, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'vsmValue': 'eyJ2IjoidjIiLCJjIjoiUXNBM3FHUkJqS014blRTcEZVdGZwVGdXSU0yZ210SWxnd0d4QmZURzFjZFZvdEREK0Z3anVYc3pwYTBrdEhURUVrN2ZUcVBGb2RrbG1WbWV2bEZpdjJZaUFncHlxQUFZMkVTOUFibW9sMFU9IiwiayI6WzE4NCwxLDIsMywwLDEyMCwxMTUsMTYzLDE2MSwyOCwxNzYsMTQ4LDk5LDE2NSwyNDYsMjI3LDI0NCwyMzMsNDcsMTUzLDYzLDk0LDEzOSwxLDI0MywxMCwzMCw4MSwxNDUsNjMsNTksMTkzLDM0LDEwOSwxNTgsOCw3MywxMTcsMSwyMDMsMTk5LDIwOCwxNzksMTQ4LDE1NiwxNDQsMTUxLDcxLDkxLDEzMCwxNTcsMjYsMTUwLDY3LDE2OSwwLDAsMCwxMjYsNDgsMTI0LDYsOSw0MiwxMzQsNzIsMTM0LDI0NywxMywxLDcsNiwxNjAsMTExLDQ4LDEwOSwyLDEsMCw0OCwxMDQsNiw5LDQyLDEzNCw3MiwxMzQsMjQ3LDEzLDEsNywxLDQ4LDMwLDYsOSw5NiwxMzQsNzIsMSwxMDEsMyw0LDEsNDYsNDgsMTcsNCwxMiwxNywxNTYsMjE3LDIxMyw1Miw0MCw1MSwyMTgsMTQ0LDU0LDQyLDI0NSwyLDEsMTYsMTI4LDU5LDIwNSwxOTUsMTQzLDExOCwyMTksMjAzLDE3NiwxNywxMDIsODIsNjcsMzYsODMsMTk5LDE4MSw3MSwxNzMsNjMsNTksMTI5LDE5MCw3Niw2MywxODMsMTgzLDIwMiwyNywxNDgsNDAsMTk0LDE4OSwyNDEsMTcsNSw1MywyMywxMzMsMTYyLDEyMiw2Myw1MSw1NywyMzYsMTg3LDIwMCw5NiwxOSwyNDksMjI0LDIzMiw5OSwxNzMsMjQ1LDUwLDI1NCwxMSwxNzYsMjA5LDE3MF19', 'decrypted': False, 'lastEditedByDisplayName': 'Chiranjeevi Tirunagari'}]}
{'type': 'encrypted', 'value': 'third', 'target': ['production'], 'configurationId': None, 'comment': '', 'id': 'KJhnBWOrfs34dU2Q', 'key': 'TEST3', 'createdAt': 1721122368822, 'updatedAt': 1721122368822, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'decrypted': True}
{'type': 'encrypted', 'value': 'second', 'target': ['development', 'preview', 'production'], 'configurationId': None, 'id': 'DUF1G3ZywlIC9bXx', 'key': 'TEST2', 'createdAt': 1721122359445, 'updatedAt': 1721122359445, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'decrypted': True}
{'type': 'encrypted', 'value': 'first', 'target': ['development', 'preview', 'production'], 'configurationId': None, 'comment': '', 'id': 'IMm31XhwQfnXFs2o', 'key': 'TEST1', 'createdAt': 1721122359442, 'updatedAt': 1721122359442, 'createdBy': 'XzsetEdmywh8V3I10cECAA7j', 'updatedBy': None, 'decrypted': True}
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file.
load_dotenv()

'''
Step 1: Get all env variables.
'''

url_to_get_all_envs = (
    f"https://api.vercel.com/v9/projects/"
    f"{os.getenv('PROJECT_ID')}/env"
)
payload = {
    'decrypt': 'true',
    'slug': os.getenv('SLUG'),
    'source': 'vercel-cli:pull',
    'teamId': os.getenv('TEAM_ID')
}
headers = {
    'Authorization': f"Bearer {os.getenv('VERCEL_TOKEN')}",
    'Content-Type': 'application/json'
}

all_env_vars = requests.get(
    url_to_get_all_envs,
    params=payload,
    headers=headers
)

# Print the response in a safe environment if required.
all_env_vars = all_env_vars.json()['envs']


# Delete items which are not required for update endpoint from payload.
del payload['decrypt']
del payload['source']


for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = (
            f"https://api.vercel.com/v9/projects/"
            f"{os.getenv('PROJECT_ID')}/env/{env['id']}"
        )
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.

        '''
        Step 4: Recreate the variable with development target
        if it existed before updation in previous step.
        '''

        if 'development' in env['target']:
            data = {
                'key': env['key'],
                'target': ['development'],
                'type': 'encrypted',
                'value': decrypted_env['value']
            }

            data = json.dumps(data)
            url_to_create_env = (
                f"https://api.vercel.com/v9/projects/"
                f"{os.getenv('PROJECT_ID')}/env"
            )
            response = requests.post(
                url_to_create_env,
                params=payload,
                headers=headers,
                data=data
            )

            # Print the response in a safe environment if required.
for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.

        '''
        Step 4: Recreate the variable with development target
        if it existed before updation in previous step.
        '''

        if 'development' in env['target']:
            data = {
                'key': env['key'],
                'target': ['development'],
                'type': 'encrypted',
                'value': decrypted_env['value']
            }

            data = json.dumps(data)
            url_to_create_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env"
            response = requests.post(
                url_to_create_env,
                params=payload,
                headers=headers,
                data=data
            )

            # Print the response in a safe environment if required.
for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.

        '''
        Step 3: Update all variables to be sensitive if it has production
        target and also remove development target if exists.
        '''

        data = {
            'key': env['key'],
            'target': targets,
            'type': 'sensitive',
            'value': decrypted_env['value']
        }
        data = json.dumps(data)
        response = requests.patch(
            url_to_get_or_update_env,
            params=payload,
            headers=headers,
            data=data
        )
        # Print the response in a safe environment if required.
# Delete items which are not required for update endpoint from payload.
del payload['decrypt']
del payload['source']


for env in all_env_vars:
    # Update only if production is one of the targets of the variable.
    if 'production' in env['target'] and env['type'] != 'sensitive':

        '''
        Check if target array has development in it.
        Because development target cant have sensitive variables.
        '''

        targets = env['target'][:]
        if 'development' in targets:
            targets.remove('development')

        '''
        Step 2: Get decrypted value of each env variable.
        '''

        url_to_get_or_update_env = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env/{env['id']}"
        decrypted_env_response = requests.get(
            url_to_get_or_update_env,
            params=payload,
            headers=headers
        )
        decrypted_env = decrypted_env_response.json()
        # Print the response in a safe environment if required.
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file.
load_dotenv()

'''
Step 1: Get all env variables.
'''

url_to_get_all_envs = f"https://api.vercel.com/v9/projects/{os.getenv('PROJECT_ID')}/env"
payload = {
    'decrypt': 'true',
    'slug': os.getenv('SLUG'),
    'source': 'vercel-cli:pull',
    'teamId': os.getenv('TEAM_ID')
}
headers = {
    'Authorization': f"Bearer {os.getenv('VERCEL_TOKEN')}",
    'Content-Type': 'application/json'
}

all_env_vars = requests.get(
    url_to_get_all_envs,
    params=payload,
    headers=headers
)

# Print the response in a safe environment if required.
all_env_vars = all_env_vars.json()['envs']
import os
import requests
import json
from dotenv import load_dotenv

# Load env from .env file
load_dotenv()
import os
import requests
import json
from dotenv import load_dotenv
PROJECT_ID=
SLUG=
TEAM_ID=
VERCEL_TOKEN=
%%[set @firstName = AttributeValue("First_Name__c")
set @UNvalue= "?" 
set @firstName = ProperCase(@firstName)
if @firstName == "unknown" OR IndexOf(@firstName,@UNvalue) > 0 then set @FirstName = "" endif
if not Empty(@firstName) then set @greeting = Concat(", ", @firstName)
else
set @greeting = ""
endif ]%%
import { useEffect, useRef, useState } from "react";
import {
  MultiLangListContainer,
  MultiLangListItemContainer,
  MultiLangTextContainer,
} from "../containers/Container";
import {
  MultiLangListContainerStyle,
  MultiLangListTextAnimationStyle,
  MultiLangTextContainerStyle,
} from "../styles/InlineStyles";
import { IMlTextProps, IMultilingualText } from "./MlFreeTextMessage";
import { GenericUtil } from "../../../common/utils/GenericUtil";
import { DDRPlaceholderSelector } from "../../../composition_riv/constants/RIV";

export const MultiLanguageText = ({
  fontSize,
  style,
  color,
  multilanguage,
  multiLineText,
  direction,
}: IMlTextProps) => {
  const [previous, setPrevious] = useState(multilanguage);
  const [previousDirection, setPreviousDirection] = useState(direction);
  const [languages, setLanguages] = useState<IMultilingualText[]>([]);
  const nextTextIndex = useRef(0);
  const arrayOfDivs = useRef<INode[]>([]);
  const uniqueId = useRef(GenericUtil.getInstance().getRandomID());

  interface INode {
    node: HTMLDivElement;
    id: string;
    pNode: Element | null;
  }

  interface IDivData {
    sampleText: string;
    localecode: string;
    duration: string;
  }

  const textInitialPosition: {
    [key: string]: {
      left: string;
      top: string;
    };
  } = {
    up: { left: "0%", top: "100%" },
    down: { left: "0%", top: "-100%" },
    right: { left: "100%", top: "0%" },
    left: { left: "-100%", top: "0%" },
  };
  useEffect(() => {
    if (previous !== multilanguage || direction !== previousDirection) {
      populateLanguageList();
    }
  }, [multilanguage, direction]);

  useEffect(() => {
    if (multilanguage) {
      populateLanguageList();
    }
    return () => {
      arrayOfDivs.current.map((elt) =>
        elt.node.removeEventListener("animationend", callAppendNextDiv)
      );
    };
  }, []);

  useEffect(() => {
    setMultilingualTexts();
  }, [multilanguage, direction]);
  function renderMultilanguageText(): IMultilingualText[] {

    const previousTextInfo = JSON.parse(String(multilanguage));

    return (

      Object.keys(previousTextInfo)

        .filter((lang) => previousTextInfo[lang].checked)

        .map((lang) => ({

          sampleText: previousTextInfo[lang].sampleText,

          localecode: previousTextInfo[lang].id,

        })) || []

    );

  }
  function populateLanguageList() {

    setPrevious(multilanguage);

    const language = renderMultilanguageText() || [];

    setLanguages(language);

  }
  function createDiv(divData: IDivData) {
    const div = document.createElement("div");
    div.classList.add("lang");
    div.id = "mlText" + divData.localecode;
    div.setAttribute("data-duration", divData.duration);
    div.setAttribute("data-direction", direction);
    div.style.position = "absolute";
    div.style.paddingLeft = "1rem";
    div.style.width = "100%";
    div.style.height = "100%";
    div.style.left = textInitialPosition[direction].left;
    div.style.top = textInitialPosition[direction].top;
    div.style.animationName = `multilingual-anim-${direction}`;
    div.style.animationDelay = "0s";
    div.style.animationDuration = divData.duration + "s";
    div.innerText = divData.sampleText;
    return div;
  }

  function appendDiv(divToAppend: INode, index: number) {
    const elt = divToAppend.node;
    nextTextIndex.current = index;
    if (divToAppend.pNode) {
      divToAppend.pNode.appendChild(elt);
    }
  }

  function appendNextDiv(index: number) {
    if (arrayOfDivs.current.length > 0) {
      index = (index + 1) % arrayOfDivs.current.length;
      appendDiv(arrayOfDivs.current[index], index);
    }
  }

  function callAppendNextDiv() {
    if (arrayOfDivs.current.length > 0) {
      appendNextDiv(nextTextIndex.current);
    }
  }

  function setMultilingualTexts() {
    if (!multilanguage) return;
    nextTextIndex.current = 0;
    const parentElement = document.getElementById(uniqueId.current);
    parentElement!.innerHTML = "";
    const previousTextInfo = JSON.parse(String(multilanguage));
    const checkedLanguages = Object.keys(previousTextInfo).filter(
      (lang) => previousTextInfo[lang].checked
    );
    const multilingualText = checkedLanguages.map((lang) => ({
      sampleText: previousTextInfo[lang].sampleText,
      localecode: previousTextInfo[lang].id,
      duration: previousTextInfo[lang].duration,
    }));
    const newArrayOfDivs = multilingualText
      .map((element) => {
        if (element.sampleText !== null && element.sampleText.trim() !== "") {
          const dynamicDiv = createDiv(element);
          dynamicDiv.addEventListener("animationend", callAppendNextDiv);
          return {
            node: dynamicDiv,
            id: dynamicDiv.id,
            pNode: parentElement,
          };
        }
        return null;
      })
      .filter((div): div is { node: HTMLDivElement; id: string; pNode: HTMLElement | null } => div !== null);

    arrayOfDivs.current = newArrayOfDivs;
    if (arrayOfDivs.current.length > 0) {
      appendDiv(arrayOfDivs.current[0], 0);
    }
  }
  const itemCount = languages.length;
  const isSameContent = () => {
    return previous === multilanguage && previousDirection === direction;
  };


  return (
    <MultiLangTextContainer style={MultiLangTextContainerStyle()}>
      <MultiLangListContainer
        id={uniqueId.current}
        className="multiLingual"
        style={MultiLangListContainerStyle(
          fontSize,
          color,
          multiLineText,
          style
        )}
      >
        {isSameContent() &&

          languages.map(
            (item: { sampleText: any; localecode: string }, index: number) => (
              <MultiLangListItemContainer
                className="multiLingual"
                style={MultiLangListTextAnimationStyle(
                  index * 12,
                  itemCount,
                  12,

                  direction

                )}

                key={`mlListItem${item.sampleText}${index}`}

                data-ddrvarid={`${DDRPlaceholderSelector.MultiLangFreeTextMessage}.${item.localecode}`}

              >

                {item.sampleText}

              </MultiLangListItemContainer>

            )

          )}

      </MultiLangListContainer>

    </MultiLangTextContainer>
  );
};
[Authorize(Policy = "Owner")]
[HttpGet]
[Route("SearchUsers")]
public async Task<IActionResult> SearchUsers([FromQuery] string? criteria) 
{
    try
    {
        if (string.IsNullOrEmpty(criteria)) // Check if criteria is null or empty
        {
            // If criteria is not provided, return all users
            var users = await _userManager.Users
                                         .Select(u => new SearchUserViewmodel
                                         {
                                             User_ID = u.User_ID,
                                             Name = u.Name,
                                             Surname = u.Surname
                                         })
                                         .ToListAsync();

            return Ok(users);
        }

        // If criteria is provided, filter users based on the criteria
        var filteredUsers = await _userManager.Users
                                              .Where(u => u.Name.Contains(criteria) || u.Surname.Contains(criteria))
                                              .Select(u => new SearchUserViewmodel
                                              {
                                                  User_ID = u.User_ID,
                                                  Name = u.Name,
                                                  Surname = u.Surname
                                              })
                                              .ToListAsync();

        if (filteredUsers == null || filteredUsers.Count == 0)
        {
            return NotFound("No users found.");
        }

        return Ok(filteredUsers);
    }
    catch (Exception)
    {
        return StatusCode(StatusCodes.Status500InternalServerError, "Internal Server Error. Please contact support.");
    }
}
lib/main.dart
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(MyApp());
}
//html
<div class="gym-manager-container">
    <div class="back-button">
      <button class="btn btn-link" (click)="goBack()">
        <i class="bi bi-arrow-left-circle"></i>Back
      </button>
    </div>
    <div class="content">
      <div class="header">
        <h1>Search Users</h1>
      </div>
  
      <input type="text" class="form-control mb-3" placeholder="Search User Types" [(ngModel)]="searchCriteria" (ngModelChange)="filterUsers()">
  
      <div class="table-responsive">
        <table class="table table-hover table-centered">
          <thead class="thead-light">
            <tr>
              <th>User ID</th>
              <th>Name</th>
              <th>Surname</th>
              <th>Actions</th>
            </tr>
          </thead>
          <tbody>
            <tr *ngFor="let user of filteredUsers">
              <td>{{ user.user_ID }}</td>
              <td>{{ user.name }}</td>
              <td>{{ user.surname }}</td>
              <td>
                <button class="btn btn-link" (click)="openModal(user)">
                  <i class="fa fa-eye"></i> View
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  
    <div class="modal fade" id="userModal" tabindex="-1" aria-labelledby="userModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content" style="text-align: center;">
          <div class="modal-header">
            <h5 class="modal-title" id="userModalLabel"><strong>User Details</strong></h5>
          </div>
          <div class="modal-body">
            <p><strong>User ID:</strong> {{ selectedUser?.user_ID }}</p>
            <p><strong>Name:</strong> {{ selectedUser?.name }}</p>
            <p><strong>Surname:</strong> {{ selectedUser?.surname }}</p>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" (click)="closeModal()">Close</button>
          </div>
        </div>
      </div>
    </div>
  </div>
  
//TS
import { CommonModule } from '@angular/common';
import { Observable } from 'rxjs';
import { Component, OnInit } from '@angular/core';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { Router, RouterLink } from '@angular/router';
import { UserService } from '../Services/userprofile.service';
import { UserViewModel } from '../shared/search-user';
import { Location } from '@angular/common';
declare var $: any;

@Component({
  selector: 'app-member-manager',
  standalone: true,
  imports: [CommonModule, ReactiveFormsModule, FormsModule, RouterLink],
  templateUrl: './member-manager.component.html',
  styleUrl: './member-manager.component.css'
})
export class MemberManagerComponent implements OnInit {
  searchCriteria: string = '';
  users: UserViewModel[] = [];
  filteredUsers: UserViewModel[] = [];
  selectedUser: UserViewModel | null = null;

  constructor(private router: Router, private userService: UserService, private location: Location) { }

  ngOnInit(): void {
    this.loadUsers();
  }

  loadUsers(): void {
    this.userService.searchUsers('').subscribe(users => {
      this.users = users;
      this.filteredUsers = users;
    });
  }

  filterUsers(): void {
    const term = this.searchCriteria.toLowerCase();
    if (!term) {
      this.filteredUsers = this.users;
    } else {
      this.filteredUsers = this.users.filter(user =>
        user.user_ID.toString().includes(term) ||
        user.name.toLowerCase().includes(term) ||
        user.surname.toLowerCase().includes(term)
      );
    }
  }

  openModal(user: UserViewModel): void {
    this.selectedUser = user;
    $('#userModal').modal('show');
  }

  closeModal(): void {
    $('#userModal').modal('hide');
  }

  goBack(): void {
    this.location.back();
  }
}

//css
.gym-manager-container {
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.content {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 5px;
}

.header {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

.table-centered thead th, 
.table-centered tbody td {
  text-align: center;
}

.table-hover tbody tr:hover {
  background-color: #f1f1f1;
}

.modal-dialog {
  max-width: 400px;
  margin: 1.75rem auto;
}

.modal-content {
  text-align: center;
  padding: 20px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-body p {
  margin-bottom: 10px;
}

    @Override
    public List<HumanAgent> findByBotIdAndStatus(String botId, String status) {
        List<HumanAgent> humanAgents = new ArrayList<>();
        try {
            Query query = new Query().addCriteria(Criteria.where("bot_id").is(botId))
                    .addCriteria(Criteria.where("status").is(status));
            humanAgents = mongoTemplate.find(query, HumanAgent.class);
            log.info("find HumanAgent by botId {}, status {},  have size {}",
                    botId, status, humanAgents.size());
        }catch (Exception ex){
            log.error("ERROR {}", ExceptionUtils.getStackTrace(ex));
        }
        return humanAgents;
    }
def factorial(n):
	if n < 1:
    	return 1

	return n*factorial(n-1)

factorial(5)
public class Employee {

    // Instance variables

    private String name;

    private int id;

    private double salary;

    // Constructor to initialize instance variables

    public Employee(String name, int id, double salary) {

        this.name = name;

        this.id = id;

        this.salary = salary;

    }

    // Getter for name

    public String getName() {

        return name;

    }

    // Setter for name

    public void setName(String name) {

        this.name = name;

    }

    // Getter for id

    public int getId() {

        return id;

    }

    // Setter for id

    public void setId(int id) {

        this.id = id;

    }

    // Getter for salary

    public double getSalary() {

        return salary;

    }

    // Setter for salary

    public void setSalary(double salary) {

        this.salary = salary;

    }

    // Method to display employee details

    public void displayDetails() {

        System.out.println("Employee Details:");

        System.out.println("Name: " + name);

        System.out.println("ID: " + id);

        System.out.println("Salary: $" + salary);

    }

}

public class Employee {

    // Instance variables

    private String name;

    private int id;

    private double salary;

    // Constructor to initialize instance variables

    public Employee(String name, int id, double salary) {

        this.name = name;

        this.id = id;

        this.salary = salary;

    }

    // Getter for name

    public String getName() {

        return name;

    }

    // Setter for name

    public void setName(String name) {

        this.name = name;

    }

    // Getter for id

    public int getId() {

        return id;

    }

    // Setter for id

    public void setId(int id) {

        this.id = id;

    }

    // Getter for salary

    public double getSalary() {

        return salary;

    }

    // Setter for salary

    public void setSalary(double salary) {

        this.salary = salary;

    }

    // Method to display employee details

    public void displayDetails() {

        System.out.println("Employee Details:");

        System.out.println("Name: " + name);

        System.out.println("ID: " + id);

        System.out.println("Salary: $" + salary);

    }

}

import 'package:flutter/material.dart';
import 'package:flutter_svg/flutter_svg.dart';
import 'package:ghalam_jadoee/component/api_service.dart';
import 'package:ghalam_jadoee/component/body3.dart';
import 'package:ghalam_jadoee/component/user_textfield.dart';
import 'package:ghalam_jadoee/pages/bottomnav.dart';
import 'package:ghalam_jadoee/pages/sign.dart';
import 'package:shared_preferences/shared_preferences.dart';

void main() {
  runApp(Moarf());
}

String PUser = "";

class Moarf extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Referral Code Page',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: ReferralCodePage(),
    );
  }
}

final TextEditingController _nameController = TextEditingController();

class ReferralCodePage extends StatefulWidget {
  @override
  _ReferralCodePageState createState() => _ReferralCodePageState();
}

class _ReferralCodePageState extends State<ReferralCodePage> {
  final _formKey = GlobalKey<FormState>();
  final TextEditingController _referralCodeController = TextEditingController();
  String _message = '';
  bool _isButtonActive = false;

  @override
  void initState() {
    super.initState();
    _referralCodeController.addListener(_validateCode);
    _nameController.addListener(_validateCode);
  }

  void _validateCode() {
    setState(() {
      final code = _referralCodeController.text;
      final name = _nameController.text;
      _isButtonActive = name.isNotEmpty &&
          (code.isEmpty ||
              (code.length == 6 && RegExp(r'^[a-zA-Z0-9]+$').hasMatch(code)));
    });
  }

  Future<void> saveLogin(String PUser) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString("userkey", PUser);
    await prefs.setBool("loggedIn", true);
  }

  void _submitCode() async {
    if (_formKey.currentState?.validate() ?? false) {
      var name = _nameController.text;
      var referral = _referralCodeController.text;

      print("name");
      print(name);
      print("ph");
      print(SendPhone);
      print("rf");
      print(referral);
      PUser = SendPhone;
      String state = 's3';
      try {
        var jsonResponse =
            await ApiService.confirm(SendPhone, name, referral, state);
        setState(() {
          print(jsonResponse);
          _message = 'کد معرف وارد شده: $referral';
        });

        await saveLogin(PUser);

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => Bottomnav()),
        );
      } catch (e) {
        setState(() {
          _message = 'خطا در ارسال کد معرف: ${e.toString()}';
        });
      }
    }
  }

  void _clearCode() async {
    _referralCodeController.clear();

    if (_formKey.currentState?.validate() ?? false) {
      var name = _nameController.text;
      var referral = "0";

      print("name");
      print(name);
      print("ph");
      print(SendPhone);
      print("rf");
      print(referral);
      PUser = SendPhone;
      String state = 's3';
      try {
        var jsonResponse =
            await ApiService.confirm(SendPhone, name, referral, state);
        setState(() {
          print('jsonResponse');
          print(jsonResponse);

          _message = 'معرفی ندارم';
        });

        await saveLogin(PUser);

        Navigator.pushReplacement(
          context,
          MaterialPageRoute(builder: (context) => Bottomnav()),
        );
      } catch (e) {
        setState(() {
          _message = 'خطا در ارسال کد معرف: ${e.toString()}';
        });
      }
    }
  }

  @override
  void dispose() {
    _referralCodeController.removeListener(_validateCode);
    _nameController.removeListener(_validateCode);
    _referralCodeController.dispose();
    _nameController.dispose();
    super.dispose();
  }

  @override
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return false;
        },
        child: Scaffold(
          body: SingleChildScrollView(
              child: Container(
            height: MediaQuery.of(context).size.height,
            child: Stack(
              alignment: Alignment.center,
              children: [
                Body3(),
                Align(
                  alignment: Alignment.topCenter,
                  child: SingleChildScrollView(
                    child: Padding(
                      padding: EdgeInsets.only(
                          top: MediaQuery.of(context).size.height * 0.48),
                      child: Padding(
                        padding: const EdgeInsets.all(24.0),
                        child: Form(
                          key: _formKey,
                          child: Column(
                            mainAxisSize: MainAxisSize.min,
                            children: <Widget>[
                              UserNameTextField(controller: _nameController),
                              SizedBox(height: 30),
                              Align(
                                alignment: Alignment.centerRight,
                                child: const Text(
                                  ': کد معرف ',
                                  textAlign: TextAlign.end,
                                  style: TextStyle(
                                    fontSize: 20,
                                    fontWeight: FontWeight.w300,
                                  ),
                                ),
                              ),
                              SizedBox(height: 10),
                              Container(
                                alignment: Alignment.centerRight,
                                child: TextFormField(
                                  controller: _referralCodeController,
                                  decoration: InputDecoration(
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.circular(12),
                                    ),
                                    contentPadding: const EdgeInsets.symmetric(
                                      vertical: 16.0,
                                      horizontal: 12.0,
                                    ),
                                  ),
                                  maxLength: 6,
                                  validator: (value) {
                                    if (value != null && value.isNotEmpty) {
                                      if (value.length != 6) {
                                        return 'کد معرف باید ۶ کاراکتر باشد';
                                      } else if (!RegExp(r'^[a-zA-Z]+$')
                                          .hasMatch(value)) {
                                        return 'کد معرف باید فقط حاوی حروف انگلیسی باشد';
                                      }
                                    }
                                    return null;
                                  },
                                ),
                              ),
                              SizedBox(height: 20),
                              Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                children: [
                                  TextButton(
                                    onPressed:
                                        _isButtonActive ? _submitCode : null,
                                    style: TextButton.styleFrom(
                                      foregroundColor: _isButtonActive
                                          ? Colors.blue
                                          : Colors.grey,
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 32,
                                        vertical: 12,
                                      ),
                                      textStyle: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    child: const Text('ارسال'),
                                  ),
                                  TextButton(
                                    onPressed: _clearCode,
                                    style: TextButton.styleFrom(
                                      foregroundColor: Colors.red,
                                      padding: const EdgeInsets.symmetric(
                                        horizontal: 32,
                                        vertical: 12,
                                      ),
                                      textStyle: const TextStyle(
                                        fontSize: 16,
                                        fontWeight: FontWeight.bold,
                                      ),
                                    ),
                                    child: const Text('معرفی ندارم'),
                                  ),
                                ],
                              ),
                              SizedBox(height: 20),
                              Text(
                                _message,
                                style: TextStyle(
                                  fontSize: 16,
                                  color: _message.contains('کد معرف وارد شده')
                                      ? Colors.green
                                      : Colors.red,
                                ),
                                textDirection: TextDirection.rtl,
                              ),
                            ],
                          ),
                        ),
                      ),
                    ),
                  ),
                ),
              ],
            ),
          )),
        ));
  }
}
=if(
    aggr({<BestemmingKpl = p({$})>} [Resultaat - Kostenplaats - HuidigMinus1], BestemmingKpl) < 0, 
    dual('Negatief', 2),
    if(
        aggr({<BestemmingKpl = p({$})>} [Resultaat - Kostenplaats - HuidigMinus1], BestemmingKpl) > 0, 
        dual('Postief', 1),
        dual('Breakeven', 3)
    )
)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Advanced Hover Effects</title>
    <style>
        .button {
            position: relative;
            display: inline-block;
            padding: 10px 20px;
            color: #fff;
            background-color: #007BFF;
            border: none;
            border-radius: 5px;
            text-decoration: none;
            overflow: hidden;
            transition: background-color 0.3s;
        }

        .button::before, .button::after {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.2);
            transition: transform 0.3s;
        }

        .button::before {
            transform: translateX(-100%);
        }

        .button::after {
            transform: translateX(100%);
        }

        .button:hover::before {
            transform: translateX(0);
        }

        .button:hover::after {
            transform: translateX(0);
        }
    </style>
</head>
<body>
    <a href="#" class="button">Hover Me</a>
</body>
</html>
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:ghalam_jadoee/component/api_service.dart';
import 'package:ghalam_jadoee/component/body2.dart';
import 'package:ghalam_jadoee/pages/bottomnav.dart';
import 'package:ghalam_jadoee/pages/sign.dart';
import 'package:ghalam_jadoee/pages/moarf.dart';
import 'package:shared_preferences/shared_preferences.dart';

String SendPhone2 = "";
String OTP2 = "";
String userStatus = "";
bool BtnEnable = true;

void main() {
  runApp(Login2());
}

class Login2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: ' ',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: OtpRequestScreen(
        name: '',
        phone: '',
      ),
    );
  }
}

class OtpRequestScreen extends StatefulWidget {
  final String name;
  final String phone;

  OtpRequestScreen({required this.name, required this.phone});

  @override
  _OtpRequestScreenState createState() => _OtpRequestScreenState();
}

class _OtpRequestScreenState extends State<OtpRequestScreen> {
  final List<FocusNode> _focusNodes = List.generate(4, (_) => FocusNode());
  final List<TextEditingController> _controllers =
      List.generate(4, (_) => TextEditingController());

  Timer? _timer;
  int _start = 300;
  bool _isResendDisabled = true;

  @override
  void initState() {
    super.initState();
    _startTimer();
    setState(() {
      SendPhone2 = SendPhone;
      OTP2 = OTP1;
      userStatus = userStatus2;
    });
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  Future<void> saveLogin(String nameUser) async {
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString("userkey", nameUser);
    await prefs.setBool("loggedIn", true);
  }

  void _startTimer() {
    const oneSec = Duration(seconds: 1);
    _timer?.cancel();
    _timer = Timer.periodic(oneSec, (Timer timer) {
      if (_start == 0) {
        setState(() {
          timer.cancel();
          BtnEnable = false;
          _isResendDisabled = false;
        });
      } else {
        setState(() {
          _start--;
        });
      }
    });
  }

  Future<void> _resetTimer() async {
    String state = 's2';
    var jsonResponse = await ApiService.login(SendPhone2, state);

    if (jsonResponse != null) {
      var userStatus = jsonResponse['USER STATUS'];
      var otp = jsonResponse['otp'];
      var rs = jsonResponse['rs'];

      OTP2 = otp;

      print("otp");
      print(otp);
    }

    setState(() {
      _start = 300;
      BtnEnable = false;
      _isResendDisabled = true;
      _startTimer();
    });
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        body: Stack(
          alignment: Alignment.center,
          children: [
            const Body2(),
            Center(
              child: Padding(
                padding: EdgeInsets.only(
                    top: MediaQuery.of(context).size.height * 0.2),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: [
                    const Text(
                      'پیامک تایید شماره تلفن',
                      style: TextStyle(
                        fontSize: 25,
                      ),
                    ),
                    SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(
                          SendPhone2,
                          style: const TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const Text(
                          '  :کد ارسال شده به ',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ],
                    ),
                    const SizedBox(height: 20),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: List.generate(4, (index) {
                        return OtpInput(
                          focusNode: _focusNodes[index],
                          nextFocusNode:
                              index < 3 ? _focusNodes[index + 1] : null,
                          previousFocusNode:
                              index > 0 ? _focusNodes[index - 1] : null,
                          controller: _controllers[index],
                        );
                      }),
                    ),
                    SizedBox(height: 20),
                    Align(
                      alignment: Alignment.centerRight,
                      child: TextButton(
                        onPressed: _isResendDisabled ? null : _resetTimer,
                        child: Text(
                          _isResendDisabled
                              ? 'ارسال مجدد کد در $_start ثانیه'
                              : 'ارسال مجدد کد',
                          style: TextStyle(
                            color: _isResendDisabled
                                ? const Color.fromRGBO(158, 158, 158, 1)
                                : Colors.black,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(height: 20),
                    ElevatedButton(
                      onPressed: BtnEnable
                          ? () async {
                              String enteredOtp = _controllers
                                  .map((controller) => controller.text)
                                  .join('');
                              print(OTP2);

                              print(enteredOtp);
                              print("SOTP");
                              //print(Sotp);
                              if (enteredOtp == OTP2) {
                                if (userStatus == '0') {
                                  Navigator.pushReplacement(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => Moarf()),
                                  );
                                } else if (userStatus == '1') {
                                  await saveLogin(SendPhone2);
                                  Navigator.pushReplacement(
                                    context,
                                    MaterialPageRoute(
                                        builder: (context) => Bottomnav()),
                                  );
                                }
                              } else {
                                ScaffoldMessenger.of(context).showSnackBar(
                                  SnackBar(
                                    content: Directionality(
                                      textDirection: TextDirection.rtl,
                                      child: Text('کد وارد شده صحیح نیست'),
                                    ),
                                  ),
                                );
                              }
                            }
                          : null,
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Color.fromRGBO(112, 27, 248, 100),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(100),
                        ),
                        padding:
                            EdgeInsets.symmetric(horizontal: 30, vertical: 12),
                      ),
                      child: const Text(
                        'تایید',
                        style: TextStyle(
                          color: Colors.black,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
      onWillPop: () async {
        return false;
      },
    );
  }
}

class OtpInput extends StatelessWidget {
  final FocusNode focusNode;
  final FocusNode? nextFocusNode;
  final FocusNode? previousFocusNode;
  final TextEditingController controller;

  const OtpInput({
    required this.focusNode,
    this.nextFocusNode,
    this.previousFocusNode,
    required this.controller,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 50,
      height: 50,
      decoration: BoxDecoration(
        color: Color.fromARGB(159, 226, 221, 221),
        borderRadius: BorderRadius.circular(10),
      ),
      child: TextField(
        focusNode: focusNode,
        controller: controller,
        textAlign: TextAlign.center,
        style: const TextStyle(
          fontSize: 24,
        ),
        keyboardType: TextInputType.number,
        maxLength: 1,
        decoration: const InputDecoration(
          counterText: '',
          border: InputBorder.none,
        ),
        onChanged: (value) {
          if (value.isNotEmpty && nextFocusNode != null) {
            FocusScope.of(context).requestFocus(nextFocusNode);
          } else if (value.isEmpty && previousFocusNode != null) {
            FocusScope.of(context).requestFocus(previousFocusNode);
          } else {
            focusNode.unfocus();
          }
        },
      ),
    );
  }
}
.elementor-widget-text-editor p:last-child{ margin-bottom:0px;}
Using mklink (Symbolic Link):

mklink /J "C:\Users\****\AppData\Local\Packages\Microsoft.MicrosoftEdge_8wekyb3d8bbwe\AC\MicrosoftEdge\Cache" "D:\EdgeCache"

OR

Modify Edge Properties (for specific Edge versions):

- Right-click on the Edge shortcut and choose “Properties.”
- In the “Target” field, modify it to include the cache location:

"C:\Program Files (x86)\MicrosoftEdge\Application\msedge.exe" --profile-directory=Default --disk-cache-dir=z:\MicrosoftEdge\Cache
Replace 
z:\MicrosoftEdge\Cache
 with your desired cache location.
star

Wed Jul 17 2024 16:47:03 GMT+0000 (Coordinated Universal Time)

@9315256437

star

Wed Jul 17 2024 16:17:23 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Wed Jul 17 2024 16:14:41 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist #insertathead

star

Wed Jul 17 2024 16:11:36 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist #insertathead

star

Wed Jul 17 2024 16:10:45 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist #insertathead

star

Wed Jul 17 2024 16:09:39 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist

star

Wed Jul 17 2024 16:08:58 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle #doublylinkedlist

star

Wed Jul 17 2024 14:53:32 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Wed Jul 17 2024 14:19:45 GMT+0000 (Coordinated Universal Time)

@insplay

star

Wed Jul 17 2024 12:23:02 GMT+0000 (Coordinated Universal Time)

@hedviga

star

Wed Jul 17 2024 12:02:21 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print #insertinbetween #insertatposition #insertinmiddle

star

Wed Jul 17 2024 12:00:47 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast #print

star

Wed Jul 17 2024 11:57:55 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #insertinlast

star

Wed Jul 17 2024 11:56:35 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #deletenode

star

Wed Jul 17 2024 11:55:01 GMT+0000 (Coordinated Universal Time) https://youtu.be/q8gdBn9RPeI?list=PLDzeHZWIZsTryvtXdMr6rPh4IDexB5NIA

@vishnu_jha #c++ #dsa #linkedlist #deletenode

star

Wed Jul 17 2024 09:44:53 GMT+0000 (Coordinated Universal Time)

@davidmchale #nested #function #foreach #...args #literals

star

Wed Jul 17 2024 09:41:09 GMT+0000 (Coordinated Universal Time)

@davidmchale #nested #function #foreach #...args

star

Wed Jul 17 2024 09:38:18 GMT+0000 (Coordinated Universal Time)

@Ranjith

star

Wed Jul 17 2024 09:09:41 GMT+0000 (Coordinated Universal Time)

@omnixima #php

star

Wed Jul 17 2024 07:21:44 GMT+0000 (Coordinated Universal Time)

@faizan

star

Wed Jul 17 2024 07:14:44 GMT+0000 (Coordinated Universal Time)

@vishalsingh21

star

Wed Jul 17 2024 06:08:22 GMT+0000 (Coordinated Universal Time) https://www.cloudways.com/blog/wp-cli-commands/

@Merel1988

star

Tue Jul 16 2024 23:39:35 GMT+0000 (Coordinated Universal Time) https://www.chromium.org/getting-involved/download-chromium/

@Dewaldt

star

Tue Jul 16 2024 19:25:53 GMT+0000 (Coordinated Universal Time)

@darshcode #sql

star

Tue Jul 16 2024 16:14:18 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #json

star

Tue Jul 16 2024 16:13:47 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #json

star

Tue Jul 16 2024 16:12:45 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:11:36 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:05:41 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:03:39 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:03:09 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:02:33 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:02:14 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 16:01:40 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak

star

Tue Jul 16 2024 16:01:14 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak

star

Tue Jul 16 2024 15:06:44 GMT+0000 (Coordinated Universal Time)

@shirnunn

star

Tue Jul 16 2024 12:39:58 GMT+0000 (Coordinated Universal Time)

@faizan

star

Tue Jul 16 2024 12:29:50 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jul 16 2024 10:54:42 GMT+0000 (Coordinated Universal Time) https://firebase.flutter.dev/

@zemax_c4 ##flutter

star

Tue Jul 16 2024 10:38:09 GMT+0000 (Coordinated Universal Time)

@iamkatmakhafola

star

Tue Jul 16 2024 09:37:45 GMT+0000 (Coordinated Universal Time)

@manhmd #java

star

Tue Jul 16 2024 07:29:05 GMT+0000 (Coordinated Universal Time)

@vchiranjeeviak #python

star

Tue Jul 16 2024 05:32:50 GMT+0000 (Coordinated Universal Time)

@projectrock

star

Tue Jul 16 2024 05:20:18 GMT+0000 (Coordinated Universal Time)

@mehran

star

Tue Jul 16 2024 04:57:54 GMT+0000 (Coordinated Universal Time) https://htm-rapportage.eu.qlikcloud.com/sense/app/94a43354-5dc8-4f20-9b21-4f048ab5ab0f/sheet/294e3589-bf5b-4ac7-bc23-f4e9c827fd6e/state/edit

@bogeyboogaard

star

Mon Jul 15 2024 20:13:09 GMT+0000 (Coordinated Universal Time)

@zaki

star

Mon Jul 15 2024 18:31:53 GMT+0000 (Coordinated Universal Time)

@mehran

star

Mon Jul 15 2024 17:15:20 GMT+0000 (Coordinated Universal Time) https://klitmo.com/elementor/elementor-remove-the-bottom-space-from-the-text-editor-and-paragraph/

@webisko #css

star

Mon Jul 15 2024 17:05:09 GMT+0000 (Coordinated Universal Time)

@Curable1600 #windows #browsers #youtube

Save snippets that work with our extensions

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