Snippets Collections
public function index(Travel $travel, ToursListRequest $request)
    {
        $tours = $travel->tours()
            ->when($request->priceFrom, function ($query) use ($request) {
                $query->where('price', '>=', $request->priceFrom * 100);
            })
            ->when($request->priceTo, function ($query) use ($request) {
                $query->where('price', '<=', $request->priceTo * 100);
            })
            ->when($request->dateFrom, function ($query) use ($request) {
                $query->where('starting_date', '>=', $request->dateFrom);
            })
            ->when($request->dateTo, function ($query) use ($request) {
                $query->where('starting_date', '<=', $request->dateTo);
            })
            ->when($request->sortBy, function ($query) use ($request) {
                if (! in_array($request->sortBy, ['price'])
                    || (! in_array($request->sortOrder, ['asc', 'desc']))) {
                    return;
                }

                $query->orderBy($request->sortBy, $request->sortOrder);
            })
            ->orderBy('starting_date')
            ->paginate();

        return TourResource::collection($tours);
    }
<!DOCTYPE html>
<html lang="en">
<head>
    <style>

body {
    background-color: lightblue;
  }
  h3{background-color: aliceblue;text-align: center;text-decoration: dotted;

  }
  h1{
    text-decoration: double;background-color: azure;
  }
div{
    align-items: center;
}
a{
    align-items: center;
}
div{
    text-align: left;background-color: aquamarine;position: static;align-items: right;
    border: 3px solid #73AD21;
}


    </style>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div style="position: fixed;right: 0px;">
     username: <input placeholder="enter user id">
    <br>
    <br>
    password: <input type="password" placeholder="enter your password">
    </div>
    <h1 style="color: red;text-align: center;"> PRODUCT DETAIL:- </h1>
    <h3 style="text-align:center;color: black;">Samsung Galaxy M34 5G (Midnight Blue, 6GB, 128GB Storage) | 120Hz sAMOLED Display | 50MP Triple No Shake Cam | 6000 mAh Battery | 12GB RAM with RAM Plus | Android 13 | Without Charger</h3>
    <h1 style="text-align: center;color: rgb(30, 32, 32);">name:-</h1>
    <p style="text-align: center;color: brown;"> samsung m3</p>
    <h2>About this item:-</h2>
    <p style="text-align: center;text-decoration: dotted; background-color: blueviolet;">
        Exynos 1280 Octa Core 2.4GHz with the 12 band support for a True 5G experience
        16.42 centimeters (6.5-inch) Super AMOLED Display, FHD+ resolution, 1080 x 2340 pixels protected by Gorilla Glass 5
        50MP+8MP+2MP Triple Camera Setup - True 50MP No Shake Cam (F1.8) Main Camera + 8MP (F2.2) + 2MP (F2.4)| 13MP (F2.0) Front Camera
        6000mAH lithium-ion battery, 1 year manufacturer warranty for device and 6 months manufacturer warranty for in-box accessories including batteries from the date of purchase
        4 Generations of OS Upgrades and 5 Years of Security Updates</p>
        <div>
    <a href="https://www.amazon.in/Samsung-Midnight-Storage-sAMOLED-Display/dp/B0C7BZX934/ref=lp_4363159031_1_1?sbo=RZvfv%2F%2FHxDF%2BO5021pAnSA%3D%3D"> <img style="align-items: center;" src="https://m.media-amazon.com/images/I/91fonhAtoAL._AC_UL320_.jpg" alt=""></a>
</div>
</html>
#include <iostream>
using namespace std;

void rotate(int arr[], int n, int k) {
    // Create a new array to store rotated elements
    int rotatedArr[n];

    // Copy the elements from the original array to the rotated array
    for (int i = 0; i < n; i++) {
        rotatedArr[i] = arr[(i + k) % n];
    }

    // Print the rotated array
    for (int i = 0; i < n; i++) {
        cout << rotatedArr[i] << " ";
    }
}

int main() {
    int n, k;
    cin >> n;//

    int* arr = new int[n];
    for (int i = 0; i < n; i++) {
        cin >> arr[i];
    }

    cin >> k;

    rotate(arr, n, k);

    delete[] arr;
    return 0;
}
#include <iostream>
using namespace std;

int main() {
    //Write your code here
    int n;
    cin>>n;

    int* arr = new int [n];

    for(int i = 0; i < n; i++){
        cin>>arr[i];
    }
    for(int i = n-1 ; i >= 0; i--){
        cout<<arr[i]<<" ";
    }

    return 0;
}
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { IonicModule } from '@ionic/angular';
import { HomePage } from '../home/home.page';

interface Restaurant {
  name: string;
  dish: string;
  rating: number;
  distance: string;
  price: number;
  image: string;
  topDish: string;
}

