Explore snippets
Discover reusable code snippets, examples, fixes, and ideas shared by developers, students, and teams.
ATM class handling transaction
Models an ATM linked to a location that verifies a PIN and processes a withdrawal transaction through a central system.
using System;
namespace HF07
{
internal class ATM
{
private string location;
private Center center;
public ATM(string location, Center center)
{
this.location = location;
this.center = center;
Write binary data to a file
This snippet writes UTF-8 encoded text data with a null byte separator into a binary file using .NET file and text encoding classes.
$text = "CodShot binary rejection test" + [char]0 + "This should be rejected by the backend.";
[System.IO.File]::WriteAllBytes("codshot-import-test-binary.js", [System.Text.Encoding]::UTF8.GetBytes($text))
Modern JavaScript User Loader
Loads and manages users asynchronously from an API, providing methods to find users by ID and render the user list in the DOM.
let users = [];
let isLoading = false;
class User {
constructor(id, name, email) {
this.id = id;
this.name = name;
this.email = email;
}
getDisplayName() {
return `${this.name} (${this.email})`;
}
}
Fetch Active Users
Fetches users from an API and returns only those who are active using async/await and ES6+ syntax.
const fetchActiveUsers = async (url) => {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();
Simple Login Form
A basic HTML form for user login with username and password fields.
<form action="/login" method="post">
<label for="username">Username:</label>
<input type="text" id="username" name="username" required>
<br>
<label for="password">Password:</label>
<input type="password" id="password" name="password" required>
<br>
Print numbers from 1 to 5
This Java program uses a for loop to print numbers from 1 to 5 on the console.
public class SimpleLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
}
}
Bank transaction and balance handling
Manages transactions across multiple banks and retrieves account balances by card or account number.
using System;
using System.Collections.Generic;
namespace HF07
{
internal class Center
{
private List<Bank> bankok;
public Center(List<Bank> bankok)
{
this.bankok = bankok;
}
Simple React Component
A basic functional React component displaying a greeting message.
import React from 'react';
function Greeting() {
return <h1>Hello, welcome to CodShot!</h1>;
}
export default Greeting;
Simple React Footer
A basic React functional component for a website footer.
import React from 'react';
const Footer = () => {
return (
<footer style={{
textAlign: 'center',
padding: '1rem',
backgroundColor: '#f1f1f1',
position: 'fixed',
bottom: 0,
width: '100%'
}}>
Language Detection and Translation Loader
Manages front-end language detection, session and cookie handling, and loads language translation scopes from PHP files with fallback suppor...
<?php
declare(strict_types=1);
// ------------------------------------------------------------
// Global language code list
// ------------------------------------------------------------
if (!defined('ALLOWED_LANG_CODES')) {
Debounced Search Input Handler
Implements a debounced search input handler that delays API calls until the user stops typing for 500ms, reducing unnecessary requests.
function debounce(func, delay = 300) {
let timeout;
return function (...args) {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, delay);
};
}
Simple PHP Router with Dynamic User ID Route
This code implements a basic PHP router that directs static URLs to specific files and handles dynamic user ID routes, returning a 404 error...
<?php
$routes = [
'/' => 'home.php',
'/about' => 'about.php',
'/user' => 'user.php'
];
$requestUri = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
function handleRoute($uri, $routes)
{
if (array_key_exists($uri, $routes)) {
Load PHPMailer Library Once
This function loads the three essential PHPMailer files only once to prevent multiple inclusions during execution.
<?php
function mailer_require_phpmailer(): void
{
static $loaded = false;
if ($loaded) {
return;
}
$base = APP_PATH . '/libraries/PHPMailer/src';
require_once $base . '/Exception.php';
require_once $base . '/PHPMailer.php';
Counter generator in Python
This Python generator function yields numbers from 1 up to a given number, then prints them.
def count_up_to(n):
count = 1
while count <= n:
yield countdfrgdf
count += 1
## original
for num in count_up_to(5):
print(num)
Responsive Bootstrap Product Card
A modern responsive product card built with Bootstrap 5, featuring a hover animation and a call-to-action button.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Product Card</title>
<!-- Bootstrap -->