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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            await _appDbContext.SaveChangesAsync();

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

        return await Register(memberViewModel);
    }

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

        return await Register(employeeViewModel);
    }

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

        return await Register(ownerViewModel);
    }

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

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

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

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

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

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

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

                        IdentityResult result = await _userManager.CreateAsync(user);

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

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

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

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

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

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

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

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

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

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

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

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

  };
};

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

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

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

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

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

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

For example:

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

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

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

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

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

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

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

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

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

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

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

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

----------

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

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

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

Example Code
array.map(el => {

})

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

Example Code
array.filter(el => {

})

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

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

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

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

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

});

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Benefits of Developing Pancakeswap clone script?

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

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



# Extract email addresses using regexp
import re
email_log = """Email received June 2 from user1@email.com.
Email received June 2 from user2@email.com.
Email rejected June 2 from invalid_email@email.com."""

#\w means any alpha numeric characters 
print(re.findall("\w+@\w+\.\w+",email_log))
import java.util.Scanner;

public class GradeCalculator {

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

        // Prompt user to enter score until a valid score is entered
        int score;
        do {
            System.out.print("Enter the score (0-100): ");
            score = scanner.nextInt();

            if (score < 0 || score > 100) {
                System.out.println("Invalid score! Score must be between 0 and 100.");
            }
        } while (score < 0 || score > 100);

        // Calculate grade based on score using switch statement
        char grade;
        switch (score / 10) {
            case 10:
            case 9:
                grade = 'A';
                break;
            case 8:
                grade = 'B';
                break;
            case 7:
                grade = 'C';
                break;
            case 6:
                grade = 'D';
                break;
            default:
                grade = 'F';
                break;
        }

        // Display the grade
        System.out.println("Grade: " + grade);

        scanner.close();
    }
}
public class Person {
    private String name;
    private int age;

    // Default constructor
    public Person() {
        this.name = "Unknown";
        this.age = 0;
    }

    // Constructor with name parameter
    public Person(String name) {
        this.name = name;
        this.age = 0;
    }

    // Constructor with name and age parameters
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    // Method to display the details
    public void display() {
        System.out.println("Name: " + name + ", Age: " + age);
    }

    public static void main(String[] args) {
        // Using default constructor
        Person person1 = new Person();
        person1.display();

        // Using constructor with name parameter
        Person person2 = new Person("Alice");
        person2.display();

        // Using constructor with name and age parameters
        Person person3 = new Person("Bob", 25);
        person3.display();
    }
}
public class MathOperations {

    // Method to add two integers
    public int add(int a, int b) {
        return a + b;
    }

    // Method to add three integers
    public int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method to add two doubles
    public double add(double a, double b) {
        return a + b;
    }

    // Method to concatenate two strings
    public String add(String a, String b) {
        return a + b;
    }

    public static void main(String[] args) {
        MathOperations math = new MathOperations();

        // Test the overloaded methods
        System.out.println("Addition of two integers: " + math.add(10, 20));
        System.out.println("Addition of three integers: " + math.add(10, 20, 30));
        System.out.println("Addition of two doubles: " + math.add(10.5, 20.5));
        System.out.println("Concatenation of two strings: " + math.add("Hello", " World"));
    }
}
import java.util.Scanner;

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

        // Prompt the user to enter a score
        System.out.print("Enter the score: ");
        int score = scanner.nextInt();

        // Determine the grade based on the score
        String grade;
        if (score >= 90 && score <= 100) {
            grade = "A";
        } else if (score >= 80 && score < 90) {
            grade = "B";
        } else if (score >= 70 && score < 80) {
            grade = "C";
        } else if (score >= 60 && score < 70) {
            grade = "D";
        } else if (score >= 0 && score < 60) {
            grade = "F";
        } else {
            grade = "Invalid score";
        }

        // Print the grade
        System.out.println("The grade is: " + grade);

        scanner.close();
    }
}
public class CommandLineSum {
    public static void main(String[] args) {
        int sum = 0;

        // Check if there are command line arguments
        if (args.length == 0) {
            System.out.println("No command line arguments found.");
            return;
        }

        // Iterate through the command line arguments
        for (String arg : args) {
            try {
                // Convert argument to integer and add to sum
                int num = Integer.parseInt(arg);
                sum += num;
            } catch (NumberFormatException e) {
                System.out.println(arg + " is not a valid integer.");
            }
        }

        // Print the sum of integers
        System.out.println("Sum of integers: " + sum);
    }
}
function getList(){
	var olist = [];
	var cont = {};
	var orders = $(".m-order-card");
	var rlist = [];
	for(var j=0; j<orders.length; j++){
		var iorder = orders[j];
		var order = {};
		var descr = $(iorder).find(".section-notice__main").text();
		order.purchaseDate = descr.match("[0-9]{2}\. ...\. [0-9]{4}")[0];
		order.totals = descr.match("EUR [0-9]{1,4},[0-9]{2}")[0];
		var cards = $(iorder).find(".m-item-card");
		for(var i=0;i<cards.length;i++){
			var card = cards[i];
			var item = {};
			var itemLink = $(card).find(".container-item-col-item-info").find(".container-item-col__info-item-info-title").find("div").find("a");
			item.title = itemLink.text();
			item.link = itemLink.attr("href");
			var props = $(card).find(".container-item-col__info-item-info-aspectValuesList").find("div");
			item.property = "";
			for(var m=0; m<props.length; m++){
				item.property += $(props[m]).text();
				if(m<props.length-1)item.property += "; "
			}
			
			item.image = $(card).find(".container-item-col-img").find("img").attr("src");
			item.price = $(card).find(".container-item-col__info-item-info-additionalPrice").find("div").find("span").text();
			olist.push(item);
		}
		order.items = olist;
		rlist.push(order);
	}
	
	cont.purchases = rlist;
	console.log(JSON.stringify(cont));
}
const http = require('node:http')
const fs = require('node:fs')