@Component({
  selector: 'app-search',
  templateUrl: './search.page.html',
  styleUrls: ['./search.page.scss'],
  standalone: true,
  imports: [IonicModule, CommonModule, FormsModule],
  providers:[HomePage]
})
export class SearchPage implements OnInit {
  searchTerm!: '';
  searchResults: Restaurant[] = [];

  ngOnInit() {
  }

  constructor( private homePage: HomePage) { }
  // Filters the restaurant list based on the user's search term for name, dish, rating, and distance.
  searchRestaurants() {
    if (this.searchTerm.length > 0) {
      this.searchResults = this.homePage.restaurantList.filter((restaurant) =>
        restaurant.name.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
        restaurant.dish.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
        restaurant.topDish.toLowerCase().includes(this.searchTerm.toLowerCase()) ||
        (restaurant.rating >= parseInt(this.searchTerm) && restaurant.rating < parseInt(this.searchTerm) + 1)

      )
    } else {
      this.searchResults = [];
    };
  };


  addToCart(restaurant:any){
    this.homePage.addToCart(restaurant);
  }

}
<ion-content>
  <ion-card>
    <ion-searchbar [(ngModel)]="searchTerm" (ionInput)="searchRestaurants()"></ion-searchbar>
    <ion-list *ngIf="searchResults.length > 0">
      <ion-item *ngFor="let restaurant of searchResults">
        <ion-thumbnail slot="start">
          <ion-img alt="restaurant-image" class="restaurant-image" id="image-background" [src]="restaurant.image"></ion-img>
        </ion-thumbnail>
        <ion-grid>
          <ion-label>
            <ion-row>
              <ion-col class="col-header">
                <ion-text color="primary">
                 <h1>{{ restaurant.name }}</h1>
              </ion-text>
              </ion-col>
            </ion-row>
            
            <ion-row>
              <ion-col class="col-header">
                <p><ion-icon name="fast-food-outline"></ion-icon>‎‎{{ restaurant.dish }}</p>
              </ion-col>
            </ion-row>
            
            <ion-row>
              <ion-col>
                <ion-text color="medium"> <sub><ion-icon name="star"></ion-icon>{{ restaurant.rating }}</sub></ion-text>
              </ion-col>
              <ion-col >
                <ion-text color="medium"><sub><ion-icon name="pricetag"></ion-icon> {{ restaurant.price | currency :'ZAR':'symbol' }}</sub></ion-text>
              </ion-col>
              <ion-col >
                <ion-text color="medium"> <sub><ion-icon name="car"></ion-icon>{{ restaurant.distance }}</sub></ion-text>
              </ion-col>
            </ion-row>
            
            <ion-row>
              <ion-col>
                <ion-button style="width: 100%" (click)="addToCart(restaurant);">Add To Cart</ion-button>
              </ion-col>
            </ion-row>
            </ion-label>
            
        </ion-grid>
      </ion-item>
    </ion-list>
  </ion-card>
</ion-content>



#include <stdio.h>

struct Item {
    char name[50];
    float price;
    int quantity;
};

float calculateTotal(struct Item items[], int itemCount) {
    float total = 0.0;
    for (int i = 0; i < itemCount; i++) {
        total += items[i].price * items[i].quantity;
    }
    return total;
}

float calculateDiscountedTotal(float total, float discount) {
    return total - (total * discount / 100);
}

float calculateRemainingCash(float total, float cashInput) {
    return cashInput - total;
}

void displayBill(struct Item items[], int itemCount, float total, float discount, float cashInput, float remainingCash) {
    printf("\n********** BILL **********\n");
    printf("Item\t\tPrice\tQuantity\n");
    printf("----------------------------\n");
    for (int i = 0; i < itemCount; i++) {
        printf("%s\t\t%.2f\t%d\n", items[i].name, items[i].price, items[i].quantity);
    }
    printf("----------------------------\n");
    printf("Total: %.2f\n", total);
    printf("Discount: %.2f%%\n", discount);
    printf("Discounted Total: %.2f\n", calculateDiscountedTotal(total, discount));
    printf("Cash Input: %.2f\n", cashInput);
    printf("Remaining Cash: %.2f\n", remainingCash);
    printf("****************************\n");
}

