Share & Discover Useful Code Examples

Explore a collection of personal and community-submitted code snippets and examples for various languages and frameworks. It will helps to enhance works and save times. Submit your own snippets and help others to learn and build faster.

package main

import "fmt"

// Define Reverse as a top-level function
func Reverse(s string) string {
	runes := []rune(s)
	for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 {
		runes[i], runes[j] = runes[j], runes[i]
	}
	return string(runes)
}

func main() {
	// Call the Reverse function from main
	fmt.Println(Reverse("Mahbub"))
}

Reverse a string in Go.

This function takes a string and returns...
<?php

// your code goes here
function generatePassword($length = 12) {
    return bin2hex(random_bytes($length / 2));
}

 const password = generatePassword();

Generate a secure random password in php

This function generates a cryptographica...
def flatten(lst):
    result = []
    for i in lst:
        if isinstance(i, list):
            result.extend(flatten(i))
        else:
            result.append(i)
    return result

Flatten a list of arbitrarily nested lists into a flat list in python

This recursive function takes a list wit...
import { useRouter } from 'next/router';

const Component = () => {
  const router = useRouter();
  console.log(router.pathname);
  return <div>{router.pathname}</div>;
};

Get Current Route Path in Nextjs

Get the current route path in a Next.js ...
.Toastify__toast-container {
  z-index: 200000;
}

React Toast shows behind modal Issue

Add this css code to your global css fil...
<?php

function capitalizeFirstLetter($string) {
    return ucfirst(strtolower($string));
}

echo capitalizeFirstLetter("mahbub");  // Mahbub

Capitalize First Letter in PHP

Change the passed parameter "mahbub" wit...
function getRandomColor() {
    return '#' + Math.floor(Math.random() * 16777215).toString(16);
}

Generate Random Hex Color JS

Create a random color in hex format with...
from datetime import datetime, date

default_format_to = "%Y-%m-%d" #ayou can change it to any format "%d-%m-%Y", "%m-%d-%Y"

def format_date(input_date, format_to = default_format_to):
    if isinstance(input_date, datetime):
        dt = input_date
    elif isinstance(input_date, date):
        dt = datetime.combine(input_date, datetime.min.time())
    elif isinstance(input_date, str):
        # Try multiple common date string formats
        for fmt in ("%Y-%m-%d", "%d-%m-%Y", "%m-%d-%Y", "%d/%m/%Y", "%m/%d/%Y"):
            try:
                dt = datetime.strptime(input_date, fmt)
                break
            except ValueError:
                continue
        else:
            raise ValueError(f"Unsupported date format: {input_date}")
    else:
        raise TypeError(f"Unsupported type: {type(input_date)}")
    
    return dt.strftime(format_to)


print(format_date("05-04-2022", default_format_to))         # 2022-04-05
print(format_date("2022-04-05"))                            # 2022-04-05
print(format_date(date(2022, 9, 19), default_format_to))    # 2022-09-19
print(format_date(datetime(2021, 4, 5)))                    # 2022-04-05

Format Date as YYYY-MM-DD in Python

Format a date object into any format def...
const [isOn, setIsOn] = useState(false);

const toggle = () => setIsOn(prev => !prev);

Toggle Boolean State in Reactjs or Nextjs

Simple toggle hook for React state....
// Function to sanitize a slug for URLs
export const sanitizeSlug = (slug) => {
  if (!slug) return "";
  return slug
    ?.trim() // Trim whitespace from the beginning and end
    .toLowerCase() // Convert to lowercase
    .replace(/[^a-z0-9\s-]/g, "") // Remove special characters except spaces and hyphens
    .replace(/\s+/g, "-") // Replace spaces with hyphens
    .replace(/-+/g, "-"); // Replace multiple hyphens with a single hyphen
};

Slugify a String in Javascript

Convert a string into a clean URL-friend...