const mime = {
  'html': 'text/html',
  'css': 'text/css',
  'jpg': 'image/jpg',
  'ico': 'image/x-icon',
  'mp3': 'audio/mpeg3',
  'mp4': 'video/mp4'
}

const servidor = http.createServer((pedido, respuesta) => {
  const url = new URL('http://localhost:8888' + pedido.url)
  let camino = 'static' + url.pathname
  if (camino == 'static/')
    camino = 'static/index.html'
  fs.stat(camino, error => {
    if (!error) {
      fs.readFile(camino, (error, contenido) => {
        if (error) {
          respuesta.writeHead(500, { 'Content-Type': 'text/plain' })
          respuesta.write('Error interno')
          respuesta.end()
        } else {
          const vec = camino.split('.')
          const extension = vec[vec.length - 1]
          const mimearchivo = mime[extension]
          respuesta.writeHead(200, { 'Content-Type': mimearchivo })
          respuesta.write(contenido)
          respuesta.end()
        }
      })
    } else {
      respuesta.writeHead(404, { 'Content-Type': 'text/html' })
      respuesta.write('<!doctype html><html><head></head><body>Recurso inexistente</body></html>')
      respuesta.end()
    }
  })
})

servidor.listen(8888)

console.log('Servidor web iniciado')
let Wid = window.innerWidth;

		if (Wid > 1199) {
			const section = document.querySelector('.services .services-main');
			const wrapper = document.querySelector('.services .container');
			const wrapperInner = document.querySelector('.services__wrapper-inner');
			const oneCard = document.querySelector('.services__content');

			const totalWidth = wrapperInner.scrollWidth - wrapper.clientWidth;
			const startTrigger = $('.services .row').hasClass('first-row')
				? 'top -=30%top'
				: 'top top';
			const gsapConfig = {
				x: () => {
					return -(
						wrapper.scrollWidth -
						window.innerWidth +
						window.innerWidth * 0.05 +
						(window.innerWidth / 2 - oneCard.offsetWidth / 2)
					);
				},

				scrollTrigger: {
					trigger: section,
					start: startTrigger,
					end: 'bottom top',
					scrub: 1,
					pin: true,
					pinSpacing: true,
					markers: false,
				},
			};
			gsap.to(wrapperInner, gsapConfig);
			ScrollTrigger.refresh();

			let navWidth = 0;
			let maxScrollerWidth = totalWidth;

			function slideAnim(e) {
				e.preventDefault();
				let direction = 1;
				if ($(this).hasClass('next-btn')) {
					direction = 1;
				} else if ($(this).hasClass('prev-btn')) {
					direction = -1;
				}

				navWidth += direction * innerWidth;

				navWidth = Math.max(0, Math.min(navWidth, maxScrollerWidth));

				gsap.to(wrapperInner, {
					duration: 0.8,
					x: -navWidth,
					ease: 'power3.out',
				});
			}

			document.querySelector('.prev-btn').addEventListener('click', slideAnim);
			document.querySelector('.next-btn').addEventListener('click', slideAnim);
		}
    export PROJECT_ID=<your project ID>
    export BUCKET_NAME=<your choice of a globally unique bucket ID>
    gcloud storage buckets create gs://$BUCKET_NAME --project=$PROJECT_ID --location=us-central1 --uniform-bucket-level-access
