Code Block Showcase

A comprehensive showcase of code blocks with various programming languages and syntax highlighting

Code Block Showcase

This project demonstrates the beautiful and consistent code block rendering across all pages of the Peta website. It showcases the One Dark Pro theme with line numbers and syntax highlighting for multiple programming languages.

Features

  • Consistent Styling: All code blocks use the same One Dark Pro theme
  • Line Numbers: Every code block displays line numbers for better readability
  • Syntax Highlighting: Support for 17+ programming languages
  • Copy Functionality: One-click code copying with visual feedback
  • Responsive Design: Code blocks adapt to different screen sizes

Python Example

Here's a Python implementation of a binary search tree:

PYTHON

1
2    class TreeNode:
3        def __init__(self, val=0, left=None, right=None):
4            self.val = val
5            self.left = left
6            self.right = right
7    
8    class BinarySearchTree:
9        def __init__(self):
10            self.root = None
11        
12        def insert(self, val):
13            if not self.root:
14                self.root = TreeNode(val)
15                return
16            
17            current = self.root
18            while True:
19                if val < current.val:
20                    if current.left:
21                        current = current.left
22                    else:
23                        current.left = TreeNode(val)
24                        break
25                elif val > current.val:
26                    if current.right:
27                        current = current.right
28                    else:
29                        current.right = TreeNode(val)
30                        break
31                else:
32                    break  # Value already exists
33        
34        def search(self, val):
35            current = self.root
36            while current:
37                if val == current.val:
38                    return True
39                elif val < current.val:
40                    current = current.left
41                else:
42                    current = current.right
43            return False
44        
45        def inorder_traversal(self):
46            result = []
47            
48            def traverse(node):
49                if node:
50                    traverse(node.left)
51                    result.append(node.val)
52                    traverse(node.right)
53            
54            traverse(self.root)
55            return result
    

TypeScript Example

TypeScript interface for a user management system:

TYPESCRIPT

1
2    interface User {
3        id: number;
4        username: string;
5        email: string;
6        firstName: string;
7        lastName: string;
8        role: UserRole;
9        createdAt: Date;
10        lastLogin?: Date;
11        isActive: boolean;
12    }
13    
14    enum UserRole {
15        ADMIN = 'admin',
16        MODERATOR = 'moderator',
17        USER = 'user',
18        GUEST = 'guest'
19    }
20    
21    class UserService {
22        private users: Map<number, User> = new Map();
23        private nextId: number = 1;
24        
25        createUser(userData: Omit<User, 'id' | 'createdAt'>): User {
26            const user: User = {
27                id: this.nextId++,
28                ...userData,
29                createdAt: new Date()
30            };
31            
32            this.users.set(user.id, user);
33            return user;
34        }
35        
36        getUserById(id: number): User | undefined {
37            return this.users.get(id);
38        }
39        
40        updateUser(id: number, updates: Partial<User>): User | null {
41            const user = this.users.get(id);
42            if (!user) return null;
43            
44            const updatedUser = { ...user, ...updates };
45            this.users.set(id, updatedUser);
46            return updatedUser;
47        }
48        
49        deleteUser(id: number): boolean {
50            return this.users.delete(id);
51        }
52        
53        getAllUsers(): User[] {
54            return Array.from(this.users.values());
55        }
56    }
    

Rust Example

Rust implementation of a thread-safe counter using Arc and Mutex:

RUST

1
2    use std::sync::{Arc, Mutex};
3    use std::thread;
4    use std::time::Duration;
5    
6    struct Counter {
7        value: Mutex<i32>,
8    }
9    
10    impl Counter {
11        fn new() -> Self {
12            Counter {
13                value: Mutex::new(0),
14            }
15        }
16        
17        fn increment(&self) {
18            let mut num = self.value.lock().unwrap();
19            *num += 1;
20        }
21        
22        fn get(&self) -> i32 {
23            let num = self.value.lock().unwrap();
24            *num
25        }
26    }
27    
28    fn main() {
29        let counter = Arc::new(Counter::new());
30        let mut handles = vec![];
31        
32        // Spawn 10 threads that each increment the counter 1000 times
33        for _ in 0..10 {
34            let counter_clone = Arc::clone(&counter);
35            let handle = thread::spawn(move || {
36                for _ in 0..1000 {
37                    counter_clone.increment();
38                    thread::sleep(Duration::from_millis(1));
39                }
40            });
41            handles.push(handle);
42        }
43        
44        // Wait for all threads to complete
45        for handle in handles {
46            handle.join().unwrap();
47        }
48        
49        println!("Final counter value: {}", counter.get());
50    }
    