int main() {
    int itemCount;
    printf("Enter the number of items: ");
    scanf("%d", &itemCount);

    struct Item items[itemCount];

    printf("Enter the details of each item:\n");
    for (int i = 0; i < itemCount; i++) {
        printf("Item %d:\n", i + 1);
        printf("Name: ");
        scanf("%s", items[i].name);
        printf("Price: ");
        scanf("%f", &items[i].price);
        printf("Quantity: ");
        scanf("%d", &items[i].quantity);
    }

    float total = calculateTotal(items, itemCount);

    float discount;
    printf("Enter discount percentage: ");
    scanf("%f", &discount);

    float cashInput;
    printf("Enter cash input: ");
    scanf("%f", &cashInput);

    float remainingCash = calculateRemainingCash(calculateDiscountedTotal(total, discount), cashInput);

    displayBill(items, itemCount, total, discount, cashInput, remainingCash);

    return 0;
}
#include <stdio.h>

void printArray(int *A, int n)
{
    for (int i = 0; i < n; i++)
    {
        printf("%d ", A[i]);
    }
    printf("\n");
}

void merge(int A[], int mid, int low, int high)
{
    int i, j, k, B[100];
    i = low;
    j = mid + 1;
    k = low;

    while (i <= mid && j <= high)
    {
        if (A[i] < A[j])
        {
            B[k] = A[i];
            i++;
            k++;
        }
        else
        {
            B[k] = A[j];
            j++;
            k++;
        }
    }
    while (i <= mid)
    {
        B[k] = A[i];
        k++;
        i++;
    }
    while (j <= high)
    {
        B[k] = A[j];
        k++;
        j++;
    }
    for (int i = low; i <= high; i++)
    {
        A[i] = B[i];
    }
    
}

void mergeSort(int A[], int low, int high){
    int mid; 
    if(low<high){
        mid = (low + high) /2;
        mergeSort(A, low, mid);
        mergeSort(A, mid+1, high);
        merge(A, mid, low, high);
    }
}

int main()
{
    // int A[] = {9, 14, 4, 8, 7, 5, 6};
    int A[] = {9, 1, 4, 14, 4, 15, 6};
    int n = 7;
    printArray(A, n);
    mergeSort(A, 0, 6);
    printArray(A, n);
    return 0;
}
#include<stdio.h>
#include<stdlib.h>

int graph[10][10], visited[10],total,arr[30];
static int k=0,count=0;
void DFS(int);
main()
{
	int i,j;
	printf("\nEnter the total number of vertices in graph\n");
	scanf("%d",&total);
	/*Adjacency matrix input*/
	printf("\nEnter the adjacency matrix\n");
	for(i=0;i<total;i++)
	{
		for(j=0;j<total;j++)
		{
			scanf("%d",&graph[i][j]);
		}
	}
	for(i=0;i<total;i++)
	{
		visited[i] = 0;
	}
	printf("\nDFS traversal is \n");
	DFS(0);
}
void DFS(int vertex)
{
	int j,c=0;
	count++;
	printf("%d\t",vertex);
	visited[vertex] = 1;
	for(j=0;j<total;j++)
	{
		if(!visited[j] && graph[vertex][j] == 1)
		{
			arr[++k] = j;
			c=1;
		}
		if(count == total)
		{
			exit(0);
		}
	}
	if(c==1)
	{
		DFS(arr[k]);
	}
	else
	{
		k--;
		DFS(arr[k]);
	}	
}
#include<stdio.h>

void BFS(int);
int graph[10][10], visited[10],total;

main()
{
	int i,j;
	printf("\nEnter the total number of vertices in graph\n");
	scanf("%d",&total);
	/*Adjacency matrix input*/
	printf("\nEnter the adjacency matrix\n");
	for(i=0;i<total;i++)
	{
		for(j=0;j<total;j++)
		{
			scanf("%d",&graph[i][j]);
		}
	}
	for(i=0;i<total;i++)
	{
		visited[i] = 0;
	}
	printf("\nBFS traversal is \n");
	BFS(0);
}
void BFS(int vertex)
{
	int j;
	printf("%d\t",vertex);
	visited[vertex] = 1;
	for(j=0;j<total;j++)
	{
		if(!visited[j] && graph[vertex][j] == 1 )
		{
			BFS(j);
		}
	}
}
 const searchParams = new URLSearchParams(window.location.search);
  const id = searchParams.get('id');
  console.log(id)
class Solution:
    def binarySearch(self, nums, target):
        start, end = 0, len(nums) - 1 

        while start <= end: 
            middle = (start + end) // 2 
            current = nums[middle] 

            if target > current: 
                start = middle + 1 
            elif target < current: 
                end = middle - 1 
            else: 
                return middle
                #return current if you want value instead of index 
        return -1 
    
    
    def search(self, nums: List[int], target: int) -> int:
        if len(nums) == 0: 
            return -1 
        elif len(nums) == 1: 
            if nums[0] != target: 
                return -1 
            else: 
                return 0 
        else: 
            rotated = False
            lastIdx = len(nums) - 1 

            if nums[lastIdx] < nums[0]: 
                rotated = True 

            if rotated == False: 
                return self.binarySearch(nums, target) 
            else: 
                previous = nums[0]
                rotateIdx = 0 
                for i in range(1, len(nums)): 
                    if nums[i] < previous: 
                        rotateIdx = i 
                    previous = nums[i]
                    
                array1 = nums[:rotateIdx]
                array1Length = len(array1)
                array2 = nums[rotateIdx:] 

                if self.binarySearch(array1, target) == -1 and self.binarySearch(array2, target) != -1: 
                    return array1Length + self.binarySearch(array2, target)
                return self.binarySearch(array1, target)