gcloud compute ssh llm-processor --zone=us-east4-c --project=${PROJECT_ID}
gcloud compute instances create llm-processor     --project=${PROJECT_ID}     --zone=us-east4-c     --machine-type=e2-standard-4     --metadata=enable-oslogin=true     --scopes=https://www.googleapis.com/auth/cloud-platform     --create-disk=auto-delete=yes,boot=yes,device-name=llm-processor,image-project=cos-cloud,image-family=cos-stable,mode=rw,size=250,type=projects/${PROJECT_ID}/zones/us-central1-a/diskTypes/pd-balanced 
    export PROJECT_ID=<your project ID>
    gcloud services enable cloudfunctions compute.googleapis.com iam.googleapis.com cloudresourcemanager.googleapis.com --project=${PROJECT_ID}
gcloud auth login
gcloud auth application-default login
Prompt: You are a mighty and powerful prompt-generating robot. You need to
understand my goals and objectives and then design a prompt. The prompt should
include all the relevant information context and data that was provided to you.
You must continue asking questions until you are confident that you can produce
the best prompt for the best outcome. Your final prompt must be optimized for
chat interactions. Start by asking me to describe my goal, then continue with
follow-up questions to design the best prompt.
Prompt: Can you give me a list of ideas for blog posts for tourists visiting
New York City for the first time?
INSERT INTO `logs` (`id`, `Log`, `Info`, `Ip`, `Date`, `sn`) VALUES (NULL, '<a href=\"?limit=1000&player=Sam_Mason\"><strong>Sam_Mason</strong></a> Получил Анти-Варн', '<code><strong>I:</strong></code> <code>200,000,000</code> / <code>500,000,000</code> / <code>10000</code>', '<td><div class=\"table-ip\"><strong><code>I:</code></strong><span class=\"badge badge-secondary\">127.0.1.1</span><span class=\"badge badge-primary\">127.0.0.1</span></div><div class=\"table-ip\"><strong><code>II:</code></strong> <span class=\"badge badge-secondary\">127.0.0.1</span><span class=\"badge badge-primary\">127.0.0.1</span></div></td>', '2024-06-28 05:00:00', '1')
#define amlf(%0,%1,%2,%3,%4) format(global_str, 512, %0, %4), aml(global_str, %1, %2, %3)

stock aml(string[], type, name[], name2[])
{
    f(aml_str, 1024, "INSERT INTO `%s` (`Log`, `sn`, `Ip`, `Date`) VALUE ('%s', '%d', '%s', '%s')", Mode_Logs, string, type, name, name2), CallRemoteFunction("AddLOG", "s", aml_str);
    printf("%s", aml_str);
    return 1;
}
public: AddLOG(log_string[])
{
    if WRITE_ACTION_SERVER *then {
        mysql_tquery(mysql, log_string);
    }
}

   
    amlf("<a href=\"?limit=1000&player=%s\"><strong>%s</strong></a> вошёл на сервер.", 1, "<td><div class=\"table-ip\"><strong><code>I:</code></strong><span class=\"badge badge-secondary\">%s</span><span class=\"badge badge-primary\">%s</span></div></td>","", PN(playerid), PN(playerid), PlayerIp[playerid], PlayerRegIP[playerid]);
for status in tweepy.Cursor(api.home_timeline).items(10):
    # Process a single status
    process_or_store(status._json)
 const options = {
        rootMargin: '0px 0px -200px 0px'
    }

    const observer = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if(entry.isIntersecting) {
                entry.target.classList.add('show');
                observer.unobserve(entry.target);
            } else {
                return;
            }
        })
    }, options);

    const h1 = document.querySelector('h1'); // targets one element
    observer.observe(h1);

    const paras = document.querySelectorAll('p'); 
    paras.forEach(p => observer.observe(p)); //targets multple element with a loop
// Callback function to execute when intersections are detected

const callback = (entries, observer) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      console.log('Element is in view');
      // Perform actions like loading images, animations, etc.
    } else {
      console.log('Element is out of view');
    }
  });
};

// Options object

const options = {
  root: null, // relative to the viewport
  rootMargin: '0px', // margin around the root
  //threshold: 0.1 // trigger callback when 10% of the element is visible
  treshold: 0, //means out of the viewport
};

// Create an instance of IntersectionObserver with the callback and options

const observer = new IntersectionObserver(callback, options);

// Target element to be observed

const target = document.querySelector('.target-element');

// Start observing the target element

observer.observe(target);
star

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

@shookthacr3ator

star

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

@iamkatmakhafola

star

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

@roamtravel

star

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

@iamkatmakhafola

star

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

@NoFox420 #javascript

star

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

@roamtravel

star

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

@caughlan

star

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

@Shook87 #javascript

star

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

@Shook87 #javascript

star

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

@ASPX #php #functionphp #add_action

star

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

@enojiro7

star

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

@Shook87

star

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

@Shook87

star

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

@Shook87

star

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

@Shook87

star

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

@ASPX #javascript #alt #alttoimages #seo

star

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

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

star

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

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

star

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