SQL Example

Complex SQL query for analytics dashboard:

SQL

1
2    WITH monthly_revenue AS (
3        SELECT 
4            DATE_TRUNC('month', order_date) AS month,
5            SUM(total_amount) AS revenue,
6            COUNT(*) AS order_count
7        FROM orders
8        WHERE order_date >= CURRENT_DATE - INTERVAL '12 months'
9        GROUP BY DATE_TRUNC('month', order_date)
10    ),
11    
12    customer_segments AS (
13        SELECT 
14            customer_id,
15            CASE 
16                WHEN total_spent > 1000 THEN 'High Value'
17                WHEN total_spent > 500 THEN 'Medium Value'
18                ELSE 'Low Value'
19            END AS segment
20        FROM (
21            SELECT 
22                customer_id,
23                SUM(total_amount) AS total_spent
24            FROM orders
25            GROUP BY customer_id
26        ) customer_totals
27    ),
28    
29    top_products AS (
30        SELECT 
31            product_id,
32            product_name,
33            SUM(quantity) AS total_sold,
34            SUM(total_amount) AS product_revenue
35        FROM order_items
36        GROUP BY product_id, product_name
37        ORDER BY product_revenue DESC
38        LIMIT 10
39    )
40    
41    SELECT 
42        mr.month,
43        mr.revenue,
44        mr.order_count,
45        COUNT(cs.customer_id) AS customer_count,
46        SUM(CASE WHEN cs.segment = 'High Value' THEN 1 ELSE 0 END) AS high_value_customers,
47        STRING_AGG(tp.product_name, ', ') AS top_products
48    FROM monthly_revenue mr
49    LEFT JOIN orders o ON DATE_TRUNC('month', o.order_date) = mr.month
50    LEFT JOIN customer_segments cs ON o.customer_id = cs.customer_id
51    LEFT JOIN top_products tp ON TRUE
52    GROUP BY mr.month, mr.revenue, mr.order_count
53    ORDER BY mr.month DESC;
    

Go Example

Go implementation of a concurrent web server with middleware:

GO

1
2    package main
3    
4    import (
5        "fmt"
6        "log"
7        "net/http"
8        "sync"
9        "time"
10    )
11    
12    type Middleware func(http.HandlerFunc) http.HandlerFunc
13    
14    func logging(next http.HandlerFunc) http.HandlerFunc {
15        return func(w http.ResponseWriter, r *http.Request) {
16            start := time.Now()
17            log.Printf("Started %s %s", r.Method, r.URL.Path)
18            
19            next.ServeHTTP(w, r)
20            
21            log.Printf("Completed %s %s in %v", r.Method, r.URL.Path, time.Since(start))
22        }
23    }
24    
25    func method(method string) Middleware {
26        return func(next http.HandlerFunc) http.HandlerFunc {
27            return func(w http.ResponseWriter, r *http.Request) {
28                if r.Method != method {
29                    http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
30                    return
31                }
32                next(w, r)
33            }
34        }
35    }
36    
37    func chain(f http.HandlerFunc, middlewares ...Middleware) http.HandlerFunc {
38        for _, m := range middlewares {
39            f = m(f)
40        }
41        return f
42    }
43    
44    func home(w http.ResponseWriter, r *http.Request) {
45        fmt.Fprintf(w, "Welcome to the Go Web Server!")
46    }
47    
48    func health(w http.ResponseWriter, r *http.Request) {
49        w.WriteHeader(http.StatusOK)
50        fmt.Fprintf(w, `{"status": "healthy", "timestamp": "%s"}`, time.Now().Format(time.RFC3339))
51    }
52    
53    type Server struct {
54        server *http.Server
55        wg     sync.WaitGroup
56    }
57    
58    func NewServer() *Server {
59        mux := http.NewServeMux()
60        
61        // Register handlers with middleware
62        mux.HandleFunc("/", chain(home, logging))
63        mux.HandleFunc("/health", chain(health, logging, method("GET")))
64        
65        return &Server{
66            server: &http.Server{
67                Addr:    ":8080",
68                Handler: mux,
69            },
70        }
71    }
72    
73    func (s *Server) Start() error {
74        s.wg.Add(1)
75        go func() {
76            defer s.wg.Done()
77            log.Println("Server starting on :8080")
78            if err := s.server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
79                log.Printf("Server error: %v", err)
80            }
81        }()
82        return nil
83    }
84    
85    func (s *Server) Stop() error {
86        ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
87        defer cancel()
88        
89        log.Println("Server shutting down...")
90        if err := s.server.Shutdown(ctx); err != nil {
91            return err
92        }
93        
94        s.wg.Wait()
95        return nil
96    }
    