function attachment_search( $query ) {
    if ( $query->is_search ) {
       $query->set( 'post_type', array( 'post', 'attachment' ) );
       $query->set( 'post_status', array( 'publish', 'inherit' ) );
    }
 
   return $query;
}

add_filter( 'pre_get_posts', 'attachment_search' );
#solution where you just take subset I and replace last return statement 
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:

   
        subset = [] 
        result = [] 
        
        #i is index of subset 
        def dfs(i): 
            if i >= len(nums): 
                result.append(subset.copy())
                return 
            
            #decision to include nums[i]
            subset.append(nums[i])
            #this recursive call will be given filled subset 
            dfs(i + 1)
            
            #decision NOT to include nums[i] 
            subset.pop()
            #this recursive call will be given empty subset 
            dfs(i + 1)
        
        dfs(0) 
        
        #need to remove duplicate sublists within result 
        return ([list(i) for i in {*[tuple(sorted(i)) for i in result]}])  
  

#solution to prevent duplicates in the first place
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:

   
        result = []
		nums.sort() 

		def backtrack(i, subset): 
        	if i == len(nums): 
            	res.append(subset.copy())
				return 
			
			#all subsets that include nums[i] 
            subset.append(nums[i]) 
			backtrack(i + 1, subset) 
			#remove number we just added 
            subset.pop()
            
            #all subsets that don't include nums[i]
        	while i + 1 < len(nums) and nums[i] == nums[i + 1]: 
            	i += 1 
			backtrack(i + 1, subset)
		
		backtrack(0, [])
		
		return result 
        
        
        
        
#solution for array with unique integer array. only last return line is dfferent 
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        subset = [] 
        result = [] 
        
        #i is index of subset 
        def dfs(i): 
            if i >= len(nums): 
                result.append(subset.copy())
                return 
            
            #decision to include nums[i]
            subset.append(nums[i])
            #this recursive call will be given filled subset 
            dfs(i + 1)
            
            #decision NOT to include nums[i] 
            subset.pop()
            #this recursive call will be given empty subset 
            dfs(i + 1)
        
        dfs(0) 
        
        return result 
        
        
        
def solution(n, k):
    return climb(n, k, [])
    
        
        
def climb(n, k, jumps):
    if n == 0:
        return [jumps]
    
    out = []
    
    for i in range(1, k+1):
        if i > n:
            continue
            
        temp = jumps + [i] 
        out += climb(n-i, k, temp)
        
    return out
class Solution:
    #number of permutations = n! 
    def permute(self, nums: List[int]) -> List[List[int]]:
        result = []
    
        if len(nums) == 1: 
            return [nums[:]] 
        
        for i in range(len(nums)): 
            #pop off first element 
            n = nums.pop(0)
            
            #numswill now have one less value, will append popped value later 
            perms = self.permute(nums) 
            
            for perm in perms: 
                perm.append(n)
            
            result.extend(perms)
            #adding popped back 
            nums.append(n) 
        
        return result 
 
class Solution:

    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = []
        
        #i is index of candidates 
        def dfs(i, current, total): 
            if total == target: 
              #if you do not add .copu() it will append empty arrays 
                result.append(current.copy())
                return 
            if i >= len(candidates) or total > target: 
                return 

            #decision tree has 2 options: 1) add candidates[i] or 2) do not add and move on to next index 
            
            #1) try adding candidates[i]
            current.append(candidates[i])
            dfs(i, current, total + candidates[i])
            #2) move on to next index 
            current.pop() 
            dfs(i + 1, current, total)
        
        dfs(0, [], 0)
        return result 
class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        subset = [] 
        result = [] 
        
        #i is index of subset 
        def dfs(i): 
            if i >= len(nums): 
                result.append(subset.copy())
                return 
            
            #decision to include nums[i]
            subset.append(nums[i])
            #this recursive call will be given filled subset 
            dfs(i + 1)
            
            #decision NOT to include nums[i] 
            subset.pop()
            #this recursive call will be given empty subset 
            dfs(i + 1)
        
        dfs(0) 
        
        return result 
        
        
