Share & grow the world's code base!

Delve into a community where programmers unite to discover code snippets, exchange skills, and enhance their programming proficiency. With abundant resources and a supportive community, you'll find everything essential for your growth and success.

33 snippets
  • Binary search algorithm in Python

    # Returns index of target in arr if present, else -1
    def binary_search(arr, target):
    	low = 0
    	high = len(arr) - 1
    
    	while low <= high:
    		# Check base case
    		mid = (high + low) // 2
    
    		# If element is smaller than mid, then it can only
    		# be present in left subarray
    		if arr[mid] > target:
    			high = mid - 1
    		# Else the element can only be present in right subarray
    		elif arr[mid] < target:
    			low = mid + 1
    		# If element is present at the middle itself
    		else:
    			return mid
    
    	# Element is not present in the array
    	return -1
    
    # Test array
    arr = [ 2, 3, 4, 10, 40 ]
    target = 10
    
    result = binary_search(arr, target)
    
    if result != -1:
    	print("Element is present at index", str(result))
    else:
    	print("Element is not present in array")

    Binary Search is a searching algorithm for finding an element's position in a sorted array. In this approach, the element is always searched in the middle of a portion of an array.

  • Binary search algorithm in Go

    package main
    
    import "fmt"
    
    // return target index if it exists in arr
    func search(arr []int, target int) int {
        low := 0
        high := len(arr) - 1
    
        for low <= high {
            mid := (low + high) / 2
    
            if arr[mid] < target {
                low = mid + 1
            } else if arr[mid] > target {
                high = mid - 1
            } else {
                return mid
            }
        }
    
        return -1
    }
    
    func main() {
        target := 7
        items := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
        fmt.Printf("Element '%d' index is %d", target, search(items, target))
    }
    
    // $ output
    // 6

    The binary search algorithm employs a divide-and-conquer approach to locate an item within a sorted array or list. It begins by comparing the target value to the middle element of the array. If they are not identical, the algorithm eliminates the half of the array where the target cannot reside and proceeds the search on the remaining half. This process iterates, with each step narrowing down the search range until the target value is discovered. If the search concludes with an empty remaining half, it indicates that the target is not present in the array.

  • Example of WaitGroup in Go

    package main
    
    import (
    	"fmt"
    	"sync"
    	"time"
    )
    
    func main() {
    	wg := &sync.WaitGroup{} // WaitGroup is used to wait for the execution of all running goroutines
    
    	for i := 1; i <= 5; i++ {
    		wg.Add(1) // launch several goroutines and increment the counter in WaitGroup for each running goroutine
    
    		go func(id int) {
    			worker(id, wg)
    		}(i)
    	}
    
    	fmt.Println("waiting for all goroutines to complete")
    	wg.Wait() // block the execution of the program until the WaitGroup counter becomes equal to 0 again
    	fmt.Println("done")
    }
    
    func worker(id int, wg *sync.WaitGroup) {
    	fmt.Printf("worker %d started\n", id)
    	time.Sleep(time.Second) // Sleep simulates a long task
    	
        fmt.Printf("worker %d finished\n", id)
    	wg.Done() // notify WaitGroup that the worker has completed
    }
    
    // $ go run waitgroups.go 
    // waiting for all goroutines finished
    // worker 4 started
    // worker 1 started
    // worker 2 started
    // worker 3 started
    // worker 2 finished
    // worker 4 finished
    // worker 1 finished
    // worker 3 finished
    // done

    To wait for multiple goroutines to execute, you can use the built-in WaitGroup construct.

  • Atomic counters in Go

    package main
    
    import (
    	"fmt"
    	"sync"
    	"sync/atomic"
    )
    
    func main() {
    	var atomicCounter, nonAtomicCounter uint64
    	wg := sync.WaitGroup{}
    
    	for i := 0; i < 50; i++ {
    		wg.Add(1)
    
    		go func() { // run 50 goroutines, each goroutine increases the counter 1000 times
    			for c := 0; c < 1000; c++ {
    				atomic.AddUint64(&atomicCounter, 1) // increase atomic counter
    				nonAtomicCounter++ // increase non-atomic counter
    			}
    
    			wg.Done()
    		}()
    	}
    
    	wg.Wait() // wait until all goroutines finish
    	
    	fmt.Println("atomic counter value:", atomicCounter)
    	fmt.Println("non atomic counter value:", nonAtomicCounter)
    }
    
    // go run counters.go 
    // atomic counter value: 50000
    // non atomic counter value: 30648

    An example of using the sync/atomic package for atomic counters accessed by goroutines.

  • Example of timeouts in Go

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	first := make(chan string, 1)
    
    	go func() {
    		time.Sleep(2 * time.Second) // wait 2 seconds before send value to channel
    		first <- "first result"     // send value to the channel
    	}()
    
    	select {
    	case result := <-first:
    		fmt.Println(result)
    	case <-time.After(time.Second): // timeout occurs before the value is read from the first channel
    		fmt.Println("first timeout")
    	}
    
    	second := make(chan string, 1)
    
    	go func() {
    		time.Sleep(time.Second)   // wait 1 second before send value to the channel
    		second <- "second result" // send value to the channel
    	}()
    
    	select {
    	case result := <-second: // the value from the channel is read before the timeout expires
    		fmt.Println(result)
    	case <-time.After(2 * time.Second):
    		fmt.Println("second timeout")
    	}
    }
    
    // $ go run timeouts.go 
    // first timeout
    // second result

    Timeouts are important for programs that connect to external resources or need to limit their execution time.

  • Example of using Go tickers

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	ticker := time.NewTicker(time.Second)
    	fmt.Println("ticker is started")
    
    	done := make(chan struct{})
    
    	go func() {
    		for {
    			select {
    			case <-done:
    				return
    			case t := <-ticker.C:
    				fmt.Println("tick", t)
    			}
    		}
    	}()
    
    	time.Sleep(5 * time.Second)
    
    	ticker.Stop()
    	fmt.Println("ticker is stopped")
    
    	time.Sleep(5 * time.Second)
    	done <- struct{}{}
    }
    
    // go run tickers.go 
    // ticker is started
    // tick 2024-02-09 23:40:25.809616086 +0700 +07 m=+1.000091237
    // tick 2024-02-09 23:40:26.809742343 +0700 +07 m=+2.000152938
    // tick 2024-02-09 23:40:27.809804037 +0700 +07 m=+3.000214622
    // tick 2024-02-09 23:40:28.809852444 +0700 +07 m=+4.000263029
    // ticker is stopped
    // tick 2024-02-09 23:40:29.809908932 +0700 +07 m=+5.000319557
    

    Tickers allow you to repeat actions at certain intervals. A Ticker holds a channel that delivers "ticks" of a clock at intervals. Tickers can be stopped in the same way as timers. When the ticker is stopped, it will no longer be able to accept values ​​into its channel.

  • Example of using Go timers

    package main
    
    import (
    	"fmt"
    	"time"
    )
    
    func main() {
    	firstTimer := time.NewTimer(3 * time.Second)
    	value := <-firstTimer.C // value is a current time
    
    	fmt.Printf("first timer expired: %v\n", value) // the line printed 3 seconds after running code
    
    	secondTimer := time.NewTimer(2 * time.Second)
    
    	go func() {
    		<-secondTimer.C
    		fmt.Println("second timer expired") // the line is not printed because the second timer is stopped before expiration
    	}()
    
    	stop := secondTimer.Stop() // stop second timer before it expired
    
    	if stop {
    		fmt.Println("second timer is stopped")
    	}
    }
    
    // $ go run timers.go
    // first timer expired: 2024-02-09 22:32:57.570649221 +0700 +07 m=+3.002054417
    // second timer is stopped

    Timers allow you to execute one event in the future. You tell the timer how long you want to wait and it provides a channel to be notified at that time. The first timer will wait for 3 seconds. <-firstTimer.C blocks the timer C channel until a message (current time) is sent indicating that the timer has expired. If you just want to wait, you can use time.Sleep. One reason a timer can be useful is that you can cancel the timer before it expires. The first timer expires 3s after the program starts, but the second is stopped before it expires.

  • Simple http server in Go

    package main
    
    import (
        "fmt"
        "net/http"
    )
    
    func hello(w http.ResponseWriter, req *http.Request) {
        fmt.Fprintf(w, "Hello, World!\n")
    }
    
    func headers(w http.ResponseWriter, req *http.Request) {
        for name, headers := range req.Header {
            for _, h := range headers {
                fmt.Fprintf(w, "%v: %v\n", name, h)
            }
        }
    }
    
    func main() {
        http.HandleFunc("/hello", hello)
        http.HandleFunc("/headers", headers)
    
        http.ListenAndServe(":8080", nil) // run http server on port 8080
    }
    

    Basic HTTP server using the net/http package. In the realm of net/http servers, a crucial concept involves handlers. These handlers implement http.Handler interface. A common method for creating a handler is to use http.HandlerFunc, applied to functions that have the required signature. Handlers receive a http.ResponseWriter and a http.Request as parameters. The response writer is employed to populate the HTTP response. Handlers can be registered on server routes by the http.HandleFunc function. This function configures the default router in the net/http package and accepts a function as its parameter. To start the http server, ListenAndServe is called with the specified port and handler. Passing nil as a second paramenter indicates using the default router we recently configured.

  • Check if a file exists or not in Go

    package main
    
    import (
    	"errors"
    	"fmt"
    	"os"
    )
    
    func main() {
    	filePath := "file.txt"
    
    	if _, err := os.Stat(filePath); errors.Is(err, os.ErrNotExist) {
    		fmt.Println("file not exists")
    	} else {
    		fmt.Println("file exists")
    	}
    }
  • How to detect OS in bash script?

    #!/bin/bash
    
    die()
    {
        echo "ERROR: $*" >&2
        exit 1
    }
    
    detect_os ()
    {
        OS="$(uname -s)"
        ARCH="$(uname -m)"
    
        case "$OS" in
            Linux)
                if [ -e /etc/lsb-release ]; then
                    source /etc/lsb-release
    
                    DIST_ID="${DISTRIB_ID}"
                    OS_VERSION="${DISTRIB_RELEASE}"
                    OS_CODENAME="${DISTRIB_CODENAME}"
                elif [ -e /etc/os-release]; then
                    source /etc/os-release
    
                    DIST_ID="${ID}"
                    OS_VERSION="${VERSION_ID}"
                    OS_CODENAME="${VERSION_CODENAME}"
    
                elif [ $(which lsb_release 2>/dev/null) ]; then
                    DIST_ID="$(lsb_release -s -i)"
                    OS_VERSION="$(lsb_release -s -r)"
                    OS_CODENAME="$(lsb_release -s -c)"
                else
                    die "Colud not get OS information"
                fi
    
                case "$DIST_ID" in
                    RedHat*)
                        OS_NAME="RedHat" ;;
                    debian)
                        OS_NAME="Debian" ;;
                    *)
                        OS_NAME="${DIST_ID}" ;;
                esac
                ;;
            *)
                die "Unsupported OS family: $OS"
                ;;
        esac
    
        echo "${OS}"
        echo "${OS_NAME}"
        echo "${OS_VERSION}"
        echo "${OS_CODENAME}"
    }

    This script returns OS information such as type, name, codename and version. It supports the following Linux distributions: Ubuntu, Debian, CentOS, RedHat. If you want to add support for other distributions, write in the comments below.

  • Implementation of the Quick Sort algorithm in Python

    def quick_sort(arr):
        if len(arr) <= 1:
            return arr
        else:
            pivot = arr[0]
            left = [x for x in arr[1:] if x <= pivot]
            right = [x for x in arr[1:] if x > pivot]
            return quick_sort(left) + [pivot] + quick_sort(right)
    
    # Example usage:
    input_array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5]
    sorted_array = quick_sort(input_array)
    
    print("Original Array:", input_array)
    print("Sorted Array:", sorted_array)
    

    In this code, the quick_sort function is a recursive implementation of the Quick Sort algorithm. The pivot element is chosen as the first element of the array, and elements are partitioned into two sub-arrays (left and right) based on their relationship to the pivot. The function is then called recursively on the left and right sub-arrays until the entire array is sorted.

  • Simple implementation of the Quick Sort algorithm in PHP

    <?php
    
    function quickSort(array $array): array
    {
        $length = count($array);
    
        if ($length <= 1) {
            return $array;
        }
    
        $pivot = $array[0];
        $left = $right = [];
    
        for ($i = 1; $i < $length; $i++) {
            if ($array[$i] < $pivot) {
                $left[] = $array[$i];
            } else {
                $right[] = $array[$i];
            }
        }
    
        return array_merge(quickSort($left), [$pivot], quickSort($right));
    }
    
    // Example usage:
    $array = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
    $sortedArray = quickSort($array);
    
    echo "Original Array: " . implode(", ", $array) . "\n";
    echo "Sorted Array: " . implode(", ", $sortedArray) . "\n";
    
    

    Here's a simple implementation of the Quick Sort algorithm in PHP

  • CSV file handling in Python

    import csv
    
    # Writing to a CSV file
    with open('data.csv', 'w', newline='') as csvfile:
        fieldnames = ['name', 'age', 'city']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
    
        writer.writeheader()
        writer.writerow({'name': 'John', 'age': 30, 'city': 'New York'})
        writer.writerow({'name': 'Alice', 'age': 25, 'city': 'London'})
    
    # Reading from a CSV file
    with open('data.csv', newline='') as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row)

    Examples of code for writing to a csv file and reading from a csv file.