C++ Example

C++ implementation of a template-based smart pointer:

CPP

1
2    #include <iostream>
3    #include <memory>
4    #include <stdexcept>
5    
6    template <typename T>
7    class SmartPointer {
8    private:
9        T* ptr;
10        size_t* refCount;
11    
12    public:
13        // Constructor
14        explicit SmartPointer(T* p = nullptr) : ptr(p), refCount(new size_t(1)) {}
15        
16        // Copy constructor
17        SmartPointer(const SmartPointer& other) : ptr(other.ptr), refCount(other.refCount) {
18            (*refCount)++;
19        }
20        
21        // Destructor
22        ~SmartPointer() {
23            (*refCount)--;
24            if (*refCount == 0) {
25                delete ptr;
26                delete refCount;
27            }
28        }
29        
30        // Assignment operator
31        SmartPointer& operator=(const SmartPointer& other) {
32            if (this != &other) {
33                (*refCount)--;
34                if (*refCount == 0) {
35                    delete ptr;
36                    delete refCount;
37                }
38                
39                ptr = other.ptr;
40                refCount = other.refCount;
41                (*refCount)++;
42            }
43            return *this;
44        }
45        
46        // Dereference operators
47        T& operator*() const {
48            if (!ptr) {
49                throw std::runtime_error("Dereferencing null pointer");
50            }
51            return *ptr;
52        }
53        
54        T* operator->() const {
55            return ptr;
56        }
57        
58        // Get raw pointer
59        T* get() const {
60            return ptr;
61        }
62        
63        // Check if pointer is null
64        explicit operator bool() const {
65            return ptr != nullptr;
66        }
67        
68        // Reset pointer
69        void reset(T* p = nullptr) {
70            (*refCount)--;
71            if (*refCount == 0) {
72                delete ptr;
73                delete refCount;
74            }
75            
76            ptr = p;
77            refCount = new size_t(1);
78        }
79        
80        // Get reference count
81        size_t use_count() const {
82            return *refCount;
83        }
84    };
85    
86    // Usage example
87    int main() {
88        SmartPointer<int> sp1(new int(42));
89        SmartPointer<int> sp2 = sp1;
90        
91        std::cout << "Value: " << *sp1 << std::endl;
92        std::cout << "Ref count: " << sp1.use_count() << std::endl;
93        
94        {
95            SmartPointer<int> sp3 = sp1;
96            std::cout << "Ref count after sp3: " << sp1.use_count() << std::endl;
97        }
98        
99        std::cout << "Ref count after sp3 scope: " << sp1.use_count() << std::endl;
100        
101        return 0;
102    }
    

Conclusion

This showcase demonstrates that the Peta website now provides:

  1. Beautiful Code Blocks: Consistent One Dark Pro theme across all pages
  2. Line Numbers: Every code block displays line numbers for easy reference
  3. Syntax Highlighting: Proper highlighting for all major programming languages
  4. Responsive Design: Code blocks work perfectly on all screen sizes
  5. Accessibility: Copy buttons and proper contrast for readability

The code blocks are now fully functional and consistent across articles, books, snippets, and projects pages! 🎉