From 7b487ced37f22d2f56a7167e8b8f757728bbca3b Mon Sep 17 00:00:00 2001
From: GitHub Action Typerwriter Animation Typerwriter Animation (predicate))
+ | std::ranges::to (predicate))
+ | std::ranges::to
- Description:
- {snippet.description}
-
- Contributed by{" "}
-
- @{snippet.author}
-
-
+ Description:
+ {snippet.description}
+
+ Contributed by{" "}
+
+ @{snippet.author}
+
+ (predicate))
- | std::ranges::to> zip(List list1, List list2) {\n // Create pairs by iterating through the indices of both lists\n return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list\n .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i\n .collect(Collectors.toList()); // Collect the pairs into a List\n}\n\n// Usage:\nList
> zipped = zip(arr1, arr2);\n\nSystem.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]\n"
+ }
+ ]
+ },
{
"name": "Basics",
"snippets": [
diff --git a/public/consolidated/javascript--react.json b/public/consolidated/javascript--react.json
new file mode 100644
index 00000000..2530b7b6
--- /dev/null
+++ b/public/consolidated/javascript--react.json
@@ -0,0 +1,18 @@
+[
+ {
+ "name": "Basics",
+ "snippets": [
+ {
+ "title": "Hello, World!",
+ "description": "Show Hello World on the page.",
+ "author": "ACR1209",
+ "tags": [
+ "printing",
+ "hello-world"
+ ],
+ "contributors": [],
+ "code": "import React from 'react';\nimport ReactDOM from 'react-dom';\n\nconst App = () => {\n return (\n
Hello, World!
\n Hello, World!
+ > zip(List list1, List list2) {\n // Create pairs by iterating through the indices of both lists\n return IntStream.range(0, Math.min(list1.size(), list2.size())) // Limit the range to the smaller list\n .mapToObj(i -> Arrays.asList(list1.get(i), list2.get(i))) // Pair elements from both lists at index i\n .collect(Collectors.toList()); // Collect the pairs into a List\n}\n\n// Usage:\nList
> zipped = zip(arr1, arr2);\n\nSystem.out.println(zipped); // Output: [[a, 1], [b, 2], [c, 3]]\n"
- }
- ]
- },
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello-World",
- "description": "Prints Hello world in the console",
- "author": "SarvariHarshitha",
- "tags": [
- "java",
- "console",
- "printing"
- ],
- "contributors": [],
- "code": "// This is the main class of the Java program\npublic class Main {\n // The main method is the entry point of the program\n public static void main(String args[]) {\n // This statement prints \"Hello, World!\" to the console\n System.out.println(\"Hello, World!\");\n }\n}\n\n"
- }
- ]
- }
-]
\ No newline at end of file
diff --git a/public/consolidated/javascript.json b/public/consolidated/javascript.json
deleted file mode 100644
index 1b49645a..00000000
--- a/public/consolidated/javascript.json
+++ /dev/null
@@ -1,872 +0,0 @@
-[
- {
- "name": "Array Manipulation",
- "snippets": [
- {
- "title": "Partition Array",
- "description": "Splits an array into two arrays based on a callback function.",
- "author": "Swaraj-Singh-30",
- "tags": [
- "array",
- "partition",
- "reduce"
- ],
- "contributors": [],
- "code": "const partition = (arr, callback) =>\n arr.reduce(\n ([pass, fail], elem) => (callback(elem) ? [[...pass, elem], fail] : [pass, [...fail, elem]]),\n [[], []]\n );\n\n// Usage:\nconst numbers = [1, 2, 3, 4, 5, 6];\nconst isEven = (n) => n % 2 === 0;\npartition(numbers, isEven); // Returns: [[2, 4, 6], [1, 3, 5]]\n"
- },
- {
- "title": "Remove Duplicates",
- "description": "Removes duplicate values from an array.",
- "author": "dostonnabotov",
- "tags": [
- "array",
- "deduplicate"
- ],
- "contributors": [],
- "code": "const removeDuplicates = (arr) => [...new Set(arr)];\n\n// Usage:\nconst numbers = [1, 2, 2, 3, 4, 4, 5];\nremoveDuplicates(numbers); // Returns: [1, 2, 3, 4, 5]\n"
- },
- {
- "title": "Remove Falsy Values",
- "description": "Removes falsy values from an array.",
- "author": "mubasshir",
- "tags": [
- "array",
- "falsy",
- "filter"
- ],
- "contributors": [],
- "code": "const removeFalsy = (arr) => arr.filter(Boolean);\n\n// Usage:\nconst array = [0, 1, false, 2, \"\", 3, null];\nremoveFalsy(array); // Returns: [1, 2, 3]\n"
- },
- {
- "title": "Shuffle Array",
- "description": "Shuffles an Array.",
- "author": "loxt-nixo",
- "tags": [
- "array",
- "shuffle"
- ],
- "contributors": [],
- "code": "function shuffleArray(array) {\n for (let i = array.length - 1; i >= 0; i--) {\n const j = Math.floor(Math.random() * (i + 1));\n [array[i], array[j]] = [array[j], array[i]];\n }\n}\n\n// Usage:\nconst array = [1, 2, 3, 4, 5];\nshuffleArray(array); // Shuffles `array` in place\n"
- },
- {
- "title": "Zip Arrays",
- "description": "Combines two arrays by pairing corresponding elements from each array.",
- "author": "Swaraj-Singh-30",
- "tags": [
- "array",
- "map"
- ],
- "contributors": [],
- "code": "const zip = (arr1, arr2) => arr1.map((value, index) => [value, arr2[index]]);\n\n// Usage:\nconst arr1 = ['a', 'b', 'c'];\nconst arr2 = [1, 2, 3];\nconsole.log(zip(arr1, arr2)); // Output: [['a', 1], ['b', 2], ['c', 3]]\n"
- }
- ]
- },
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "James-Beans",
- "tags": [
- "printing",
- "hello-world"
- ],
- "contributors": [],
- "code": "console.log(\"Hello, World!\"); // Prints Hello, World! to the console\n"
- }
- ]
- },
- {
- "name": "Color Manipulation",
- "snippets": [
- {
- "title": "RGB to Hex Color",
- "description": "Converts RGB color values to hexadecimal color code.",
- "author": "jjcantu",
- "tags": [
- "color",
- "conversion"
- ],
- "contributors": [],
- "code": "function rgbToHex(r, g, b) {\n const toHex = (n) => {\n const hex = n.toString(16);\n return hex.length === 1 ? '0' + hex : hex;\n };\n \n return '#' + toHex(r) + toHex(g) + toHex(b);\n}\n\n// Usage:\nconsole.log(rgbToHex(255, 128, 0)); // Output: \"#ff8000\"\nconsole.log(rgbToHex(0, 255, 0)); // Output: \"#00ff00\"\n"
- }
- ]
- },
- {
- "name": "Date And Time",
- "snippets": [
- {
- "title": "Check Leap Year",
- "description": "Determines if a given year is a leap year.",
- "author": "axorax",
- "tags": [
- "date",
- "leap-year"
- ],
- "contributors": [],
- "code": "const isLeapYear = (year) => (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;\n\n// Usage:\nisLeapYear(2024); // Returns: true\nisLeapYear(2023); // Returns: false\n"
- },
- {
- "title": "Convert to Unix Timestamp",
- "description": "Converts a date to a Unix timestamp in seconds.",
- "author": "Yugveer06",
- "tags": [
- "date",
- "unix",
- "timestamp"
- ],
- "contributors": [],
- "code": "function convertToUnixSeconds(input) {\n if (typeof input === 'string') {\n if (!input.trim()) {\n throw new Error('Date string cannot be empty or whitespace');\n }\n } else if (!input) {\n throw new Error('Input is required');\n }\n\n let date;\n\n if (typeof input === 'string') {\n date = new Date(input);\n } else if (input instanceof Date) {\n date = input;\n } else {\n throw new Error('Input must be a valid date string or Date object');\n }\n\n if (isNaN(date.getTime())) {\n throw new Error('Invalid date provided');\n }\n\n return Math.floor(date.getTime() / 1000);\n}\n\n// Usage:\nconvertToUnixSeconds('2025-01-01T12:00:00Z'); // Returns: 1735732800\nconvertToUnixSeconds(new Date('2025-01-01T12:00:00Z')); // Returns: 1735732800\nconvertToUnixSeconds(new Date()); // Returns: Current Unix timestamp in seconds\n"
- },
- {
- "title": "Format Date",
- "description": "Formats a date in 'YYYY-MM-DD' format.",
- "author": "dostonnabotov",
- "tags": [
- "date",
- "format"
- ],
- "contributors": [],
- "code": "const formatDate = (date) => date.toISOString().split('T')[0];\n\n// Usage:\nformatDate(new Date(2024, 11, 10)); // Returns: '2024-12-10'\n"
- },
- {
- "title": "Get Day of the Year",
- "description": "Calculates the day of the year (1-365 or 1-366 for leap years) for a given date.",
- "author": "axorax",
- "tags": [
- "date",
- "day-of-year"
- ],
- "contributors": [],
- "code": "const getDayOfYear = (date) => {\n const startOfYear = new Date(date.getFullYear(), 0, 0);\n const diff = date - startOfYear + (startOfYear.getTimezoneOffset() - date.getTimezoneOffset()) * 60 * 1000;\n return Math.floor(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\ngetDayOfYear(new Date('2024-12-31')) // Returns: 366 (Leap year)\n"
- },
- {
- "title": "Get Days in Month",
- "description": "Calculates the number of days in a specific month of a given year.",
- "author": "axorax",
- "tags": [
- "date",
- "days-in-month"
- ],
- "contributors": [],
- "code": "const getDaysInMonth = (year, month) => new Date(year, month + 1, 0).getDate();\n\n// Usage:\ngetDaysInMonth(2024, 1); // Returns: 29 (February in a leap year)\ngetDaysInMonth(2023, 1); // Returns: 28\n"
- },
- {
- "title": "Get Time Difference",
- "description": "Calculates the time difference in days between two dates.",
- "author": "dostonnabotov",
- "tags": [
- "date",
- "time-difference"
- ],
- "contributors": [],
- "code": "const getTimeDifference = (date1, date2) => {\n const diff = Math.abs(date2 - date1);\n return Math.ceil(diff / (1000 * 60 * 60 * 24));\n};\n\n// Usage:\nconst date1 = new Date('2024-01-01');\nconst date2 = new Date('2024-12-31');\ngetTimeDifference(date1, date2); // Returns: 365\n"
- },
- {
- "title": "Relative Time Formatter",
- "description": "Displays how long ago a date occurred or how far in the future a date is.",
- "author": "Yugveer06",
- "tags": [
- "date",
- "time",
- "relative",
- "future",
- "past"
- ],
- "contributors": [],
- "code": "const getRelativeTime = (date) => {\n const now = Date.now();\n const diff = date.getTime() - now;\n const seconds = Math.abs(Math.floor(diff / 1000));\n const minutes = Math.abs(Math.floor(seconds / 60));\n const hours = Math.abs(Math.floor(minutes / 60));\n const days = Math.abs(Math.floor(hours / 24));\n const years = Math.abs(Math.floor(days / 365));\n\n if (Math.abs(diff) < 1000) return 'just now';\n\n const isFuture = diff > 0;\n\n if (years > 0) return `${isFuture ? 'in ' : ''}${years} ${years === 1 ? 'year' : 'years'}${isFuture ? '' : ' ago'}`;\n if (days > 0) return `${isFuture ? 'in ' : ''}${days} ${days === 1 ? 'day' : 'days'}${isFuture ? '' : ' ago'}`;\n if (hours > 0) return `${isFuture ? 'in ' : ''}${hours} ${hours === 1 ? 'hour' : 'hours'}${isFuture ? '' : ' ago'}`;\n if (minutes > 0) return `${isFuture ? 'in ' : ''}${minutes} ${minutes === 1 ? 'minute' : 'minutes'}${isFuture ? '' : ' ago'}`;\n\n return `${isFuture ? 'in ' : ''}${seconds} ${seconds === 1 ? 'second' : 'seconds'}${isFuture ? '' : ' ago'}`;\n}\n\n// Usage:\nconst pastDate = new Date('2021-12-29 13:00:00');\nconst futureDate = new Date('2099-12-29 13:00:00');\ngetRelativeTime(pastDate); // x years ago\ngetRelativeTime(new Date()); // just now\ngetRelativeTime(futureDate); // in x years\n"
- },
- {
- "title": "Start of the Day",
- "description": "Returns the start of the day (midnight) for a given date.",
- "author": "axorax",
- "tags": [
- "date",
- "start-of-day"
- ],
- "contributors": [],
- "code": "const startOfDay = (date) => new Date(date.setHours(0, 0, 0, 0));\n\n// Usage:\nconst today = new Date();\nstartOfDay(today); // Returns: Date object for midnight\n"
- }
- ]
- },
- {
- "name": "Dom Manipulation",
- "snippets": [
- {
- "title": "Change Element Style",
- "description": "Changes the inline style of an element.",
- "author": "axorax",
- "tags": [
- "dom",
- "style"
- ],
- "contributors": [],
- "code": "const changeElementStyle = (element, styleObj) => {\n Object.entries(styleObj).forEach(([property, value]) => {\n element.style[property] = value;\n });\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nchangeElementStyle(element, { color: 'red', backgroundColor: 'yellow' });\n"
- },
- {
- "title": "Remove Element",
- "description": "Removes a specified element from the DOM.",
- "author": "axorax",
- "tags": [
- "dom",
- "remove"
- ],
- "contributors": [],
- "code": "const removeElement = (element) => {\n if (element && element.parentNode) {\n element.parentNode.removeChild(element);\n }\n};\n\n// Usage:\nconst element = document.querySelector('.my-element');\nremoveElement(element);\n"
- }
- ]
- },
- {
- "name": "Function Utilities",
- "snippets": [
- {
- "title": "Compose Functions",
- "description": "Composes multiple functions into a single function, where the output of one function becomes the input of the next.",
- "author": "axorax",
- "tags": [
- "function",
- "compose"
- ],
- "contributors": [],
- "code": "const compose = (...funcs) => (initialValue) => {\n return funcs.reduce((acc, func) => func(acc), initialValue);\n};\n\n// Usage:\nconst add2 = (x) => x + 2;\nconst multiply3 = (x) => x * 3;\nconst composed = compose(multiply3, add2);\ncomposed(5); // Returns: 17 ((5 * 3) + 2)\n"
- },
- {
- "title": "Curry Function",
- "description": "Transforms a function into its curried form.",
- "author": "axorax",
- "tags": [
- "curry",
- "function"
- ],
- "contributors": [],
- "code": "const curry = (func) => {\n const curried = (...args) => {\n if (args.length >= func.length) {\n return func(...args);\n }\n return (...nextArgs) => curried(...args, ...nextArgs);\n };\n return curried;\n};\n\n// Usage:\nconst add = (a, b, c) => a + b + c;\nconst curriedAdd = curry(add);\ncurriedAdd(1)(2)(3); // Returns: 6\ncurriedAdd(1, 2)(3); // Returns: 6\n"
- },
- {
- "title": "Debounce Function",
- "description": "Delays a function execution until after a specified time.",
- "author": "dostonnabotov",
- "tags": [
- "debounce",
- "performance"
- ],
- "contributors": [],
- "code": "const debounce = (func, delay) => {\n let timeout;\n\n return (...args) => {\n clearTimeout(timeout);\n timeout = setTimeout(() => func(...args), delay);\n };\n};\n\n// Usage:\nwindow.addEventListener(\n 'resize',\n debounce(() => console.log('Resized!'), 500), // Will only output after resizing has stopped for 500ms\n);\n"
- },
- {
- "title": "Get Contrast Color",
- "description": "Returns either black or white text color based on the brightness of the provided hex color.",
- "author": "yaya12085",
- "tags": [
- "color",
- "hex",
- "contrast",
- "brightness"
- ],
- "contributors": [],
- "code": "const getContrastColor = (hexColor) => {\n // Expand short hex color to full format\n if (hexColor.length === 4) {\n hexColor = `#${hexColor[1]}${hexColor[1]}${hexColor[2]}${hexColor[2]}${hexColor[3]}${hexColor[3]}`;\n }\n const r = parseInt(hexColor.slice(1, 3), 16);\n const g = parseInt(hexColor.slice(3, 5), 16);\n const b = parseInt(hexColor.slice(5, 7), 16);\n const brightness = (r * 299 + g * 587 + b * 114) / 1000;\n return brightness >= 128 ? \"#000000\" : \"#FFFFFF\";\n};\n\n// Usage:\ngetContrastColor('#fff'); // Returns: #000000 (black)\ngetContrastColor('#123456'); // Returns: #FFFFFF (white)\ngetContrastColor('#ff6347'); // Returns: #000000 (black)\ngetContrastColor('#f4f'); // Returns: #000000 (black)\n"
- },
- {
- "title": "Memoize Function",
- "description": "Caches the result of a function based on its arguments to improve performance.",
- "author": "axorax",
- "tags": [
- "memoization",
- "optimization"
- ],
- "contributors": [],
- "code": "const memoize = (func) => {\n const cache = new Map();\n return (...args) => {\n const key = JSON.stringify(args);\n if (cache.has(key)) {\n return cache.get(key);\n }\n const result = func(...args);\n cache.set(key, result);\n return result;\n };\n};\n\n// Usage:\nconst factorial = memoize((n) => (n <= 1 ? 1 : n * factorial(n - 1)));\nfactorial(5); // Returns: 120\nfactorial(5); // Returns: 120 (retrieved from cache)\n"
- },
- {
- "title": "Once Function",
- "description": "Ensures a function is only called once.",
- "author": "axorax",
- "tags": [
- "function",
- "once"
- ],
- "contributors": [],
- "code": "const once = (func) => {\n let called = false;\n return (...args) => {\n if (!called) {\n called = true;\n return func(...args);\n }\n };\n};\n\n// Usage:\nconst initialize = once(() => console.log('Initialized!'));\ninitialize(); // Output: Initialized!\ninitialize(); // No output\n"
- },
- {
- "title": "Rate Limit Function",
- "description": "Limits how often a function can be executed within a given time window.",
- "author": "axorax",
- "tags": [
- "function",
- "rate-limiting"
- ],
- "contributors": [],
- "code": "const rateLimit = (func, limit, timeWindow) => {\n let queue = [];\n setInterval(() => {\n if (queue.length) {\n const next = queue.shift();\n func(...next.args);\n }\n }, timeWindow);\n return (...args) => {\n if (queue.length < limit) {\n queue.push({ args });\n }\n };\n};\n\n// Usage:\nconst fetchData = () => console.log('Fetching data...');\nconst rateLimitedFetch = rateLimit(fetchData, 2, 1000);\nsetInterval(() => rateLimitedFetch(), 200); // Limits fetchData calls to twice a seconds\n"
- },
- {
- "title": "Repeat Function Invocation",
- "description": "Invokes a function a specified number of times.",
- "author": "dostonnabotov",
- "tags": [
- "function",
- "repeat"
- ],
- "contributors": [],
- "code": "const times = (func, n) => {\n Array.from(Array(n)).forEach(() => {\n func();\n });\n};\n\n// Usage:\nconst randomFunction = () => console.log('Function called!');\ntimes(randomFunction, 3); // Logs 'Function called!' three times\n"
- },
- {
- "title": "Sleep Function",
- "description": "Waits for a specified amount of milliseconds before resolving.",
- "author": "0xHouss",
- "tags": [
- "javascript",
- "sleep",
- "delay",
- "utility",
- "promises"
- ],
- "contributors": [],
- "code": "const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));\n\n// Usage:\nconsole.log('Hello');\nawait sleep(2000); // Waits for 2 seconds\nconsole.log('World!');\n"
- }
- ]
- },
- {
- "name": "Local Storage",
- "snippets": [
- {
- "title": "Add Item to localStorage",
- "description": "Stores a value in localStorage under the given key.",
- "author": "dostonnabotov",
- "tags": [
- "localStorage",
- "storage"
- ],
- "contributors": [],
- "code": "const addToLocalStorage = (key, value) => {\n localStorage.setItem(key, JSON.stringify(value));\n};\n\n// Usage:\naddToLocalStorage('user', { name: 'John', age: 30 });\n"
- },
- {
- "title": "Check if Item Exists in localStorage",
- "description": "Checks if a specific item exists in localStorage.",
- "author": "axorax",
- "tags": [
- "localStorage",
- "storage"
- ],
- "contributors": [],
- "code": "const isItemInLocalStorage = (key) => {\n return localStorage.getItem(key) !== null;\n};\n\n// Usage:\nconsole.log(isItemInLocalStorage('user')); // Output: true or false\n"
- },
- {
- "title": "Retrieve Item from localStorage",
- "description": "Retrieves a value from localStorage by key and parses it.",
- "author": "dostonnabotov",
- "tags": [
- "localStorage",
- "storage"
- ],
- "contributors": [],
- "code": "const getFromLocalStorage = (key) => {\n const item = localStorage.getItem(key);\n return item ? JSON.parse(item) : null;\n};\n\n// Usage:\ngetFromLocalStorage('user'); // Returns: { name: 'John', age: 30 }\n"
- }
- ]
- },
- {
- "name": "Mathematical Functions",
- "snippets": [
- {
- "title": "Greatest Common Divisor",
- "description": "Calculates the largest positive integer that divides each of the integers without leaving a remainder. Useful for calculating aspect ratios.",
- "author": "JanluOfficial",
- "tags": [
- "math",
- "division"
- ],
- "contributors": [],
- "code": "function gcd(a, b) {\n while (b !== 0) {\n let temp = b;\n b = a % b;\n a = temp;\n }\n return a;\n}\n\n// Usage:\ngcd(1920, 1080); // Returns: 120\ngcd(1920, 1200); // Returns: 240\ngcd(5,12); // Returns: 1\n"
- }
- ]
- },
- {
- "name": "Number Formatting",
- "snippets": [
- {
- "title": "Convert Number to Currency",
- "description": "Converts a number to a currency format with a specific locale.",
- "author": "axorax",
- "tags": [
- "number",
- "currency"
- ],
- "contributors": [],
- "code": "const convertToCurrency = (num, locale = 'en-US', currency = 'USD') => {\n return new Intl.NumberFormat(locale, {\n style: 'currency',\n currency: currency\n }).format(num);\n};\n\n// Usage:\nconvertToCurrency(1234567.89); // Returns: '$1,234,567.89'\nconvertToCurrency(987654.32, 'de-DE', 'EUR'); // Returns: '987.654,32 €'\n"
- },
- {
- "title": "Convert Number to Roman Numerals",
- "description": "Converts a number to Roman numeral representation.",
- "author": "axorax",
- "tags": [
- "number",
- "roman"
- ],
- "contributors": [],
- "code": "const numberToRoman = (num) => {\n const romanNumerals = {\n 1: 'I', 4: 'IV', 5: 'V', 9: 'IX', 10: 'X', 40: 'XL', 50: 'L',\n 90: 'XC', 100: 'C', 400: 'CD', 500: 'D', 900: 'CM', 1000: 'M'\n };\n let result = '';\n Object.keys(romanNumerals).reverse().forEach(value => {\n while (num >= value) {\n result += romanNumerals[value];\n num -= value;\n }\n });\n return result;\n};\n\n// Usage:\nnumberToRoman(1994); // Returns: 'MCMXCIV'\nnumberToRoman(58); // Returns: 'LVIII'\n"
- },
- {
- "title": "Convert to Scientific Notation",
- "description": "Converts a number to scientific notation.",
- "author": "axorax",
- "tags": [
- "number",
- "scientific"
- ],
- "contributors": [],
- "code": "const toScientificNotation = (num) => {\n if (isNaN(num)) {\n throw new Error('Input must be a number');\n }\n if (num === 0) {\n return '0e+0';\n }\n const exponent = Math.floor(Math.log10(Math.abs(num)));\n const mantissa = num / Math.pow(10, exponent);\n return `${mantissa.toFixed(2)}e${exponent >= 0 ? '+' : ''}${exponent}`;\n};\n\n// Usage:\ntoScientificNotation(12345); // Returns: '1.23e+4'\ntoScientificNotation(0.0005678); // Returns: '5.68e-4'\ntoScientificNotation(1000); // Returns: '1.00e+3'\ntoScientificNotation(0); // Returns: '0e+0'\ntoScientificNotation(-54321); // Returns: '-5.43e+4'\n"
- },
- {
- "title": "Format File Size",
- "description": "Converts bytes into human-readable file size format.",
- "author": "jjcantu",
- "tags": [
- "format",
- "size"
- ],
- "contributors": [],
- "code": "function formatFileSize(bytes) {\n if (bytes === 0) return '0 Bytes';\n \n const k = 1024;\n const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];\n const i = Math.floor(Math.log(bytes) / Math.log(k));\n \n return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];\n}\n\n// Usage:\nconsole.log(formatFileSize(1234)); // Output: \"1.21 KB\"\nconsole.log(formatFileSize(1234567)); // Output: \"1.18 MB\"\n"
- },
- {
- "title": "Format Number with Commas",
- "description": "Formats a number with commas for better readability (e.g., 1000 -> 1,000).",
- "author": "axorax",
- "tags": [
- "number",
- "format"
- ],
- "contributors": [],
- "code": "const formatNumberWithCommas = (num) => {\n return num.toString().replace(/\\B(?=(\\d{3})+(?!\\d))/g, ',');\n};\n\n// Usage:\nformatNumberWithCommas(1000); // Returns: '1,000'\nformatNumberWithCommas(1234567); // Returns: '1,234,567'\nformatNumberWithCommas(987654321); // Returns: '987,654,321'\n"
- },
- {
- "title": "Number Formatter",
- "description": "Formats a number with suffixes (K, M, B, etc.).",
- "author": "realvishalrana",
- "tags": [
- "number",
- "format"
- ],
- "contributors": [],
- "code": "const nFormatter = (num) => {\n if (!num) return;\n num = parseFloat(num.toString().replace(/[^0-9.]/g, ''));\n const suffixes = ['', 'K', 'M', 'B', 'T', 'P', 'E'];\n let index = 0;\n while (num >= 1000 && index < suffixes.length - 1) {\n num /= 1000;\n index++;\n }\n return num.toFixed(2).replace(/\\.0+$|(\\.[0-9]*[1-9])0+$/, '$1') + suffixes[index];\n};\n\n// Usage:\nnFormatter(1234567); // Returns: '1.23M'\n"
- },
- {
- "title": "Number to Words Converter",
- "description": "Converts a number to its word representation in English.",
- "author": "axorax",
- "tags": [
- "number",
- "words"
- ],
- "contributors": [],
- "code": "const numberToWords = (num) => {\n const below20 = ['Zero', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen'];\n const tens = ['', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety'];\n const above1000 = ['Hundred', 'Thousand', 'Million', 'Billion'];\n if (num < 20) return below20[num];\n let words = '';\n for (let i = 0; num > 0; i++) {\n if (i > 0 && num % 1000 !== 0) words = above1000[i] + ' ' + words;\n if (num % 100 >= 20) {\n words = tens[Math.floor(num / 10)] + ' ' + words;\n num %= 10;\n }\n if (num < 20) words = below20[num] + ' ' + words;\n num = Math.floor(num / 100);\n }\n return words.trim();\n};\n\n// Usage:\nnumberToWords(123); // Returns: 'One Hundred Twenty Three'\nnumberToWords(2045); // Returns: 'Two Thousand Forty Five'\n"
- }
- ]
- },
- {
- "name": "Object Manipulation",
- "snippets": [
- {
- "title": "Check if Object is Empty",
- "description": "Checks whether an object has no own enumerable properties.",
- "author": "axorax",
- "tags": [
- "object",
- "check",
- "empty"
- ],
- "contributors": [],
- "code": "function isEmptyObject(obj) {\n return Object.keys(obj).length === 0;\n}\n\n// Usage:\nisEmptyObject({}); // Returns: true\nisEmptyObject({ a: 1 }); // Returns: false\n"
- },
- {
- "title": "Compare Two Objects Shallowly",
- "description": "Compares two objects shallowly and returns whether they are equal.",
- "author": "axorax",
- "tags": [
- "object",
- "compare",
- "shallow"
- ],
- "contributors": [],
- "code": "function shallowEqual(obj1, obj2) {\n const keys1 = Object.keys(obj1);\n const keys2 = Object.keys(obj2);\n if (keys1.length !== keys2.length) return false;\n return keys1.every(key => obj1[key] === obj2[key]);\n}\n\n// Usage:\nconst obj1 = { a: 1, b: 2 };\nconst obj2 = { a: 1, b: 2 };\nconst obj3 = { a: 1, b: 3 };\nshallowEqual(obj1, obj2); // Returns: true\nshallowEqual(obj1, obj3); // Returns: false\n"
- },
- {
- "title": "Convert Object to Query String",
- "description": "Converts an object to a query string for use in URLs.",
- "author": "axorax",
- "tags": [
- "object",
- "query string",
- "url"
- ],
- "contributors": [],
- "code": "function toQueryString(obj) {\n return Object.entries(obj)\n .map(([key, value]) => encodeURIComponent(key) + '=' + encodeURIComponent(value))\n .join('&');\n}\n\n// Usage:\nconst params = { search: 'test', page: 1 };\ntoQueryString(params); // Returns: 'search=test&page=1'\n"
- },
- {
- "title": "Count Properties in Object",
- "description": "Counts the number of own properties in an object.",
- "author": "axorax",
- "tags": [
- "object",
- "count",
- "properties"
- ],
- "contributors": [],
- "code": "function countProperties(obj) {\n return Object.keys(obj).length;\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ncountProperties(obj); // Returns: 3\n"
- },
- {
- "title": "Deep Clone Object",
- "description": "Creates a deep copy of an object or array without reference.",
- "author": "jjcantu",
- "tags": [
- "object",
- "clone"
- ],
- "contributors": [],
- "code": "function deepClone(obj) {\n if (obj === null || typeof obj !== 'object') return obj;\n \n const clone = Array.isArray(obj) ? [] : {};\n \n for (let key in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, key)) {\n clone[key] = deepClone(obj[key]);\n }\n }\n \n return clone;\n}\n\n// Usage:\nconst original = { a: 1, b: { c: 2 }, d: [1, 2, 3] };\nconst cloned = deepClone(original);\nconsole.log(cloned); // Output: 'original' but cloned\n"
- },
- {
- "title": "Filter Object",
- "description": "Filter out entries in an object where the value is falsy, including empty strings, empty objects, null, and undefined.",
- "author": "realvishalrana",
- "tags": [
- "object",
- "filter"
- ],
- "contributors": [],
- "code": "export const filterObject = (object = {}) =>\n Object.fromEntries(\n Object.entries(object)\n .filter(([key, value]) => value !== null && value !== undefined && value !== '' && (typeof value !== 'object' || Object.keys(value).length > 0))\n );\n\n// Usage:\nconst obj1 = { a: 1, b: null, c: undefined, d: 4, e: '', f: {} };\nfilterObject(obj1); // Returns: { a: 1, d: 4 }\n\nconst obj2 = { x: 0, y: false, z: 'Hello', w: [] };\nfilterObject(obj2); // Returns: { z: 'Hello' }\n\nconst obj3 = { name: 'John', age: null, address: { city: 'New York' }, phone: '' };\nfilterObject(obj3); // Returns: { name: 'John', address: { city: 'New York' } }\n\nconst obj4 = { a: 0, b: '', c: false, d: {}, e: 'Valid' };\nfilterObject(obj4); // Returns: { e: 'Valid' }\n"
- },
- {
- "title": "Flatten Nested Object",
- "description": "Flattens a nested object into a single-level object with dot notation for keys.",
- "author": "axorax",
- "tags": [
- "object",
- "flatten"
- ],
- "contributors": [],
- "code": "function flattenObject(obj, prefix = '') {\n return Object.keys(obj).reduce((acc, key) => {\n const fullPath = prefix ? `${prefix}.${key}` : key;\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n Object.assign(acc, flattenObject(obj[key], fullPath));\n } else {\n acc[fullPath] = obj[key];\n }\n return acc;\n }, {});\n}\n\n// Usage:\nconst nestedObj = { a: { b: { c: 1 }, d: 2 }, e: 3 };\nflattenObject(nestedObj); // Returns: { 'a.b.c': 1, 'a.d': 2, e: 3 }\n"
- },
- {
- "title": "Freeze Object",
- "description": "Freezes an object to make it immutable.",
- "author": "axorax",
- "tags": [
- "object",
- "freeze",
- "immutable"
- ],
- "contributors": [],
- "code": "function freezeObject(obj) {\n return Object.freeze(obj);\n}\n\n// Usage:\nconst obj = { a: 1, b: 2 };\nconst frozenObj = freezeObject(obj);\nfrozenObj.a = 42; // This will fail silently in strict mode.\nfrozenObj.a; // Returns: 1\n"
- },
- {
- "title": "Get Nested Value",
- "description": "Retrieves the value at a given path in a nested object.",
- "author": "realvishalrana",
- "tags": [
- "object",
- "nested"
- ],
- "contributors": [],
- "code": "const getNestedValue = (obj, path) => {\n const keys = path.split('.');\n return keys.reduce((currentObject, key) => {\n return currentObject && typeof currentObject === 'object' ? currentObject[key] : undefined;\n }, obj);\n};\n\n// Usage:\nconst obj = { a: { b: { c: 42 } } };\ngetNestedValue(obj, 'a.b.c'); // Returns: 42\n"
- },
- {
- "title": "Invert Object Keys and Values",
- "description": "Creates a new object by swapping keys and values of the given object.",
- "author": "axorax",
- "tags": [
- "object",
- "invert"
- ],
- "contributors": [],
- "code": "function invertObject(obj) {\n return Object.fromEntries(\n Object.entries(obj).map(([key, value]) => [value, key])\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\ninvertObject(obj); // Returns: { '1': 'a', '2': 'b', '3': 'c' }\n"
- },
- {
- "title": "Merge Objects Deeply",
- "description": "Deeply merges two or more objects, including nested properties.",
- "author": "axorax",
- "tags": [
- "object",
- "merge",
- "deep"
- ],
- "contributors": [],
- "code": "function deepMerge(...objects) {\n return objects.reduce((acc, obj) => {\n Object.keys(obj).forEach(key => {\n if (typeof obj[key] === 'object' && obj[key] !== null) {\n acc[key] = deepMerge(acc[key] || {}, obj[key]);\n } else {\n acc[key] = obj[key];\n }\n });\n return acc;\n }, {});\n}\n\n// Usage:\nconst obj1 = { a: 1, b: { c: 2 } };\nconst obj2 = { b: { d: 3 }, e: 4 };\ndeepMerge(obj1, obj2); // Returns: { a: 1, b: { c: 2, d: 3 }, e: 4 }\n"
- },
- {
- "title": "Omit Keys from Object",
- "description": "Creates a new object with specific keys omitted.",
- "author": "axorax",
- "tags": [
- "object",
- "omit"
- ],
- "contributors": [],
- "code": "function omitKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => !keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\nomitKeys(obj, ['b', 'c']); // Returns: { a: 1 }\n"
- },
- {
- "title": "Pick Keys from Object",
- "description": "Creates a new object with only the specified keys.",
- "author": "axorax",
- "tags": [
- "object",
- "pick"
- ],
- "contributors": [],
- "code": "function pickKeys(obj, keys) {\n return Object.fromEntries(\n Object.entries(obj).filter(([key]) => keys.includes(key))\n );\n}\n\n// Usage:\nconst obj = { a: 1, b: 2, c: 3 };\npickKeys(obj, ['a', 'c']); // Returns: { a: 1, c: 3 }\n"
- },
- {
- "title": "Unique By Key",
- "description": "Filters an array of objects to only include unique objects by a specified key.",
- "author": "realvishalrana",
- "tags": [
- "array",
- "unique"
- ],
- "contributors": [],
- "code": "const uniqueByKey = (key, arr) =>\n arr.filter((obj, index, self) => index === self.findIndex((t) => t?.[key] === obj?.[key]));\n\n// Usage:\nconst arr = [\n { id: 1, name: 'John' },\n { id: 2, name: 'Jane' },\n { id: 1, name: 'John' }\n];\nuniqueByKey('id', arr); // Returns: [{ id: 1, name: 'John' }, { id: 2, name: 'Jane' }]\n"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "Capitalize String",
- "description": "Capitalizes the first letter of a string.",
- "author": "dostonnabotov",
- "tags": [
- "string",
- "capitalize"
- ],
- "contributors": [],
- "code": "function capitalize(str) {\n return str.charAt(0).toUpperCase() + str.slice(1);\n}\n\n// Usage:\ncapitalize('hello'); // Returns: 'Hello'\n"
- },
- {
- "title": "Check if String is a Palindrome",
- "description": "Checks whether a given string is a palindrome.",
- "author": "axorax",
- "tags": [
- "check",
- "palindrome",
- "string"
- ],
- "contributors": [],
- "code": "function isPalindrome(str) {\n const cleanStr = str.replace(/[^a-zA-Z0-9]/g, '').toLowerCase();\n return cleanStr === cleanStr.split('').reverse().join('');\n}\n\n// Example usage:\nisPalindrome('A man, a plan, a canal, Panama'); // Returns: true\n"
- },
- {
- "title": "Convert String to Camel Case",
- "description": "Converts a given string into camelCase.",
- "author": "aumirza",
- "tags": [
- "string",
- "case",
- "camelCase"
- ],
- "contributors": [],
- "code": "function toCamelCase(str) {\n return str.replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Usage:\ntoCamelCase('hello world test'); // Returns: 'helloWorldTest'\n"
- },
- {
- "title": "Convert String to Param Case",
- "description": "Converts a given string into param-case.",
- "author": "aumirza",
- "tags": [
- "string",
- "case",
- "paramCase"
- ],
- "contributors": [],
- "code": "function toParamCase(str) {\n return str.toLowerCase().replace(/\\s+/g, '-');\n}\n\n// Usage:\ntoParamCase('Hello World Test'); // Returns: 'hello-world-test'\n"
- },
- {
- "title": "Convert String to Pascal Case",
- "description": "Converts a given string into Pascal Case.",
- "author": "aumirza",
- "tags": [
- "string",
- "case",
- "pascalCase"
- ],
- "contributors": [],
- "code": "function toPascalCase(str) {\n return str.replace(/\\b\\w/g, (s) => s.toUpperCase()).replace(/\\W+(.)/g, (match, chr) => chr.toUpperCase());\n}\n\n// Usage:\ntoPascalCase('hello world test'); // Returns: 'HelloWorldTest'\n"
- },
- {
- "title": "Convert String to Snake Case",
- "description": "Converts a given string into snake_case.",
- "author": "axorax",
- "tags": [
- "string",
- "case",
- "snake_case"
- ],
- "contributors": [],
- "code": "function toSnakeCase(str) {\n return str.replace(/([a-z])([A-Z])/g, '$1_$2')\n .replace(/\\s+/g, '_')\n .toLowerCase();\n}\n\n// Usage:\ntoSnakeCase('Hello World Test'); // Returns: 'hello_world_test'\n"
- },
- {
- "title": "Convert String to Title Case",
- "description": "Converts a given string into Title Case.",
- "author": "aumirza",
- "tags": [
- "string",
- "case",
- "titleCase"
- ],
- "contributors": [],
- "code": "function toTitleCase(str) {\n return str.toLowerCase().replace(/\\b\\w/g, (s) => s.toUpperCase());\n}\n\n// Usage:\ntoTitleCase('hello world test'); // Returns: 'Hello World Test'\n"
- },
- {
- "title": "Convert Tabs to Spaces",
- "description": "Converts all tab characters in a string to spaces.",
- "author": "axorax",
- "tags": [
- "string",
- "tabs",
- "spaces"
- ],
- "contributors": [],
- "code": "function tabsToSpaces(str, spacesPerTab = 4) {\n return str.replace(/\\t/g, ' '.repeat(spacesPerTab));\n}\n\n// Usage:\ntabsToSpaces('Hello\\tWorld', 2); // Returns: 'Hello World'\n"
- },
- {
- "title": "Count Words in a String",
- "description": "Counts the number of words in a string.",
- "author": "axorax",
- "tags": [
- "string",
- "manipulation",
- "word count",
- "count"
- ],
- "contributors": [],
- "code": "function countWords(str) {\n return str.trim().split(/\\s+/).length;\n}\n\n// Usage:\ncountWords('Hello world! This is a test.'); // Returns: 6\n"
- },
- {
- "title": "Data with Prefix",
- "description": "Adds a prefix and postfix to data, with a fallback value.",
- "author": "realvishalrana",
- "tags": [
- "data",
- "prefix",
- "postfix",
- "format"
- ],
- "contributors": [],
- "code": "const dataWithPrefix = (data, fallback = '-', prefix = '', postfix = '') => {\n return data ? `${prefix}${data}${postfix}` : fallback;\n};\n\n// Usage:\ndataWithPrefix('123', '-', '(', ')'); // Returns: '(123)'\ndataWithPrefix('', '-', '(', ')'); // Returns: '-'\ndataWithPrefix('Hello', 'N/A', 'Mr. ', ''); // Returns: 'Mr. Hello'\ndataWithPrefix(null, 'N/A', 'Mr. ', ''); // Returns: 'N/A'\n"
- },
- {
- "title": "Extract Initials from Name",
- "description": "Extracts and returns the initials from a full name.",
- "author": "axorax",
- "tags": [
- "string",
- "initials",
- "name"
- ],
- "contributors": [],
- "code": "function getInitials(name) {\n return name.split(' ').map(part => part.charAt(0).toUpperCase()).join('');\n}\n\n// Usage:\ngetInitials('John Doe'); // Returns: 'JD'\n"
- },
- {
- "title": "Generate UUID",
- "description": "Generates a UUID (v4) string.",
- "author": "jjcantu",
- "tags": [
- "uuid",
- "generate",
- "string"
- ],
- "contributors": [],
- "code": "function generateUUID() {\n return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {\n const r = Math.random() * 16 | 0;\n const v = c === 'x' ? r : (r & 0x3 | 0x8);\n return v.toString(16);\n });\n}\n\n// Usage:\nconsole.log(generateUUID()); // Output: \"a1b2c3d4-e5f6-4g7h-8i9j-k0l1m2n3o4p5\"\n"
- },
- {
- "title": "Mask Sensitive Information",
- "description": "Masks parts of a sensitive string, like a credit card or email address.",
- "author": "axorax",
- "tags": [
- "string",
- "mask",
- "sensitive"
- ],
- "contributors": [],
- "code": "function maskSensitiveInfo(str, visibleCount = 4, maskChar = '*') {\n return str.slice(0, visibleCount) + maskChar.repeat(Math.max(0, str.length - visibleCount));\n}\n\n// Usage:\nmaskSensitiveInfo('123456789', 4); // Returns: '1234*****'\nmaskSensitiveInfo('example@mail.com', 2, '#'); // Returns: 'ex#############'\n"
- },
- {
- "title": "Pad String on Both Sides",
- "description": "Pads a string on both sides with a specified character until it reaches the desired length.",
- "author": "axorax",
- "tags": [
- "string",
- "pad",
- "manipulation"
- ],
- "contributors": [],
- "code": "function padString(str, length, char = ' ') {\n const totalPad = length - str.length;\n const padStart = Math.floor(totalPad / 2);\n const padEnd = totalPad - padStart;\n return char.repeat(padStart) + str + char.repeat(padEnd);\n}\n\n// Usage:\npadString('hello', 10, '*'); // Returns: '**hello***'\n"
- },
- {
- "title": "Random string",
- "description": "Generates a random string of characters of a certain length",
- "author": "kruimol",
- "tags": [
- "function",
- "random"
- ],
- "contributors": [],
- "code": "function makeid(length, characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789') {\n return Array.from({ length }, () => characters.charAt(Math.floor(Math.random() * characters.length))).join('');\n}\n\nmakeid(3); // Returns: gDs (Random)\nmakeid(5, \"1234\" /* (optional) */); // Returns: \"35453\" (Random)\n"
- },
- {
- "title": "Remove All Whitespace",
- "description": "Removes all whitespace from a string.",
- "author": "axorax",
- "tags": [
- "string",
- "whitespace"
- ],
- "contributors": [],
- "code": "function removeWhitespace(str) {\n return str.replace(/\\s+/g, '');\n}\n\n// Usage:\nremoveWhitespace('Hello world!'); // Returns: 'Helloworld!'\n"
- },
- {
- "title": "Remove Vowels from a String",
- "description": "Removes all vowels from a given string.",
- "author": "axorax",
- "tags": [
- "string",
- "remove",
- "vowels"
- ],
- "contributors": [],
- "code": "function removeVowels(str) {\n return str.replace(/[aeiouAEIOU]/g, '');\n}\n\n// Usage:\nremoveVowels('Hello World'); // Returns: 'Hll Wrld'\n"
- },
- {
- "title": "Reverse String",
- "description": "Reverses the characters in a string.",
- "author": "dostonnabotov",
- "tags": [
- "string",
- "reverse"
- ],
- "contributors": [],
- "code": "const reverseString = (str) => str.split('').reverse().join('');\n\n// Usage:\nreverseString('hello'); // Returns: 'olleh'\n"
- },
- {
- "title": "Slugify String",
- "description": "Converts a string into a URL-friendly slug format.",
- "author": "dostonnabotov",
- "tags": [
- "string",
- "slug"
- ],
- "contributors": [],
- "code": "const slugify = (string, separator = \"-\") => {\n return string\n .toString() // Cast to string (optional)\n .toLowerCase() // Convert the string to lowercase letters\n .trim() // Remove whitespace from both sides of a string (optional)\n .replace(/\\s+/g, separator) // Replace spaces with {separator}\n .replace(/[^\\w\\-]+/g, \"\") // Remove all non-word chars\n .replace(/\\_/g, separator) // Replace _ with {separator}\n .replace(/\\-\\-+/g, separator) // Replace multiple - with single {separator}\n .replace(/\\-$/g, \"\"); // Remove trailing -\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\nslugify(title); // Returns: 'hello-world-this-is-a-test'\nslugify(title, \"_\"); // Returns: 'hello_world_this_is_a_test'\n"
- },
- {
- "title": "Truncate Text",
- "description": "Truncates the text to a maximum length and appends '...' if the text exceeds the maximum length.",
- "author": "realvishalrana",
- "tags": [
- "string",
- "truncate",
- "text"
- ],
- "contributors": [],
- "code": "const truncateText = (text = '', maxLength = 50) => {\n return `${text.slice(0, maxLength)}${text.length >= maxLength ? '...' : ''}`;\n};\n\n// Usage:\nconst title = \"Hello, World! This is a Test.\";\ntruncateText(title); // Returns: 'Hello, World! This is a Test.'\ntruncateText(title, 10); // Returns: 'Hello, Wor...'\n"
- }
- ]
- }
-]
\ No newline at end of file
diff --git a/public/consolidated/python.json b/public/consolidated/python.json
deleted file mode 100644
index 8acadcfc..00000000
--- a/public/consolidated/python.json
+++ /dev/null
@@ -1,713 +0,0 @@
-[
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "James-Beans",
- "tags": [
- "printing",
- "hello-world"
- ],
- "contributors": [],
- "code": "print(\"Hello, World!\") # Prints Hello, World! to the terminal.\n"
- }
- ]
- },
- {
- "name": "Datetime Utilities",
- "snippets": [
- {
- "title": "Calculate Date Difference in Milliseconds",
- "description": "Calculates the difference between two dates in milliseconds.",
- "author": "e3nviction",
- "tags": [
- "datetime",
- "difference"
- ],
- "contributors": [],
- "code": "from datetime import datetime\n\ndef date_difference_in_millis(date1, date2):\n delta = date2 - date1\n return delta.total_seconds() * 1000\n\n# Usage:\nd1 = datetime(2023, 1, 1, 12, 0, 0)\nd2 = datetime(2023, 1, 1, 12, 1, 0)\ndate_difference_in_millis(d1, d2) # Returns: 60000\n"
- },
- {
- "title": "Check if Date is a Weekend",
- "description": "Checks whether a given date falls on a weekend.",
- "author": "axorax",
- "tags": [
- "datetime",
- "weekend"
- ],
- "contributors": [],
- "code": "from datetime import datetime\n\ndef is_weekend(date):\n try:\n return date.weekday() >= 5 # Saturday = 5, Sunday = 6\n except AttributeError:\n raise TypeError(\"Input must be a datetime object\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nis_weekend(date) # Returns: True (Sunday)\n"
- },
- {
- "title": "Day of the Week String",
- "description": "Gets the string of the day of the week for a given date.",
- "author": "axorax",
- "tags": [
- "datetime",
- "weekday"
- ],
- "contributors": [],
- "code": "from datetime import datetime\n\ndef get_day_of_week(date):\n days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']\n try:\n return days[date.weekday()]\n except IndexError:\n raise ValueError(\"Invalid date\")\n\n# Usage:\ndate = datetime(2023, 1, 1)\nget_day_of_week(date) # Returns: 'Sunday'\n"
- },
- {
- "title": "Generate Date Range List",
- "description": "Generates a list of dates between two given dates.",
- "author": "axorax",
- "tags": [
- "datetime",
- "range"
- ],
- "contributors": [],
- "code": "from datetime import datetime, timedelta\n\ndef generate_date_range(start_date, end_date):\n if start_date > end_date:\n raise ValueError(\"start_date must be before end_date\")\n\n current_date = start_date\n date_list = []\n while current_date <= end_date:\n date_list.append(current_date)\n current_date += timedelta(days=1)\n\n return date_list\n\n# Usage:\nstart = datetime(2023, 1, 1)\nend = datetime(2023, 1, 5)\ndates = generate_date_range(start, end)\nfor d in dates:\n print(d.strftime('%Y-%m-%d'))\n# Outputs: '2023-01-01', '2023-01-02', '2023-01-03', '2023-01-04', '2023-01-05'\n"
- },
- {
- "title": "Get Current Date and Time as String",
- "description": "Fetches the current date and time as a formatted string.",
- "author": "e3nviction",
- "tags": [
- "datetime",
- "current",
- "string"
- ],
- "contributors": [],
- "code": "from datetime import datetime\n\ndef get_current_datetime_string():\n return datetime.now().strftime('%Y-%m-%d %H:%M:%S')\n\n# Usage:\nget_current_datetime_string() # Returns: '2023-01-01 12:00:00'\n"
- },
- {
- "title": "Get Number of Days in a Month",
- "description": "Determines the number of days in a specific month and year.",
- "author": "axorax",
- "tags": [
- "datetime",
- "calendar"
- ],
- "contributors": [],
- "code": "from calendar import monthrange\nfrom datetime import datetime\n\ndef get_days_in_month(year, month):\n try:\n return monthrange(year, month)[1]\n except ValueError as e:\n raise ValueError(f\"Invalid month or year: {e}\")\n\n# Usage:\nget_days_in_month(2023, 2) # Returns: 28 (for non-leap year February)\n"
- },
- {
- "title": "Measure Execution Time",
- "description": "Measures the execution time of a code block.",
- "author": "dostonnabotov",
- "tags": [
- "time",
- "execution"
- ],
- "contributors": [],
- "code": "import time\n\ndef measure_time(func, *args):\n start = time.time()\n result = func(*args)\n end = time.time()\n print(f'Execution time: {end - start:.6f} seconds')\n return result\n\n# Usage:\ndef slow_function():\n time.sleep(2)\n\nmeasure_time(slow_function) # Outputs an execution time of ~2s\n"
- }
- ]
- },
- {
- "name": "Error Handling",
- "snippets": [
- {
- "title": "Create Custom Exception Type",
- "description": "Create a Custom Exception Type that can be called with raise.",
- "author": "mrcool7387",
- "tags": [
- "python",
- "error-creation",
- "organisation",
- "utility"
- ],
- "contributors": [],
- "code": "class ExceptionName(BaseException):\n def __init__(message: str):\n super().__init__(message)\n\n# Usage\na: int = 1\n\nif a > 0:\n raise ExceptionName('Error Message')\n"
- },
- {
- "title": "Retry Function Execution on Exception",
- "description": "Retries a function execution a specified number of times if it raises an exception.",
- "author": "axorax",
- "tags": [
- "error-handling",
- "retry"
- ],
- "contributors": [],
- "code": "import time\n\ndef retry(func, retries=3, delay=1):\n for attempt in range(retries):\n try:\n return func()\n except Exception as e:\n print(f\"Attempt {attempt + 1} failed: {e}\")\n time.sleep(delay)\n raise Exception(\"All retry attempts failed\")\n\n# Usage:\ndef unstable_function():\n raise ValueError(\"Simulated failure\")\n\n# Retry 3 times with 2 seconds delay:\ntry:\n retry(unstable_function, retries=3, delay=2)\nexcept Exception as e:\n print(e) # Output: All retry attempts failed\n"
- }
- ]
- },
- {
- "name": "File Handling",
- "snippets": [
- {
- "title": "Find Files",
- "description": "Finds all files of the specified type within a given directory.",
- "author": "Jackeastern",
- "tags": [
- "os",
- "filesystem",
- "file_search"
- ],
- "contributors": [],
- "code": "import os\n\ndef find_files(directory, file_type):\n file_type = file_type.lower() # Convert file_type to lowercase\n found_files = []\n\n for root, _, files in os.walk(directory):\n for file in files:\n file_ext = os.path.splitext(file)[1].lower()\n if file_ext == file_type:\n full_path = os.path.join(root, file)\n found_files.append(full_path)\n\n return found_files\n\n# Example Usage:\nfind_files('/path/to/your/directory', '.pdf') # Returns all .pdf in directory\n"
- },
- {
- "title": "Get File Extension",
- "description": "Gets the extension of a file.",
- "author": "axorax",
- "tags": [
- "file",
- "extension"
- ],
- "contributors": [],
- "code": "import os\n\ndef get_file_extension(filepath):\n return os.path.splitext(filepath)[1]\n\n# Usage:\nget_file_extension('example.txt') # Returns: '.txt'\n"
- },
- {
- "title": "List Files in Directory",
- "description": "Lists all files in a specified directory.",
- "author": "axorax",
- "tags": [
- "file",
- "list",
- "directory"
- ],
- "contributors": [],
- "code": "import os\n\ndef list_files(directory):\n return [f for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]\n\n# Usage:\nlist_files('/path/to/directory') # Returns: List of file in the directory\n"
- },
- {
- "title": "Read File in Chunks",
- "description": "Reads a file in chunks of a specified size.",
- "author": "axorax",
- "tags": [
- "file",
- "read",
- "chunks"
- ],
- "contributors": [],
- "code": "def read_file_in_chunks(filepath, chunk_size):\n with open(filepath, 'r') as file:\n while chunk := file.read(chunk_size):\n yield chunk\n\n# Usage:\nfor chunk in read_file_in_chunks('example.txt', 1024):\n print(chunk) # Outputs: Chucks of 1024 bytes\n"
- }
- ]
- },
- {
- "name": "Json Manipulation",
- "snippets": [
- {
- "title": "Filter JSON Data",
- "description": "Filters a JSON object based on a condition and returns the filtered data.",
- "author": "axorax",
- "tags": [
- "json",
- "filter",
- "data"
- ],
- "contributors": [],
- "code": "import json\n\ndef filter_json_data(filepath, condition):\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Filter data based on the provided condition\n filtered_data = [item for item in data if condition(item)]\n\n return filtered_data\n\n# Usage:\ncondition = lambda x: x['age'] > 25\nfilter_json_data('data.json', condition) # Returns: `data.json` filtered with `condition`\n"
- },
- {
- "title": "Flatten Nested JSON",
- "description": "Flattens a nested JSON object into a flat dictionary.",
- "author": "axorax",
- "tags": [
- "json",
- "flatten",
- "nested"
- ],
- "contributors": [],
- "code": "def flatten_json(nested_json, prefix=''):\n flat_dict = {}\n for key, value in nested_json.items():\n if isinstance(value, dict):\n flat_dict.update(flatten_json(value, prefix + key + '.'))\n else:\n flat_dict[prefix + key] = value\n return flat_dict\n\n# Usage:\nnested_json = {'name': 'John', 'address': {'city': 'New York', 'zip': '10001'}}\nflatten_json(nested_json) # Returns: {'name': 'John', 'address.city': 'New York', 'address.zip': '10001'}\n"
- },
- {
- "title": "Merge Multiple JSON Files",
- "description": "Merges multiple JSON files into one and writes the merged data into a new file.",
- "author": "axorax",
- "tags": [
- "json",
- "merge",
- "file"
- ],
- "contributors": [],
- "code": "import json\n\ndef merge_json_files(filepaths, output_filepath):\n merged_data = []\n\n # Read each JSON file and merge their data\n for filepath in filepaths:\n with open(filepath, 'r') as file:\n data = json.load(file)\n merged_data.extend(data)\n\n # Write the merged data into a new file\n with open(output_filepath, 'w') as file:\n json.dump(merged_data, file, indent=4)\n\n# Usage:\nfiles_to_merge = ['file1.json', 'file2.json']\nmerge_json_files(files_to_merge, 'merged.json')\n"
- },
- {
- "title": "Read JSON File",
- "description": "Reads a JSON file and parses its content.",
- "author": "e3nviction",
- "tags": [
- "json",
- "file",
- "read"
- ],
- "contributors": [],
- "code": "import json\n\ndef read_json(filepath):\n with open(filepath, 'r') as file:\n return json.load(file)\n\n# Usage:\nread_json('data.json') # Returns: Content of file as dict\n"
- },
- {
- "title": "Update JSON File",
- "description": "Updates an existing JSON file with new data or modifies the existing values.",
- "author": "axorax",
- "tags": [
- "json",
- "update",
- "file"
- ],
- "contributors": [],
- "code": "import json\n\ndef update_json(filepath, new_data):\n # Read the existing JSON data\n with open(filepath, 'r') as file:\n data = json.load(file)\n\n # Update the data with the new content\n data.update(new_data)\n\n # Write the updated data back to the JSON file\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\nnew_data = {'age': 31}\nupdate_json('data.json', new_data) # Updates `age` in `data.json` without modifying other keys\n"
- },
- {
- "title": "Write JSON File",
- "description": "Writes a dictionary to a JSON file.",
- "author": "e3nviction",
- "tags": [
- "json",
- "file",
- "write"
- ],
- "contributors": [],
- "code": "import json\n\ndef write_json(filepath, data):\n with open(filepath, 'w') as file:\n json.dump(data, file, indent=4)\n\n# Usage:\ndata = {'name': 'John', 'age': 30}\nwrite_json('data.json', data)\n"
- }
- ]
- },
- {
- "name": "List Manipulation",
- "snippets": [
- {
- "title": "Find Duplicates in a List",
- "description": "Identifies duplicate elements in a list.",
- "author": "axorax",
- "tags": [
- "list",
- "duplicates"
- ],
- "contributors": [],
- "code": "def find_duplicates(lst):\n seen = set()\n duplicates = set()\n for item in lst:\n if item in seen:\n duplicates.add(item)\n else:\n seen.add(item)\n return list(duplicates)\n\n# Usage:\ndata = [1, 2, 3, 2, 4, 5, 1]\nfind_duplicates(data) # Returns: [1, 2]\n"
- },
- {
- "title": "Find Intersection of Two Lists",
- "description": "Finds the common elements between two lists.",
- "author": "axorax",
- "tags": [
- "list",
- "intersection"
- ],
- "contributors": [],
- "code": "def list_intersection(lst1, lst2):\n return [item for item in lst1 if item in lst2]\n\n# Usage:\nlist_a = [1, 2, 3, 4]\nlist_b = [3, 4, 5, 6]\nlist_intersection(list_a, list_b) # Returns: [3, 4]\n"
- },
- {
- "title": "Find Maximum Difference in List",
- "description": "Finds the maximum difference between any two elements in a list.",
- "author": "axorax",
- "tags": [
- "list",
- "difference"
- ],
- "contributors": [],
- "code": "def max_difference(lst):\n if not lst or len(lst) < 2:\n return 0\n return max(lst) - min(lst)\n\n# Usage:\ndata = [10, 3, 5, 20, 7]\nmax_difference(data) # Returns: 17\n"
- },
- {
- "title": "Flatten Nested List",
- "description": "Flattens a multi-dimensional list into a single list.",
- "author": "dostonnabotov",
- "tags": [
- "list",
- "flatten"
- ],
- "contributors": [],
- "code": "def flatten_list(lst):\n return [item for sublist in lst for item in sublist]\n\n# Usage:\nnested_list = [[1, 2], [3, 4], [5]]\nflatten_list(nested_list) # Returns: [1, 2, 3, 4, 5]\n"
- },
- {
- "title": "Flatten Unevenly Nested Lists",
- "description": "Converts unevenly nested lists of any depth into a single flat list.",
- "author": "agilarasu",
- "tags": [
- "list",
- "flattening",
- "nested-lists",
- "depth"
- ],
- "contributors": [],
- "code": "def flatten(nested_list):\n for item in nested_list:\n if isinstance(item, list):\n yield from flatten(item)\n else:\n yield item\n\n# Usage:\nnested_list = [1, [2, [3, 4]], 5]\nlist(flatten(nested_list)) # Returns: [1, 2, 3, 4, 5]\n"
- },
- {
- "title": "Partition List",
- "description": "Partitions a list into sublists of a given size.",
- "author": "axorax",
- "tags": [
- "list",
- "partition"
- ],
- "contributors": [],
- "code": "def partition_list(lst, size):\n for i in range(0, len(lst), size):\n yield lst[i:i + size]\n\n# Usage:\ndata = [1, 2, 3, 4, 5, 6, 7]\nlist(partition_list(data, 3)) # Returns: [[1, 2, 3], [4, 5, 6], [7]]\n"
- },
- {
- "title": "Remove Duplicates",
- "description": "Removes duplicate elements from a list while maintaining order.",
- "author": "dostonnabotov",
- "tags": [
- "list",
- "duplicates",
- "filter"
- ],
- "contributors": [],
- "code": "def remove_duplicates(lst):\n return list(dict.fromkeys(lst))\n\n# Usage:\nremove_duplicates([1, 2, 2, 3, 4, 4, 5]) # Returns: [1, 2, 3, 4, 5]\n"
- }
- ]
- },
- {
- "name": "Math And Numbers",
- "snippets": [
- {
- "title": "Calculate Compound Interest",
- "description": "Calculates compound interest for a given principal amount, rate, and time period.",
- "author": "axorax",
- "tags": [
- "python",
- "math",
- "compound interest",
- "finance"
- ],
- "contributors": [],
- "code": "def compound_interest(principal, rate, time, n=1):\n return principal * (1 + rate / n) ** (n * time)\n\n# Usage:\ncompound_interest(1000, 0.05, 5) # Returns: 1276.2815625000003\ncompound_interest(1000, 0.05, 5, 12) # Returns: 1283.68\n"
- },
- {
- "title": "Check Perfect Square",
- "description": "Checks if a number is a perfect square.",
- "author": "axorax",
- "tags": [
- "math",
- "perfect square",
- "check"
- ],
- "contributors": [],
- "code": "def is_perfect_square(n):\n if n < 0:\n return False\n root = int(n**0.5)\n return root * root == n\n\n# Usage:\nis_perfect_square(16) # Returns: True\nis_perfect_square(20) # Returns: False\n"
- },
- {
- "title": "Check Prime Number",
- "description": "Checks if a number is a prime number.",
- "author": "dostonnabotov",
- "tags": [
- "math",
- "prime",
- "check"
- ],
- "contributors": [],
- "code": "def is_prime(n):\n if n <= 1:\n return False\n for i in range(2, int(n**0.5) + 1):\n if n % i == 0:\n return False\n return True\n\n# Usage:\nis_prime(17) # Returns: True\n"
- },
- {
- "title": "Convert Binary to Decimal",
- "description": "Converts a binary string to its decimal equivalent.",
- "author": "axorax",
- "tags": [
- "math",
- "binary",
- "decimal",
- "conversion"
- ],
- "contributors": [],
- "code": "def binary_to_decimal(binary_str):\n return int(binary_str, 2)\n\n# Usage:\nbinary_to_decimal('1010') # Returns: 10\nbinary_to_decimal('1101') # Returns: 13\n"
- },
- {
- "title": "Convert Bytes to Human-Readable Format",
- "description": "Converts a size in bytes to a human-readable format.",
- "author": "axorax",
- "tags": [
- "bytes",
- "format"
- ],
- "contributors": [],
- "code": "def bytes_to_human_readable(num):\n for unit in ['B', 'KB', 'MB', 'GB', 'TB', 'PB']:\n if num < 1024:\n return f\"{num:.2f} {unit}\"\n num /= 1024\n\n# Usage:\nbytes_to_human_readable(123456789) # Returns: '117.74 MB'\n"
- },
- {
- "title": "Find LCM (Least Common Multiple)",
- "description": "Calculates the least common multiple (LCM) of two numbers.",
- "author": "axorax",
- "tags": [
- "python",
- "math",
- "lcm",
- "gcd",
- "utility"
- ],
- "contributors": [],
- "code": "def lcm(a, b):\n return abs(a * b) // gcd(a, b)\n\n# Usage:\nlcm(12, 15) # Returns: 60\nlcm(7, 5) # Returns: 35\n"
- },
- {
- "title": "Solve Quadratic Equation",
- "description": "Solves a quadratic equation ax^2 + bx + c = 0 and returns the roots.",
- "author": "axorax",
- "tags": [
- "math",
- "quadratic",
- "equation",
- "solver"
- ],
- "contributors": [],
- "code": "import cmath\n\ndef solve_quadratic(a, b, c):\n discriminant = cmath.sqrt(b**2 - 4 * a * c)\n root1 = (-b + discriminant) / (2 * a)\n root2 = (-b - discriminant) / (2 * a)\n return root1, root2\n\n# Usage:\nsolve_quadratic(1, -3, 2) # Returns: ((2+0j), (1+0j))\nsolve_quadratic(1, 2, 5) # Returns: ((-1+2j), (-1-2j))\n"
- }
- ]
- },
- {
- "name": "Sqlite Database",
- "snippets": [
- {
- "title": "Create SQLite Database Table",
- "description": "Creates a table in an SQLite database with a dynamic schema.",
- "author": "e3nviction",
- "tags": [
- "sqlite",
- "database",
- "table"
- ],
- "contributors": [],
- "code": "import sqlite3\n\ndef create_table(db_name, table_name, schema):\n conn = sqlite3.connect(db_name)\n cursor = conn.cursor()\n schema_string = ', '.join([f'{col} {dtype}' for col, dtype in schema.items()])\n cursor.execute(f'''\n CREATE TABLE IF NOT EXISTS {table_name} (\n {schema_string}\n )''')\n conn.commit()\n conn.close()\n\n# Usage:\ndb_name = 'example.db'\ntable_name = 'users'\nschema = {\n 'id': 'INTEGER PRIMARY KEY',\n 'name': 'TEXT',\n 'age': 'INTEGER',\n 'email': 'TEXT'\n}\ncreate_table(db_name, table_name, schema)\n"
- },
- {
- "title": "Insert Data into Sqlite Table",
- "description": "Inserts a row into a specified SQLite table using a dictionary of fields and values.",
- "author": "e3nviction",
- "tags": [
- "sqlite",
- "database"
- ],
- "contributors": [],
- "code": "import sqlite3\n\ndef insert_into_table(db_path, table_name, data):\n with sqlite3.connect(db_path) as conn:\n columns = ', '.join(data.keys())\n placeholders = ', '.join(['?'] * len(data))\n sql = f\"INSERT INTO {table_name} ({columns}) VALUES ({placeholders})\"\n conn.execute(sql, tuple(data.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ndata = {\n 'name': 'John Doe',\n 'email': 'john@example.com',\n 'age': 30\n}\ninsert_into_table(db_path, table_name, data)\n"
- },
- {
- "title": "Query Data from Sqlite Table",
- "description": "Fetches data from a specified SQLite table, with options for selecting specific columns and applying a WHERE clause.",
- "author": "pl44t",
- "tags": [
- "sqlite",
- "database"
- ],
- "contributors": [],
- "code": "import sqlite3\n\ndef query_table(db_path, table_name, columns='*', where_clause=None):\n with sqlite3.connect(db_path) as conn:\n cursor = conn.cursor()\n sql = f\"SELECT {columns} FROM {table_name}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n cursor.execute(sql)\n return cursor.fetchall()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\ncolumns = 'id, name, email'\nwhere_clause = 'age > 25'\nresult = query_table(db_path, table_name, columns, where_clause)\nfor row in result:\n print(row)\n\n"
- },
- {
- "title": "Update Records in Sqlite Table",
- "description": "Updates records in a specified SQLite table, allowing dynamic column updates and an optional WHERE clause.",
- "author": "pl44t",
- "tags": [
- "sqlite",
- "database"
- ],
- "contributors": [],
- "code": "import sqlite3\n\ndef update_table(db_path, table_name, updates, where_clause=None):\n with sqlite3.connect(db_path) as conn:\n set_clause = ', '.join([f\"{col} = ?\" for col in updates.keys()])\n sql = f\"UPDATE {table_name} SET {set_clause}\"\n if where_clause:\n sql += f\" WHERE {where_clause}\"\n conn.execute(sql, tuple(updates.values()))\n conn.commit()\n\n# Usage:\ndb_path = 'example.db'\ntable_name = 'users'\nupdates = {'name': 'Jane Doe', 'age': 28}\nwhere_clause = \"id = 1\"\nupdate_table(db_path, table_name, updates, where_clause)\n\n"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "Capitalize Words",
- "description": "Capitalizes the first letter of each word in a string.",
- "author": "axorax",
- "tags": [
- "string",
- "capitalize"
- ],
- "contributors": [],
- "code": "def capitalize_words(s):\n return ' '.join(word.capitalize() for word in s.split())\n\n# Usage:\ncapitalize_words('hello world') # Returns: 'Hello World'\n"
- },
- {
- "title": "Check Anagram",
- "description": "Checks if two strings are anagrams of each other.",
- "author": "SteliosGee",
- "tags": [
- "string",
- "anagram",
- "check"
- ],
- "contributors": [],
- "code": "def is_anagram(s1, s2):\n return sorted(s1) == sorted(s2)\n\n# Usage:\nis_anagram('listen', 'silent') # Returns: True\n"
- },
- {
- "title": "Check Palindrome",
- "description": "Checks if a string is a palindrome.",
- "author": "dostonnabotov",
- "tags": [
- "string",
- "palindrome"
- ],
- "contributors": [],
- "code": "def is_palindrome(s):\n s = s.lower().replace(' ', '')\n return s == s[::-1]\n\n# Usage:\nis_palindrome('A man a plan a canal Panama') # Returns: True\n"
- },
- {
- "title": "Convert Snake Case to Camel Case",
- "description": "Converts a snake_case string to camelCase.",
- "author": "axorax",
- "tags": [
- "string",
- "snake-case",
- "camel-case",
- "convert"
- ],
- "contributors": [],
- "code": "def snake_to_camel(s):\n parts = s.split('_')\n return parts[0] + ''.join(word.capitalize() for word in parts[1:])\n\n# Usage:\nsnake_to_camel('hello_world') # Returns: 'helloWorld'\n"
- },
- {
- "title": "Convert String to ASCII",
- "description": "Converts a string into its ASCII representation.",
- "author": "axorax",
- "tags": [
- "string",
- "ascii",
- "convert"
- ],
- "contributors": [],
- "code": "def string_to_ascii(s):\n return [ord(char) for char in s]\n\n# Usage:\nstring_to_ascii('hello') # Returns: [104, 101, 108, 108, 111]\n"
- },
- {
- "title": "Count Character Frequency",
- "description": "Counts the frequency of each character in a string.",
- "author": "axorax",
- "tags": [
- "string",
- "character-frequency"
- ],
- "contributors": [],
- "code": "from collections import Counter\n\ndef char_frequency(s):\n return dict(Counter(s))\n\n# Usage:\nchar_frequency('hello') # Returns: {'h': 1, 'e': 1, 'l': 2, 'o': 1}\n"
- },
- {
- "title": "Count Vowels",
- "description": "Counts the number of vowels in a string.",
- "author": "SteliosGee",
- "tags": [
- "string",
- "vowels",
- "count"
- ],
- "contributors": [],
- "code": "def count_vowels(s):\n vowels = 'aeiou'\n return len([char for char in s.lower() if char in vowels])\n\n# Usage:\ncount_vowels('hello') # Returns: 2\n"
- },
- {
- "title": "Count Words",
- "description": "Counts the number of words in a string.",
- "author": "axorax",
- "tags": [
- "string",
- "word-count"
- ],
- "contributors": [],
- "code": "def count_words(s):\n return len(s.split())\n\n# Usage:\ncount_words('The quick brown fox') # Returns: 4\n"
- },
- {
- "title": "Find All Substrings",
- "description": "Finds all substrings of a given string.",
- "author": "axorax",
- "tags": [
- "string",
- "substring",
- "find"
- ],
- "contributors": [],
- "code": "def find_substrings(s):\n substrings = []\n for i in range(len(s)):\n for j in range(i + 1, len(s) + 1):\n substrings.append(s[i:j])\n return substrings\n\n# Usage:\nfind_substrings('abc') # Returns: ['a', 'ab', 'abc', 'b', 'bc', 'c']\n"
- },
- {
- "title": "Find Longest Word",
- "description": "Finds the longest word in a string.",
- "author": "axorax",
- "tags": [
- "string",
- "longest-word"
- ],
- "contributors": [],
- "code": "def find_longest_word(s):\n words = s.split()\n return max(words, key=len) if words else ''\n\n# Usage:\nfind_longest_word('The quick brown fox') # Returns: 'quick'\n"
- },
- {
- "title": "Find Unique Characters",
- "description": "Finds all unique characters in a string.",
- "author": "axorax",
- "tags": [
- "string",
- "unique",
- "characters"
- ],
- "contributors": [],
- "code": "def find_unique_chars(s):\n return ''.join(sorted(set(s)))\n\n# Usage:\nfind_unique_chars('banana') # Results: 'abn'\n"
- },
- {
- "title": "Generate Random String",
- "description": "Generates a random alphanumeric string.",
- "author": "dostonnabotov",
- "tags": [
- "random",
- "string"
- ],
- "contributors": [],
- "code": "import random\nimport string\n\ndef random_string(length):\n letters_and_digits = string.ascii_letters + string.digits\n return ''.join(random.choice(letters_and_digits) for _ in range(length))\n\n# Usage:\nrandom_string(10) # Results: Random 10-character string\n"
- },
- {
- "title": "Remove Duplicate Characters",
- "description": "Removes duplicate characters from a string while maintaining the order.",
- "author": "axorax",
- "tags": [
- "string",
- "duplicates",
- "remove"
- ],
- "contributors": [],
- "code": "def remove_duplicate_chars(s):\n seen = set()\n return ''.join(char for char in s if not (char in seen or seen.add(char)))\n\n# Usage:\nremove_duplicate_chars('programming') # Returns: 'progamin'\n"
- },
- {
- "title": "Remove Punctuation",
- "description": "Removes punctuation from a string.",
- "author": "SteliosGee",
- "tags": [
- "string",
- "punctuation",
- "remove"
- ],
- "contributors": [],
- "code": "import string\n\ndef remove_punctuation(s):\n return s.translate(str.maketrans('', '', string.punctuation))\n\n# Usage:\nremove_punctuation('Hello, World!') # Returns: 'Hello World'\n"
- },
- {
- "title": "Remove Specific Characters",
- "description": "Removes specific characters from a string.",
- "author": "axorax",
- "tags": [
- "string",
- "remove",
- "characters"
- ],
- "contributors": [],
- "code": "def remove_chars(s, chars):\n return ''.join(c for c in s if c not in chars)\n\n# Usage:\nremove_chars('hello world', 'eo') # Returns: 'hll wrld'\n"
- },
- {
- "title": "Remove Whitespace",
- "description": "Removes all whitespace from a string.",
- "author": "axorax",
- "tags": [
- "string",
- "whitespace",
- "remove"
- ],
- "contributors": [],
- "code": "def remove_whitespace(s):\n return ''.join(s.split())\n\n# Usage:\nremove_whitespace('hello world') # Returns: 'helloworld'\n"
- },
- {
- "title": "Reverse String",
- "description": "Reverses the characters in a string.",
- "author": "dostonnabotov",
- "tags": [
- "string",
- "reverse"
- ],
- "contributors": [],
- "code": "def reverse_string(s):\n return s[::-1]\n\n# Usage:\nreverse_string('hello') # Returns: 'olleh'\n"
- },
- {
- "title": "Split Camel Case",
- "description": "Splits a camel case string into separate words.",
- "author": "axorax",
- "tags": [
- "string",
- "camel-case",
- "split"
- ],
- "contributors": [],
- "code": "import re\n\ndef split_camel_case(s):\n return ' '.join(re.findall(r'[A-Z][a-z]*|[a-z]+', s))\n\n# Usage:\nsplit_camel_case('camelCaseString') # Returns: 'camel Case String'\n"
- },
- {
- "title": "Truncate String",
- "description": "Truncates a string to a specified length and adds an ellipsis.",
- "author": "axorax",
- "tags": [
- "string",
- "truncate"
- ],
- "contributors": [],
- "code": "def truncate_string(s, length):\n return s[:length] + '...' if len(s) > length else s\n\n# Usage:\ntruncate_string('This is a long string', 10) # Returns: 'This is a ...'\n"
- }
- ]
- }
-]
\ No newline at end of file
diff --git a/public/consolidated/regex.json b/public/consolidated/regex.json
deleted file mode 100644
index 201f84ae..00000000
--- a/public/consolidated/regex.json
+++ /dev/null
@@ -1,74 +0,0 @@
-[
- {
- "name": "Miscellaneous",
- "snippets": [
- {
- "title": "Hexadecimal Color",
- "description": "Matches hex color codes",
- "author": "majvax",
- "tags": [
- "color",
- "hexadecimal"
- ],
- "contributors": [],
- "code": "^#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$\n\n\n-> Usage:\n#FFF1 ✗\n#FFF ✓\n#FFF000 ✓\n"
- },
- {
- "title": "IPv4",
- "description": "Matches IPv4 address",
- "author": "majvax",
- "tags": [
- "ipv4",
- "networking"
- ],
- "contributors": [],
- "code": "^((25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})\\.){3}(25[0-5]|2[0-4]\\d|1\\d{2}|\\d{1,2})$\n\n\n-> Usage:\n123.300.0.101 ✗\n127.0.0.1 ✓\n192.168.0.1 ✓\n"
- },
- {
- "title": "Unintentional Duplication",
- "description": "Matches duplicated word in a text.",
- "author": "majvax",
- "tags": [
- "duplication"
- ],
- "contributors": [],
- "code": "\\b(\\w+)\\s+\\1\\b\n\n\n-> Usage:\nI need to finish this task ✗\nI need to to finish this task ✓\n"
- },
- {
- "title": "Whitespace Trimmer",
- "description": "Matches leading and/or trailing whitespace.",
- "author": "majvax",
- "tags": [
- "trim"
- ],
- "contributors": [],
- "code": "^\\s+|\\s+$\n\n\n-> Usage:\n(don't account for the quotation marks, it just to visualize whitespace)\n\"Hello World\" ✗\n\" Hello World\" ✓\n\"Hello World \" ✓\n\" Hello World \" ✓\n"
- }
- ]
- },
- {
- "name": "Validation pattern",
- "snippets": [
- {
- "title": "Email Address",
- "description": "Match any email address",
- "author": "majvax",
- "tags": [
- "email"
- ],
- "contributors": [],
- "code": "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$\n\n-> Usage:\nexample.name@domain.com.ru ✓\nname.surname@gmail.com ✓\n"
- },
- {
- "title": "Strong Password",
- "description": "Match password with at least 12 characters, one uppercased letter, one number, and one special character.",
- "author": "majvax",
- "tags": [
- "password"
- ],
- "contributors": [],
- "code": "^(?=.*[A-Z])(?=.*[a-z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{12,}$\n\n-> Usage:\nlongpassword ✗\nlongpassw0rd ✗\nlongp@ssw0rd ✗\nLongp@ssw0rd ✓\n"
- }
- ]
- }
-]
\ No newline at end of file
diff --git a/public/consolidated/ruby.json b/public/consolidated/ruby.json
deleted file mode 100644
index 90a66a2c..00000000
--- a/public/consolidated/ruby.json
+++ /dev/null
@@ -1,222 +0,0 @@
-[
- {
- "name": "Array Manipulation",
- "snippets": [
- {
- "title": "Binary Search",
- "description": "Searches for an element in a sorted array using binary search.",
- "author": "ACR1209",
- "tags": [
- "array",
- "binary-search",
- "search"
- ],
- "contributors": [],
- "code": "def binary_search(array, target)\n low = 0\n high = array.length - 1\n\n while low <= high\n mid = (low + high) / 2\n guess = array[mid]\n\n if guess == target\n return mid\n elsif guess > target\n high = mid - 1\n else\n low = mid + 1\n end\n end\n\n return nil\nend\n\n# Usage:\narray = [1, 3, 5, 7, 9]\ntarget = 5\nresult = binary_search(array, target)\nputs result # Output: 2\n"
- },
- {
- "title": "Chunk Array",
- "description": "Splits an array into chunks of a specified size.",
- "author": "ACR1209",
- "tags": [
- "array",
- "chunk"
- ],
- "contributors": [],
- "code": "def chunk_array(array, size)\n array.each_slice(size).to_a\nend\n\n# Usage:\narr = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nchunked_arr = chunk_array(arr, 2)\nputs chunked_arr.inspect # Output: [[1, 2], [3, 4], [5, 6], [7, 8], [9]]\n"
- },
- {
- "title": "Matrix Transpose",
- "description": "Transposes a 2D matrix.",
- "author": "ACR1209",
- "tags": [
- "array",
- "matrix",
- "transpose"
- ],
- "contributors": [],
- "code": "def transpose_matrix(matrix)\n return [] if matrix.empty?\n return [] if matrix.first.empty?\n\n matrix.first.zip(*matrix[1..-1])\nend\n\n# Usage:\nmatrix = [\n [1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]\n]\nprint transpose_matrix(matrix) # Output: [[1, 4, 7], [2, 5, 8], [3, 6, 9]]\n"
- }
- ]
- },
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "ACR1209",
- "tags": [
- "printing",
- "hello-world",
- "utility"
- ],
- "contributors": [],
- "code": "puts 'Hello, World!'\n"
- }
- ]
- },
- {
- "name": "Error Handling",
- "snippets": [
- {
- "title": "Custom Error Class",
- "description": "Defines and raises a custom error class in Ruby.",
- "author": "ACR1209",
- "tags": [
- "error handling",
- "custom error"
- ],
- "contributors": [],
- "code": "class MyCustomError < StandardError; end\n\ndef risky_method(value)\n raise MyCustomError, \"Value must be positive\" if value <= 0\n \"Valid value: #{value}\"\nend\n\n# Usage:\nbegin\n puts risky_method(-1)\nrescue MyCustomError => e\n puts e.message # Output: \"Value must be positive\"\nend\n"
- }
- ]
- },
- {
- "name": "Math And Numbers",
- "snippets": [
- {
- "title": "Calculate Compound Interest",
- "description": "Calculates compound interest for a given principal amount, rate, and time period.",
- "author": "ACR1209",
- "tags": [
- "math",
- "compound interest",
- "finance"
- ],
- "contributors": [
- "axorax"
- ],
- "code": "def compound_interest(principal, rate, time, n = 1)\n principal * (1 + rate / n) ** (n * time)\nend\n\n# Usage:\nputs compound_interest(1000, 0.05, 5) # Output: 1276.2815625000003\nputs compound_interest(1000, 0.05, 5, 12) # Output: 1283.3586785035118\n"
- },
- {
- "title": "Calculate Factorial",
- "description": "Computes the factorial of a given integer.",
- "author": "ACR1209",
- "tags": [
- "math",
- "factorial"
- ],
- "contributors": [],
- "code": "def factorial(n)\n return 1 if n <= 1\n (2..n).reduce(1, :*)\nend\n\n# Usage:\nputs factorial(5) # Output: 120\n"
- },
- {
- "title": "Check Prime Number",
- "description": "Checks if a number is a prime number.",
- "author": "ACR1209",
- "tags": [
- "math",
- "prime",
- "check"
- ],
- "contributors": [
- "dostonnabotov"
- ],
- "code": "def is_prime?(n)\n return false if n <= 1\n (2..Math.sqrt(n)).each do |i|\n return false if n % i == 0\n end\n true\nend\n\n# Usage:\nputs is_prime?(29) # Output: true\nputs is_prime?(30) # Output: false\n"
- },
- {
- "title": "Find all primes up to integer (Sieve of Sundaram)",
- "description": "Finds all the prime numbers up to a specific integer.",
- "author": "ACR1209",
- "tags": [
- "math",
- "prime numbers"
- ],
- "contributors": [],
- "code": "def sieve_of_sundaram(limit)\n n = (limit - 1) / 2\n marked = Array.new(n + 1, false)\n\n (1..n).each do |i|\n j = i\n while (i + j + 2 * i * j) <= n\n marked[i + j + 2 * i * j] = true\n j += 1\n end\n end\n\n primes = [2]\n (1..n).each do |i|\n primes << (2 * i + 1) unless marked[i]\n end\n\n primes\nend\n\n# Usage:\nprint sieve_of_sundaram(30) # Output: [2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\n"
- }
- ]
- },
- {
- "name": "String Manipulation",
- "snippets": [
- {
- "title": "Capitalize Words",
- "description": "Capitalizes the first letter of each word in a string.",
- "author": "ACR1209",
- "tags": [
- "string",
- "capitalize",
- "words"
- ],
- "contributors": [],
- "code": "def capitalize_words(str)\n str.split.map(&:capitalize).join(' ')\nend\n\n# Usage:\nsentence = \"ruby is awesome\"\nputs capitalize_words(sentence) # Output: \"Ruby Is Awesome\"\n"
- },
- {
- "title": "Count Word Occurrences in String",
- "description": "Counts the occurrences of each word in a given string.",
- "author": "ACR1209",
- "tags": [
- "string",
- "occurrences",
- "word-count"
- ],
- "contributors": [],
- "code": "def count_word_occurrences(text)\n words = text.downcase.scan(/\\w+/)\n occurrences = Hash.new(0)\n words.each { |word| occurrences[word] += 1 }\n occurrences\nend\n\n# Usage:\ntext = \"ruby is awesome and Ruby is fun\"\nputs count_word_occurrences(text) # Output: {\"ruby\"=>2, \"is\"=>2, \"awesome\"=>1, \"and\"=>1, \"fun\"=>1}\n"
- },
- {
- "title": "Remove Punctuation",
- "description": "Removes all punctuation from a given string.",
- "author": "ACR1209",
- "tags": [
- "string",
- "punctuation",
- "remove"
- ],
- "contributors": [],
- "code": "def remove_punctuation(str)\n str.gsub(/[[:punct:]]/, '')\nend\n\n# Usage:\ntext = \"Hello, Ruby! How's it going?\"\nputs remove_punctuation(text) # Output: \"Hello Ruby Hows it going\"\n"
- },
- {
- "title": "Transform Camel Case to Snake Case",
- "description": "Converts a Camel or Pascal Case string to Snake case.",
- "author": "ACR1209",
- "tags": [
- "string",
- "convert",
- "camel-case",
- "snake-case",
- "pascal-case"
- ],
- "contributors": [],
- "code": "def camel_to_snake(str)\n str.gsub(/([A-Z])/, '_\\1').sub(/^_/, '').downcase\nend\n\n# Usage:\ncamel_case = \"camelCaseToSnakeCase\"\npascal_case = \"PascalCaseToSnakeCase\"\nputs camel_to_snake(camel_case) # Output: \"camel_case_to_snake_case\"\nputs camel_to_snake(pascal_case) # Output: \"pascal_case_to_snake_case\"\n"
- },
- {
- "title": "Transform from Snake Case to Camel Case",
- "description": "Converts a Snake Case string to Camel Case.",
- "author": "ACR1209",
- "tags": [
- "string",
- "convert",
- "snake-case",
- "camel-case"
- ],
- "contributors": [],
- "code": "def snake_to_camel(str)\n str.split('_').map.with_index { |word, index| \n index == 0 ? word : word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_camel_case\"\nputs snake_to_camel(snake_case) # Output: \"snakeCaseToCamelCase\"\n"
- },
- {
- "title": "Transform from Snake Case to Pascal Case",
- "description": "Converts a Snake Case string to Pascal Case.",
- "author": "ACR1209",
- "tags": [
- "string",
- "convert",
- "snake-case",
- "pascal-case"
- ],
- "contributors": [],
- "code": "def snake_to_pascal(str)\n str.split('_').map.with_index { |word, index| \n word.capitalize \n }.join\nend\n\n# Usage:\nsnake_case = \"snake_case_to_pascal_case\"\nputs snake_to_pascal(snake_case) # Output: \"SnakeCaseToPascalCase\"\n"
- },
- {
- "title": "Truncate String",
- "description": "Truncates a string to a specified length, optionally adding an ellipsis.",
- "author": "ACR1209",
- "tags": [
- "string",
- "truncate"
- ],
- "contributors": [],
- "code": "def truncate_string(str, max_length)\n return str if str.length <= max_length || max_length <= 3\n str[0, max_length - 3] + '...'\nend\n\n# Usage:\nlong_string = \"Ruby is a dynamic, open source programming language.\"\nputs truncate_string(20, long_string) # Output: \"Ruby is a dynamic...\"\nputs truncate_string(54, long_string) # Output: \"Ruby is a dynamic, open source programming language.\"\n"
- }
- ]
- }
-]
\ No newline at end of file
diff --git a/public/consolidated/rust.json b/public/consolidated/rust.json
deleted file mode 100644
index d3bd8f67..00000000
--- a/public/consolidated/rust.json
+++ /dev/null
@@ -1,61 +0,0 @@
-[
- {
- "name": "Basics",
- "snippets": [
- {
- "title": "Hello, World!",
- "description": "Prints Hello, World! to the terminal.",
- "author": "James-Beans",
- "tags": [
- "printing",
- "hello-world"
- ],
- "contributors": [],
- "code": "fn main() { // Defines the main running function\n println!(\"Hello, World!\"); // Prints Hello, World! to the terminal.\n}\n"
- }
- ]
- },
- {
- "name": "File Handling",
- "snippets": [
- {
- "title": "Find Files",
- "description": "Finds all files of the specified extension within a given directory.",
- "author": "Mathys-Gasnier",
- "tags": [
- "file",
- "search"
- ],
- "contributors": [],
- "code": "fn find_files(directory: &str, file_type: &str) -> std::io::Result
- {snippet.tags.map((tag) => (
-
+
+ {snippet.tags.map((tag) => (
+
+ Hello, World!
\n
- Contributed by{" "} + Created by{" "} = ({ @{snippet.author}
+ {(snippet.contributors ?? []).length > 0 && ( +