Files
snippet-pastebin/src/data/templates.json
T

238 lines
44 KiB
JSON
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
[
{
"id": "react-counter",
"title": "React Counter Component",
"description": "A simple counter with increment/decrement buttons and reset functionality",
"language": "TSX",
"category": "react",
"hasPreview": true,
"functionName": "Counter",
"code": "import { useState } from 'react'\nimport { Button } from '@/components/ui/button'\nimport { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'\nimport { Plus, Minus, ArrowCounterClockwise } from '@phosphor-icons/react'\n\nfunction Counter() {\n const [count, setCount] = useState(0)\n\n return (\n <Card className=\"w-full max-w-sm\">\n <CardHeader>\n <CardTitle className=\"text-center\">Counter</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"text-6xl font-bold text-center text-primary\">\n {count}\n </div>\n <div className=\"flex gap-2 justify-center\">\n <Button\n onClick={() => setCount((prev) => prev - 1)}\n variant=\"outline\"\n size=\"lg\"\n className=\"gap-2\"\n >\n <Minus weight=\"bold\" />\n Decrement\n </Button>\n <Button\n onClick={() => setCount((prev) => prev + 1)}\n size=\"lg\"\n className=\"gap-2\"\n >\n <Plus weight=\"bold\" />\n Increment\n </Button>\n </div>\n <Button\n onClick={() => setCount(0)}\n variant=\"ghost\"\n className=\"w-full gap-2\"\n >\n <ArrowCounterClockwise />\n Reset\n </Button>\n </CardContent>\n </Card>\n )\n}\n\nexport default Counter"
},
{
"id": "react-form",
"title": "React Form with Validation",
"description": "Contact form with email validation and submit handling",
"language": "TSX",
"category": "react",
"hasPreview": true,
"functionName": "ContactForm",
"code": "import { useState } from 'react'\nimport { Button } from '@/components/ui/button'\nimport { Input } from '@/components/ui/input'\nimport { Label } from '@/components/ui/label'\nimport { Textarea } from '@/components/ui/textarea'\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'\nimport { PaperPlaneRight } from '@phosphor-icons/react'\n\nfunction ContactForm() {\n const [formData, setFormData] = useState({\n name: '',\n email: '',\n message: ''\n })\n const [errors, setErrors] = useState<Record<string, string>>({})\n const [submitted, setSubmitted] = useState(false)\n\n const validateEmail = (email: string) => {\n return /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/.test(email)\n }\n\n const handleSubmit = (e: React.FormEvent) => {\n e.preventDefault()\n const newErrors: Record<string, string> = {}\n\n if (!formData.name.trim()) {\n newErrors.name = 'Name is required'\n }\n if (!formData.email.trim()) {\n newErrors.email = 'Email is required'\n } else if (!validateEmail(formData.email)) {\n newErrors.email = 'Invalid email format'\n }\n if (!formData.message.trim()) {\n newErrors.message = 'Message is required'\n }\n\n if (Object.keys(newErrors).length > 0) {\n setErrors(newErrors)\n return\n }\n\n setSubmitted(true)\n setErrors({})\n }\n\n const handleChange = (field: string, value: string) => {\n setFormData((prev) => ({ ...prev, [field]: value }))\n if (errors[field]) {\n setErrors((prev) => ({ ...prev, [field]: '' }))\n }\n }\n\n if (submitted) {\n return (\n <Card className=\"w-full max-w-md\">\n <CardContent className=\"pt-6 text-center space-y-4\">\n <div className=\"text-6xl\">✓</div>\n <div>\n <h3 className=\"text-xl font-semibold mb-2\">Message Sent!</h3>\n <p className=\"text-muted-foreground\">We'll get back to you soon.</p>\n </div>\n <Button onClick={() => {\n setSubmitted(false)\n setFormData({ name: '', email: '', message: '' })\n }}>Send Another</Button>\n </CardContent>\n </Card>\n )\n }\n\n return (\n <Card className=\"w-full max-w-md\">\n <CardHeader>\n <CardTitle>Contact Us</CardTitle>\n <CardDescription>Send us a message and we'll respond shortly</CardDescription>\n </CardHeader>\n <CardContent>\n <form onSubmit={handleSubmit} className=\"space-y-4\">\n <div className=\"space-y-2\">\n <Label htmlFor=\"name\">Name *</Label>\n <Input\n id=\"name\"\n value={formData.name}\n onChange={(e) => handleChange('name', e.target.value)}\n className={errors.name ? 'border-destructive' : ''}\n />\n {errors.name && (\n <p className=\"text-sm text-destructive\">{errors.name}</p>\n )}\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"email\">Email *</Label>\n <Input\n id=\"email\"\n type=\"email\"\n value={formData.email}\n onChange={(e) => handleChange('email', e.target.value)}\n className={errors.email ? 'border-destructive' : ''}\n />\n {errors.email && (\n <p className=\"text-sm text-destructive\">{errors.email}</p>\n )}\n </div>\n <div className=\"space-y-2\">\n <Label htmlFor=\"message\">Message *</Label>\n <Textarea\n id=\"message\"\n value={formData.message}\n onChange={(e) => handleChange('message', e.target.value)}\n rows={4}\n className={errors.message ? 'border-destructive' : ''}\n />\n {errors.message && (\n <p className=\"text-sm text-destructive\">{errors.message}</p>\n )}\n </div>\n <Button type=\"submit\" className=\"w-full gap-2\">\n <PaperPlaneRight weight=\"bold\" />\n Send Message\n </Button>\n </form>\n </CardContent>\n </Card>\n )\n}\n\nexport default ContactForm"
},
{
"id": "react-todo",
"title": "React Todo List",
"description": "Interactive todo list with add, complete, and delete functionality",
"language": "TSX",
"category": "react",
"hasPreview": true,
"functionName": "TodoList",
"code": "import { useState } from 'react'\nimport { Button } from '@/components/ui/button'\nimport { Input } from '@/components/ui/input'\nimport { Checkbox } from '@/components/ui/checkbox'\nimport { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'\nimport { Plus, Trash } from '@phosphor-icons/react'\n\ninterface Todo {\n id: number\n text: string\n completed: boolean\n}\n\nfunction TodoList() {\n const [todos, setTodos] = useState<Todo[]>([])\n const [inputValue, setInputValue] = useState('')\n\n const addTodo = () => {\n if (inputValue.trim()) {\n setTodos((prev) => [\n ...prev,\n { id: Date.now(), text: inputValue.trim(), completed: false }\n ])\n setInputValue('')\n }\n }\n\n const toggleTodo = (id: number) => {\n setTodos((prev) =>\n prev.map((todo) =>\n todo.id === id ? { ...todo, completed: !todo.completed } : todo\n )\n )\n }\n\n const deleteTodo = (id: number) => {\n setTodos((prev) => prev.filter((todo) => todo.id !== id))\n }\n\n return (\n <Card className=\"w-full max-w-md\">\n <CardHeader>\n <CardTitle>Todo List</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"flex gap-2\">\n <Input\n placeholder=\"Add a new todo...\"\n value={inputValue}\n onChange={(e) => setInputValue(e.target.value)}\n onKeyPress={(e) => e.key === 'Enter' && addTodo()}\n />\n <Button onClick={addTodo} size=\"icon\">\n <Plus weight=\"bold\" />\n </Button>\n </div>\n {todos.length === 0 ? (\n <p className=\"text-center text-muted-foreground py-8\">\n No todos yet. Add one above!\n </p>\n ) : (\n <div className=\"space-y-2\">\n {todos.map((todo) => (\n <div\n key={todo.id}\n className=\"flex items-center gap-3 p-3 rounded-lg border bg-card hover:bg-accent/50 transition-colors\"\n >\n <Checkbox\n checked={todo.completed}\n onCheckedChange={() => toggleTodo(todo.id)}\n />\n <span\n className={`flex-1 ${todo.completed ? 'line-through text-muted-foreground' : ''}`}\n >\n {todo.text}\n </span>\n <Button\n variant=\"ghost\"\n size=\"sm\"\n onClick={() => deleteTodo(todo.id)}\n className=\"text-destructive hover:text-destructive\"\n >\n <Trash />\n </Button>\n </div>\n ))}\n </div>\n )}\n {todos.length > 0 && (\n <div className=\"text-sm text-muted-foreground text-center pt-2\">\n {todos.filter((t) => !t.completed).length} of {todos.length} remaining\n </div>\n )}\n </CardContent>\n </Card>\n )\n}\n\nexport default TodoList"
},
{
"id": "react-tabs",
"title": "React Tabs Component",
"description": "Tabbed interface showing different content panels",
"language": "TSX",
"category": "react",
"hasPreview": true,
"functionName": "TabsDemo",
"code": "import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs'\nimport { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'\nimport { User, Gear, Bell } from '@phosphor-icons/react'\n\nfunction TabsDemo() {\n return (\n <div className=\"w-full max-w-2xl\">\n <Tabs defaultValue=\"account\" className=\"w-full\">\n <TabsList className=\"grid w-full grid-cols-3\">\n <TabsTrigger value=\"account\" className=\"gap-2\">\n <User weight=\"bold\" />\n Account\n </TabsTrigger>\n <TabsTrigger value=\"settings\" className=\"gap-2\">\n <Gear weight=\"bold\" />\n Settings\n </TabsTrigger>\n <TabsTrigger value=\"notifications\" className=\"gap-2\">\n <Bell weight=\"bold\" />\n Notifications\n </TabsTrigger>\n </TabsList>\n <TabsContent value=\"account\">\n <Card>\n <CardHeader>\n <CardTitle>Account Information</CardTitle>\n <CardDescription>\n View and manage your account details\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-2\">\n <div className=\"space-y-1\">\n <h4 className=\"text-sm font-medium\">Username</h4>\n <p className=\"text-sm text-muted-foreground\">john.doe@example.com</p>\n </div>\n <div className=\"space-y-1\">\n <h4 className=\"text-sm font-medium\">Member Since</h4>\n <p className=\"text-sm text-muted-foreground\">January 2024</p>\n </div>\n </CardContent>\n </Card>\n </TabsContent>\n <TabsContent value=\"settings\">\n <Card>\n <CardHeader>\n <CardTitle>Settings</CardTitle>\n <CardDescription>\n Configure your preferences and options\n </CardDescription>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"flex items-center justify-between\">\n <div>\n <h4 className=\"text-sm font-medium\">Email Notifications</h4>\n <p className=\"text-sm text-muted-foreground\">Receive email updates</p>\n </div>\n <input type=\"checkbox\" defaultChecked />\n </div>\n <div className=\"flex items-center justify-between\">\n <div>\n <h4 className=\"text-sm font-medium\">Two-Factor Auth</h4>\n <p className=\"text-sm text-muted-foreground\">Extra security layer</p>\n </div>\n <input type=\"checkbox\" />\n </div>\n </CardContent>\n </Card>\n </TabsContent>\n <TabsContent value=\"notifications\">\n <Card>\n <CardHeader>\n <CardTitle>Notifications</CardTitle>\n <CardDescription>\n Your recent notifications and alerts\n </CardDescription>\n </CardHeader>\n <CardContent>\n <div className=\"space-y-4\">\n <div className=\"flex items-start gap-3 p-3 rounded-lg bg-muted/50\">\n <Bell className=\"text-primary mt-1\" weight=\"fill\" />\n <div>\n <p className=\"text-sm font-medium\">Welcome!</p>\n <p className=\"text-sm text-muted-foreground\">\n Thanks for joining our platform\n </p>\n <p className=\"text-xs text-muted-foreground mt-1\">2 hours ago</p>\n </div>\n </div>\n </div>\n </CardContent>\n </Card>\n </TabsContent>\n </Tabs>\n </div>\n )\n}\n\nexport default TabsDemo"
},
{
"id": "react-accordion",
"title": "React Accordion Component",
"description": "Collapsible FAQ accordion with smooth animations",
"language": "TSX",
"category": "react",
"hasPreview": true,
"functionName": "FAQAccordion",
"code": "import {\n Accordion,\n AccordionContent,\n AccordionItem,\n AccordionTrigger,\n} from '@/components/ui/accordion'\nimport { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'\n\nfunction FAQAccordion() {\n return (\n <Card className=\"w-full max-w-2xl\">\n <CardHeader>\n <CardTitle>Frequently Asked Questions</CardTitle>\n </CardHeader>\n <CardContent>\n <Accordion type=\"single\" collapsible className=\"w-full\">\n <AccordionItem value=\"item-1\">\n <AccordionTrigger>What is React?</AccordionTrigger>\n <AccordionContent>\n React is a JavaScript library for building user interfaces,\n particularly single-page applications. It allows developers to\n create reusable UI components and manage the state of their\n applications efficiently.\n </AccordionContent>\n </AccordionItem>\n <AccordionItem value=\"item-2\">\n <AccordionTrigger>How do I get started?</AccordionTrigger>\n <AccordionContent>\n Getting started is easy! You can begin by installing Node.js,\n then use Create React App or Vite to scaffold a new project.\n Follow the official React documentation for step-by-step\n tutorials and guides.\n </AccordionContent>\n </AccordionItem>\n <AccordionItem value=\"item-3\">\n <AccordionTrigger>Is it accessible?</AccordionTrigger>\n <AccordionContent>\n Yes, when built correctly, React applications can be fully\n accessible. It's important to use semantic HTML, ARIA attributes,\n and test your application with screen readers and keyboard\n navigation.\n </AccordionContent>\n </AccordionItem>\n <AccordionItem value=\"item-4\">\n <AccordionTrigger>Can I use it with TypeScript?</AccordionTrigger>\n <AccordionContent>\n Absolutely! React has excellent TypeScript support. TypeScript\n adds static typing to JavaScript, which helps catch errors early\n and improves code quality. Many modern React projects use\n TypeScript as the default.\n </AccordionContent>\n </AccordionItem>\n </Accordion>\n </CardContent>\n </Card>\n )\n}\n\nexport default FAQAccordion"
},
{
"id": "react-modal",
"title": "React Modal Dialog",
"description": "Interactive modal with open/close animations",
"language": "TSX",
"category": "react",
"hasPreview": true,
"functionName": "ModalDemo",
"code": "import { useState } from 'react'\nimport { Button } from '@/components/ui/button'\nimport {\n Dialog,\n DialogContent,\n DialogDescription,\n DialogFooter,\n DialogHeader,\n DialogTitle,\n DialogTrigger,\n} from '@/components/ui/dialog'\nimport { Input } from '@/components/ui/input'\nimport { Label } from '@/components/ui/label'\nimport { Card, CardContent } from '@/components/ui/card'\n\nfunction ModalDemo() {\n const [name, setName] = useState('')\n const [savedName, setSavedName] = useState('')\n\n const handleSave = () => {\n setSavedName(name)\n setName('')\n }\n\n return (\n <Card className=\"w-full max-w-md\">\n <CardContent className=\"pt-6 space-y-4\">\n <div className=\"text-center space-y-2\">\n <h3 className=\"text-xl font-semibold\">Modal Dialog Demo</h3>\n <p className=\"text-muted-foreground\">\n Click the button below to open a modal\n </p>\n </div>\n {savedName && (\n <div className=\"p-4 rounded-lg bg-primary/10 border border-primary/20\">\n <p className=\"text-sm font-medium\">Saved Name:</p>\n <p className=\"text-lg font-bold text-primary\">{savedName}</p>\n </div>\n )}\n <Dialog>\n <DialogTrigger asChild>\n <Button className=\"w-full\">Open Dialog</Button>\n </DialogTrigger>\n <DialogContent className=\"sm:max-w-[425px]\">\n <DialogHeader>\n <DialogTitle>Edit Profile</DialogTitle>\n <DialogDescription>\n Make changes to your profile here. Click save when you're done.\n </DialogDescription>\n </DialogHeader>\n <div className=\"grid gap-4 py-4\">\n <div className=\"grid grid-cols-4 items-center gap-4\">\n <Label htmlFor=\"name\" className=\"text-right\">\n Name\n </Label>\n <Input\n id=\"name\"\n value={name}\n onChange={(e) => setName(e.target.value)}\n className=\"col-span-3\"\n placeholder=\"Enter your name\"\n />\n </div>\n </div>\n <DialogFooter>\n <Button type=\"submit\" onClick={handleSave}>\n Save changes\n </Button>\n </DialogFooter>\n </DialogContent>\n </Dialog>\n </CardContent>\n </Card>\n )\n}\n\nexport default ModalDemo"
},
{
"id": "react-search",
"title": "React Search Filter",
"description": "Real-time search and filter through a list of items",
"language": "TSX",
"category": "react",
"hasPreview": true,
"functionName": "SearchFilter",
"code": "import { useState, useMemo } from 'react'\nimport { Input } from '@/components/ui/input'\nimport { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'\nimport { Badge } from '@/components/ui/badge'\nimport { MagnifyingGlass } from '@phosphor-icons/react'\n\nconst ITEMS = [\n { id: 1, name: 'React', category: 'Frontend', color: 'blue' },\n { id: 2, name: 'Node.js', category: 'Backend', color: 'green' },\n { id: 3, name: 'TypeScript', category: 'Language', color: 'blue' },\n { id: 4, name: 'PostgreSQL', category: 'Database', color: 'blue' },\n { id: 5, name: 'MongoDB', category: 'Database', color: 'green' },\n { id: 6, name: 'Express', category: 'Backend', color: 'gray' },\n { id: 7, name: 'Vue', category: 'Frontend', color: 'green' },\n { id: 8, name: 'Python', category: 'Language', color: 'yellow' },\n { id: 9, name: 'Django', category: 'Backend', color: 'green' },\n { id: 10, name: 'Angular', category: 'Frontend', color: 'red' },\n]\n\nfunction SearchFilter() {\n const [searchQuery, setSearchQuery] = useState('')\n\n const filteredItems = useMemo(() => {\n if (!searchQuery.trim()) return ITEMS\n const query = searchQuery.toLowerCase()\n return ITEMS.filter(\n (item) =>\n item.name.toLowerCase().includes(query) ||\n item.category.toLowerCase().includes(query)\n )\n }, [searchQuery])\n\n return (\n <Card className=\"w-full max-w-2xl\">\n <CardHeader>\n <CardTitle>Search Technologies</CardTitle>\n </CardHeader>\n <CardContent className=\"space-y-4\">\n <div className=\"relative\">\n <MagnifyingGlass className=\"absolute left-3 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground\" />\n <Input\n placeholder=\"Search by name or category...\"\n value={searchQuery}\n onChange={(e) => setSearchQuery(e.target.value)}\n className=\"pl-10\"\n />\n </div>\n <div className=\"text-sm text-muted-foreground\">\n Showing {filteredItems.length} of {ITEMS.length} items\n </div>\n {filteredItems.length === 0 ? (\n <div className=\"text-center py-12 text-muted-foreground\">\n No items found\n </div>\n ) : (\n <div className=\"grid grid-cols-1 md:grid-cols-2 gap-3\">\n {filteredItems.map((item) => (\n <div\n key={item.id}\n className=\"flex items-center justify-between p-4 rounded-lg border bg-card hover:bg-accent/50 transition-colors\"\n >\n <div>\n <h4 className=\"font-semibold\">{item.name}</h4>\n <p className=\"text-sm text-muted-foreground\">\n {item.category}\n </p>\n </div>\n <Badge variant=\"secondary\">{item.category}</Badge>\n </div>\n ))}\n </div>\n )}\n </CardContent>\n </Card>\n )\n}\n\nexport default SearchFilter"
},
{
"id": "fetch-api",
"title": "Fetch API Example",
"description": "Making HTTP requests with async/await and error handling",
"language": "JavaScript",
"category": "api",
"code": "async function fetchUserData(userId) {\n try {\n const response = await fetch(\n `https://jsonplaceholder.typicode.com/users/${userId}`\n )\n \n if (!response.ok) {\n throw new Error(`HTTP error! status: ${response.status}`)\n }\n \n const data = await response.json()\n console.log('User data:', data)\n return data\n } catch (error) {\n console.error('Failed to fetch user:', error)\n throw error\n }\n}\n\nfetchUserData(1)"
},
{
"id": "array-methods",
"title": "JavaScript Array Methods",
"description": "Common array operations: map, filter, reduce, and find",
"language": "JavaScript",
"category": "basics",
"code": "const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nconst doubled = numbers.map(n => n * 2)\nconsole.log('Doubled:', doubled)\n\nconst evens = numbers.filter(n => n % 2 === 0)\nconsole.log('Evens:', evens)\n\nconst sum = numbers.reduce((acc, n) => acc + n, 0)\nconsole.log('Sum:', sum)\n\nconst firstBigNumber = numbers.find(n => n > 5)\nconsole.log('First > 5:', firstBigNumber)\n\nconst squared = numbers.map(n => n ** 2)\nconsole.log('Squared:', squared)"
},
{
"id": "promise-chain",
"title": "Promise Chaining",
"description": "Handling async operations with promise chains",
"language": "JavaScript",
"category": "async",
"code": "function delay(ms) {\n return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nfunction fetchUser(id) {\n return delay(1000).then(() => ({\n id,\n name: 'John Doe',\n email: 'john@example.com'\n }))\n}\n\nfunction fetchPosts(userId) {\n return delay(800).then(() => ([\n { id: 1, title: 'Post 1', userId },\n { id: 2, title: 'Post 2', userId }\n ]))\n}\n\nfetchUser(1)\n .then(user => {\n console.log('User:', user)\n return fetchPosts(user.id)\n })\n .then(posts => {\n console.log('Posts:', posts)\n })\n .catch(error => {\n console.error('Error:', error)\n })"
},
{
"id": "typescript-interface",
"title": "TypeScript Interface",
"description": "Defining typed interfaces and using them in functions",
"language": "TypeScript",
"category": "types",
"code": "interface User {\n id: number\n name: string\n email: string\n role: 'admin' | 'user' | 'guest'\n metadata?: {\n createdAt: Date\n lastLogin: Date\n }\n}\n\ninterface ApiResponse<T> {\n data: T\n status: number\n message: string\n}\n\nfunction getUser(id: number): ApiResponse<User> {\n return {\n data: {\n id,\n name: 'John Doe',\n email: 'john@example.com',\n role: 'admin',\n metadata: {\n createdAt: new Date(),\n lastLogin: new Date()\n }\n },\n status: 200,\n message: 'Success'\n }\n}\n\nconst response = getUser(1)\nconsole.log(response.data.name)"
},
{
"id": "css-flexbox",
"title": "CSS Flexbox Layout",
"description": "Responsive flexbox layout with common patterns",
"language": "CSS",
"category": "layout",
"code": ".container {\n display: flex;\n flex-direction: row;\n justify-content: space-between;\n align-items: center;\n gap: 1rem;\n padding: 2rem;\n}\n\n.card {\n flex: 1;\n min-width: 300px;\n padding: 1.5rem;\n border-radius: 0.5rem;\n background: white;\n box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);\n}\n\n@media (max-width: 768px) {\n .container {\n flex-direction: column;\n }\n \n .card {\n width: 100%;\n }\n}"
},
{
"id": "css-grid",
"title": "CSS Grid Layout",
"description": "Modern grid layout with responsive columns",
"language": "CSS",
"category": "layout",
"code": ".grid-container {\n display: grid;\n grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));\n gap: 2rem;\n padding: 2rem;\n}\n\n.grid-item {\n padding: 1.5rem;\n border-radius: 0.5rem;\n background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);\n color: white;\n}\n\n.featured {\n grid-column: span 2;\n}\n\n@media (max-width: 768px) {\n .featured {\n grid-column: span 1;\n }\n}"
},
{
"id": "python-euler-1",
"title": "Project Euler #1: Multiples of 3 or 5",
"description": "Find the sum of all multiples of 3 or 5 below 1000",
"language": "Python",
"category": "euler",
"hasPreview": true,
"code": "# Project Euler Problem 1\n# Find the sum of all multiples of 3 or 5 below 1000\n\ndef solve_euler_1(limit=1000):\n total = 0\n for i in range(limit):\n if i % 3 == 0 or i % 5 == 0:\n total += i\n return total\n\nresult = solve_euler_1(1000)\nprint(f\"The sum of all multiples of 3 or 5 below 1000 is: {result}\")\n\n# More efficient solution using arithmetic series\ndef solve_euler_1_optimized(limit=1000):\n def sum_divisible_by(n):\n p = (limit - 1) // n\n return n * p * (p + 1) // 2\n \n return sum_divisible_by(3) + sum_divisible_by(5) - sum_divisible_by(15)\n\nresult_optimized = solve_euler_1_optimized(1000)\nprint(f\"Optimized solution: {result_optimized}\")"
},
{
"id": "python-euler-2",
"title": "Project Euler #2: Even Fibonacci Numbers",
"description": "Find the sum of even-valued Fibonacci numbers not exceeding 4 million",
"language": "Python",
"category": "euler",
"hasPreview": true,
"code": "# Project Euler Problem 2\n# Find the sum of even-valued Fibonacci numbers not exceeding 4 million\n\ndef solve_euler_2(limit=4_000_000):\n a, b = 1, 2\n total = 0\n \n while a <= limit:\n if a % 2 == 0:\n total += a\n a, b = b, a + b\n \n return total\n\nresult = solve_euler_2(4_000_000)\nprint(f\"The sum of even Fibonacci numbers not exceeding 4 million is: {result}\")\n\n# Show the first few even Fibonacci numbers\nprint(\"\\nFirst 10 even Fibonacci numbers:\")\na, b = 1, 2\ncount = 0\nwhile count < 10:\n if a % 2 == 0:\n print(f\" {count + 1}. {a}\")\n count += 1\n a, b = b, a + b"
},
{
"id": "python-euler-6",
"title": "Project Euler #6: Sum Square Difference",
"description": "Find the difference between sum of squares and square of sum",
"language": "Python",
"category": "euler",
"hasPreview": true,
"code": "# Project Euler Problem 6\n# Find the difference between the sum of the squares of the first 100 natural numbers\n# and the square of the sum\n\ndef solve_euler_6(n=100):\n # Sum of squares: 1^2 + 2^2 + ... + n^2\n sum_of_squares = sum(i**2 for i in range(1, n + 1))\n \n # Square of sum: (1 + 2 + ... + n)^2\n square_of_sum = sum(range(1, n + 1)) ** 2\n \n difference = square_of_sum - sum_of_squares\n \n return sum_of_squares, square_of_sum, difference\n\nsum_sq, sq_sum, diff = solve_euler_6(100)\nprint(f\"Sum of squares (1² + 2² + ... + 100²) = {sum_sq}\")\nprint(f\"Square of sum (1 + 2 + ... + 100)² = {sq_sum}\")\nprint(f\"Difference = {diff}\")\n\n# Using mathematical formulas for efficiency\ndef solve_euler_6_optimized(n=100):\n # Formula: sum of squares = n(n+1)(2n+1)/6\n sum_of_squares = n * (n + 1) * (2 * n + 1) // 6\n \n # Formula: sum = n(n+1)/2, so square of sum = [n(n+1)/2]^2\n square_of_sum = (n * (n + 1) // 2) ** 2\n \n return square_of_sum - sum_of_squares\n\nprint(f\"\\nOptimized solution: {solve_euler_6_optimized(100)}\")"
},
{
"id": "python-fibonacci",
"title": "Fibonacci Sequence Generator",
"description": "Generate Fibonacci numbers using different approaches",
"language": "Python",
"category": "algorithms",
"hasPreview": true,
"code": "# Generate Fibonacci sequence using different methods\n\n# Method 1: Iterative\ndef fibonacci_iterative(n):\n if n <= 0:\n return []\n elif n == 1:\n return [0]\n \n fib = [0, 1]\n for i in range(2, n):\n fib.append(fib[i-1] + fib[i-2])\n return fib\n\nprint(\"First 15 Fibonacci numbers (iterative):\")\nprint(fibonacci_iterative(15))\n\n# Method 2: Generator (memory efficient)\ndef fibonacci_generator(n):\n a, b = 0, 1\n count = 0\n while count < n:\n yield a\n a, b = b, a + b\n count += 1\n\nprint(\"\\nFirst 15 Fibonacci numbers (generator):\")\nprint(list(fibonacci_generator(15)))\n\n# Method 3: Recursive (with memoization)\ndef fibonacci_recursive(n, memo={}):\n if n in memo:\n return memo[n]\n if n <= 1:\n return n\n memo[n] = fibonacci_recursive(n-1, memo) + fibonacci_recursive(n-2, memo)\n return memo[n]\n\nprint(\"\\n20th Fibonacci number (recursive with memoization):\")\nprint(fibonacci_recursive(20))"
},
{
"id": "python-prime-numbers",
"title": "Prime Number Generator",
"description": "Find prime numbers using the Sieve of Eratosthenes",
"language": "Python",
"category": "algorithms",
"hasPreview": true,
"code": "# Prime number algorithms\n\n# Method 1: Simple prime checker\ndef is_prime(n):\n if n < 2:\n return False\n if n == 2:\n return True\n if n % 2 == 0:\n return False\n \n # Check odd divisors up to sqrt(n)\n i = 3\n while i * i <= n:\n if n % i == 0:\n return False\n i += 2\n return True\n\nprint(\"Prime numbers up to 50:\")\nprimes = [n for n in range(2, 51) if is_prime(n)]\nprint(primes)\n\n# Method 2: Sieve of Eratosthenes (efficient for finding many primes)\ndef sieve_of_eratosthenes(limit):\n if limit < 2:\n return []\n \n # Create a boolean array and initialize all as true\n is_prime = [True] * (limit + 1)\n is_prime[0] = is_prime[1] = False\n \n p = 2\n while p * p <= limit:\n if is_prime[p]:\n # Mark all multiples of p as not prime\n for i in range(p * p, limit + 1, p):\n is_prime[i] = False\n p += 1\n \n return [i for i in range(limit + 1) if is_prime[i]]\n\nprint(\"\\nFirst 25 primes using Sieve:\")\nall_primes = sieve_of_eratosthenes(100)\nprint(all_primes[:25])\nprint(f\"\\nTotal primes up to 100: {len(all_primes)}\")"
},
{
"id": "python-data-structures",
"title": "Python Data Structures Demo",
"description": "Working with lists, dictionaries, sets, and tuples",
"language": "Python",
"category": "basics",
"hasPreview": true,
"code": "# Python data structures examples\n\n# Lists (mutable, ordered)\nfruits = ['apple', 'banana', 'cherry', 'date']\nprint(\"Lists:\")\nprint(f\" Original: {fruits}\")\nfruits.append('elderberry')\nprint(f\" After append: {fruits}\")\nprint(f\" Second item: {fruits[1]}\")\n\n# Dictionaries (key-value pairs)\nperson = {\n 'name': 'Alice',\n 'age': 30,\n 'city': 'New York',\n 'hobbies': ['reading', 'coding', 'hiking']\n}\nprint(\"\\nDictionaries:\")\nprint(f\" Person: {person}\")\nprint(f\" Name: {person['name']}\")\nprint(f\" Hobbies: {', '.join(person['hobbies'])}\")\n\n# Sets (unique, unordered)\nnumbers = {1, 2, 3, 4, 5, 3, 2, 1}\nprint(\"\\nSets (duplicates removed):\")\nprint(f\" Numbers: {numbers}\")\nmore_numbers = {4, 5, 6, 7, 8}\nprint(f\" Union: {numbers | more_numbers}\")\nprint(f\" Intersection: {numbers & more_numbers}\")\n\n# Tuples (immutable, ordered)\ncoordinates = (10, 20)\nprint(\"\\nTuples:\")\nprint(f\" Coordinates: {coordinates}\")\nx, y = coordinates\nprint(f\" x={x}, y={y}\")\n\n# List comprehensions\nsquares = [x**2 for x in range(1, 11)]\nprint(f\"\\nList comprehension (squares): {squares}\")\nevens = [x for x in range(1, 21) if x % 2 == 0]\nprint(f\"Even numbers 1-20: {evens}\")"
},
{
"id": "python-file-operations",
"title": "Python File Operations",
"description": "Reading and writing files with error handling",
"language": "Python",
"category": "basics",
"hasPreview": true,
"code": "# Python file operations (simulated for web environment)\n\n# Note: In a real environment, these would work with actual files\n# Here we demonstrate the patterns\n\nprint(\"File Operations Patterns:\\n\")\n\n# Writing to a file\nprint(\"1. Writing to a file:\")\nfile_content = \"\"\"# Example of writing to a file\ntry:\n with open('example.txt', 'w') as f:\n f.write('Hello, World!\\\\n')\n f.write('This is a second line.\\\\n')\n print(' ✓ File written successfully')\nexcept IOError as e:\n print(f' ✗ Error writing file: {e}')\n\"\"\"\nprint(file_content)\n\n# Reading from a file\nprint(\"\\n2. Reading from a file:\")\nread_example = \"\"\"try:\n with open('example.txt', 'r') as f:\n content = f.read()\n print(content)\nexcept FileNotFoundError:\n print(' ✗ File not found')\nexcept IOError as e:\n print(f' ✗ Error reading file: {e}')\n\"\"\"\nprint(read_example)\n\n# Reading lines\nprint(\"\\n3. Reading line by line:\")\nlines_example = \"\"\"with open('example.txt', 'r') as f:\n for line_num, line in enumerate(f, 1):\n print(f' Line {line_num}: {line.strip()}')\n\"\"\"\nprint(lines_example)\n\n# Demonstrate string operations as alternative\nprint(\"\\n4. Working with text data:\")\ntext_data = \"Hello, World!\\nThis is a second line.\\nAnd a third!\"\nlines = text_data.split('\\n')\nprint(f\" Total lines: {len(lines)}\")\nfor i, line in enumerate(lines, 1):\n print(f\" Line {i}: {line}\")"
},
{
"id": "python-interactive-hello",
"title": "Interactive: Hello User",
"description": "Simple interactive program that greets the user by name",
"language": "Python",
"category": "interactive",
"hasPreview": true,
"code": "# Interactive program - asks for user's name and greets them\n\nprint(\"Welcome to the greeting program!\")\nprint()\n\nname = input(\"What is your name? \")\nprint(f\"\\nHello, {name}! Nice to meet you!\")\n\nage = input(\"How old are you? \")\nprint(f\"\\nWow, {age} years old! That's awesome!\")\n\ncolor = input(\"What's your favorite color? \")\nprint(f\"\\n{color} is a great choice! I love that color too.\")\n\nprint(f\"\\nThanks for chatting, {name}! Have a wonderful day!\")"
},
{
"id": "python-calculator-input",
"title": "Interactive: Simple Calculator",
"description": "Calculator that takes user input for operations",
"language": "Python",
"category": "interactive",
"hasPreview": true,
"code": "# Interactive calculator\n\nprint(\"=== Simple Calculator ===\")\nprint()\n\nnum1 = float(input(\"Enter first number: \"))\nnum2 = float(input(\"Enter second number: \"))\n\nprint(\"\\nAvailable operations:\")\nprint(\" + : Addition\")\nprint(\" - : Subtraction\")\nprint(\" * : Multiplication\")\nprint(\" / : Division\")\nprint()\n\noperation = input(\"Choose operation (+, -, *, /): \")\n\nif operation == '+':\n result = num1 + num2\n print(f\"\\n{num1} + {num2} = {result}\")\nelif operation == '-':\n result = num1 - num2\n print(f\"\\n{num1} - {num2} = {result}\")\nelif operation == '*':\n result = num1 * num2\n print(f\"\\n{num1} × {num2} = {result}\")\nelif operation == '/':\n if num2 != 0:\n result = num1 / num2\n print(f\"\\n{num1} ÷ {num2} = {result}\")\n else:\n print(\"\\nError: Cannot divide by zero!\")\nelse:\n print(\"\\nInvalid operation!\")"
},
{
"id": "python-guess-number",
"title": "Interactive: Number Guessing Game",
"description": "Classic number guessing game with user input",
"language": "Python",
"category": "interactive",
"hasPreview": true,
"code": "# Number guessing game\nimport random\n\nprint(\"=== Number Guessing Game ===\")\nprint(\"I'm thinking of a number between 1 and 100...\")\nprint()\n\ntarget = random.randint(1, 100)\nattempts = 0\nmax_attempts = 7\n\nwhile attempts < max_attempts:\n guess = int(input(f\"Attempt {attempts + 1}/{max_attempts} - Enter your guess: \"))\n attempts += 1\n \n if guess < target:\n print(\"Too low! Try a higher number.\\n\")\n elif guess > target:\n print(\"Too high! Try a lower number.\\n\")\n else:\n print(f\"\\n🎉 Congratulations! You guessed it in {attempts} attempts!\")\n break\nelse:\n print(f\"\\n😞 Game over! The number was {target}.\")\n print(f\"You used all {max_attempts} attempts.\")"
},
{
"id": "python-mad-libs",
"title": "Interactive: Mad Libs Story",
"description": "Fun interactive story generator using user input",
"language": "Python",
"category": "interactive",
"hasPreview": true,
"code": "# Mad Libs - Interactive story generator\n\nprint(\"=== Mad Libs Story Generator ===\")\nprint(\"Fill in the blanks to create a funny story!\")\nprint()\n\nnoun1 = input(\"Enter a noun (thing): \")\nadjective1 = input(\"Enter an adjective (describing word): \")\nverb1 = input(\"Enter a verb ending in -ing: \")\nnoun2 = input(\"Enter another noun: \")\nadjective2 = input(\"Enter another adjective: \")\nnoun3 = input(\"Enter a plural noun: \")\nverb2 = input(\"Enter a verb: \")\nnoun4 = input(\"Enter one more noun: \")\n\nprint(\"\\n\" + \"=\" * 50)\nprint(\"YOUR STORY:\")\nprint(\"=\" * 50)\nprint()\nprint(f\"Once upon a time, there was a {adjective1} {noun1}.\")\nprint(f\"It loved {verb1} in the park every morning.\")\nprint(f\"One day, it found a mysterious {noun2} on the ground.\")\nprint(f\"The {noun2} was so {adjective2} that it started to glow!\")\nprint(f\"Suddenly, hundreds of tiny {noun3} appeared and began to {verb2}.\")\nprint(f\"The {noun1} was amazed and took the {noun2} to the nearest {noun4}.\")\nprint(f\"And they all lived happily ever after!\")\nprint()\nprint(\"=\" * 50)\nprint(\"The End!\")"
},
{
"id": "python-todo-cli",
"title": "Interactive: Todo List CLI",
"description": "Command-line todo list with interactive menu",
"language": "Python",
"category": "interactive",
"hasPreview": true,
"code": "# Interactive CLI Todo List\n\ntodos = []\n\nprint(\"=== Todo List Manager ===\")\nprint()\n\nwhile True:\n print(\"\\nCurrent Todos:\")\n if not todos:\n print(\" (No todos yet)\")\n else:\n for i, todo in enumerate(todos, 1):\n print(f\" {i}. {todo}\")\n \n print(\"\\nOptions:\")\n print(\" 1. Add todo\")\n print(\" 2. Remove todo\")\n print(\" 3. Exit\")\n \n choice = input(\"\\nEnter choice (1-3): \")\n \n if choice == '1':\n todo = input(\"Enter new todo: \")\n if todo.strip():\n todos.append(todo)\n print(f\"✓ Added: {todo}\")\n else:\n print(\"✗ Todo cannot be empty\")\n \n elif choice == '2':\n if not todos:\n print(\"✗ No todos to remove\")\n else:\n try:\n num = int(input(f\"Enter todo number (1-{len(todos)}): \"))\n if 1 <= num <= len(todos):\n removed = todos.pop(num - 1)\n print(f\"✓ Removed: {removed}\")\n else:\n print(\"✗ Invalid number\")\n except ValueError:\n print(\"✗ Please enter a valid number\")\n \n elif choice == '3':\n print(\"\\nGoodbye! Final todo count:\", len(todos))\n break\n \n else:\n print(\"✗ Invalid choice\")"
},
{
"id": "python-quiz-game",
"title": "Interactive: Quiz Game",
"description": "Multiple choice quiz with score tracking",
"language": "Python",
"category": "interactive",
"hasPreview": true,
"code": "# Interactive Quiz Game\n\nprint(\"=== Python Programming Quiz ===\")\nprint(\"Answer the following questions!\")\nprint()\n\nscore = 0\ntotal_questions = 5\n\n# Question 1\nprint(\"Question 1: What does CPU stand for?\")\nprint(\" A) Central Process Unit\")\nprint(\" B) Central Processing Unit\")\nprint(\" C) Computer Personal Unit\")\nprint(\" D) Central Processor Unit\")\nanswer = input(\"Your answer (A/B/C/D): \").upper()\nif answer == 'B':\n print(\"✓ Correct!\\n\")\n score += 1\nelse:\n print(\"✗ Wrong! The answer was B\\n\")\n\n# Question 2\nprint(\"Question 2: Which programming language is known as the 'language of the web'?\")\nprint(\" A) Python\")\nprint(\" B) Java\")\nprint(\" C) JavaScript\")\nprint(\" D) C++\")\nanswer = input(\"Your answer (A/B/C/D): \").upper()\nif answer == 'C':\n print(\"✓ Correct!\\n\")\n score += 1\nelse:\n print(\"✗ Wrong! The answer was C\\n\")\n\n# Question 3\nprint(\"Question 3: What is 2 to the power of 8?\")\nprint(\" A) 128\")\nprint(\" B) 256\")\nprint(\" C) 512\")\nprint(\" D) 64\")\nanswer = input(\"Your answer (A/B/C/D): \").upper()\nif answer == 'B':\n print(\"✓ Correct!\\n\")\n score += 1\nelse:\n print(\"✗ Wrong! The answer was B\\n\")\n\n# Question 4\nprint(\"Question 4: Which data structure uses LIFO (Last In, First Out)?\")\nprint(\" A) Queue\")\nprint(\" B) Stack\")\nprint(\" C) Array\")\nprint(\" D) Tree\")\nanswer = input(\"Your answer (A/B/C/D): \").upper()\nif answer == 'B':\n print(\"✓ Correct!\\n\")\n score += 1\nelse:\n print(\"✗ Wrong! The answer was B\\n\")\n\n# Question 5\nprint(\"Question 5: What does HTML stand for?\")\nprint(\" A) Hyper Text Markup Language\")\nprint(\" B) High Tech Modern Language\")\nprint(\" C) Home Tool Markup Language\")\nprint(\" D) Hyperlinks and Text Markup Language\")\nanswer = input(\"Your answer (A/B/C/D): \").upper()\nif answer == 'A':\n print(\"✓ Correct!\\n\")\n score += 1\nelse:\n print(\"✗ Wrong! The answer was A\\n\")\n\n# Final score\nprint(\"=\" * 40)\nprint(f\"Quiz Complete! Your score: {score}/{total_questions}\")\npercentage = (score / total_questions) * 100\nprint(f\"Percentage: {percentage:.1f}%\")\n\nif score == total_questions:\n print(\"🌟 Perfect score! You're a genius!\")\nelif score >= 3:\n print(\"👍 Good job! Keep learning!\")\nelse:\n print(\"📚 Keep studying! You'll do better next time!\")\nprint(\"=\" * 40)"
}
]