class Tree(object):
  def __init__(self, x, left=None, right=None):
    self.value = x
    self.left = left
    self.right = right 

x = Tree(1, Tree(0, Tree(1), Tree(3)), Tree(4))


def solution(t): 
    if not t: 
        return 0 
    
    stack = [(t, 0)]
    branchesSum = 0 
    
    while stack: 
        node, v = stack.pop() 
        if node.left or node.right:
        #depth first search 
        # the v is a little confusing to understand but easier to see in python tutor 
        # it goes from 1 to 10 to 100 etc. based on the height of the branch 
        # can probably do something like str() and converting back to int() as well 
            if node.left: 
                stack.append((node.left, node.value + v * 10)) 
            if node.right: 
                stack.append((node.right, node.value + v * 10)) 
        else: 
            branchesSum += node.value + v * 10 
    return branchesSum 
#
# Binary trees are already defined with this interface:
# class Tree(object):
#   def __init__(self, x):
#     self.value = x
#     self.left = None
#     self.right = None
import math 
def solution(t):
    if t is None: return [] 
    
    stack = [t] 
    result = []
    
    while len(stack) > 0: 
        result.append(max(tree.value for tree in stack)) 
        next_row = [tree.left for tree in stack if tree.left] + [tree.right for tree in stack if tree.right]
        stack = next_row 
    return result 


 #1. Add max value of ‘stack’ to result. 2. Create a new list of all next values for each value in stack. 3. redefine stack to this newly made list. 4. repeat 


#alternate solution 
def solution(t):
    largestValues = []
    q = []
    height = 0
    if t:
        q.append([t, height])
        while q:
            item = q.pop()
            node = item[0]
            currentHeight = item[1]
            if node.left:
                q.insert(0, [node.left, currentHeight + 1] )
            if node.right:
                q.insert(0, [node.right, currentHeight + 1])
            checkLargest(node.value, currentHeight, largestValues)
            
    return largestValues
    
        
def checkLargest(value, height, largestValues):
    if height == len(largestValues):
        largestValues.append(value)
    else:
        if largestValues[height] < value:
            largestValues[height] = value
# //Tree Traversal (visit every node once) 
# //Heavy on recursion 
 
# //Breadth-first (BFS) vs. Depth-first (DFS) 
 
# // DFS: 
# // 1) in order (go in order of value)
# // 2) pre order (start at root)
# // 3) post order (start at botom)
 
 
# //When to use BFS vs. DFS: 
# //For a fully loaded (wide) tree, BFS queue will be overloaded in the start (overloaded space complexity)
# //For a longer tree, DFS will take more memory (more rare, Trees are usually wide)
# //Big O for both is same 
 
# //In order: useful if you want sorted array at end (you don't really know what the root is bc it's in the middle)
# //PreOrder: useful to "export a tree" so that it can be copied bc it flattens it 

class Node: 
  def __init__(self, value): 
    self.value = value 
    self.left = None 
    self.right = None 
 
class BinarySearchTree: 
  def __init__(self): 
    self.root = None 
 
  #adds number to correct place 
  def insert(self, value): 
    #creates new Node   
    new_node = Node(value) 
    #start at root 
    #if no root exists, root becomes new_node 
    if self.root == None: 
      self.root = new_node 
      return self 
    
    current = self.root 
    
    while True: 
      #to handle special case where value is same as current node 
      #you can return None or you can add a counter property 
      if value == current.value: 
        return None 
      #check to see if value is less than current 
      if value < current.value: 
        #check to see if there is node to left 
        #if not, add new_node to left 
        if current.left == None: 
          current.left = new_node 
          return self
        #if there is node to left, move to that node and repeat 
        current = current.left 
      #check to see if value is greater than current 
      else: 
        #check to see if there is node to right 
        #if not, add new_node to right 
        if current.right == None: 
          current.right = new_node 
          return self 
        #if there is node to right, move to that node and repeat 
        current = current.right 
        
  #Breadth first search iterative using queue 
  def BFS(self):
    node = self.root 
    #we will return data 
    data = [] 
    queue = [] 
    #place root node inside queue (recall FIFO)
    queue.append(node) 
    #while queue is not empty 
    while len(queue) > 0: 
      #dequeue node from queue and append to data  
      node = queue.pop(0)
      data.append(node) 
      #if there is left on node dequeued, add to queue 
      if node.left: 
        queue.append(node.left) 
      #if there is right on node dequeued, add to queue 
      if node.right: 
        queue.append(node.right) 
      #above two lines of code could be changed if it was a ternary tree, etc. instead of binary 
      #just loop for all children 
    return data 
  
  #parent down uses recursive 
  def DFSPreoder(self): 
    data = [] 
    #if you want to DFS not from root, create a variable here named current and specify which node to start from 
    #helper function 
    def traverse(node): 
      #all of root node's left will happen first, then right 
      #for other types of DFS, just tweak this order 
      data.append(node.value) 
      if node.left:
        traverse(node.left)
      if node.right: 
        traverse(node.right)
    
    traverse(self.root) 
    return data 
  
  #children up, root should be last value 
  def DFSPostOrder(self): 
    data = []
    
    def traverse(node): 
      if node.left:
        traverse(node.left)
      if node.right: 
        traverse(node.right)
      data.append(node.value)
    
    traverse(self.root)
    return data 
  
  #result data list should be sorted 
  def DFSInOrder(self):
    data = []
    def traverse(node): 
      if node.left: 
        traverse(node.left)
      data.push(node.value)
      if node.right: 
        traverse(node.right)
    traverse(self.root)
    return data 

