Provides starter code for a variety of programming and scripting languages.
\n\n\n"
},
{
"key": "python",
"name": "Python",
"catKey": "oop",
"catName": "OOP",
"template": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"\nBasic Python Code Template\n--------------------------\n\nA simple skeleton file to get started with a Python script.\nIncludes a main execution block and a sample function.\n\"\"\"\n\nimport sys # Example: Import standard library (optional)\n# import os # Example: Another common import (optional)\n\ndef process_data(data):\n \"\"\"\n Placeholder function to process data.\n Replace with your actual logic.\n \"\"\"\n print(f\"Processing data: {data}\")\n # Add your processing steps here\n processed_result = data.upper() # Example processing\n return processed_result\n\ndef main(args=None):\n \"\"\"\n Main execution function.\n Parses command-line arguments and orchestrates the script's flow.\n \"\"\"\n if args is None:\n args = sys.argv[1:] # Get command-line arguments, excluding script name\n\n print(\"--- Python Template Start ---\")\n\n if not args:\n print(\"No command-line arguments provided. Using default data.\")\n sample_data = \"default_input\"\n else:\n print(f\"Received arguments: {args}\")\n sample_data = args[0] # Use the first argument as sample data\n\n # Call a function with the data\n result = process_data(sample_data)\n print(f\"Processed result: {result}\")\n\n print(\"--- Python Template End ---\")\n return 0 # Exit code 0 indicates success\n\n# Standard Python entry point check\nif __name__ == \"__main__\":\n # Execute the main function and exit with its return code\n sys.exit(main())"
},
{
"key": "sql",
"name": "SQL",
"catKey": "dsl",
"catName": "DSL / Query",
"template": "-- ======================================================================\n-- SQL Script Template\n-- ======================================================================\n-- Purpose: [Briefly describe the purpose of this script]\n-- Author: [Your Name]\n-- Date: ` + new Date().toISOString().slice(0, 10) + `\n-- Database: [Specify Target Database System, e.g., PostgreSQL, MySQL, SQLite]\n-- ======================================================================\n\n-- Recommended Settings (Uncomment and adjust as needed)\n-- ----------------------------------------------------------------------\n-- PRAGMA foreign_keys = ON; -- SQLite: Enforce foreign key constraints\n-- SET client_encoding = 'UTF8'; -- PostgreSQL: Set client encoding\n-- SET NAMES utf8mb4; -- MySQL: Set connection character set\n\n\n-- ======================================================================\n-- Schema Definition (DDL - Data Definition Language)\n-- ======================================================================\n-- Use CREATE, ALTER, DROP statements here\n\n-- Example: Creating Tables\n-- ----------------------------------------------------------------------\n/*\nDROP TABLE IF EXISTS OrderItems; -- Drop dependent table first\nDROP TABLE IF EXISTS Products;\nDROP TABLE IF EXISTS Orders;\nDROP TABLE IF EXISTS Customers;\n\nCREATE TABLE Customers (\n CustomerID INT PRIMARY KEY, -- Or SERIAL, AUTO_INCREMENT depending on DB\n FirstName VARCHAR(50) NOT NULL,\n LastName VARCHAR(50) NOT NULL,\n Email VARCHAR(100) UNIQUE,\n RegistrationDate DATE DEFAULT CURRENT_DATE\n);\n\nCREATE TABLE Products (\n ProductID INT PRIMARY KEY,\n ProductName VARCHAR(100) NOT NULL,\n Category VARCHAR(50),\n Price DECIMAL(10, 2) CHECK (Price >= 0),\n StockQuantity INT DEFAULT 0\n);\n\nCREATE TABLE Orders (\n OrderID INT PRIMARY KEY,\n CustomerID INT,\n OrderDate TIMESTAMP DEFAULT CURRENT_TIMESTAMP,\n Status VARCHAR(20) DEFAULT 'Pending',\n FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID) ON DELETE SET NULL -- Or ON DELETE CASCADE\n);\n\nCREATE TABLE OrderItems (\n OrderItemID INT PRIMARY KEY,\n OrderID INT NOT NULL,\n ProductID INT NOT NULL,\n Quantity INT CHECK (Quantity > 0),\n UnitPrice DECIMAL(10, 2), -- Price at the time of order\n FOREIGN KEY (OrderID) REFERENCES Orders(OrderID) ON DELETE CASCADE,\n FOREIGN KEY (ProductID) REFERENCES Products(ProductID) ON DELETE RESTRICT\n);\n*/\n\n-- Example: Creating Indexes for performance\n-- ----------------------------------------------------------------------\n-- CREATE INDEX idx_customer_email ON Customers (Email);\n-- CREATE INDEX idx_product_category ON Products (Category);\n-- CREATE INDEX idx_order_customer ON Orders (CustomerID);\n\n\n-- ======================================================================\n-- Data Manipulation (DML - Data Manipulation Language)\n-- ======================================================================\n-- Use INSERT, UPDATE, DELETE statements here\n\n-- Example: Inserting Data\n-- ----------------------------------------------------------------------\n/*\nINSERT INTO Customers (CustomerID, FirstName, LastName, Email) VALUES\n(1, 'Alice', 'Smith', 'alice.s@example.com'),\n(2, 'Bob', 'Johnson', 'bob.j@example.com');\n\nINSERT INTO Products (ProductID, ProductName, Category, Price, StockQuantity) VALUES\n(101, 'Laptop', 'Electronics', 1200.00, 50),\n(102, 'Keyboard', 'Accessories', 75.50, 150);\n\n-- Assume OrderID 1 is placed by CustomerID 1 for ProductID 101\nINSERT INTO Orders (OrderID, CustomerID) VALUES (1, 1);\nINSERT INTO OrderItems (OrderItemID, OrderID, ProductID, Quantity, UnitPrice) VALUES\n(1, 1, 101, 1, 1200.00);\n*/\n\n\n-- Example: Updating Data\n-- ----------------------------------------------------------------------\n-- UPDATE Products SET StockQuantity = StockQuantity - 1 WHERE ProductID = 101;\n-- UPDATE Orders SET Status = 'Shipped' WHERE OrderID = 1;\n\n\n-- Example: Deleting Data (Use with caution!)\n-- ----------------------------------------------------------------------\n-- DELETE FROM Customers WHERE CustomerID = 2; -- Requires handling dependencies if ON DELETE RESTRICT is used\n\n\n-- ======================================================================\n-- Data Querying (DQL - Data Query Language)\n-- ======================================================================\n-- Use SELECT statements here\n\n-- Example: Simple Select\n-- ----------------------------------------------------------------------\n-- SELECT FirstName, LastName FROM Customers WHERE RegistrationDate > '2024-01-01';\n\n\n-- Example: Join Query\n-- ----------------------------------------------------------------------\n/*\nSELECT\n o.OrderID,\n o.OrderDate,\n c.FirstName || ' ' || c.LastName AS CustomerName, -- Concatenation varies (e.g., CONCAT() in MySQL)\n p.ProductName,\n oi.Quantity,\n oi.UnitPrice\nFROM Orders o\nJOIN Customers c ON o.CustomerID = c.CustomerID\nJOIN OrderItems oi ON o.OrderID = oi.OrderID\nJOIN Products p ON oi.ProductID = p.ProductID\nWHERE o.Status = 'Pending'\nORDER BY o.OrderDate DESC;\n*/\n\n-- ======================================================================\n-- End of Script\n-- ======================================================================\n-- Optional: Commit changes if transaction control is manual\n-- COMMIT;\n-- Optional: Run cleanup commands if needed"
}
];
// Immediately Invoked Function Expression (IIFE) to contain scope
(function(){
// --- DOM References ---
const mainCategorySelect = document.getElementById('mainCategory');
const languageSelect = document.getElementById('language');
const templateOutput = document.getElementById('templateOutput');
const copyButton = document.getElementById('templateCopyBtn');
const clearButton = document.getElementById('templateClearBtn');
// --- Core Functions (Rewritten for dynamic data) ---
function populateCategories() {
mainCategorySelect.innerHTML = ''; // Clear existing options
// Use a Map to get unique categories { catKey: catName }
const uniqueCategories = new Map();
if (typeof loadedSkeletonsData !== 'undefined') {
loadedSkeletonsData.forEach(skeleton => {
if (!uniqueCategories.has(skeleton.catKey)) {
uniqueCategories.set(skeleton.catKey, skeleton.catName);
}
});
}
// Convert Map to array, sort by category display name, and add options
const sortedCategories = Array.from(uniqueCategories.entries()) // [ [catKey, catName], ... ]
.sort(([, nameA], [, nameB]) => nameA.localeCompare(nameB)); // Sort by name (index 1)
if (sortedCategories.length === 0) {
// Handle case where no valid templates were loaded
mainCategorySelect.add(new Option("No templates found", ""));
mainCategorySelect.disabled = true;
languageSelect.disabled = true;
return; // Exit early
}
mainCategorySelect.disabled = false;
sortedCategories.forEach(([catKey, catName]) => {
mainCategorySelect.add(new Option(catName, catKey));
});
}
function populateLanguages(selectedCategoryKey) {
languageSelect.innerHTML = ''; // Clear previous language options
languageSelect.disabled = true; // Disable initially
if (!selectedCategoryKey || typeof loadedSkeletonsData === 'undefined') {
// If "No templates found" was selected or category key is empty or data missing
updateTemplate(); // Ensure template area is cleared/reset
return;
}
// Filter loaded data for languages belonging to the selected category
const languagesInCategory = loadedSkeletonsData
.filter(skeleton => skeleton.catKey === selectedCategoryKey)
.sort((a, b) => a.name.localeCompare(b.name)); // Sort languages by display name
if (languagesInCategory.length > 0) {
languagesInCategory.forEach(lang => {
languageSelect.add(new Option(lang.name, lang.key)); // Use display name (lang.name) and language key (lang.key)
});
languageSelect.disabled = false; // Enable the dropdown
} else {
// If no languages found for this category (edge case), add placeholder
languageSelect.add(new Option("No languages", ""));
// Keep disabled
}
updateTemplate(); // Update snippet display after potentially changing the language list
}
function updateTemplate() {
const selectedLangKey = languageSelect.value;
templateOutput.value = ''; // Clear output first
templateOutput.placeholder = 'Select category and language...'; // Default placeholder
if (selectedLangKey && typeof loadedSkeletonsData !== 'undefined') {
// Find the template data for the selected language key
const skeletonData = loadedSkeletonsData.find(skeleton => skeleton.key === selectedLangKey);
if (skeletonData) {
templateOutput.value = skeletonData.template;
templateOutput.placeholder = 'Template loaded.';
} else {
// Language key exists in dropdown but not in data (shouldn't happen)
const selectedLangName = languageSelect.options[languageSelect.selectedIndex]?.text || selectedLangKey;
templateOutput.value = `/* Error: Template data not found for key: ${selectedLangKey} (${selectedLangName}) */`;
templateOutput.placeholder = 'Template data error...';
console.error("Data mismatch: Language key", selectedLangKey, "not found in loadedSkeletonsData.");
}
} else if (mainCategorySelect.value && !languageSelect.disabled) {
// Category selected, but no specific language selected yet (or none available)
templateOutput.placeholder = 'Select a language...';
} else if (mainCategorySelect.disabled) {
templateOutput.placeholder = 'No templates available.';
templateOutput.value = '/* No templates loaded. Check /skeletons directory and file formats. */';
}
// If selectedLangKey is empty (e.g., "No languages" placeholder), do nothing, textarea remains empty
}
// --- Event Listeners --- (Unchanged logic, just call the new functions)
mainCategorySelect.addEventListener('change', () => populateLanguages(mainCategorySelect.value));
languageSelect.addEventListener('change', updateTemplate);
copyButton.addEventListener('click', () => {
if (!templateOutput.value) return; // Don't copy if empty
templateOutput.select();
templateOutput.setSelectionRange(0, 99999); // For mobile devices
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(templateOutput.value)
.then(() => {
const original = copyButton.innerHTML;
copyButton.innerHTML = ' Copied!';
setTimeout(() => { copyButton.innerHTML = original; }, 2000);
})
.catch(err => {
console.error('Async clipboard copy failed: ', err);
alert('Failed to copy text.');
});
} else {
try { // Fallback
if(document.execCommand('copy')) {
const original = copyButton.innerHTML;
copyButton.textContent = 'Copied!';
setTimeout(() => { copyButton.innerHTML = original; }, 2000);
} else { alert('Failed to copy text (fallback).'); }
} catch (e) { console.error('Fallback execCommand copy failed', e); alert('Failed to copy text.'); }
}
window.getSelection()?.removeAllRanges();
templateOutput.blur();
});
clearButton.addEventListener('click', () => {
templateOutput.value = '';
templateOutput.placeholder = 'Select category and language...';
// Optionally reset dropdowns - might be good UX
// if (!mainCategorySelect.disabled && mainCategorySelect.options.length > 0) {
// mainCategorySelect.selectedIndex = 0;
// populateLanguages(mainCategorySelect.value);
// }
});
// --- Initialization ---
// Check if data was successfully loaded by PHP before initializing dropdowns
if (typeof loadedSkeletonsData !== 'undefined' && Array.isArray(loadedSkeletonsData)) {
populateCategories();
// Populate languages based on the first category (if any exist and is selected)
if (mainCategorySelect.options.length > 0 && mainCategorySelect.value) {
populateLanguages(mainCategorySelect.value);
} else {
// Handle case where populateCategories resulted in "No templates found"
populateLanguages(""); // Ensure language dropdown is cleared/disabled and template area reflects this
}
} else {
// Handle case where PHP found no valid skeleton files or an error occurred server-side
mainCategorySelect.innerHTML = '';
mainCategorySelect.disabled = true;
languageSelect.innerHTML = '';
languageSelect.disabled = true;
templateOutput.value = '/* Error loading templates. Check server logs and the /skeletons directory. Ensure files exist and have the correct METADATA format. */';
templateOutput.placeholder = 'Error loading templates.';
console.error("PHP did not provide valid loadedSkeletonsData. Check PHP error logs and the script output.");
}
})(); // End IIFE