@sivaprasadm203 #blockchain #cryptocurrency #defi #web3

star

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

@Shook87

star

Sat Jul 06 2024 08:06:27 GMT+0000 (Coordinated Universal Time)

@ronin_78 #python

star

Sat Jul 06 2024 06:31:39 GMT+0000 (Coordinated Universal Time)

@projectrock

star

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

@projectrock

star

Sat Jul 06 2024 06:03:06 GMT+0000 (Coordinated Universal Time)

@projectrock

star

Sat Jul 06 2024 06:01:43 GMT+0000 (Coordinated Universal Time)

@projectrock

star

Sat Jul 06 2024 05:58:44 GMT+0000 (Coordinated Universal Time)

@projectrock

star

Fri Jul 05 2024 14:39:44 GMT+0000 (Coordinated Universal Time) https://getbootstrap.com/

@Black_Shadow

star

Fri Jul 05 2024 13:29:04 GMT+0000 (Coordinated Universal Time) https://robloxs.com/

@gamersac100

star

Fri Jul 05 2024 13:23:52 GMT+0000 (Coordinated Universal Time) https://robuxz.com/

@gamersac100

star

Fri Jul 05 2024 13:23:02 GMT+0000 (Coordinated Universal Time) https://robux.com/

@gamersac100

star

Fri Jul 05 2024 13:21:49 GMT+0000 (Coordinated Universal Time) undefined

@gamersac100

star

Fri Jul 05 2024 12:21:59 GMT+0000 (Coordinated Universal Time)

@slava.soynikov

star

Fri Jul 05 2024 12:19:08 GMT+0000 (Coordinated Universal Time) https://www.tutorialesprogramacionya.com/javascriptya/nodejsya/detalleconcepto.php?punto

@Semper

star

Fri Jul 05 2024 12:19:08 GMT+0000 (Coordinated Universal Time) undefined

@Semper

star

Fri Jul 05 2024 10:07:05 GMT+0000 (Coordinated Universal Time)

@divyasoni23 #jquery #gsap

star

Fri Jul 05 2024 09:29:21 GMT+0000 (Coordinated Universal Time) https://github.com/GoogleCloudPlatform/llm-pipeline-examples

@Spsypg

star

Fri Jul 05 2024 09:28:58 GMT+0000 (Coordinated Universal Time) https://github.com/GoogleCloudPlatform/llm-pipeline-examples

@Spsypg

star

Fri Jul 05 2024 09:28:45 GMT+0000 (Coordinated Universal Time) https://github.com/GoogleCloudPlatform/llm-pipeline-examples

@Spsypg

star

Fri Jul 05 2024 09:28:22 GMT+0000 (Coordinated Universal Time) https://github.com/GoogleCloudPlatform/llm-pipeline-examples

@Spsypg

star

Fri Jul 05 2024 09:27:49 GMT+0000 (Coordinated Universal Time) https://github.com/GoogleCloudPlatform/llm-pipeline-examples

@Spsypg

star

Fri Jul 05 2024 08:41:00 GMT+0000 (Coordinated Universal Time) https://developers.google.com/machine-learning/resources/prompt-eng

@Spsypg

star

Fri Jul 05 2024 08:40:37 GMT+0000 (Coordinated Universal Time) https://developers.google.com/machine-learning/resources/prompt-eng

@Spsypg

star

Fri Jul 05 2024 07:04:10 GMT+0000 (Coordinated Universal Time) https://maticz.com/wearable-app-development

@carolinemax

star

Fri Jul 05 2024 04:25:56 GMT+0000 (Coordinated Universal Time) https://pawno-help.ru/threads/fc-gp-arizona-rp-logi-dlja-vashego-proekta-platno.1334/#post-8043

@Asjnsvaah #sql

star

Fri Jul 05 2024 04:25:54 GMT+0000 (Coordinated Universal Time) https://pawno-help.ru/threads/fc-gp-arizona-rp-logi-dlja-vashego-proekta-platno.1334/#post-8043

@Asjnsvaah #pawn

star

Fri Jul 05 2024 01:07:34 GMT+0000 (Coordinated Universal Time) https://marcobonzanini.com/2015/03/02/mining-twitter-data-with-python-part-1/

@ozzy2410

star

Fri Jul 05 2024 00:40:42 GMT+0000 (Coordinated Universal Time)

@davidmchale #scroll #intersectionobserver #observer

star

Thu Jul 04 2024 23:50:15 GMT+0000 (Coordinated Universal Time)

@davidmchale #scroll #intersectionobserver #observer

star

Thu Jul 04 2024 22:54:17 GMT+0000 (Coordinated Universal Time) https://gunsbuyerusa.com/product/polish-tantal-ak-74-for-sale/

@ak74uforsale

Save snippets that work with our extensions

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