t = BinarySearchTree() 
t.insert(1)
t.insert(5)
t.insert(6)
t.insert(2)
t.insert(0) 
t.insert(-1)
t.insert(7) 

print(t.DFSInOrder())
# //Lists are linear but trees are nonlinear 
# //Often working with binary trees and specifically binary search trees 
 
# //SL is techically a special case tree 
 
# //Root: top node of tree
# //Child: node directly connected to another node when moving away from root 
# //Parent: converse notion of child 
# //Siblings: group of node with same parent 
# //Leaf: node with no children 
# //Edge: connection betweeen one node and another (often arrows) 
 
# //Used for HTML DOM, network routing, abstract syntax trees, folder organization, AI, best possible move (decision tree)
 
# //We will focus on binary search tree (can only have at most 2 child nodes)
# //For each node, everything to left is smaller. Right >> bigger
 


class Node: 
  def __init__(self, value): 
    self.value = value 
    self.left = None 
    self.right = None 

class BinarySearchTree: 
  def __init__(self): 
    self.root = None 

  #adds number to correct place 
  def insert(self, value): 
    #creates new Node   
    new_node = Node(value) 
    #start at root 
    #if no root exists, root becomes new_node 
    if self.root == None: 
      self.root = new_node 
      return self 
    
    current = self.root 
    
    while True: 
      #to handle special case where value is same as current node 
      #you can return None or you can add a counter property 
      if value == current.value: 
        return None 
      #check to see if value is less than current 
      if value < current.value: 
        #check to see if there is node to left 
        #if not, add new_node to left 
        if current.left == None: 
          current.left = new_node 
          return self
        #if there is node to left, move to that node and repeat 
        current = current.left 
      #check to see if value is greater than current 
      else: 
        #check to see if there is node to right 
        #if not, add new_node to right 
        if current.right == None: 
          current.right = new_node 
          return self 
        #if there is node to right, move to that node and repeat 
        current = current.right 
  
  #find() returns value while contains() returns boolean 
  #find will point to entire node 
  def find(self, value): 
    #check to see if there is root and if not, we are done! 
    if self.root == None: 
      return False 
    current = self.root 
    found = False 
    
    while current and not found: 
      #if value is less than current 
      if value < current.value: 
        #check to see if there is node to left 
        #if there is, move to that node and repeat 
        current = current.left 
        #if not, we ar edone because current will no longer exist 
      #if value is greater than current 
      elif value > current.value: 
        #check to see if there is node to right 
        #if there is, move to that node and repeat 
        current = current.right 
        #if not, we are done because current will no longer exist 
      else: 
        found = True 
    
    if not found:
      return None 
    return current 
    
  def contains(self, value): 
    if self.root == None: 
      return False 
    current = self.root 
    found = False 
    
    while current and not found: 
      if value < current.value: 
        current = current.left 
      elif value > current.value: 
        current = current.right 
      else: 
        return True 
    return False 
          
t = BinarySearchTree()
t.insert(3)
t.insert(5)
t.insert(2)
t.insert(-1)
t.insert(6)
t.find(6) 
t.contains(6)

# // Insertion and Search: O(log N) VERY GOOD 
# // Not guaranteed if BST is a one sided tree (choose a different root) 
 
 
 
# //      10
# //   5     13
# // 2  7  11  16
 
# // tree = BinarySearchTree()
# // tree.insert(10)
# // tree.insert(5)
# // tree.insert(13)
# // tree.insert(11)
# // tree.insert(2)
# // tree.insert(16)
# // tree.insert(7)
# // tree.find(7) >> will point to node with 7  
# // tree.contains(6) >> False 
 
 
 
 
 
# //Primitive way of making Tree before insert() 
# // tree = BinarySearchTree()
# // tree.root = Node(10)
# // tree.root.right = Node(15)
# // tree.root.left = Node(7)
# // tree.root.left.right = Node(9)






haystack.indexOf(haystack.find(arr => arr.includes(search)));
<- 2
function philosophy_search_form($form)
{
   $home_dir = home_url('/');
   $label = __('Search for:', 'philosophy');
   $btn_label = __('Search', 'philosophy');
   $search_form = <<<FORM
   <form role="search" method="get" class="header__search-form" action="{$home_dir}">
      <label>
            <span class="hide-content">{$label}</span>
            <input type="search" class="search-field" placeholder="Type Keywords" value="" name="s" title="{$label}" autocomplete="off">
      </label>
      <input type="hidden" name="post_type" value="book">
      <input type="submit" class="search-submit" value="{$btn_label}">
   </form>
   FORM;

   return $search_form;
}
add_filter('get_search_form', 'philosophy_search_form');
// Search Highlighting
function buson_highlight_search_results($text)
{
   if (is_search()) {
      $pattern = '/('. join('|', explode(' ', get_search_query())).')/i';
      $text = preg_replace($pattern, '<span class="search-highlight">\0</span>', $text);
   }
   return $text;
}
add_filter('the_content', 'buson_highlight_search_results');
add_filter('the_excerpt', 'buson_highlight_search_results');
add_filter('the_title', 'buson_highlight_search_results');
// Efficient Code : Time Complexity : O(R + C)
 
import java.util.*;
import java.io.*;
 
class GFG 
{ 
	static int R = 4, C = 4;

	static void search(int mat[][], int x)
	{
		int i  = 0, j = C - 1;

		while(i < R && j >= 0)
		{
			if(mat[i][j] == x)
			{
				System.out.println("Found at (" + i + ", " + j + ")");
				return;
			}
			else if(mat[i][j] > x)
			{
				j--;
			}
			else
			{
				i++;
			}
		}
		System.out.println("Not Found");
	}

	public static void main(String args[]) 
    {
        int arr[][] = {{10, 20, 30, 40},
    				   {15, 25, 35, 45},
    				   {27, 29, 35, 45},
    				   {32, 33, 39, 50}};
    	int x = 29;	   

    	search(arr, x);

		
    } 
}
 
 
 
 
// Naive Code : Time Complexity : O(R * C)
 
	static int R = 4, C = 4;

	static void search(int mat[][], int x)
	{
		for(int i = 0; i < R; i++)
		{
			for(int j = 0; j < C; j++)
			{
				if(mat[i][j] == x)
				{
					System.out.println("Found at (" + i + ", " + j + ")");
					
					return;
				}
			}
		}

		System.out.println("Not Found");
	}
​//Search a value with incorrect spaces.. 

var input = 'gu ara nteed rate';
var table = 'core_company';
var field = 'name';

var searchName = input.replace(/\s/g, '').toLowerCase();
var gr = new GlideRecord(table);
gr.addEncodedQuery(field + 'ISNOTEMPTY');
gr.query();
while (gr.next()) {
  	var fieldString = gr.getValue(field).replace(/\s/g, '').toLowerCase();
 
    if (fieldString.indexOf(searchName) != -1)
        gs.info('FOUND: "' + gr[field].getDisplayValue() + '"');
}
/*
Example:

2021-03-15T18:05:40.674Z: FOUND: "Guaranteed Rate Insurance"
2021-03-15T18:05:40.677Z: FOUND: "Guaranteed Rate, Inc2"
2021-03-15T18:05:40.678Z: FOUND: "Guaranteed Rate, Inc."
2021-03-15T18:05:40.680Z: FOUND: "Guaranteed Rate, Inc"
2021-03-15T18:05:40.682Z: FOUND: "Guaranteed Rate Affinity"

*/
import numpy as np

def pagerank(M, num_iterations=100, d=0.85):
    N = M.shape[1]
    v = np.random.rand(N, 1)
    v = v / np.linalg.norm(v, 1)
    iteration = 0
    while iteration < num_iterations:
        iteration += 1
        v = d * np.matmul(M, v) + (1 - d) / N
    return v
import java.util.Stack;

/**
 * Java Program to implement a binary search tree. A binary search tree is a
 * sorted binary tree, where value of a node is greater than or equal to its
 * left the child and less than or equal to its right child.
 * 
 * @author WINDOWS 8
 *
 */
public class BST {

    private static class Node {
        private int data;
        private Node left, right;

        public Node(int value) {
            data = value;
            left = right = null;
        }
    }

    private Node root;

    public BST() {
        root = null;
    }

    public Node getRoot() {
        return root;
    }

    /**
     * Java function to check if binary tree is empty or not
     * Time Complexity of this solution is constant O(1) for
     * best, average and worst case. 
     * 
     * @return true if binary search tree is empty
     */
    public boolean isEmpty() {
        return null == root;
    }

    
    /**
     * Java function to return number of nodes in this binary search tree.
     * Time complexity of this method is O(n)
     * @return size of this binary search tree
     */
    public int size() {
        Node current = root;
        int size = 0;
        Stack<Node> stack = new Stack<Node>();
        while (!stack.isEmpty() || current != null) {
            if (current != null) {
                stack.push(current);
                current = current.left;
            } else {
                size++;
                current = stack.pop();
                current = current.right;
            }
        }
        return size;
    }


    /**
     * Java function to clear the binary search tree.
     * Time complexity of this method is O(1)
     */
    public void clear() {
        root = null;
    }

}
star

Sat Jan 20 2024 01:44:36 GMT+0000 (Coordinated Universal Time) https://github.com/LaravelDaily/Laravel-Travel-API-Course/blob/main/app/Http/Controllers/Api/V1/TourController.php

#laravel #php #filtering #search #eloquent
star

Wed Aug 23 2023 17:03:49 GMT+0000 (Coordinated Universal Time)

#algo #search #dfs
star

Tue Aug 08 2023 20:46:13 GMT+0000 (Coordinated Universal Time)

#arr #duplicate #search #rotate
star

Tue Aug 08 2023 19:44:50 GMT+0000 (Coordinated Universal Time)

#arr #duplicate #search
star

Fri Jun 23 2023 08:02:37 GMT+0000 (Coordinated Universal Time)

#ionic #search #typescript
star

Fri Jun 23 2023 07:58:39 GMT+0000 (Coordinated Universal Time)

#ionic #search
star

Fri May 26 2023 11:18:16 GMT+0000 (Coordinated Universal Time)

#algo #search #dfs
star

Tue May 23 2023 18:14:51 GMT+0000 (Coordinated Universal Time)

#algo #search #dfs
star

Mon May 22 2023 12:45:36 GMT+0000 (Coordinated Universal Time)

#algo #search #dfs
star

Mon May 22 2023 12:25:11 GMT+0000 (Coordinated Universal Time)

#algo #bfs #search
star

Tue Mar 21 2023 06:14:02 GMT+0000 (Coordinated Universal Time)

#searchparams #url #search #id
star

Fri Aug 12 2022 22:53:09 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/search-in-rotated-sorted-array/submissions/

#python #binary #search #leetcode #neetcode
star

Wed Aug 10 2022 09:53:31 GMT+0000 (Coordinated Universal Time) https://casabona.org/2014/12/add-attachments-wordpress-search-results/

#wordpress #search #attachments
star

Tue Aug 09 2022 22:02:17 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/subsets-ii/submissions/

#python #depth #first #search #recursive #codesignal #climb #list
star

Tue Aug 09 2022 21:41:13 GMT+0000 (Coordinated Universal Time) https://app.codesignal.com/interview-practice/task/cAXEnPyzknC5zgd7x/description

#python #depth #first #search #recursive #codesignal #climb
star

Tue Aug 09 2022 20:11:11 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/permutations/submissions/

#python #depth #first #search #recursive #neetcode
star

Tue Aug 09 2022 19:43:50 GMT+0000 (Coordinated Universal Time) https://leetcode.com/problems/combination-sum/submissions/

#python #depth #first #search #recursive #neetcode
star

Tue Aug 09 2022 00:00:39 GMT+0000 (Coordinated Universal Time) https://app.codesignal.com/interview-practice/task/2oxNWXTS8eWBzvnRB/description

#python #methods #queue #codesignal #first #search #max #depth
star

Tue Jun 28 2022 23:46:22 GMT+0000 (Coordinated Universal Time) https://dev.to/ptable/two-dimensional-array-search-4b2g

#array #search
star

Sat May 14 2022 10:33:53 GMT+0000 (Coordinated Universal Time)

#search #post_type
star

Sat May 14 2022 10:25:20 GMT+0000 (Coordinated Universal Time)

#search
star

Mon Mar 15 2021 18:06:36 GMT+0000 (Coordinated Universal Time)

#servicenow #search #javascript
star

Thu Jan 02 2020 19:00:00 GMT+0000 (Coordinated Universal Time) https://en.wikipedia.org/wiki/PageRank

#javascript #python #search #historicalcode #google #algorithms
star

Sun Dec 29 2019 20:06:50 GMT+0000 (Coordinated Universal Time) https://javarevisited.blogspot.com/2015/10/how-to-implement-binary-search-tree-in-java-example.html#axzz4wnEtnNB3

#java #interviewquestions #search

Save snippets that work with our extensions

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